repo
string
commit
string
message
string
diff
string
coleifer/django-generic-aggregation
ff14769d3ea24f9445bea55c368416e4d7edee03
Pushing fix to the README
diff --git a/README.rst b/README.rst index 8da2e8a..81faba4 100644 --- a/README.rst +++ b/README.rst @@ -1,48 +1,48 @@ ========================== django-generic-aggregation ========================== annotate() and aggregate() for generically-related data. Examples -------- You want the most commented on blog entries:: >>> from django.contrib.comments.models import Comment >>> from django.db.models import Count >>> from blog.models import BlogEntry >>> from generic_aggregation import generic_annotate >>> annotated = generic_annotate(BlogEntry.objects.all(), Comment.content_object, 'id', Count) >>> for entry in annotated: ... print entry.title, entry.score The most popular 5 The second best 4 Nobody commented 0 You want to figure out which items are highest rated:: from django.db.models import Sum, Avg # assume a Food model and a generic Rating model apple = Food.objects.create(name='apple') # create some ratings on the food Rating.objects.create(content_object=apple, rating=3) Rating.objects.create(content_object=apple, rating=5) Rating.objects.create(content_object=apple, rating=7) >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', Sum) >>> print aggregate 15 >>> aggregate = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', Avg) >>> print aggregate - 4 + 5 Check the tests - there are more examples there. Tested with postgres & sqlite
coleifer/django-generic-aggregation
b41d9bead583df20af347b328a5f6fdf3f678944
Added support for aggregating and annotating over a subset of GFK'd items (i.e. today's most commented on blog entries)
diff --git a/generic_aggregation/tests/models.py b/generic_aggregation/tests/models.py index e79bd49..1121736 100644 --- a/generic_aggregation/tests/models.py +++ b/generic_aggregation/tests/models.py @@ -1,20 +1,22 @@ +import datetime + from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Food(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class Rating(models.Model): rating = models.IntegerField() - created = models.DateTimeField(auto_now_add=True) + created = models.DateTimeField(default=datetime.datetime.now) object_id = models.IntegerField() content_type = models.ForeignKey(ContentType) content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id') def __unicode__(self): return '%s rated %s' % (self.content_object, self.rating) diff --git a/generic_aggregation/tests/tests.py b/generic_aggregation/tests/tests.py index f6d5200..bf8c10c 100644 --- a/generic_aggregation/tests/tests.py +++ b/generic_aggregation/tests/tests.py @@ -1,83 +1,104 @@ import datetime from django.contrib.contenttypes.models import ContentType from django.db import models from django.test import TestCase from generic_aggregation import generic_annotate, generic_aggregate from generic_aggregation.tests.models import Food, Rating class SimpleTest(TestCase): def setUp(self): self.apple = Food.objects.create(name='apple') self.orange = Food.objects.create(name='orange') dt = datetime.datetime(2010, 1, 1) Rating.objects.create(content_object=self.apple, rating=5) Rating.objects.create(content_object=self.apple, rating=3) Rating.objects.create(content_object=self.apple, rating=1, created=dt) - Rating.objects.create(content_object=self.apple, rating=7, created=dt) + Rating.objects.create(content_object=self.apple, rating=3, created=dt) Rating.objects.create(content_object=self.orange, rating=4) Rating.objects.create(content_object=self.orange, rating=3) Rating.objects.create(content_object=self.orange, rating=8, created=dt) def test_annotation(self): annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(annotated_qs.count(), 2) food_a, food_b = annotated_qs self.assertEqual(food_a.score, 4) self.assertEqual(food_a.name, 'apple') self.assertEqual(food_b.score, 3) self.assertEqual(food_b.name, 'orange') annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) self.assertEqual(annotated_qs.count(), 2) - food_a, food_b = annotated_qs - - self.assertEqual(food_a.score, 16) - self.assertEqual(food_a.name, 'apple') + food_b, food_a = annotated_qs self.assertEqual(food_b.score, 15) self.assertEqual(food_b.name, 'orange') + self.assertEqual(food_a.score, 12) + self.assertEqual(food_a.name, 'apple') + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Avg) self.assertEqual(annotated_qs.count(), 2) food_b, food_a = annotated_qs self.assertEqual(food_b.score, 5) self.assertEqual(food_b.name, 'orange') - self.assertEqual(food_a.score, 4) + self.assertEqual(food_a.score, 3) self.assertEqual(food_a.name, 'apple') def test_aggregation(self): # number of ratings on any food aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 7) # total of ratings out there for all foods aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum) - self.assertEqual(aggregated, 31) + self.assertEqual(aggregated, 27) # (showing the use of filters and inner query) aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 4) aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Count) self.assertEqual(aggregated, 3) # avg for apple aggregated = generic_aggregate(Food.objects.filter(name='apple'), Rating.content_object, 'rating', models.Avg) - self.assertEqual(aggregated, 4) + self.assertEqual(aggregated, 3) # avg for orange aggregated = generic_aggregate(Food.objects.filter(name='orange'), Rating.content_object, 'rating', models.Avg) self.assertEqual(aggregated, 5) + + def test_subset_annotation(self): + todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) + annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) + self.assertEqual(annotated_qs.count(), 2) + + food_a, food_b = annotated_qs + + self.assertEqual(food_a.score, 8) + self.assertEqual(food_a.name, 'apple') + + self.assertEqual(food_b.score, 7) + self.assertEqual(food_b.name, 'orange') + + def test_subset_aggregation(self): + todays_ratings = Rating.objects.filter(created__gte=datetime.date.today()) + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Sum, todays_ratings) + self.assertEqual(aggregated, 15) + + aggregated = generic_aggregate(Food.objects.all(), Rating.content_object, 'rating', models.Count, todays_ratings) + self.assertEqual(aggregated, 4) diff --git a/generic_aggregation/utils.py b/generic_aggregation/utils.py index 10cae85..5a23e0f 100644 --- a/generic_aggregation/utils.py +++ b/generic_aggregation/utils.py @@ -1,74 +1,102 @@ from django.contrib.contenttypes.models import ContentType from django.db import connection, models -def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, desc=True): +def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, + generic_queryset=None, desc=True): ordering = desc and '-score' or 'score' content_type = ContentType.objects.get_for_model(queryset.model) qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match qn(gfk_field.fk_field), # the object_id field on the GFK qn(queryset.model._meta.db_table), # the table and pk from the main qn(queryset.model._meta.pk.name) # part of the query ) extra = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s=%s.%s """ % params - queryset = queryset.extra(select={ - 'score': extra - }, - order_by=[ordering]) + if generic_queryset is not None: + inner_query, inner_query_params = generic_queryset.values_list('pk').query.as_sql() + + inner_params = ( + qn(generic_queryset.model._meta.db_table), + qn(generic_queryset.model._meta.pk.name), + ) + inner_start = ' AND %s.%s IN (' % inner_params + inner_end = ')' + extra = extra + inner_start + inner_query + inner_end + else: + inner_query_params = [] + + queryset = queryset.extra( + select={'score': extra}, + select_params=inner_query_params, + order_by=[ordering] + ) return queryset -def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum): +def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, + generic_queryset=None): content_type = ContentType.objects.get_for_model(queryset.model) queryset = queryset.values_list('pk') # just the pks - inner_query, inner_params = queryset.query.as_nested_sql() + query, query_params = queryset.query.as_nested_sql() qn = connection.ops.quote_name # collect the params we'll be using params = ( aggregator.name, # the function that's doing the aggregation qn(aggregate_field), # the field containing the value to aggregate qn(gfk_field.model._meta.db_table), # table holding gfk'd item info qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK content_type.pk, # the content_type id we need to match qn(gfk_field.fk_field), # the object_id field on the GFK ) query_start = """ SELECT %s(%s) AS aggregate_score FROM %s WHERE %s=%s AND %s IN ( """ % params query_end = ")" + if generic_queryset is not None: + inner_query, inner_query_params = generic_queryset.values_list('pk').query.as_sql() + + query_params += inner_query_params + + inner_params = ( + qn(generic_queryset.model._meta.pk.name), + ) + inner_start = ' AND %s IN (' % inner_params + inner_end = ')' + query_end = query_end + inner_start + inner_query + inner_end + # pass in the inner_query unmodified as we will use the cursor to handle # quoting the inner parameters correctly - query = query_start + inner_query + query_end + query = query_start + query + query_end cursor = connection.cursor() - cursor.execute(query, inner_params) + cursor.execute(query, query_params) row = cursor.fetchone() return row[0]
dzamkov/Alunite-old
158d3dc1031eeb82119495fc3d76dac02cec69ef
Refactoring, starting on dynamics
diff --git a/Alunite/Simulation/Dynamics/Progression.cs b/Alunite/Simulation/Dynamics/Progression.cs new file mode 100644 index 0000000..d7c3aeb --- /dev/null +++ b/Alunite/Simulation/Dynamics/Progression.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// The progression of a matter over time. The matter may interact + /// with other matter outside the progression. + /// </summary> + public abstract class Progression + { + + } + +} \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Link.cs b/Alunite/Simulation/Entities/Link.cs index 16a887b..2fc2622 100644 --- a/Alunite/Simulation/Entities/Link.cs +++ b/Alunite/Simulation/Entities/Link.cs @@ -1,84 +1,75 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// An entity that creates internal links within another source entity. /// </summary> public class LinkEntity : Entity { public LinkEntity(Entity Source) { this._Source = Source; this._Links = new List<_Link>(); } /// <summary> /// Gets the source entity for this link entity. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> - /// Links two terminals within the source entity. Note that once a terminal is linked, it can no longer - /// be used outside the entity. + /// Creates a link between two terminals. There is a many to one relationship between output and + /// input terminals. /// </summary> - public void Link<TInput, TOutput>(Terminal<TInput, TOutput> A, Terminal<TOutput, TInput> B) + public void Link<T>(OutTerminal<T> Output, InTerminal<T> Input) { - this._Links.Add(_Link.Create<TInput, TOutput>(A, B)); - } - - /// <summary> - /// Links two terminals within the source entity. Note that once a terminal is linked, it can no longer - /// be used outside the entity. - /// </summary> - public void Link<TOutput>(Terminal<Void, TOutput> Output, Terminal<TOutput, Void> Input) - { - this._Links.Add(_Link.Create<Void, TOutput>(Output, Input)); + this._Links.Add(_Link.Create(Output, Input)); } public override bool Phantom { get { return this._Source.Phantom; } } private Entity _Source; private List<_Link> _Links; } /// <summary> /// A link within a link entity. /// </summary> internal class _Link { /// <summary> /// Creates a link between two terminals. /// </summary> - public static _Link Create<TA, TB>(Terminal<TA, TB> A, Terminal<TB, TA> B) + public static _Link Create<T>(OutTerminal<T> Output, InTerminal<T> Input) { - return new SpecialTerminal<TA, TB>() + return new SpecialTerminal<T> { - A = A, - B = B + Output = Output, + Input = Input }; } /// <summary> /// A specialized link between complimentary typed terminals. /// </summary>> - public class SpecialTerminal<TA, TB> : _Link + public class SpecialTerminal<T> : _Link { - public Terminal<TA, TB> A; - public Terminal<TB, TA> B; + public OutTerminal<T> Output; + public InTerminal<T> Input; } } } \ No newline at end of file diff --git a/Alunite/Simulation/Signal.cs b/Alunite/Simulation/Signal.cs index 6a2b9c8..4f12cc5 100644 --- a/Alunite/Simulation/Signal.cs +++ b/Alunite/Simulation/Signal.cs @@ -1,108 +1,112 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// A continous time-varying value. + /// Represents an infinitely precise, continous time-varying value. /// </summary> /// <remarks>All ranges in signals represent the interval [Start, End).</remarks> - /// <typeparam name="T">The type of the signal at any one time.</typeparam> + /// <typeparam name="T">The type of the signal at any one time or a range of time.</typeparam> public abstract class Signal<T> { /// <summary> - /// Gets the value of the signal at any one time. Not that no times before 0.0 may be used. + /// Gets the value of the signal at the specified time. /// </summary> - /// <remarks>Due to the fact that a double can not perfectly represent any one time, this actually gets the average - /// of the signal between Time and the next highest double.</remarks> public abstract T this[double Time] { get; } /// <summary> /// Gets the length of this signal in seconds, or infinity to indicate an unbounded signal. /// </summary> public virtual double Length { get { return double.PositiveInfinity; } } } /// <summary> /// A maybe signal whose value is always nothing. /// </summary> - public class NothingSignal<T> : Signal<Maybe<T>> + public sealed class NothingSignal<T> : Signal<Maybe<T>> { private NothingSignal() { } /// <summary> /// Gets the only instance of this signal. /// </summary> public static readonly NothingSignal<T> Singleton = new NothingSignal<T>(); public override Maybe<T> this[double Time] { get { return Maybe<T>.Nothing; } } } /// <summary> /// Signal-related functions. /// </summary> public static class Signal { - + /// <summary> + /// Gets a maybe signal whose value is always nothing. + /// </summary> + public static NothingSignal<T> Nothing<T>() + { + return NothingSignal<T>.Singleton; + } } /// <summary> /// A sample type that contains a variable amount of items (as events) of the given type. /// </summary> /// <remarks>This can be used as the type parameter of a signal to create an event signal.</remarks> public struct Multi<T> { /// <summary> /// Gets if the multi sample contains no items. /// </summary> public bool Empty { get { return !this.Items.GetEnumerator().MoveNext(); } } /// <summary> /// The chronologically-ordered collection of all items in the period of the sample. /// </summary> public IEnumerable<T> Items; } /// <summary> /// A chronologically-placed item. /// </summary> public struct Event<T> { public Event(T Item, double Time) { this.Item = Item; this.Time = Time; } /// <summary> /// The data for the event. /// </summary> public T Item; /// <summary> /// The time at which the event occurs. /// </summary> public double Time; } } \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs index e8590de..737fbfd 100644 --- a/Alunite/Simulation/Simulation.cs +++ b/Alunite/Simulation/Simulation.cs @@ -1,59 +1,54 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A mutable representation of the progression of an entity over time. Simulations can be interacted with using /// unbound terminals in the supplied entity. /// </summary> public abstract class Simulation { /// <summary> /// Creates a simulation with the given initial state. /// </summary> public static Simulation Create(Entity World) { return new _Simulation(World); } /// <summary> - /// Creates a connection to a terminal by specifing an input signal and reciving an output signal. Both - /// signals may be updated along with the simulation. If either signal is Nothing at any time, it - /// indicates that the terminal is inactive in the corresponding direction. + /// Reads the signal from the given terminal. The signal will be Nothing when the terminal is not + /// active, either because the entity that has the terminal does not have the required terminal or + /// the entity does not exist. /// </summary> - public abstract Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal); + public abstract Mutable<Signal<Maybe<T>>> Read<T>(OutTerminal<T> Terminal); /// <summary> - /// Creates a one-way connection with a terminal that only gives information. + /// Writes a signal to the given terminal. Note that only one input source may be used + /// for each input terminal. /// </summary> - public void Write<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) - { - this.Connect<TInput, TOutput>(Input, Terminal); - } - - /// <summary> - /// Creates a one-way connection with a terminal that only receives information. - /// </summary> - public Mutable<Signal<Maybe<TOutput>>> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) - { - return this.Connect((Mutable<Signal<Maybe<TInput>>>)NothingSignal<TInput>.Singleton, Terminal); - } + public abstract void Write<T>(InTerminal<T> Terminal, Mutable<Signal<Maybe<T>>> Signal); } /// <summary> /// A concrete implementation of simulation. /// </summary> internal class _Simulation : Simulation { public _Simulation(Entity World) { } - public override Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) + public override Mutable<Signal<Maybe<T>>> Read<T>(OutTerminal<T> Terminal) + { + throw new NotImplementedException(); + } + + public override void Write<T>(InTerminal<T> Terminal, Mutable<Signal<Maybe<T>>> Signal) { throw new NotImplementedException(); } } } \ No newline at end of file diff --git a/Alunite/Simulation/Terminal.cs b/Alunite/Simulation/Terminal.cs index dc2d9b2..b84649c 100644 --- a/Alunite/Simulation/Terminal.cs +++ b/Alunite/Simulation/Terminal.cs @@ -1,31 +1,21 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// A reference to a bidirectional channel in an entity that can be used for communication with complimentary terminals over time. + /// A reference to a terminal which takes an input signal produced by a complimentary terminal. /// </summary> - /// <typeparam name="TInput">The type of input received on the channel at any one time.</typeparam> - /// <typeparam name="TOutput">The type of output given by the channel at any one time.</typeparam> - public class Terminal<TInput, TOutput> : Node - { - - } - - /// <summary> - /// A terminal that receives input without giving any output. - /// </summary> - public class InTerminal<TInput> : Terminal<TInput, Void> + public class InTerminal<T> : Node { } /// <summary> - /// A terminal that gives output without receiving any input. + /// A reference to a terminal which produces an output signal that may be used by a complimentary terminal. /// </summary> - public class OutTerminal<TOutput> : Terminal<Void, TOutput> + public class OutTerminal<T> : Node { } } \ No newline at end of file
dzamkov/Alunite-old
baacdc5f18fd8782e738106a94ad8ecbfbe7c6fc
Can't remeber what I did
diff --git a/Alunite/Simulation/Entities/Link.cs b/Alunite/Simulation/Entities/Link.cs index 6a14ee7..16a887b 100644 --- a/Alunite/Simulation/Entities/Link.cs +++ b/Alunite/Simulation/Entities/Link.cs @@ -1,83 +1,84 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// An entity that creates internal links within another source entity. Note that once an internal link is made, neither of the involved - /// terminals may be referenced with the LinkEntity. + /// An entity that creates internal links within another source entity. /// </summary> public class LinkEntity : Entity { public LinkEntity(Entity Source) { this._Source = Source; this._Links = new List<_Link>(); } /// <summary> /// Gets the source entity for this link entity. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> - /// Links two terminals within the source entity. + /// Links two terminals within the source entity. Note that once a terminal is linked, it can no longer + /// be used outside the entity. /// </summary> public void Link<TInput, TOutput>(Terminal<TInput, TOutput> A, Terminal<TOutput, TInput> B) { this._Links.Add(_Link.Create<TInput, TOutput>(A, B)); } /// <summary> - /// Links two terminals within the source entity. + /// Links two terminals within the source entity. Note that once a terminal is linked, it can no longer + /// be used outside the entity. /// </summary> public void Link<TOutput>(Terminal<Void, TOutput> Output, Terminal<TOutput, Void> Input) { this._Links.Add(_Link.Create<Void, TOutput>(Output, Input)); } public override bool Phantom { get { return this._Source.Phantom; } } private Entity _Source; private List<_Link> _Links; } /// <summary> /// A link within a link entity. /// </summary> internal class _Link { /// <summary> /// Creates a link between two terminals. /// </summary> public static _Link Create<TA, TB>(Terminal<TA, TB> A, Terminal<TB, TA> B) { - return new Special<TA, TB>() + return new SpecialTerminal<TA, TB>() { A = A, B = B }; } /// <summary> /// A specialized link between complimentary typed terminals. /// </summary>> - public class Special<TA, TB> : _Link + public class SpecialTerminal<TA, TB> : _Link { public Terminal<TA, TB> A; public Terminal<TB, TA> B; } } } \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs index d771b26..e8590de 100644 --- a/Alunite/Simulation/Simulation.cs +++ b/Alunite/Simulation/Simulation.cs @@ -1,59 +1,59 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// Represents the progression of an entity over time. Simulations can be interacted with using + /// A mutable representation of the progression of an entity over time. Simulations can be interacted with using /// unbound terminals in the supplied entity. /// </summary> public abstract class Simulation { /// <summary> /// Creates a simulation with the given initial state. /// </summary> public static Simulation Create(Entity World) { return new _Simulation(World); } /// <summary> /// Creates a connection to a terminal by specifing an input signal and reciving an output signal. Both /// signals may be updated along with the simulation. If either signal is Nothing at any time, it /// indicates that the terminal is inactive in the corresponding direction. /// </summary> public abstract Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal); /// <summary> /// Creates a one-way connection with a terminal that only gives information. /// </summary> public void Write<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) { this.Connect<TInput, TOutput>(Input, Terminal); } /// <summary> /// Creates a one-way connection with a terminal that only receives information. /// </summary> public Mutable<Signal<Maybe<TOutput>>> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) { return this.Connect((Mutable<Signal<Maybe<TInput>>>)NothingSignal<TInput>.Singleton, Terminal); } } /// <summary> /// A concrete implementation of simulation. /// </summary> internal class _Simulation : Simulation { public _Simulation(Entity World) { } public override Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) { throw new NotImplementedException(); } } } \ No newline at end of file
dzamkov/Alunite-old
2e01e9d67c7eb4f5281c2e630ce64de66d3e8d0c
Mutable, signal updates
diff --git a/Alunite/Data/Mutable.cs b/Alunite/Data/Mutable.cs index 1df1812..7feeb16 100644 --- a/Alunite/Data/Mutable.cs +++ b/Alunite/Data/Mutable.cs @@ -1,22 +1,61 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// A mutable object that informs subscribers when it is changed. + /// A mutable reference to an object. /// </summary> - /// <typeparam name="TDesc">A description of a change.</typeparam> - public interface IMutable<TDesc> + public class Mutable<T> { + public Mutable(T Current) + { + this._Current = Current; + } + + public static implicit operator T(Mutable<T> Ref) + { + return Ref.Current; + } + + public static implicit operator Mutable<T>(T Current) + { + return new Mutable<T>(Current); + } + + /// <summary> + /// Gets the current referenced object. + /// </summary> + public T Current + { + get + { + return this._Current; + } + } + /// <summary> - /// An event fired when the mutable object's outward interface is modified. + /// Updates the item for this mutable reference. /// </summary> - event ChangedHandler<TDesc> Changed; + public void Update(T New) + { + this._Current = New; + if (this.Changed != null) + { + this.Changed(New); + } + } + + /// <summary> + /// An event fired when the current item is changed. + /// </summary> + public event ChangedHandler<T> Changed; + + private T _Current; } /// <summary> /// An event handler for a change in a mutable object. /// </summary> - public delegate void ChangedHandler<TDesc>(TDesc ChangeDescription); + public delegate void ChangedHandler<T>(T New); } \ No newline at end of file diff --git a/Alunite/Simulation/Signal.cs b/Alunite/Simulation/Signal.cs index 694e0e0..6a2b9c8 100644 --- a/Alunite/Simulation/Signal.cs +++ b/Alunite/Simulation/Signal.cs @@ -1,80 +1,108 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous time-varying value. /// </summary> /// <remarks>All ranges in signals represent the interval [Start, End).</remarks> /// <typeparam name="T">The type of the signal at any one time.</typeparam> - public abstract class Signal<T> : IMutable<Void> + public abstract class Signal<T> { /// <summary> /// Gets the value of the signal at any one time. Not that no times before 0.0 may be used. /// </summary> /// <remarks>Due to the fact that a double can not perfectly represent any one time, this actually gets the average /// of the signal between Time and the next highest double.</remarks> public abstract T this[double Time] { get; } /// <summary> - /// Informs the subscribers of this signal that it has been changed. + /// Gets the length of this signal in seconds, or infinity to indicate an unbounded signal. /// </summary> - protected void OnChange() + public virtual double Length { - if (this.Changed != null) + get { - this.Changed(Void.Value); + return double.PositiveInfinity; } } - - public event ChangedHandler<Void> Changed; } /// <summary> /// A maybe signal whose value is always nothing. /// </summary> public class NothingSignal<T> : Signal<Maybe<T>> { private NothingSignal() { } /// <summary> /// Gets the only instance of this signal. /// </summary> public static readonly NothingSignal<T> Singleton = new NothingSignal<T>(); public override Maybe<T> this[double Time] { get { return Maybe<T>.Nothing; } } } /// <summary> - /// A sample type that contains a variable amount of items of the given type. + /// Signal-related functions. + /// </summary> + public static class Signal + { + + } + + /// <summary> + /// A sample type that contains a variable amount of items (as events) of the given type. /// </summary> /// <remarks>This can be used as the type parameter of a signal to create an event signal.</remarks> - public struct Event<T> + public struct Multi<T> { /// <summary> - /// Gets if the event sample contains no events. + /// Gets if the multi sample contains no items. /// </summary> public bool Empty { get { return !this.Items.GetEnumerator().MoveNext(); } } /// <summary> - /// The chronologically-ordered collection of all events in the period of the sample. + /// The chronologically-ordered collection of all items in the period of the sample. /// </summary> public IEnumerable<T> Items; } + + /// <summary> + /// A chronologically-placed item. + /// </summary> + public struct Event<T> + { + public Event(T Item, double Time) + { + this.Item = Item; + this.Time = Time; + } + + /// <summary> + /// The data for the event. + /// </summary> + public T Item; + + /// <summary> + /// The time at which the event occurs. + /// </summary> + public double Time; + } } \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs index c3ad66c..d771b26 100644 --- a/Alunite/Simulation/Simulation.cs +++ b/Alunite/Simulation/Simulation.cs @@ -1,59 +1,59 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents the progression of an entity over time. Simulations can be interacted with using /// unbound terminals in the supplied entity. /// </summary> public abstract class Simulation { /// <summary> /// Creates a simulation with the given initial state. /// </summary> public static Simulation Create(Entity World) { return new _Simulation(World); } /// <summary> /// Creates a connection to a terminal by specifing an input signal and reciving an output signal. Both - /// signals may be modified along with the simulation. If either signal is Nothing at any time, it + /// signals may be updated along with the simulation. If either signal is Nothing at any time, it /// indicates that the terminal is inactive in the corresponding direction. /// </summary> - public abstract Signal<Maybe<TOutput>> Connect<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal); + public abstract Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal); /// <summary> /// Creates a one-way connection with a terminal that only gives information. /// </summary> - public void Write<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal) + public void Write<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) { this.Connect<TInput, TOutput>(Input, Terminal); } /// <summary> /// Creates a one-way connection with a terminal that only receives information. /// </summary> - public Signal<Maybe<TOutput>> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) + public Mutable<Signal<Maybe<TOutput>>> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) { - return this.Connect(NothingSignal<TInput>.Singleton, Terminal); + return this.Connect((Mutable<Signal<Maybe<TInput>>>)NothingSignal<TInput>.Singleton, Terminal); } } /// <summary> /// A concrete implementation of simulation. /// </summary> internal class _Simulation : Simulation { public _Simulation(Entity World) { } - public override Signal<Maybe<TOutput>> Connect<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal) + public override Mutable<Signal<Maybe<TOutput>>> Connect<TInput, TOutput>(Mutable<Signal<Maybe<TInput>>> Input, Terminal<TInput, TOutput> Terminal) { throw new NotImplementedException(); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index b35dbe7..0d87f9e 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,33 +1,33 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for a simulation. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(Signal<Maybe<View>> Feed) + public Visualizer(Mutable<Signal<Maybe<View>>> Feed) { this._Feed = Feed; } public override void RenderScene() { } public override void SetupProjection(Point Viewsize) { } - private Signal<Maybe<View>> _Feed; + private Mutable<Signal<Maybe<View>>> _Feed; } } \ No newline at end of file
dzamkov/Alunite-old
2b9f8f25e570bd821d9604ad9c5c0a7bca076f3c
Maybe signal
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index e934c2d..722ef5b 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,82 +1,83 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Data\Filter.cs" /> <Compile Include="Data\MatchMatrix.cs" /> + <Compile Include="Data\Maybe.cs" /> <Compile Include="Data\Mutable.cs" /> <Compile Include="Data\Void.cs" /> <Compile Include="Math\Arithmetic.cs" /> <Compile Include="Math\Curve.cs" /> <Compile Include="Math\Scalar.cs" /> <Compile Include="Program.cs" /> <Compile Include="Math\Quaternion.cs" /> <Compile Include="Data\Set.cs" /> <Compile Include="Data\Sink.cs" /> <Compile Include="Math\Transform.cs" /> <Compile Include="Data\UsageSet.cs" /> <Compile Include="Math\Vector.cs" /> <Compile Include="Simulation\Entities\Camera.cs" /> <Compile Include="Simulation\Entities\Compound.cs" /> <Compile Include="Simulation\Entities\Link.cs" /> <Compile Include="Simulation\Entities\Sphere.cs" /> <Compile Include="Simulation\Entity.cs" /> <Compile Include="Simulation\Node.cs" /> <Compile Include="Simulation\Signal.cs" /> <Compile Include="Simulation\Simulation.cs" /> <Compile Include="Simulation\Terminal.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Data/Maybe.cs b/Alunite/Data/Maybe.cs new file mode 100644 index 0000000..3dbca43 --- /dev/null +++ b/Alunite/Data/Maybe.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// An object that can store all the values of its given type plus a Nothing value. + /// </summary> + public struct Maybe<T> + { + public Maybe(T Value) + { + this.Data = Value; + this.IsNothing = false; + } + + /// <summary> + /// Gets the Nothing value. + /// </summary> + public static Maybe<T> Nothing + { + get + { + return new Maybe<T>() + { + Data = default(T), + IsNothing = true + }; + } + } + + /// <summary> + /// Gets a data maybe value. + /// </summary> + public static Maybe<T> Just(T Data) + { + return new Maybe<T>(Data); + } + + /// <summary> + /// Tries to get the data from this maybe value. Returns true if it exists or false if this + /// is a Nothing value. + /// </summary> + public bool TryGetData(out T Data) + { + if (this.IsNothing) + { + Data = default(T); + return false; + } + else + { + Data = this.Data; + return true; + } + } + + /// <summary> + /// The data for the structure if Nothing is set to false. + /// </summary> + public T Data; + + /// <summary> + /// Is this value Nothing? + /// </summary> + public bool IsNothing; + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Signal.cs b/Alunite/Simulation/Signal.cs index 779bf41..694e0e0 100644 --- a/Alunite/Simulation/Signal.cs +++ b/Alunite/Simulation/Signal.cs @@ -1,60 +1,80 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous time-varying value. /// </summary> + /// <remarks>All ranges in signals represent the interval [Start, End).</remarks> /// <typeparam name="T">The type of the signal at any one time.</typeparam> public abstract class Signal<T> : IMutable<Void> { /// <summary> - /// Gets the value of the signal at any one time. + /// Gets the value of the signal at any one time. Not that no times before 0.0 may be used. /// </summary> /// <remarks>Due to the fact that a double can not perfectly represent any one time, this actually gets the average /// of the signal between Time and the next highest double.</remarks> public abstract T this[double Time] { get; } - /// <summary> - /// Gets the sum of the values in the range [Start, End) divided by the size of interval. - /// </summary> - public abstract T Average(double Start, double End); - /// <summary> /// Informs the subscribers of this signal that it has been changed. /// </summary> protected void OnChange() { if (this.Changed != null) { this.Changed(Void.Value); } } public event ChangedHandler<Void> Changed; } + /// <summary> + /// A maybe signal whose value is always nothing. + /// </summary> + public class NothingSignal<T> : Signal<Maybe<T>> + { + private NothingSignal() + { + + } + + /// <summary> + /// Gets the only instance of this signal. + /// </summary> + public static readonly NothingSignal<T> Singleton = new NothingSignal<T>(); + + public override Maybe<T> this[double Time] + { + get + { + return Maybe<T>.Nothing; + } + } + } + /// <summary> /// A sample type that contains a variable amount of items of the given type. /// </summary> /// <remarks>This can be used as the type parameter of a signal to create an event signal.</remarks> public struct Event<T> { /// <summary> /// Gets if the event sample contains no events. /// </summary> public bool Empty { get { return !this.Items.GetEnumerator().MoveNext(); } } /// <summary> /// The chronologically-ordered collection of all events in the period of the sample. /// </summary> public IEnumerable<T> Items; } } \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs index 6c6c8d8..c3ad66c 100644 --- a/Alunite/Simulation/Simulation.cs +++ b/Alunite/Simulation/Simulation.cs @@ -1,52 +1,59 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents the progression of an entity over time. Simulations can be interacted with using /// unbound terminals in the supplied entity. /// </summary> public abstract class Simulation { /// <summary> /// Creates a simulation with the given initial state. /// </summary> public static Simulation Create(Entity World) { return new _Simulation(World); } /// <summary> - /// Gets a signal for the output of the given terminal. Note that the signal will update as the simulation updates (if any corrections are made - /// to input signals). + /// Creates a connection to a terminal by specifing an input signal and reciving an output signal. Both + /// signals may be modified along with the simulation. If either signal is Nothing at any time, it + /// indicates that the terminal is inactive in the corresponding direction. /// </summary> - public abstract Signal<TOutput> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal); + public abstract Signal<Maybe<TOutput>> Connect<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal); /// <summary> - /// Sets the input of the given terminal to the specified signal. + /// Creates a one-way connection with a terminal that only gives information. /// </summary> - public abstract void Write<TInput, TOutput>(Terminal<TInput, TOutput> Terminal, Signal<TInput> Signal); + public void Write<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal) + { + this.Connect<TInput, TOutput>(Input, Terminal); + } + + /// <summary> + /// Creates a one-way connection with a terminal that only receives information. + /// </summary> + public Signal<Maybe<TOutput>> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) + { + return this.Connect(NothingSignal<TInput>.Singleton, Terminal); + } } /// <summary> /// A concrete implementation of simulation. /// </summary> internal class _Simulation : Simulation { public _Simulation(Entity World) { } - public override Signal<TOutput> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) - { - throw new NotImplementedException(); - } - - public override void Write<TInput, TOutput>(Terminal<TInput, TOutput> Terminal, Signal<TInput> Signal) + public override Signal<Maybe<TOutput>> Connect<TInput, TOutput>(Signal<Maybe<TInput>> Input, Terminal<TInput, TOutput> Terminal) { throw new NotImplementedException(); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 9e73ed0..b35dbe7 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,33 +1,33 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for a simulation. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(Signal<View> Feed) + public Visualizer(Signal<Maybe<View>> Feed) { this._Feed = Feed; } public override void RenderScene() { } public override void SetupProjection(Point Viewsize) { } - private Signal<View> _Feed; + private Signal<Maybe<View>> _Feed; } } \ No newline at end of file
dzamkov/Alunite-old
67c0b1bde6f1b1fcf5fd2e7d992d77da97342e11
Minirefactor
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 18a49ab..e934c2d 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,81 +1,82 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>9.0.21022</ProductVersion> + <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Data\Filter.cs" /> <Compile Include="Data\MatchMatrix.cs" /> <Compile Include="Data\Mutable.cs" /> <Compile Include="Data\Void.cs" /> <Compile Include="Math\Arithmetic.cs" /> <Compile Include="Math\Curve.cs" /> <Compile Include="Math\Scalar.cs" /> <Compile Include="Program.cs" /> <Compile Include="Math\Quaternion.cs" /> <Compile Include="Data\Set.cs" /> <Compile Include="Data\Sink.cs" /> <Compile Include="Math\Transform.cs" /> <Compile Include="Data\UsageSet.cs" /> <Compile Include="Math\Vector.cs" /> <Compile Include="Simulation\Entities\Camera.cs" /> <Compile Include="Simulation\Entities\Compound.cs" /> <Compile Include="Simulation\Entities\Link.cs" /> <Compile Include="Simulation\Entities\Sphere.cs" /> <Compile Include="Simulation\Entity.cs" /> + <Compile Include="Simulation\Node.cs" /> <Compile Include="Simulation\Signal.cs" /> <Compile Include="Simulation\Simulation.cs" /> <Compile Include="Simulation\Terminal.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index b81081c..19ae938 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,34 +1,34 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { CameraEntity camsensor = Entity.Camera(); Entity cambody = Entity.Sphere(0.1, 0.1).Apply(new Transform(-0.12, 0.0, 0.0)); Entity cam = camsensor.Embody(cambody); Entity obj = Entity.Sphere(0.1, 2.1).Apply(new Transform(5.0, 0.0, 0.0)); CompoundEntity world = Entity.Compound(); - Terminal<Void, View> camout = world.Add(cam).Lookup(camsensor.Output); + OutTerminal<View> camout = world.Add(cam).Lookup(camsensor.Output); world.Add(obj); Simulation sim = Simulation.Create(world); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.Control = new Visualizer(sim.Read(camout)); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Camera.cs b/Alunite/Simulation/Entities/Camera.cs index f45d019..29f1399 100644 --- a/Alunite/Simulation/Entities/Camera.cs +++ b/Alunite/Simulation/Entities/Camera.cs @@ -1,43 +1,43 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A sensor entity that exposes a terminal which gives the image seen starting at (0.0, 0.0, 0.0) and looking towards (1.0, 0.0, 0.0) in local /// coordinates. /// </summary> public class CameraEntity : PhantomEntity { internal CameraEntity() { - this._Output = new Terminal<Void, View>(); + this._Output = new OutTerminal<View>(); } /// <summary> /// Gets the only instance of this class. /// </summary> public static readonly CameraEntity Singleton = new CameraEntity(); /// <summary> - /// Gets the output image of this camera sensor. + /// Gets the output image terminal of this camera sensor. /// </summary> - public Terminal<Void, View> Output + public OutTerminal<View> Output { get { return this._Output; } } - private Terminal<Void, View> _Output; + private OutTerminal<View> _Output; } /// <summary> /// A view of a simulation that can be rendered to a graphics context. /// </summary> public class View { } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Compound.cs b/Alunite/Simulation/Entities/Compound.cs index 6dc942d..b2902e2 100644 --- a/Alunite/Simulation/Entities/Compound.cs +++ b/Alunite/Simulation/Entities/Compound.cs @@ -1,76 +1,76 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// An entity made from the combination of other entities. Note that each entity has its terminals remapped to avoid + /// An entity made from the combination of other entities. Note that each entity has its nodes remapped to avoid /// conflicts when reusing entities. /// </summary> public class CompoundEntity : Entity { public CompoundEntity() { this._Elements = new List<Element>(); } /// <summary> /// Gets the entities that make up this compound entity. /// </summary> public IEnumerable<Element> Elements { get { return this._Elements; } } /// <summary> /// An element within a compound entity. /// </summary> public struct Element { /// <summary> - /// A mapping of terminals from internally in the entity to externally in the compound entity. + /// A mapping of nodes from internally in the entity to externally in the compound entity. /// </summary> - public TerminalMap TerminalMap; + public NodeMap NodeMap; /// <summary> /// The entity for this element. /// </summary> public Entity Entity; } /// <summary> - /// Adds an entity to the compound and returns a terminal map that can be used to get global terminals for each - /// entities local terminals. + /// Adds an entity to the compound and returns a terminal map that can be used to get global nodes for each + /// entity's local node. /// </summary> - public TerminalMap Add(Entity Entity) + public NodeMap Add(Entity Entity) { - TerminalMap tm = this._Elements.Count == 0 ? (TerminalMap)TerminalMap.Identity : TerminalMap.Lazy; + NodeMap tm = this._Elements.Count == 0 ? (NodeMap)NodeMap.Identity : NodeMap.Lazy; this._Elements.Add(new Element() { - TerminalMap = tm, + NodeMap = tm, Entity = Entity }); return tm; } public override bool Phantom { get { foreach (Element e in this._Elements) { if (!e.Entity.Phantom) { return false; } } return true; } } private List<Element> _Elements; } } \ No newline at end of file diff --git a/Alunite/Simulation/Entity.cs b/Alunite/Simulation/Entity.cs index 772b55d..29eae0c 100644 --- a/Alunite/Simulation/Entity.cs +++ b/Alunite/Simulation/Entity.cs @@ -1,195 +1,195 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A static description of a dynamic object that can interact with other entities in a simulation over time. Note that each entity may be used multiple /// times and is not linked with any particular context. /// </summary> public class Entity { /// <summary> /// Creates an entity with a transform to this entity. /// </summary> public virtual TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this, Transform); } /// <summary> /// Gets wether or not this entity has any physical components. A phantom entity is invisible, massless and indescructible. /// </summary> public virtual bool Phantom { get { return false; } } /// <summary> /// Gets a camera entity. /// </summary> public static CameraEntity Camera() { return CameraEntity.Singleton; } /// <summary> /// Creates a sphere with the specified mass and radius. /// </summary> public static SphereEntity Sphere(double Mass, double Radius) { return new SphereEntity(Mass, Radius); } /// <summary> /// Creates a compound entity. /// </summary> public static CompoundEntity Compound() { return new CompoundEntity(); } /// <summary> /// Creates a linking entity on another entity. /// </summary> public static LinkEntity Link(Entity Source) { return new LinkEntity(Source); } /// <summary> /// Creates an entity that attaches this entity to the specified physical body. Only phantom entities may be embodied. /// </summary> public EmbodimentEntity Embody(Entity Body) { return new EmbodimentEntity(this, Body); } } /// <summary> /// An invisible, indestructible, massless entity that may interact with a simulation. /// </summary> public class PhantomEntity : Entity { public override bool Phantom { get { return true; } } } /// <summary> /// An entity which attaches a phantom entity to a physical form. This allows the attached entity to move and be destroyed with the physical entity while still retaining /// its special properties. /// </summary> public class EmbodimentEntity : Entity { public EmbodimentEntity(Entity Control, Entity Body) { this._Control = Control; this._Body = Body; - this._BodyMap = new LazyTerminalMap(); + this._BodyMap = new LazyNodeMap(); } /// <summary> /// Gets the phantom entity that is "embodied". /// </summary> public Entity Control { get { return this._Control; } } /// <summary> /// Gets the physical entity used as the body. /// </summary> public Entity Body { get { return this._Body; } } public override bool Phantom { get { return false; } } /// <summary> - /// Gets the terminal map from terminals internal to the body to terminals that can be referenced externally on this entity. No + /// Gets the node map from terminals internal to the body to nodes that can be referenced externally on this entity. No /// mapping is required for the "Phantom" part of this entity. /// </summary> - public TerminalMap BodyMap + public NodeMap BodyMap { get { return this._BodyMap; } } private Entity _Control; private Entity _Body; - private LazyTerminalMap _BodyMap; + private LazyNodeMap _BodyMap; } /// <summary> /// An entity that represents a transformed form of a source entity. /// </summary> public class TransformedEntity : Entity { public TransformedEntity(Entity Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } public override TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this._Source, this._Transform.Apply(Transform)); } /// <summary> /// Gets the entity that is transformed. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> /// Gets the transform used. /// </summary> public Transform Transform { get { return this._Transform; } } public override bool Phantom { get { return this._Source.Phantom; } } private Entity _Source; private Transform _Transform; } } \ No newline at end of file diff --git a/Alunite/Simulation/Node.cs b/Alunite/Simulation/Node.cs new file mode 100644 index 0000000..71faae5 --- /dev/null +++ b/Alunite/Simulation/Node.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A reference to a particular feature within an entity that can be accessed and used externally on the entity. + /// </summary> + /// <remarks>Terminals are only compared by reference and therfore, need no additional information.</remarks> + public class Node + { + public override string ToString() + { + return this.GetHashCode().ToString(); + } + } + + /// <summary> + /// A mapping of nodes in one entity to those in another, usually larger and more complex entity. + /// </summary> + public abstract class NodeMap + { + /// <summary> + /// Gets the identity node map. + /// </summary> + public static IdentityNodeMap Identity + { + get + { + return IdentityNodeMap.Singleton; + } + } + + /// <summary> + /// Gets a new lazy node map. + /// </summary> + public static LazyNodeMap Lazy + { + get + { + return new LazyNodeMap(); + } + } + + /// <summary> + /// Finds the corresponding node for the given local node. + /// </summary> + public abstract T Lookup<T>(T Node) + where T : Node, new(); + } + + /// <summary> + /// A node map where lookup operations simply return the same node that is given. + /// </summary> + public class IdentityNodeMap : NodeMap + { + internal IdentityNodeMap() + { + + } + + /// <summary> + /// Gets the only instance of this class. + /// </summary> + public static readonly IdentityNodeMap Singleton = new IdentityNodeMap(); + + public override T Lookup<T>(T Node) + { + return Node; + } + } + + /// <summary> + /// A node map that only produces new nodes as they are looked up. + /// </summary> + public class LazyNodeMap : NodeMap + { + public LazyNodeMap() + { + this._Nodes = new Dictionary<Node, Node>(); + } + + public override T Lookup<T>(T Node) + { + Node res; + if (this._Nodes.TryGetValue(Node, out res)) + { + return res as T; + } + else + { + T tres = new T(); + this._Nodes[Node] = tres; + return tres; + } + } + + private Dictionary<Node, Node> _Nodes; + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Terminal.cs b/Alunite/Simulation/Terminal.cs index e9ceaa9..dc2d9b2 100644 --- a/Alunite/Simulation/Terminal.cs +++ b/Alunite/Simulation/Terminal.cs @@ -1,101 +1,31 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A reference to a bidirectional channel in an entity that can be used for communication with complimentary terminals over time. /// </summary> - /// <remarks>Terminals are only compared by reference and therfore, need no additional information.</remarks> /// <typeparam name="TInput">The type of input received on the channel at any one time.</typeparam> /// <typeparam name="TOutput">The type of output given by the channel at any one time.</typeparam> - public class Terminal<TInput, TOutput> + public class Terminal<TInput, TOutput> : Node { - public override string ToString() - { - return this.GetHashCode().ToString(); - } + } /// <summary> - /// A mapping of terminals in one entity to those in another, usually larger and more complex entity. + /// A terminal that receives input without giving any output. /// </summary> - public abstract class TerminalMap + public class InTerminal<TInput> : Terminal<TInput, Void> { - /// <summary> - /// Gets the identity terminal map. - /// </summary> - public static IdentityTerminalMap Identity - { - get - { - return IdentityTerminalMap.Singleton; - } - } - /// <summary> - /// Gets a new lazy terminal map. - /// </summary> - public static LazyTerminalMap Lazy - { - get - { - return new LazyTerminalMap(); - } - } - - /// <summary> - /// Finds the corresponding terminal for the given local terminal. - /// </summary> - public abstract Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal); - } - - /// <summary> - /// A terminal map where lookup operations simply return the same terminal that is given. - /// </summary> - public class IdentityTerminalMap : TerminalMap - { - internal IdentityTerminalMap() - { - - } - - /// <summary> - /// Gets the only instance of this class. - /// </summary> - public static readonly IdentityTerminalMap Singleton = new IdentityTerminalMap(); - - public override Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) - { - return Terminal; - } } /// <summary> - /// A terminal map that only produces new terminals when they are looked up. + /// A terminal that gives output without receiving any input. /// </summary> - public class LazyTerminalMap : TerminalMap + public class OutTerminal<TOutput> : Terminal<Void, TOutput> { - public LazyTerminalMap() - { - this._Terminals = new Dictionary<object, object>(); - } - - public override Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) - { - object res; - if (this._Terminals.TryGetValue(Terminal, out res)) - { - return res as Terminal<TInput, TOutput>; - } - else - { - Terminal<TInput, TOutput> tres = new Terminal<TInput,TOutput>(); - this._Terminals[Terminal] = tres; - return tres; - } - } - private Dictionary<object, object> _Terminals; } } \ No newline at end of file
dzamkov/Alunite-old
e97b6de569a03d372f55836a6aac9eda9fa3967a
Slight refactor
diff --git a/Alunite/Simulation/Entities/Compound.cs b/Alunite/Simulation/Entities/Compound.cs index ddc279d..6dc942d 100644 --- a/Alunite/Simulation/Entities/Compound.cs +++ b/Alunite/Simulation/Entities/Compound.cs @@ -1,61 +1,76 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// An entity made from the combination of other entities. Note that each entity has its terminals remapped to avoid /// conflicts when reusing entities. /// </summary> public class CompoundEntity : Entity { public CompoundEntity() { this._Elements = new List<Element>(); } /// <summary> /// Gets the entities that make up this compound entity. /// </summary> public IEnumerable<Element> Elements { get { return this._Elements; } } /// <summary> /// An element within a compound entity. /// </summary> public struct Element { /// <summary> /// A mapping of terminals from internally in the entity to externally in the compound entity. /// </summary> public TerminalMap TerminalMap; /// <summary> /// The entity for this element. /// </summary> public Entity Entity; } /// <summary> /// Adds an entity to the compound and returns a terminal map that can be used to get global terminals for each /// entities local terminals. /// </summary> public TerminalMap Add(Entity Entity) { TerminalMap tm = this._Elements.Count == 0 ? (TerminalMap)TerminalMap.Identity : TerminalMap.Lazy; this._Elements.Add(new Element() { TerminalMap = tm, Entity = Entity }); return tm; } + public override bool Phantom + { + get + { + foreach (Element e in this._Elements) + { + if (!e.Entity.Phantom) + { + return false; + } + } + return true; + } + } + private List<Element> _Elements; } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Link.cs b/Alunite/Simulation/Entities/Link.cs index 61248f8..6a14ee7 100644 --- a/Alunite/Simulation/Entities/Link.cs +++ b/Alunite/Simulation/Entities/Link.cs @@ -1,75 +1,83 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// An entity that creates internal links within another source entity. Note that once an internal link is made, neither of the involved /// terminals may be referenced with the LinkEntity. /// </summary> public class LinkEntity : Entity { public LinkEntity(Entity Source) { this._Source = Source; this._Links = new List<_Link>(); } /// <summary> /// Gets the source entity for this link entity. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> /// Links two terminals within the source entity. /// </summary> public void Link<TInput, TOutput>(Terminal<TInput, TOutput> A, Terminal<TOutput, TInput> B) { this._Links.Add(_Link.Create<TInput, TOutput>(A, B)); } /// <summary> /// Links two terminals within the source entity. /// </summary> public void Link<TOutput>(Terminal<Void, TOutput> Output, Terminal<TOutput, Void> Input) { this._Links.Add(_Link.Create<Void, TOutput>(Output, Input)); } + public override bool Phantom + { + get + { + return this._Source.Phantom; + } + } + private Entity _Source; private List<_Link> _Links; } /// <summary> /// A link within a link entity. /// </summary> internal class _Link { /// <summary> /// Creates a link between two terminals. /// </summary> public static _Link Create<TA, TB>(Terminal<TA, TB> A, Terminal<TB, TA> B) { return new Special<TA, TB>() { A = A, B = B }; } /// <summary> /// A specialized link between complimentary typed terminals. /// </summary>> public class Special<TA, TB> : _Link { public Terminal<TA, TB> A; public Terminal<TB, TA> B; } } } \ No newline at end of file diff --git a/Alunite/Simulation/Entity.cs b/Alunite/Simulation/Entity.cs index c538755..772b55d 100644 --- a/Alunite/Simulation/Entity.cs +++ b/Alunite/Simulation/Entity.cs @@ -1,163 +1,195 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A static description of a dynamic object that can interact with other entities in a simulation over time. Note that each entity may be used multiple /// times and is not linked with any particular context. /// </summary> public class Entity { /// <summary> /// Creates an entity with a transform to this entity. /// </summary> public virtual TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this, Transform); } + /// <summary> + /// Gets wether or not this entity has any physical components. A phantom entity is invisible, massless and indescructible. + /// </summary> + public virtual bool Phantom + { + get + { + return false; + } + } + /// <summary> /// Gets a camera entity. /// </summary> public static CameraEntity Camera() { return CameraEntity.Singleton; } /// <summary> /// Creates a sphere with the specified mass and radius. /// </summary> public static SphereEntity Sphere(double Mass, double Radius) { return new SphereEntity(Mass, Radius); } /// <summary> /// Creates a compound entity. /// </summary> public static CompoundEntity Compound() { return new CompoundEntity(); } /// <summary> /// Creates a linking entity on another entity. /// </summary> public static LinkEntity Link(Entity Source) { return new LinkEntity(Source); } /// <summary> - /// Creates an entity that attaches this entity to the specified physical body. This will remove all matter - /// from this entity if any exists. + /// Creates an entity that attaches this entity to the specified physical body. Only phantom entities may be embodied. /// </summary> public EmbodimentEntity Embody(Entity Body) { return new EmbodimentEntity(this, Body); } } /// <summary> /// An invisible, indestructible, massless entity that may interact with a simulation. /// </summary> public class PhantomEntity : Entity { - + public override bool Phantom + { + get + { + return true; + } + } } /// <summary> - /// An entity which attaches a entity to a physical form. This allows the attached entity to move and be destroyed with the physical entity while still retaining + /// An entity which attaches a phantom entity to a physical form. This allows the attached entity to move and be destroyed with the physical entity while still retaining /// its special properties. /// </summary> public class EmbodimentEntity : Entity { - public EmbodimentEntity(Entity Phantom, Entity Body) + public EmbodimentEntity(Entity Control, Entity Body) { - this._Phantom = Phantom; + this._Control = Control; this._Body = Body; this._BodyMap = new LazyTerminalMap(); } /// <summary> - /// Gets the entity that is "embodied". + /// Gets the phantom entity that is "embodied". /// </summary> - public Entity Phantom + public Entity Control { get { - return this._Phantom; + return this._Control; } } /// <summary> /// Gets the physical entity used as the body. /// </summary> public Entity Body { get { return this._Body; } } + public override bool Phantom + { + get + { + return false; + } + } + /// <summary> /// Gets the terminal map from terminals internal to the body to terminals that can be referenced externally on this entity. No /// mapping is required for the "Phantom" part of this entity. /// </summary> public TerminalMap BodyMap { get { return this._BodyMap; } } - private Entity _Phantom; + private Entity _Control; private Entity _Body; private LazyTerminalMap _BodyMap; } /// <summary> /// An entity that represents a transformed form of a source entity. /// </summary> public class TransformedEntity : Entity { public TransformedEntity(Entity Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } public override TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this._Source, this._Transform.Apply(Transform)); } /// <summary> /// Gets the entity that is transformed. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> /// Gets the transform used. /// </summary> public Transform Transform { get { return this._Transform; } } + public override bool Phantom + { + get + { + return this._Source.Phantom; + } + } + private Entity _Source; private Transform _Transform; } } \ No newline at end of file
dzamkov/Alunite-old
3be60dbdbfd8e192ba0041230930bb70c1848677
Some refactoring
diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 9242b11..b81081c 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,34 +1,34 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { CameraEntity camsensor = Entity.Camera(); Entity cambody = Entity.Sphere(0.1, 0.1).Apply(new Transform(-0.12, 0.0, 0.0)); Entity cam = camsensor.Embody(cambody); Entity obj = Entity.Sphere(0.1, 2.1).Apply(new Transform(5.0, 0.0, 0.0)); - CompoundEntity world = new CompoundEntity(); + CompoundEntity world = Entity.Compound(); Terminal<Void, View> camout = world.Add(cam).Lookup(camsensor.Output); world.Add(obj); Simulation sim = Simulation.Create(world); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.Control = new Visualizer(sim.Read(camout)); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Compound.cs b/Alunite/Simulation/Entities/Compound.cs index adda1c6..ddc279d 100644 --- a/Alunite/Simulation/Entities/Compound.cs +++ b/Alunite/Simulation/Entities/Compound.cs @@ -1,64 +1,61 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// An entity made from the combination of other entities. Note that each entity has its terminals remapped to avoid /// conflicts when reusing entities. /// </summary> public class CompoundEntity : Entity { public CompoundEntity() { - this._Elements = new List<_Element>(); + this._Elements = new List<Element>(); } /// <summary> /// Gets the entities that make up this compound entity. /// </summary> - public IEnumerable<Entity> Elements + public IEnumerable<Element> Elements { get { - foreach (_Element e in this._Elements) - { - yield return e.Entity; - } + return this._Elements; } } + /// <summary> + /// An element within a compound entity. + /// </summary> + public struct Element + { + /// <summary> + /// A mapping of terminals from internally in the entity to externally in the compound entity. + /// </summary> + public TerminalMap TerminalMap; + + /// <summary> + /// The entity for this element. + /// </summary> + public Entity Entity; + } + /// <summary> /// Adds an entity to the compound and returns a terminal map that can be used to get global terminals for each /// entities local terminals. /// </summary> public TerminalMap Add(Entity Entity) { TerminalMap tm = this._Elements.Count == 0 ? (TerminalMap)TerminalMap.Identity : TerminalMap.Lazy; - this._Elements.Add(new _Element() + this._Elements.Add(new Element() { TerminalMap = tm, Entity = Entity }); return tm; } - private List<_Element> _Elements; - } - - /// <summary> - /// An entity used within a compound entity. - /// </summary> - internal struct _Element - { - /// <summary> - /// A mapping of terminals from locally to globally within the compound entity. - /// </summary> - public TerminalMap TerminalMap; - - /// <summary> - /// The entity for this element. - /// </summary> - public Entity Entity; + private List<Element> _Elements; } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Link.cs b/Alunite/Simulation/Entities/Link.cs index f2b3862..61248f8 100644 --- a/Alunite/Simulation/Entities/Link.cs +++ b/Alunite/Simulation/Entities/Link.cs @@ -1,74 +1,75 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// An entity that creates internal links within another source entity. + /// An entity that creates internal links within another source entity. Note that once an internal link is made, neither of the involved + /// terminals may be referenced with the LinkEntity. /// </summary> public class LinkEntity : Entity { public LinkEntity(Entity Source) { this._Source = Source; this._Links = new List<_Link>(); } /// <summary> /// Gets the source entity for this link entity. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> /// Links two terminals within the source entity. /// </summary> public void Link<TInput, TOutput>(Terminal<TInput, TOutput> A, Terminal<TOutput, TInput> B) { this._Links.Add(_Link.Create<TInput, TOutput>(A, B)); } /// <summary> /// Links two terminals within the source entity. /// </summary> public void Link<TOutput>(Terminal<Void, TOutput> Output, Terminal<TOutput, Void> Input) { this._Links.Add(_Link.Create<Void, TOutput>(Output, Input)); } private Entity _Source; private List<_Link> _Links; } /// <summary> /// A link within a link entity. /// </summary> internal class _Link { /// <summary> /// Creates a link between two terminals. /// </summary> public static _Link Create<TA, TB>(Terminal<TA, TB> A, Terminal<TB, TA> B) { return new Special<TA, TB>() { A = A, B = B }; } /// <summary> /// A specialized link between complimentary typed terminals. /// </summary>> public class Special<TA, TB> : _Link { public Terminal<TA, TB> A; public Terminal<TB, TA> B; } } } \ No newline at end of file diff --git a/Alunite/Simulation/Entity.cs b/Alunite/Simulation/Entity.cs index c5b9716..c538755 100644 --- a/Alunite/Simulation/Entity.cs +++ b/Alunite/Simulation/Entity.cs @@ -1,130 +1,163 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A static description of a dynamic object that can interact with other entities in a simulation over time. Note that each entity may be used multiple /// times and is not linked with any particular context. /// </summary> public class Entity { /// <summary> /// Creates an entity with a transform to this entity. /// </summary> public virtual TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this, Transform); } /// <summary> /// Gets a camera entity. /// </summary> public static CameraEntity Camera() { return CameraEntity.Singleton; } /// <summary> /// Creates a sphere with the specified mass and radius. /// </summary> public static SphereEntity Sphere(double Mass, double Radius) { return new SphereEntity(Mass, Radius); } - } - /// <summary> - /// An invisible, indestructible, massless entity that may interact with a simulation. - /// </summary> - public class PhantomEntity : Entity - { /// <summary> - /// Creates an entity that gives this phantom entity the specified physical body. + /// Creates a compound entity. + /// </summary> + public static CompoundEntity Compound() + { + return new CompoundEntity(); + } + + /// <summary> + /// Creates a linking entity on another entity. + /// </summary> + public static LinkEntity Link(Entity Source) + { + return new LinkEntity(Source); + } + + /// <summary> + /// Creates an entity that attaches this entity to the specified physical body. This will remove all matter + /// from this entity if any exists. /// </summary> public EmbodimentEntity Embody(Entity Body) { return new EmbodimentEntity(this, Body); } } /// <summary> - /// An entity which attaches a phantom entity a physical form. This allows the phantom entity to move and be destroyed like a physical entity while still retaining + /// An invisible, indestructible, massless entity that may interact with a simulation. + /// </summary> + public class PhantomEntity : Entity + { + + } + + /// <summary> + /// An entity which attaches a entity to a physical form. This allows the attached entity to move and be destroyed with the physical entity while still retaining /// its special properties. /// </summary> public class EmbodimentEntity : Entity { - public EmbodimentEntity(PhantomEntity Phantom, Entity Body) + public EmbodimentEntity(Entity Phantom, Entity Body) { this._Phantom = Phantom; this._Body = Body; + this._BodyMap = new LazyTerminalMap(); } /// <summary> - /// Gets the phantom entity that is "embodied". + /// Gets the entity that is "embodied". /// </summary> - public PhantomEntity Phantom + public Entity Phantom { get { return this._Phantom; } } /// <summary> /// Gets the physical entity used as the body. /// </summary> public Entity Body { get { return this._Body; } } - private PhantomEntity _Phantom; + /// <summary> + /// Gets the terminal map from terminals internal to the body to terminals that can be referenced externally on this entity. No + /// mapping is required for the "Phantom" part of this entity. + /// </summary> + public TerminalMap BodyMap + { + get + { + return this._BodyMap; + } + } + + private Entity _Phantom; private Entity _Body; + private LazyTerminalMap _BodyMap; } /// <summary> /// An entity that represents a transformed form of a source entity. /// </summary> public class TransformedEntity : Entity { public TransformedEntity(Entity Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } public override TransformedEntity Apply(Transform Transform) { return new TransformedEntity(this._Source, this._Transform.Apply(Transform)); } /// <summary> /// Gets the entity that is transformed. /// </summary> public Entity Source { get { return this._Source; } } /// <summary> /// Gets the transform used. /// </summary> public Transform Transform { get { return this._Transform; } } private Entity _Source; private Transform _Transform; } } \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs index 0727a55..6c6c8d8 100644 --- a/Alunite/Simulation/Simulation.cs +++ b/Alunite/Simulation/Simulation.cs @@ -1,31 +1,52 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents the progression of an entity over time. Simulations can be interacted with using /// unbound terminals in the supplied entity. /// </summary> public abstract class Simulation { /// <summary> /// Creates a simulation with the given initial state. /// </summary> public static Simulation Create(Entity World) { - return null; + return new _Simulation(World); } /// <summary> /// Gets a signal for the output of the given terminal. Note that the signal will update as the simulation updates (if any corrections are made /// to input signals). /// </summary> public abstract Signal<TOutput> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal); /// <summary> /// Sets the input of the given terminal to the specified signal. /// </summary> public abstract void Write<TInput, TOutput>(Terminal<TInput, TOutput> Terminal, Signal<TInput> Signal); } + + /// <summary> + /// A concrete implementation of simulation. + /// </summary> + internal class _Simulation : Simulation + { + public _Simulation(Entity World) + { + + } + + public override Signal<TOutput> Read<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) + { + throw new NotImplementedException(); + } + + public override void Write<TInput, TOutput>(Terminal<TInput, TOutput> Terminal, Signal<TInput> Signal) + { + throw new NotImplementedException(); + } + } } \ No newline at end of file
dzamkov/Alunite-old
64c951f737bb741350818b0094ccb4b7ac4ec829
New entity and simulation system
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index abae4d9..fca113c 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,79 +1,79 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> - <Compile Include="Fast\BinaryMatter.cs" /> - <Compile Include="Fast\Matter.cs" /> - <Compile Include="Fast\ParticleMatter.cs" /> - <Compile Include="Fast\Physics.cs" /> - <Compile Include="Fast\Substance.cs" /> - <Compile Include="Fast\TransformedMatter.cs" /> <Compile Include="Data\Filter.cs" /> <Compile Include="Data\MatchMatrix.cs" /> + <Compile Include="Data\Void.cs" /> <Compile Include="Math\Arithmetic.cs" /> <Compile Include="Math\Curve.cs" /> <Compile Include="Math\Scalar.cs" /> - <Compile Include="Physics.cs" /> - <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Math\Quaternion.cs" /> <Compile Include="Data\Set.cs" /> <Compile Include="Data\Sink.cs" /> <Compile Include="Math\Transform.cs" /> <Compile Include="Data\UsageSet.cs" /> <Compile Include="Math\Vector.cs" /> + <Compile Include="Simulation\Entities\Camera.cs" /> + <Compile Include="Simulation\Entities\Compound.cs" /> + <Compile Include="Simulation\Entities\Link.cs" /> + <Compile Include="Simulation\Entity.cs" /> + <Compile Include="Simulation\Signal.cs" /> + <Compile Include="Simulation\Simulation.cs" /> + <Compile Include="Simulation\Terminal.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Data/Void.cs b/Alunite/Data/Void.cs new file mode 100644 index 0000000..d8f2491 --- /dev/null +++ b/Alunite/Data/Void.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A dataless object with only one value. + /// </summary> + public struct Void + { + + } +} \ No newline at end of file diff --git a/Alunite/Fast/BinaryMatter.cs b/Alunite/Fast/BinaryMatter.cs deleted file mode 100644 index e669bbb..0000000 --- a/Alunite/Fast/BinaryMatter.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// Matter created by the composition of a untransformed and a transformed matter. - /// </summary> - public class BinaryMatter : Matter - { - public BinaryMatter(Matter A, Matter B, Transform AToB) - { - this._A = A; - this._B = B; - this._AToB = AToB; - } - - /// <summary> - /// Gets the untransformed part of this matter. - /// </summary> - public Matter A - { - get - { - return this._A; - } - } - - /// <summary> - /// Gets the source of the transformed part of this matter. - /// </summary> - public Matter B - { - get - { - return this._B; - } - } - - /// <summary> - /// Gets the transformed part of this matter with the transform applied. - /// </summary> - public TransformedMatter BFull - { - get - { - return new TransformedMatter(this._B, this._AToB); - } - } - - /// <summary> - /// Gets the transform from A's (and this matter's) coordinate space to B's coordinate space. - /// </summary> - public Transform AToB - { - get - { - return this._AToB; - } - } - - public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) - { - double amass, bmass; - Vector acen, bcen; - double aext, bext; - this._A.GetMassSummary(Physics, out amass, out acen, out aext); - this._B.GetMassSummary(Physics, out bmass, out bcen, out bext); - bcen = this._AToB.ApplyToOffset(bcen); - - Mass = amass + bmass; - CenterOfMass = acen * (amass / Mass) + bcen * (bmass / Mass); - - double alen = (acen - CenterOfMass).Length + aext; - double blen = (bcen - CenterOfMass).Length + bext; - Extent = Math.Max(alen, blen); - } - - public override Matter Update(Physics Physics, Matter Environment, double Time) - { - Matter na = this.A.Update(Physics, Physics.Combine(this.B.Apply(Physics, this.AToB), Environment), Time); - Matter nb = this.B.Update(Physics, Physics.Combine(this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); - return Physics.Combine(na, nb.Apply(Physics, this.AToB.Update(Time))); - } - - public override void OutputUsed(HashSet<Matter> Elements) - { - Elements.Add(this); - this._A.OutputUsed(Elements); - this._B.OutputUsed(Elements); - } - - public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) - { - this._A.OutputParticles(Physics, Transform, Particles); - this._B.OutputParticles(Physics, this._AToB.Apply(Transform), Particles); - } - - public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) - { - Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); - Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); - return agrav + bgrav; - } - - private Matter _A; - private Matter _B; - private Transform _AToB; - } - - /// <summary> - /// Binary matter with many properties memoized, allowing it to perform faster at the cost of using more memory. - /// </summary> - public class MemoizedBinaryMatter : BinaryMatter - { - public MemoizedBinaryMatter(Matter A, Matter B, Transform AToB) - : base(A, B, AToB) - { - this._Mass = double.NaN; - } - - public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) - { - if (double.IsNaN(this._Mass)) - { - base.GetMassSummary(Physics, out this._Mass, out this._CenterOfMass, out this._Extent); - } - Mass = this._Mass; - CenterOfMass = this._CenterOfMass; - Extent = this._Extent; - } - - public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) - { - double mass; Vector com; double ext; this.GetMassSummary(Physics, out mass, out com, out ext); - Vector offset = Position - com; - double offsetlen = com.Length; - double rat = (mass * ext) / (offsetlen * offsetlen); - if (rat >= RecurseThreshold) - { - return base.GetGravity(Physics, Position, Mass, RecurseThreshold); - } - else - { - return offset * (Physics.GetGravityStrength(mass, Mass, offsetlen) / offsetlen); - } - } - - private double _Mass; - private Vector _CenterOfMass; - private double _Extent; - } -} \ No newline at end of file diff --git a/Alunite/Fast/Matter.cs b/Alunite/Fast/Matter.cs deleted file mode 100644 index 070d0b9..0000000 --- a/Alunite/Fast/Matter.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// Matter in a fast physics system. - /// </summary> - public abstract class Matter : IMatter - { - public Matter() - { - - } - - /// <summary> - /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to - /// describe it. - /// </summary> - public int Complexity - { - get - { - HashSet<Matter> used = new HashSet<Matter>(); - this.OutputUsed(used); - return used.Count; - } - } - - /// <summary> - /// Applies a transform to this matter. - /// </summary> - public virtual Matter Apply(Physics Physics, Transform Transform) - { - return new TransformedMatter(this, Transform); - } - - /// <summary> - /// Gets the updated form of this matter in the specified environment after the given time. - /// </summary> - public abstract Matter Update(Physics Physics, Matter Environment, double Time); - - /// <summary> - /// Gets a summary of the location and density of mass inside the matter by getting the total mass, center of mass, - /// and extent (distance from the center of mass to the farthest piece of matter). - /// </summary> - public abstract void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent); - - /// <summary> - /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. - /// </summary> - /// <param name="RecurseThreshold">The ratio of (mass * extent) / (distance ^ 2) a piece of matter will have to have in order to have its - /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> - public virtual Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return Physics.GetGravity(Physics.GetMass(this), Position, Mass); - } - - /// <summary> - /// Recursively outputs all matter used in the definition of this matter, including this matter itself. - /// </summary> - public virtual void OutputUsed(HashSet<Matter> Elements) - { - Elements.Add(this); - } - - /// <summary> - /// Outputs all particles defined in this matter, after applying the specified transform. - /// </summary> - public virtual void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) - { - - } - - /// <summary> - /// Gets all particles defined in this matter. - /// </summary> - public IEnumerable<Particle<Substance>> GetParticles(Physics Physics) - { - List<Particle<Substance>> parts = new List<Particle<Substance>>(); - this.OutputParticles(Physics, Transform.Identity, parts); - return parts; - } - } -} \ No newline at end of file diff --git a/Alunite/Fast/ParticleMatter.cs b/Alunite/Fast/ParticleMatter.cs deleted file mode 100644 index 7150981..0000000 --- a/Alunite/Fast/ParticleMatter.cs +++ /dev/null @@ -1,85 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// Matter containing a single, untransformed particle. - /// </summary> - public class ParticleMatter : Matter - { - public ParticleMatter(Substance Substance, double Mass, AxisAngle Spin) - { - this._Substance = Substance; - this._Mass = Mass; - this._Spin = Spin; - } - - /// <summary> - /// Gets the substance of the particle represented by this matter. - /// </summary> - public Substance Substance - { - get - { - return this._Substance; - } - } - - /// <summary> - /// Gets the untransformed spin of the particle represented by this matter. - /// </summary> - public AxisAngle Spin - { - get - { - return this._Spin; - } - } - - public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) - { - Particles.Add(new Particle<Substance>() - { - Mass = this._Mass, - Spin = this._Spin.Apply(Transform.Rotation), - Substance = this._Substance, - Orientation = Transform.Rotation, - Position = Transform.Offset, - Velocity = Transform.VelocityOffset - }); - } - - public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) - { - Mass = this._Mass; - CenterOfMass = new Vector(0.0, 0.0, 0.0); - Extent = 0.0; - } - - public override Matter Update(Physics Physics, Matter Environment, double Time) - { - Particle<Substance> part = new Particle<Substance>() - { - Mass = this._Mass, - Spin = this._Spin, - Substance = this._Substance, - Orientation = Quaternion.Identity, - Position = new Vector(0.0, 0.0, 0.0), - Velocity = new Vector(0.0, 0.0, 0.0) - }; - this.Substance.Update(Physics, Environment, Time, ref part); - return Physics.Create(part); - } - - public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return Physics.GetGravity(this._Mass, Position, Mass); - } - - private Substance _Substance; - private double _Mass; - private AxisAngle _Spin; - } -} \ No newline at end of file diff --git a/Alunite/Fast/Physics.cs b/Alunite/Fast/Physics.cs deleted file mode 100644 index 7a08b6c..0000000 --- a/Alunite/Fast/Physics.cs +++ /dev/null @@ -1,190 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// A physics system where interactions between matter are memozied allowing for - /// faster simulation. - /// </summary> - public class Physics : IParticlePhysics<Matter, Substance>, IGravitationalPhysics<Matter> - { - public Physics(double G) - { - this._G = G; - } - - public Physics() - : this(6.67428e-11) - { - - } - - /// <summary> - /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. - /// </summary> - public double G - { - get - { - return this._G; - } - } - - public Matter Create(Particle<Substance> Particle) - { - return new TransformedMatter( - new ParticleMatter(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), - new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); - } - - /// <summary> - /// Creates a lattice of the specified object. The amount of items in the lattice is equal to (2 ^ (Log2Size * 3)). - /// </summary> - public Matter CreateLattice(Matter Object, int Log2Size, double Spacing) - { - // Get "major" spacing - Spacing = Spacing * Math.Pow(2.0, Log2Size - 1); - - // Extract transform - TransformedMatter trans = Object as TransformedMatter; - if (trans != null) - { - Object = trans.Source; - return this._CreateLattice(Object, Log2Size, Spacing).Apply(this, trans.Transform); - } - else - { - return this._CreateLattice(Object, Log2Size, Spacing); - } - } - - private Matter _CreateLattice(Matter Object, int Log2Size, double MajorSpacing) - { - // Create a lattice with major spacing - if (Log2Size <= 0) - { - return Object; - } - if (Log2Size > 1) - { - Object = this._CreateLattice(Object, Log2Size - 1, MajorSpacing * 0.5); - } - - BinaryMatter a = this.QuickCombine(Object, Object, new Transform(MajorSpacing, 0.0, 0.0)); - BinaryMatter b = this.QuickCombine(a, a, new Transform(0.0, MajorSpacing, 0.0)); - BinaryMatter c = this.QuickCombine(b, b, new Transform(0.0, 0.0, MajorSpacing)); - return c; - } - - public Matter Apply(Matter Matter, Transform Transform) - { - if (Matter != null) - { - return Matter.Apply(this, Transform); - } - else - { - return null; - } - } - - public Matter Update(Matter Matter, Matter Environment, double Time) - { - return Matter.Update(this, Environment, Time); - } - - public Matter Compose(IEnumerable<Matter> Elements) - { - Matter cur = this.Null; - foreach (Matter matter in Elements) - { - cur = this.Combine(cur, matter); - } - return cur; - } - - /// <summary> - /// Combines two pieces of matter in a similar manner to Compose. - /// </summary> - public Matter Combine(Matter A, Matter B) - { - if (A == null) - { - return B; - } - if (B == null) - { - return A; - } - - TransformedMatter atrans = A as TransformedMatter; - TransformedMatter btrans = B as TransformedMatter; - - Transform atob = Transform.Identity; - if (btrans != null) - { - atob = btrans.Transform; - B = btrans.Source; - } - - if (atrans != null) - { - return new MemoizedBinaryMatter(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(this, atrans.Transform); - } - else - { - return new MemoizedBinaryMatter(A, B, atob); - } - } - - /// <summary> - /// Quickly combines two nonnull pieces of untransformed matter. - /// </summary> - public BinaryMatter QuickCombine(Matter A, Matter B, Transform AToB) - { - return new MemoizedBinaryMatter(A, B, AToB); - } - - public Matter Null - { - get - { - return null; - } - } - - /// <summary> - /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given - /// offset in meters. - /// </summary> - public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) - { - double sqrlen = Offset.SquareLength; - return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); - } - - /// <summary> - /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. - /// </summary> - public double GetGravityStrength(double MassA, double MassB, double Distance) - { - return -this._G * (MassA + MassB) / (Distance * Distance); - } - - public Vector GetGravity(Matter Environment, Vector Position, double Mass) - { - return Environment.GetGravity(this, Position, Mass, 0.0); - } - - public double GetMass(Matter Matter) - { - double mass; Vector com; double extent; - Matter.GetMassSummary(this, out mass, out com, out extent); - return mass; - } - - private double _G; - } -} \ No newline at end of file diff --git a/Alunite/Fast/Substance.cs b/Alunite/Fast/Substance.cs deleted file mode 100644 index 31045eb..0000000 --- a/Alunite/Fast/Substance.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// A substance in a fast physics system. - /// </summary> - public class Substance : IAutoSubstance<Physics, Matter, Substance> - { - private Substance() - { - - } - - /// <summary> - /// The default (and currently only) possible substance. - /// </summary> - public static readonly Substance Default = new Substance(); - - public void Update(Physics Physics, Matter Environment, double Time, ref Particle<Substance> Particle) - { - Vector force = new Vector(); - force += Environment.GetGravity(Physics, new Vector(0.0, 0.0, 0.0), Particle.Mass, Physics.G * 1.0e15); - - foreach (Particle<Substance> part in Environment.GetParticles(Physics)) - { - Vector off = part.Position - Particle.Position; - double offlen = off.Length; - force += off * (-0.01 / (offlen * offlen * offlen)); - } - - Particle.Velocity += force * (Time / Particle.Mass); - Particle.Update(Time); - } - - public MatterDisparity GetDisparity( - Physics Physics, Matter Environment, - double OldMass, double NewMass, - ISubstance NewSubstance, - Vector DeltaPosition, - Vector DeltaVelocity, - Quaternion DeltaOrientation, - AxisAngle OldSpin, AxisAngle NewSpin) - { - throw new NotImplementedException(); - } - } -} \ No newline at end of file diff --git a/Alunite/Fast/TransformedMatter.cs b/Alunite/Fast/TransformedMatter.cs deleted file mode 100644 index 9ef45fe..0000000 --- a/Alunite/Fast/TransformedMatter.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite.Fast -{ - /// <summary> - /// Matter created by transforming other "Source" matter. - /// </summary> - public class TransformedMatter : Matter - { - public TransformedMatter(Matter Source, Transform Transform) - { - this._Source = Source; - this._Transform = Transform; - } - - /// <summary> - /// Gets the source matter for this transformed matter. - /// </summary> - public Matter Source - { - get - { - return this._Source; - } - } - - /// <summary> - /// Gets the transform applied by this transformed matter. - /// </summary> - public Transform Transform - { - get - { - return this._Transform; - } - } - - public override Matter Apply(Physics Physics, Transform Transform) - { - return new TransformedMatter(this.Source, this.Transform.Apply(Transform)); - } - - public override Matter Update(Physics Physics, Matter Environment, double Time) - { - return Physics.Apply(this.Source.Update(Physics, Physics.Apply(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); - } - - public override void OutputUsed(HashSet<Matter> Elements) - { - Elements.Add(this); - this._Source.OutputUsed(Elements); - } - - public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) - { - this._Source.OutputParticles(Physics, this._Transform.Apply(Transform), Particles); - } - - public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) - { - this._Source.GetMassSummary(Physics, out Mass, out CenterOfMass, out Extent); - CenterOfMass = this._Transform.ApplyToOffset(CenterOfMass); - } - - public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return this._Transform.ApplyToDirection(this._Source.GetGravity(Physics, this._Transform.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); - } - - private Matter _Source; - private Transform _Transform; - } -} \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs deleted file mode 100644 index 3651d3b..0000000 --- a/Alunite/Particle.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// A physical system that allows the introduction and simulation of particles. - /// </summary> - public interface IParticlePhysics<TMatter, TSubstance> : ISpatialPhysics<TMatter> - where TMatter : IMatter - where TSubstance : ISubstance - { - /// <summary> - /// Creates a matter form of a single particle with the specified properties. - /// </summary> - TMatter Create(Particle<TSubstance> Particle); - } - - /// <summary> - /// Contains the properties of a particle. - /// </summary> - public struct Particle<TSubstance> - { - /// <summary> - /// The substance the particle is of. - /// </summary> - public TSubstance Substance; - - /// <summary> - /// The relative position of the particle. - /// </summary> - public Vector Position; - - /// <summary> - /// The relative velocity of the particle. - /// </summary> - public Vector Velocity; - - /// <summary> - /// The orientation of the particle. - /// </summary> - public Quaternion Orientation; - - /// <summary> - /// The angular velocity of the particle. - /// </summary> - public AxisAngle Spin; - - /// <summary> - /// The mass of the particle in kilograms. - /// </summary> - public double Mass; - - /// <summary> - /// Updates the spatial state of this particle by the given amount of time in seconds. - /// </summary> - public void Update(double Time) - { - this.Position += this.Velocity * Time; - this.Orientation.Apply(this.Spin * Time); - } - } - - /// <summary> - /// Descibes the physical properties of a particle. - /// </summary> - public interface ISubstance - { - - } - - /// <summary> - /// A substance with known interactions in a certain kind of physics system. - /// </summary> - public interface IAutoSubstance<TPhysics, TMatter, TSubstance> : ISubstance - where TPhysics : IParticlePhysics<TMatter, TSubstance> - where TMatter : IMatter - where TSubstance : IAutoSubstance<TPhysics, TMatter, TSubstance> - { - /// <summary> - /// Updates a particle of this kind of substance in the given environment. - /// </summary> - void Update(TPhysics Physics, TMatter Environment, double Time, ref Particle<TSubstance> Particle); - - /// <summary> - /// Gets the complex disparity created if a particle of this substance was replaced with a new particle with the described - /// properties. - /// </summary> - MatterDisparity GetDisparity( - TPhysics Physics, TMatter Environment, - double OldMass, double NewMass, - ISubstance NewSubstance, - Vector DeltaPosition, - Vector DeltaVelocity, - Quaternion DeltaOrientation, - AxisAngle OldSpin, AxisAngle NewSpin); - } -} \ No newline at end of file diff --git a/Alunite/Physics.cs b/Alunite/Physics.cs deleted file mode 100644 index 7a7ccd3..0000000 --- a/Alunite/Physics.cs +++ /dev/null @@ -1,128 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Represents a set of physical laws that allow the interaction of matter over time. - /// </summary> - public interface IPhysics<TMatter> - where TMatter : IMatter - { - /// <summary> - /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting - /// upon the target matter. - /// </summary> - TMatter Update(TMatter Matter, TMatter Environment, double Time); - - /// <summary> - /// Creates some matter that is the physical composition of other matter. - /// </summary> - TMatter Compose(IEnumerable<TMatter> Elements); - - /// <summary> - /// Gets matter that has no affect or interaction in the physics system. - /// </summary> - TMatter Null { get; } - } - - /// <summary> - /// A physical system that acts in three-dimensional space. - /// </summary> - public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> - where TMatter : IMatter - { - /// <summary> - /// Applies a transformation to some matter. - /// </summary> - TMatter Apply(TMatter Matter, Transform Transform); - } - - /// <summary> - /// A physical system where all matter has a mass expressable in kilograms. - /// </summary> - public interface IMassPhysics<TMatter> : IPhysics<TMatter> - where TMatter : IMatter - { - /// <summary> - /// Gets the mass of the given matter. - /// </summary> - double GetMass(TMatter Matter); - } - - /// <summary> - /// A physical system where gravity (a force that affects all matter depending only on their mass) exists. Note that gravity must be - /// a force felt mutally by involved matter. - /// </summary> - public interface IGravitationalPhysics<TMatter> : ISpatialPhysics<TMatter>, IMassPhysics<TMatter> - where TMatter : IMatter - { - /// <summary> - /// Gets the gravity (meters / second ^ 2) a particle at the specified position and mass will feel if it was in the given environment. - /// </summary> - Vector GetGravity(TMatter Environment, Vector Position, double Mass); - } - - /// <summary> - /// Represents an untransformed object that can participate in physical interactions. - /// </summary> - public interface IMatter - { - - } - - /// <summary> - /// Describes the difference between two pieces of matter. - /// </summary> - /// <remarks>The "simple matter disparity" does not take into account forces to external matter while the "complex matter disparity" does. Note that - /// matter disparity is for the most part an approximation used for optimizations.</remarks> - public struct MatterDisparity - { - public MatterDisparity(double Movement, double Translation, double Mass) - { - this.Movement = Movement; - this.Translation = Translation; - this.Mass = Mass; - } - - /// <summary> - /// Gets the matter disparity between two identical pieces of matter. - /// </summary> - public static MatterDisparity Identical - { - get - { - return new MatterDisparity(0.0, 0.0, 0.0); - } - } - - /// <summary> - /// Gets the simple matter disparity between two particles. - /// </summary> - public static MatterDisparity BetweenParticles(double MassA, Vector PosA, Vector VelA, double MassB, Vector PosB, Vector VelB) - { - return new MatterDisparity( - (MassA + MassB) * (VelA - VelB).Length, - (MassA + MassB) * (PosA - PosB).Length, - Math.Abs(MassA - MassB)); - } - - /// <summary> - /// The amount of mass, course deviation that would be caused if the compared pieces of matter were swapped in usage, measured in - /// kilograms meters per second. Note that if this is for "complex matter disparity", this should take into account external - /// matter and forces. - /// </summary> - public double Movement; - - /// <summary> - /// The amount of mass that is immediately translated between the two compared pieces of matter, measured in kilogram meters. - /// </summary> - public double Translation; - - /// <summary> - /// The difference in mass of the two compared pieces of matter measured in kilograms. - /// </summary> - public double Mass; - } -} \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 0c7f628..72307ea 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,37 +1,22 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; -using Alunite.Fast; - namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Curve<Scalar> t = new Curve<Scalar>(new Scalar[] { 1.0, -(67.0 / 81.0), (26.0 / 81.0), 0.0 }); - double s = t[1.0 / 3.0]; - double q = t[2.0 / 3.0]; - - Curve<Scalar> test = Curve.Match(new Scalar[] { 0.0, 1.0, 2.0, 1.0, 0.0 }); - double a = test[0.0]; - double b = test[0.25]; - double c = test[0.5]; - double d = test[0.75]; - double e = test[1.0]; - Curve<Vector> acurve = Curve.Linear(new Vector(-1.0, 0.0, 0.5), new Vector(1.0, 0.0, 0.5)); - Curve<Vector> bcurve = Curve.Linear(new Vector(0.0, 1.0, 0.0), new Vector(0.0, -1.0, 0.0)); - Curve<Scalar> dist = Curve.Distance(acurve, bcurve); } } } \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Camera.cs b/Alunite/Simulation/Entities/Camera.cs new file mode 100644 index 0000000..e25735d --- /dev/null +++ b/Alunite/Simulation/Entities/Camera.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A sensor entity that exposes a terminal which gives the image seen starting at (0.0, 0.0, 0.0) and looking towards (1.0, 0.0, 0.0) in local + /// coordinates. + /// </summary> + public class CameraEntity : PhantomEntity + { + internal CameraEntity() + { + this._Output = new Terminal<Void, Image>(); + } + + /// <summary> + /// Gets the only instance of this class. + /// </summary> + public static readonly CameraEntity Singleton = new CameraEntity(); + + /// <summary> + /// Gets the output image of this camera sensor. + /// </summary> + public Terminal<Void, Image> Output + { + get + { + return this._Output; + } + } + + private Terminal<Void, Image> _Output; + } + + /// <summary> + /// Represents a static picture with an infinite resolution that can be drawn to a graphics context. + /// </summary> + public class Image + { + + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Compound.cs b/Alunite/Simulation/Entities/Compound.cs new file mode 100644 index 0000000..fdb70d3 --- /dev/null +++ b/Alunite/Simulation/Entities/Compound.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// An entity made from the combination of other entities. Note that each entity has its terminals remapped to avoid + /// conflicts when reusing entities. + /// </summary> + public class CompoundEntity + { + public CompoundEntity() + { + this._Elements = new List<_Element>(); + } + + /// <summary> + /// Gets the entities that make up this compound entity. + /// </summary> + public IEnumerable<Entity> Elements + { + get + { + foreach (_Element e in this._Elements) + { + yield return e.Entity; + } + } + } + + /// <summary> + /// Adds an entity to the compound and returns a terminal map that can be used to get global terminals for each + /// entities local terminals. + /// </summary> + public TerminalMap Add(Entity Entity) + { + TerminalMap tm = this._Elements.Count == 0 ? (TerminalMap)TerminalMap.Identity : TerminalMap.Lazy; + this._Elements.Add(new _Element() + { + TerminalMap = tm, + Entity = Entity + }); + return tm; + } + + private List<_Element> _Elements; + } + + /// <summary> + /// An entity used within a compound entity. + /// </summary> + internal struct _Element + { + /// <summary> + /// A mapping of terminals from locally to globally within the compound entity. + /// </summary> + public TerminalMap TerminalMap; + + /// <summary> + /// The entity for this element. + /// </summary> + public Entity Entity; + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Entities/Link.cs b/Alunite/Simulation/Entities/Link.cs new file mode 100644 index 0000000..f2b3862 --- /dev/null +++ b/Alunite/Simulation/Entities/Link.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// An entity that creates internal links within another source entity. + /// </summary> + public class LinkEntity : Entity + { + public LinkEntity(Entity Source) + { + this._Source = Source; + this._Links = new List<_Link>(); + } + + /// <summary> + /// Gets the source entity for this link entity. + /// </summary> + public Entity Source + { + get + { + return this._Source; + } + } + + /// <summary> + /// Links two terminals within the source entity. + /// </summary> + public void Link<TInput, TOutput>(Terminal<TInput, TOutput> A, Terminal<TOutput, TInput> B) + { + this._Links.Add(_Link.Create<TInput, TOutput>(A, B)); + } + + /// <summary> + /// Links two terminals within the source entity. + /// </summary> + public void Link<TOutput>(Terminal<Void, TOutput> Output, Terminal<TOutput, Void> Input) + { + this._Links.Add(_Link.Create<Void, TOutput>(Output, Input)); + } + + private Entity _Source; + private List<_Link> _Links; + } + + /// <summary> + /// A link within a link entity. + /// </summary> + internal class _Link + { + /// <summary> + /// Creates a link between two terminals. + /// </summary> + public static _Link Create<TA, TB>(Terminal<TA, TB> A, Terminal<TB, TA> B) + { + return new Special<TA, TB>() + { + A = A, + B = B + }; + } + + /// <summary> + /// A specialized link between complimentary typed terminals. + /// </summary>> + public class Special<TA, TB> : _Link + { + public Terminal<TA, TB> A; + public Terminal<TB, TA> B; + } + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Entity.cs b/Alunite/Simulation/Entity.cs new file mode 100644 index 0000000..3b8b0ac --- /dev/null +++ b/Alunite/Simulation/Entity.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A static description of a dynamic object that can interact with other entities in a simulation over time. Note that each entity may be used multiple + /// times and is not linked with any particular context. + /// </summary> + public class Entity + { + + } + + /// <summary> + /// An invisible, indestructible, massless entity that may interact with a simulation. + /// </summary> + public class PhantomEntity : Entity + { + /// <summary> + /// Creates an entity that gives this phantom entity the specified physical body. + /// </summary> + public EmbodimentEntity Embody(Entity Body) + { + return new EmbodimentEntity(this, Body); + } + } + + /// <summary> + /// An entity which attaches a phantom entity a physical form. This allows the phantom entity to move and be destroyed like a physical entity while still retaining + /// its special properties. + /// </summary> + public class EmbodimentEntity : Entity + { + public EmbodimentEntity(PhantomEntity Phantom, Entity Body) + { + this._Phantom = Phantom; + this._Body = Body; + } + + private PhantomEntity _Phantom; + private Entity _Body; + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Signal.cs b/Alunite/Simulation/Signal.cs new file mode 100644 index 0000000..07a1a97 --- /dev/null +++ b/Alunite/Simulation/Signal.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A continous time-varying value. + /// </summary> + /// <typeparam name="T">The type of the signal at any one time.</typeparam> + public abstract class Signal<T> + { + /// <summary> + /// Gets the value of the signal at any one time. + /// </summary> + /// <remarks>Due to the fact that a double can not perfectly represent any one time, this actually gets the average + /// of the signal between Time and the next highest double.</remarks> + public abstract T this[double Time] { get; } + + /// <summary> + /// Gets the sum of the value in the range [Start, End) divided by the size of interval. + /// </summary> + public abstract T Average(double Start, double End); + } + + /// <summary> + /// A sample type that contains a variable amount of items of the given type. + /// </summary> + /// <remarks>This can be used as the type parameter of a signal to create an event signal.</remarks> + public struct Event<T> + { + /// <summary> + /// Gets if the event sample contains no events. + /// </summary> + public bool Empty + { + get + { + return !this.Items.GetEnumerator().MoveNext(); + } + } + + /// <summary> + /// The chronologically-ordered collection of all events in the period of the sample. + /// </summary> + public IEnumerable<T> Items; + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Simulation.cs b/Alunite/Simulation/Simulation.cs new file mode 100644 index 0000000..7a21aaa --- /dev/null +++ b/Alunite/Simulation/Simulation.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Represents the progression of an entity over time. Simulations can be interacted with using + /// unbound terminals in the supplied entity. + /// </summary> + public class Simulation + { + /// <summary> + /// Creates a simulation with the given initial state. + /// </summary> + public static Simulation Create(Entity World) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Alunite/Simulation/Terminal.cs b/Alunite/Simulation/Terminal.cs new file mode 100644 index 0000000..e9ceaa9 --- /dev/null +++ b/Alunite/Simulation/Terminal.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A reference to a bidirectional channel in an entity that can be used for communication with complimentary terminals over time. + /// </summary> + /// <remarks>Terminals are only compared by reference and therfore, need no additional information.</remarks> + /// <typeparam name="TInput">The type of input received on the channel at any one time.</typeparam> + /// <typeparam name="TOutput">The type of output given by the channel at any one time.</typeparam> + public class Terminal<TInput, TOutput> + { + public override string ToString() + { + return this.GetHashCode().ToString(); + } + } + + /// <summary> + /// A mapping of terminals in one entity to those in another, usually larger and more complex entity. + /// </summary> + public abstract class TerminalMap + { + /// <summary> + /// Gets the identity terminal map. + /// </summary> + public static IdentityTerminalMap Identity + { + get + { + return IdentityTerminalMap.Singleton; + } + } + + /// <summary> + /// Gets a new lazy terminal map. + /// </summary> + public static LazyTerminalMap Lazy + { + get + { + return new LazyTerminalMap(); + } + } + + /// <summary> + /// Finds the corresponding terminal for the given local terminal. + /// </summary> + public abstract Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal); + } + + /// <summary> + /// A terminal map where lookup operations simply return the same terminal that is given. + /// </summary> + public class IdentityTerminalMap : TerminalMap + { + internal IdentityTerminalMap() + { + + } + + /// <summary> + /// Gets the only instance of this class. + /// </summary> + public static readonly IdentityTerminalMap Singleton = new IdentityTerminalMap(); + + public override Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) + { + return Terminal; + } + } + + /// <summary> + /// A terminal map that only produces new terminals when they are looked up. + /// </summary> + public class LazyTerminalMap : TerminalMap + { + public LazyTerminalMap() + { + this._Terminals = new Dictionary<object, object>(); + } + + public override Terminal<TInput, TOutput> Lookup<TInput, TOutput>(Terminal<TInput, TOutput> Terminal) + { + object res; + if (this._Terminals.TryGetValue(Terminal, out res)) + { + return res as Terminal<TInput, TOutput>; + } + else + { + Terminal<TInput, TOutput> tres = new Terminal<TInput,TOutput>(); + this._Terminals[Terminal] = tres; + return tres; + } + } + + private Dictionary<object, object> _Terminals; + } +} \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 53430a7..54e383a 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,64 +1,26 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; -using Alunite.Fast; - namespace Alunite { /// <summary> - /// A visualizer for matter. + /// A visualizer for a simulation. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(Physics Physics, Matter World) - { - this._Physics = Physics; - this._World = World; - } - - public override void SetupProjection(Point Viewsize) - { - Vector3d up = new Vector3d(0.0, 0.0, 1.0); - Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); - Vector lookpos = new Vector(0.5, 0.5, 0.5); - Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); - GL.MultMatrix(ref proj); - GL.MultMatrix(ref view); - } - public override void RenderScene() { - GL.Enable(EnableCap.DepthTest); - GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.PointSize(2.0f); - GL.Begin(BeginMode.Points); - GL.Color4(Color.RGB(0.0, 0.5, 1.0)); - foreach (Particle<Substance> part in this._World.GetParticles(this._Physics)) - { - GL.Vertex3(part.Position); - } - GL.End(); - GL.Disable(EnableCap.DepthTest); + throw new NotImplementedException(); } - public override void Update(GUIControlContext Context, double Time) + public override void SetupProjection(Point Viewsize) { - { - Physics phys = this._Physics; - this._World = phys.Update(this._World, phys.Null, Time * 0.1); - } - this._Time += Time * 0.2; + throw new NotImplementedException(); } - - private Physics _Physics; - private Matter _World; - private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
3dda9dd5db684ba47308d47715b4470444efbe56
More curve stuff
diff --git a/Alunite/Math/Arithmetic.cs b/Alunite/Math/Arithmetic.cs index b0684b2..c7ab397 100644 --- a/Alunite/Math/Arithmetic.cs +++ b/Alunite/Math/Arithmetic.cs @@ -1,42 +1,53 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents an object that can have additive and subtractive operations applied to it. Note that it can be assumed that the default /// Operand is the additive identity. /// </summary> /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> public interface IAdditive<TBase, TOperand> { /// <summary> /// Gets the sum of this and a operand. /// </summary> TBase Add(TOperand Operand); /// <summary> /// Gets the difference of this and a operand. /// </summary> TBase Subtract(TOperand Operand); } /// <summary> /// Represents an object that can have multiplicative and divise operations applied to it. /// </summary> /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> public interface IMultiplicative<TBase, TOperand> { /// <summary> /// Gets the product of this and a operand. /// </summary> TBase Multiply(TOperand Operand); /// <summary> /// Gets the quotient of this and a operand. /// </summary> TBase Divide(TOperand Operand); } + + /// <summary> + /// Represents an object that has a square root. + /// </summary> + public interface ISquareRootable<TBase> : IMultiplicative<TBase, TBase> + { + /// <summary> + /// Gets the square root of this object. + /// </summary> + TBase SquareRoot { get; } + } } \ No newline at end of file diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs index dfb91b6..28fa25a 100644 --- a/Alunite/Math/Curve.cs +++ b/Alunite/Math/Curve.cs @@ -1,352 +1,460 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. /// </summary> public sealed class Curve<T> where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { public Curve(T[] Points) { this._Points = Points; } /// <summary> /// Creates an identical curve with a higher order. /// </summary> public Curve<T> Elevate(int Order) { int target = Order + 1; T[] cpoints = this._Points; while (cpoints.Length < target) { int cur = cpoints.Length; T[] npoints = new T[cur + 1]; npoints[0] = cpoints[0]; npoints[cur] = cpoints[cur - 1]; double dcur = (double)cur; for (int i = 1; i < cur; i++) { npoints[i] = cpoints[i - 1].Multiply((double)i / dcur).Add(cpoints[i].Multiply((dcur - (double)i) / dcur)); } cpoints = npoints; } return new Curve<T>(cpoints); } /// <summary> /// Gets the order (complexity, degree) of this bezier curve. 0 is the minimum order for /// a valid curve. /// </summary> public int Order { get { return this._Points.Length - 1; } } /// <summary> /// Gets the control points for this curve. Note that the array should not be modified. /// </summary> public T[] Points { get { return this._Points; } } /// <summary> /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. /// </summary> public T this[double Param] { get { T[] coff = this._GetCoffecients(); T res = coff[0]; double apar = Param; for (int i = 1; i < coff.Length; i++) { res = res.Add(coff[i].Multiply(apar)); apar *= Param; } return res; } } /// <summary> /// Gets the first value in this curve. /// </summary> public T Initial { get { return this._Points[0]; } } /// <summary> /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. /// </summary> private T[] _GetCoffecients() { if (this._Coff == null) { int size = this._Points.Length; this._Coff = new T[size]; double[] bcoff = Curve.GetBezierCoffecients(this.Order); for (int t = 0; t < size; t++) { int s = t * size; T coff = this._Points[0].Multiply(bcoff[s]); for (int i = 1; i < size; i++) { s++; coff = coff.Add(this._Points[i].Multiply(bcoff[s])); } this._Coff[t] = coff; } } return this._Coff; } private T[] _Points; private T[] _Coff; } /// <summary> /// Contains functions related to curves. /// </summary> public static class Curve { /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<T> Constant<T>(T Value) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Value }); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<T> Linear<T>(T Start, T End) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Start, End }); } /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<Scalar> Constant(double Value) { return Constant<Scalar>(Value); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<Scalar> Linear(double Start, double End) { return Linear<Scalar>(Start, End); } /// <summary> /// Gets the intergral of the given curve starting at the specified initial value. /// </summary> public static Curve<T> Integral<T>(Curve<T> Curve, T Initial) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] ipoints = new T[cpoints.Length + 1]; double scale = 1.0 / (double)cpoints.Length; ipoints[0] = Initial; for (int t = 0; t < cpoints.Length; t++) { Initial = Initial.Add(cpoints[t].Multiply(scale)); ipoints[t + 1] = Initial; } return new Curve<T>(ipoints); } /// <summary> /// Gets the derivative of the given curve. /// </summary> public static Curve<T> Derivative<T>(Curve<T> Curve) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; int size = cpoints.Length; if (size > 1) { T[] ipoints = new T[size - 1]; double scale = (double)(size - 1); for (int t = 0; t < ipoints.Length; t++) { ipoints[t] = cpoints[t + 1].Subtract(cpoints[t]).Multiply(scale); } return new Curve<T>(ipoints); } else { return Constant(default(T)); } } /// <summary> /// Sets both curves to have the same order without changing their content. /// </summary> public static void Align<T>(ref Curve<T> A, ref Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { if (A.Order < B.Order) { A = A.Elevate(B.Order); } else { B = B.Elevate(A.Order); } } /// <summary> /// Gets the sum of two curves. /// </summary> public static Curve<T> Add<T>(Curve<T> A, Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { Align(ref A, ref B); T[] apoints = A.Points; T[] bpoints = B.Points; T[] npoints = new T[apoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = apoints[t].Add(bpoints[t]); } return new Curve<T>(npoints); } /// <summary> /// Gets the difference of two curves. /// </summary> public static Curve<T> Subtract<T>(Curve<T> A, Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { Align(ref A, ref B); T[] apoints = A.Points; T[] bpoints = B.Points; T[] npoints = new T[apoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = apoints[t].Subtract(bpoints[t]); } return new Curve<T>(npoints); } /// <summary> /// Scales a curve by the specified multiplier. /// </summary> public static Curve<T> Scale<T>(Curve<T> Curve, double Multiplier) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] npoints = new T[cpoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = cpoints[t].Multiply(Multiplier); } return new Curve<T>(npoints); } /// <summary> /// Gets the product of two curves. /// </summary> public static Curve<R> Multiply<R, L>(Curve<R> Right, Curve<L> Left) where R : IAdditive<R, R>, IMultiplicative<R, Scalar>, IMultiplicative<R, L> where L : IAdditive<L, L>, IMultiplicative<L, Scalar> { R[] rpoints = Right.Points; L[] lpoints = Left.Points; R[] npoints = new R[rpoints.Length + lpoints.Length - 1]; double da = (double)rpoints.Length; double db = (double)lpoints.Length; // Note: The coffecients used to determine the influence a pair of input points // has on the output are base on binomial coffecients, which are encoded into the diagonals // of bezier coffecients. double[] rcoff = GetBezierCoffecients(rpoints.Length - 1); double[] lcoff = GetBezierCoffecients(lpoints.Length - 1); double[] ncoff = GetBezierCoffecients(npoints.Length - 1); for (int x = 0; x < rpoints.Length; x++) { double crcoff = rcoff[x + (x * rpoints.Length)]; for (int y = 0; y < lpoints.Length; y++) { double clcoff = lcoff[y + (y * lpoints.Length)]; int t = x + y; npoints[t] = npoints[t].Add(rpoints[x].Multiply(lpoints[y]).Multiply(crcoff * clcoff)); } } for (int t = 0; t < npoints.Length; t++) { npoints[t] = npoints[t].Divide(ncoff[t + (t * npoints.Length)]); } return new Curve<R>(npoints); } + /// <summary> + /// Gets the square of the specified curve. + /// </summary> + public static Curve<T> Square<T>(Curve<T> Curve) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar>, IMultiplicative<T, T> + { + return Multiply(Curve, Curve); + } + + /// <summary> + /// Approximates the quotient of a constant divided by a curve. The accuracy of the resulting curve depends on the + /// order of the input curve. + /// </summary> + public static Curve<T> Divide<T>(T Constant, Curve<T> Curve) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar>, IMultiplicative<T, T> + { + T[] cpoints = Curve.Points; + T[] npoints = new T[cpoints.Length]; + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = Constant.Divide(cpoints[t]); + } + return new Curve<T>(npoints); + } + + /// <summary> + /// Approximates the square root of a curve. The accuracy of the resulting curve depends on the + /// order of the input curve. + /// </summary> + public static Curve<T> SquareRoot<T>(Curve<T> Curve) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar>, ISquareRootable<T> + { + T[] cpoints = Curve.Points; + T[] npoints = new T[cpoints.Length]; + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = cpoints[t].SquareRoot; + } + return new Curve<T>(npoints); + } + + /// <summary> + /// Splits a vector curve into component curves. + /// </summary> + public static void Split(Curve<Vector> Curve, out Curve<Scalar> X, out Curve<Scalar> Y, out Curve<Scalar> Z) + { + Vector[] cpoints = Curve.Points; + Scalar[] xpoints = new Scalar[cpoints.Length]; + Scalar[] ypoints = new Scalar[cpoints.Length]; + Scalar[] zpoints = new Scalar[cpoints.Length]; + for (int t = 0; t < cpoints.Length; t++) + { + xpoints[t] = cpoints[t].X; + ypoints[t] = cpoints[t].Y; + zpoints[t] = cpoints[t].Z; + } + X = new Curve<Scalar>(xpoints); + Y = new Curve<Scalar>(ypoints); + Z = new Curve<Scalar>(zpoints); + } + + /// <summary> + /// Gets a curve representing the square of the length of the given vector curve over all parameters. + /// </summary> + public static Curve<Scalar> SquareLength(Curve<Vector> Curve) + { + Curve<Scalar> xcurve, ycurve, zcurve; + Split(Curve, out xcurve, out ycurve, out zcurve); + xcurve = Square(xcurve); + ycurve = Square(ycurve); + zcurve = Square(zcurve); + return Add(Add(xcurve, ycurve), zcurve); + } + + /// <summary> + /// Gets a curve that approximates the length of a vector curve over all parameters. + /// </summary> + public static Curve<Scalar> Length(Curve<Vector> Curve) + { + return SquareRoot(SquareLength(Curve)); + } + + /// <summary> + /// Gets a curve that approximates the distance between two vector curves over all parameters. + /// </summary> + public static Curve<Scalar> Distance(Curve<Vector> A, Curve<Vector> B) + { + return Length(Subtract(A, B)); + } + + /// <summary> + /// Creates a curve which matches the specified parameters at their corresponding parameters (starting at 0.0 and then increasing + /// by 1 / Order for each value). + /// </summary> + public static Curve<T> Match<T>(T[] Values) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + if (Values.Length == 1) + { + return Constant(Values[0]); + } + if (Values.Length == 2) + { + return Linear(Values[0], Values[1]); + } + return null; + } + /// <summary> /// Contains the coffecients needed to evaluate bezier curves of certain orders. /// </summary> private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); /// <summary> /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of /// the parameter given to the curve and the control points. /// </summary> public static double[] GetBezierCoffecients(int Order) { if (Order < _BezierCoffecients.Count) { return _BezierCoffecients[Order]; } else { // Compute the coffecients based on the previous order int psize = Order; int size = (Order + 1); double[] coff = new double[size * size]; if (Order == 0) { coff[0] = 1; } else { double[] precoff = GetBezierCoffecients(Order - 1); for (int x = 0; x < psize; x++) { for (int y = 0; y < psize; y++) { double cur = precoff[x + (y * psize)]; coff[x + (y * size) + size] -= cur; coff[x + (y * size) + size + 1] += cur; coff[x + (y * size)] += cur; } } } _BezierCoffecients.Add(coff); return coff; } } } } \ No newline at end of file diff --git a/Alunite/Math/Scalar.cs b/Alunite/Math/Scalar.cs index 876ba1a..fe5fe6f 100644 --- a/Alunite/Math/Scalar.cs +++ b/Alunite/Math/Scalar.cs @@ -1,55 +1,63 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in one-dimensional space. /// </summary> - public struct Scalar : IAdditive<Scalar, Scalar>, IMultiplicative<Scalar, Scalar> + public struct Scalar : IAdditive<Scalar, Scalar>, IMultiplicative<Scalar, Scalar>, ISquareRootable<Scalar> { public Scalar(double Value) { this.Value = Value; } public static implicit operator double(Scalar Scalar) { return Scalar.Value; } public static implicit operator Scalar(double Value) { return new Scalar(Value); } public Scalar Add(Scalar Operand) { return this + Operand; } public Scalar Subtract(Scalar Operand) { return this - Operand; } public Scalar Multiply(Scalar Operand) { return this * Operand; } public Scalar Divide(Scalar Operand) { return this / Operand; } + public Scalar SquareRoot + { + get + { + return Math.Sqrt(this.Value); + } + } + public override string ToString() { return this.Value.ToString(); } public double Value; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index a925378..0c7f628 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,31 +1,37 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Curve<Scalar> acurve = Curve.Linear(0.0, 1.0); - Curve<Scalar> bcurve = Curve.Linear(1.0, 0.4); - acurve = Curve.Integral(acurve, (Scalar)0.1); - bcurve = Curve.Integral(bcurve, (Scalar)0.0); - Curve<Scalar> pcurve = Curve.Multiply(acurve, bcurve); - double p = 0.4; - double ab = acurve[p] * bcurve[p]; - double tn = pcurve[p]; + Curve<Scalar> t = new Curve<Scalar>(new Scalar[] { 1.0, -(67.0 / 81.0), (26.0 / 81.0), 0.0 }); + double s = t[1.0 / 3.0]; + double q = t[2.0 / 3.0]; + + Curve<Scalar> test = Curve.Match(new Scalar[] { 0.0, 1.0, 2.0, 1.0, 0.0 }); + double a = test[0.0]; + double b = test[0.25]; + double c = test[0.5]; + double d = test[0.75]; + double e = test[1.0]; + + Curve<Vector> acurve = Curve.Linear(new Vector(-1.0, 0.0, 0.5), new Vector(1.0, 0.0, 0.5)); + Curve<Vector> bcurve = Curve.Linear(new Vector(0.0, 1.0, 0.0), new Vector(0.0, -1.0, 0.0)); + Curve<Scalar> dist = Curve.Distance(acurve, bcurve); } } } \ No newline at end of file
dzamkov/Alunite-old
62e2475f5661f4dbb8aff26ae067987d66282f2e
Bezier curve multiplication
diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs index 5e653c8..dfb91b6 100644 --- a/Alunite/Math/Curve.cs +++ b/Alunite/Math/Curve.cs @@ -1,314 +1,352 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. /// </summary> public sealed class Curve<T> where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { public Curve(T[] Points) { this._Points = Points; } /// <summary> /// Creates an identical curve with a higher order. /// </summary> public Curve<T> Elevate(int Order) { int target = Order + 1; T[] cpoints = this._Points; while (cpoints.Length < target) { int cur = cpoints.Length; T[] npoints = new T[cur + 1]; npoints[0] = cpoints[0]; npoints[cur] = cpoints[cur - 1]; double dcur = (double)cur; for (int i = 1; i < cur; i++) { npoints[i] = cpoints[i - 1].Multiply((double)i / dcur).Add(cpoints[i].Multiply((dcur - (double)i) / dcur)); } cpoints = npoints; } return new Curve<T>(cpoints); } /// <summary> /// Gets the order (complexity, degree) of this bezier curve. 0 is the minimum order for /// a valid curve. /// </summary> public int Order { get { return this._Points.Length - 1; } } /// <summary> /// Gets the control points for this curve. Note that the array should not be modified. /// </summary> public T[] Points { get { return this._Points; } } /// <summary> /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. /// </summary> public T this[double Param] { get { T[] coff = this._GetCoffecients(); T res = coff[0]; double apar = Param; for (int i = 1; i < coff.Length; i++) { res = res.Add(coff[i].Multiply(apar)); apar *= Param; } return res; } } /// <summary> /// Gets the first value in this curve. /// </summary> public T Initial { get { return this._Points[0]; } } /// <summary> /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. /// </summary> private T[] _GetCoffecients() { if (this._Coff == null) { int size = this._Points.Length; this._Coff = new T[size]; double[] bcoff = Curve.GetBezierCoffecients(this.Order); for (int t = 0; t < size; t++) { int s = t * size; T coff = this._Points[0].Multiply(bcoff[s]); for (int i = 1; i < size; i++) { s++; coff = coff.Add(this._Points[i].Multiply(bcoff[s])); } this._Coff[t] = coff; } } return this._Coff; } private T[] _Points; private T[] _Coff; } /// <summary> /// Contains functions related to curves. /// </summary> public static class Curve { /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<T> Constant<T>(T Value) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Value }); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<T> Linear<T>(T Start, T End) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Start, End }); } /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<Scalar> Constant(double Value) { return Constant<Scalar>(Value); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<Scalar> Linear(double Start, double End) { return Linear<Scalar>(Start, End); } /// <summary> /// Gets the intergral of the given curve starting at the specified initial value. /// </summary> public static Curve<T> Integral<T>(Curve<T> Curve, T Initial) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] ipoints = new T[cpoints.Length + 1]; double scale = 1.0 / (double)cpoints.Length; ipoints[0] = Initial; for (int t = 0; t < cpoints.Length; t++) { Initial = Initial.Add(cpoints[t].Multiply(scale)); ipoints[t + 1] = Initial; } return new Curve<T>(ipoints); } /// <summary> /// Gets the derivative of the given curve. /// </summary> public static Curve<T> Derivative<T>(Curve<T> Curve) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; int size = cpoints.Length; if (size > 1) { T[] ipoints = new T[size - 1]; double scale = (double)(size - 1); for (int t = 0; t < ipoints.Length; t++) { ipoints[t] = cpoints[t + 1].Subtract(cpoints[t]).Multiply(scale); } return new Curve<T>(ipoints); } else { return Constant(default(T)); } } /// <summary> /// Sets both curves to have the same order without changing their content. /// </summary> public static void Align<T>(ref Curve<T> A, ref Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { if (A.Order < B.Order) { A = A.Elevate(B.Order); } else { B = B.Elevate(A.Order); } } /// <summary> /// Gets the sum of two curves. /// </summary> public static Curve<T> Add<T>(Curve<T> A, Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { Align(ref A, ref B); T[] apoints = A.Points; T[] bpoints = B.Points; T[] npoints = new T[apoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = apoints[t].Add(bpoints[t]); } return new Curve<T>(npoints); } /// <summary> /// Gets the difference of two curves. /// </summary> public static Curve<T> Subtract<T>(Curve<T> A, Curve<T> B) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { Align(ref A, ref B); T[] apoints = A.Points; T[] bpoints = B.Points; T[] npoints = new T[apoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = apoints[t].Subtract(bpoints[t]); } return new Curve<T>(npoints); } /// <summary> /// Scales a curve by the specified multiplier. /// </summary> public static Curve<T> Scale<T>(Curve<T> Curve, double Multiplier) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] npoints = new T[cpoints.Length]; for (int t = 0; t < npoints.Length; t++) { npoints[t] = cpoints[t].Multiply(Multiplier); } return new Curve<T>(npoints); } + /// <summary> + /// Gets the product of two curves. + /// </summary> + public static Curve<R> Multiply<R, L>(Curve<R> Right, Curve<L> Left) + where R : IAdditive<R, R>, IMultiplicative<R, Scalar>, IMultiplicative<R, L> + where L : IAdditive<L, L>, IMultiplicative<L, Scalar> + { + R[] rpoints = Right.Points; + L[] lpoints = Left.Points; + R[] npoints = new R[rpoints.Length + lpoints.Length - 1]; + double da = (double)rpoints.Length; + double db = (double)lpoints.Length; + + // Note: The coffecients used to determine the influence a pair of input points + // has on the output are base on binomial coffecients, which are encoded into the diagonals + // of bezier coffecients. + double[] rcoff = GetBezierCoffecients(rpoints.Length - 1); + double[] lcoff = GetBezierCoffecients(lpoints.Length - 1); + double[] ncoff = GetBezierCoffecients(npoints.Length - 1); + + for (int x = 0; x < rpoints.Length; x++) + { + double crcoff = rcoff[x + (x * rpoints.Length)]; + for (int y = 0; y < lpoints.Length; y++) + { + double clcoff = lcoff[y + (y * lpoints.Length)]; + int t = x + y; + npoints[t] = npoints[t].Add(rpoints[x].Multiply(lpoints[y]).Multiply(crcoff * clcoff)); + } + } + + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = npoints[t].Divide(ncoff[t + (t * npoints.Length)]); + } + return new Curve<R>(npoints); + } + /// <summary> /// Contains the coffecients needed to evaluate bezier curves of certain orders. /// </summary> private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); /// <summary> /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of /// the parameter given to the curve and the control points. /// </summary> public static double[] GetBezierCoffecients(int Order) { if (Order < _BezierCoffecients.Count) { return _BezierCoffecients[Order]; } else { // Compute the coffecients based on the previous order int psize = Order; int size = (Order + 1); double[] coff = new double[size * size]; if (Order == 0) { coff[0] = 1; } else { double[] precoff = GetBezierCoffecients(Order - 1); for (int x = 0; x < psize; x++) { for (int y = 0; y < psize; y++) { double cur = precoff[x + (y * psize)]; coff[x + (y * size) + size] -= cur; coff[x + (y * size) + size + 1] += cur; coff[x + (y * size)] += cur; } } } _BezierCoffecients.Add(coff); return coff; } } } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index bc9c0f8..a925378 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,30 +1,31 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Curve<Vector> acceleration = Curve.Constant(new Vector(0.0, 0.0, -9.8)); - Curve<Vector> velocity = Curve.Integral(acceleration, new Vector(0.0, 0.0, 0.0)); - Curve<Vector> position = Curve.Integral(velocity, new Vector(0.0, 0.0, 0.0)); - Curve<Vector> nposition = position.Elevate(7); - - double a = position[0.86].Length; - double b = nposition[0.86].Length; + Curve<Scalar> acurve = Curve.Linear(0.0, 1.0); + Curve<Scalar> bcurve = Curve.Linear(1.0, 0.4); + acurve = Curve.Integral(acurve, (Scalar)0.1); + bcurve = Curve.Integral(bcurve, (Scalar)0.0); + Curve<Scalar> pcurve = Curve.Multiply(acurve, bcurve); + double p = 0.4; + double ab = acurve[p] * bcurve[p]; + double tn = pcurve[p]; } } } \ No newline at end of file
dzamkov/Alunite-old
c01e4daf9ba73596ecdde78faf96e0d8e039e8cd
Curve elevation and arithmetic
diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs index 75074fb..5e653c8 100644 --- a/Alunite/Math/Curve.cs +++ b/Alunite/Math/Curve.cs @@ -1,225 +1,314 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. /// </summary> public sealed class Curve<T> where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { public Curve(T[] Points) { this._Points = Points; } /// <summary> - /// Gets the order (complexity) of this bezier curve. 0 is the minimum order for + /// Creates an identical curve with a higher order. + /// </summary> + public Curve<T> Elevate(int Order) + { + int target = Order + 1; + T[] cpoints = this._Points; + while (cpoints.Length < target) + { + int cur = cpoints.Length; + T[] npoints = new T[cur + 1]; + npoints[0] = cpoints[0]; + npoints[cur] = cpoints[cur - 1]; + + double dcur = (double)cur; + for (int i = 1; i < cur; i++) + { + npoints[i] = cpoints[i - 1].Multiply((double)i / dcur).Add(cpoints[i].Multiply((dcur - (double)i) / dcur)); + } + cpoints = npoints; + } + return new Curve<T>(cpoints); + } + + /// <summary> + /// Gets the order (complexity, degree) of this bezier curve. 0 is the minimum order for /// a valid curve. /// </summary> public int Order { get { return this._Points.Length - 1; } } /// <summary> /// Gets the control points for this curve. Note that the array should not be modified. /// </summary> public T[] Points { get { return this._Points; } } /// <summary> /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. /// </summary> public T this[double Param] { get { T[] coff = this._GetCoffecients(); T res = coff[0]; double apar = Param; for (int i = 1; i < coff.Length; i++) { res = res.Add(coff[i].Multiply(apar)); apar *= Param; } return res; } } /// <summary> /// Gets the first value in this curve. /// </summary> public T Initial { get { return this._Points[0]; } } /// <summary> /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. /// </summary> private T[] _GetCoffecients() { if (this._Coff == null) { int size = this._Points.Length; this._Coff = new T[size]; double[] bcoff = Curve.GetBezierCoffecients(this.Order); for (int t = 0; t < size; t++) { int s = t * size; T coff = this._Points[0].Multiply(bcoff[s]); for (int i = 1; i < size; i++) { s++; coff = coff.Add(this._Points[i].Multiply(bcoff[s])); } this._Coff[t] = coff; } } return this._Coff; } private T[] _Points; private T[] _Coff; } /// <summary> /// Contains functions related to curves. /// </summary> public static class Curve { /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<T> Constant<T>(T Value) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Value }); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<T> Linear<T>(T Start, T End) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Start, End }); } /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<Scalar> Constant(double Value) { return Constant<Scalar>(Value); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<Scalar> Linear(double Start, double End) { return Linear<Scalar>(Start, End); } /// <summary> /// Gets the intergral of the given curve starting at the specified initial value. /// </summary> public static Curve<T> Integral<T>(Curve<T> Curve, T Initial) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] ipoints = new T[cpoints.Length + 1]; double scale = 1.0 / (double)cpoints.Length; ipoints[0] = Initial; for (int t = 0; t < cpoints.Length; t++) { Initial = Initial.Add(cpoints[t].Multiply(scale)); ipoints[t + 1] = Initial; } return new Curve<T>(ipoints); } /// <summary> /// Gets the derivative of the given curve. /// </summary> public static Curve<T> Derivative<T>(Curve<T> Curve) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; int size = cpoints.Length; if (size > 1) { T[] ipoints = new T[size - 1]; double scale = (double)(size - 1); for (int t = 0; t < ipoints.Length; t++) { ipoints[t] = cpoints[t + 1].Subtract(cpoints[t]).Multiply(scale); } return new Curve<T>(ipoints); } else { return Constant(default(T)); } } + /// <summary> + /// Sets both curves to have the same order without changing their content. + /// </summary> + public static void Align<T>(ref Curve<T> A, ref Curve<T> B) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + if (A.Order < B.Order) + { + A = A.Elevate(B.Order); + } + else + { + B = B.Elevate(A.Order); + } + } + + /// <summary> + /// Gets the sum of two curves. + /// </summary> + public static Curve<T> Add<T>(Curve<T> A, Curve<T> B) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + Align(ref A, ref B); + T[] apoints = A.Points; + T[] bpoints = B.Points; + T[] npoints = new T[apoints.Length]; + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = apoints[t].Add(bpoints[t]); + } + return new Curve<T>(npoints); + } + + /// <summary> + /// Gets the difference of two curves. + /// </summary> + public static Curve<T> Subtract<T>(Curve<T> A, Curve<T> B) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + Align(ref A, ref B); + T[] apoints = A.Points; + T[] bpoints = B.Points; + T[] npoints = new T[apoints.Length]; + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = apoints[t].Subtract(bpoints[t]); + } + return new Curve<T>(npoints); + } + + /// <summary> + /// Scales a curve by the specified multiplier. + /// </summary> + public static Curve<T> Scale<T>(Curve<T> Curve, double Multiplier) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + T[] cpoints = Curve.Points; + T[] npoints = new T[cpoints.Length]; + for (int t = 0; t < npoints.Length; t++) + { + npoints[t] = cpoints[t].Multiply(Multiplier); + } + return new Curve<T>(npoints); + } + /// <summary> /// Contains the coffecients needed to evaluate bezier curves of certain orders. /// </summary> private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); /// <summary> /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of /// the parameter given to the curve and the control points. /// </summary> public static double[] GetBezierCoffecients(int Order) { if (Order < _BezierCoffecients.Count) { return _BezierCoffecients[Order]; } else { // Compute the coffecients based on the previous order int psize = Order; int size = (Order + 1); double[] coff = new double[size * size]; if (Order == 0) { coff[0] = 1; } else { double[] precoff = GetBezierCoffecients(Order - 1); for (int x = 0; x < psize; x++) { for (int y = 0; y < psize; y++) { double cur = precoff[x + (y * psize)]; coff[x + (y * size) + size] -= cur; coff[x + (y * size) + size + 1] += cur; coff[x + (y * size)] += cur; } } } _BezierCoffecients.Add(coff); return coff; } } } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index bc64cc6..bc9c0f8 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,26 +1,30 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Curve<Vector> acceleration = Curve.Constant(new Vector(0.0, 0.0, -9.8)); Curve<Vector> velocity = Curve.Integral(acceleration, new Vector(0.0, 0.0, 0.0)); Curve<Vector> position = Curve.Integral(velocity, new Vector(0.0, 0.0, 0.0)); + Curve<Vector> nposition = position.Elevate(7); + + double a = position[0.86].Length; + double b = nposition[0.86].Length; } } } \ No newline at end of file
dzamkov/Alunite-old
83516d55538f1891cd1656b20d421c5abadcc64f
Derivative
diff --git a/Alunite/Math/Arithmetic.cs b/Alunite/Math/Arithmetic.cs index abbca48..b0684b2 100644 --- a/Alunite/Math/Arithmetic.cs +++ b/Alunite/Math/Arithmetic.cs @@ -1,41 +1,42 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// Represents an object that can have additive and subtractive operations applied to it. + /// Represents an object that can have additive and subtractive operations applied to it. Note that it can be assumed that the default + /// Operand is the additive identity. /// </summary> /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> public interface IAdditive<TBase, TOperand> { /// <summary> /// Gets the sum of this and a operand. /// </summary> TBase Add(TOperand Operand); /// <summary> /// Gets the difference of this and a operand. /// </summary> TBase Subtract(TOperand Operand); } /// <summary> /// Represents an object that can have multiplicative and divise operations applied to it. /// </summary> /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> public interface IMultiplicative<TBase, TOperand> { /// <summary> /// Gets the product of this and a operand. /// </summary> TBase Multiply(TOperand Operand); /// <summary> /// Gets the quotient of this and a operand. /// </summary> TBase Divide(TOperand Operand); } } \ No newline at end of file diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs index 1bc7519..75074fb 100644 --- a/Alunite/Math/Curve.cs +++ b/Alunite/Math/Curve.cs @@ -1,190 +1,225 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. /// </summary> public sealed class Curve<T> where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { public Curve(T[] Points) { this._Points = Points; } /// <summary> /// Gets the order (complexity) of this bezier curve. 0 is the minimum order for /// a valid curve. /// </summary> public int Order { get { return this._Points.Length - 1; } } /// <summary> /// Gets the control points for this curve. Note that the array should not be modified. /// </summary> public T[] Points { get { return this._Points; } } /// <summary> /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. /// </summary> public T this[double Param] { get { T[] coff = this._GetCoffecients(); T res = coff[0]; double apar = Param; for (int i = 1; i < coff.Length; i++) { res = res.Add(coff[i].Multiply(apar)); apar *= Param; } return res; } } + /// <summary> + /// Gets the first value in this curve. + /// </summary> + public T Initial + { + get + { + return this._Points[0]; + } + } + /// <summary> /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. /// </summary> private T[] _GetCoffecients() { if (this._Coff == null) { int size = this._Points.Length; this._Coff = new T[size]; double[] bcoff = Curve.GetBezierCoffecients(this.Order); for (int t = 0; t < size; t++) { int s = t * size; T coff = this._Points[0].Multiply(bcoff[s]); for (int i = 1; i < size; i++) { s++; coff = coff.Add(this._Points[i].Multiply(bcoff[s])); } this._Coff[t] = coff; } } return this._Coff; } private T[] _Points; private T[] _Coff; } /// <summary> /// Contains functions related to curves. /// </summary> public static class Curve { /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<T> Constant<T>(T Value) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Value }); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<T> Linear<T>(T Start, T End) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { return new Curve<T>(new T[] { Start, End }); } /// <summary> /// Creates a curve with a constant value. /// </summary> public static Curve<Scalar> Constant(double Value) { return Constant<Scalar>(Value); } /// <summary> /// Creates a curve that varies linearly between two values. /// </summary> public static Curve<Scalar> Linear(double Start, double End) { return Linear<Scalar>(Start, End); } /// <summary> /// Gets the intergral of the given curve starting at the specified initial value. /// </summary> public static Curve<T> Integral<T>(Curve<T> Curve, T Initial) where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { T[] cpoints = Curve.Points; T[] ipoints = new T[cpoints.Length + 1]; double scale = 1.0 / (double)cpoints.Length; ipoints[0] = Initial; for (int t = 0; t < cpoints.Length; t++) { Initial = Initial.Add(cpoints[t].Multiply(scale)); ipoints[t + 1] = Initial; } return new Curve<T>(ipoints); } + /// <summary> + /// Gets the derivative of the given curve. + /// </summary> + public static Curve<T> Derivative<T>(Curve<T> Curve) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + T[] cpoints = Curve.Points; + int size = cpoints.Length; + if (size > 1) + { + T[] ipoints = new T[size - 1]; + double scale = (double)(size - 1); + for (int t = 0; t < ipoints.Length; t++) + { + ipoints[t] = cpoints[t + 1].Subtract(cpoints[t]).Multiply(scale); + } + return new Curve<T>(ipoints); + } + else + { + return Constant(default(T)); + } + } + /// <summary> /// Contains the coffecients needed to evaluate bezier curves of certain orders. /// </summary> private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); /// <summary> /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of /// the parameter given to the curve and the control points. /// </summary> public static double[] GetBezierCoffecients(int Order) { if (Order < _BezierCoffecients.Count) { return _BezierCoffecients[Order]; } else { // Compute the coffecients based on the previous order int psize = Order; int size = (Order + 1); double[] coff = new double[size * size]; if (Order == 0) { coff[0] = 1; } else { double[] precoff = GetBezierCoffecients(Order - 1); for (int x = 0; x < psize; x++) { for (int y = 0; y < psize; y++) { double cur = precoff[x + (y * psize)]; coff[x + (y * size) + size] -= cur; coff[x + (y * size) + size + 1] += cur; coff[x + (y * size)] += cur; } } } _BezierCoffecients.Add(coff); return coff; } } } } \ No newline at end of file
dzamkov/Alunite-old
36deb9d554df4e98165cbdac789812615b36a419
Curve integrals
diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs index e4d36de..1bc7519 100644 --- a/Alunite/Math/Curve.cs +++ b/Alunite/Math/Curve.cs @@ -1,127 +1,190 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. /// </summary> public sealed class Curve<T> where T : IAdditive<T, T>, IMultiplicative<T, Scalar> { public Curve(T[] Points) { this._Points = Points; } /// <summary> /// Gets the order (complexity) of this bezier curve. 0 is the minimum order for /// a valid curve. /// </summary> public int Order { get { return this._Points.Length - 1; } } + /// <summary> + /// Gets the control points for this curve. Note that the array should not be modified. + /// </summary> + public T[] Points + { + get + { + return this._Points; + } + } + /// <summary> /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. /// </summary> public T this[double Param] { get { T[] coff = this._GetCoffecients(); T res = coff[0]; double apar = Param; for (int i = 1; i < coff.Length; i++) { res = res.Add(coff[i].Multiply(apar)); apar *= Param; } return res; } } /// <summary> /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. /// </summary> private T[] _GetCoffecients() { if (this._Coff == null) { int size = this._Points.Length; this._Coff = new T[size]; double[] bcoff = Curve.GetBezierCoffecients(this.Order); for (int t = 0; t < size; t++) { int s = t * size; T coff = this._Points[0].Multiply(bcoff[s]); for (int i = 1; i < size; i++) { s++; coff = coff.Add(this._Points[i].Multiply(bcoff[s])); } this._Coff[t] = coff; } } return this._Coff; } private T[] _Points; private T[] _Coff; } /// <summary> /// Contains functions related to curves. /// </summary> public static class Curve { + /// <summary> + /// Creates a curve with a constant value. + /// </summary> + public static Curve<T> Constant<T>(T Value) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + return new Curve<T>(new T[] { Value }); + } + + /// <summary> + /// Creates a curve that varies linearly between two values. + /// </summary> + public static Curve<T> Linear<T>(T Start, T End) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + return new Curve<T>(new T[] { Start, End }); + } + + /// <summary> + /// Creates a curve with a constant value. + /// </summary> + public static Curve<Scalar> Constant(double Value) + { + return Constant<Scalar>(Value); + } + + /// <summary> + /// Creates a curve that varies linearly between two values. + /// </summary> + public static Curve<Scalar> Linear(double Start, double End) + { + return Linear<Scalar>(Start, End); + } + + /// <summary> + /// Gets the intergral of the given curve starting at the specified initial value. + /// </summary> + public static Curve<T> Integral<T>(Curve<T> Curve, T Initial) + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + T[] cpoints = Curve.Points; + T[] ipoints = new T[cpoints.Length + 1]; + double scale = 1.0 / (double)cpoints.Length; + + ipoints[0] = Initial; + for (int t = 0; t < cpoints.Length; t++) + { + Initial = Initial.Add(cpoints[t].Multiply(scale)); + ipoints[t + 1] = Initial; + } + return new Curve<T>(ipoints); + } /// <summary> /// Contains the coffecients needed to evaluate bezier curves of certain orders. /// </summary> private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); /// <summary> /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of /// the parameter given to the curve and the control points. /// </summary> public static double[] GetBezierCoffecients(int Order) { if (Order < _BezierCoffecients.Count) { return _BezierCoffecients[Order]; } else { // Compute the coffecients based on the previous order int psize = Order; int size = (Order + 1); double[] coff = new double[size * size]; if (Order == 0) { coff[0] = 1; } else { double[] precoff = GetBezierCoffecients(Order - 1); for (int x = 0; x < psize; x++) { for (int y = 0; y < psize; y++) { double cur = precoff[x + (y * psize)]; coff[x + (y * size) + size] -= cur; coff[x + (y * size) + size + 1] += cur; coff[x + (y * size)] += cur; } } } _BezierCoffecients.Add(coff); return coff; } } } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index d145c1c..bc64cc6 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,29 +1,26 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - - Curve<Scalar> curve = new Curve<Scalar>(new Scalar[] - { - 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 0.6, 0.2, 0.3, 0.4, 0.5 - }); - double val = curve[1.0]; + Curve<Vector> acceleration = Curve.Constant(new Vector(0.0, 0.0, -9.8)); + Curve<Vector> velocity = Curve.Integral(acceleration, new Vector(0.0, 0.0, 0.0)); + Curve<Vector> position = Curve.Integral(velocity, new Vector(0.0, 0.0, 0.0)); } } } \ No newline at end of file
dzamkov/Alunite-old
e42a1f25f85210936778388f58b63edcf5182a46
Bezier curve
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index d44fa0e..abae4d9 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,76 +1,79 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Fast\BinaryMatter.cs" /> <Compile Include="Fast\Matter.cs" /> <Compile Include="Fast\ParticleMatter.cs" /> <Compile Include="Fast\Physics.cs" /> <Compile Include="Fast\Substance.cs" /> <Compile Include="Fast\TransformedMatter.cs" /> <Compile Include="Data\Filter.cs" /> <Compile Include="Data\MatchMatrix.cs" /> + <Compile Include="Math\Arithmetic.cs" /> + <Compile Include="Math\Curve.cs" /> + <Compile Include="Math\Scalar.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Math\Quaternion.cs" /> <Compile Include="Data\Set.cs" /> <Compile Include="Data\Sink.cs" /> <Compile Include="Math\Transform.cs" /> <Compile Include="Data\UsageSet.cs" /> <Compile Include="Math\Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Math/Arithmetic.cs b/Alunite/Math/Arithmetic.cs new file mode 100644 index 0000000..abbca48 --- /dev/null +++ b/Alunite/Math/Arithmetic.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Represents an object that can have additive and subtractive operations applied to it. + /// </summary> + /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> + /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> + public interface IAdditive<TBase, TOperand> + { + /// <summary> + /// Gets the sum of this and a operand. + /// </summary> + TBase Add(TOperand Operand); + + /// <summary> + /// Gets the difference of this and a operand. + /// </summary> + TBase Subtract(TOperand Operand); + } + + /// <summary> + /// Represents an object that can have multiplicative and divise operations applied to it. + /// </summary> + /// <typeparam name="TBase">The base of the objects produced by this kind of arithmetic.</typeparam> + /// <typeparam name="TOperand">The allowable operand for the arithmetic.</typeparam> + public interface IMultiplicative<TBase, TOperand> + { + /// <summary> + /// Gets the product of this and a operand. + /// </summary> + TBase Multiply(TOperand Operand); + + /// <summary> + /// Gets the quotient of this and a operand. + /// </summary> + TBase Divide(TOperand Operand); + } +} \ No newline at end of file diff --git a/Alunite/Math/Curve.cs b/Alunite/Math/Curve.cs new file mode 100644 index 0000000..e4d36de --- /dev/null +++ b/Alunite/Math/Curve.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A continous function with a domain of reals bounded between 0.0 and 1.0 defined using a bezier curve. + /// </summary> + public sealed class Curve<T> + where T : IAdditive<T, T>, IMultiplicative<T, Scalar> + { + public Curve(T[] Points) + { + this._Points = Points; + } + + /// <summary> + /// Gets the order (complexity) of this bezier curve. 0 is the minimum order for + /// a valid curve. + /// </summary> + public int Order + { + get + { + return this._Points.Length - 1; + } + } + + /// <summary> + /// Gets the value of the curve with the specified parameter between 0.0 and 1.0. + /// </summary> + public T this[double Param] + { + get + { + T[] coff = this._GetCoffecients(); + T res = coff[0]; + double apar = Param; + for (int i = 1; i < coff.Length; i++) + { + res = res.Add(coff[i].Multiply(apar)); + apar *= Param; + } + return res; + } + } + + /// <summary> + /// Gets the coffecients that can be multiplied by corresponding degrees of the parameter to get the result at the parameter. + /// </summary> + private T[] _GetCoffecients() + { + if (this._Coff == null) + { + int size = this._Points.Length; + this._Coff = new T[size]; + double[] bcoff = Curve.GetBezierCoffecients(this.Order); + for (int t = 0; t < size; t++) + { + int s = t * size; + T coff = this._Points[0].Multiply(bcoff[s]); + for (int i = 1; i < size; i++) + { + s++; + coff = coff.Add(this._Points[i].Multiply(bcoff[s])); + } + this._Coff[t] = coff; + } + } + return this._Coff; + } + + private T[] _Points; + private T[] _Coff; + } + + /// <summary> + /// Contains functions related to curves. + /// </summary> + public static class Curve + { + + /// <summary> + /// Contains the coffecients needed to evaluate bezier curves of certain orders. + /// </summary> + private static readonly List<double[]> _BezierCoffecients = new List<double[]>(); + + /// <summary> + /// Gets the bezier coffecients for the specified order. They are given as a matrix correlating the degree of + /// the parameter given to the curve and the control points. + /// </summary> + public static double[] GetBezierCoffecients(int Order) + { + if (Order < _BezierCoffecients.Count) + { + return _BezierCoffecients[Order]; + } + else + { + // Compute the coffecients based on the previous order + int psize = Order; + int size = (Order + 1); + double[] coff = new double[size * size]; + if (Order == 0) + { + coff[0] = 1; + } + else + { + double[] precoff = GetBezierCoffecients(Order - 1); + for (int x = 0; x < psize; x++) + { + for (int y = 0; y < psize; y++) + { + double cur = precoff[x + (y * psize)]; + coff[x + (y * size) + size] -= cur; + coff[x + (y * size) + size + 1] += cur; + coff[x + (y * size)] += cur; + } + } + } + _BezierCoffecients.Add(coff); + return coff; + } + } + } +} \ No newline at end of file diff --git a/Alunite/Math/Scalar.cs b/Alunite/Math/Scalar.cs new file mode 100644 index 0000000..876ba1a --- /dev/null +++ b/Alunite/Math/Scalar.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; + +using OpenTK; + +namespace Alunite +{ + /// <summary> + /// Represents a point or offset in one-dimensional space. + /// </summary> + public struct Scalar : IAdditive<Scalar, Scalar>, IMultiplicative<Scalar, Scalar> + { + public Scalar(double Value) + { + this.Value = Value; + } + + public static implicit operator double(Scalar Scalar) + { + return Scalar.Value; + } + + public static implicit operator Scalar(double Value) + { + return new Scalar(Value); + } + + public Scalar Add(Scalar Operand) + { + return this + Operand; + } + + public Scalar Subtract(Scalar Operand) + { + return this - Operand; + } + + public Scalar Multiply(Scalar Operand) + { + return this * Operand; + } + + public Scalar Divide(Scalar Operand) + { + return this / Operand; + } + + public override string ToString() + { + return this.Value.ToString(); + } + + public double Value; + } +} \ No newline at end of file diff --git a/Alunite/Math/Vector.cs b/Alunite/Math/Vector.cs index cf0642a..8ba6f84 100644 --- a/Alunite/Math/Vector.cs +++ b/Alunite/Math/Vector.cs @@ -1,182 +1,166 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in three-dimensional space. /// </summary> - public struct Vector + public struct Vector : IAdditive<Vector, Vector>, IMultiplicative<Vector, Scalar> { public Vector(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } public static implicit operator Vector3d(Vector Vector) { return new Vector3d(Vector.X, Vector.Y, Vector.Z); } public static explicit operator Vector3(Vector Vector) { return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); } - public static bool operator ==(Vector A, Vector B) + public Vector Add(Vector Operand) { - return A.X == B.X && A.Y == B.Y && A.Z == B.Z; + return new Vector(this.X + Operand.X, this.Y + Operand.Y, this.Z + Operand.Z); } - public static bool operator !=(Vector A, Vector B) + public Vector Subtract(Vector Operand) { - return A.X != B.X || A.Y != B.Y || A.Z != B.Z; + return new Vector(this.X - Operand.X, this.Y - Operand.Y, this.Z - Operand.Z); + } + + public Vector Multiply(Scalar Operand) + { + return new Vector(this.X * Operand, this.Y * Operand, this.Z * Operand); + } + + public Vector Divide(Scalar Operand) + { + return new Vector(this.X / Operand, this.Y / Operand, this.Z / Operand); } public static Vector operator +(Vector A, Vector B) { - return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); + return A.Add(B); } public static Vector operator -(Vector A, Vector B) { - return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); + return A.Subtract(B); } public static Vector operator *(Vector A, double Magnitude) { - return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); + return A.Multiply(Magnitude); } public static Vector operator -(Vector A) { return new Vector(-A.X, -A.Y, -A.Z); } public override string ToString() { return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); } - public override int GetHashCode() - { - int xhash = this.X.GetHashCode(); - int yhash = this.Y.GetHashCode(); - int zhash = this.Z.GetHashCode(); - return unchecked(xhash ^ (yhash + 0x1337BED5) ^ (zhash + 0x2B50CDF1) ^ (yhash << 3) ^ (yhash >> 3) ^ (zhash << 7) ^ (zhash >> 7)); - } - /// <summary> /// Gets if this vector is inside the specified sphere. /// </summary> public bool InSphere(Vector Center, double Radius) { return (this - Center).SquareLength < Radius * Radius; } /// <summary> /// Gets the cross product of two vectors. /// </summary> public static Vector Cross(Vector A, Vector B) { return new Vector( (A.Y * B.Z) - (A.Z * B.Y), (A.Z * B.X) - (A.X * B.Z), (A.X * B.Y) - (A.Y * B.X)); } - /// <summary> - /// Compares two vectors lexographically. - /// </summary> - public static bool Compare(Vector A, Vector B) - { - if (A.X > B.X) - return true; - if (A.X < B.X) - return false; - if (A.Y > B.Y) - return true; - if (A.Y < B.Y) - return false; - if (A.Z > B.Z) - return true; - return false; - } - /// <summary> /// Gets the outgoing ray of an object hitting a plane with the specified normal at the /// specified incoming ray. /// </summary> public static Vector Reflect(Vector Incoming, Vector Normal) { return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); } /// <summary> /// Multiplies each component of the vectors with the other's corresponding component. /// </summary> public static Vector Scale(Vector A, Vector B) { return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } /// <summary> /// Gets the dot product between two vectors. /// </summary> public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } /// <summary> /// Gets the length of the vector. /// </summary> public double Length { get { return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the length of the vector. /// </summary> public double SquareLength { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Normalizes the vector so its length is one but its direction is unchanged. /// </summary> public void Normalize() { double ilen = 1.0 / this.Length; this.X *= ilen; this.Y *= ilen; this.Z *= ilen; } /// <summary> /// Normalizes the specified vector. /// </summary> public static Vector Normalize(Vector A) { A.Normalize(); return A; } public double X; public double Y; public double Z; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 3031a2d..d145c1c 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,56 +1,29 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Transform testa = new Transform( - new Vector(1.0, 0.5, 0.3), - new Vector(1.0, 0.5, 0.3), - Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); - testa = testa.ApplyTo(testa.Inverse); - - // Set up a world - Physics fp = new Physics(); - Matter obj = fp.CreateLattice(fp.Create(new Particle<Substance>() - { - Substance = Substance.Default, - Mass = 1.0, - Position = new Vector(0.0, 0.0, 0.0), - Orientation = Quaternion.Identity, - Spin = AxisAngle.Identity - }), 2, 0.1); - - Matter earth = fp.Create(new Particle<Substance>() + Curve<Scalar> curve = new Curve<Scalar>(new Scalar[] { - Substance = Substance.Default, - Mass = 5.9742e24, - Position = new Vector(0.0, 0.0, -6.3675e6), - Orientation = Quaternion.Identity, - Spin = AxisAngle.Identity + 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 0.6, 0.2, 0.3, 0.4, 0.5 }); - - Matter world = obj; - - HostWindow hw = new HostWindow("Alunite", 640, 480); - hw.WindowState = WindowState.Maximized; - hw.Control = new Visualizer(fp, world); - hw.Run(60.0); + double val = curve[1.0]; } } } \ No newline at end of file
dzamkov/Alunite-old
83b89608cf03b2c17972c325ce829686b7e687f1
Organization
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index af1cf29..d44fa0e 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,77 +1,76 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Fast\BinaryMatter.cs" /> <Compile Include="Fast\Matter.cs" /> <Compile Include="Fast\ParticleMatter.cs" /> <Compile Include="Fast\Physics.cs" /> <Compile Include="Fast\Substance.cs" /> <Compile Include="Fast\TransformedMatter.cs" /> - <Compile Include="Filter.cs" /> - <Compile Include="MatchMatrix.cs" /> + <Compile Include="Data\Filter.cs" /> + <Compile Include="Data\MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> - <Compile Include="Quaternion.cs" /> - <Compile Include="Set.cs" /> - <Compile Include="Sink.cs" /> - <Compile Include="SphereTree.cs" /> - <Compile Include="Transform.cs" /> - <Compile Include="UsageSet.cs" /> - <Compile Include="Vector.cs" /> + <Compile Include="Math\Quaternion.cs" /> + <Compile Include="Data\Set.cs" /> + <Compile Include="Data\Sink.cs" /> + <Compile Include="Math\Transform.cs" /> + <Compile Include="Data\UsageSet.cs" /> + <Compile Include="Math\Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Filter.cs b/Alunite/Data/Filter.cs similarity index 100% rename from Alunite/Filter.cs rename to Alunite/Data/Filter.cs diff --git a/Alunite/MatchMatrix.cs b/Alunite/Data/MatchMatrix.cs similarity index 100% rename from Alunite/MatchMatrix.cs rename to Alunite/Data/MatchMatrix.cs diff --git a/Alunite/Set.cs b/Alunite/Data/Set.cs similarity index 100% rename from Alunite/Set.cs rename to Alunite/Data/Set.cs diff --git a/Alunite/Sink.cs b/Alunite/Data/Sink.cs similarity index 100% rename from Alunite/Sink.cs rename to Alunite/Data/Sink.cs diff --git a/Alunite/UsageSet.cs b/Alunite/Data/UsageSet.cs similarity index 100% rename from Alunite/UsageSet.cs rename to Alunite/Data/UsageSet.cs diff --git a/Alunite/Quaternion.cs b/Alunite/Math/Quaternion.cs similarity index 100% rename from Alunite/Quaternion.cs rename to Alunite/Math/Quaternion.cs diff --git a/Alunite/Transform.cs b/Alunite/Math/Transform.cs similarity index 100% rename from Alunite/Transform.cs rename to Alunite/Math/Transform.cs diff --git a/Alunite/Vector.cs b/Alunite/Math/Vector.cs similarity index 100% rename from Alunite/Vector.cs rename to Alunite/Math/Vector.cs diff --git a/Alunite/Program.cs b/Alunite/Program.cs index f2a8294..3031a2d 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,56 +1,56 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world Physics fp = new Physics(); Matter obj = fp.CreateLattice(fp.Create(new Particle<Substance>() { Substance = Substance.Default, Mass = 1.0, Position = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity - }), 3, 0.1); + }), 2, 0.1); Matter earth = fp.Create(new Particle<Substance>() { Substance = Substance.Default, Mass = 5.9742e24, Position = new Vector(0.0, 0.0, -6.3675e6), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity }); Matter world = obj; HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(fp, world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/SphereTree.cs b/Alunite/SphereTree.cs deleted file mode 100644 index 01370b0..0000000 --- a/Alunite/SphereTree.cs +++ /dev/null @@ -1,192 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Alunite -{ - /// <summary> - /// Partions and organizes spherical nodes containing data into a bounding volume hierarchy. Note that this object does not contain - /// an actual tree, just the properties of the tree's its nodes make. - /// </summary> - public abstract class SphereTree<TNode> - { - /// <summary> - /// Gets the position and radius of a sphere that encloses two other spheres. - /// </summary> - public static void Enclose(Vector PosA, double RadA, Vector PosB, double RadB, out Vector Pos, out double Rad) - { - Vector dir = PosB - PosA; - double dis = dir.Length; - dir *= 1.0 / dis; - Rad = (dis + RadA + RadB) * 0.5; - Pos = PosA + dir * (Rad - RadA); - } - - /// <summary> - /// Gets the position and radius of the specified node. - /// </summary> - public abstract void GetBound(TNode Node, out Vector Position, out double Radius); - - /// <summary> - /// Gets the subnodes for a node, if the node is a compound node. - /// </summary> - public abstract bool GetSubnodes(TNode Node, ref TNode A, ref TNode B); - - /// <summary> - /// Creates a compound node containing the two specified subnodes. - /// </summary> - public abstract TNode CreateCompound(TNode A, TNode B); - - /// <summary> - /// Creates a well-balanced tree containing the given nodes. - /// </summary> - public TNode Create(IEnumerable<TNode> Nodes) - { - TNode cur = default(TNode); - IEnumerator<TNode> e = Nodes.GetEnumerator(); - if (e.MoveNext()) - { - cur = e.Current; - while (e.MoveNext()) - { - cur = this.Insert(cur, e.Current); - } - } - return cur; - } - - /// <summary> - /// Inserts node B into tree A leaving them well-balanced. - /// </summary> - public TNode Insert(TNode A, TNode B) - { - TNode suba = default(TNode); - TNode subb = default(TNode); - if (!this.GetSubnodes(A, ref suba, ref subb)) - { - return this.CreateCompound(A, B); - } - - Vector possuba; double radsuba; - Vector possubb; double radsubb; - Vector posb; double radb; - Vector posa; double rada; - this.GetBound(suba, out possuba, out radsuba); - this.GetBound(subb, out possubb, out radsubb); - this.GetBound(A, out posa, out rada); - this.GetBound(B, out posb, out radb); - - double subdis = rada * 2.0; - double subadis = (possuba - posb).Length + radsuba + radb; - double subbdis = (possubb - posb).Length + radsubb + radb; - if (subdis < subadis) - { - if (subdis < subbdis) - { - return this.CreateCompound(A, B); - } - else - { - return this.CreateCompound(this.Insert(subb, B), suba); - } - } - else - { - if (subadis < subbdis) - { - return this.CreateCompound(this.Insert(suba, B), subb); - } - else - { - return this.CreateCompound(this.Insert(subb, B), suba); - } - } - } - } - - /// <summary> - /// A sphere tree that automatically creates and maintains compound nodes which track position, radius and subnodes. - /// </summary> - public abstract class SimpleSphereTree<TLeaf> : SphereTree<SimpleSphereTreeNode<TLeaf>> - { - /// <summary> - /// Gets the bounding sphere for a leaf. - /// </summary> - public abstract void GetBound(TLeaf Leaf, out Vector Position, out double Radius); - - /// <summary> - /// Creates a leaf node for a leaf. - /// </summary> - public SimpleSphereTreeNode<TLeaf> Create(TLeaf Leaf) - { - return new SimpleSphereTreeNode<TLeaf>._Leaf() - { - Leaf = Leaf - }; - } - - public sealed override void GetBound(SimpleSphereTreeNode<TLeaf> Node, out Vector Position, out double Radius) - { - Node._GetBound(this, out Position, out Radius); - } - - public sealed override bool GetSubnodes(SimpleSphereTreeNode<TLeaf> Node, ref SimpleSphereTreeNode<TLeaf> A, ref SimpleSphereTreeNode<TLeaf> B) - { - var c = Node as SimpleSphereTreeNode<TLeaf>._Compound; - if (c != null) - { - A = c.A; - B = c.B; - return true; - } - return false; - } - - public sealed override SimpleSphereTreeNode<TLeaf> CreateCompound(SimpleSphereTreeNode<TLeaf> A, SimpleSphereTreeNode<TLeaf> B) - { - Vector posa; double rada; this.GetBound(A, out posa, out rada); - Vector posb; double radb; this.GetBound(B, out posb, out radb); - Vector pos; double rad; Enclose(posa, rada, posb, radb, out pos, out rad); - - - return new SimpleSphereTreeNode<TLeaf>._Compound() - { - A = A, - B = B, - Radius = rad, - Position = pos - }; - } - } - - /// <summary> - /// A node for a SimpleSphereTree. - /// </summary> - public abstract class SimpleSphereTreeNode<TLeaf> - { - internal abstract void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius); - - internal class _Leaf : SimpleSphereTreeNode<TLeaf> - { - internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) - { - Tree.GetBound(this.Leaf, out Position, out Radius); - } - - public TLeaf Leaf; - } - - internal class _Compound : SimpleSphereTreeNode<TLeaf> - { - internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) - { - Position = this.Position; - Radius = this.Radius; - } - - public Vector Position; - public double Radius; - public SimpleSphereTreeNode<TLeaf> A; - public SimpleSphereTreeNode<TLeaf> B; - } - } -} \ No newline at end of file
dzamkov/Alunite-old
1699cbbef720290462a69d2260678752e72206e9
Sets, sinks and filter. Probably won't be all too useful
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index e402bd9..af1cf29 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,74 +1,77 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Fast\BinaryMatter.cs" /> <Compile Include="Fast\Matter.cs" /> <Compile Include="Fast\ParticleMatter.cs" /> <Compile Include="Fast\Physics.cs" /> <Compile Include="Fast\Substance.cs" /> <Compile Include="Fast\TransformedMatter.cs" /> + <Compile Include="Filter.cs" /> <Compile Include="MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> + <Compile Include="Set.cs" /> + <Compile Include="Sink.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="Transform.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Fast/BinaryMatter.cs b/Alunite/Fast/BinaryMatter.cs index 6a8b76d..e669bbb 100644 --- a/Alunite/Fast/BinaryMatter.cs +++ b/Alunite/Fast/BinaryMatter.cs @@ -1,154 +1,154 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// Matter created by the composition of a untransformed and a transformed matter. /// </summary> public class BinaryMatter : Matter { public BinaryMatter(Matter A, Matter B, Transform AToB) { this._A = A; this._B = B; this._AToB = AToB; } /// <summary> /// Gets the untransformed part of this matter. /// </summary> public Matter A { get { return this._A; } } /// <summary> /// Gets the source of the transformed part of this matter. /// </summary> public Matter B { get { return this._B; } } /// <summary> /// Gets the transformed part of this matter with the transform applied. /// </summary> public TransformedMatter BFull { get { return new TransformedMatter(this._B, this._AToB); } } /// <summary> /// Gets the transform from A's (and this matter's) coordinate space to B's coordinate space. /// </summary> public Transform AToB { get { return this._AToB; } } public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) { double amass, bmass; Vector acen, bcen; double aext, bext; this._A.GetMassSummary(Physics, out amass, out acen, out aext); this._B.GetMassSummary(Physics, out bmass, out bcen, out bext); bcen = this._AToB.ApplyToOffset(bcen); Mass = amass + bmass; CenterOfMass = acen * (amass / Mass) + bcen * (bmass / Mass); double alen = (acen - CenterOfMass).Length + aext; double blen = (bcen - CenterOfMass).Length + bext; Extent = Math.Max(alen, blen); } public override Matter Update(Physics Physics, Matter Environment, double Time) { Matter na = this.A.Update(Physics, Physics.Combine(this.B.Apply(Physics, this.AToB), Environment), Time); Matter nb = this.B.Update(Physics, Physics.Combine(this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); return Physics.Combine(na, nb.Apply(Physics, this.AToB.Update(Time))); } public override void OutputUsed(HashSet<Matter> Elements) { Elements.Add(this); this._A.OutputUsed(Elements); this._B.OutputUsed(Elements); } - public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) { - this._A.OutputParticles(Transform, Particles); - this._B.OutputParticles(this._AToB.Apply(Transform), Particles); + this._A.OutputParticles(Physics, Transform, Particles); + this._B.OutputParticles(Physics, this._AToB.Apply(Transform), Particles); } public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); return agrav + bgrav; } private Matter _A; private Matter _B; private Transform _AToB; } /// <summary> /// Binary matter with many properties memoized, allowing it to perform faster at the cost of using more memory. /// </summary> public class MemoizedBinaryMatter : BinaryMatter { public MemoizedBinaryMatter(Matter A, Matter B, Transform AToB) : base(A, B, AToB) { this._Mass = double.NaN; } public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) { if (double.IsNaN(this._Mass)) { base.GetMassSummary(Physics, out this._Mass, out this._CenterOfMass, out this._Extent); } Mass = this._Mass; CenterOfMass = this._CenterOfMass; Extent = this._Extent; } public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { double mass; Vector com; double ext; this.GetMassSummary(Physics, out mass, out com, out ext); Vector offset = Position - com; double offsetlen = com.Length; double rat = (mass * ext) / (offsetlen * offsetlen); if (rat >= RecurseThreshold) { return base.GetGravity(Physics, Position, Mass, RecurseThreshold); } else { return offset * (Physics.GetGravityStrength(mass, Mass, offsetlen) / offsetlen); } } private double _Mass; private Vector _CenterOfMass; private double _Extent; } } \ No newline at end of file diff --git a/Alunite/Fast/Matter.cs b/Alunite/Fast/Matter.cs index aa5dc28..070d0b9 100644 --- a/Alunite/Fast/Matter.cs +++ b/Alunite/Fast/Matter.cs @@ -1,89 +1,86 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class Matter : IMatter { public Matter() { } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<Matter> used = new HashSet<Matter>(); this.OutputUsed(used); return used.Count; } } - /// <summary> - /// Gets the position of all the particles in this matter, for debug purposes. - /// </summary> - public IEnumerable<Particle<Substance>> Particles - { - get - { - List<Particle<Substance>> parts = new List<Particle<Substance>>(); - this.OutputParticles(Transform.Identity, parts); - return parts; - } - } - /// <summary> /// Applies a transform to this matter. /// </summary> public virtual Matter Apply(Physics Physics, Transform Transform) { return new TransformedMatter(this, Transform); } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public abstract Matter Update(Physics Physics, Matter Environment, double Time); /// <summary> /// Gets a summary of the location and density of mass inside the matter by getting the total mass, center of mass, /// and extent (distance from the center of mass to the farthest piece of matter). /// </summary> public abstract void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent); /// <summary> /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. /// </summary> /// <param name="RecurseThreshold">The ratio of (mass * extent) / (distance ^ 2) a piece of matter will have to have in order to have its /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> public virtual Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { return Physics.GetGravity(Physics.GetMass(this), Position, Mass); } /// <summary> /// Recursively outputs all matter used in the definition of this matter, including this matter itself. /// </summary> public virtual void OutputUsed(HashSet<Matter> Elements) { Elements.Add(this); } /// <summary> /// Outputs all particles defined in this matter, after applying the specified transform. /// </summary> - public virtual void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + public virtual void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) { } + + /// <summary> + /// Gets all particles defined in this matter. + /// </summary> + public IEnumerable<Particle<Substance>> GetParticles(Physics Physics) + { + List<Particle<Substance>> parts = new List<Particle<Substance>>(); + this.OutputParticles(Physics, Transform.Identity, parts); + return parts; + } } } \ No newline at end of file diff --git a/Alunite/Fast/ParticleMatter.cs b/Alunite/Fast/ParticleMatter.cs index a4c184d..7150981 100644 --- a/Alunite/Fast/ParticleMatter.cs +++ b/Alunite/Fast/ParticleMatter.cs @@ -1,85 +1,85 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// Matter containing a single, untransformed particle. /// </summary> public class ParticleMatter : Matter { public ParticleMatter(Substance Substance, double Mass, AxisAngle Spin) { this._Substance = Substance; this._Mass = Mass; this._Spin = Spin; } /// <summary> /// Gets the substance of the particle represented by this matter. /// </summary> public Substance Substance { get { return this._Substance; } } /// <summary> /// Gets the untransformed spin of the particle represented by this matter. /// </summary> public AxisAngle Spin { get { return this._Spin; } } - public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) { Particles.Add(new Particle<Substance>() { Mass = this._Mass, Spin = this._Spin.Apply(Transform.Rotation), Substance = this._Substance, Orientation = Transform.Rotation, Position = Transform.Offset, Velocity = Transform.VelocityOffset }); } public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this._Mass; CenterOfMass = new Vector(0.0, 0.0, 0.0); Extent = 0.0; } public override Matter Update(Physics Physics, Matter Environment, double Time) { Particle<Substance> part = new Particle<Substance>() { Mass = this._Mass, Spin = this._Spin, Substance = this._Substance, Orientation = Quaternion.Identity, Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0) }; this.Substance.Update(Physics, Environment, Time, ref part); return Physics.Create(part); } public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { return Physics.GetGravity(this._Mass, Position, Mass); } private Substance _Substance; private double _Mass; private AxisAngle _Spin; } } \ No newline at end of file diff --git a/Alunite/Fast/Physics.cs b/Alunite/Fast/Physics.cs index e13cdba..7a08b6c 100644 --- a/Alunite/Fast/Physics.cs +++ b/Alunite/Fast/Physics.cs @@ -1,190 +1,190 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class Physics : IParticlePhysics<Matter, Substance>, IGravitationalPhysics<Matter> { public Physics(double G) { this._G = G; } public Physics() : this(6.67428e-11) { } /// <summary> /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. /// </summary> public double G { get { return this._G; } } public Matter Create(Particle<Substance> Particle) { return new TransformedMatter( new ParticleMatter(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); } /// <summary> /// Creates a lattice of the specified object. The amount of items in the lattice is equal to (2 ^ (Log2Size * 3)). /// </summary> public Matter CreateLattice(Matter Object, int Log2Size, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, Log2Size - 1); // Extract transform TransformedMatter trans = Object as TransformedMatter; if (trans != null) { Object = trans.Source; return this._CreateLattice(Object, Log2Size, Spacing).Apply(this, trans.Transform); } else { return this._CreateLattice(Object, Log2Size, Spacing); } } private Matter _CreateLattice(Matter Object, int Log2Size, double MajorSpacing) { // Create a lattice with major spacing if (Log2Size <= 0) { return Object; } if (Log2Size > 1) { Object = this._CreateLattice(Object, Log2Size - 1, MajorSpacing * 0.5); } BinaryMatter a = this.QuickCombine(Object, Object, new Transform(MajorSpacing, 0.0, 0.0)); BinaryMatter b = this.QuickCombine(a, a, new Transform(0.0, MajorSpacing, 0.0)); BinaryMatter c = this.QuickCombine(b, b, new Transform(0.0, 0.0, MajorSpacing)); return c; } public Matter Apply(Matter Matter, Transform Transform) { if (Matter != null) { return Matter.Apply(this, Transform); } else { return null; } } public Matter Update(Matter Matter, Matter Environment, double Time) { return Matter.Update(this, Environment, Time); } public Matter Compose(IEnumerable<Matter> Elements) { Matter cur = this.Null; foreach (Matter matter in Elements) { cur = this.Combine(cur, matter); } return cur; } /// <summary> /// Combines two pieces of matter in a similar manner to Compose. /// </summary> public Matter Combine(Matter A, Matter B) { if (A == null) { return B; } if (B == null) { return A; } TransformedMatter atrans = A as TransformedMatter; TransformedMatter btrans = B as TransformedMatter; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } if (atrans != null) { return new MemoizedBinaryMatter(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(this, atrans.Transform); } else { return new MemoizedBinaryMatter(A, B, atob); } } /// <summary> - /// Quickly combines two pieces of untransformed matter. + /// Quickly combines two nonnull pieces of untransformed matter. /// </summary> public BinaryMatter QuickCombine(Matter A, Matter B, Transform AToB) { return new MemoizedBinaryMatter(A, B, AToB); } public Matter Null { get { return null; } } /// <summary> /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given /// offset in meters. /// </summary> public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) { double sqrlen = Offset.SquareLength; return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); } /// <summary> /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. /// </summary> public double GetGravityStrength(double MassA, double MassB, double Distance) { return -this._G * (MassA + MassB) / (Distance * Distance); } public Vector GetGravity(Matter Environment, Vector Position, double Mass) { return Environment.GetGravity(this, Position, Mass, 0.0); } public double GetMass(Matter Matter) { double mass; Vector com; double extent; Matter.GetMassSummary(this, out mass, out com, out extent); return mass; } private double _G; } } \ No newline at end of file diff --git a/Alunite/Fast/Substance.cs b/Alunite/Fast/Substance.cs index 0355897..31045eb 100644 --- a/Alunite/Fast/Substance.cs +++ b/Alunite/Fast/Substance.cs @@ -1,40 +1,50 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// A substance in a fast physics system. /// </summary> public class Substance : IAutoSubstance<Physics, Matter, Substance> { private Substance() { } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly Substance Default = new Substance(); public void Update(Physics Physics, Matter Environment, double Time, ref Particle<Substance> Particle) { - Particle.Velocity += Environment.GetGravity(Physics, new Vector(0.0, 0.0, 0.0), Particle.Mass, Physics.G * 1.0e15) * (Time / Particle.Mass); + Vector force = new Vector(); + force += Environment.GetGravity(Physics, new Vector(0.0, 0.0, 0.0), Particle.Mass, Physics.G * 1.0e15); + + foreach (Particle<Substance> part in Environment.GetParticles(Physics)) + { + Vector off = part.Position - Particle.Position; + double offlen = off.Length; + force += off * (-0.01 / (offlen * offlen * offlen)); + } + + Particle.Velocity += force * (Time / Particle.Mass); Particle.Update(Time); } public MatterDisparity GetDisparity( Physics Physics, Matter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } } } \ No newline at end of file diff --git a/Alunite/Fast/TransformedMatter.cs b/Alunite/Fast/TransformedMatter.cs index 2174db8..9ef45fe 100644 --- a/Alunite/Fast/TransformedMatter.cs +++ b/Alunite/Fast/TransformedMatter.cs @@ -1,75 +1,75 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// Matter created by transforming other "Source" matter. /// </summary> public class TransformedMatter : Matter { public TransformedMatter(Matter Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } /// <summary> /// Gets the source matter for this transformed matter. /// </summary> public Matter Source { get { return this._Source; } } /// <summary> /// Gets the transform applied by this transformed matter. /// </summary> public Transform Transform { get { return this._Transform; } } public override Matter Apply(Physics Physics, Transform Transform) { return new TransformedMatter(this.Source, this.Transform.Apply(Transform)); } public override Matter Update(Physics Physics, Matter Environment, double Time) { return Physics.Apply(this.Source.Update(Physics, Physics.Apply(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); } public override void OutputUsed(HashSet<Matter> Elements) { Elements.Add(this); this._Source.OutputUsed(Elements); } - public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + public override void OutputParticles(Physics Physics, Transform Transform, List<Particle<Substance>> Particles) { - this._Source.OutputParticles(this._Transform.Apply(Transform), Particles); + this._Source.OutputParticles(Physics, this._Transform.Apply(Transform), Particles); } public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) { this._Source.GetMassSummary(Physics, out Mass, out CenterOfMass, out Extent); CenterOfMass = this._Transform.ApplyToOffset(CenterOfMass); } public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { return this._Transform.ApplyToDirection(this._Source.GetGravity(Physics, this._Transform.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); } private Matter _Source; private Transform _Transform; } } \ No newline at end of file diff --git a/Alunite/Filter.cs b/Alunite/Filter.cs new file mode 100644 index 0000000..38ae6fa --- /dev/null +++ b/Alunite/Filter.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// An object that determines which objects of a common type may pass. + /// </summary> + /// <typeparam name="T">The type of the filtered objects.</typeparam> + public abstract class Filter<T> + { + /// <summary> + /// Gets wether the specified item is allowed to pass through the filter. + /// </summary> + public abstract bool Allow(T Item); + } +} \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 4fb0509..f2a8294 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,56 +1,56 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world Physics fp = new Physics(); Matter obj = fp.CreateLattice(fp.Create(new Particle<Substance>() { Substance = Substance.Default, Mass = 1.0, Position = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity - }), 2, 0.1); + }), 3, 0.1); Matter earth = fp.Create(new Particle<Substance>() { Substance = Substance.Default, Mass = 5.9742e24, Position = new Vector(0.0, 0.0, -6.3675e6), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity }); - Matter world = fp.Combine(obj, earth); + Matter world = obj; HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(fp, world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Set.cs b/Alunite/Set.cs new file mode 100644 index 0000000..a564637 --- /dev/null +++ b/Alunite/Set.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A possibly-infinite collection of items. + /// </summary> + public abstract class Set<T> + { + /// <summary> + /// Pushes all items in this set to the specified sink. + /// </summary> + public abstract void Push<TSink>(TSink Sink) + where TSink : Sink<T>; + + /// <summary> + /// Gets all items in this set + /// </summary> + public virtual IEnumerable<T> Pull + { + get + { + List<T> li = new List<T>(); + this.Push<ListSink<T>>(new ListSink<T>(li)); + return li; + } + } + + /// <summary> + /// Creates a set with the given filter applied. + /// </summary> + public virtual Set<T> Filter<TFilter>(TFilter Filter) + where TFilter : Filter<T> + { + return new FilteredSet<T, TFilter>(this, Filter); + } + } + + /// <summary> + /// A set defined with a collection. + /// </summary> + public class StaticSet<T> : Set<T> + { + public StaticSet(IEnumerable<T> Source) + { + this._Source = Source; + } + + public override void Push<TSink>(TSink Sink) + { + Sink.Push(this._Source); + } + + public override IEnumerable<T> Pull + { + get + { + return this._Source; + } + } + + private IEnumerable<T> _Source; + } + + /// <summary> + /// A set based on a source set, with a filter applied. + /// </summary> + public class FilteredSet<T, TFilter> : Set<T> + where TFilter : Filter<T> + { + public FilteredSet(Set<T> Source, TFilter Filter) + { + this._Source = Source; + this._Filter = Filter; + } + + public override void Push<TSink>(TSink Sink) + { + this._Source.Push<FilteredSink<T, TFilter, TSink>>(new FilteredSink<T, TFilter, TSink>(Sink, this._Filter)); + } + + private Set<T> _Source; + private TFilter _Filter; + } +} \ No newline at end of file diff --git a/Alunite/Sink.cs b/Alunite/Sink.cs new file mode 100644 index 0000000..5ddeb30 --- /dev/null +++ b/Alunite/Sink.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// An object to which an unbounded amount of items can be pushed. + /// </summary> + /// <typeparam name="T">The type of items this sink can receive.</typeparam> + public abstract class Sink<T> + { + /// <summary> + /// Pushes, or gives, an item to this sink. + /// </summary> + public abstract void Push(T Item); + + /// <summary> + /// Pushes an ordered collection of items to the sink. + /// </summary> + public void Push(IEnumerable<T> Items) + { + foreach (T item in Items) + { + this.Push(item); + } + } + + /// <summary> + /// Creates a sink where all pushed items are appended to a list. + /// </summary> + public static ListSink<T> ToList(List<T> List) + { + return new ListSink<T>(List); + } + } + + /// <summary> + /// A sink where all pushed items are appeneded to a list. + /// </summary> + public sealed class ListSink<T> : Sink<T> + { + public ListSink(List<T> Target) + { + this._Target = Target; + } + + /// <summary> + /// Gets the target list of this sink. + /// </summary> + public List<T> Target + { + get + { + return this._Target; + } + } + + public override void Push(T Item) + { + this._Target.Add(Item); + } + + private List<T> _Target; + } + + /// <summary> + /// A sink that filters pushed items before passing them on to another sink. + /// </summary> + public sealed class FilteredSink<T, TFilter, TTarget> : Sink<T> + where TFilter : Filter<T> + where TTarget : Sink<T> + { + public FilteredSink(TTarget Target, TFilter Filter) + { + this._Target = Target; + this._Filter = Filter; + } + + public override void Push(T Item) + { + if (this._Filter.Allow(Item)) + { + this._Target.Push(Item); + } + } + + private TTarget _Target; + private TFilter _Filter; + } +} \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs index 9232787..3758cb3 100644 --- a/Alunite/Transform.cs +++ b/Alunite/Transform.cs @@ -1,108 +1,127 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } public Transform(Vector Offset) { this.Offset = Offset; this.VelocityOffset = new Vector(0.0, 0.0, 0.0); this.Rotation = Quaternion.Identity; } public Transform(double X, double Y, double Z) : this(new Vector(X, Y, Z)) { } + public Transform(Quaternion Rotation) + { + this.Offset = new Vector(0.0, 0.0, 0.0); + this.VelocityOffset = new Vector(0.0, 0.0, 0.0); + this.Rotation = Rotation; + } + + public Transform(AxisAngle Rotation) + : this((Quaternion)Rotation) + { + + } + + public Transform(Vector Axis, double Angle) + : this(new AxisAngle(Axis, Angle)) + { + + } + /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies this transform to a direction vector. /// </summary> public Vector ApplyToDirection(Vector Dir) { return this.Rotation.Rotate(Dir); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } /// <summary> /// Updates the state of this transform after the given amount of time in seconds. /// </summary> public Transform Update(double Time) { return new Transform(this.Offset + this.VelocityOffset * Time, this.VelocityOffset, this.Rotation); } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Vector.cs b/Alunite/Vector.cs index cb2ed10..cf0642a 100644 --- a/Alunite/Vector.cs +++ b/Alunite/Vector.cs @@ -1,174 +1,182 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in three-dimensional space. /// </summary> public struct Vector { public Vector(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } public static implicit operator Vector3d(Vector Vector) { return new Vector3d(Vector.X, Vector.Y, Vector.Z); } public static explicit operator Vector3(Vector Vector) { return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); } public static bool operator ==(Vector A, Vector B) { return A.X == B.X && A.Y == B.Y && A.Z == B.Z; } public static bool operator !=(Vector A, Vector B) { return A.X != B.X || A.Y != B.Y || A.Z != B.Z; } public static Vector operator +(Vector A, Vector B) { return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vector operator -(Vector A, Vector B) { return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vector operator *(Vector A, double Magnitude) { return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); } public static Vector operator -(Vector A) { return new Vector(-A.X, -A.Y, -A.Z); } public override string ToString() { return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); } public override int GetHashCode() { int xhash = this.X.GetHashCode(); int yhash = this.Y.GetHashCode(); int zhash = this.Z.GetHashCode(); return unchecked(xhash ^ (yhash + 0x1337BED5) ^ (zhash + 0x2B50CDF1) ^ (yhash << 3) ^ (yhash >> 3) ^ (zhash << 7) ^ (zhash >> 7)); } + /// <summary> + /// Gets if this vector is inside the specified sphere. + /// </summary> + public bool InSphere(Vector Center, double Radius) + { + return (this - Center).SquareLength < Radius * Radius; + } + /// <summary> /// Gets the cross product of two vectors. /// </summary> public static Vector Cross(Vector A, Vector B) { return new Vector( (A.Y * B.Z) - (A.Z * B.Y), (A.Z * B.X) - (A.X * B.Z), (A.X * B.Y) - (A.Y * B.X)); } /// <summary> /// Compares two vectors lexographically. /// </summary> public static bool Compare(Vector A, Vector B) { if (A.X > B.X) return true; if (A.X < B.X) return false; if (A.Y > B.Y) return true; if (A.Y < B.Y) return false; if (A.Z > B.Z) return true; return false; } /// <summary> /// Gets the outgoing ray of an object hitting a plane with the specified normal at the /// specified incoming ray. /// </summary> public static Vector Reflect(Vector Incoming, Vector Normal) { return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); } /// <summary> /// Multiplies each component of the vectors with the other's corresponding component. /// </summary> public static Vector Scale(Vector A, Vector B) { return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } /// <summary> /// Gets the dot product between two vectors. /// </summary> public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } /// <summary> /// Gets the length of the vector. /// </summary> public double Length { get { return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the length of the vector. /// </summary> public double SquareLength { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Normalizes the vector so its length is one but its direction is unchanged. /// </summary> public void Normalize() { double ilen = 1.0 / this.Length; this.X *= ilen; this.Y *= ilen; this.Z *= ilen; } /// <summary> /// Normalizes the specified vector. /// </summary> public static Vector Normalize(Vector A) { A.Normalize(); return A; } public double X; public double Y; public double Z; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 59dec8c..53430a7 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,64 +1,64 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; using Alunite.Fast; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Physics Physics, Matter World) { this._Physics = Physics; this._World = World; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); - foreach (Particle<Substance> part in this._World.Particles) + foreach (Particle<Substance> part in this._World.GetParticles(this._Physics)) { GL.Vertex3(part.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { { Physics phys = this._Physics; this._World = phys.Update(this._World, phys.Null, Time * 0.1); } this._Time += Time * 0.2; } private Physics _Physics; private Matter _World; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
541ee92bae7882717876a8f9f89febf2ebee72e1
Restored original speed
diff --git a/Alunite/Fast/BinaryMatter.cs b/Alunite/Fast/BinaryMatter.cs index 1d0fbd1..6a8b76d 100644 --- a/Alunite/Fast/BinaryMatter.cs +++ b/Alunite/Fast/BinaryMatter.cs @@ -1,111 +1,154 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// Matter created by the composition of a untransformed and a transformed matter. /// </summary> public class BinaryMatter : Matter { public BinaryMatter(Matter A, Matter B, Transform AToB) { this._A = A; this._B = B; this._AToB = AToB; } /// <summary> /// Gets the untransformed part of this matter. /// </summary> public Matter A { get { return this._A; } } /// <summary> /// Gets the source of the transformed part of this matter. /// </summary> public Matter B { get { return this._B; } } /// <summary> /// Gets the transformed part of this matter with the transform applied. /// </summary> public TransformedMatter BFull { get { return new TransformedMatter(this._B, this._AToB); } } /// <summary> /// Gets the transform from A's (and this matter's) coordinate space to B's coordinate space. /// </summary> public Transform AToB { get { return this._AToB; } } public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) { double amass, bmass; Vector acen, bcen; double aext, bext; this._A.GetMassSummary(Physics, out amass, out acen, out aext); this._B.GetMassSummary(Physics, out bmass, out bcen, out bext); bcen = this._AToB.ApplyToOffset(bcen); Mass = amass + bmass; CenterOfMass = acen * (amass / Mass) + bcen * (bmass / Mass); double alen = (acen - CenterOfMass).Length + aext; double blen = (bcen - CenterOfMass).Length + bext; Extent = Math.Max(alen, blen); } public override Matter Update(Physics Physics, Matter Environment, double Time) { Matter na = this.A.Update(Physics, Physics.Combine(this.B.Apply(Physics, this.AToB), Environment), Time); Matter nb = this.B.Update(Physics, Physics.Combine(this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); return Physics.Combine(na, nb.Apply(Physics, this.AToB.Update(Time))); } public override void OutputUsed(HashSet<Matter> Elements) { Elements.Add(this); this._A.OutputUsed(Elements); this._B.OutputUsed(Elements); } public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) { this._A.OutputParticles(Transform, Particles); this._B.OutputParticles(this._AToB.Apply(Transform), Particles); } public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) { Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); return agrav + bgrav; } private Matter _A; private Matter _B; private Transform _AToB; } + + /// <summary> + /// Binary matter with many properties memoized, allowing it to perform faster at the cost of using more memory. + /// </summary> + public class MemoizedBinaryMatter : BinaryMatter + { + public MemoizedBinaryMatter(Matter A, Matter B, Transform AToB) + : base(A, B, AToB) + { + this._Mass = double.NaN; + } + + public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) + { + if (double.IsNaN(this._Mass)) + { + base.GetMassSummary(Physics, out this._Mass, out this._CenterOfMass, out this._Extent); + } + Mass = this._Mass; + CenterOfMass = this._CenterOfMass; + Extent = this._Extent; + } + + public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) + { + double mass; Vector com; double ext; this.GetMassSummary(Physics, out mass, out com, out ext); + Vector offset = Position - com; + double offsetlen = com.Length; + double rat = (mass * ext) / (offsetlen * offsetlen); + if (rat >= RecurseThreshold) + { + return base.GetGravity(Physics, Position, Mass, RecurseThreshold); + } + else + { + return offset * (Physics.GetGravityStrength(mass, Mass, offsetlen) / offsetlen); + } + } + + private double _Mass; + private Vector _CenterOfMass; + private double _Extent; + } } \ No newline at end of file diff --git a/Alunite/Fast/Physics.cs b/Alunite/Fast/Physics.cs index 6027f47..e13cdba 100644 --- a/Alunite/Fast/Physics.cs +++ b/Alunite/Fast/Physics.cs @@ -1,190 +1,190 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite.Fast { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class Physics : IParticlePhysics<Matter, Substance>, IGravitationalPhysics<Matter> { public Physics(double G) { this._G = G; } public Physics() : this(6.67428e-11) { } /// <summary> /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. /// </summary> public double G { get { return this._G; } } public Matter Create(Particle<Substance> Particle) { return new TransformedMatter( new ParticleMatter(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); } /// <summary> /// Creates a lattice of the specified object. The amount of items in the lattice is equal to (2 ^ (Log2Size * 3)). /// </summary> public Matter CreateLattice(Matter Object, int Log2Size, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, Log2Size - 1); // Extract transform TransformedMatter trans = Object as TransformedMatter; if (trans != null) { Object = trans.Source; return this._CreateLattice(Object, Log2Size, Spacing).Apply(this, trans.Transform); } else { return this._CreateLattice(Object, Log2Size, Spacing); } } private Matter _CreateLattice(Matter Object, int Log2Size, double MajorSpacing) { // Create a lattice with major spacing if (Log2Size <= 0) { return Object; } if (Log2Size > 1) { Object = this._CreateLattice(Object, Log2Size - 1, MajorSpacing * 0.5); } BinaryMatter a = this.QuickCombine(Object, Object, new Transform(MajorSpacing, 0.0, 0.0)); BinaryMatter b = this.QuickCombine(a, a, new Transform(0.0, MajorSpacing, 0.0)); BinaryMatter c = this.QuickCombine(b, b, new Transform(0.0, 0.0, MajorSpacing)); return c; } public Matter Apply(Matter Matter, Transform Transform) { if (Matter != null) { return Matter.Apply(this, Transform); } else { return null; } } public Matter Update(Matter Matter, Matter Environment, double Time) { return Matter.Update(this, Environment, Time); } public Matter Compose(IEnumerable<Matter> Elements) { Matter cur = this.Null; foreach (Matter matter in Elements) { cur = this.Combine(cur, matter); } return cur; } /// <summary> /// Combines two pieces of matter in a similar manner to Compose. /// </summary> public Matter Combine(Matter A, Matter B) { if (A == null) { return B; } if (B == null) { return A; } TransformedMatter atrans = A as TransformedMatter; TransformedMatter btrans = B as TransformedMatter; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } if (atrans != null) { - return new BinaryMatter(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(this, atrans.Transform); + return new MemoizedBinaryMatter(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(this, atrans.Transform); } else { - return new BinaryMatter(A, B, atob); + return new MemoizedBinaryMatter(A, B, atob); } } /// <summary> /// Quickly combines two pieces of untransformed matter. /// </summary> public BinaryMatter QuickCombine(Matter A, Matter B, Transform AToB) { - return new BinaryMatter(A, B, AToB); + return new MemoizedBinaryMatter(A, B, AToB); } public Matter Null { get { return null; } } /// <summary> /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given /// offset in meters. /// </summary> public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) { double sqrlen = Offset.SquareLength; return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); } /// <summary> /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. /// </summary> public double GetGravityStrength(double MassA, double MassB, double Distance) { return -this._G * (MassA + MassB) / (Distance * Distance); } public Vector GetGravity(Matter Environment, Vector Position, double Mass) { return Environment.GetGravity(this, Position, Mass, 0.0); } public double GetMass(Matter Matter) { double mass; Vector com; double extent; Matter.GetMassSummary(this, out mass, out com, out extent); return mass; } private double _G; } } \ No newline at end of file
dzamkov/Alunite-old
825fda266df2b872e496549443a512a727093f9a
Better organization
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index d71445f..e402bd9 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,71 +1,74 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> - <Compile Include="FastPhysics.cs" /> - <Compile Include="FastPhysicsMatter.cs" /> - <Compile Include="FastPhysicsSubstance.cs" /> + <Compile Include="Fast\BinaryMatter.cs" /> + <Compile Include="Fast\Matter.cs" /> + <Compile Include="Fast\ParticleMatter.cs" /> + <Compile Include="Fast\Physics.cs" /> + <Compile Include="Fast\Substance.cs" /> + <Compile Include="Fast\TransformedMatter.cs" /> <Compile Include="MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="Transform.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Fast/BinaryMatter.cs b/Alunite/Fast/BinaryMatter.cs new file mode 100644 index 0000000..1d0fbd1 --- /dev/null +++ b/Alunite/Fast/BinaryMatter.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite.Fast +{ + /// <summary> + /// Matter created by the composition of a untransformed and a transformed matter. + /// </summary> + public class BinaryMatter : Matter + { + public BinaryMatter(Matter A, Matter B, Transform AToB) + { + this._A = A; + this._B = B; + this._AToB = AToB; + } + + /// <summary> + /// Gets the untransformed part of this matter. + /// </summary> + public Matter A + { + get + { + return this._A; + } + } + + /// <summary> + /// Gets the source of the transformed part of this matter. + /// </summary> + public Matter B + { + get + { + return this._B; + } + } + + /// <summary> + /// Gets the transformed part of this matter with the transform applied. + /// </summary> + public TransformedMatter BFull + { + get + { + return new TransformedMatter(this._B, this._AToB); + } + } + + /// <summary> + /// Gets the transform from A's (and this matter's) coordinate space to B's coordinate space. + /// </summary> + public Transform AToB + { + get + { + return this._AToB; + } + } + + public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) + { + double amass, bmass; + Vector acen, bcen; + double aext, bext; + this._A.GetMassSummary(Physics, out amass, out acen, out aext); + this._B.GetMassSummary(Physics, out bmass, out bcen, out bext); + bcen = this._AToB.ApplyToOffset(bcen); + + Mass = amass + bmass; + CenterOfMass = acen * (amass / Mass) + bcen * (bmass / Mass); + + double alen = (acen - CenterOfMass).Length + aext; + double blen = (bcen - CenterOfMass).Length + bext; + Extent = Math.Max(alen, blen); + } + + public override Matter Update(Physics Physics, Matter Environment, double Time) + { + Matter na = this.A.Update(Physics, Physics.Combine(this.B.Apply(Physics, this.AToB), Environment), Time); + Matter nb = this.B.Update(Physics, Physics.Combine(this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); + return Physics.Combine(na, nb.Apply(Physics, this.AToB.Update(Time))); + } + + public override void OutputUsed(HashSet<Matter> Elements) + { + Elements.Add(this); + this._A.OutputUsed(Elements); + this._B.OutputUsed(Elements); + } + + public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + { + this._A.OutputParticles(Transform, Particles); + this._B.OutputParticles(this._AToB.Apply(Transform), Particles); + } + + public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) + { + Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); + Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); + return agrav + bgrav; + } + + private Matter _A; + private Matter _B; + private Transform _AToB; + } +} \ No newline at end of file diff --git a/Alunite/Fast/Matter.cs b/Alunite/Fast/Matter.cs new file mode 100644 index 0000000..aa5dc28 --- /dev/null +++ b/Alunite/Fast/Matter.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite.Fast +{ + /// <summary> + /// Matter in a fast physics system. + /// </summary> + public abstract class Matter : IMatter + { + public Matter() + { + + } + + /// <summary> + /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to + /// describe it. + /// </summary> + public int Complexity + { + get + { + HashSet<Matter> used = new HashSet<Matter>(); + this.OutputUsed(used); + return used.Count; + } + } + + /// <summary> + /// Gets the position of all the particles in this matter, for debug purposes. + /// </summary> + public IEnumerable<Particle<Substance>> Particles + { + get + { + List<Particle<Substance>> parts = new List<Particle<Substance>>(); + this.OutputParticles(Transform.Identity, parts); + return parts; + } + } + + /// <summary> + /// Applies a transform to this matter. + /// </summary> + public virtual Matter Apply(Physics Physics, Transform Transform) + { + return new TransformedMatter(this, Transform); + } + + /// <summary> + /// Gets the updated form of this matter in the specified environment after the given time. + /// </summary> + public abstract Matter Update(Physics Physics, Matter Environment, double Time); + + /// <summary> + /// Gets a summary of the location and density of mass inside the matter by getting the total mass, center of mass, + /// and extent (distance from the center of mass to the farthest piece of matter). + /// </summary> + public abstract void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent); + + /// <summary> + /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. + /// </summary> + /// <param name="RecurseThreshold">The ratio of (mass * extent) / (distance ^ 2) a piece of matter will have to have in order to have its + /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> + public virtual Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return Physics.GetGravity(Physics.GetMass(this), Position, Mass); + } + + /// <summary> + /// Recursively outputs all matter used in the definition of this matter, including this matter itself. + /// </summary> + public virtual void OutputUsed(HashSet<Matter> Elements) + { + Elements.Add(this); + } + + /// <summary> + /// Outputs all particles defined in this matter, after applying the specified transform. + /// </summary> + public virtual void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + { + + } + } +} \ No newline at end of file diff --git a/Alunite/Fast/ParticleMatter.cs b/Alunite/Fast/ParticleMatter.cs new file mode 100644 index 0000000..a4c184d --- /dev/null +++ b/Alunite/Fast/ParticleMatter.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite.Fast +{ + /// <summary> + /// Matter containing a single, untransformed particle. + /// </summary> + public class ParticleMatter : Matter + { + public ParticleMatter(Substance Substance, double Mass, AxisAngle Spin) + { + this._Substance = Substance; + this._Mass = Mass; + this._Spin = Spin; + } + + /// <summary> + /// Gets the substance of the particle represented by this matter. + /// </summary> + public Substance Substance + { + get + { + return this._Substance; + } + } + + /// <summary> + /// Gets the untransformed spin of the particle represented by this matter. + /// </summary> + public AxisAngle Spin + { + get + { + return this._Spin; + } + } + + public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + { + Particles.Add(new Particle<Substance>() + { + Mass = this._Mass, + Spin = this._Spin.Apply(Transform.Rotation), + Substance = this._Substance, + Orientation = Transform.Rotation, + Position = Transform.Offset, + Velocity = Transform.VelocityOffset + }); + } + + public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) + { + Mass = this._Mass; + CenterOfMass = new Vector(0.0, 0.0, 0.0); + Extent = 0.0; + } + + public override Matter Update(Physics Physics, Matter Environment, double Time) + { + Particle<Substance> part = new Particle<Substance>() + { + Mass = this._Mass, + Spin = this._Spin, + Substance = this._Substance, + Orientation = Quaternion.Identity, + Position = new Vector(0.0, 0.0, 0.0), + Velocity = new Vector(0.0, 0.0, 0.0) + }; + this.Substance.Update(Physics, Environment, Time, ref part); + return Physics.Create(part); + } + + public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return Physics.GetGravity(this._Mass, Position, Mass); + } + + private Substance _Substance; + private double _Mass; + private AxisAngle _Spin; + } +} \ No newline at end of file diff --git a/Alunite/Fast/Physics.cs b/Alunite/Fast/Physics.cs new file mode 100644 index 0000000..6027f47 --- /dev/null +++ b/Alunite/Fast/Physics.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite.Fast +{ + /// <summary> + /// A physics system where interactions between matter are memozied allowing for + /// faster simulation. + /// </summary> + public class Physics : IParticlePhysics<Matter, Substance>, IGravitationalPhysics<Matter> + { + public Physics(double G) + { + this._G = G; + } + + public Physics() + : this(6.67428e-11) + { + + } + + /// <summary> + /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. + /// </summary> + public double G + { + get + { + return this._G; + } + } + + public Matter Create(Particle<Substance> Particle) + { + return new TransformedMatter( + new ParticleMatter(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), + new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); + } + + /// <summary> + /// Creates a lattice of the specified object. The amount of items in the lattice is equal to (2 ^ (Log2Size * 3)). + /// </summary> + public Matter CreateLattice(Matter Object, int Log2Size, double Spacing) + { + // Get "major" spacing + Spacing = Spacing * Math.Pow(2.0, Log2Size - 1); + + // Extract transform + TransformedMatter trans = Object as TransformedMatter; + if (trans != null) + { + Object = trans.Source; + return this._CreateLattice(Object, Log2Size, Spacing).Apply(this, trans.Transform); + } + else + { + return this._CreateLattice(Object, Log2Size, Spacing); + } + } + + private Matter _CreateLattice(Matter Object, int Log2Size, double MajorSpacing) + { + // Create a lattice with major spacing + if (Log2Size <= 0) + { + return Object; + } + if (Log2Size > 1) + { + Object = this._CreateLattice(Object, Log2Size - 1, MajorSpacing * 0.5); + } + + BinaryMatter a = this.QuickCombine(Object, Object, new Transform(MajorSpacing, 0.0, 0.0)); + BinaryMatter b = this.QuickCombine(a, a, new Transform(0.0, MajorSpacing, 0.0)); + BinaryMatter c = this.QuickCombine(b, b, new Transform(0.0, 0.0, MajorSpacing)); + return c; + } + + public Matter Apply(Matter Matter, Transform Transform) + { + if (Matter != null) + { + return Matter.Apply(this, Transform); + } + else + { + return null; + } + } + + public Matter Update(Matter Matter, Matter Environment, double Time) + { + return Matter.Update(this, Environment, Time); + } + + public Matter Compose(IEnumerable<Matter> Elements) + { + Matter cur = this.Null; + foreach (Matter matter in Elements) + { + cur = this.Combine(cur, matter); + } + return cur; + } + + /// <summary> + /// Combines two pieces of matter in a similar manner to Compose. + /// </summary> + public Matter Combine(Matter A, Matter B) + { + if (A == null) + { + return B; + } + if (B == null) + { + return A; + } + + TransformedMatter atrans = A as TransformedMatter; + TransformedMatter btrans = B as TransformedMatter; + + Transform atob = Transform.Identity; + if (btrans != null) + { + atob = btrans.Transform; + B = btrans.Source; + } + + if (atrans != null) + { + return new BinaryMatter(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(this, atrans.Transform); + } + else + { + return new BinaryMatter(A, B, atob); + } + } + + /// <summary> + /// Quickly combines two pieces of untransformed matter. + /// </summary> + public BinaryMatter QuickCombine(Matter A, Matter B, Transform AToB) + { + return new BinaryMatter(A, B, AToB); + } + + public Matter Null + { + get + { + return null; + } + } + + /// <summary> + /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given + /// offset in meters. + /// </summary> + public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) + { + double sqrlen = Offset.SquareLength; + return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); + } + + /// <summary> + /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. + /// </summary> + public double GetGravityStrength(double MassA, double MassB, double Distance) + { + return -this._G * (MassA + MassB) / (Distance * Distance); + } + + public Vector GetGravity(Matter Environment, Vector Position, double Mass) + { + return Environment.GetGravity(this, Position, Mass, 0.0); + } + + public double GetMass(Matter Matter) + { + double mass; Vector com; double extent; + Matter.GetMassSummary(this, out mass, out com, out extent); + return mass; + } + + private double _G; + } +} \ No newline at end of file diff --git a/Alunite/FastPhysicsSubstance.cs b/Alunite/Fast/Substance.cs similarity index 59% rename from Alunite/FastPhysicsSubstance.cs rename to Alunite/Fast/Substance.cs index ee741aa..0355897 100644 --- a/Alunite/FastPhysicsSubstance.cs +++ b/Alunite/Fast/Substance.cs @@ -1,42 +1,40 @@ using System; using System.Collections.Generic; using System.Linq; -namespace Alunite +namespace Alunite.Fast { /// <summary> /// A substance in a fast physics system. /// </summary> - public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> + public class Substance : IAutoSubstance<Physics, Matter, Substance> { - private FastPhysicsSubstance() + private Substance() { - this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); + } /// <summary> /// The default (and currently only) possible substance. /// </summary> - public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); + public static readonly Substance Default = new Substance(); - public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) + public void Update(Physics Physics, Matter Environment, double Time, ref Particle<Substance> Particle) { Particle.Velocity += Environment.GetGravity(Physics, new Vector(0.0, 0.0, 0.0), Particle.Mass, Physics.G * 1.0e15) * (Time / Particle.Mass); Particle.Update(Time); } public MatterDisparity GetDisparity( - FastPhysics Physics, FastPhysicsMatter Environment, + Physics Physics, Matter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } - - private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Fast/TransformedMatter.cs b/Alunite/Fast/TransformedMatter.cs new file mode 100644 index 0000000..2174db8 --- /dev/null +++ b/Alunite/Fast/TransformedMatter.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite.Fast +{ + /// <summary> + /// Matter created by transforming other "Source" matter. + /// </summary> + public class TransformedMatter : Matter + { + public TransformedMatter(Matter Source, Transform Transform) + { + this._Source = Source; + this._Transform = Transform; + } + + /// <summary> + /// Gets the source matter for this transformed matter. + /// </summary> + public Matter Source + { + get + { + return this._Source; + } + } + + /// <summary> + /// Gets the transform applied by this transformed matter. + /// </summary> + public Transform Transform + { + get + { + return this._Transform; + } + } + + public override Matter Apply(Physics Physics, Transform Transform) + { + return new TransformedMatter(this.Source, this.Transform.Apply(Transform)); + } + + public override Matter Update(Physics Physics, Matter Environment, double Time) + { + return Physics.Apply(this.Source.Update(Physics, Physics.Apply(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); + } + + public override void OutputUsed(HashSet<Matter> Elements) + { + Elements.Add(this); + this._Source.OutputUsed(Elements); + } + + public override void OutputParticles(Transform Transform, List<Particle<Substance>> Particles) + { + this._Source.OutputParticles(this._Transform.Apply(Transform), Particles); + } + + public override void GetMassSummary(Physics Physics, out double Mass, out Vector CenterOfMass, out double Extent) + { + this._Source.GetMassSummary(Physics, out Mass, out CenterOfMass, out Extent); + CenterOfMass = this._Transform.ApplyToOffset(CenterOfMass); + } + + public override Vector GetGravity(Physics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return this._Transform.ApplyToDirection(this._Source.GetGravity(Physics, this._Transform.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); + } + + private Matter _Source; + private Transform _Transform; + } +} \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs deleted file mode 100644 index 0e17b84..0000000 --- a/Alunite/FastPhysics.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// A physics system where interactions between matter are memozied allowing for - /// faster simulation. - /// </summary> - public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance>, IGravitationalPhysics<FastPhysicsMatter> - { - public FastPhysics(double G) - { - this._G = G; - } - - public FastPhysics() - : this(6.67428e-11) - { - - } - - /// <summary> - /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. - /// </summary> - public double G - { - get - { - return this._G; - } - } - - public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) - { - return FastPhysicsMatter.Particle(this, Particle); - } - - public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) - { - if (Matter != null) - { - return Matter.Apply(this, Transform); - } - else - { - return null; - } - } - - public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) - { - return Matter.Update(this, Environment, Time); - } - - public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Elements) - { - FastPhysicsMatter cur = this.Null; - foreach (FastPhysicsMatter matter in Elements) - { - cur = this.Combine(cur, matter); - } - return cur; - } - - /// <summary> - /// Combines two pieces of matter in a similar manner to Compose. - /// </summary> - public FastPhysicsMatter Combine(FastPhysicsMatter A, FastPhysicsMatter B) - { - return FastPhysicsMatter.Combine(this, A, B); - } - - public FastPhysicsMatter Null - { - get - { - return null; - } - } - - /// <summary> - /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given - /// offset in meters. - /// </summary> - public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) - { - double sqrlen = Offset.SquareLength; - return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); - } - - /// <summary> - /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. - /// </summary> - public double GetGravityStrength(double MassA, double MassB, double Distance) - { - return -this._G * (MassA + MassB) / (Distance * Distance); - } - - public Vector GetGravity(FastPhysicsMatter Environment, Vector Position, double Mass) - { - return Environment.GetGravity(this, Position, Mass, 0.0); - } - - public double GetMass(FastPhysicsMatter Matter) - { - double mass; Vector com; double extent; - Matter.GetMass(out mass, out com, out extent); - return mass; - } - - private double _G; - } -} \ No newline at end of file diff --git a/Alunite/FastPhysicsMatter.cs b/Alunite/FastPhysicsMatter.cs deleted file mode 100644 index c8992c0..0000000 --- a/Alunite/FastPhysicsMatter.cs +++ /dev/null @@ -1,366 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Matter in a fast physics system. - /// </summary> - public abstract class FastPhysicsMatter : IMatter - { - private FastPhysicsMatter() - { - this._Usages = new UsageSet<_Binary>(); - } - - /// <summary> - /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to - /// describe it. - /// </summary> - public int Complexity - { - get - { - HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); - this._GetUsed(used); - return used.Count; - } - } - - /// <summary> - /// Gets the position of all the particles in this matter, for debug purposes. - /// </summary> - public IEnumerable<Particle<FastPhysicsSubstance>> Particles - { - get - { - List<Particle<FastPhysicsSubstance>> parts = new List<Particle<FastPhysicsSubstance>>(); - this._GetParticles(Transform.Identity, parts); - return parts; - } - } - - /// <summary> - /// Applies a transform to this matter. - /// </summary> - public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) - { - return new _Transformed(this, Transform); - } - - /// <summary> - /// Gets the updated form of this matter in the specified environment after the given time. - /// </summary> - public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); - - /// <summary> - /// Creates matter for a particle. - /// </summary> - public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) - { - return new _Transformed( - new _Particle(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), - new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); - } - - /// <summary> - /// Quickly creates a lattice with a power of two size of the specified object. - /// </summary> - public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) - { - // Get "major" spacing - Spacing = Spacing * Math.Pow(2.0, LogSize - 1); - - // Extract transform - _Transformed trans = Object as _Transformed; - if (trans != null) - { - Object = trans.Source; - return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); - } - else - { - return _CreateLattice(Physics, LogSize, Object, Spacing); - } - } - - private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) - { - if (LogSize <= 0) - { - return Object; - } - if (LogSize > 1) - { - Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); - } - _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); - _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); - _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); - return binc; - } - - /// <summary> - /// Combines two pieces of fast physics matter. - /// </summary> - public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) - { - if (A == null) - { - return B; - } - if (B == null) - { - return A; - } - - _Transformed atrans = A as _Transformed; - _Transformed btrans = B as _Transformed; - - Transform atob = Transform.Identity; - if (btrans != null) - { - atob = btrans.Transform; - B = btrans.Source; - } - - if (atrans != null) - { - return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); - } - else - { - return new _Binary(A, B, atob); - } - } - - /// <summary> - /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. - /// </summary> - public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); - - /// <summary> - /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. - /// </summary> - /// <param name="RecurseThreshold">The ratio of (mass * extent) / (distance ^ 2) a piece of matter will have to have in order to have its - /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> - public virtual Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return Physics.GetGravity(Physics.GetMass(this), Position, Mass); - } - - /// <summary> - /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including - /// this matter itself. - /// </summary> - internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); - } - - /// <summary> - /// Adds all particles in this matter to the given list after applying the specified transform. - /// </summary> - internal virtual void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - - } - - /// <summary> - /// Matter containing a single particle. - /// </summary> - internal class _Particle : FastPhysicsMatter - { - public _Particle(FastPhysicsSubstance Substance, double Mass, AxisAngle Spin) - { - this.Substance = Substance; - this.Mass = Mass; - this.Spin = Spin; - } - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - Particles.Add(new Particle<FastPhysicsSubstance>() - { - Mass = this.Mass, - Spin = this.Spin, - Substance = this.Substance, - Orientation = Transform.Rotation, - Position = Transform.Offset, - Velocity = Transform.VelocityOffset - }); - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - Mass = this.Mass; - CenterOfMass = new Vector(0.0, 0.0, 0.0); - Extent = 0.0; - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() - { - Mass = this.Mass, - Spin = this.Spin, - Substance = this.Substance, - Orientation = Quaternion.Identity, - Position = new Vector(0.0, 0.0, 0.0), - Velocity = new Vector(0.0, 0.0, 0.0) - }; - this.Substance.Update(Physics, Environment, Time, ref part); - return Particle(Physics, part); - } - - public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return Physics.GetGravity(this.Mass, Position, Mass); - } - - public FastPhysicsSubstance Substance; - public double Mass; - public AxisAngle Spin; - } - - /// <summary> - /// Matter created by transforming some source matter. - /// </summary> - internal class _Transformed : FastPhysicsMatter - { - public _Transformed(FastPhysicsMatter Source, Transform Transform) - { - this.Source = Source; - this.Transform = Transform; - } - - public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) - { - return new _Transformed(this.Source, this.Transform.Apply(Transform)); - } - - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); - this.Source._GetUsed(Elements); - } - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - this.Source._GetParticles(this.Transform.Apply(Transform), Particles); - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - this.Source.GetMass(out Mass, out CenterOfMass, out Extent); - CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); - } - - public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) - { - return this.Transform.ApplyToDirection(this.Source.GetGravity(Physics, this.Transform.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); - } - - public FastPhysicsMatter Source; - public Transform Transform; - } - - /// <summary> - /// Matter created by the combination of some untransformed matter and some - /// transformed matter. - /// </summary> - internal class _Binary : FastPhysicsMatter - { - public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) - : this(A, B, AToB, true) - { - - } - - public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB, bool Reuse) - { - this.A = A; - this.B = B; - this.AToB = AToB; - - double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); - double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); - this.Mass = amass + bmass; - this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); - - double alen = (acen - this.CenterOfMass).Length + aext; - double blen = (bcen - this.CenterOfMass).Length + bext; - this.Extent = Math.Max(alen, blen); - - if (Reuse) - { - A._Usages.Add(this); - if (A != B) - { - B._Usages.Add(this); - } - } - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, this.B.Apply(Physics, this.AToB), Environment), Time); - FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); - return Combine(Physics, na, nb.Apply(Physics, this.AToB.Update(Time))); - } - - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); - this.A._GetUsed(Elements); - this.B._GetUsed(Elements); - } - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - this.A._GetParticles(Transform, Particles); - this.B._GetParticles(this.AToB.Apply(Transform), Particles); - } - - public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) - { - Vector offset = Position - this.CenterOfMass; - double offsetlen = offset.Length; - - double rat = (this.Mass * this.Extent) / (offsetlen * offsetlen); - if (rat >= RecurseThreshold) - { - Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); - Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); - return agrav + bgrav; - } - else - { - return offset * (Physics.GetGravityStrength(this.Mass, Mass, offsetlen) / offsetlen); - } - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - Mass = this.Mass; - CenterOfMass = this.CenterOfMass; - Extent = this.Extent; - } - - public double Mass; - public Vector CenterOfMass; - public double Extent; - public FastPhysicsMatter A; - public FastPhysicsMatter B; - public Transform AToB; - } - - private UsageSet<_Binary> _Usages; - } -} \ No newline at end of file diff --git a/Alunite/Physics.cs b/Alunite/Physics.cs index d33cc19..7a7ccd3 100644 --- a/Alunite/Physics.cs +++ b/Alunite/Physics.cs @@ -1,128 +1,128 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Elements); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> - TMatter Transform(TMatter Matter, Transform Transform); + TMatter Apply(TMatter Matter, Transform Transform); } /// <summary> /// A physical system where all matter has a mass expressable in kilograms. /// </summary> public interface IMassPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the mass of the given matter. /// </summary> double GetMass(TMatter Matter); } /// <summary> /// A physical system where gravity (a force that affects all matter depending only on their mass) exists. Note that gravity must be /// a force felt mutally by involved matter. /// </summary> public interface IGravitationalPhysics<TMatter> : ISpatialPhysics<TMatter>, IMassPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the gravity (meters / second ^ 2) a particle at the specified position and mass will feel if it was in the given environment. /// </summary> Vector GetGravity(TMatter Environment, Vector Position, double Mass); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Describes the difference between two pieces of matter. /// </summary> /// <remarks>The "simple matter disparity" does not take into account forces to external matter while the "complex matter disparity" does. Note that /// matter disparity is for the most part an approximation used for optimizations.</remarks> public struct MatterDisparity { public MatterDisparity(double Movement, double Translation, double Mass) { this.Movement = Movement; this.Translation = Translation; this.Mass = Mass; } /// <summary> /// Gets the matter disparity between two identical pieces of matter. /// </summary> public static MatterDisparity Identical { get { return new MatterDisparity(0.0, 0.0, 0.0); } } /// <summary> /// Gets the simple matter disparity between two particles. /// </summary> public static MatterDisparity BetweenParticles(double MassA, Vector PosA, Vector VelA, double MassB, Vector PosB, Vector VelB) { return new MatterDisparity( (MassA + MassB) * (VelA - VelB).Length, (MassA + MassB) * (PosA - PosB).Length, Math.Abs(MassA - MassB)); } /// <summary> /// The amount of mass, course deviation that would be caused if the compared pieces of matter were swapped in usage, measured in /// kilograms meters per second. Note that if this is for "complex matter disparity", this should take into account external /// matter and forces. /// </summary> public double Movement; /// <summary> /// The amount of mass that is immediately translated between the two compared pieces of matter, measured in kilogram meters. /// </summary> public double Translation; /// <summary> /// The difference in mass of the two compared pieces of matter measured in kilograms. /// </summary> public double Mass; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 3a92236..4fb0509 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,54 +1,56 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; +using Alunite.Fast; + namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world - FastPhysics fp = new FastPhysics(); - FastPhysicsMatter obj = FastPhysicsMatter.CreateLattice(fp, 2, fp.Create(new Particle<FastPhysicsSubstance>() + Physics fp = new Physics(); + Matter obj = fp.CreateLattice(fp.Create(new Particle<Substance>() { - Substance = FastPhysicsSubstance.Default, + Substance = Substance.Default, Mass = 1.0, Position = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity - }), 0.1); + }), 2, 0.1); - FastPhysicsMatter earth = fp.Create(new Particle<FastPhysicsSubstance>() + Matter earth = fp.Create(new Particle<Substance>() { - Substance = FastPhysicsSubstance.Default, + Substance = Substance.Default, Mass = 5.9742e24, Position = new Vector(0.0, 0.0, -6.3675e6), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity }); - FastPhysicsMatter world = fp.Combine(obj, earth); + Matter world = fp.Combine(obj, earth); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(fp, world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs index b134884..9232787 100644 --- a/Alunite/Transform.cs +++ b/Alunite/Transform.cs @@ -1,102 +1,108 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } public Transform(Vector Offset) { this.Offset = Offset; this.VelocityOffset = new Vector(0.0, 0.0, 0.0); this.Rotation = Quaternion.Identity; } + public Transform(double X, double Y, double Z) + : this(new Vector(X, Y, Z)) + { + + } + /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies this transform to a direction vector. /// </summary> public Vector ApplyToDirection(Vector Dir) { return this.Rotation.Rotate(Dir); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } /// <summary> /// Updates the state of this transform after the given amount of time in seconds. /// </summary> public Transform Update(double Time) { return new Transform(this.Offset + this.VelocityOffset * Time, this.VelocityOffset, this.Rotation); } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index f5d8de2..59dec8c 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,62 +1,64 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; +using Alunite.Fast; + namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(FastPhysics Physics, FastPhysicsMatter World) + public Visualizer(Physics Physics, Matter World) { this._Physics = Physics; this._World = World; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); - foreach (Particle<FastPhysicsSubstance> part in this._World.Particles) + foreach (Particle<Substance> part in this._World.Particles) { GL.Vertex3(part.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { { - FastPhysics phys = this._Physics; + Physics phys = this._Physics; this._World = phys.Update(this._World, phys.Null, Time * 0.1); } this._Time += Time * 0.2; } - private FastPhysics _Physics; - private FastPhysicsMatter _World; + private Physics _Physics; + private Matter _World; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
07526d54677c2319887e38f6cdac2aca6ffc7bce
Faster, more accurate gravity
diff --git a/Alunite/FastPhysicsMatter.cs b/Alunite/FastPhysicsMatter.cs index 9513c90..c8992c0 100644 --- a/Alunite/FastPhysicsMatter.cs +++ b/Alunite/FastPhysicsMatter.cs @@ -1,367 +1,366 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Particle<FastPhysicsSubstance>> Particles { get { List<Particle<FastPhysicsSubstance>> parts = new List<Particle<FastPhysicsSubstance>>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed(this, Transform); } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { - return new _Transformed(_Particle.Default, new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); + return new _Transformed( + new _Particle(Particle.Substance, Particle.Mass, Particle.Spin.Apply(Particle.Orientation.Conjugate)), + new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); } /// <summary> /// Quickly creates a lattice with a power of two size of the specified object. /// </summary> public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, LogSize - 1); // Extract transform _Transformed trans = Object as _Transformed; if (trans != null) { Object = trans.Source; return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); } else { return _CreateLattice(Physics, LogSize, Object, Spacing); } } private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) { if (LogSize <= 0) { return Object; } if (LogSize > 1) { Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); } _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); return binc; } /// <summary> /// Combines two pieces of fast physics matter. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { if (A == null) { return B; } if (B == null) { return A; } _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } if (atrans != null) { return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); } else { return new _Binary(A, B, atob); } } /// <summary> /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. /// </summary> public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); /// <summary> /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. /// </summary> - /// <param name="RecurseThreshold">The ratio of mass / (distance ^ 2) a piece of matter will have to have in order to have its + /// <param name="RecurseThreshold">The ratio of (mass * extent) / (distance ^ 2) a piece of matter will have to have in order to have its /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> public virtual Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) { return Physics.GetGravity(Physics.GetMass(this), Position, Mass); } /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { - /// <summary> - /// Default particle. - /// </summary> - public static readonly _Particle Default = new _Particle() { Substance = FastPhysicsSubstance.Default, Mass = 1.0 }; + public _Particle(FastPhysicsSubstance Substance, double Mass, AxisAngle Spin) + { + this.Substance = Substance; + this.Mass = Mass; + this.Spin = Spin; + } internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { Particles.Add(new Particle<FastPhysicsSubstance>() { Mass = this.Mass, Spin = this.Spin, Substance = this.Substance, Orientation = Transform.Rotation, Position = Transform.Offset, Velocity = Transform.VelocityOffset }); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = new Vector(0.0, 0.0, 0.0); Extent = 0.0; } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() { Mass = this.Mass, Spin = this.Spin, Substance = this.Substance, Orientation = Quaternion.Identity, Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0) }; this.Substance.Update(Physics, Environment, Time, ref part); - return new _Transformed(new _Particle() - { - Mass = part.Mass, - Spin = part.Spin, - Substance = part.Substance - }, new Transform(part.Position, part.Velocity, part.Orientation)); + return Particle(Physics, part); } public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) { return Physics.GetGravity(this.Mass, Position, Mass); } public FastPhysicsSubstance Substance; public double Mass; public AxisAngle Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public _Transformed(FastPhysicsMatter Source, Transform Transform) { this.Source = Source; this.Transform = Transform; } public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed(this.Source, this.Transform.Apply(Transform)); } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { this.Source.GetMass(out Mass, out CenterOfMass, out Extent); CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); } public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) { - return this.Transform.ApplyToDirection(this.Source.GetGravity(Physics, this.Transform.Inverse.ApplyToDirection(Position), Mass, RecurseThreshold)); + return this.Transform.ApplyToDirection(this.Source.GetGravity(Physics, this.Transform.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) : this(A, B, AToB, true) { } public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB, bool Reuse) { this.A = A; this.B = B; this.AToB = AToB; double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); this.Mass = amass + bmass; this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); double alen = (acen - this.CenterOfMass).Length + aext; double blen = (bcen - this.CenterOfMass).Length + bext; this.Extent = Math.Max(alen, blen); if (Reuse) { A._Usages.Add(this); if (A != B) { B._Usages.Add(this); } } } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { - FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, Environment, this.B.Apply(Physics, this.AToB)), Time); - FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, Environment, this.A).Apply(Physics, this.AToB.Inverse), Time); - return Combine(Physics, na, nb.Apply(Physics, this.AToB)); + FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, this.B.Apply(Physics, this.AToB), Environment), Time); + FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, this.A, Environment).Apply(Physics, this.AToB.Inverse), Time); + return Combine(Physics, na, nb.Apply(Physics, this.AToB.Update(Time))); } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) { Vector offset = Position - this.CenterOfMass; double offsetlen = offset.Length; - double rat = this.Mass / (offsetlen * offsetlen); + double rat = (this.Mass * this.Extent) / (offsetlen * offsetlen); if (rat >= RecurseThreshold) { - return - A.GetGravity(Physics, Position, Mass, RecurseThreshold) + - this.AToB.ApplyToDirection(B.GetGravity(Physics, this.AToB.Inverse.ApplyToDirection(Position), Mass, RecurseThreshold)); + Vector agrav = this.A.GetGravity(Physics, Position, Mass, RecurseThreshold); + Vector bgrav = this.AToB.ApplyToDirection(this.B.GetGravity(Physics, this.AToB.Inverse.ApplyToOffset(Position), Mass, RecurseThreshold)); + return agrav + bgrav; } else { return offset * (Physics.GetGravityStrength(this.Mass, Mass, offsetlen) / offsetlen); } } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = this.CenterOfMass; Extent = this.Extent; } public double Mass; public Vector CenterOfMass; public double Extent; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } } \ No newline at end of file diff --git a/Alunite/FastPhysicsSubstance.cs b/Alunite/FastPhysicsSubstance.cs index c15eaac..ee741aa 100644 --- a/Alunite/FastPhysicsSubstance.cs +++ b/Alunite/FastPhysicsSubstance.cs @@ -1,42 +1,42 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { - Particle.Velocity.Z -= Time; + Particle.Velocity += Environment.GetGravity(Physics, new Vector(0.0, 0.0, 0.0), Particle.Mass, Physics.G * 1.0e15) * (Time / Particle.Mass); Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 6113a98..3a92236 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,44 +1,54 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world FastPhysics fp = new FastPhysics(); - FastPhysicsMatter world = FastPhysicsMatter.CreateLattice(fp, 1, fp.Create(new Particle<FastPhysicsSubstance>() - { - Substance = FastPhysicsSubstance.Default, - Mass = 1.0, - Position = new Vector(0.0, 0.0, 0.0), - Velocity = new Vector(0.0, 0.0, 0.0), - Orientation = Quaternion.Identity, - Spin = AxisAngle.Identity - }), 0.1); + FastPhysicsMatter obj = FastPhysicsMatter.CreateLattice(fp, 2, fp.Create(new Particle<FastPhysicsSubstance>() + { + Substance = FastPhysicsSubstance.Default, + Mass = 1.0, + Position = new Vector(0.0, 0.0, 0.0), + Orientation = Quaternion.Identity, + Spin = AxisAngle.Identity + }), 0.1); + + FastPhysicsMatter earth = fp.Create(new Particle<FastPhysicsSubstance>() + { + Substance = FastPhysicsSubstance.Default, + Mass = 5.9742e24, + Position = new Vector(0.0, 0.0, -6.3675e6), + Orientation = Quaternion.Identity, + Spin = AxisAngle.Identity + }); + + FastPhysicsMatter world = fp.Combine(obj, earth); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(fp, world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index 4e584d2..a25e110 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,228 +1,236 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } public Quaternion(Vector Axis, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; this.B = Axis.X * sina; this.C = Axis.Y * sina; this.D = Axis.Z * sina; } /// <summary> /// Gets a rotation quaternion for a rotation described in axis angle form. /// </summary> public static Quaternion AxisAngle(Vector Axis, double Angle) { return new Quaternion(Axis, Angle); } /// <summary> /// Gets a rotation quaternion for the angle between two distinct normal vectors. /// </summary> public static Quaternion AngleBetween(Vector A, Vector B) { double hcosang = Math.Sqrt(0.5 + 0.5 * Vector.Dot(A, B)); double hsinang = Math.Sqrt(1.0 - hcosang * hcosang); double sinang = 2.0 * hsinang * hcosang; Vector axis = Vector.Cross(A, B); axis *= 1.0 / sinang; return new Quaternion(hcosang, axis * hsinang); } /// <summary> /// Gets the identity quaternion. /// </summary> public static Quaternion Identity { get { return new Quaternion(1.0, 0.0, 0.0, 0.0); } } /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } /// <summary> /// Gets the absolute value of the quaternion. /// </summary> public double Abs { get { return Math.Sqrt(this.A * this.A + this.B * this.B + this.C * this.C + this.D * this.D); } } /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } /// <summary> /// Applies the rotation represented by this quaternion to another. /// </summary> public Quaternion ApplyTo(Quaternion Other) { return Quaternion.Normalize(this * Other); } /// <summary> /// Applies a rotation to this quaternion. /// </summary> public Quaternion Apply(Quaternion Other) { return Quaternion.Normalize(Other * this); } /// <summary> /// Normalizes the quaternion. /// </summary> public void Normalize() { double d = 1.0 / this.Abs; this.A *= d; this.B *= d; this.C *= d; this.D *= d; } /// <summary> /// Normalizes the specified quaternion. /// </summary> public static Quaternion Normalize(Quaternion A) { A.Normalize(); return A; } /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { Quaternion q = new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); return q; } public double A; public double B; public double C; public double D; } /// <summary> /// An axis angle representation of rotation. /// </summary> public struct AxisAngle { public AxisAngle(Vector Axis, double Angle) { this.Axis = Axis; this.Angle = Angle; } /// <summary> /// Gets an axis angle representation of an identity rotation. /// </summary> public static AxisAngle Identity { get { return new AxisAngle(new Vector(1.0, 0.0, 0.0), 0.0); } } + /// <summary> + /// Applies a rotation created by a quaternion to this axis-angle rotation. + /// </summary> + public AxisAngle Apply(Quaternion Rotation) + { + return new AxisAngle(Rotation.Rotate(this.Axis), Angle); + } + public static implicit operator Quaternion(AxisAngle AxisAngle) { return Quaternion.AxisAngle(AxisAngle.Axis, AxisAngle.Angle); } public static AxisAngle operator *(AxisAngle AxisAngle, double Factor) { return new AxisAngle(AxisAngle.Axis, AxisAngle.Angle * Factor); } /// <summary> /// The angle, in radians, of the rotation. /// </summary> public double Angle; /// <summary> /// The normalized axis of the rotation. /// </summary> public Vector Axis; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index c3012c5..f5d8de2 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,64 +1,62 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(FastPhysics Physics, FastPhysicsMatter World) { this._Physics = Physics; this._World = World; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); foreach (Particle<FastPhysicsSubstance> part in this._World.Particles) { GL.Vertex3(part.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { { FastPhysics phys = this._Physics; - this._World = phys.Update(this._World, phys.Null, Time); - - Vector grav = this._Physics.GetGravity(this._World, new Vector(0.0, 0.0, 1.0), 100.0); + this._World = phys.Update(this._World, phys.Null, Time * 0.1); } this._Time += Time * 0.2; } private FastPhysics _Physics; private FastPhysicsMatter _World; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
0e57ca47ef4af7dfec4f3554f23da691e1d09418
Cleaning up, Gravity
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index de5492a..d71445f 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,69 +1,71 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>9.0.30729</ProductVersion> + <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="FastPhysics.cs" /> + <Compile Include="FastPhysicsMatter.cs" /> + <Compile Include="FastPhysicsSubstance.cs" /> <Compile Include="MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="Transform.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index b4138ac..0e17b84 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,406 +1,115 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> - public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> + public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance>, IGravitationalPhysics<FastPhysicsMatter> { - public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) - { - return FastPhysicsMatter.Particle(this, Particle); - } - - public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) - { - if (Matter != null) - { - return Matter.Apply(this, Transform); - } - else - { - return null; - } - } - - public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) - { - return Matter.Update(this, Environment, Time); - } - - public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) - { - throw new NotImplementedException(); - } - - /// <summary> - /// Combines two pieces of matter in a similar manner to Compose. - /// </summary> - public FastPhysicsMatter Combine(FastPhysicsMatter A, FastPhysicsMatter B) - { - return FastPhysicsMatter.Combine(this, A, B); - } - - public FastPhysicsMatter Null + public FastPhysics(double G) { - get - { - return null; - } + this._G = G; } - } - /// <summary> - /// Matter in a fast physics system. - /// </summary> - public abstract class FastPhysicsMatter : IMatter - { - private FastPhysicsMatter() + public FastPhysics() + : this(6.67428e-11) { - this._Usages = new UsageSet<_Binary>(); - } - /// <summary> - /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to - /// describe it. - /// </summary> - public int Complexity - { - get - { - HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); - this._GetUsed(used); - return used.Count; - } } /// <summary> - /// Gets the position of all the particles in this matter, for debug purposes. + /// Gets the gravitational constant for this physical system in newton meters / kilogram ^ 2. /// </summary> - public IEnumerable<Particle<FastPhysicsSubstance>> Particles + public double G { get { - List<Particle<FastPhysicsSubstance>> parts = new List<Particle<FastPhysicsSubstance>>(); - this._GetParticles(Transform.Identity, parts); - return parts; + return this._G; } } - /// <summary> - /// Applies a transform to this matter. - /// </summary> - public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) - { - return new _Transformed(this, Transform); - } - - /// <summary> - /// Gets the updated form of this matter in the specified environment after the given time. - /// </summary> - public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); - - /// <summary> - /// Creates matter for a particle. - /// </summary> - public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) + public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { - return new _Transformed(_Particle.Default, new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); + return FastPhysicsMatter.Particle(this, Particle); } - /// <summary> - /// Quickly creates a lattice with a power of two size of the specified object. - /// </summary> - public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) + public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { - // Get "major" spacing - Spacing = Spacing * Math.Pow(2.0, LogSize - 1); - - // Extract transform - _Transformed trans = Object as _Transformed; - if (trans != null) + if (Matter != null) { - Object = trans.Source; - return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); + return Matter.Apply(this, Transform); } else { - return _CreateLattice(Physics, LogSize, Object, Spacing); + return null; } } - private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) + public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { - if (LogSize <= 0) - { - return Object; - } - if (LogSize > 1) - { - Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); - } - _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); - _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); - _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); - return binc; + return Matter.Update(this, Environment, Time); } - /// <summary> - /// Combines two pieces of fast physics matter. - /// </summary> - public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) + public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Elements) { - if (A == null) - { - return B; - } - if (B == null) + FastPhysicsMatter cur = this.Null; + foreach (FastPhysicsMatter matter in Elements) { - return A; + cur = this.Combine(cur, matter); } - - _Transformed atrans = A as _Transformed; - _Transformed btrans = B as _Transformed; - - Transform atob = Transform.Identity; - if (btrans != null) - { - atob = btrans.Transform; - B = btrans.Source; - } - - if (atrans != null) - { - return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); - } - else - { - return new _Binary(A, B, atob); - } - } - - /// <summary> - /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. - /// </summary> - public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); - - /// <summary> - /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including - /// this matter itself. - /// </summary> - internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); + return cur; } /// <summary> - /// Adds all particles in this matter to the given list after applying the specified transform. + /// Combines two pieces of matter in a similar manner to Compose. /// </summary> - internal virtual void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) + public FastPhysicsMatter Combine(FastPhysicsMatter A, FastPhysicsMatter B) { - + return FastPhysicsMatter.Combine(this, A, B); } - /// <summary> - /// Matter containing a single particle. - /// </summary> - internal class _Particle : FastPhysicsMatter + public FastPhysicsMatter Null { - /// <summary> - /// Default particle. - /// </summary> - public static readonly _Particle Default = new _Particle() { Substance = FastPhysicsSubstance.Default, Mass = 1.0 }; - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - Particles.Add(new Particle<FastPhysicsSubstance>() - { - Mass = this.Mass, - Spin = this.Spin, - Substance = this.Substance, - Orientation = Transform.Rotation, - Position = Transform.Offset, - Velocity = Transform.VelocityOffset - }); - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - Mass = this.Mass; - CenterOfMass = new Vector(0.0, 0.0, 0.0); - Extent = 0.0; - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + get { - Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() - { - Mass = this.Mass, - Spin = this.Spin, - Substance = this.Substance, - Orientation = Quaternion.Identity, - Position = new Vector(0.0, 0.0, 0.0), - Velocity = new Vector(0.0, 0.0, 0.0) - }; - this.Substance.Update(Physics, Environment, Time, ref part); - return new _Transformed(new _Particle() - { - Mass = part.Mass, - Spin = part.Spin, - Substance = part.Substance - }, new Transform(part.Position, part.Velocity, part.Orientation)); + return null; } - - public FastPhysicsSubstance Substance; - public double Mass; - public AxisAngle Spin; } /// <summary> - /// Matter created by transforming some source matter. + /// Gets the gravity an object will feel towards a planet (and vice versa) when the object is at the given + /// offset in meters. /// </summary> - internal class _Transformed : FastPhysicsMatter + public Vector GetGravity(double PlanetMass, Vector Offset, double Mass) { - public _Transformed(FastPhysicsMatter Source, Transform Transform) - { - this.Source = Source; - this.Transform = Transform; - } - - public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) - { - return new _Transformed(this.Source, this.Transform.Apply(Transform)); - } - - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); - this.Source._GetUsed(Elements); - } - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - this.Source._GetParticles(this.Transform.Apply(Transform), Particles); - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - this.Source.GetMass(out Mass, out CenterOfMass, out Extent); - CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); - } - - public FastPhysicsMatter Source; - public Transform Transform; + double sqrlen = Offset.SquareLength; + return Offset * (-this._G * (PlanetMass + Mass) / (sqrlen * Math.Sqrt(sqrlen))); } /// <summary> - /// Matter created by the combination of some untransformed matter and some - /// transformed matter. + /// Gets the strength in newtons of the gravity force between the two objects. Note that negatives indicate attraction and positives repulsion. /// </summary> - internal class _Binary : FastPhysicsMatter + public double GetGravityStrength(double MassA, double MassB, double Distance) { - public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) - { - this.A = A; - this.B = B; - this.AToB = AToB; - - double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); - double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); - this.Mass = amass + bmass; - this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); - - double alen = (acen - this.CenterOfMass).Length + aext; - double blen = (bcen - this.CenterOfMass).Length + bext; - this.Extent = Math.Max(alen, blen); - - A._Usages.Add(this); - if (A != B) - { - B._Usages.Add(this); - } - } - - public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, Environment, this.B.Apply(Physics, this.AToB)), Time); - FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, Environment, this.A).Apply(Physics, this.AToB.Inverse), Time); - return Combine(Physics, na, nb.Apply(Physics, this.AToB)); - } - - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) - { - Elements.Add(this); - this.A._GetUsed(Elements); - this.B._GetUsed(Elements); - } - - internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) - { - this.A._GetParticles(Transform, Particles); - this.B._GetParticles(this.AToB.Apply(Transform), Particles); - } - - public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) - { - Mass = this.Mass; - CenterOfMass = this.CenterOfMass; - Extent = this.Extent; - } - - public double Mass; - public Vector CenterOfMass; - public double Extent; - public FastPhysicsMatter A; - public FastPhysicsMatter B; - public Transform AToB; + return -this._G * (MassA + MassB) / (Distance * Distance); } - private UsageSet<_Binary> _Usages; - } - - /// <summary> - /// A substance in a fast physics system. - /// </summary> - public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> - { - private FastPhysicsSubstance() - { - this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); - } - - /// <summary> - /// The default (and currently only) possible substance. - /// </summary> - public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); - - public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) + public Vector GetGravity(FastPhysicsMatter Environment, Vector Position, double Mass) { - Particle.Velocity.Z -= Time; - Particle.Update(Time); + return Environment.GetGravity(this, Position, Mass, 0.0); } - public MatterDisparity GetDisparity( - FastPhysics Physics, FastPhysicsMatter Environment, - double OldMass, double NewMass, - ISubstance NewSubstance, - Vector DeltaPosition, - Vector DeltaVelocity, - Quaternion DeltaOrientation, - AxisAngle OldSpin, AxisAngle NewSpin) + public double GetMass(FastPhysicsMatter Matter) { - throw new NotImplementedException(); + double mass; Vector com; double extent; + Matter.GetMass(out mass, out com, out extent); + return mass; } - private UsageSet<FastPhysicsMatter._Particle> _Usages; + private double _G; } } \ No newline at end of file diff --git a/Alunite/FastPhysicsMatter.cs b/Alunite/FastPhysicsMatter.cs new file mode 100644 index 0000000..9513c90 --- /dev/null +++ b/Alunite/FastPhysicsMatter.cs @@ -0,0 +1,367 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Matter in a fast physics system. + /// </summary> + public abstract class FastPhysicsMatter : IMatter + { + private FastPhysicsMatter() + { + this._Usages = new UsageSet<_Binary>(); + } + + /// <summary> + /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to + /// describe it. + /// </summary> + public int Complexity + { + get + { + HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); + this._GetUsed(used); + return used.Count; + } + } + + /// <summary> + /// Gets the position of all the particles in this matter, for debug purposes. + /// </summary> + public IEnumerable<Particle<FastPhysicsSubstance>> Particles + { + get + { + List<Particle<FastPhysicsSubstance>> parts = new List<Particle<FastPhysicsSubstance>>(); + this._GetParticles(Transform.Identity, parts); + return parts; + } + } + + /// <summary> + /// Applies a transform to this matter. + /// </summary> + public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) + { + return new _Transformed(this, Transform); + } + + /// <summary> + /// Gets the updated form of this matter in the specified environment after the given time. + /// </summary> + public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); + + /// <summary> + /// Creates matter for a particle. + /// </summary> + public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) + { + return new _Transformed(_Particle.Default, new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); + } + + /// <summary> + /// Quickly creates a lattice with a power of two size of the specified object. + /// </summary> + public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) + { + // Get "major" spacing + Spacing = Spacing * Math.Pow(2.0, LogSize - 1); + + // Extract transform + _Transformed trans = Object as _Transformed; + if (trans != null) + { + Object = trans.Source; + return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); + } + else + { + return _CreateLattice(Physics, LogSize, Object, Spacing); + } + } + + private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) + { + if (LogSize <= 0) + { + return Object; + } + if (LogSize > 1) + { + Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); + } + _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); + _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); + _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); + return binc; + } + + /// <summary> + /// Combines two pieces of fast physics matter. + /// </summary> + public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) + { + if (A == null) + { + return B; + } + if (B == null) + { + return A; + } + + _Transformed atrans = A as _Transformed; + _Transformed btrans = B as _Transformed; + + Transform atob = Transform.Identity; + if (btrans != null) + { + atob = btrans.Transform; + B = btrans.Source; + } + + if (atrans != null) + { + return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); + } + else + { + return new _Binary(A, B, atob); + } + } + + /// <summary> + /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. + /// </summary> + public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); + + /// <summary> + /// Gets the force of gravity a particle at the specified offset and mass will feel from this matter. + /// </summary> + /// <param name="RecurseThreshold">The ratio of mass / (distance ^ 2) a piece of matter will have to have in order to have its + /// gravity force "refined". Set at 0.0 to get the exact gravity.</param> + public virtual Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return Physics.GetGravity(Physics.GetMass(this), Position, Mass); + } + + /// <summary> + /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including + /// this matter itself. + /// </summary> + internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + } + + /// <summary> + /// Adds all particles in this matter to the given list after applying the specified transform. + /// </summary> + internal virtual void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) + { + + } + + /// <summary> + /// Matter containing a single particle. + /// </summary> + internal class _Particle : FastPhysicsMatter + { + /// <summary> + /// Default particle. + /// </summary> + public static readonly _Particle Default = new _Particle() { Substance = FastPhysicsSubstance.Default, Mass = 1.0 }; + + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) + { + Particles.Add(new Particle<FastPhysicsSubstance>() + { + Mass = this.Mass, + Spin = this.Spin, + Substance = this.Substance, + Orientation = Transform.Rotation, + Position = Transform.Offset, + Velocity = Transform.VelocityOffset + }); + } + + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) + { + Mass = this.Mass; + CenterOfMass = new Vector(0.0, 0.0, 0.0); + Extent = 0.0; + } + + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() + { + Mass = this.Mass, + Spin = this.Spin, + Substance = this.Substance, + Orientation = Quaternion.Identity, + Position = new Vector(0.0, 0.0, 0.0), + Velocity = new Vector(0.0, 0.0, 0.0) + }; + this.Substance.Update(Physics, Environment, Time, ref part); + return new _Transformed(new _Particle() + { + Mass = part.Mass, + Spin = part.Spin, + Substance = part.Substance + }, new Transform(part.Position, part.Velocity, part.Orientation)); + } + + public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return Physics.GetGravity(this.Mass, Position, Mass); + } + + public FastPhysicsSubstance Substance; + public double Mass; + public AxisAngle Spin; + } + + /// <summary> + /// Matter created by transforming some source matter. + /// </summary> + internal class _Transformed : FastPhysicsMatter + { + public _Transformed(FastPhysicsMatter Source, Transform Transform) + { + this.Source = Source; + this.Transform = Transform; + } + + public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) + { + return new _Transformed(this.Source, this.Transform.Apply(Transform)); + } + + internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + this.Source._GetUsed(Elements); + } + + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) + { + this.Source._GetParticles(this.Transform.Apply(Transform), Particles); + } + + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) + { + this.Source.GetMass(out Mass, out CenterOfMass, out Extent); + CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); + } + + public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) + { + return this.Transform.ApplyToDirection(this.Source.GetGravity(Physics, this.Transform.Inverse.ApplyToDirection(Position), Mass, RecurseThreshold)); + } + + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); + } + + public FastPhysicsMatter Source; + public Transform Transform; + } + + /// <summary> + /// Matter created by the combination of some untransformed matter and some + /// transformed matter. + /// </summary> + internal class _Binary : FastPhysicsMatter + { + public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) + : this(A, B, AToB, true) + { + + } + + public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB, bool Reuse) + { + this.A = A; + this.B = B; + this.AToB = AToB; + + double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); + double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); + this.Mass = amass + bmass; + this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); + + double alen = (acen - this.CenterOfMass).Length + aext; + double blen = (bcen - this.CenterOfMass).Length + bext; + this.Extent = Math.Max(alen, blen); + + if (Reuse) + { + A._Usages.Add(this); + if (A != B) + { + B._Usages.Add(this); + } + } + } + + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, Environment, this.B.Apply(Physics, this.AToB)), Time); + FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, Environment, this.A).Apply(Physics, this.AToB.Inverse), Time); + return Combine(Physics, na, nb.Apply(Physics, this.AToB)); + } + + internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + this.A._GetUsed(Elements); + this.B._GetUsed(Elements); + } + + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) + { + this.A._GetParticles(Transform, Particles); + this.B._GetParticles(this.AToB.Apply(Transform), Particles); + } + + public override Vector GetGravity(FastPhysics Physics, Vector Position, double Mass, double RecurseThreshold) + { + Vector offset = Position - this.CenterOfMass; + double offsetlen = offset.Length; + + double rat = this.Mass / (offsetlen * offsetlen); + if (rat >= RecurseThreshold) + { + return + A.GetGravity(Physics, Position, Mass, RecurseThreshold) + + this.AToB.ApplyToDirection(B.GetGravity(Physics, this.AToB.Inverse.ApplyToDirection(Position), Mass, RecurseThreshold)); + } + else + { + return offset * (Physics.GetGravityStrength(this.Mass, Mass, offsetlen) / offsetlen); + } + } + + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) + { + Mass = this.Mass; + CenterOfMass = this.CenterOfMass; + Extent = this.Extent; + } + + public double Mass; + public Vector CenterOfMass; + public double Extent; + public FastPhysicsMatter A; + public FastPhysicsMatter B; + public Transform AToB; + } + + private UsageSet<_Binary> _Usages; + } +} \ No newline at end of file diff --git a/Alunite/FastPhysicsSubstance.cs b/Alunite/FastPhysicsSubstance.cs new file mode 100644 index 0000000..c15eaac --- /dev/null +++ b/Alunite/FastPhysicsSubstance.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// A substance in a fast physics system. + /// </summary> + public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> + { + private FastPhysicsSubstance() + { + this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); + } + + /// <summary> + /// The default (and currently only) possible substance. + /// </summary> + public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); + + public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) + { + Particle.Velocity.Z -= Time; + Particle.Update(Time); + } + + public MatterDisparity GetDisparity( + FastPhysics Physics, FastPhysicsMatter Environment, + double OldMass, double NewMass, + ISubstance NewSubstance, + Vector DeltaPosition, + Vector DeltaVelocity, + Quaternion DeltaOrientation, + AxisAngle OldSpin, AxisAngle NewSpin) + { + throw new NotImplementedException(); + } + + private UsageSet<FastPhysicsMatter._Particle> _Usages; + } +} \ No newline at end of file diff --git a/Alunite/Physics.cs b/Alunite/Physics.cs index b225d5b..d33cc19 100644 --- a/Alunite/Physics.cs +++ b/Alunite/Physics.cs @@ -1,103 +1,128 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> - TMatter Compose(IEnumerable<TMatter> Matter); + TMatter Compose(IEnumerable<TMatter> Elements); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } + /// <summary> + /// A physical system where all matter has a mass expressable in kilograms. + /// </summary> + public interface IMassPhysics<TMatter> : IPhysics<TMatter> + where TMatter : IMatter + { + /// <summary> + /// Gets the mass of the given matter. + /// </summary> + double GetMass(TMatter Matter); + } + + /// <summary> + /// A physical system where gravity (a force that affects all matter depending only on their mass) exists. Note that gravity must be + /// a force felt mutally by involved matter. + /// </summary> + public interface IGravitationalPhysics<TMatter> : ISpatialPhysics<TMatter>, IMassPhysics<TMatter> + where TMatter : IMatter + { + /// <summary> + /// Gets the gravity (meters / second ^ 2) a particle at the specified position and mass will feel if it was in the given environment. + /// </summary> + Vector GetGravity(TMatter Environment, Vector Position, double Mass); + } + /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Describes the difference between two pieces of matter. /// </summary> /// <remarks>The "simple matter disparity" does not take into account forces to external matter while the "complex matter disparity" does. Note that /// matter disparity is for the most part an approximation used for optimizations.</remarks> public struct MatterDisparity { public MatterDisparity(double Movement, double Translation, double Mass) { this.Movement = Movement; this.Translation = Translation; this.Mass = Mass; } /// <summary> /// Gets the matter disparity between two identical pieces of matter. /// </summary> public static MatterDisparity Identical { get { return new MatterDisparity(0.0, 0.0, 0.0); } } /// <summary> /// Gets the simple matter disparity between two particles. /// </summary> public static MatterDisparity BetweenParticles(double MassA, Vector PosA, Vector VelA, double MassB, Vector PosB, Vector VelB) { return new MatterDisparity( (MassA + MassB) * (VelA - VelB).Length, (MassA + MassB) * (PosA - PosB).Length, Math.Abs(MassA - MassB)); } /// <summary> /// The amount of mass, course deviation that would be caused if the compared pieces of matter were swapped in usage, measured in /// kilograms meters per second. Note that if this is for "complex matter disparity", this should take into account external /// matter and forces. /// </summary> public double Movement; /// <summary> /// The amount of mass that is immediately translated between the two compared pieces of matter, measured in kilogram meters. /// </summary> public double Translation; /// <summary> /// The difference in mass of the two compared pieces of matter measured in kilograms. /// </summary> public double Mass; } } \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs index 994d9d8..b134884 100644 --- a/Alunite/Transform.cs +++ b/Alunite/Transform.cs @@ -1,94 +1,102 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } public Transform(Vector Offset) { this.Offset = Offset; this.VelocityOffset = new Vector(0.0, 0.0, 0.0); this.Rotation = Quaternion.Identity; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } + /// <summary> + /// Applies this transform to a direction vector. + /// </summary> + public Vector ApplyToDirection(Vector Dir) + { + return this.Rotation.Rotate(Dir); + } + /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } /// <summary> /// Updates the state of this transform after the given amount of time in seconds. /// </summary> public Transform Update(double Time) { return new Transform(this.Offset + this.VelocityOffset * Time, this.VelocityOffset, this.Rotation); } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 11c3381..c3012c5 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,62 +1,64 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(FastPhysics Physics, FastPhysicsMatter World) { this._Physics = Physics; this._World = World; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); foreach (Particle<FastPhysicsSubstance> part in this._World.Particles) { GL.Vertex3(part.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { { FastPhysics phys = this._Physics; this._World = phys.Update(this._World, phys.Null, Time); + + Vector grav = this._Physics.GetGravity(this._World, new Vector(0.0, 0.0, 1.0), 100.0); } this._Time += Time * 0.2; } private FastPhysics _Physics; private FastPhysicsMatter _World; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
501442b86f7602bfcc4f6d2bdfb0c01c3de798f1
Actual movement
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index ed55492..de5492a 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,66 +1,69 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> - <ProductVersion>9.0.21022</ProductVersion> + <ProductVersion>9.0.30729</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="FastPhysics.cs" /> <Compile Include="MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="Transform.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> - <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> + <Reference Include="OpenTK, Version=1.0.0.201, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\OpenTKGUI\bin\Release\OpenTK.dll</HintPath> + </Reference> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 67ea23d..b4138ac 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,397 +1,406 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { if (Matter != null) { return Matter.Apply(this, Transform); } else { return null; } } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { throw new NotImplementedException(); } /// <summary> /// Combines two pieces of matter in a similar manner to Compose. /// </summary> public FastPhysicsMatter Combine(FastPhysicsMatter A, FastPhysicsMatter B) { return FastPhysicsMatter.Combine(this, A, B); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> - public IEnumerable<Vector> Particles + public IEnumerable<Particle<FastPhysicsSubstance>> Particles { get { - List<Vector> parts = new List<Vector>(); + List<Particle<FastPhysicsSubstance>> parts = new List<Particle<FastPhysicsSubstance>>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed(this, Transform); } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed(_Particle.Default, new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); } /// <summary> /// Quickly creates a lattice with a power of two size of the specified object. /// </summary> public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, LogSize - 1); // Extract transform _Transformed trans = Object as _Transformed; if (trans != null) { Object = trans.Source; return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); } else { return _CreateLattice(Physics, LogSize, Object, Spacing); } } private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) { if (LogSize <= 0) { return Object; } if (LogSize > 1) { Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); } _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); return binc; } /// <summary> /// Combines two pieces of fast physics matter. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { if (A == null) { return B; } if (B == null) { return A; } _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } if (atrans != null) { return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); } else { return new _Binary(A, B, atob); } } /// <summary> /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. /// </summary> public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> - internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) + internal virtual void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle() { Substance = FastPhysicsSubstance.Default, Mass = 1.0 }; - internal override void _GetParticles(Transform Transform, List<Vector> Particles) + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { - Particles.Add(Transform.Offset); + Particles.Add(new Particle<FastPhysicsSubstance>() + { + Mass = this.Mass, + Spin = this.Spin, + Substance = this.Substance, + Orientation = Transform.Rotation, + Position = Transform.Offset, + Velocity = Transform.VelocityOffset + }); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = new Vector(0.0, 0.0, 0.0); Extent = 0.0; } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() { Mass = this.Mass, Spin = this.Spin, Substance = this.Substance, Orientation = Quaternion.Identity, Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0) }; this.Substance.Update(Physics, Environment, Time, ref part); return new _Transformed(new _Particle() { Mass = part.Mass, Spin = part.Spin, Substance = part.Substance }, new Transform(part.Position, part.Velocity, part.Orientation)); } public FastPhysicsSubstance Substance; public double Mass; public AxisAngle Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public _Transformed(FastPhysicsMatter Source, Transform Transform) { this.Source = Source; this.Transform = Transform; } public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed(this.Source, this.Transform.Apply(Transform)); } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } - internal override void _GetParticles(Transform Transform, List<Vector> Particles) + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { this.Source.GetMass(out Mass, out CenterOfMass, out Extent); CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) { this.A = A; this.B = B; this.AToB = AToB; double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); this.Mass = amass + bmass; this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); double alen = (acen - this.CenterOfMass).Length + aext; double blen = (bcen - this.CenterOfMass).Length + bext; this.Extent = Math.Max(alen, blen); A._Usages.Add(this); if (A != B) { B._Usages.Add(this); } } public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, Environment, this.B.Apply(Physics, this.AToB)), Time); FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, Environment, this.A).Apply(Physics, this.AToB.Inverse), Time); return Combine(Physics, na, nb.Apply(Physics, this.AToB)); } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } - internal override void _GetParticles(Transform Transform, List<Vector> Particles) + internal override void _GetParticles(Transform Transform, List<Particle<FastPhysicsSubstance>> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = this.CenterOfMass; Extent = this.Extent; } public double Mass; public Vector CenterOfMass; public double Extent; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { + Particle.Velocity.Z -= Time; Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 23939ef..6113a98 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,46 +1,44 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world FastPhysics fp = new FastPhysics(); FastPhysicsMatter world = FastPhysicsMatter.CreateLattice(fp, 1, fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity }), 0.1); - world = world.Update(fp, fp.Null, 0.1); - HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; - hw.Control = new Visualizer(world.Particles); + hw.Control = new Visualizer(fp, world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 59305b3..11c3381 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,56 +1,62 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(IEnumerable<Vector> PointSetA) + public Visualizer(FastPhysics Physics, FastPhysicsMatter World) { - this._PointSetA = PointSetA; + this._Physics = Physics; + this._World = World; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); - foreach (Vector v in this._PointSetA) + foreach (Particle<FastPhysicsSubstance> part in this._World.Particles) { - GL.Vertex3(v); + GL.Vertex3(part.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { + { + FastPhysics phys = this._Physics; + this._World = phys.Update(this._World, phys.Null, Time); + } this._Time += Time * 0.2; } - private IEnumerable<Vector> _PointSetA; + private FastPhysics _Physics; + private FastPhysicsMatter _World; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
911e836a86c55f8f5c6071dbfbfedf1647c6eec2
"Updating"
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 7f635c2..67ea23d 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,330 +1,397 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { - return Matter.Apply(this, Transform); + if (Matter != null) + { + return Matter.Apply(this, Transform); + } + else + { + return null; + } } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { throw new NotImplementedException(); } + /// <summary> + /// Combines two pieces of matter in a similar manner to Compose. + /// </summary> + public FastPhysicsMatter Combine(FastPhysicsMatter A, FastPhysicsMatter B) + { + return FastPhysicsMatter.Combine(this, A, B); + } + public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Vector> Particles { get { List<Vector> parts = new List<Vector>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { - return new _Transformed() - { - Source = this, - Transform = Transform - }; + return new _Transformed(this, Transform); } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> - public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) - { - return null; - } + public abstract FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time); /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { - return new _Transformed() - { - Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), - Source = /*new _Particle() - { - Mass = Particle.Mass, - Spin = Particle.Spin, - Substance = Particle.Substance - }*/ _Particle.Default - }; + return new _Transformed(_Particle.Default, new Transform(Particle.Position, Particle.Velocity, Particle.Orientation)); } /// <summary> /// Quickly creates a lattice with a power of two size of the specified object. /// </summary> public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, LogSize - 1); // Extract transform _Transformed trans = Object as _Transformed; if (trans != null) { Object = trans.Source; return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); } else { return _CreateLattice(Physics, LogSize, Object, Spacing); } } private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) { if (LogSize <= 0) { return Object; } if (LogSize > 1) { Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); } _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); return binc; } + /// <summary> + /// Combines two pieces of fast physics matter. + /// </summary> + public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) + { + if (A == null) + { + return B; + } + if (B == null) + { + return A; + } + + _Transformed atrans = A as _Transformed; + _Transformed btrans = B as _Transformed; + + Transform atob = Transform.Identity; + if (btrans != null) + { + atob = btrans.Transform; + B = btrans.Source; + } + + if (atrans != null) + { + return new _Binary(atrans.Source, B, atob.Apply(atrans.Transform.Inverse)).Apply(Physics, atrans.Transform); + } + else + { + return new _Binary(A, B, atob); + } + } + /// <summary> /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. /// </summary> public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> - public static readonly _Particle Default = new _Particle() { Mass = 1.0 }; + public static readonly _Particle Default = new _Particle() { Substance = FastPhysicsSubstance.Default, Mass = 1.0 }; internal override void _GetParticles(Transform Transform, List<Vector> Particles) { Particles.Add(Transform.Offset); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = new Vector(0.0, 0.0, 0.0); Extent = 0.0; } - public ISubstance Substance; + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + Particle<FastPhysicsSubstance> part = new Particle<FastPhysicsSubstance>() + { + Mass = this.Mass, + Spin = this.Spin, + Substance = this.Substance, + Orientation = Quaternion.Identity, + Position = new Vector(0.0, 0.0, 0.0), + Velocity = new Vector(0.0, 0.0, 0.0) + }; + this.Substance.Update(Physics, Environment, Time, ref part); + return new _Transformed(new _Particle() + { + Mass = part.Mass, + Spin = part.Spin, + Substance = part.Substance + }, new Transform(part.Position, part.Velocity, part.Orientation)); + } + + public FastPhysicsSubstance Substance; public double Mass; - public Quaternion Spin; + public AxisAngle Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { + public _Transformed(FastPhysicsMatter Source, Transform Transform) + { + this.Source = Source; + this.Transform = Transform; + } + public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { - return new _Transformed() - { - Source = this.Source, - Transform = Transform.ApplyTo(this.Transform) - }; + return new _Transformed(this.Source, this.Transform.Apply(Transform)); } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { this.Source.GetMass(out Mass, out CenterOfMass, out Extent); CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); } + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + return Physics.Transform(this.Source.Update(Physics, Physics.Transform(Environment, this.Transform.Inverse), Time), this.Transform.Update(Time)); + } + public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) { this.A = A; this.B = B; this.AToB = AToB; double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); this.Mass = amass + bmass; this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); double alen = (acen - this.CenterOfMass).Length + aext; double blen = (bcen - this.CenterOfMass).Length + bext; this.Extent = Math.Max(alen, blen); A._Usages.Add(this); if (A != B) { B._Usages.Add(this); } } + public override FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + FastPhysicsMatter na = this.A.Update(Physics, Combine(Physics, Environment, this.B.Apply(Physics, this.AToB)), Time); + FastPhysicsMatter nb = this.B.Update(Physics, Combine(Physics, Environment, this.A).Apply(Physics, this.AToB.Inverse), Time); + return Combine(Physics, na, nb.Apply(Physics, this.AToB)); + } + internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { Mass = this.Mass; CenterOfMass = this.CenterOfMass; Extent = this.Extent; } public double Mass; public Vector CenterOfMass; public double Extent; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 04748d8..23939ef 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,44 +1,46 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world FastPhysics fp = new FastPhysics(); - FastPhysicsMatter world = FastPhysicsMatter.CreateLattice(fp, 4, fp.Create(new Particle<FastPhysicsSubstance>() + FastPhysicsMatter world = FastPhysicsMatter.CreateLattice(fp, 1, fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity }), 0.1); + world = world.Update(fp, fp.Null, 0.1); + HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world.Particles); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs index 83b662e..994d9d8 100644 --- a/Alunite/Transform.cs +++ b/Alunite/Transform.cs @@ -1,87 +1,94 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } public Transform(Vector Offset) { this.Offset = Offset; this.VelocityOffset = new Vector(0.0, 0.0, 0.0); this.Rotation = Quaternion.Identity; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } + /// <summary> + /// Updates the state of this transform after the given amount of time in seconds. + /// </summary> + public Transform Update(double Time) + { + return new Transform(this.Offset + this.VelocityOffset * Time, this.VelocityOffset, this.Rotation); + } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file
dzamkov/Alunite-old
ecbf1e0e4ec7cd5bd74500cb44883ed1e2e47851
Sensical alternative to bounding spheres
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 0b6476e..7f635c2 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,327 +1,330 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { throw new NotImplementedException(); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Vector> Particles { get { List<Vector> parts = new List<Vector>(); this._GetParticles(Transform.Identity, parts); return parts; } } - - - /// <summary> - /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not - /// have any correlation to where the matter can apply force. - /// </summary> - public abstract void GetBoundingSphere(out Vector Position, out double Radius); - /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Quickly creates a lattice with a power of two size of the specified object. /// </summary> public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, LogSize - 1); // Extract transform _Transformed trans = Object as _Transformed; if (trans != null) { Object = trans.Source; return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); } else { return _CreateLattice(Physics, LogSize, Object, Spacing); } } private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) { if (LogSize <= 0) { return Object; } if (LogSize > 1) { Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); } - _Binary bina = _Combine(Physics, Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); - _Binary binb = _Combine(Physics, bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); - _Binary binc = _Combine(Physics, binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); + _Binary bina = new _Binary(Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); + _Binary binb = new _Binary(bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); + _Binary binc = new _Binary(binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); return binc; } /// <summary> - /// Combines two "bits" of matter into one without searching through cached compounds. + /// Gets the mass, center of mass, and extent (distance from the center of mass to the farthest piece of matter) for this matter. /// </summary> - private static FastPhysicsMatter._Binary _Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) - { - FastPhysicsMatter._Binary bin = new _Binary() - { - A = A, - B = B, - AToB = AToB - }; - A._Usages.Add(bin); - if (A != B) - { - B._Usages.Add(bin); - } - return bin; - } + public abstract void GetMass(out double Mass, out Vector CenterOfMass, out double Extent); /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> - public static readonly _Particle Default = new _Particle(); + public static readonly _Particle Default = new _Particle() { Mass = 1.0 }; - public override void GetBoundingSphere(out Vector Position, out double Radius) + internal override void _GetParticles(Transform Transform, List<Vector> Particles) { - Position = new Vector(0.0, 0.0, 0.0); - Radius = 0.0; + Particles.Add(Transform.Offset); } - internal override void _GetParticles(Transform Transform, List<Vector> Particles) + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) { - Particles.Add(Transform.Offset); + Mass = this.Mass; + CenterOfMass = new Vector(0.0, 0.0, 0.0); + Extent = 0.0; } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } - public override void GetBoundingSphere(out Vector Position, out double Radius) - { - Source.GetBoundingSphere(out Position, out Radius); - Position = Transform.Offset + Transform.Rotation.Rotate(Position); - } - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) + { + this.Source.GetMass(out Mass, out CenterOfMass, out Extent); + CenterOfMass = this.Transform.ApplyToOffset(CenterOfMass); + } + public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { - public override void GetBoundingSphere(out Vector Position, out double Radius) + public _Binary(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) { - Position = this.BoundCenter; - Radius = this.BoundRadius; + this.A = A; + this.B = B; + this.AToB = AToB; + + double amass; Vector acen; double aext; A.GetMass(out amass, out acen, out aext); + double bmass; Vector bcen; double bext; B.GetMass(out bmass, out bcen, out bext); bcen = this.AToB.ApplyToOffset(bcen); + this.Mass = amass + bmass; + this.CenterOfMass = acen * (amass / this.Mass) + bcen * (bmass / this.Mass); + + double alen = (acen - this.CenterOfMass).Length + aext; + double blen = (bcen - this.CenterOfMass).Length + bext; + this.Extent = Math.Max(alen, blen); + + A._Usages.Add(this); + if (A != B) + { + B._Usages.Add(this); + } } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } - public Vector BoundCenter; - public double BoundRadius; + public override void GetMass(out double Mass, out Vector CenterOfMass, out double Extent) + { + Mass = this.Mass; + CenterOfMass = this.CenterOfMass; + Extent = this.Extent; + } + + public double Mass; + public Vector CenterOfMass; + public double Extent; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file
dzamkov/Alunite-old
045dd2c8a98b59bd7fba8a221b93721709769d95
Removed the current atrocity of combining matter, something else will have to be done
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 0bd0a25..0b6476e 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,498 +1,327 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { - return new FastPhysicsMatter._SphereTree(this).Create(Matter); + throw new NotImplementedException(); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Vector> Particles { get { List<Vector> parts = new List<Vector>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Quickly creates a lattice with a power of two size of the specified object. /// </summary> public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) { // Get "major" spacing Spacing = Spacing * Math.Pow(2.0, LogSize - 1); // Extract transform _Transformed trans = Object as _Transformed; if (trans != null) { Object = trans.Source; return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); } else { return _CreateLattice(Physics, LogSize, Object, Spacing); } } private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) { if (LogSize <= 0) { return Object; } if (LogSize > 1) { Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); } - _Binary bina = _QuickCombine(Physics, Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); - _Binary binb = _QuickCombine(Physics, bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); - _Binary binc = _QuickCombine(Physics, binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); + _Binary bina = _Combine(Physics, Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); + _Binary binb = _Combine(Physics, bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); + _Binary binc = _Combine(Physics, binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); return binc; } /// <summary> /// Combines two "bits" of matter into one without searching through cached compounds. /// </summary> - private static FastPhysicsMatter._Binary _QuickCombine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) + private static FastPhysicsMatter._Binary _Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) { FastPhysicsMatter._Binary bin = new _Binary() { A = A, B = B, AToB = AToB }; - Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); - Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = AToB.ApplyToOffset(posb); - SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); A._Usages.Add(bin); if (A != B) { B._Usages.Add(bin); } return bin; } - /// <summary> - /// Combines two "bits" of matter into one. - /// </summary> - public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) - { - // Untransform - _Transformed atrans = A as _Transformed; - _Transformed btrans = B as _Transformed; - Transform atob = Transform.Identity; - if (btrans != null) - { - atob = btrans.Transform; - B = btrans.Source; - } - Transform? full = null; - if (atrans != null) - { - Transform fullval = atrans.Transform; - full = fullval; - atob = atob.Apply(fullval.Inverse); - A = atrans.Source; - } - - // Check usages of elements to see if this binary matter already exists - FastPhysicsMatter res = null; - UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; - foreach (var ind in usages.Usages) - { - Transform dfull; - _Binary testbin = ind.Value; - if (testbin.A == A && testbin.B == B) - { - if (_TryMatch(A, B, atob, testbin.AToB, out dfull)) - { - res = testbin; - usages.Accept(ind); - if(full != null) - { - full = full.Value.ApplyTo(dfull); - } - else - { - full = dfull; - } - break; - } - } - if (testbin.B == A && testbin.A == B) - { - Transform natob = atob.Inverse; - if (_TryMatch(B, A, natob, testbin.AToB, out dfull)) - { - res = testbin; - usages.Accept(ind); - - // Since the elements are swapped, correct transforms - if (full != null) - { - full = full.Value.Apply(atob).ApplyTo(dfull); - } - else - { - full = atob.ApplyTo(dfull); - } - break; - } - } - } - - // Create binary matter - if (res == null) - { - res = _QuickCombine(Physics, A, B, atob); - } - - - // Retransform (if needed) - if (full != null) - { - res = new _Transformed() - { - Source = res, - Transform = full.Value - }; - } - return res; - } - - /// <summary> - /// Compares two binary matter with the same elements to and sees if the "Candiate" binary matter can be used in place of the "Current" binary matter, and if - /// so, gets the additional transform (to be applied to the binary matter) needed. - /// </summary> - private static bool _TryMatch(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToBCurrent, Transform AToBCanidate, out Transform Full) - { - // Find circumcenter vectors - Vector bbpos; double bbrad; B.GetBoundingSphere(out bbpos, out bbrad); - Vector curvec = AToBCurrent.ApplyToOffset(bbpos); double curvecdis = curvec.Length; - Vector canvec = AToBCanidate.ApplyToOffset(bbpos); double canvecdis = canvec.Length; - curvec *= 1.0 / curvecdis; - canvec *= 1.0 / canvecdis; - - // Check if the distances are anywhere near each other. - if (Math.Abs(Math.Sqrt(curvecdis) - Math.Sqrt(canvecdis)) < 0.0001 && A is _Particle && B is _Particle) - { - // Orient the current matter to the candiate matter - Quaternion ort = Quaternion.AngleBetween(canvec, curvec); - Full = new Transform(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), ort); - return true; - } - - Full = Transform.Identity; - return false; - } - - /// <summary> - /// A sphere tree for matter. - /// </summary> - internal class _SphereTree : SphereTree<FastPhysicsMatter> - { - public _SphereTree(FastPhysics Physics) - { - this._Physics = Physics; - } - - public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) - { - return Combine(this._Physics, A, B); - } - - public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) - { - Node.GetBoundingSphere(out Position, out Radius); - } - - public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) - { - return Node._GetSubnodes(this._Physics, ref A, ref B); - } - - private FastPhysics _Physics; - } - - /// <summary> - /// Gets the subnodes for this node for use in a sphere tree. - /// </summary> - internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) - { - return false; - } - /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { Particles.Add(Transform.Offset); } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } - internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) - { - if (this.Source._GetSubnodes(Physics, ref A, ref B)) - { - A = A.Apply(Physics, this.Transform); - B = B.Apply(Physics, this.Transform); - return true; - } - return false; - } - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } - internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) - { - A = this.A; - B = this.B.Apply(Physics, this.AToB); - return true; - } - internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file
dzamkov/Alunite-old
00e27bd5c334296461dae436b277e645c1f785da
Extremely memory-efficent lattice
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index ad2658f..0bd0a25 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,450 +1,498 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Vector> Particles { get { List<Vector> parts = new List<Vector>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } + /// <summary> + /// Quickly creates a lattice with a power of two size of the specified object. + /// </summary> + public static FastPhysicsMatter CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double Spacing) + { + // Get "major" spacing + Spacing = Spacing * Math.Pow(2.0, LogSize - 1); + + // Extract transform + _Transformed trans = Object as _Transformed; + if (trans != null) + { + Object = trans.Source; + return _CreateLattice(Physics, LogSize, Object, Spacing).Apply(Physics, trans.Transform); + } + else + { + return _CreateLattice(Physics, LogSize, Object, Spacing); + } + } + + private static FastPhysicsMatter _CreateLattice(FastPhysics Physics, int LogSize, FastPhysicsMatter Object, double MajorSpacing) + { + if (LogSize <= 0) + { + return Object; + } + if (LogSize > 1) + { + Object = _CreateLattice(Physics, LogSize - 1, Object, MajorSpacing * 0.5); + } + _Binary bina = _QuickCombine(Physics, Object, Object, new Transform(new Vector(MajorSpacing, 0.0, 0.0))); + _Binary binb = _QuickCombine(Physics, bina, bina, new Transform(new Vector(0.0, MajorSpacing, 0.0))); + _Binary binc = _QuickCombine(Physics, binb, binb, new Transform(new Vector(0.0, 0.0, MajorSpacing))); + return binc; + } + + /// <summary> + /// Combines two "bits" of matter into one without searching through cached compounds. + /// </summary> + private static FastPhysicsMatter._Binary _QuickCombine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B, Transform AToB) + { + FastPhysicsMatter._Binary bin = new _Binary() + { + A = A, + B = B, + AToB = AToB + }; + Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); + Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = AToB.ApplyToOffset(posb); + SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); + A._Usages.Add(bin); + if (A != B) + { + B._Usages.Add(bin); + } + return bin; + } + /// <summary> /// Combines two "bits" of matter into one. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { // Untransform _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } Transform? full = null; if (atrans != null) { Transform fullval = atrans.Transform; full = fullval; atob = atob.Apply(fullval.Inverse); A = atrans.Source; } // Check usages of elements to see if this binary matter already exists FastPhysicsMatter res = null; UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; foreach (var ind in usages.Usages) { Transform dfull; _Binary testbin = ind.Value; if (testbin.A == A && testbin.B == B) { if (_TryMatch(A, B, atob, testbin.AToB, out dfull)) { res = testbin; usages.Accept(ind); if(full != null) { full = full.Value.ApplyTo(dfull); } else { full = dfull; } break; } } if (testbin.B == A && testbin.A == B) { Transform natob = atob.Inverse; if (_TryMatch(B, A, natob, testbin.AToB, out dfull)) { res = testbin; usages.Accept(ind); // Since the elements are swapped, correct transforms if (full != null) { full = full.Value.Apply(atob).ApplyTo(dfull); } else { full = atob.ApplyTo(dfull); } break; } } } // Create binary matter if (res == null) { - FastPhysicsMatter._Binary bin = new _Binary() - { - A = A, - B = B, - AToB = atob - }; - res = bin; - Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); - Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); - SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); - A._Usages.Add(bin); - B._Usages.Add(bin); + res = _QuickCombine(Physics, A, B, atob); } // Retransform (if needed) if (full != null) { res = new _Transformed() { Source = res, Transform = full.Value }; } return res; } /// <summary> /// Compares two binary matter with the same elements to and sees if the "Candiate" binary matter can be used in place of the "Current" binary matter, and if /// so, gets the additional transform (to be applied to the binary matter) needed. /// </summary> private static bool _TryMatch(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToBCurrent, Transform AToBCanidate, out Transform Full) { // Find circumcenter vectors Vector bbpos; double bbrad; B.GetBoundingSphere(out bbpos, out bbrad); Vector curvec = AToBCurrent.ApplyToOffset(bbpos); double curvecdis = curvec.Length; Vector canvec = AToBCanidate.ApplyToOffset(bbpos); double canvecdis = canvec.Length; curvec *= 1.0 / curvecdis; canvec *= 1.0 / canvecdis; // Check if the distances are anywhere near each other. if (Math.Abs(Math.Sqrt(curvecdis) - Math.Sqrt(canvecdis)) < 0.0001 && A is _Particle && B is _Particle) { // Orient the current matter to the candiate matter Quaternion ort = Quaternion.AngleBetween(canvec, curvec); Full = new Transform(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), ort); return true; } Full = Transform.Identity; return false; } /// <summary> /// A sphere tree for matter. /// </summary> internal class _SphereTree : SphereTree<FastPhysicsMatter> { public _SphereTree(FastPhysics Physics) { this._Physics = Physics; } public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) { return Combine(this._Physics, A, B); } public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) { Node.GetBoundingSphere(out Position, out Radius); } public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return Node._GetSubnodes(this._Physics, ref A, ref B); } private FastPhysics _Physics; } /// <summary> /// Gets the subnodes for this node for use in a sphere tree. /// </summary> internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return false; } /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { Particles.Add(Transform.Offset); } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { if (this.Source._GetSubnodes(Physics, ref A, ref B)) { A = A.Apply(Physics, this.Transform); B = B.Apply(Physics, this.Transform); return true; } return false; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { A = this.A; B = this.B.Apply(Physics, this.AToB); return true; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index fcf6631..04748d8 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,59 +1,44 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world FastPhysics fp = new FastPhysics(); - List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); - Random r = new Random(2); - List<Vector> pointset = new List<Vector>(); - for(double x = 0.05; x < 1.0; x += 0.1) - { - for (double y = 0.05; y < 1.0; y += 0.1) - { - for (double z = 0.05; z < 1.0; z += 0.1) - { - Vector pos = new Vector(x + r.NextDouble() * 0.001, y + r.NextDouble() * 0.001, z + r.NextDouble() * 0.001); - elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() + FastPhysicsMatter world = FastPhysicsMatter.CreateLattice(fp, 4, fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, - Position = pos, + Position = new Vector(0.0, 0.0, 0.0), Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity - })); - pointset.Add(pos); - } - } - } - FastPhysicsMatter world = fp.Compose(elems); + }), 0.1); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; - hw.Control = new Visualizer(world.Particles, pointset); + hw.Control = new Visualizer(world.Particles); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs index b8cbfe4..83b662e 100644 --- a/Alunite/Transform.cs +++ b/Alunite/Transform.cs @@ -1,80 +1,87 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } + public Transform(Vector Offset) + { + this.Offset = Offset; + this.VelocityOffset = new Vector(0.0, 0.0, 0.0); + this.Rotation = Quaternion.Identity; + } + /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 4330b3b..59305b3 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,63 +1,56 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { - public Visualizer(IEnumerable<Vector> PointSetA, IEnumerable<Vector> PointSetB) + public Visualizer(IEnumerable<Vector> PointSetA) { this._PointSetA = PointSetA; - this._PointSetB = PointSetB; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); GL.Color4(Color.RGB(0.0, 0.5, 1.0)); foreach (Vector v in this._PointSetA) { GL.Vertex3(v); } - GL.Color4(Color.RGB(1.0, 0.5, 0.0)); - foreach (Vector v in this._PointSetB) - { - GL.Vertex3(v); - } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { this._Time += Time * 0.2; } private IEnumerable<Vector> _PointSetA; - private IEnumerable<Vector> _PointSetB; private double _Time; } } \ No newline at end of file
dzamkov/Alunite-old
03c1046e71960994e3744529baaec84d5992fc80
Put transform in its own file
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 113235e..ed55492 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,65 +1,66 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="FastPhysics.cs" /> <Compile Include="MatchMatrix.cs" /> <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="SphereTree.cs" /> + <Compile Include="Transform.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index ce13b8d..ad2658f 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,450 +1,450 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the position of all the particles in this matter, for debug purposes. /// </summary> public IEnumerable<Vector> Particles { get { List<Vector> parts = new List<Vector>(); this._GetParticles(Transform.Identity, parts); return parts; } } /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Combines two "bits" of matter into one. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { // Untransform _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } Transform? full = null; if (atrans != null) { Transform fullval = atrans.Transform; full = fullval; atob = atob.Apply(fullval.Inverse); A = atrans.Source; } // Check usages of elements to see if this binary matter already exists FastPhysicsMatter res = null; UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; foreach (var ind in usages.Usages) { Transform dfull; _Binary testbin = ind.Value; if (testbin.A == A && testbin.B == B) { if (_TryMatch(A, B, atob, testbin.AToB, out dfull)) { res = testbin; usages.Accept(ind); if(full != null) { full = full.Value.ApplyTo(dfull); } else { full = dfull; } break; } } if (testbin.B == A && testbin.A == B) { Transform natob = atob.Inverse; if (_TryMatch(B, A, natob, testbin.AToB, out dfull)) { res = testbin; usages.Accept(ind); // Since the elements are swapped, correct transforms if (full != null) { full = full.Value.Apply(atob).ApplyTo(dfull); } else { full = atob.ApplyTo(dfull); } break; } } } // Create binary matter if (res == null) { FastPhysicsMatter._Binary bin = new _Binary() { A = A, B = B, AToB = atob }; res = bin; Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); A._Usages.Add(bin); B._Usages.Add(bin); } // Retransform (if needed) if (full != null) { res = new _Transformed() { Source = res, Transform = full.Value }; } return res; } /// <summary> /// Compares two binary matter with the same elements to and sees if the "Candiate" binary matter can be used in place of the "Current" binary matter, and if /// so, gets the additional transform (to be applied to the binary matter) needed. /// </summary> private static bool _TryMatch(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToBCurrent, Transform AToBCanidate, out Transform Full) { // Find circumcenter vectors Vector bbpos; double bbrad; B.GetBoundingSphere(out bbpos, out bbrad); Vector curvec = AToBCurrent.ApplyToOffset(bbpos); double curvecdis = curvec.Length; Vector canvec = AToBCanidate.ApplyToOffset(bbpos); double canvecdis = canvec.Length; curvec *= 1.0 / curvecdis; canvec *= 1.0 / canvecdis; // Check if the distances are anywhere near each other. if (Math.Abs(Math.Sqrt(curvecdis) - Math.Sqrt(canvecdis)) < 0.0001 && A is _Particle && B is _Particle) { // Orient the current matter to the candiate matter Quaternion ort = Quaternion.AngleBetween(canvec, curvec); Full = new Transform(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), ort); return true; } Full = Transform.Identity; return false; } /// <summary> /// A sphere tree for matter. /// </summary> internal class _SphereTree : SphereTree<FastPhysicsMatter> { public _SphereTree(FastPhysics Physics) { this._Physics = Physics; } public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) { return Combine(this._Physics, A, B); } public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) { Node.GetBoundingSphere(out Position, out Radius); } public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return Node._GetSubnodes(this._Physics, ref A, ref B); } private FastPhysics _Physics; } /// <summary> /// Gets the subnodes for this node for use in a sphere tree. /// </summary> internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return false; } /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Adds all particles in this matter to the given list after applying the specified transform. /// </summary> internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) { } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { Particles.Add(Transform.Offset); } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { if (this.Source._GetSubnodes(Physics, ref A, ref B)) { A = A.Apply(Physics, this.Transform); B = B.Apply(Physics, this.Transform); return true; } return false; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { - this.Source._GetParticles(Transform.ApplyTo(this.Transform), Particles); + this.Source._GetParticles(this.Transform.Apply(Transform), Particles); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { A = this.A; B = this.B.Apply(Physics, this.AToB); return true; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } internal override void _GetParticles(Transform Transform, List<Vector> Particles) { this.A._GetParticles(Transform, Particles); this.B._GetParticles(this.AToB.Apply(Transform), Particles); } public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Physics.cs b/Alunite/Physics.cs index 7a1f788..b225d5b 100644 --- a/Alunite/Physics.cs +++ b/Alunite/Physics.cs @@ -1,177 +1,103 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Describes the difference between two pieces of matter. /// </summary> /// <remarks>The "simple matter disparity" does not take into account forces to external matter while the "complex matter disparity" does. Note that /// matter disparity is for the most part an approximation used for optimizations.</remarks> public struct MatterDisparity { public MatterDisparity(double Movement, double Translation, double Mass) { this.Movement = Movement; this.Translation = Translation; this.Mass = Mass; } /// <summary> /// Gets the matter disparity between two identical pieces of matter. /// </summary> public static MatterDisparity Identical { get { return new MatterDisparity(0.0, 0.0, 0.0); } } /// <summary> /// Gets the simple matter disparity between two particles. /// </summary> public static MatterDisparity BetweenParticles(double MassA, Vector PosA, Vector VelA, double MassB, Vector PosB, Vector VelB) { return new MatterDisparity( (MassA + MassB) * (VelA - VelB).Length, (MassA + MassB) * (PosA - PosB).Length, Math.Abs(MassA - MassB)); } /// <summary> /// The amount of mass, course deviation that would be caused if the compared pieces of matter were swapped in usage, measured in /// kilograms meters per second. Note that if this is for "complex matter disparity", this should take into account external /// matter and forces. /// </summary> public double Movement; /// <summary> /// The amount of mass that is immediately translated between the two compared pieces of matter, measured in kilogram meters. /// </summary> public double Translation; /// <summary> /// The difference in mass of the two compared pieces of matter measured in kilograms. /// </summary> public double Mass; } - - /// <summary> - /// Represents a possible the orientation, translation and velocity offset for matter. - /// </summary> - public struct Transform - { - public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) - { - this.Offset = Offset; - this.VelocityOffset = VelocityOffset; - this.Rotation = Rotation; - } - - /// <summary> - /// Applies this transform to another, in effect combining them. - /// </summary> - public Transform ApplyTo(Transform Transform) - { - return new Transform( - this.Offset + this.Rotation.Rotate(Transform.Offset), - this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), - this.Rotation.ApplyTo(Transform.Rotation)); - } - - /// <summary> - /// Applies this transform to an offset vector. - /// </summary> - public Vector ApplyToOffset(Vector Offset) - { - return this.Offset + this.Rotation.Rotate(Offset); - } - - /// <summary> - /// Applies a transform to this transform. - /// </summary> - public Transform Apply(Transform Transform) - { - return Transform.ApplyTo(this); - } - - /// <summary> - /// Gets the inverse of this transform. - /// </summary> - public Transform Inverse - { - get - { - Quaternion nrot = this.Rotation.Conjugate; - return new Transform( - nrot.Rotate(-this.Offset), - nrot.Rotate(-this.VelocityOffset), - nrot); - } - } - - /// <summary> - /// Gets the identity transform. - /// </summary> - public static Transform Identity - { - get - { - return new Transform( - new Vector(0.0, 0.0, 0.0), - new Vector(0.0, 0.0, 0.0), - Quaternion.Identity); - } - } - - - public Vector Offset; - public Vector VelocityOffset; - public Quaternion Rotation; - } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index f5cdec7..fcf6631 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,53 +1,59 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform testa = new Transform( new Vector(1.0, 0.5, 0.3), new Vector(1.0, 0.5, 0.3), Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); testa = testa.ApplyTo(testa.Inverse); // Set up a world FastPhysics fp = new FastPhysics(); List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); Random r = new Random(2); List<Vector> pointset = new List<Vector>(); - for(int t = 0; t < 1000; t++) + for(double x = 0.05; x < 1.0; x += 0.1) { - Vector pos = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()); - elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() + for (double y = 0.05; y < 1.0; y += 0.1) { - Substance = FastPhysicsSubstance.Default, - Mass = 1.0, - Position = pos, - Velocity = new Vector(0.0, 0.0, 0.0), - Orientation = Quaternion.Identity, - Spin = AxisAngle.Identity - })); - pointset.Add(pos); + for (double z = 0.05; z < 1.0; z += 0.1) + { + Vector pos = new Vector(x + r.NextDouble() * 0.001, y + r.NextDouble() * 0.001, z + r.NextDouble() * 0.001); + elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() + { + Substance = FastPhysicsSubstance.Default, + Mass = 1.0, + Position = pos, + Velocity = new Vector(0.0, 0.0, 0.0), + Orientation = Quaternion.Identity, + Spin = AxisAngle.Identity + })); + pointset.Add(pos); + } + } } FastPhysicsMatter world = fp.Compose(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world.Particles, pointset); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Transform.cs b/Alunite/Transform.cs new file mode 100644 index 0000000..b8cbfe4 --- /dev/null +++ b/Alunite/Transform.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Represents a possible the orientation, translation and velocity offset for matter. + /// </summary> + public struct Transform + { + public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) + { + this.Offset = Offset; + this.VelocityOffset = VelocityOffset; + this.Rotation = Rotation; + } + + /// <summary> + /// Applies this transform to another, in effect combining them. + /// </summary> + public Transform ApplyTo(Transform Transform) + { + return new Transform( + this.Offset + this.Rotation.Rotate(Transform.Offset), + this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), + this.Rotation.ApplyTo(Transform.Rotation)); + } + + /// <summary> + /// Applies this transform to an offset vector. + /// </summary> + public Vector ApplyToOffset(Vector Offset) + { + return this.Offset + this.Rotation.Rotate(Offset); + } + + /// <summary> + /// Applies a transform to this transform. + /// </summary> + public Transform Apply(Transform Transform) + { + return Transform.ApplyTo(this); + } + + /// <summary> + /// Gets the inverse of this transform. + /// </summary> + public Transform Inverse + { + get + { + Quaternion nrot = this.Rotation.Conjugate; + return new Transform( + nrot.Rotate(-this.Offset), + nrot.Rotate(-this.VelocityOffset), + nrot); + } + } + + /// <summary> + /// Gets the identity transform. + /// </summary> + public static Transform Identity + { + get + { + return new Transform( + new Vector(0.0, 0.0, 0.0), + new Vector(0.0, 0.0, 0.0), + Quaternion.Identity); + } + } + + + public Vector Offset; + public Vector VelocityOffset; + public Quaternion Rotation; + } +} \ No newline at end of file
dzamkov/Alunite-old
4d2075503e74c9cb238a918f5df16710c7e3b7fc
Rotational symmetry detected for binary compounds of two points
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 7c67d57..ce13b8d 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,377 +1,450 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } + /// <summary> + /// Gets the position of all the particles in this matter, for debug purposes. + /// </summary> + public IEnumerable<Vector> Particles + { + get + { + List<Vector> parts = new List<Vector>(); + this._GetParticles(Transform.Identity, parts); + return parts; + } + } + + + /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Combines two "bits" of matter into one. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { // Untransform _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } Transform? full = null; if (atrans != null) { Transform fullval = atrans.Transform; - full = fullval = atrans.Transform; + full = fullval; atob = atob.Apply(fullval.Inverse); A = atrans.Source; } // Check usages of elements to see if this binary matter already exists FastPhysicsMatter res = null; - /*UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; + UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; foreach (var ind in usages.Usages) { + Transform dfull; _Binary testbin = ind.Value; if (testbin.A == A && testbin.B == B) { - if (testbin.AToB.GetSimilarity(atob, 1.0, 1.0, 1.0) > transsimthreshold) + if (_TryMatch(A, B, atob, testbin.AToB, out dfull)) { res = testbin; usages.Accept(ind); + if(full != null) + { + full = full.Value.ApplyTo(dfull); + } + else + { + full = dfull; + } break; } } if (testbin.B == A && testbin.A == B) { Transform natob = atob.Inverse; - if (testbin.AToB.GetSimilarity(natob, 1.0, 1.0, 1.0) > transsimthreshold) + if (_TryMatch(B, A, natob, testbin.AToB, out dfull)) { res = testbin; + usages.Accept(ind); // Since the elements are swapped, correct transforms if (full != null) { - full = full.Value.Apply(atob); + full = full.Value.Apply(atob).ApplyTo(dfull); } else { - full = atob; + full = atob.ApplyTo(dfull); } - - usages.Accept(ind); break; } } - }*/ + } // Create binary matter if (res == null) { FastPhysicsMatter._Binary bin = new _Binary() { A = A, B = B, AToB = atob }; res = bin; Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); A._Usages.Add(bin); B._Usages.Add(bin); } // Retransform (if needed) if (full != null) { res = new _Transformed() { Source = res, Transform = full.Value }; } return res; } + /// <summary> + /// Compares two binary matter with the same elements to and sees if the "Candiate" binary matter can be used in place of the "Current" binary matter, and if + /// so, gets the additional transform (to be applied to the binary matter) needed. + /// </summary> + private static bool _TryMatch(FastPhysicsMatter A, FastPhysicsMatter B, Transform AToBCurrent, Transform AToBCanidate, out Transform Full) + { + // Find circumcenter vectors + Vector bbpos; double bbrad; B.GetBoundingSphere(out bbpos, out bbrad); + Vector curvec = AToBCurrent.ApplyToOffset(bbpos); double curvecdis = curvec.Length; + Vector canvec = AToBCanidate.ApplyToOffset(bbpos); double canvecdis = canvec.Length; + curvec *= 1.0 / curvecdis; + canvec *= 1.0 / canvecdis; + + // Check if the distances are anywhere near each other. + if (Math.Abs(Math.Sqrt(curvecdis) - Math.Sqrt(canvecdis)) < 0.0001 && A is _Particle && B is _Particle) + { + // Orient the current matter to the candiate matter + Quaternion ort = Quaternion.AngleBetween(canvec, curvec); + Full = new Transform(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), ort); + return true; + } + + Full = Transform.Identity; + return false; + } + /// <summary> /// A sphere tree for matter. /// </summary> internal class _SphereTree : SphereTree<FastPhysicsMatter> { public _SphereTree(FastPhysics Physics) { this._Physics = Physics; } public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) { return Combine(this._Physics, A, B); } public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) { Node.GetBoundingSphere(out Position, out Radius); } public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return Node._GetSubnodes(this._Physics, ref A, ref B); } private FastPhysics _Physics; } /// <summary> /// Gets the subnodes for this node for use in a sphere tree. /// </summary> internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return false; } /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } + /// <summary> + /// Adds all particles in this matter to the given list after applying the specified transform. + /// </summary> + internal virtual void _GetParticles(Transform Transform, List<Vector> Particles) + { + + } + /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } + internal override void _GetParticles(Transform Transform, List<Vector> Particles) + { + Particles.Add(Transform.Offset); + } + public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { if (this.Source._GetSubnodes(Physics, ref A, ref B)) { A = A.Apply(Physics, this.Transform); B = B.Apply(Physics, this.Transform); return true; } return false; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } + internal override void _GetParticles(Transform Transform, List<Vector> Particles) + { + this.Source._GetParticles(Transform.ApplyTo(this.Transform), Particles); + } + public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { A = this.A; B = this.B.Apply(Physics, this.AToB); return true; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } + internal override void _GetParticles(Transform Transform, List<Vector> Particles) + { + this.A._GetParticles(Transform, Particles); + this.B._GetParticles(this.AToB.Apply(Transform), Particles); + } + public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } public MatterDisparity GetDisparity( FastPhysics Physics, FastPhysicsMatter Environment, double OldMass, double NewMass, ISubstance NewSubstance, Vector DeltaPosition, Vector DeltaVelocity, Quaternion DeltaOrientation, AxisAngle OldSpin, AxisAngle NewSpin) { throw new NotImplementedException(); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/MatchMatrix.cs b/Alunite/MatchMatrix.cs index 60b0c3c..979671a 100644 --- a/Alunite/MatchMatrix.cs +++ b/Alunite/MatchMatrix.cs @@ -1,99 +1,99 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A matrix that relates two objects of a common base to a function that generates a result of the desired type. /// </summary> public class MatchMatrix<TBase, TResult> where TBase : class { public MatchMatrix(Match<TBase, TBase> Default) { this._Rules = new Stack<MatchMatrix<TBase, TResult>._Rule>(); this._Rules.Push(new _Rule.Special<TBase, TBase>(Default)); } /// <summary> - /// Symmetrically adds a rule for the matrix for the two specialized types. The most recently added rules have the highest priority. + /// Adds a symmetric rule for the matrix for the two specialized types. The most recently added rules have the highest priority. /// </summary> public void AddRule<TA, TB>(Match<TA, TB> Rule) where TA : class, TBase where TB : class, TBase { this._Rules.Push(new _Rule.Special<TA, TB>(Rule)); } /// <summary> /// Gets the result defined by the matrix for the two specified objects. /// </summary> public TResult GetResult(TBase A, TBase B) { TResult res = default(TResult); foreach (_Rule r in this._Rules) { if (r.Try(A, B, ref res)) { return res; } } return res; } /// <summary> /// A function that produces a result given two objects of a specialized type from the common base. /// </summary> public delegate TResult Match<TA, TB>(TA A, TB B) where TA : TBase where TB : TBase; /// <summary> /// Represents a matching rule. /// </summary> private abstract class _Rule { /// <summary> /// Tries to apply this rule to the specified object pair. /// </summary> public abstract bool Try(TBase A, TBase B, ref TResult Result); public class Special<TA, TB> : _Rule where TA : class, TBase where TB : class, TBase { public Special(Match<TA, TB> Match) { this.Match = Match; } public override bool Try(TBase A, TBase B, ref TResult Result) { TA a = A as TA; TB b = B as TB; if (a != null && b != null) { Result = this.Match(a, b); return true; } a = B as TA; b = A as TB; if (a != null && b != null) { Result = this.Match(a, b); return true; } return false; } /// <summary> /// The match for this rule. /// </summary> public Match<TA, TB> Match; } } private Stack<_Rule> _Rules; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 62e3dc2..f5cdec7 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,78 +1,53 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { - private class _Person - { - - } - - private class _AngryPerson : _Person - { - - } - - private class _SadPerson : _Person - { - - } - - private class _HappyPerson : _Person - { - - } - /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - // Match matrix test - MatchMatrix<_Person, bool> getsalongwith = new MatchMatrix<_Person, bool>((a, b) => true); - getsalongwith.AddRule<_AngryPerson, _Person>((a, b) => false); - getsalongwith.AddRule<_SadPerson, _HappyPerson>((a, b) => false); + Transform testa = new Transform( + new Vector(1.0, 0.5, 0.3), + new Vector(1.0, 0.5, 0.3), + Quaternion.AngleBetween(Vector.Normalize(new Vector(0.9, 0.8, 0.7)), new Vector(0.0, 0.0, 1.0))); + testa = testa.ApplyTo(testa.Inverse); - bool testa = getsalongwith.GetResult(new _HappyPerson(), new _AngryPerson()); - bool testb = getsalongwith.GetResult(new _HappyPerson(), new _SadPerson()); - bool testc = getsalongwith.GetResult(new _HappyPerson(), new _HappyPerson()); // Set up a world FastPhysics fp = new FastPhysics(); List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); - Random r = new Random(); + Random r = new Random(2); + List<Vector> pointset = new List<Vector>(); for(int t = 0; t < 1000; t++) { + Vector pos = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()); elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, - Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), + Position = pos, Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity })); + pointset.Add(pos); } FastPhysicsMatter world = fp.Compose(elems); - for (int t = 0; t < 10; t++) - { - world = fp.Update(world, fp.Null, 0.1); - } - - /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; - hw.Control = new Visualizer(world); - hw.Run(60.0);*/ + hw.Control = new Visualizer(world.Particles, pointset); + hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index 00a0f7f..4e584d2 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,217 +1,228 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } public Quaternion(Vector Axis, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; this.B = Axis.X * sina; this.C = Axis.Y * sina; this.D = Axis.Z * sina; } /// <summary> /// Gets a rotation quaternion for a rotation described in axis angle form. /// </summary> public static Quaternion AxisAngle(Vector Axis, double Angle) { return new Quaternion(Axis, Angle); } /// <summary> /// Gets a rotation quaternion for the angle between two distinct normal vectors. /// </summary> public static Quaternion AngleBetween(Vector A, Vector B) { double hcosang = Math.Sqrt(0.5 + 0.5 * Vector.Dot(A, B)); double hsinang = Math.Sqrt(1.0 - hcosang * hcosang); double sinang = 2.0 * hsinang * hcosang; Vector axis = Vector.Cross(A, B); axis *= 1.0 / sinang; return new Quaternion(hcosang, axis * hsinang); } /// <summary> /// Gets the identity quaternion. /// </summary> public static Quaternion Identity { get { return new Quaternion(1.0, 0.0, 0.0, 0.0); } } /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } + /// <summary> + /// Gets the absolute value of the quaternion. + /// </summary> + public double Abs + { + get + { + return Math.Sqrt(this.A * this.A + this.B * this.B + this.C * this.C + this.D * this.D); + } + } + /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } /// <summary> /// Applies the rotation represented by this quaternion to another. /// </summary> public Quaternion ApplyTo(Quaternion Other) { - return this * Other; + return Quaternion.Normalize(this * Other); } /// <summary> /// Applies a rotation to this quaternion. /// </summary> public Quaternion Apply(Quaternion Other) { - return Other * this; + return Quaternion.Normalize(Other * this); } /// <summary> /// Normalizes the quaternion. /// </summary> public void Normalize() { - double d = 1.0 / Math.Sqrt(this.A * this.A + this.B * this.B + this.C * this.C + this.D * this.D); + double d = 1.0 / this.Abs; this.A *= d; this.B *= d; this.C *= d; this.D *= d; } /// <summary> /// Normalizes the specified quaternion. /// </summary> public static Quaternion Normalize(Quaternion A) { A.Normalize(); return A; } /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; - return (this * new Quaternion(0.0, Point) * this.Conjugate).Imag; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { - return new Quaternion( + Quaternion q = new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); + return q; } public double A; public double B; public double C; public double D; } /// <summary> /// An axis angle representation of rotation. /// </summary> public struct AxisAngle { public AxisAngle(Vector Axis, double Angle) { this.Axis = Axis; this.Angle = Angle; } /// <summary> /// Gets an axis angle representation of an identity rotation. /// </summary> public static AxisAngle Identity { get { return new AxisAngle(new Vector(1.0, 0.0, 0.0), 0.0); } } public static implicit operator Quaternion(AxisAngle AxisAngle) { return Quaternion.AxisAngle(AxisAngle.Axis, AxisAngle.Angle); } public static AxisAngle operator *(AxisAngle AxisAngle, double Factor) { return new AxisAngle(AxisAngle.Axis, AxisAngle.Angle * Factor); } /// <summary> /// The angle, in radians, of the rotation. /// </summary> public double Angle; /// <summary> /// The normalized axis of the rotation. /// </summary> public Vector Axis; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 12b0d55..4330b3b 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,74 +1,63 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> - /*public class Visualizer : Render3DControl + public class Visualizer : Render3DControl { - public Visualizer(Matter Matter) + public Visualizer(IEnumerable<Vector> PointSetA, IEnumerable<Vector> PointSetB) { - this._Matter = Matter; - } - - /// <summary> - /// Gets the matter to be visualized. - /// </summary> - public Matter Matter - { - get - { - return this._Matter; - } + this._PointSetA = PointSetA; + this._PointSetB = PointSetB; } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); - foreach (Particle p in this._Matter.Particles) + GL.Color4(Color.RGB(0.0, 0.5, 1.0)); + foreach (Vector v in this._PointSetA) + { + GL.Vertex3(v); + } + GL.Color4(Color.RGB(1.0, 0.5, 0.0)); + foreach (Vector v in this._PointSetB) { - Color col = Color.RGB(1.0, 1.0, 1.0); - IVisualSubstance vissub = p.Substance as IVisualSubstance; - if (vissub != null) - { - col = vissub.Color; - } - GL.Color4(col); - GL.Vertex3(p.Position); + GL.Vertex3(v); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { this._Time += Time * 0.2; - //this._Matter = this._Matter.Update(Matter.Null, Time * 0.1); } + private IEnumerable<Vector> _PointSetA; + private IEnumerable<Vector> _PointSetB; private double _Time; - private Matter _Matter; - }*/ + } } \ No newline at end of file
dzamkov/Alunite-old
ec04d6fb024c5348fc9a812f2ddd57b13b55bf11
Matter disparity and match matrix
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index c4e19e0..113235e 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,65 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> - <Compile Include="Similarity.cs" /> <Compile Include="FastPhysics.cs" /> - <Compile Include="Matter.cs" /> + <Compile Include="MatchMatrix.cs" /> + <Compile Include="Physics.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 9116886..7c67d57 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,366 +1,377 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } /// <summary> /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to /// describe it. /// </summary> public int Complexity { get { HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); this._GetUsed(used); return used.Count; } } /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Combines two "bits" of matter into one. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { // Untransform _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } Transform? full = null; if (atrans != null) { Transform fullval = atrans.Transform; full = fullval = atrans.Transform; atob = atob.Apply(fullval.Inverse); A = atrans.Source; } // Check usages of elements to see if this binary matter already exists FastPhysicsMatter res = null; - UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; - Similarity transsimthreshold = 0.01; + /*UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; foreach (var ind in usages.Usages) { _Binary testbin = ind.Value; if (testbin.A == A && testbin.B == B) { if (testbin.AToB.GetSimilarity(atob, 1.0, 1.0, 1.0) > transsimthreshold) { res = testbin; usages.Accept(ind); break; } } if (testbin.B == A && testbin.A == B) { Transform natob = atob.Inverse; if (testbin.AToB.GetSimilarity(natob, 1.0, 1.0, 1.0) > transsimthreshold) { res = testbin; // Since the elements are swapped, correct transforms if (full != null) { full = full.Value.Apply(atob); } else { full = atob; } usages.Accept(ind); break; } } - } + }*/ // Create binary matter if (res == null) { FastPhysicsMatter._Binary bin = new _Binary() { A = A, B = B, AToB = atob }; res = bin; Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); A._Usages.Add(bin); B._Usages.Add(bin); } // Retransform (if needed) if (full != null) { res = new _Transformed() { Source = res, Transform = full.Value }; } return res; } /// <summary> /// A sphere tree for matter. /// </summary> internal class _SphereTree : SphereTree<FastPhysicsMatter> { public _SphereTree(FastPhysics Physics) { this._Physics = Physics; } public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) { return Combine(this._Physics, A, B); } public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) { Node.GetBoundingSphere(out Position, out Radius); } public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return Node._GetSubnodes(this._Physics, ref A, ref B); } private FastPhysics _Physics; } /// <summary> /// Gets the subnodes for this node for use in a sphere tree. /// </summary> internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return false; } /// <summary> /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including /// this matter itself. /// </summary> internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { if (this.Source._GetSubnodes(Physics, ref A, ref B)) { A = A.Apply(Physics, this.Transform); B = B.Apply(Physics, this.Transform); return true; } return false; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.Source._GetUsed(Elements); } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { A = this.A; B = this.B.Apply(Physics, this.AToB); return true; } internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) { Elements.Add(this); this.A._GetUsed(Elements); this.B._GetUsed(Elements); } public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } + public MatterDisparity GetDisparity( + FastPhysics Physics, FastPhysicsMatter Environment, + double OldMass, double NewMass, + ISubstance NewSubstance, + Vector DeltaPosition, + Vector DeltaVelocity, + Quaternion DeltaOrientation, + AxisAngle OldSpin, AxisAngle NewSpin) + { + throw new NotImplementedException(); + } + private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/MatchMatrix.cs b/Alunite/MatchMatrix.cs new file mode 100644 index 0000000..60b0c3c --- /dev/null +++ b/Alunite/MatchMatrix.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// A matrix that relates two objects of a common base to a function that generates a result of the desired type. + /// </summary> + public class MatchMatrix<TBase, TResult> + where TBase : class + { + public MatchMatrix(Match<TBase, TBase> Default) + { + this._Rules = new Stack<MatchMatrix<TBase, TResult>._Rule>(); + this._Rules.Push(new _Rule.Special<TBase, TBase>(Default)); + } + + /// <summary> + /// Symmetrically adds a rule for the matrix for the two specialized types. The most recently added rules have the highest priority. + /// </summary> + public void AddRule<TA, TB>(Match<TA, TB> Rule) + where TA : class, TBase + where TB : class, TBase + { + this._Rules.Push(new _Rule.Special<TA, TB>(Rule)); + } + + /// <summary> + /// Gets the result defined by the matrix for the two specified objects. + /// </summary> + public TResult GetResult(TBase A, TBase B) + { + TResult res = default(TResult); + foreach (_Rule r in this._Rules) + { + if (r.Try(A, B, ref res)) + { + return res; + } + } + return res; + } + + /// <summary> + /// A function that produces a result given two objects of a specialized type from the common base. + /// </summary> + public delegate TResult Match<TA, TB>(TA A, TB B) + where TA : TBase + where TB : TBase; + + /// <summary> + /// Represents a matching rule. + /// </summary> + private abstract class _Rule + { + /// <summary> + /// Tries to apply this rule to the specified object pair. + /// </summary> + public abstract bool Try(TBase A, TBase B, ref TResult Result); + + public class Special<TA, TB> : _Rule + where TA : class, TBase + where TB : class, TBase + { + public Special(Match<TA, TB> Match) + { + this.Match = Match; + } + + public override bool Try(TBase A, TBase B, ref TResult Result) + { + TA a = A as TA; + TB b = B as TB; + if (a != null && b != null) + { + Result = this.Match(a, b); + return true; + } + a = B as TA; + b = A as TB; + if (a != null && b != null) + { + Result = this.Match(a, b); + return true; + } + return false; + } + + /// <summary> + /// The match for this rule. + /// </summary> + public Match<TA, TB> Match; + } + } + + private Stack<_Rule> _Rules; + } +} \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index e377480..3651d3b 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,86 +1,99 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physical system that allows the introduction and simulation of particles. /// </summary> public interface IParticlePhysics<TMatter, TSubstance> : ISpatialPhysics<TMatter> where TMatter : IMatter where TSubstance : ISubstance { /// <summary> /// Creates a matter form of a single particle with the specified properties. /// </summary> TMatter Create(Particle<TSubstance> Particle); } /// <summary> /// Contains the properties of a particle. /// </summary> public struct Particle<TSubstance> { /// <summary> /// The substance the particle is of. /// </summary> public TSubstance Substance; /// <summary> /// The relative position of the particle. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle. /// </summary> public Vector Velocity; /// <summary> /// The orientation of the particle. /// </summary> public Quaternion Orientation; /// <summary> /// The angular velocity of the particle. /// </summary> public AxisAngle Spin; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Updates the spatial state of this particle by the given amount of time in seconds. /// </summary> public void Update(double Time) { this.Position += this.Velocity * Time; this.Orientation.Apply(this.Spin * Time); } } /// <summary> /// Descibes the physical properties of a particle. /// </summary> public interface ISubstance { } /// <summary> /// A substance with known interactions in a certain kind of physics system. /// </summary> public interface IAutoSubstance<TPhysics, TMatter, TSubstance> : ISubstance where TPhysics : IParticlePhysics<TMatter, TSubstance> where TMatter : IMatter where TSubstance : IAutoSubstance<TPhysics, TMatter, TSubstance> { /// <summary> /// Updates a particle of this kind of substance in the given environment. /// </summary> void Update(TPhysics Physics, TMatter Environment, double Time, ref Particle<TSubstance> Particle); + + /// <summary> + /// Gets the complex disparity created if a particle of this substance was replaced with a new particle with the described + /// properties. + /// </summary> + MatterDisparity GetDisparity( + TPhysics Physics, TMatter Environment, + double OldMass, double NewMass, + ISubstance NewSubstance, + Vector DeltaPosition, + Vector DeltaVelocity, + Quaternion DeltaOrientation, + AxisAngle OldSpin, AxisAngle NewSpin); } } \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Physics.cs similarity index 63% rename from Alunite/Matter.cs rename to Alunite/Physics.cs index c5fb3f3..7a1f788 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Physics.cs @@ -1,130 +1,177 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } + /// <summary> + /// Describes the difference between two pieces of matter. + /// </summary> + /// <remarks>The "simple matter disparity" does not take into account forces to external matter while the "complex matter disparity" does. Note that + /// matter disparity is for the most part an approximation used for optimizations.</remarks> + public struct MatterDisparity + { + public MatterDisparity(double Movement, double Translation, double Mass) + { + this.Movement = Movement; + this.Translation = Translation; + this.Mass = Mass; + } + + /// <summary> + /// Gets the matter disparity between two identical pieces of matter. + /// </summary> + public static MatterDisparity Identical + { + get + { + return new MatterDisparity(0.0, 0.0, 0.0); + } + } + + /// <summary> + /// Gets the simple matter disparity between two particles. + /// </summary> + public static MatterDisparity BetweenParticles(double MassA, Vector PosA, Vector VelA, double MassB, Vector PosB, Vector VelB) + { + return new MatterDisparity( + (MassA + MassB) * (VelA - VelB).Length, + (MassA + MassB) * (PosA - PosB).Length, + Math.Abs(MassA - MassB)); + } + + /// <summary> + /// The amount of mass, course deviation that would be caused if the compared pieces of matter were swapped in usage, measured in + /// kilograms meters per second. Note that if this is for "complex matter disparity", this should take into account external + /// matter and forces. + /// </summary> + public double Movement; + + /// <summary> + /// The amount of mass that is immediately translated between the two compared pieces of matter, measured in kilogram meters. + /// </summary> + public double Translation; + + /// <summary> + /// The difference in mass of the two compared pieces of matter measured in kilograms. + /// </summary> + public double Mass; + } + /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } - public Similarity GetSimilarity(Transform Other, double OffsetWeight, double VelocityWeight, double RotationWeight) - { - return - this.Offset.GetOffsetSimilarity(Other.Offset).Weigh(OffsetWeight) + - this.VelocityOffset.GetOffsetSimilarity(Other.VelocityOffset).Weigh(VelocityWeight) + - this.Rotation.GetRotationSimilarity(Other.Rotation).Weigh(RotationWeight); - } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index b023648..62e3dc2 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,57 +1,78 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { + private class _Person + { + + } + + private class _AngryPerson : _Person + { + + } + + private class _SadPerson : _Person + { + + } + + private class _HappyPerson : _Person + { + + } + /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - // Quaternion test - Vector a = new Vector(0.0, 0.0, 1.0); - Vector b = new Vector(0.0, 0.3, 1.0); - a.Normalize(); - b.Normalize(); - Quaternion between = Quaternion.AngleBetween(a, b); - a = between.Rotate(a); + // Match matrix test + MatchMatrix<_Person, bool> getsalongwith = new MatchMatrix<_Person, bool>((a, b) => true); + getsalongwith.AddRule<_AngryPerson, _Person>((a, b) => false); + getsalongwith.AddRule<_SadPerson, _HappyPerson>((a, b) => false); + + bool testa = getsalongwith.GetResult(new _HappyPerson(), new _AngryPerson()); + bool testb = getsalongwith.GetResult(new _HappyPerson(), new _SadPerson()); + bool testc = getsalongwith.GetResult(new _HappyPerson(), new _HappyPerson()); // Set up a world FastPhysics fp = new FastPhysics(); List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); Random r = new Random(); for(int t = 0; t < 1000; t++) { elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, Spin = AxisAngle.Identity })); } FastPhysicsMatter world = fp.Compose(elems); for (int t = 0; t < 10; t++) { world = fp.Update(world, fp.Null, 0.1); } /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index f09679e..00a0f7f 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,226 +1,217 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } public Quaternion(Vector Axis, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; this.B = Axis.X * sina; this.C = Axis.Y * sina; this.D = Axis.Z * sina; } - /// <summary> - /// Gets the similarity between this and another quaternion when they are used to represent rotation. - /// </summary> - public Similarity GetRotationSimilarity(Quaternion Other) - { - // Too much work for now - return 0.0001; - } - /// <summary> /// Gets a rotation quaternion for a rotation described in axis angle form. /// </summary> public static Quaternion AxisAngle(Vector Axis, double Angle) { return new Quaternion(Axis, Angle); } /// <summary> /// Gets a rotation quaternion for the angle between two distinct normal vectors. /// </summary> public static Quaternion AngleBetween(Vector A, Vector B) { double hcosang = Math.Sqrt(0.5 + 0.5 * Vector.Dot(A, B)); double hsinang = Math.Sqrt(1.0 - hcosang * hcosang); double sinang = 2.0 * hsinang * hcosang; Vector axis = Vector.Cross(A, B); axis *= 1.0 / sinang; return new Quaternion(hcosang, axis * hsinang); } /// <summary> /// Gets the identity quaternion. /// </summary> public static Quaternion Identity { get { return new Quaternion(1.0, 0.0, 0.0, 0.0); } } /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } /// <summary> /// Applies the rotation represented by this quaternion to another. /// </summary> public Quaternion ApplyTo(Quaternion Other) { return this * Other; } /// <summary> /// Applies a rotation to this quaternion. /// </summary> public Quaternion Apply(Quaternion Other) { return Other * this; } /// <summary> /// Normalizes the quaternion. /// </summary> public void Normalize() { double d = 1.0 / Math.Sqrt(this.A * this.A + this.B * this.B + this.C * this.C + this.D * this.D); this.A *= d; this.B *= d; this.C *= d; this.D *= d; } /// <summary> /// Normalizes the specified quaternion. /// </summary> public static Quaternion Normalize(Quaternion A) { A.Normalize(); return A; } /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; return (this * new Quaternion(0.0, Point) * this.Conjugate).Imag; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { return new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); } public double A; public double B; public double C; public double D; } /// <summary> /// An axis angle representation of rotation. /// </summary> public struct AxisAngle { public AxisAngle(Vector Axis, double Angle) { this.Axis = Axis; this.Angle = Angle; } /// <summary> /// Gets an axis angle representation of an identity rotation. /// </summary> public static AxisAngle Identity { get { return new AxisAngle(new Vector(1.0, 0.0, 0.0), 0.0); } } public static implicit operator Quaternion(AxisAngle AxisAngle) { return Quaternion.AxisAngle(AxisAngle.Axis, AxisAngle.Angle); } public static AxisAngle operator *(AxisAngle AxisAngle, double Factor) { return new AxisAngle(AxisAngle.Axis, AxisAngle.Angle * Factor); } /// <summary> /// The angle, in radians, of the rotation. /// </summary> public double Angle; /// <summary> /// The normalized axis of the rotation. /// </summary> public Vector Axis; } } \ No newline at end of file diff --git a/Alunite/Similarity.cs b/Alunite/Similarity.cs deleted file mode 100644 index 5dee67a..0000000 --- a/Alunite/Similarity.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Represents the similarity between objects. Similarity is described on a subjective exponential scale - /// with a double. 0.0 indicates objects are identical while +infinity indicates objects are opposites. The geometric mean of - /// the similarity of any combination of objects of a common base should be near 1.0. - /// </summary> - public struct Similarity - { - public Similarity(double Value) - { - this.Value = Value; - } - - /// <summary> - /// Multiplies the weight of this similarity when used for comparison. - /// </summary> - public Similarity Weigh(double Amount) - { - return new Similarity(this.Value * Amount); - } - - /// <summary> - /// A similarity that indicates objects are identical. - /// </summary> - public static readonly Similarity Identical = new Similarity(0.0); - - /// <summary> - /// Combines two similarity quantities. - /// </summary> - public static Similarity operator +(Similarity A, Similarity B) - { - return new Similarity(A.Value + B.Value); - } - - /// <summary> - /// Gets if A represents a stronger similarity than B. - /// </summary> - public static bool operator >(Similarity A, Similarity B) - { - return A.Value < B.Value; - } - - /// <summary> - /// Gets if B represents a weaker similarity than B. - /// </summary> - public static bool operator <(Similarity A, Similarity B) - { - return A.Value > B.Value; - } - - /// <summary> - /// Gets a similarity from a value. - /// </summary> - public static implicit operator Similarity(double Value) - { - return new Similarity(Value); - } - - /// <summary> - /// The double value of this similarity. - /// </summary> - public double Value; - } -} \ No newline at end of file diff --git a/Alunite/Vector.cs b/Alunite/Vector.cs index 92104b0..cb2ed10 100644 --- a/Alunite/Vector.cs +++ b/Alunite/Vector.cs @@ -1,182 +1,174 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in three-dimensional space. /// </summary> public struct Vector { public Vector(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } public static implicit operator Vector3d(Vector Vector) { return new Vector3d(Vector.X, Vector.Y, Vector.Z); } public static explicit operator Vector3(Vector Vector) { return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); } public static bool operator ==(Vector A, Vector B) { return A.X == B.X && A.Y == B.Y && A.Z == B.Z; } public static bool operator !=(Vector A, Vector B) { return A.X != B.X || A.Y != B.Y || A.Z != B.Z; } public static Vector operator +(Vector A, Vector B) { return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vector operator -(Vector A, Vector B) { return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vector operator *(Vector A, double Magnitude) { return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); } public static Vector operator -(Vector A) { return new Vector(-A.X, -A.Y, -A.Z); } public override string ToString() { return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); } public override int GetHashCode() { int xhash = this.X.GetHashCode(); int yhash = this.Y.GetHashCode(); int zhash = this.Z.GetHashCode(); return unchecked(xhash ^ (yhash + 0x1337BED5) ^ (zhash + 0x2B50CDF1) ^ (yhash << 3) ^ (yhash >> 3) ^ (zhash << 7) ^ (zhash >> 7)); } - /// <summary> - /// Gets the similarity between this vector and another if the vector is used as an offset or position. - /// </summary> - public Similarity GetOffsetSimilarity(Vector Other) - { - return (this - Other).Length; - } - /// <summary> /// Gets the cross product of two vectors. /// </summary> public static Vector Cross(Vector A, Vector B) { return new Vector( (A.Y * B.Z) - (A.Z * B.Y), (A.Z * B.X) - (A.X * B.Z), (A.X * B.Y) - (A.Y * B.X)); } /// <summary> /// Compares two vectors lexographically. /// </summary> public static bool Compare(Vector A, Vector B) { if (A.X > B.X) return true; if (A.X < B.X) return false; if (A.Y > B.Y) return true; if (A.Y < B.Y) return false; if (A.Z > B.Z) return true; return false; } /// <summary> /// Gets the outgoing ray of an object hitting a plane with the specified normal at the /// specified incoming ray. /// </summary> public static Vector Reflect(Vector Incoming, Vector Normal) { return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); } /// <summary> /// Multiplies each component of the vectors with the other's corresponding component. /// </summary> public static Vector Scale(Vector A, Vector B) { return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } /// <summary> /// Gets the dot product between two vectors. /// </summary> public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } /// <summary> /// Gets the length of the vector. /// </summary> public double Length { get { return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the length of the vector. /// </summary> public double SquareLength { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Normalizes the vector so its length is one but its direction is unchanged. /// </summary> public void Normalize() { double ilen = 1.0 / this.Length; this.X *= ilen; this.Y *= ilen; this.Z *= ilen; } /// <summary> /// Normalizes the specified vector. /// </summary> public static Vector Normalize(Vector A) { A.Normalize(); return A; } public double X; public double Y; public double Z; } } \ No newline at end of file
dzamkov/Alunite-old
eafe2f5ba06409966ef33a3a94e1b5ec36acecf5
More quaternion maths
diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 7646ab9..c5fb3f3 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,130 +1,130 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), - this.Rotation * Transform.Rotation); + this.Rotation.ApplyTo(Transform.Rotation)); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Similarity GetSimilarity(Transform Other, double OffsetWeight, double VelocityWeight, double RotationWeight) { return this.Offset.GetOffsetSimilarity(Other.Offset).Weigh(OffsetWeight) + this.VelocityOffset.GetOffsetSimilarity(Other.VelocityOffset).Weigh(VelocityWeight) + this.Rotation.GetRotationSimilarity(Other.Rotation).Weigh(RotationWeight); } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index 1604e40..e377480 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,85 +1,86 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physical system that allows the introduction and simulation of particles. /// </summary> public interface IParticlePhysics<TMatter, TSubstance> : ISpatialPhysics<TMatter> where TMatter : IMatter where TSubstance : ISubstance { /// <summary> /// Creates a matter form of a single particle with the specified properties. /// </summary> TMatter Create(Particle<TSubstance> Particle); } /// <summary> /// Contains the properties of a particle. /// </summary> public struct Particle<TSubstance> { /// <summary> /// The substance the particle is of. /// </summary> public TSubstance Substance; /// <summary> /// The relative position of the particle. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle. /// </summary> public Vector Velocity; /// <summary> /// The orientation of the particle. /// </summary> public Quaternion Orientation; /// <summary> /// The angular velocity of the particle. /// </summary> - public Quaternion Spin; + public AxisAngle Spin; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Updates the spatial state of this particle by the given amount of time in seconds. /// </summary> public void Update(double Time) { this.Position += this.Velocity * Time; + this.Orientation.Apply(this.Spin * Time); } } /// <summary> /// Descibes the physical properties of a particle. /// </summary> public interface ISubstance { } /// <summary> /// A substance with known interactions in a certain kind of physics system. /// </summary> public interface IAutoSubstance<TPhysics, TMatter, TSubstance> : ISubstance where TPhysics : IParticlePhysics<TMatter, TSubstance> where TMatter : IMatter where TSubstance : IAutoSubstance<TPhysics, TMatter, TSubstance> { /// <summary> /// Updates a particle of this kind of substance in the given environment. /// </summary> void Update(TPhysics Physics, TMatter Environment, double Time, ref Particle<TSubstance> Particle); } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index f67ac40..b023648 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,49 +1,57 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { + // Quaternion test + Vector a = new Vector(0.0, 0.0, 1.0); + Vector b = new Vector(0.0, 0.3, 1.0); + a.Normalize(); + b.Normalize(); + Quaternion between = Quaternion.AngleBetween(a, b); + a = between.Rotate(a); + // Set up a world FastPhysics fp = new FastPhysics(); List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); Random r = new Random(); for(int t = 0; t < 1000; t++) { elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() { Substance = FastPhysicsSubstance.Default, Mass = 1.0, Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), Velocity = new Vector(0.0, 0.0, 0.0), Orientation = Quaternion.Identity, - Spin = Quaternion.Identity + Spin = AxisAngle.Identity })); } FastPhysicsMatter world = fp.Compose(elems); for (int t = 0; t < 10; t++) { world = fp.Update(world, fp.Null, 0.1); } /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index cb1d5cc..f09679e 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,124 +1,226 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } - public Quaternion(Vector Vector, double Angle) + public Quaternion(Vector Axis, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; - this.B = Vector.X * sina; - this.C = Vector.Y * sina; - this.D = Vector.Z * sina; + this.B = Axis.X * sina; + this.C = Axis.Y * sina; + this.D = Axis.Z * sina; } /// <summary> /// Gets the similarity between this and another quaternion when they are used to represent rotation. /// </summary> public Similarity GetRotationSimilarity(Quaternion Other) { // Too much work for now return 0.0001; } + /// <summary> + /// Gets a rotation quaternion for a rotation described in axis angle form. + /// </summary> + public static Quaternion AxisAngle(Vector Axis, double Angle) + { + return new Quaternion(Axis, Angle); + } + + /// <summary> + /// Gets a rotation quaternion for the angle between two distinct normal vectors. + /// </summary> + public static Quaternion AngleBetween(Vector A, Vector B) + { + double hcosang = Math.Sqrt(0.5 + 0.5 * Vector.Dot(A, B)); + double hsinang = Math.Sqrt(1.0 - hcosang * hcosang); + double sinang = 2.0 * hsinang * hcosang; + Vector axis = Vector.Cross(A, B); + axis *= 1.0 / sinang; + return new Quaternion(hcosang, axis * hsinang); + } + /// <summary> /// Gets the identity quaternion. /// </summary> public static Quaternion Identity { get { return new Quaternion(1.0, 0.0, 0.0, 0.0); } } /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } + /// <summary> + /// Applies the rotation represented by this quaternion to another. + /// </summary> + public Quaternion ApplyTo(Quaternion Other) + { + return this * Other; + } + + /// <summary> + /// Applies a rotation to this quaternion. + /// </summary> + public Quaternion Apply(Quaternion Other) + { + return Other * this; + } + + /// <summary> + /// Normalizes the quaternion. + /// </summary> + public void Normalize() + { + double d = 1.0 / Math.Sqrt(this.A * this.A + this.B * this.B + this.C * this.C + this.D * this.D); + this.A *= d; + this.B *= d; + this.C *= d; + this.D *= d; + } + + /// <summary> + /// Normalizes the specified quaternion. + /// </summary> + public static Quaternion Normalize(Quaternion A) + { + A.Normalize(); + return A; + } + /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; + return (this * new Quaternion(0.0, Point) * this.Conjugate).Imag; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { return new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); } public double A; public double B; public double C; public double D; } + + /// <summary> + /// An axis angle representation of rotation. + /// </summary> + public struct AxisAngle + { + public AxisAngle(Vector Axis, double Angle) + { + this.Axis = Axis; + this.Angle = Angle; + } + + /// <summary> + /// Gets an axis angle representation of an identity rotation. + /// </summary> + public static AxisAngle Identity + { + get + { + return new AxisAngle(new Vector(1.0, 0.0, 0.0), 0.0); + } + } + + public static implicit operator Quaternion(AxisAngle AxisAngle) + { + return Quaternion.AxisAngle(AxisAngle.Axis, AxisAngle.Angle); + } + + public static AxisAngle operator *(AxisAngle AxisAngle, double Factor) + { + return new AxisAngle(AxisAngle.Axis, AxisAngle.Angle * Factor); + } + + /// <summary> + /// The angle, in radians, of the rotation. + /// </summary> + public double Angle; + + /// <summary> + /// The normalized axis of the rotation. + /// </summary> + public Vector Axis; + } } \ No newline at end of file
dzamkov/Alunite-old
376a5411579bd371eec5e5158499bfa90a454287
"Instancing" of matter
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 9c22405..c4e19e0 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,66 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> - <Compile Include="Approximate.cs" /> + <Compile Include="Similarity.cs" /> <Compile Include="FastPhysics.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> - <Compile Include="Reduce.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Approximate.cs b/Alunite/Approximate.cs deleted file mode 100644 index e24846b..0000000 --- a/Alunite/Approximate.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// An object that can be loosely compared to another object with the same base. Similarity is described on a subjective exponential scale - /// with a double. 0.0 indicates objects are identical while +infinity indicates objects are opposites. The geometric mean of - /// the similarity of any combination of objects of a common base should be near 1.0. - /// </summary> - /// <remarks>The similarity between numbers is the absolute value of their difference.</remarks> - public interface IApproximatable<TBase> - where TBase : IApproximatable<TBase> - { - /// <summary> - /// Gets the similarity this object has with another. - /// </summary> - double GetSimilarity(TBase Object); - } -} \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 04b2aa2..9116886 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,286 +1,366 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { this._Usages = new UsageSet<_Binary>(); } + /// <summary> + /// Estimates the complexity of this matter by getting the amount of unique bits of matter used to + /// describe it. + /// </summary> + public int Complexity + { + get + { + HashSet<FastPhysicsMatter> used = new HashSet<FastPhysicsMatter>(); + this._GetUsed(used); + return used.Count; + } + } + /// <summary> /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not /// have any correlation to where the matter can apply force. /// </summary> public abstract void GetBoundingSphere(out Vector Position, out double Radius); /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance }*/ _Particle.Default }; } /// <summary> /// Combines two "bits" of matter into one. /// </summary> public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) { // Untransform _Transformed atrans = A as _Transformed; _Transformed btrans = B as _Transformed; Transform atob = Transform.Identity; if (btrans != null) { atob = btrans.Transform; B = btrans.Source; } Transform? full = null; if (atrans != null) { Transform fullval = atrans.Transform; full = fullval = atrans.Transform; atob = atob.Apply(fullval.Inverse); A = atrans.Source; } + // Check usages of elements to see if this binary matter already exists + FastPhysicsMatter res = null; + UsageSet<_Binary> usages = A._Usages.Size > B._Usages.Size ? B._Usages : A._Usages; + Similarity transsimthreshold = 0.01; + foreach (var ind in usages.Usages) + { + _Binary testbin = ind.Value; + if (testbin.A == A && testbin.B == B) + { + if (testbin.AToB.GetSimilarity(atob, 1.0, 1.0, 1.0) > transsimthreshold) + { + res = testbin; + usages.Accept(ind); + break; + } + } + if (testbin.B == A && testbin.A == B) + { + Transform natob = atob.Inverse; + if (testbin.AToB.GetSimilarity(natob, 1.0, 1.0, 1.0) > transsimthreshold) + { + res = testbin; + + // Since the elements are swapped, correct transforms + if (full != null) + { + full = full.Value.Apply(atob); + } + else + { + full = atob; + } + + usages.Accept(ind); + break; + } + } + } + // Create binary matter - FastPhysicsMatter._Binary bin = new _Binary() + if (res == null) { - A = A, - B = B, - AToB = atob - }; - Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); - Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); - SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); + FastPhysicsMatter._Binary bin = new _Binary() + { + A = A, + B = B, + AToB = atob + }; + res = bin; + Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); + Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); + SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); + A._Usages.Add(bin); + B._Usages.Add(bin); + } // Retransform (if needed) - FastPhysicsMatter res = bin; if (full != null) { res = new _Transformed() { Source = res, Transform = full.Value }; } return res; } /// <summary> /// A sphere tree for matter. /// </summary> internal class _SphereTree : SphereTree<FastPhysicsMatter> { public _SphereTree(FastPhysics Physics) { this._Physics = Physics; } public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) { return Combine(this._Physics, A, B); } public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) { Node.GetBoundingSphere(out Position, out Radius); } public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return Node._GetSubnodes(this._Physics, ref A, ref B); } private FastPhysics _Physics; } /// <summary> /// Gets the subnodes for this node for use in a sphere tree. /// </summary> internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { return false; } + /// <summary> + /// Gets all the matter used to make up this matter, that is, all the matter needed to give this matter meaning, including + /// this matter itself. + /// </summary> + internal virtual void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + } + /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { /// <summary> /// Default particle. /// </summary> public static readonly _Particle Default = new _Particle(); public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = new Vector(0.0, 0.0, 0.0); Radius = 0.0; } public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public override void GetBoundingSphere(out Vector Position, out double Radius) { Source.GetBoundingSphere(out Position, out Radius); Position = Transform.Offset + Transform.Rotation.Rotate(Position); } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { if (this.Source._GetSubnodes(Physics, ref A, ref B)) { A = A.Apply(Physics, this.Transform); B = B.Apply(Physics, this.Transform); return true; } return false; } + internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + this.Source._GetUsed(Elements); + } + public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public override void GetBoundingSphere(out Vector Position, out double Radius) { Position = this.BoundCenter; Radius = this.BoundRadius; } internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) { A = this.A; B = this.B.Apply(Physics, this.AToB); return true; } + internal override void _GetUsed(HashSet<FastPhysicsMatter> Elements) + { + Elements.Add(this); + this.A._GetUsed(Elements); + this.B._GetUsed(Elements); + } + public Vector BoundCenter; public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index e804a56..7646ab9 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,122 +1,130 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Applies this transform to an offset vector. /// </summary> public Vector ApplyToOffset(Vector Offset) { return this.Offset + this.Rotation.Rotate(Offset); } /// <summary> /// Applies a transform to this transform. /// </summary> public Transform Apply(Transform Transform) { return Transform.ApplyTo(this); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } + public Similarity GetSimilarity(Transform Other, double OffsetWeight, double VelocityWeight, double RotationWeight) + { + return + this.Offset.GetOffsetSimilarity(Other.Offset).Weigh(OffsetWeight) + + this.VelocityOffset.GetOffsetSimilarity(Other.VelocityOffset).Weigh(VelocityWeight) + + this.Rotation.GetRotationSimilarity(Other.Rotation).Weigh(RotationWeight); + } + public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 9acd158..f67ac40 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,56 +1,49 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { // Set up a world FastPhysics fp = new FastPhysics(); List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); - double size = 0.5; - double step = 0.1; - for (double x = -size + step * 0.5; x < size; x += step) + Random r = new Random(); + for(int t = 0; t < 1000; t++) { - for (double y = -size + step * 0.5; y < size; y += step) + elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() { - for (double z = -size + step * 0.5; z < size; z += step) - { - elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() - { - Substance = FastPhysicsSubstance.Default, - Mass = 1.0, - Position = new Vector(x, y, z), - Velocity = new Vector(0.0, 0.0, 0.0), - Orientation = Quaternion.Identity, - Spin = Quaternion.Identity - })); - } - } + Substance = FastPhysicsSubstance.Default, + Mass = 1.0, + Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), + Velocity = new Vector(0.0, 0.0, 0.0), + Orientation = Quaternion.Identity, + Spin = Quaternion.Identity + })); } FastPhysicsMatter world = fp.Compose(elems); for (int t = 0; t < 10; t++) { world = fp.Update(world, fp.Null, 0.1); } /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index c83966f..cb1d5cc 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,115 +1,124 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } public Quaternion(Vector Vector, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; this.B = Vector.X * sina; this.C = Vector.Y * sina; this.D = Vector.Z * sina; } + /// <summary> + /// Gets the similarity between this and another quaternion when they are used to represent rotation. + /// </summary> + public Similarity GetRotationSimilarity(Quaternion Other) + { + // Too much work for now + return 0.0001; + } + /// <summary> /// Gets the identity quaternion. /// </summary> public static Quaternion Identity { get { return new Quaternion(1.0, 0.0, 0.0, 0.0); } } /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { return new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); } public double A; public double B; public double C; public double D; } } \ No newline at end of file diff --git a/Alunite/Reduce.cs b/Alunite/Reduce.cs deleted file mode 100644 index cfa9892..0000000 --- a/Alunite/Reduce.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Contains functions related to the reduction and simplification of composite matter. - /// </summary> - public static class Reduce - { - - } -} \ No newline at end of file diff --git a/Alunite/Similarity.cs b/Alunite/Similarity.cs new file mode 100644 index 0000000..5dee67a --- /dev/null +++ b/Alunite/Similarity.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Represents the similarity between objects. Similarity is described on a subjective exponential scale + /// with a double. 0.0 indicates objects are identical while +infinity indicates objects are opposites. The geometric mean of + /// the similarity of any combination of objects of a common base should be near 1.0. + /// </summary> + public struct Similarity + { + public Similarity(double Value) + { + this.Value = Value; + } + + /// <summary> + /// Multiplies the weight of this similarity when used for comparison. + /// </summary> + public Similarity Weigh(double Amount) + { + return new Similarity(this.Value * Amount); + } + + /// <summary> + /// A similarity that indicates objects are identical. + /// </summary> + public static readonly Similarity Identical = new Similarity(0.0); + + /// <summary> + /// Combines two similarity quantities. + /// </summary> + public static Similarity operator +(Similarity A, Similarity B) + { + return new Similarity(A.Value + B.Value); + } + + /// <summary> + /// Gets if A represents a stronger similarity than B. + /// </summary> + public static bool operator >(Similarity A, Similarity B) + { + return A.Value < B.Value; + } + + /// <summary> + /// Gets if B represents a weaker similarity than B. + /// </summary> + public static bool operator <(Similarity A, Similarity B) + { + return A.Value > B.Value; + } + + /// <summary> + /// Gets a similarity from a value. + /// </summary> + public static implicit operator Similarity(double Value) + { + return new Similarity(Value); + } + + /// <summary> + /// The double value of this similarity. + /// </summary> + public double Value; + } +} \ No newline at end of file diff --git a/Alunite/UsageSet.cs b/Alunite/UsageSet.cs index 29e85e5..bbb9a07 100644 --- a/Alunite/UsageSet.cs +++ b/Alunite/UsageSet.cs @@ -1,99 +1,110 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Maintains a collection of objects that contain a certain resource. This can be used to reference one of the using objects /// directly when it is identical to the target object. The set weakly references target objects and will sort them by likeliness /// of being accepted. /// </summary> public class UsageSet<TUsage> { public UsageSet() { this._Set = new LinkedList<WeakReference>(); } public UsageSet(IEnumerable<TUsage> Usages) { this._Set = new LinkedList<WeakReference>( from u in Usages select new WeakReference(u, false)); } /// <summary> /// Gets the indices to the usages in the usage set. /// </summary> public IEnumerable<Index> Usages { get { LinkedListNode<WeakReference> cur = this._Set.First; while (cur != null) { LinkedListNode<WeakReference> next = cur.Next; WeakReference val = cur.Value; if (val.IsAlive) { yield return new Index() { _Node = cur, _Value = (TUsage)val.Target }; } else { this._Set.Remove(cur); } cur = next; } } } + /// <summary> + /// Gets an approximation of the size of the usage set (this may change often). + /// </summary> + public int Size + { + get + { + return this._Set.Count; + } + } + /// <summary> /// Adds (or rather, makes informed) a usage to the usage set. /// </summary> public Index Add(TUsage Usage) { return new Index() { _Value = Usage, _Node = this._Set.AddFirst(new WeakReference(Usage, false)) }; } /// <summary> /// Informs the usage set that the usage at the specified index has been accepted as useful. This allows the /// usage set to reorder usages by usefulness as needed. /// </summary> public void Accept(Index Index) { this._Set.Remove(Index._Node); this._Set.AddFirst(Index._Node); } /// <summary> /// An index to a particular usage in the usage set. /// </summary> public struct Index { /// <summary> /// Gets the value of the usage set at this index. /// </summary> public TUsage Value { get { return this._Value; } } internal TUsage _Value; internal LinkedListNode<WeakReference> _Node; } private LinkedList<WeakReference> _Set; } } \ No newline at end of file diff --git a/Alunite/Vector.cs b/Alunite/Vector.cs index cb2ed10..92104b0 100644 --- a/Alunite/Vector.cs +++ b/Alunite/Vector.cs @@ -1,174 +1,182 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in three-dimensional space. /// </summary> public struct Vector { public Vector(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } public static implicit operator Vector3d(Vector Vector) { return new Vector3d(Vector.X, Vector.Y, Vector.Z); } public static explicit operator Vector3(Vector Vector) { return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); } public static bool operator ==(Vector A, Vector B) { return A.X == B.X && A.Y == B.Y && A.Z == B.Z; } public static bool operator !=(Vector A, Vector B) { return A.X != B.X || A.Y != B.Y || A.Z != B.Z; } public static Vector operator +(Vector A, Vector B) { return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vector operator -(Vector A, Vector B) { return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vector operator *(Vector A, double Magnitude) { return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); } public static Vector operator -(Vector A) { return new Vector(-A.X, -A.Y, -A.Z); } public override string ToString() { return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); } public override int GetHashCode() { int xhash = this.X.GetHashCode(); int yhash = this.Y.GetHashCode(); int zhash = this.Z.GetHashCode(); return unchecked(xhash ^ (yhash + 0x1337BED5) ^ (zhash + 0x2B50CDF1) ^ (yhash << 3) ^ (yhash >> 3) ^ (zhash << 7) ^ (zhash >> 7)); } + /// <summary> + /// Gets the similarity between this vector and another if the vector is used as an offset or position. + /// </summary> + public Similarity GetOffsetSimilarity(Vector Other) + { + return (this - Other).Length; + } + /// <summary> /// Gets the cross product of two vectors. /// </summary> public static Vector Cross(Vector A, Vector B) { return new Vector( (A.Y * B.Z) - (A.Z * B.Y), (A.Z * B.X) - (A.X * B.Z), (A.X * B.Y) - (A.Y * B.X)); } /// <summary> /// Compares two vectors lexographically. /// </summary> public static bool Compare(Vector A, Vector B) { if (A.X > B.X) return true; if (A.X < B.X) return false; if (A.Y > B.Y) return true; if (A.Y < B.Y) return false; if (A.Z > B.Z) return true; return false; } /// <summary> /// Gets the outgoing ray of an object hitting a plane with the specified normal at the /// specified incoming ray. /// </summary> public static Vector Reflect(Vector Incoming, Vector Normal) { return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); } /// <summary> /// Multiplies each component of the vectors with the other's corresponding component. /// </summary> public static Vector Scale(Vector A, Vector B) { return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } /// <summary> /// Gets the dot product between two vectors. /// </summary> public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } /// <summary> /// Gets the length of the vector. /// </summary> public double Length { get { return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the length of the vector. /// </summary> public double SquareLength { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Normalizes the vector so its length is one but its direction is unchanged. /// </summary> public void Normalize() { double ilen = 1.0 / this.Length; this.X *= ilen; this.Y *= ilen; this.Z *= ilen; } /// <summary> /// Normalizes the specified vector. /// </summary> public static Vector Normalize(Vector A) { A.Normalize(); return A; } public double X; public double Y; public double Z; } } \ No newline at end of file
dzamkov/Alunite-old
5f1ba1d76598ace625a9c3607e160842ee9ccadf
Matter has sucsessfully been created, however none of the originally planned optimizations (which are the main reason I started this project) are in yet.
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 89a69c7..9c22405 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,65 +1,66 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> + <Compile Include="Approximate.cs" /> <Compile Include="FastPhysics.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Reduce.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Approximate.cs b/Alunite/Approximate.cs new file mode 100644 index 0000000..e24846b --- /dev/null +++ b/Alunite/Approximate.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// An object that can be loosely compared to another object with the same base. Similarity is described on a subjective exponential scale + /// with a double. 0.0 indicates objects are identical while +infinity indicates objects are opposites. The geometric mean of + /// the similarity of any combination of objects of a common base should be near 1.0. + /// </summary> + /// <remarks>The similarity between numbers is the absolute value of their difference.</remarks> + public interface IApproximatable<TBase> + where TBase : IApproximatable<TBase> + { + /// <summary> + /// Gets the similarity this object has with another. + /// </summary> + double GetSimilarity(TBase Object); + } +} \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index e0d96aa..04b2aa2 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,149 +1,286 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { - throw new NotImplementedException(); + return new FastPhysicsMatter._SphereTree(this).Create(Matter); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { - + this._Usages = new UsageSet<_Binary>(); } + /// <summary> + /// Gets the bounding sphere for this matter. The bounding sphere encloses all mass within the matter and does not + /// have any correlation to where the matter can apply force. + /// </summary> + public abstract void GetBoundingSphere(out Vector Position, out double Radius); + /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } /// <summary> /// Gets the updated form of this matter in the specified environment after the given time. /// </summary> public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) { return null; } /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), - Source = new _Particle() + Source = /*new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance - } + }*/ _Particle.Default + }; + } + + /// <summary> + /// Combines two "bits" of matter into one. + /// </summary> + public static FastPhysicsMatter Combine(FastPhysics Physics, FastPhysicsMatter A, FastPhysicsMatter B) + { + // Untransform + _Transformed atrans = A as _Transformed; + _Transformed btrans = B as _Transformed; + Transform atob = Transform.Identity; + if (btrans != null) + { + atob = btrans.Transform; + B = btrans.Source; + } + Transform? full = null; + if (atrans != null) + { + Transform fullval = atrans.Transform; + full = fullval = atrans.Transform; + atob = atob.Apply(fullval.Inverse); + A = atrans.Source; + } + + // Create binary matter + FastPhysicsMatter._Binary bin = new _Binary() + { + A = A, + B = B, + AToB = atob }; + Vector posa; double rada; A.GetBoundingSphere(out posa, out rada); + Vector posb; double radb; B.GetBoundingSphere(out posb, out radb); posb = atob.ApplyToOffset(posb); + SphereTree<FastPhysicsMatter>.Enclose(posa, rada, posb, radb, out bin.BoundCenter, out bin.BoundRadius); + + + // Retransform (if needed) + FastPhysicsMatter res = bin; + if (full != null) + { + res = new _Transformed() + { + Source = res, + Transform = full.Value + }; + } + return res; + } + + /// <summary> + /// A sphere tree for matter. + /// </summary> + internal class _SphereTree : SphereTree<FastPhysicsMatter> + { + public _SphereTree(FastPhysics Physics) + { + this._Physics = Physics; + } + + public override FastPhysicsMatter CreateCompound(FastPhysicsMatter A, FastPhysicsMatter B) + { + return Combine(this._Physics, A, B); + } + + public override void GetBound(FastPhysicsMatter Node, out Vector Position, out double Radius) + { + Node.GetBoundingSphere(out Position, out Radius); + } + + public override bool GetSubnodes(FastPhysicsMatter Node, ref FastPhysicsMatter A, ref FastPhysicsMatter B) + { + return Node._GetSubnodes(this._Physics, ref A, ref B); + } + + private FastPhysics _Physics; + } + + /// <summary> + /// Gets the subnodes for this node for use in a sphere tree. + /// </summary> + internal virtual bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) + { + return false; } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { + /// <summary> + /// Default particle. + /// </summary> + public static readonly _Particle Default = new _Particle(); + + public override void GetBoundingSphere(out Vector Position, out double Radius) + { + Position = new Vector(0.0, 0.0, 0.0); + Radius = 0.0; + } + public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } + public override void GetBoundingSphere(out Vector Position, out double Radius) + { + Source.GetBoundingSphere(out Position, out Radius); + Position = Transform.Offset + Transform.Rotation.Rotate(Position); + } + + internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) + { + if (this.Source._GetSubnodes(Physics, ref A, ref B)) + { + A = A.Apply(Physics, this.Transform); + B = B.Apply(Physics, this.Transform); + return true; + } + return false; + } + public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { + public override void GetBoundingSphere(out Vector Position, out double Radius) + { + Position = this.BoundCenter; + Radius = this.BoundRadius; + } + + internal override bool _GetSubnodes(FastPhysics Physics, ref FastPhysicsMatter A, ref FastPhysicsMatter B) + { + A = this.A; + B = this.B.Apply(Physics, this.AToB); + return true; + } + + public Vector BoundCenter; + public double BoundRadius; public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } + + private UsageSet<_Binary> _Usages; } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { - + this._Usages = new UsageSet<FastPhysicsMatter._Particle>(); } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } + + private UsageSet<FastPhysicsMatter._Particle> _Usages; } } \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 60f4d29..e804a56 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,106 +1,122 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); /// <summary> /// Gets matter that has no affect or interaction in the physics system. /// </summary> TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } + /// <summary> + /// Applies this transform to an offset vector. + /// </summary> + public Vector ApplyToOffset(Vector Offset) + { + return this.Offset + this.Rotation.Rotate(Offset); + } + + /// <summary> + /// Applies a transform to this transform. + /// </summary> + public Transform Apply(Transform Transform) + { + return Transform.ApplyTo(this); + } + /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/SphereTree.cs b/Alunite/SphereTree.cs index 9dab08d..01370b0 100644 --- a/Alunite/SphereTree.cs +++ b/Alunite/SphereTree.cs @@ -1,184 +1,192 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Partions and organizes spherical nodes containing data into a bounding volume hierarchy. Note that this object does not contain /// an actual tree, just the properties of the tree's its nodes make. /// </summary> public abstract class SphereTree<TNode> { + /// <summary> + /// Gets the position and radius of a sphere that encloses two other spheres. + /// </summary> + public static void Enclose(Vector PosA, double RadA, Vector PosB, double RadB, out Vector Pos, out double Rad) + { + Vector dir = PosB - PosA; + double dis = dir.Length; + dir *= 1.0 / dis; + Rad = (dis + RadA + RadB) * 0.5; + Pos = PosA + dir * (Rad - RadA); + } + /// <summary> /// Gets the position and radius of the specified node. /// </summary> public abstract void GetBound(TNode Node, out Vector Position, out double Radius); /// <summary> /// Gets the subnodes for a node, if the node is a compound node. /// </summary> public abstract bool GetSubnodes(TNode Node, ref TNode A, ref TNode B); /// <summary> /// Creates a compound node containing the two specified subnodes. /// </summary> public abstract TNode CreateCompound(TNode A, TNode B); /// <summary> /// Creates a well-balanced tree containing the given nodes. /// </summary> public TNode Create(IEnumerable<TNode> Nodes) { TNode cur = default(TNode); IEnumerator<TNode> e = Nodes.GetEnumerator(); if (e.MoveNext()) { cur = e.Current; while (e.MoveNext()) { cur = this.Insert(cur, e.Current); } } return cur; } /// <summary> /// Inserts node B into tree A leaving them well-balanced. /// </summary> public TNode Insert(TNode A, TNode B) { TNode suba = default(TNode); TNode subb = default(TNode); if (!this.GetSubnodes(A, ref suba, ref subb)) { return this.CreateCompound(A, B); } Vector possuba; double radsuba; Vector possubb; double radsubb; Vector posb; double radb; Vector posa; double rada; this.GetBound(suba, out possuba, out radsuba); this.GetBound(subb, out possubb, out radsubb); this.GetBound(A, out posa, out rada); this.GetBound(B, out posb, out radb); double subdis = rada * 2.0; double subadis = (possuba - posb).Length + radsuba + radb; double subbdis = (possubb - posb).Length + radsubb + radb; if (subdis < subadis) { if (subdis < subbdis) { return this.CreateCompound(A, B); } else { return this.CreateCompound(this.Insert(subb, B), suba); } } else { if (subadis < subbdis) { return this.CreateCompound(this.Insert(suba, B), subb); } else { return this.CreateCompound(this.Insert(subb, B), suba); } } } } /// <summary> /// A sphere tree that automatically creates and maintains compound nodes which track position, radius and subnodes. /// </summary> public abstract class SimpleSphereTree<TLeaf> : SphereTree<SimpleSphereTreeNode<TLeaf>> { /// <summary> /// Gets the bounding sphere for a leaf. /// </summary> public abstract void GetBound(TLeaf Leaf, out Vector Position, out double Radius); /// <summary> /// Creates a leaf node for a leaf. /// </summary> public SimpleSphereTreeNode<TLeaf> Create(TLeaf Leaf) { return new SimpleSphereTreeNode<TLeaf>._Leaf() { Leaf = Leaf }; } public sealed override void GetBound(SimpleSphereTreeNode<TLeaf> Node, out Vector Position, out double Radius) { Node._GetBound(this, out Position, out Radius); } public sealed override bool GetSubnodes(SimpleSphereTreeNode<TLeaf> Node, ref SimpleSphereTreeNode<TLeaf> A, ref SimpleSphereTreeNode<TLeaf> B) { var c = Node as SimpleSphereTreeNode<TLeaf>._Compound; if (c != null) { A = c.A; B = c.B; return true; } return false; } public sealed override SimpleSphereTreeNode<TLeaf> CreateCompound(SimpleSphereTreeNode<TLeaf> A, SimpleSphereTreeNode<TLeaf> B) { Vector posa; double rada; this.GetBound(A, out posa, out rada); Vector posb; double radb; this.GetBound(B, out posb, out radb); - Vector dir = posb - posa; - double dis = dir.Length; - dir *= 1.0 / dis; - - double rad = (dis + rada + radb) * 0.5; - Vector pos = posa + dir * (rad - rada); + Vector pos; double rad; Enclose(posa, rada, posb, radb, out pos, out rad); + return new SimpleSphereTreeNode<TLeaf>._Compound() { A = A, B = B, Radius = rad, Position = pos }; } } /// <summary> /// A node for a SimpleSphereTree. /// </summary> public abstract class SimpleSphereTreeNode<TLeaf> { internal abstract void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius); internal class _Leaf : SimpleSphereTreeNode<TLeaf> { internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) { Tree.GetBound(this.Leaf, out Position, out Radius); } public TLeaf Leaf; } internal class _Compound : SimpleSphereTreeNode<TLeaf> { internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) { Position = this.Position; Radius = this.Radius; } public Vector Position; public double Radius; public SimpleSphereTreeNode<TLeaf> A; public SimpleSphereTreeNode<TLeaf> B; } } } \ No newline at end of file diff --git a/Alunite/Vector.cs b/Alunite/Vector.cs index 203b1df..cb2ed10 100644 --- a/Alunite/Vector.cs +++ b/Alunite/Vector.cs @@ -1,166 +1,174 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a point or offset in three-dimensional space. /// </summary> public struct Vector { public Vector(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } public static implicit operator Vector3d(Vector Vector) { return new Vector3d(Vector.X, Vector.Y, Vector.Z); } public static explicit operator Vector3(Vector Vector) { return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); } public static bool operator ==(Vector A, Vector B) { return A.X == B.X && A.Y == B.Y && A.Z == B.Z; } public static bool operator !=(Vector A, Vector B) { return A.X != B.X || A.Y != B.Y || A.Z != B.Z; } public static Vector operator +(Vector A, Vector B) { return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vector operator -(Vector A, Vector B) { return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vector operator *(Vector A, double Magnitude) { return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); } public static Vector operator -(Vector A) { return new Vector(-A.X, -A.Y, -A.Z); } public override string ToString() { return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); } + public override int GetHashCode() + { + int xhash = this.X.GetHashCode(); + int yhash = this.Y.GetHashCode(); + int zhash = this.Z.GetHashCode(); + return unchecked(xhash ^ (yhash + 0x1337BED5) ^ (zhash + 0x2B50CDF1) ^ (yhash << 3) ^ (yhash >> 3) ^ (zhash << 7) ^ (zhash >> 7)); + } + /// <summary> /// Gets the cross product of two vectors. /// </summary> public static Vector Cross(Vector A, Vector B) { return new Vector( (A.Y * B.Z) - (A.Z * B.Y), (A.Z * B.X) - (A.X * B.Z), (A.X * B.Y) - (A.Y * B.X)); } /// <summary> /// Compares two vectors lexographically. /// </summary> public static bool Compare(Vector A, Vector B) { if (A.X > B.X) return true; if (A.X < B.X) return false; if (A.Y > B.Y) return true; if (A.Y < B.Y) return false; if (A.Z > B.Z) return true; return false; } /// <summary> /// Gets the outgoing ray of an object hitting a plane with the specified normal at the /// specified incoming ray. /// </summary> public static Vector Reflect(Vector Incoming, Vector Normal) { return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); } /// <summary> /// Multiplies each component of the vectors with the other's corresponding component. /// </summary> public static Vector Scale(Vector A, Vector B) { return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } /// <summary> /// Gets the dot product between two vectors. /// </summary> public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } /// <summary> /// Gets the length of the vector. /// </summary> public double Length { get { return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); } } /// <summary> /// Gets the square of the length of the vector. /// </summary> public double SquareLength { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z; } } /// <summary> /// Normalizes the vector so its length is one but its direction is unchanged. /// </summary> public void Normalize() { double ilen = 1.0 / this.Length; this.X *= ilen; this.Y *= ilen; this.Z *= ilen; } /// <summary> /// Normalizes the specified vector. /// </summary> public static Vector Normalize(Vector A) { A.Normalize(); return A; } public double X; public double Y; public double Z; } } \ No newline at end of file
dzamkov/Alunite-old
fcbe3926e3690905f906e7f528e4001224b89e11
UsageSet
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 612ce5a..89a69c7 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,64 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="FastPhysics.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Reduce.cs" /> <Compile Include="SphereTree.cs" /> + <Compile Include="UsageSet.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 650cb03..e0d96aa 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,141 +1,149 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { - throw new NotImplementedException(); + return Matter.Update(this, Environment, Time); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { throw new NotImplementedException(); } public FastPhysicsMatter Null { get { return null; } } } /// <summary> /// Matter in a fast physics system. /// </summary> public abstract class FastPhysicsMatter : IMatter { private FastPhysicsMatter() { } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this, Transform = Transform }; } + /// <summary> + /// Gets the updated form of this matter in the specified environment after the given time. + /// </summary> + public virtual FastPhysicsMatter Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time) + { + return null; + } + /// <summary> /// Creates matter for a particle. /// </summary> public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) { return new _Transformed() { Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), Source = new _Particle() { Mass = Particle.Mass, Spin = Particle.Spin, Substance = Particle.Substance } }; } /// <summary> /// Matter containing a single particle. /// </summary> internal class _Particle : FastPhysicsMatter { public ISubstance Substance; public double Mass; public Quaternion Spin; } /// <summary> /// Matter created by transforming some source matter. /// </summary> internal class _Transformed : FastPhysicsMatter { public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) { return new _Transformed() { Source = this.Source, Transform = Transform.ApplyTo(this.Transform) }; } public FastPhysicsMatter Source; public Transform Transform; } /// <summary> /// Matter created by the combination of some untransformed matter and some /// transformed matter. /// </summary> internal class _Binary : FastPhysicsMatter { public FastPhysicsMatter A; public FastPhysicsMatter B; public Transform AToB; } } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } } } \ No newline at end of file diff --git a/Alunite/UsageSet.cs b/Alunite/UsageSet.cs new file mode 100644 index 0000000..29e85e5 --- /dev/null +++ b/Alunite/UsageSet.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Maintains a collection of objects that contain a certain resource. This can be used to reference one of the using objects + /// directly when it is identical to the target object. The set weakly references target objects and will sort them by likeliness + /// of being accepted. + /// </summary> + public class UsageSet<TUsage> + { + public UsageSet() + { + this._Set = new LinkedList<WeakReference>(); + } + + public UsageSet(IEnumerable<TUsage> Usages) + { + this._Set = new LinkedList<WeakReference>( + from u in Usages + select new WeakReference(u, false)); + } + + /// <summary> + /// Gets the indices to the usages in the usage set. + /// </summary> + public IEnumerable<Index> Usages + { + get + { + LinkedListNode<WeakReference> cur = this._Set.First; + while (cur != null) + { + LinkedListNode<WeakReference> next = cur.Next; + WeakReference val = cur.Value; + if (val.IsAlive) + { + yield return new Index() + { + _Node = cur, + _Value = (TUsage)val.Target + }; + } + else + { + this._Set.Remove(cur); + } + cur = next; + } + } + } + + /// <summary> + /// Adds (or rather, makes informed) a usage to the usage set. + /// </summary> + public Index Add(TUsage Usage) + { + return new Index() + { + _Value = Usage, + _Node = this._Set.AddFirst(new WeakReference(Usage, false)) + }; + } + + /// <summary> + /// Informs the usage set that the usage at the specified index has been accepted as useful. This allows the + /// usage set to reorder usages by usefulness as needed. + /// </summary> + public void Accept(Index Index) + { + this._Set.Remove(Index._Node); + this._Set.AddFirst(Index._Node); + } + + /// <summary> + /// An index to a particular usage in the usage set. + /// </summary> + public struct Index + { + /// <summary> + /// Gets the value of the usage set at this index. + /// </summary> + public TUsage Value + { + get + { + return this._Value; + } + } + + internal TUsage _Value; + internal LinkedListNode<WeakReference> _Node; + } + + private LinkedList<WeakReference> _Set; + } +} \ No newline at end of file
dzamkov/Alunite-old
f663c141f488ff1bea5eed755a5ad004db3a2bbe
Starting to implement things
diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs index 0cf24f7..650cb03 100644 --- a/Alunite/FastPhysics.cs +++ b/Alunite/FastPhysics.cs @@ -1,62 +1,141 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// A physics system where interactions between matter are memozied allowing for /// faster simulation. /// </summary> public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> { public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) { - throw new NotImplementedException(); + return FastPhysicsMatter.Particle(this, Particle); } public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) { - throw new NotImplementedException(); + return Matter.Apply(this, Transform); } public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) { throw new NotImplementedException(); } public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) { throw new NotImplementedException(); } + + public FastPhysicsMatter Null + { + get + { + return null; + } + } } /// <summary> /// Matter in a fast physics system. /// </summary> - public class FastPhysicsMatter : IMatter + public abstract class FastPhysicsMatter : IMatter { + private FastPhysicsMatter() + { + + } + /// <summary> + /// Applies a transform to this matter. + /// </summary> + public virtual FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) + { + return new _Transformed() + { + Source = this, + Transform = Transform + }; + } + + /// <summary> + /// Creates matter for a particle. + /// </summary> + public static FastPhysicsMatter Particle(FastPhysics Physics, Particle<FastPhysicsSubstance> Particle) + { + return new _Transformed() + { + Transform = new Transform(Particle.Position, Particle.Velocity, Particle.Orientation), + Source = new _Particle() + { + Mass = Particle.Mass, + Spin = Particle.Spin, + Substance = Particle.Substance + } + }; + } + + /// <summary> + /// Matter containing a single particle. + /// </summary> + internal class _Particle : FastPhysicsMatter + { + public ISubstance Substance; + public double Mass; + public Quaternion Spin; + } + + /// <summary> + /// Matter created by transforming some source matter. + /// </summary> + internal class _Transformed : FastPhysicsMatter + { + public override FastPhysicsMatter Apply(FastPhysics Physics, Transform Transform) + { + return new _Transformed() + { + Source = this.Source, + Transform = Transform.ApplyTo(this.Transform) + }; + } + + public FastPhysicsMatter Source; + public Transform Transform; + } + + /// <summary> + /// Matter created by the combination of some untransformed matter and some + /// transformed matter. + /// </summary> + internal class _Binary : FastPhysicsMatter + { + public FastPhysicsMatter A; + public FastPhysicsMatter B; + public Transform AToB; + } } /// <summary> /// A substance in a fast physics system. /// </summary> public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> { private FastPhysicsSubstance() { } /// <summary> /// The default (and currently only) possible substance. /// </summary> public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) { Particle.Update(Time); } } } \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index aa7485a..60f4d29 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,101 +1,106 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> public interface IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting /// upon the target matter. /// </summary> TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> /// Creates some matter that is the physical composition of other matter. /// </summary> TMatter Compose(IEnumerable<TMatter> Matter); + + /// <summary> + /// Gets matter that has no affect or interaction in the physics system. + /// </summary> + TMatter Null { get; } } /// <summary> /// A physical system that acts in three-dimensional space. /// </summary> public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> where TMatter : IMatter { /// <summary> /// Applies a transformation to some matter. /// </summary> TMatter Transform(TMatter Matter, Transform Transform); } /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public interface IMatter { } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index e5f501e..9acd158 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,26 +1,56 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { + // Set up a world + FastPhysics fp = new FastPhysics(); + List<FastPhysicsMatter> elems = new List<FastPhysicsMatter>(); + double size = 0.5; + double step = 0.1; + for (double x = -size + step * 0.5; x < size; x += step) + { + for (double y = -size + step * 0.5; y < size; y += step) + { + for (double z = -size + step * 0.5; z < size; z += step) + { + elems.Add(fp.Create(new Particle<FastPhysicsSubstance>() + { + Substance = FastPhysicsSubstance.Default, + Mass = 1.0, + Position = new Vector(x, y, z), + Velocity = new Vector(0.0, 0.0, 0.0), + Orientation = Quaternion.Identity, + Spin = Quaternion.Identity + })); + } + } + } + FastPhysicsMatter world = fp.Compose(elems); + + for (int t = 0; t < 10; t++) + { + world = fp.Update(world, fp.Null, 0.1); + } + /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } } } \ No newline at end of file
dzamkov/Alunite-old
ea93c34aea7701b42021743f44656316316d41ed
More organizing as I prepare to strike (write meaningful code)
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 0101703..612ce5a 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,63 +1,64 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> + <Compile Include="FastPhysics.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Reduce.cs" /> <Compile Include="SphereTree.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/FastPhysics.cs b/Alunite/FastPhysics.cs new file mode 100644 index 0000000..0cf24f7 --- /dev/null +++ b/Alunite/FastPhysics.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// A physics system where interactions between matter are memozied allowing for + /// faster simulation. + /// </summary> + public class FastPhysics : IParticlePhysics<FastPhysicsMatter, FastPhysicsSubstance> + { + public FastPhysicsMatter Create(Particle<FastPhysicsSubstance> Particle) + { + throw new NotImplementedException(); + } + + public FastPhysicsMatter Transform(FastPhysicsMatter Matter, Transform Transform) + { + throw new NotImplementedException(); + } + + public FastPhysicsMatter Update(FastPhysicsMatter Matter, FastPhysicsMatter Environment, double Time) + { + throw new NotImplementedException(); + } + + public FastPhysicsMatter Compose(IEnumerable<FastPhysicsMatter> Matter) + { + throw new NotImplementedException(); + } + } + + /// <summary> + /// Matter in a fast physics system. + /// </summary> + public class FastPhysicsMatter : IMatter + { + + } + + /// <summary> + /// A substance in a fast physics system. + /// </summary> + public class FastPhysicsSubstance : IAutoSubstance<FastPhysics, FastPhysicsMatter, FastPhysicsSubstance> + { + private FastPhysicsSubstance() + { + + } + + /// <summary> + /// The default (and currently only) possible substance. + /// </summary> + public static readonly FastPhysicsSubstance Default = new FastPhysicsSubstance(); + + public void Update(FastPhysics Physics, FastPhysicsMatter Environment, double Time, ref Particle<FastPhysicsSubstance> Particle) + { + Particle.Update(Time); + } + } +} \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index bb26c81..1604e40 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,32 +1,85 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> - /// Descibes the physical properties of a particle. + /// A physical system that allows the introduction and simulation of particles. /// </summary> - public interface ISubstance<TPhysics, TMatter> - where TPhysics : IParticlePhysics<TPhysics, TMatter> + public interface IParticlePhysics<TMatter, TSubstance> : ISpatialPhysics<TMatter> where TMatter : IMatter + where TSubstance : ISubstance { /// <summary> - /// Updates a particle of this substance. + /// Creates a matter form of a single particle with the specified properties. /// </summary> - void Update(TPhysics Physics, TMatter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); + TMatter Create(Particle<TSubstance> Particle); } /// <summary> - /// A physical system that allows the introduction and simulation of particles. + /// Contains the properties of a particle. + /// </summary> + public struct Particle<TSubstance> + { + /// <summary> + /// The substance the particle is of. + /// </summary> + public TSubstance Substance; + + /// <summary> + /// The relative position of the particle. + /// </summary> + public Vector Position; + + /// <summary> + /// The relative velocity of the particle. + /// </summary> + public Vector Velocity; + + /// <summary> + /// The orientation of the particle. + /// </summary> + public Quaternion Orientation; + + /// <summary> + /// The angular velocity of the particle. + /// </summary> + public Quaternion Spin; + + /// <summary> + /// The mass of the particle in kilograms. + /// </summary> + public double Mass; + + /// <summary> + /// Updates the spatial state of this particle by the given amount of time in seconds. + /// </summary> + public void Update(double Time) + { + this.Position += this.Velocity * Time; + } + } + + /// <summary> + /// Descibes the physical properties of a particle. /// </summary> - public interface IParticlePhysics<TSelf, TMatter> : ISpatialPhysics<TMatter> - where TSelf : IParticlePhysics<TSelf, TMatter> + public interface ISubstance + { + + } + + /// <summary> + /// A substance with known interactions in a certain kind of physics system. + /// </summary> + public interface IAutoSubstance<TPhysics, TMatter, TSubstance> : ISubstance + where TPhysics : IParticlePhysics<TMatter, TSubstance> where TMatter : IMatter + where TSubstance : IAutoSubstance<TPhysics, TMatter, TSubstance> { /// <summary> - /// Creates a matter form of a single particle with the specified properties. + /// Updates a particle of this kind of substance in the given environment. /// </summary> - TMatter Create(ISubstance<TSelf, TMatter> Substance, Vector Position, Vector Velocity, Quaternion Orientation, double Mass); + void Update(TPhysics Physics, TMatter Environment, double Time, ref Particle<TSubstance> Particle); } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index c5765eb..e5f501e 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,47 +1,26 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Random r = new Random(); - - // Create point set - _SphereTree st = new _SphereTree(); - var points = new List<SimpleSphereTreeNode<Vector>>(); - for (int t = 0; t < 1000000; t++) - { - points.Add(st.Create(new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()))); - } - SimpleSphereTreeNode<Vector> node = st.Create(points); - return; - /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } - - private class _SphereTree : SimpleSphereTree<Vector> - { - public override void GetBound(Vector Leaf, out Vector Position, out double Radius) - { - Position = Leaf; - Radius = 0.0; - } - } } } \ No newline at end of file
dzamkov/Alunite-old
c9109df96a013959dd3036e9e59da69f57ba4dd2
Better "OSP"
diff --git a/Alunite/Program.cs b/Alunite/Program.cs index c96806d..c5765eb 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,28 +1,47 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Random r = new Random(); + // Create point set + _SphereTree st = new _SphereTree(); + var points = new List<SimpleSphereTreeNode<Vector>>(); + for (int t = 0; t < 1000000; t++) + { + points.Add(st.Create(new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()))); + } + SimpleSphereTreeNode<Vector> node = st.Create(points); + return; + /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0);*/ } + + private class _SphereTree : SimpleSphereTree<Vector> + { + public override void GetBound(Vector Leaf, out Vector Position, out double Radius) + { + Position = Leaf; + Radius = 0.0; + } + } } } \ No newline at end of file diff --git a/Alunite/SphereTree.cs b/Alunite/SphereTree.cs index e68d11c..9dab08d 100644 --- a/Alunite/SphereTree.cs +++ b/Alunite/SphereTree.cs @@ -1,114 +1,184 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> - /// Partions and organizes spherical nodes containing data into a bounding volume hierarchy. + /// Partions and organizes spherical nodes containing data into a bounding volume hierarchy. Note that this object does not contain + /// an actual tree, just the properties of the tree's its nodes make. /// </summary> public abstract class SphereTree<TNode> { /// <summary> /// Gets the position and radius of the specified node. /// </summary> public abstract void GetBound(TNode Node, out Vector Position, out double Radius); /// <summary> /// Gets the subnodes for a node, if the node is a compound node. /// </summary> public abstract bool GetSubnodes(TNode Node, ref TNode A, ref TNode B); /// <summary> /// Creates a compound node containing the two specified subnodes. /// </summary> public abstract TNode CreateCompound(TNode A, TNode B); + + /// <summary> + /// Creates a well-balanced tree containing the given nodes. + /// </summary> + public TNode Create(IEnumerable<TNode> Nodes) + { + TNode cur = default(TNode); + IEnumerator<TNode> e = Nodes.GetEnumerator(); + if (e.MoveNext()) + { + cur = e.Current; + while (e.MoveNext()) + { + cur = this.Insert(cur, e.Current); + } + } + return cur; + } + + /// <summary> + /// Inserts node B into tree A leaving them well-balanced. + /// </summary> + public TNode Insert(TNode A, TNode B) + { + TNode suba = default(TNode); + TNode subb = default(TNode); + if (!this.GetSubnodes(A, ref suba, ref subb)) + { + return this.CreateCompound(A, B); + } + + Vector possuba; double radsuba; + Vector possubb; double radsubb; + Vector posb; double radb; + Vector posa; double rada; + this.GetBound(suba, out possuba, out radsuba); + this.GetBound(subb, out possubb, out radsubb); + this.GetBound(A, out posa, out rada); + this.GetBound(B, out posb, out radb); + + double subdis = rada * 2.0; + double subadis = (possuba - posb).Length + radsuba + radb; + double subbdis = (possubb - posb).Length + radsubb + radb; + if (subdis < subadis) + { + if (subdis < subbdis) + { + return this.CreateCompound(A, B); + } + else + { + return this.CreateCompound(this.Insert(subb, B), suba); + } + } + else + { + if (subadis < subbdis) + { + return this.CreateCompound(this.Insert(suba, B), subb); + } + else + { + return this.CreateCompound(this.Insert(subb, B), suba); + } + } + } } /// <summary> /// A sphere tree that automatically creates and maintains compound nodes which track position, radius and subnodes. /// </summary> public abstract class SimpleSphereTree<TLeaf> : SphereTree<SimpleSphereTreeNode<TLeaf>> { /// <summary> /// Gets the bounding sphere for a leaf. /// </summary> public abstract void GetBound(TLeaf Leaf, out Vector Position, out double Radius); /// <summary> /// Creates a leaf node for a leaf. /// </summary> public SimpleSphereTreeNode<TLeaf> Create(TLeaf Leaf) { return new SimpleSphereTreeNode<TLeaf>._Leaf() { Leaf = Leaf }; } public sealed override void GetBound(SimpleSphereTreeNode<TLeaf> Node, out Vector Position, out double Radius) { Node._GetBound(this, out Position, out Radius); } public sealed override bool GetSubnodes(SimpleSphereTreeNode<TLeaf> Node, ref SimpleSphereTreeNode<TLeaf> A, ref SimpleSphereTreeNode<TLeaf> B) { var c = Node as SimpleSphereTreeNode<TLeaf>._Compound; if (c != null) { A = c.A; B = c.B; return true; } return false; } public sealed override SimpleSphereTreeNode<TLeaf> CreateCompound(SimpleSphereTreeNode<TLeaf> A, SimpleSphereTreeNode<TLeaf> B) { Vector posa; double rada; this.GetBound(A, out posa, out rada); Vector posb; double radb; this.GetBound(B, out posb, out radb); Vector dir = posb - posa; double dis = dir.Length; dir *= 1.0 / dis; + double rad = (dis + rada + radb) * 0.5; + Vector pos = posa + dir * (rad - rada); + return new SimpleSphereTreeNode<TLeaf>._Compound() { A = A, B = B, - Radius = (dis + rada + radb) * 0.5, - Position = posa + dir * (dis * 0.5 + rada) + Radius = rad, + Position = pos }; } } /// <summary> /// A node for a SimpleSphereTree. /// </summary> public abstract class SimpleSphereTreeNode<TLeaf> { internal abstract void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius); internal class _Leaf : SimpleSphereTreeNode<TLeaf> { internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) { Tree.GetBound(this.Leaf, out Position, out Radius); } public TLeaf Leaf; } internal class _Compound : SimpleSphereTreeNode<TLeaf> { internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) { Position = this.Position; Radius = this.Radius; } public Vector Position; public double Radius; public SimpleSphereTreeNode<TLeaf> A; public SimpleSphereTreeNode<TLeaf> B; } } } \ No newline at end of file
dzamkov/Alunite-old
656dc50de5941fd3572477b4a61734e21759abc3
Shameful reorganizing and reworking
diff --git a/Alunite/Adminium.cs b/Alunite/Adminium.cs deleted file mode 100644 index 8578e0c..0000000 --- a/Alunite/Adminium.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -using OpenTKGUI; - -namespace Alunite -{ - /// <summary> - /// A simple substances that will not change velocity in response to a force, in effect making it static. - /// </summary> - public class Adminium : IVisualSubstance - { - public Color Color - { - get - { - return Color.RGB(0.5, 0.5, 0.5); - } - } - - public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) - { - Position += Velocity * Time; - return this; - } - } -} \ No newline at end of file diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 78d6612..0101703 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,67 +1,63 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> - <Compile Include="Adminium.cs" /> - <Compile Include="BinaryMatter.cs" /> - <Compile Include="BlobMatter.cs" /> - <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Reduce.cs" /> - <Compile Include="OSP.cs" /> + <Compile Include="SphereTree.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/BinaryMatter.cs b/Alunite/BinaryMatter.cs deleted file mode 100644 index ba2b021..0000000 --- a/Alunite/BinaryMatter.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Matter composed of two elements. - /// </summary> - public class BinaryMatter : CompositeMatter - { - public BinaryMatter(Matter A, Matter B) - { - this._A = A; - this._B = B; - } - - /// <summary> - /// Creates some binary matter. - /// </summary> - public static BinaryMatter Create(Matter A, Matter B) - { - return new BinaryMatter(A, B); - } - - public override IEnumerable<Matter> Elements - { - get - { - yield return this._A; - yield return this._B; - } - } - - public override Matter Apply(Transform Transform) - { - return BinaryMatter.Create( - this._A.Apply(Transform), - this._B.Apply(Transform)); - } - - public override Matter Update(Matter Environment, double Time) - { - Matter na = this._A.Update(BinaryMatter.Create(Environment, this._B), Time); - Matter nb = this._B.Update(BinaryMatter.Create(Environment, this._A), Time); - return BinaryMatter.Create(na, nb); - } - - private Matter _A; - private Matter _B; - } -} \ No newline at end of file diff --git a/Alunite/BlobMatter.cs b/Alunite/BlobMatter.cs deleted file mode 100644 index 54ddfb2..0000000 --- a/Alunite/BlobMatter.cs +++ /dev/null @@ -1,226 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Matter composed of efficently organized particles that can only interact in a limited range. Note that it - /// is assumed that the "blob" is too light to create a gravitational force. - /// </summary> - public class BlobMatter : CompositeMatter - { - public BlobMatter(double GridSize) - { - this._GridSize = GridSize; - this._Grid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); - } - - private BlobMatter(double GridSize, Dictionary<_GridRef, List<Particle>> Grid) - { - this._GridSize = GridSize; - this._Grid = Grid; - } - - /// <summary> - /// Gets size of units in the grid used to organize particles. This must be above the interaction - /// distance of particles in the grid. - /// </summary> - public double GridSize - { - get - { - return this._GridSize; - } - } - - public override IEnumerable<Particle> Particles - { - get - { - return - from pl in this._Grid.Values - from p in pl - select p; - } - } - - public override IEnumerable<Matter> Elements - { - get - { - return - from p in this.Particles - select p.Matter; - } - } - - public override Vector GetGravityForce(Vector Position, double Mass) - { - return new Vector(0.0, 0.0, 0.0); - } - - public override Matter Update(Matter Environment, double Time) - { - var ngrid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); - - foreach (var kvp in this._Grid) - { - List<Particle> inunit = kvp.Value; - - // Get surronding units the particles in this unit can interact with. - List<List<Particle>> surrondunit = new List<List<Particle>>(); - _GridRef gref = kvp.Key; - for (int x = gref.X - 1; x <= gref.X + 1; x++) - { - for (int y = gref.Y - 1; y <= gref.Y + 1; y++) - { - for (int z = gref.Z - 1; z <= gref.Z + 1; z++) - { - _GridRef sref = new _GridRef(x, y, z); - if (sref.X != gref.X || sref.Y != gref.Y || sref.Z != gref.Z) - { - List<Particle> sunit; - if (this._Grid.TryGetValue(sref, out sunit)) - { - surrondunit.Add(sunit); - } - } - } - } - } - - // Update particles - for (int t = 0; t < inunit.Count; t++) - { - Particle p = inunit[t]; - _GridEnvironment e = new _GridEnvironment() - { - InUnit = inunit, - CurIndex = t, - SurrondUnit = surrondunit - }; - p.Substance = p.Substance.Update( - BinaryMatter.Create(Environment, e), - Time, - ref p.Position, - ref p.Velocity, - ref p.Orientation, - ref p.Mass); - _Add(ngrid, this._GridSize, p); - } - } - - return new BlobMatter(this._GridSize, ngrid); - } - - /// <summary> - /// Gets the grid reference for the specified position. - /// </summary> - private static _GridRef _ForPos(Vector Position, double GridSize) - { - return new _GridRef( - (int)(Position.X / GridSize), - (int)(Position.Y / GridSize), - (int)(Position.Z / GridSize)); - } - - /// <summary> - /// Adds a particle to a grid. - /// </summary> - private static void _Add(Dictionary<_GridRef, List<Particle>> Grid, double GridSize, Particle Particle) - { - _GridRef gref = _ForPos(Particle.Position, GridSize); - List<Particle> unit; - if (!Grid.TryGetValue(gref, out unit)) - { - unit = Grid[gref] = new List<Particle>(); - } - unit.Add(Particle); - } - - /// <summary> - /// Adds a particle to this blob. - /// </summary> - public void Add(Particle Particle) - { - _Add(this._Grid, this._GridSize, Particle); - } - - /// <summary> - /// An environment given to a particle on the grid. - /// </summary> - private class _GridEnvironment : Matter - { - public override IEnumerable<Particle> Particles - { - get - { - for (int t = 0; t < this.InUnit.Count; t++) - { - if (t != this.CurIndex) - { - yield return this.InUnit[t]; - } - } - foreach (List<Particle> unit in this.SurrondUnit) - { - foreach (Particle p in unit) - { - yield return p; - } - } - } - } - - public override Vector GetGravityForce(Vector Position, double Mass) - { - return new Vector(0.0, 0.0, 0.0); - } - - public override Matter Update(Matter Environment, double Time) - { - throw new NotImplementedException(); - } - - public int CurIndex; - public List<Particle> InUnit; - public List<List<Particle>> SurrondUnit; - } - - /// <summary> - /// A reference to a unit on the grid. - /// </summary> - private struct _GridRef - { - public _GridRef(int X, int Y, int Z) - { - this.X = X; - this.Y = Y; - this.Z = Z; - } - - public int X; - public int Y; - public int Z; - - public class EqualityComparer : IEqualityComparer<_GridRef> - { - public static readonly EqualityComparer Singleton = new EqualityComparer(); - - public bool Equals(_GridRef x, _GridRef y) - { - return x.X == y.X && x.Y == y.Y && x.Z == y.Z; - } - - public int GetHashCode(_GridRef obj) - { - return obj.X ^ (obj.Y + 0x1337BED5) ^ (obj.Z + 0x12384923) ^ (obj.Y << 3) ^ (obj.Y >> 3) ^ (obj.Z << 7) ^ (obj.Z >> 7); - } - } - } - - private Dictionary<_GridRef, List<Particle>> _Grid; - private double _GridSize; - } -} \ No newline at end of file diff --git a/Alunite/Fluid.cs b/Alunite/Fluid.cs deleted file mode 100644 index 5143745..0000000 --- a/Alunite/Fluid.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -using OpenTKGUI; - -namespace Alunite -{ - /// <summary> - /// Functions related to fluids. - /// </summary> - public static class Fluid - { - /// <summary> - /// Gets a substance for a fluid. - /// </summary> - public static ISubstance GetSubstance() - { - return new _Substance(); - } - - private class _Substance : IVisualSubstance - { - public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) - { - Vector force = Environment.GetGravityForce(Position, Mass); - - double h = 0.1; - foreach (Particle p in Environment.GetParticles(Position, h)) - { - Vector away = Position - p.Position; - double dis = away.Length; - force += away * (0.1 / (dis * dis * dis)); - } - - Velocity += force * Time; - Position += Velocity * Time; - return this; - } - - public Color Color - { - get - { - return Color.RGB(0.0, 0.5, 1.0); - } - } - } - } -} \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 8db1fb3..aa7485a 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,287 +1,101 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> - /// Represents an untransformed object that can participate in physical interactions. Note that all operations - /// on matter use units of meters, seconds, kilograms and kelvin. + /// Represents a set of physical laws that allow the interaction of matter over time. /// </summary> - public abstract class Matter + public interface IPhysics<TMatter> + where TMatter : IMatter { - private class _NullMatter : Matter - { - public override Matter Update(Matter Environment, double Time) - { - return this; - } - } - - /// <summary> - /// Gets a matter that has no effects or interactions. - /// </summary> - public static readonly Matter Null = new _NullMatter(); - - /// <summary> - /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given - /// in the frame of reference of the matter in question) by a given amount of time in seconds. - /// </summary> - public abstract Matter Update(Matter Environment, double Time); - /// <summary> - /// Gets the gravitational force that would act on an object of the given mass and at the specified offset from this matter. + /// Gets the updated state of some matter after some time elapses. The environment is all the matter acting + /// upon the target matter. /// </summary> - public virtual Vector GetGravityForce(Vector Position, double Mass) - { - Vector force = new Vector(0.0, 0.0, 0.0); - foreach (Particle p in this.Particles) - { - Vector to = p.Position - Position; - double dis = to.Length; - force += to * (Matter.G * (p.Mass + Mass) / (dis * dis * dis)); - } - return force; - } - - /// <summary> - /// Gets particles in this matter within a certain distance of the given position. - /// </summary> - public virtual IEnumerable<Particle> GetParticles(Vector Position, double Distance) - { - double dd = Distance * Distance; - return - from p in this.Particles - where (p.Position - Position).SquareLength <= dd - select p; - } - - /// <summary> - /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects - /// in kilograms and R the distance between them in meters. - /// </summary> - public static double G = 6.67428e-11; - - /// <summary> - /// Gets the particles in this matter. - /// </summary> - public virtual IEnumerable<Particle> Particles - { - get - { - return new Particle[0]; - } - } + TMatter Update(TMatter Matter, TMatter Environment, double Time); /// <summary> - /// Applies a transform to this matter. + /// Creates some matter that is the physical composition of other matter. /// </summary> - public virtual Matter Apply(Transform Transform) - { - return new TransformMatter(this, Transform); - } + TMatter Compose(IEnumerable<TMatter> Matter); } /// <summary> - /// Matter made by a physical composition of other matter. + /// A physical system that acts in three-dimensional space. /// </summary> - public abstract class CompositeMatter : Matter + public interface ISpatialPhysics<TMatter> : IPhysics<TMatter> + where TMatter : IMatter { /// <summary> - /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). - /// </summary> - public abstract IEnumerable<Matter> Elements { get; } - - public override Vector GetGravityForce(Vector Position, double Mass) - { - Vector force = new Vector(0.0, 0.0, 0.0); - foreach (Matter e in this.Elements) - { - force += e.GetGravityForce(Position, Mass); - } - return force; - } - - /// <summary> - /// Creates composite matter from the specified elements. + /// Applies a transformation to some matter. /// </summary> - public static CompositeMatter Create(IEnumerable<Matter> Elements) - { - return new _Concrete(Elements); - } - - private class _Concrete : CompositeMatter - { - public _Concrete(IEnumerable<Matter> Elements) - { - this._Elements = Elements; - } - - public override IEnumerable<Matter> Elements - { - get - { - return this._Elements; - } - } - - private IEnumerable<Matter> _Elements; - } - - public override Matter Update(Matter Environment, double Time) - { - LinkedList<Matter> elems = new LinkedList<Matter>(this.Elements); - List<Matter> res = new List<Matter>(elems.Count); - - LinkedListNode<Matter> cur = elems.First; - elems.AddFirst(Environment); - - while (cur != null) - { - Matter curmat = cur.Value; - LinkedListNode<Matter> next = cur.Next; - elems.Remove(cur); + TMatter Transform(TMatter Matter, Transform Transform); + } - res.Add(curmat.Update(Create(elems), Time)); - elems.AddFirst(curmat); - cur = next; - } - if (res.Count == 0) - { - return Matter.Null; - } - if (res.Count == 1) - { - return res[0]; - } - return Create(res); - } + /// <summary> + /// Represents an untransformed object that can participate in physical interactions. + /// </summary> + public interface IMatter + { - public override IEnumerable<Particle> Particles - { - get - { - return - from e in this.Elements - from p in e.Particles - select p; - } - } } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } - - /// <summary> - /// A piece of transformed matter. - /// </summary> - public class TransformMatter : Matter - { - public TransformMatter(Matter Source, Transform Transform) - { - this._Source = Source; - this._Transform = Transform; - } - - /// <summary> - /// Gets the transform of the source matter. - /// </summary> - public Transform Transform - { - get - { - return this._Transform; - } - } - - /// <summary> - /// Gets the source matter . - /// </summary> - public Matter Source - { - get - { - return this._Source; - } - } - - public override Matter Update(Matter Environment, double Time) - { - Transform ntrans = this._Transform; - ntrans.Offset += ntrans.VelocityOffset * Time; - return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(ntrans); - } - - public override Matter Apply(Transform Transform) - { - return new TransformMatter(this._Source, Transform.ApplyTo(this._Transform)); - } - - public override IEnumerable<Particle> Particles - { - get - { - return - from p in this._Source.Particles - select p.Apply(this._Transform); - } - } - - private Transform _Transform; - private Matter _Source; - } } \ No newline at end of file diff --git a/Alunite/OSP.cs b/Alunite/OSP.cs deleted file mode 100644 index af5b8f9..0000000 --- a/Alunite/OSP.cs +++ /dev/null @@ -1,126 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Alunite -{ - /// <summary> - /// Contains functions for finding the optimal sphere partioning of a set - /// of leaf nodes where each node is given a bounding sphere. A node can contain - /// the optimal sphere partioning of a set of leaves if the two leaves with the smallest - /// common bounding sphere are grouped in a single node and all subnodes contain the - /// optimal sphere partioning of their set of leaves. - /// </summary> - /// <remarks>Comparing nodes with optimal sphere partioning is a good way of finding patterns in a set of points.</remarks> - public static class OSP - { - /// <summary> - /// Input to an OSP finder. - /// </summary> - public interface IOSPInput<TNode, TScalar> - { - /// <summary> - /// Gets the subnodes in a node, if the node is a compound node, as opposed to a leaf node. - /// </summary> - bool GetSubnodes(TNode Node, out TNode A, out TNode B); - - /// <summary> - /// Gets if the scalar value A is larger than B. - /// </summary> - bool Greater(TScalar A, TScalar B); - - /// <summary> - /// Gets the diameter of a node. - /// </summary> - TScalar GetDiameter(TNode Node); - - /// <summary> - /// Gets the distance between two nodes at the closest points on their bounding spheres. - /// </summary> - TScalar GetShortDistance(TNode A, TNode B); - - /// <summary> - /// Gets the distance between two nodes at the furthest points on their bounding spheres. This is equivalent to - /// the diameter of the bounding sphere containing both nodes. - /// </summary> - TScalar GetLongDistance(TNode A, TNode B); - - /// <summary> - /// Creates a compound node with the specified subnodes. - /// </summary> - TNode CreateCompound(TNode A, TNode B); - } - - /// <summary> - /// Creates a (near) OSP node of the specified leaf nodes. - /// </summary> - public static TNode Create<TInput, TNode, TScalar>(TInput Input, IEnumerable<TNode> Nodes) - where TInput : IOSPInput<TNode, TScalar> - { - // Insert leafs into OSP node one at a time. - TNode cur = default(TNode); - IEnumerator<TNode> en = Nodes.GetEnumerator(); - if (en.MoveNext()) - { - cur = en.Current; - while (en.MoveNext()) - { - cur = Combine<TInput, TNode, TScalar>(Input, cur, en.Current); - } - } - return cur; - } - - /// <summary> - /// Combines two OSP nodes. This function will be faster if A is the more complex node. - /// </summary> - /// <remarks>The resulting node may not be OSP, but it will be well-balanced.</remarks> - public static TNode Combine<TInput, TNode, TScalar>(TInput Input, TNode A, TNode B) - where TInput : IOSPInput<TNode, TScalar> - { - // Get sub nodes - TNode subc; - TNode subd; - if (!Input.GetSubnodes(A, out subc, out subd)) - { - if (!Input.GetSubnodes(B, out subc, out subd)) - { - // Trivial case, both nodes are leaves - return Input.CreateCompound(A, B); - } - - // Swap A and B so that subc and subd belong to A - TNode temp = A; - A = B; - B = temp; - } - - // Create a node between C, D and B with the smallest possible diameter - TScalar cddis = Input.GetDiameter(A); - TScalar cbdis = Input.GetLongDistance(subc, B); - TScalar dbdis = Input.GetLongDistance(subd, B); - if (Input.Greater(cbdis, cddis)) - { - if (Input.Greater(dbdis, cddis)) - { - return Input.CreateCompound(A, B); - } - else - { - return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); - } - } - else - { - if (Input.Greater(cbdis, dbdis)) - { - return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); - } - else - { - return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subc, B), subd); - } - } - } - } -} \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index 5f348a2..bb26c81 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,186 +1,32 @@ using System; using System.Collections.Generic; using System.Linq; -using OpenTKGUI; - namespace Alunite { /// <summary> - /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which - /// are common to all particles. - /// </summary> - public interface ISubstance - { - /// <summary> - /// Updates a particle of this substance by the specified amount of time in seconds in the given environment. This function should account for every - /// force at every scale, including gravity and electromagnetism. - /// </summary> - ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); - } - - /// <summary> - /// A substance with some visual properties. + /// Descibes the physical properties of a particle. /// </summary> - public interface IVisualSubstance : ISubstance + public interface ISubstance<TPhysics, TMatter> + where TPhysics : IParticlePhysics<TPhysics, TMatter> + where TMatter : IMatter { /// <summary> - /// Gets the color this substance should be displayed with. + /// Updates a particle of this substance. /// </summary> - Color Color { get; } + void Update(TPhysics Physics, TMatter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); } /// <summary> - /// Describes a particle in a certain frame of reference. + /// A physical system that allows the introduction and simulation of particles. /// </summary> - public struct Particle + public interface IParticlePhysics<TSelf, TMatter> : ISpatialPhysics<TMatter> + where TSelf : IParticlePhysics<TSelf, TMatter> + where TMatter : IMatter { - public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) - { - this.Position = Position; - this.Velocity = Velocity; - this.Orientation = Orientation; - this.Mass = Mass; - this.Substance = Substance; - } - - public Particle(Vector Position, double Mass, ISubstance Substance) - { - this.Position = Position; - this.Velocity = new Vector(0.0, 0.0, 0.0); - this.Orientation = Quaternion.Identity; - this.Mass = Mass; - this.Substance = Substance; - } - - public Particle(Transform Transform, double Mass, ISubstance Substance) - { - this.Position = Transform.Offset; - this.Velocity = Transform.VelocityOffset; - this.Orientation = Transform.Rotation; - this.Mass = Mass; - this.Substance = Substance; - } - - /// <summary> - /// Gets the transform of the particle from the origin. - /// </summary> - public Transform Transform - { - get - { - return new Transform( - this.Position, - this.Velocity, - this.Orientation); - } - } - - /// <summary> - /// Gets a matter representation of this particle. - /// </summary> - public Matter Matter - { - get - { - return new ParticleMatter(this.Substance, this.Mass).Apply(this.Transform); - } - } - - /// <summary> - /// Gets the particle with a transform applied to it. - /// </summary> - public Particle Apply(Transform Transform) - { - return new Particle(Transform.ApplyTo(this.Transform), this.Mass, this.Substance); - } - - /// <summary> - /// The relative location of the particle in meters. - /// </summary> - public Vector Position; - /// <summary> - /// The relative velocity of the particle in meters per second. + /// Creates a matter form of a single particle with the specified properties. /// </summary> - public Vector Velocity; - - /// <summary> - /// The relative orientation of the particle. This can be ignored for particles - /// whose orientation doesn't matter. - /// </summary> - public Quaternion Orientation; - - /// <summary> - /// The mass of the particle in kilograms. - /// </summary> - public double Mass; - - /// <summary> - /// Gets the substance of the particle, which describes the particles properties. - /// </summary> - public ISubstance Substance; - } - - /// <summary> - /// Matter containing a single unoriented particle. - /// </summary> - public class ParticleMatter : Matter - { - public ParticleMatter(ISubstance Substance, double Mass) - { - this._Substance = Substance; - this._Mass = Mass; - } - - /// <summary> - /// Gets the substance of the particle. - /// </summary> - public ISubstance Substance - { - get - { - return this._Substance; - } - } - - /// <summary> - /// Gets the mass of the particle. - /// </summary> - public double Mass - { - get - { - return this._Mass; - } - } - - public override IEnumerable<Particle> Particles - { - get - { - return new Particle[1] - { - new Particle(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, this._Mass, this._Substance) - }; - } - } - - - public override Matter Update(Matter Environment, double Time) - { - Vector pos = new Vector(0.0, 0.0, 0.0); - Vector vel = new Vector(0.0, 0.0, 0.0); - Quaternion ort = Quaternion.Identity; - double mass = this._Mass; - ISubstance nsub = this._Substance.Update(Environment, Time, ref pos, ref vel, ref ort, ref mass); - return - new TransformMatter( - new ParticleMatter(nsub, mass), - new Transform(pos, vel, ort)); - } - - private ISubstance _Substance; - private double _Mass; + TMatter Create(ISubstance<TSelf, TMatter> Substance, Vector Position, Vector Velocity, Quaternion Orientation, double Mass); } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index d4d1121..c96806d 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,139 +1,28 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Random r = new Random(); - // OSP test - List<_OSPNode> nodes = new List<_OSPNode>(); - for (int t = 0; t < 100000; t++) - { - nodes.Add(new _OSPNode(r.NextDouble() * 0.01, new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()))); - } - _OSPNode ospnode = OSP.Create<_OSPNode.Input, _OSPNode, double>(new _OSPNode.Input(), nodes); - - // Create a test world - List<Matter> elems = new List<Matter>(); - - BlobMatter worldblob = new BlobMatter(0.1); - - // Water - for (int t = 0; t < 10000; t++) - { - worldblob.Add(new Particle( - new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble() * 0.5), - 0.01, Fluid.GetSubstance())); - } - - // Adminium walls - double step = 0.02; - for (double x = step / 2.0; x <= 1.0; x += step) - { - for (double y = step / 2.0; y <= 1.0; y += step) - { - worldblob.Add(new Particle(new Vector(x, y, 0.0), 0.01, new Adminium())); - worldblob.Add(new Particle(new Vector(x, 0.0, y), 0.01, new Adminium())); - worldblob.Add(new Particle(new Vector(0.0, x, y), 0.01, new Adminium())); - worldblob.Add(new Particle(new Vector(x, 1.0, y), 0.01, new Adminium())); - worldblob.Add(new Particle(new Vector(1.0, x, y), 0.01, new Adminium())); - } - } - - // "Earth" - elems.Add(worldblob); - elems.Add(new Particle( - new Vector(0.0, 0.0, -6.3675e6), - 5.9721e24, new Adminium()).Matter); - - Matter world = CompositeMatter.Create(elems); - + /* HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); - hw.Run(60.0); - } - - private class _OSPNode - { - public _OSPNode(double Radius, Vector Position) - { - this.Radius = Radius; - this.Position = Position; - } - - public _OSPNode(_OSPNode A, _OSPNode B) - { - Vector dir = B.Position - A.Position; - double dis = dir.Length; - dir *= 1.0 / dis; - this.Radius = (dis + A.Radius + B.Radius) * 0.5; - this.Position = A.Position + dir * (this.Radius - A.Radius); - this.SubA = A; - this.SubB = B; - } - - public class Input : OSP.IOSPInput<_OSPNode, double> - { - public bool GetSubnodes(_OSPNode Node, out _OSPNode A, out _OSPNode B) - { - if (Node.SubA != null) - { - A = Node.SubA; - B = Node.SubB; - return true; - } - else - { - A = null; - B = null; - return false; - } - } - - public bool Greater(double A, double B) - { - return A > B; - } - - public double GetDiameter(_OSPNode Node) - { - return Node.Radius * 2.0; - } - - public double GetShortDistance(_OSPNode A, _OSPNode B) - { - return (A.Position - B.Position).Length - A.Radius - B.Radius; - } - - public double GetLongDistance(_OSPNode A, _OSPNode B) - { - return (A.Position - B.Position).Length + A.Radius + B.Radius; - } - - public _OSPNode CreateCompound(_OSPNode A, _OSPNode B) - { - return new _OSPNode(A, B); - } - } - - public double Radius; - public Vector Position; - public _OSPNode SubA; - public _OSPNode SubB; + hw.Run(60.0);*/ } } } \ No newline at end of file diff --git a/Alunite/Reduce.cs b/Alunite/Reduce.cs index be633be..cfa9892 100644 --- a/Alunite/Reduce.cs +++ b/Alunite/Reduce.cs @@ -1,14 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Contains functions related to the reduction and simplification of composite matter. /// </summary> public static class Reduce { - + } } \ No newline at end of file diff --git a/Alunite/SphereTree.cs b/Alunite/SphereTree.cs new file mode 100644 index 0000000..e68d11c --- /dev/null +++ b/Alunite/SphereTree.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Partions and organizes spherical nodes containing data into a bounding volume hierarchy. + /// </summary> + public abstract class SphereTree<TNode> + { + /// <summary> + /// Gets the position and radius of the specified node. + /// </summary> + public abstract void GetBound(TNode Node, out Vector Position, out double Radius); + + /// <summary> + /// Gets the subnodes for a node, if the node is a compound node. + /// </summary> + public abstract bool GetSubnodes(TNode Node, ref TNode A, ref TNode B); + + /// <summary> + /// Creates a compound node containing the two specified subnodes. + /// </summary> + public abstract TNode CreateCompound(TNode A, TNode B); + } + + /// <summary> + /// A sphere tree that automatically creates and maintains compound nodes which track position, radius and subnodes. + /// </summary> + public abstract class SimpleSphereTree<TLeaf> : SphereTree<SimpleSphereTreeNode<TLeaf>> + { + /// <summary> + /// Gets the bounding sphere for a leaf. + /// </summary> + public abstract void GetBound(TLeaf Leaf, out Vector Position, out double Radius); + + /// <summary> + /// Creates a leaf node for a leaf. + /// </summary> + public SimpleSphereTreeNode<TLeaf> Create(TLeaf Leaf) + { + return new SimpleSphereTreeNode<TLeaf>._Leaf() + { + Leaf = Leaf + }; + } + + public sealed override void GetBound(SimpleSphereTreeNode<TLeaf> Node, out Vector Position, out double Radius) + { + Node._GetBound(this, out Position, out Radius); + } + + public sealed override bool GetSubnodes(SimpleSphereTreeNode<TLeaf> Node, ref SimpleSphereTreeNode<TLeaf> A, ref SimpleSphereTreeNode<TLeaf> B) + { + var c = Node as SimpleSphereTreeNode<TLeaf>._Compound; + if (c != null) + { + A = c.A; + B = c.B; + return true; + } + return false; + } + + public sealed override SimpleSphereTreeNode<TLeaf> CreateCompound(SimpleSphereTreeNode<TLeaf> A, SimpleSphereTreeNode<TLeaf> B) + { + Vector posa; double rada; this.GetBound(A, out posa, out rada); + Vector posb; double radb; this.GetBound(B, out posb, out radb); + Vector dir = posb - posa; + double dis = dir.Length; + dir *= 1.0 / dis; + + return new SimpleSphereTreeNode<TLeaf>._Compound() + { + A = A, + B = B, + Radius = (dis + rada + radb) * 0.5, + Position = posa + dir * (dis * 0.5 + rada) + }; + } + } + + /// <summary> + /// A node for a SimpleSphereTree. + /// </summary> + public abstract class SimpleSphereTreeNode<TLeaf> + { + internal abstract void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius); + + internal class _Leaf : SimpleSphereTreeNode<TLeaf> + { + internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) + { + Tree.GetBound(this.Leaf, out Position, out Radius); + } + + public TLeaf Leaf; + } + + internal class _Compound : SimpleSphereTreeNode<TLeaf> + { + internal override void _GetBound(SimpleSphereTree<TLeaf> Tree, out Vector Position, out double Radius) + { + Position = this.Position; + Radius = this.Radius; + } + + public Vector Position; + public double Radius; + public SimpleSphereTreeNode<TLeaf> A; + public SimpleSphereTreeNode<TLeaf> B; + } + } +} \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index a1755b8..12b0d55 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,74 +1,74 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> - public class Visualizer : Render3DControl + /*public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(2.0f); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { Color col = Color.RGB(1.0, 1.0, 1.0); IVisualSubstance vissub = p.Substance as IVisualSubstance; if (vissub != null) { col = vissub.Color; } GL.Color4(col); GL.Vertex3(p.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { this._Time += Time * 0.2; //this._Matter = this._Matter.Update(Matter.Null, Time * 0.1); } private double _Time; private Matter _Matter; - } + }*/ } \ No newline at end of file
dzamkov/Alunite-old
a854c66c6d72e979948c97ab43d5afcd21f7bdda
Better OSP (also discovered that my OSP algorithim isn't actually optimal, just really good)
diff --git a/Alunite/OSP.cs b/Alunite/OSP.cs index dbd6465..af5b8f9 100644 --- a/Alunite/OSP.cs +++ b/Alunite/OSP.cs @@ -1,132 +1,126 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Contains functions for finding the optimal sphere partioning of a set /// of leaf nodes where each node is given a bounding sphere. A node can contain /// the optimal sphere partioning of a set of leaves if the two leaves with the smallest /// common bounding sphere are grouped in a single node and all subnodes contain the /// optimal sphere partioning of their set of leaves. /// </summary> /// <remarks>Comparing nodes with optimal sphere partioning is a good way of finding patterns in a set of points.</remarks> public static class OSP { /// <summary> /// Input to an OSP finder. /// </summary> public interface IOSPInput<TNode, TScalar> { /// <summary> /// Gets the subnodes in a node, if the node is a compound node, as opposed to a leaf node. /// </summary> bool GetSubnodes(TNode Node, out TNode A, out TNode B); /// <summary> /// Gets if the scalar value A is larger than B. /// </summary> bool Greater(TScalar A, TScalar B); /// <summary> /// Gets the diameter of a node. /// </summary> TScalar GetDiameter(TNode Node); /// <summary> /// Gets the distance between two nodes at the closest points on their bounding spheres. /// </summary> TScalar GetShortDistance(TNode A, TNode B); /// <summary> /// Gets the distance between two nodes at the furthest points on their bounding spheres. This is equivalent to /// the diameter of the bounding sphere containing both nodes. /// </summary> TScalar GetLongDistance(TNode A, TNode B); /// <summary> /// Creates a compound node with the specified subnodes. /// </summary> TNode CreateCompound(TNode A, TNode B); } /// <summary> - /// Creates an OSP node of the specified leaf nodes. + /// Creates a (near) OSP node of the specified leaf nodes. /// </summary> public static TNode Create<TInput, TNode, TScalar>(TInput Input, IEnumerable<TNode> Nodes) where TInput : IOSPInput<TNode, TScalar> { // Insert leafs into OSP node one at a time. TNode cur = default(TNode); IEnumerator<TNode> en = Nodes.GetEnumerator(); if (en.MoveNext()) { cur = en.Current; while (en.MoveNext()) { cur = Combine<TInput, TNode, TScalar>(Input, cur, en.Current); } } return cur; } /// <summary> /// Combines two OSP nodes. This function will be faster if A is the more complex node. /// </summary> + /// <remarks>The resulting node may not be OSP, but it will be well-balanced.</remarks> public static TNode Combine<TInput, TNode, TScalar>(TInput Input, TNode A, TNode B) where TInput : IOSPInput<TNode, TScalar> { // Get sub nodes TNode subc; TNode subd; if (!Input.GetSubnodes(A, out subc, out subd)) { if (!Input.GetSubnodes(B, out subc, out subd)) { // Trivial case, both nodes are leaves return Input.CreateCompound(A, B); } // Swap A and B so that subc and subd belong to A TNode temp = A; A = B; B = temp; } - // If the distance between them is greater than either diameter, the node containing both must be OSP - TScalar dis = Input.GetShortDistance(A, B); - if (Input.Greater(dis, Input.GetDiameter(A)) && Input.Greater(dis, Input.GetDiameter(B))) - { - return Input.CreateCompound(A, B); - } - // Create a node between C, D and B with the smallest possible diameter - TScalar cddis = Input.GetLongDistance(subc, subd); + TScalar cddis = Input.GetDiameter(A); TScalar cbdis = Input.GetLongDistance(subc, B); TScalar dbdis = Input.GetLongDistance(subd, B); if (Input.Greater(cbdis, cddis)) { if (Input.Greater(dbdis, cddis)) { return Input.CreateCompound(A, B); } else { return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); } } else { if (Input.Greater(cbdis, dbdis)) { return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); } else { return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subc, B), subd); } } } } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 2a4eda5..d4d1121 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,139 +1,139 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Random r = new Random(); // OSP test List<_OSPNode> nodes = new List<_OSPNode>(); - for (int t = 0; t < 10000; t++) + for (int t = 0; t < 100000; t++) { nodes.Add(new _OSPNode(r.NextDouble() * 0.01, new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()))); } _OSPNode ospnode = OSP.Create<_OSPNode.Input, _OSPNode, double>(new _OSPNode.Input(), nodes); // Create a test world List<Matter> elems = new List<Matter>(); BlobMatter worldblob = new BlobMatter(0.1); // Water for (int t = 0; t < 10000; t++) { worldblob.Add(new Particle( new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble() * 0.5), 0.01, Fluid.GetSubstance())); } // Adminium walls double step = 0.02; for (double x = step / 2.0; x <= 1.0; x += step) { for (double y = step / 2.0; y <= 1.0; y += step) { worldblob.Add(new Particle(new Vector(x, y, 0.0), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(x, 0.0, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(0.0, x, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(x, 1.0, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(1.0, x, y), 0.01, new Adminium())); } } // "Earth" elems.Add(worldblob); elems.Add(new Particle( new Vector(0.0, 0.0, -6.3675e6), 5.9721e24, new Adminium()).Matter); Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0); } private class _OSPNode { public _OSPNode(double Radius, Vector Position) { this.Radius = Radius; this.Position = Position; } public _OSPNode(_OSPNode A, _OSPNode B) { Vector dir = B.Position - A.Position; double dis = dir.Length; dir *= 1.0 / dis; this.Radius = (dis + A.Radius + B.Radius) * 0.5; this.Position = A.Position + dir * (this.Radius - A.Radius); this.SubA = A; this.SubB = B; } public class Input : OSP.IOSPInput<_OSPNode, double> { public bool GetSubnodes(_OSPNode Node, out _OSPNode A, out _OSPNode B) { if (Node.SubA != null) { A = Node.SubA; B = Node.SubB; return true; } else { A = null; B = null; return false; } } public bool Greater(double A, double B) { return A > B; } public double GetDiameter(_OSPNode Node) { return Node.Radius * 2.0; } public double GetShortDistance(_OSPNode A, _OSPNode B) { return (A.Position - B.Position).Length - A.Radius - B.Radius; } public double GetLongDistance(_OSPNode A, _OSPNode B) { return (A.Position - B.Position).Length + A.Radius + B.Radius; } public _OSPNode CreateCompound(_OSPNode A, _OSPNode B) { return new _OSPNode(A, B); } } public double Radius; public Vector Position; public _OSPNode SubA; public _OSPNode SubB; } } } \ No newline at end of file
dzamkov/Alunite-old
48c28d4a73066c969745f0e4b7659835fec86a9e
Optimal sphere partioning, to be used for pattern finding
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 455c42c..78d6612 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,65 +1,67 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Adminium.cs" /> <Compile Include="BinaryMatter.cs" /> <Compile Include="BlobMatter.cs" /> <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> + <Compile Include="Reduce.cs" /> + <Compile Include="OSP.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/OSP.cs b/Alunite/OSP.cs new file mode 100644 index 0000000..dbd6465 --- /dev/null +++ b/Alunite/OSP.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Contains functions for finding the optimal sphere partioning of a set + /// of leaf nodes where each node is given a bounding sphere. A node can contain + /// the optimal sphere partioning of a set of leaves if the two leaves with the smallest + /// common bounding sphere are grouped in a single node and all subnodes contain the + /// optimal sphere partioning of their set of leaves. + /// </summary> + /// <remarks>Comparing nodes with optimal sphere partioning is a good way of finding patterns in a set of points.</remarks> + public static class OSP + { + /// <summary> + /// Input to an OSP finder. + /// </summary> + public interface IOSPInput<TNode, TScalar> + { + /// <summary> + /// Gets the subnodes in a node, if the node is a compound node, as opposed to a leaf node. + /// </summary> + bool GetSubnodes(TNode Node, out TNode A, out TNode B); + + /// <summary> + /// Gets if the scalar value A is larger than B. + /// </summary> + bool Greater(TScalar A, TScalar B); + + /// <summary> + /// Gets the diameter of a node. + /// </summary> + TScalar GetDiameter(TNode Node); + + /// <summary> + /// Gets the distance between two nodes at the closest points on their bounding spheres. + /// </summary> + TScalar GetShortDistance(TNode A, TNode B); + + /// <summary> + /// Gets the distance between two nodes at the furthest points on their bounding spheres. This is equivalent to + /// the diameter of the bounding sphere containing both nodes. + /// </summary> + TScalar GetLongDistance(TNode A, TNode B); + + /// <summary> + /// Creates a compound node with the specified subnodes. + /// </summary> + TNode CreateCompound(TNode A, TNode B); + } + + /// <summary> + /// Creates an OSP node of the specified leaf nodes. + /// </summary> + public static TNode Create<TInput, TNode, TScalar>(TInput Input, IEnumerable<TNode> Nodes) + where TInput : IOSPInput<TNode, TScalar> + { + // Insert leafs into OSP node one at a time. + TNode cur = default(TNode); + IEnumerator<TNode> en = Nodes.GetEnumerator(); + if (en.MoveNext()) + { + cur = en.Current; + while (en.MoveNext()) + { + cur = Combine<TInput, TNode, TScalar>(Input, cur, en.Current); + } + } + return cur; + } + + /// <summary> + /// Combines two OSP nodes. This function will be faster if A is the more complex node. + /// </summary> + public static TNode Combine<TInput, TNode, TScalar>(TInput Input, TNode A, TNode B) + where TInput : IOSPInput<TNode, TScalar> + { + // Get sub nodes + TNode subc; + TNode subd; + if (!Input.GetSubnodes(A, out subc, out subd)) + { + if (!Input.GetSubnodes(B, out subc, out subd)) + { + // Trivial case, both nodes are leaves + return Input.CreateCompound(A, B); + } + + // Swap A and B so that subc and subd belong to A + TNode temp = A; + A = B; + B = temp; + } + + // If the distance between them is greater than either diameter, the node containing both must be OSP + TScalar dis = Input.GetShortDistance(A, B); + if (Input.Greater(dis, Input.GetDiameter(A)) && Input.Greater(dis, Input.GetDiameter(B))) + { + return Input.CreateCompound(A, B); + } + + // Create a node between C, D and B with the smallest possible diameter + TScalar cddis = Input.GetLongDistance(subc, subd); + TScalar cbdis = Input.GetLongDistance(subc, B); + TScalar dbdis = Input.GetLongDistance(subd, B); + if (Input.Greater(cbdis, cddis)) + { + if (Input.Greater(dbdis, cddis)) + { + return Input.CreateCompound(A, B); + } + else + { + return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); + } + } + else + { + if (Input.Greater(cbdis, dbdis)) + { + return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subd, B), subc); + } + else + { + return Input.CreateCompound(Combine<TInput, TNode, TScalar>(Input, subc, B), subd); + } + } + } + } +} \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 83a4404..2a4eda5 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,59 +1,139 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - // Create a test world Random r = new Random(); + + // OSP test + List<_OSPNode> nodes = new List<_OSPNode>(); + for (int t = 0; t < 10000; t++) + { + nodes.Add(new _OSPNode(r.NextDouble() * 0.01, new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()))); + } + _OSPNode ospnode = OSP.Create<_OSPNode.Input, _OSPNode, double>(new _OSPNode.Input(), nodes); + + // Create a test world List<Matter> elems = new List<Matter>(); + BlobMatter worldblob = new BlobMatter(0.1); // Water - for (int t = 0; t < 500; t++) + for (int t = 0; t < 10000; t++) { worldblob.Add(new Particle( new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble() * 0.5), 0.01, Fluid.GetSubstance())); } // Adminium walls - for (double x = 0.0; x <= 1.0; x += 0.04) + double step = 0.02; + for (double x = step / 2.0; x <= 1.0; x += step) { - for (double y = 0.0; y <= 1.0; y += 0.04) + for (double y = step / 2.0; y <= 1.0; y += step) { worldblob.Add(new Particle(new Vector(x, y, 0.0), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(x, 0.0, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(0.0, x, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(x, 1.0, y), 0.01, new Adminium())); worldblob.Add(new Particle(new Vector(1.0, x, y), 0.01, new Adminium())); } } // "Earth" elems.Add(worldblob); elems.Add(new Particle( new Vector(0.0, 0.0, -6.3675e6), 5.9721e24, new Adminium()).Matter); Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0); } + + private class _OSPNode + { + public _OSPNode(double Radius, Vector Position) + { + this.Radius = Radius; + this.Position = Position; + } + + public _OSPNode(_OSPNode A, _OSPNode B) + { + Vector dir = B.Position - A.Position; + double dis = dir.Length; + dir *= 1.0 / dis; + this.Radius = (dis + A.Radius + B.Radius) * 0.5; + this.Position = A.Position + dir * (this.Radius - A.Radius); + this.SubA = A; + this.SubB = B; + } + + public class Input : OSP.IOSPInput<_OSPNode, double> + { + public bool GetSubnodes(_OSPNode Node, out _OSPNode A, out _OSPNode B) + { + if (Node.SubA != null) + { + A = Node.SubA; + B = Node.SubB; + return true; + } + else + { + A = null; + B = null; + return false; + } + } + + public bool Greater(double A, double B) + { + return A > B; + } + + public double GetDiameter(_OSPNode Node) + { + return Node.Radius * 2.0; + } + + public double GetShortDistance(_OSPNode A, _OSPNode B) + { + return (A.Position - B.Position).Length - A.Radius - B.Radius; + } + + public double GetLongDistance(_OSPNode A, _OSPNode B) + { + return (A.Position - B.Position).Length + A.Radius + B.Radius; + } + + public _OSPNode CreateCompound(_OSPNode A, _OSPNode B) + { + return new _OSPNode(A, B); + } + } + + public double Radius; + public Vector Position; + public _OSPNode SubA; + public _OSPNode SubB; + } } } \ No newline at end of file diff --git a/Alunite/Reduce.cs b/Alunite/Reduce.cs new file mode 100644 index 0000000..be633be --- /dev/null +++ b/Alunite/Reduce.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Contains functions related to the reduction and simplification of composite matter. + /// </summary> + public static class Reduce + { + + } +} \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 49eccce..a1755b8 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,74 +1,74 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); - GL.PointSize(5.0f); + GL.PointSize(2.0f); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { Color col = Color.RGB(1.0, 1.0, 1.0); IVisualSubstance vissub = p.Substance as IVisualSubstance; if (vissub != null) { col = vissub.Color; } GL.Color4(col); GL.Vertex3(p.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { this._Time += Time * 0.2; - this._Matter = this._Matter.Update(Matter.Null, Time * 0.1); + //this._Matter = this._Matter.Update(Matter.Null, Time * 0.1); } private double _Time; private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
c1dd36f8ca7be52cef29158875d27c57ef247816
BinaryMatter, a more efficent composite matter
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index ef8773e..455c42c 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,64 +1,65 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Adminium.cs" /> + <Compile Include="BinaryMatter.cs" /> <Compile Include="BlobMatter.cs" /> <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/BinaryMatter.cs b/Alunite/BinaryMatter.cs new file mode 100644 index 0000000..ba2b021 --- /dev/null +++ b/Alunite/BinaryMatter.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Matter composed of two elements. + /// </summary> + public class BinaryMatter : CompositeMatter + { + public BinaryMatter(Matter A, Matter B) + { + this._A = A; + this._B = B; + } + + /// <summary> + /// Creates some binary matter. + /// </summary> + public static BinaryMatter Create(Matter A, Matter B) + { + return new BinaryMatter(A, B); + } + + public override IEnumerable<Matter> Elements + { + get + { + yield return this._A; + yield return this._B; + } + } + + public override Matter Apply(Transform Transform) + { + return BinaryMatter.Create( + this._A.Apply(Transform), + this._B.Apply(Transform)); + } + + public override Matter Update(Matter Environment, double Time) + { + Matter na = this._A.Update(BinaryMatter.Create(Environment, this._B), Time); + Matter nb = this._B.Update(BinaryMatter.Create(Environment, this._A), Time); + return BinaryMatter.Create(na, nb); + } + + private Matter _A; + private Matter _B; + } +} \ No newline at end of file diff --git a/Alunite/BlobMatter.cs b/Alunite/BlobMatter.cs index 7619d62..54ddfb2 100644 --- a/Alunite/BlobMatter.cs +++ b/Alunite/BlobMatter.cs @@ -1,216 +1,226 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Matter composed of efficently organized particles that can only interact in a limited range. Note that it /// is assumed that the "blob" is too light to create a gravitational force. /// </summary> - public class BlobMatter : Matter + public class BlobMatter : CompositeMatter { public BlobMatter(double GridSize) { this._GridSize = GridSize; this._Grid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); } private BlobMatter(double GridSize, Dictionary<_GridRef, List<Particle>> Grid) { this._GridSize = GridSize; this._Grid = Grid; } /// <summary> /// Gets size of units in the grid used to organize particles. This must be above the interaction /// distance of particles in the grid. /// </summary> public double GridSize { get { return this._GridSize; } } public override IEnumerable<Particle> Particles { get { return from pl in this._Grid.Values from p in pl select p; } } + public override IEnumerable<Matter> Elements + { + get + { + return + from p in this.Particles + select p.Matter; + } + } + public override Vector GetGravityForce(Vector Position, double Mass) { return new Vector(0.0, 0.0, 0.0); } public override Matter Update(Matter Environment, double Time) { var ngrid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); foreach (var kvp in this._Grid) { List<Particle> inunit = kvp.Value; // Get surronding units the particles in this unit can interact with. List<List<Particle>> surrondunit = new List<List<Particle>>(); _GridRef gref = kvp.Key; for (int x = gref.X - 1; x <= gref.X + 1; x++) { for (int y = gref.Y - 1; y <= gref.Y + 1; y++) { for (int z = gref.Z - 1; z <= gref.Z + 1; z++) { _GridRef sref = new _GridRef(x, y, z); if (sref.X != gref.X || sref.Y != gref.Y || sref.Z != gref.Z) { List<Particle> sunit; if (this._Grid.TryGetValue(sref, out sunit)) { surrondunit.Add(sunit); } } } } } // Update particles for (int t = 0; t < inunit.Count; t++) { Particle p = inunit[t]; _GridEnvironment e = new _GridEnvironment() { InUnit = inunit, CurIndex = t, SurrondUnit = surrondunit }; p.Substance = p.Substance.Update( - CompositeMatter.Create(new Matter[] { e, Environment }), + BinaryMatter.Create(Environment, e), Time, ref p.Position, ref p.Velocity, ref p.Orientation, ref p.Mass); _Add(ngrid, this._GridSize, p); } } return new BlobMatter(this._GridSize, ngrid); } /// <summary> /// Gets the grid reference for the specified position. /// </summary> private static _GridRef _ForPos(Vector Position, double GridSize) { return new _GridRef( (int)(Position.X / GridSize), (int)(Position.Y / GridSize), (int)(Position.Z / GridSize)); } /// <summary> /// Adds a particle to a grid. /// </summary> private static void _Add(Dictionary<_GridRef, List<Particle>> Grid, double GridSize, Particle Particle) { _GridRef gref = _ForPos(Particle.Position, GridSize); List<Particle> unit; if (!Grid.TryGetValue(gref, out unit)) { unit = Grid[gref] = new List<Particle>(); } unit.Add(Particle); } /// <summary> /// Adds a particle to this blob. /// </summary> public void Add(Particle Particle) { _Add(this._Grid, this._GridSize, Particle); } /// <summary> /// An environment given to a particle on the grid. /// </summary> private class _GridEnvironment : Matter { public override IEnumerable<Particle> Particles { get { for (int t = 0; t < this.InUnit.Count; t++) { if (t != this.CurIndex) { yield return this.InUnit[t]; } } foreach (List<Particle> unit in this.SurrondUnit) { foreach (Particle p in unit) { yield return p; } } } } public override Vector GetGravityForce(Vector Position, double Mass) { return new Vector(0.0, 0.0, 0.0); } public override Matter Update(Matter Environment, double Time) { throw new NotImplementedException(); } public int CurIndex; public List<Particle> InUnit; public List<List<Particle>> SurrondUnit; } /// <summary> /// A reference to a unit on the grid. /// </summary> private struct _GridRef { public _GridRef(int X, int Y, int Z) { this.X = X; this.Y = Y; this.Z = Z; } public int X; public int Y; public int Z; public class EqualityComparer : IEqualityComparer<_GridRef> { public static readonly EqualityComparer Singleton = new EqualityComparer(); public bool Equals(_GridRef x, _GridRef y) { return x.X == y.X && x.Y == y.Y && x.Z == y.Z; } public int GetHashCode(_GridRef obj) { return obj.X ^ (obj.Y + 0x1337BED5) ^ (obj.Z + 0x12384923) ^ (obj.Y << 3) ^ (obj.Y >> 3) ^ (obj.Z << 7) ^ (obj.Z >> 7); } } } private Dictionary<_GridRef, List<Particle>> _Grid; private double _GridSize; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index c2fbddf..49eccce 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,74 +1,74 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Vector lookpos = new Vector(0.5, 0.5, 0.5); Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { Color col = Color.RGB(1.0, 1.0, 1.0); IVisualSubstance vissub = p.Substance as IVisualSubstance; if (vissub != null) { col = vissub.Color; } GL.Color4(col); GL.Vertex3(p.Position); } GL.End(); GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { this._Time += Time * 0.2; - this._Matter = this._Matter.Update(Matter.Null, Time * 0.01); + this._Matter = this._Matter.Update(Matter.Null, Time * 0.1); } private double _Time; private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
28b9e8b1479225241c04264eb31a9f6d326c437f
BlobMatter to slightly speed up particles
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 6ad91fb..ef8773e 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,63 +1,64 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Adminium.cs" /> + <Compile Include="BlobMatter.cs" /> <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/BlobMatter.cs b/Alunite/BlobMatter.cs new file mode 100644 index 0000000..7619d62 --- /dev/null +++ b/Alunite/BlobMatter.cs @@ -0,0 +1,216 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Matter composed of efficently organized particles that can only interact in a limited range. Note that it + /// is assumed that the "blob" is too light to create a gravitational force. + /// </summary> + public class BlobMatter : Matter + { + public BlobMatter(double GridSize) + { + this._GridSize = GridSize; + this._Grid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); + } + + private BlobMatter(double GridSize, Dictionary<_GridRef, List<Particle>> Grid) + { + this._GridSize = GridSize; + this._Grid = Grid; + } + + /// <summary> + /// Gets size of units in the grid used to organize particles. This must be above the interaction + /// distance of particles in the grid. + /// </summary> + public double GridSize + { + get + { + return this._GridSize; + } + } + + public override IEnumerable<Particle> Particles + { + get + { + return + from pl in this._Grid.Values + from p in pl + select p; + } + } + + public override Vector GetGravityForce(Vector Position, double Mass) + { + return new Vector(0.0, 0.0, 0.0); + } + + public override Matter Update(Matter Environment, double Time) + { + var ngrid = new Dictionary<_GridRef, List<Particle>>(_GridRef.EqualityComparer.Singleton); + + foreach (var kvp in this._Grid) + { + List<Particle> inunit = kvp.Value; + + // Get surronding units the particles in this unit can interact with. + List<List<Particle>> surrondunit = new List<List<Particle>>(); + _GridRef gref = kvp.Key; + for (int x = gref.X - 1; x <= gref.X + 1; x++) + { + for (int y = gref.Y - 1; y <= gref.Y + 1; y++) + { + for (int z = gref.Z - 1; z <= gref.Z + 1; z++) + { + _GridRef sref = new _GridRef(x, y, z); + if (sref.X != gref.X || sref.Y != gref.Y || sref.Z != gref.Z) + { + List<Particle> sunit; + if (this._Grid.TryGetValue(sref, out sunit)) + { + surrondunit.Add(sunit); + } + } + } + } + } + + // Update particles + for (int t = 0; t < inunit.Count; t++) + { + Particle p = inunit[t]; + _GridEnvironment e = new _GridEnvironment() + { + InUnit = inunit, + CurIndex = t, + SurrondUnit = surrondunit + }; + p.Substance = p.Substance.Update( + CompositeMatter.Create(new Matter[] { e, Environment }), + Time, + ref p.Position, + ref p.Velocity, + ref p.Orientation, + ref p.Mass); + _Add(ngrid, this._GridSize, p); + } + } + + return new BlobMatter(this._GridSize, ngrid); + } + + /// <summary> + /// Gets the grid reference for the specified position. + /// </summary> + private static _GridRef _ForPos(Vector Position, double GridSize) + { + return new _GridRef( + (int)(Position.X / GridSize), + (int)(Position.Y / GridSize), + (int)(Position.Z / GridSize)); + } + + /// <summary> + /// Adds a particle to a grid. + /// </summary> + private static void _Add(Dictionary<_GridRef, List<Particle>> Grid, double GridSize, Particle Particle) + { + _GridRef gref = _ForPos(Particle.Position, GridSize); + List<Particle> unit; + if (!Grid.TryGetValue(gref, out unit)) + { + unit = Grid[gref] = new List<Particle>(); + } + unit.Add(Particle); + } + + /// <summary> + /// Adds a particle to this blob. + /// </summary> + public void Add(Particle Particle) + { + _Add(this._Grid, this._GridSize, Particle); + } + + /// <summary> + /// An environment given to a particle on the grid. + /// </summary> + private class _GridEnvironment : Matter + { + public override IEnumerable<Particle> Particles + { + get + { + for (int t = 0; t < this.InUnit.Count; t++) + { + if (t != this.CurIndex) + { + yield return this.InUnit[t]; + } + } + foreach (List<Particle> unit in this.SurrondUnit) + { + foreach (Particle p in unit) + { + yield return p; + } + } + } + } + + public override Vector GetGravityForce(Vector Position, double Mass) + { + return new Vector(0.0, 0.0, 0.0); + } + + public override Matter Update(Matter Environment, double Time) + { + throw new NotImplementedException(); + } + + public int CurIndex; + public List<Particle> InUnit; + public List<List<Particle>> SurrondUnit; + } + + /// <summary> + /// A reference to a unit on the grid. + /// </summary> + private struct _GridRef + { + public _GridRef(int X, int Y, int Z) + { + this.X = X; + this.Y = Y; + this.Z = Z; + } + + public int X; + public int Y; + public int Z; + + public class EqualityComparer : IEqualityComparer<_GridRef> + { + public static readonly EqualityComparer Singleton = new EqualityComparer(); + + public bool Equals(_GridRef x, _GridRef y) + { + return x.X == y.X && x.Y == y.Y && x.Z == y.Z; + } + + public int GetHashCode(_GridRef obj) + { + return obj.X ^ (obj.Y + 0x1337BED5) ^ (obj.Z + 0x12384923) ^ (obj.Y << 3) ^ (obj.Y >> 3) ^ (obj.Z << 7) ^ (obj.Z >> 7); + } + } + } + + private Dictionary<_GridRef, List<Particle>> _Grid; + private double _GridSize; + } +} \ No newline at end of file diff --git a/Alunite/Fluid.cs b/Alunite/Fluid.cs index 62b8b57..5143745 100644 --- a/Alunite/Fluid.cs +++ b/Alunite/Fluid.cs @@ -1,51 +1,50 @@ using System; using System.Collections.Generic; using System.Linq; using OpenTKGUI; namespace Alunite { /// <summary> /// Functions related to fluids. /// </summary> public static class Fluid { /// <summary> /// Gets a substance for a fluid. /// </summary> public static ISubstance GetSubstance() { return new _Substance(); } private class _Substance : IVisualSubstance { public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) { - // Loop through particles in the environment to find forces - Vector force = new Vector(0.0, 0.0, 0.0); - foreach (Particle p in Environment.Particles) - { - Vector to = p.Position - Position; - double dis = to.Length; + Vector force = Environment.GetGravityForce(Position, Mass); - // Gravity - force += to * (Particle.G * (p.Mass + Mass) / (dis * dis * dis)); + double h = 0.1; + foreach (Particle p in Environment.GetParticles(Position, h)) + { + Vector away = Position - p.Position; + double dis = away.Length; + force += away * (0.1 / (dis * dis * dis)); } Velocity += force * Time; Position += Velocity * Time; return this; } public Color Color { get { return Color.RGB(0.0, 0.5, 1.0); } } } } } \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 5ff4bb3..8db1fb3 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,235 +1,287 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> - /// Represents an untransformed object that can participate in physical interactions. + /// Represents an untransformed object that can participate in physical interactions. Note that all operations + /// on matter use units of meters, seconds, kilograms and kelvin. /// </summary> public abstract class Matter { private class _NullMatter : Matter { public override Matter Update(Matter Environment, double Time) { return this; } } /// <summary> /// Gets a matter that has no effects or interactions. /// </summary> public static readonly Matter Null = new _NullMatter(); /// <summary> /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given /// in the frame of reference of the matter in question) by a given amount of time in seconds. /// </summary> public abstract Matter Update(Matter Environment, double Time); + /// <summary> + /// Gets the gravitational force that would act on an object of the given mass and at the specified offset from this matter. + /// </summary> + public virtual Vector GetGravityForce(Vector Position, double Mass) + { + Vector force = new Vector(0.0, 0.0, 0.0); + foreach (Particle p in this.Particles) + { + Vector to = p.Position - Position; + double dis = to.Length; + force += to * (Matter.G * (p.Mass + Mass) / (dis * dis * dis)); + } + return force; + } + + /// <summary> + /// Gets particles in this matter within a certain distance of the given position. + /// </summary> + public virtual IEnumerable<Particle> GetParticles(Vector Position, double Distance) + { + double dd = Distance * Distance; + return + from p in this.Particles + where (p.Position - Position).SquareLength <= dd + select p; + } + + /// <summary> + /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects + /// in kilograms and R the distance between them in meters. + /// </summary> + public static double G = 6.67428e-11; + /// <summary> /// Gets the particles in this matter. /// </summary> public virtual IEnumerable<Particle> Particles { get { return new Particle[0]; } } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual Matter Apply(Transform Transform) { return new TransformMatter(this, Transform); } } /// <summary> /// Matter made by a physical composition of other matter. /// </summary> public abstract class CompositeMatter : Matter { /// <summary> /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). /// </summary> public abstract IEnumerable<Matter> Elements { get; } + public override Vector GetGravityForce(Vector Position, double Mass) + { + Vector force = new Vector(0.0, 0.0, 0.0); + foreach (Matter e in this.Elements) + { + force += e.GetGravityForce(Position, Mass); + } + return force; + } + /// <summary> /// Creates composite matter from the specified elements. /// </summary> public static CompositeMatter Create(IEnumerable<Matter> Elements) { return new _Concrete(Elements); } private class _Concrete : CompositeMatter { public _Concrete(IEnumerable<Matter> Elements) { this._Elements = Elements; } public override IEnumerable<Matter> Elements { get { return this._Elements; } } private IEnumerable<Matter> _Elements; } public override Matter Update(Matter Environment, double Time) { LinkedList<Matter> elems = new LinkedList<Matter>(this.Elements); List<Matter> res = new List<Matter>(elems.Count); LinkedListNode<Matter> cur = elems.First; elems.AddFirst(Environment); while (cur != null) { Matter curmat = cur.Value; LinkedListNode<Matter> next = cur.Next; elems.Remove(cur); res.Add(curmat.Update(Create(elems), Time)); elems.AddFirst(curmat); cur = next; } + if (res.Count == 0) + { + return Matter.Null; + } + if (res.Count == 1) + { + return res[0]; + } return Create(res); } public override IEnumerable<Particle> Particles { get { return from e in this.Elements from p in e.Particles select p; } } } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } /// <summary> /// A piece of transformed matter. /// </summary> public class TransformMatter : Matter { public TransformMatter(Matter Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } /// <summary> /// Gets the transform of the source matter. /// </summary> public Transform Transform { get { return this._Transform; } } /// <summary> /// Gets the source matter . /// </summary> public Matter Source { get { return this._Source; } } public override Matter Update(Matter Environment, double Time) { Transform ntrans = this._Transform; ntrans.Offset += ntrans.VelocityOffset * Time; return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(ntrans); } public override Matter Apply(Transform Transform) { return new TransformMatter(this._Source, Transform.ApplyTo(this._Transform)); } public override IEnumerable<Particle> Particles { get { return from p in this._Source.Particles select p.Apply(this._Transform); } } private Transform _Transform; private Matter _Source; } } \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index f00a441..5f348a2 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,183 +1,186 @@ using System; using System.Collections.Generic; +using System.Linq; using OpenTKGUI; namespace Alunite { /// <summary> /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which /// are common to all particles. /// </summary> public interface ISubstance { /// <summary> - /// Updates a particle of this substance by the specified amount of time in seconds in the given environment. Assume - /// that the units used in the Environment are consistent with those used for particles (meters, seconds, kilograms). This function should account for every + /// Updates a particle of this substance by the specified amount of time in seconds in the given environment. This function should account for every /// force at every scale, including gravity and electromagnetism. /// </summary> ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); } /// <summary> /// A substance with some visual properties. /// </summary> public interface IVisualSubstance : ISubstance { /// <summary> /// Gets the color this substance should be displayed with. /// </summary> Color Color { get; } } /// <summary> /// Describes a particle in a certain frame of reference. /// </summary> public struct Particle { public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) { this.Position = Position; this.Velocity = Velocity; this.Orientation = Orientation; this.Mass = Mass; this.Substance = Substance; } + public Particle(Vector Position, double Mass, ISubstance Substance) + { + this.Position = Position; + this.Velocity = new Vector(0.0, 0.0, 0.0); + this.Orientation = Quaternion.Identity; + this.Mass = Mass; + this.Substance = Substance; + } + public Particle(Transform Transform, double Mass, ISubstance Substance) { this.Position = Transform.Offset; this.Velocity = Transform.VelocityOffset; this.Orientation = Transform.Rotation; this.Mass = Mass; this.Substance = Substance; } /// <summary> /// Gets the transform of the particle from the origin. /// </summary> public Transform Transform { get { return new Transform( this.Position, this.Velocity, this.Orientation); } } /// <summary> /// Gets a matter representation of this particle. /// </summary> public Matter Matter { get { return new ParticleMatter(this.Substance, this.Mass).Apply(this.Transform); } } /// <summary> /// Gets the particle with a transform applied to it. /// </summary> public Particle Apply(Transform Transform) { return new Particle(Transform.ApplyTo(this.Transform), this.Mass, this.Substance); } - /// <summary> - /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects - /// in kilograms and R the distance between them in meters. - /// </summary> - public static double G = 6.67428e-11; - /// <summary> /// The relative location of the particle in meters. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle in meters per second. /// </summary> public Vector Velocity; /// <summary> /// The relative orientation of the particle. This can be ignored for particles /// whose orientation doesn't matter. /// </summary> public Quaternion Orientation; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Gets the substance of the particle, which describes the particles properties. /// </summary> public ISubstance Substance; } /// <summary> /// Matter containing a single unoriented particle. /// </summary> public class ParticleMatter : Matter { public ParticleMatter(ISubstance Substance, double Mass) { this._Substance = Substance; this._Mass = Mass; } /// <summary> /// Gets the substance of the particle. /// </summary> public ISubstance Substance { get { return this._Substance; } } /// <summary> /// Gets the mass of the particle. /// </summary> public double Mass { get { return this._Mass; } } public override IEnumerable<Particle> Particles { get { return new Particle[1] { new Particle(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, this._Mass, this._Substance) }; } } public override Matter Update(Matter Environment, double Time) { Vector pos = new Vector(0.0, 0.0, 0.0); Vector vel = new Vector(0.0, 0.0, 0.0); Quaternion ort = Quaternion.Identity; double mass = this._Mass; ISubstance nsub = this._Substance.Update(Environment, Time, ref pos, ref vel, ref ort, ref mass); return new TransformMatter( new ParticleMatter(nsub, mass), new Transform(pos, vel, ort)); } private ISubstance _Substance; private double _Mass; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 90a2698..83a4404 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,50 +1,59 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - double gforce = 5.9e24 / Math.Pow(6.367e6, 2.0) * Particle.G; - // Create a test world Random r = new Random(); + List<Matter> elems = new List<Matter>(); + BlobMatter worldblob = new BlobMatter(0.1); // Water - List<Matter> elems = new List<Matter>(); - for (int t = 0; t < 100; t++) + for (int t = 0; t < 500; t++) + { + worldblob.Add(new Particle( + new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble() * 0.5), + 0.01, Fluid.GetSubstance())); + } + + // Adminium walls + for (double x = 0.0; x <= 1.0; x += 0.04) { - elems.Add(new Particle( - new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), - new Vector(0.0, 0.0, 0.0), - Quaternion.Identity, - 0.01, Fluid.GetSubstance()).Matter); + for (double y = 0.0; y <= 1.0; y += 0.04) + { + worldblob.Add(new Particle(new Vector(x, y, 0.0), 0.01, new Adminium())); + worldblob.Add(new Particle(new Vector(x, 0.0, y), 0.01, new Adminium())); + worldblob.Add(new Particle(new Vector(0.0, x, y), 0.01, new Adminium())); + worldblob.Add(new Particle(new Vector(x, 1.0, y), 0.01, new Adminium())); + worldblob.Add(new Particle(new Vector(1.0, x, y), 0.01, new Adminium())); + } } // "Earth" + elems.Add(worldblob); elems.Add(new Particle( new Vector(0.0, 0.0, -6.3675e6), - new Vector(0.0, 0.0, 0.0), - Quaternion.Identity, 5.9721e24, new Adminium()).Matter); Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 4c49301..c2fbddf 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,69 +1,74 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); - Matrix4d view = Matrix4d.LookAt(new Vector(3.0, 3.0, 3.0), new Vector(0.0, 0.0, 0.0), up); + Vector lookpos = new Vector(0.5, 0.5, 0.5); + Matrix4d view = Matrix4d.LookAt(new Vector(3.0 * Math.Sin(this._Time), 3.0 * Math.Cos(this._Time), 3.0) + lookpos, lookpos, up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { + GL.Enable(EnableCap.DepthTest); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { Color col = Color.RGB(1.0, 1.0, 1.0); IVisualSubstance vissub = p.Substance as IVisualSubstance; if (vissub != null) { col = vissub.Color; } GL.Color4(col); GL.Vertex3(p.Position); } GL.End(); + GL.Disable(EnableCap.DepthTest); } public override void Update(GUIControlContext Context, double Time) { - this._Matter = this._Matter.Update(Matter.Null, Time); + this._Time += Time * 0.2; + this._Matter = this._Matter.Update(Matter.Null, Time * 0.01); } + private double _Time; private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
69ba4d5f28e476794f9295abd54109ec0b59f550
Slow, accurate, gravity
diff --git a/Alunite/Adminium.cs b/Alunite/Adminium.cs new file mode 100644 index 0000000..8578e0c --- /dev/null +++ b/Alunite/Adminium.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +using OpenTKGUI; + +namespace Alunite +{ + /// <summary> + /// A simple substances that will not change velocity in response to a force, in effect making it static. + /// </summary> + public class Adminium : IVisualSubstance + { + public Color Color + { + get + { + return Color.RGB(0.5, 0.5, 0.5); + } + } + + public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) + { + Position += Velocity * Time; + return this; + } + } +} \ No newline at end of file diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 3f78a18..6ad91fb 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,61 +1,63 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> + <Compile Include="Adminium.cs" /> <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> + <Reference Include="System.Drawing" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Fluid.cs b/Alunite/Fluid.cs index 8f532e1..62b8b57 100644 --- a/Alunite/Fluid.cs +++ b/Alunite/Fluid.cs @@ -1,30 +1,51 @@ using System; using System.Collections.Generic; using System.Linq; +using OpenTKGUI; + namespace Alunite { /// <summary> /// Functions related to fluids. /// </summary> public static class Fluid { /// <summary> /// Gets a substance for a fluid. /// </summary> public static ISubstance GetSubstance() { return new _Substance(); } - private class _Substance : ISubstance + private class _Substance : IVisualSubstance { public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) { - Velocity.Z -= 0.1 * Time; + // Loop through particles in the environment to find forces + Vector force = new Vector(0.0, 0.0, 0.0); + foreach (Particle p in Environment.Particles) + { + Vector to = p.Position - Position; + double dis = to.Length; + + // Gravity + force += to * (Particle.G * (p.Mass + Mass) / (dis * dis * dis)); + } + + Velocity += force * Time; Position += Velocity * Time; return this; } + + public Color Color + { + get + { + return Color.RGB(0.0, 0.5, 1.0); + } + } } } } \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index 590473e..f00a441 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,170 +1,183 @@ using System; using System.Collections.Generic; +using OpenTKGUI; + namespace Alunite { /// <summary> /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which /// are common to all particles. /// </summary> public interface ISubstance { /// <summary> /// Updates a particle of this substance by the specified amount of time in seconds in the given environment. Assume /// that the units used in the Environment are consistent with those used for particles (meters, seconds, kilograms). This function should account for every /// force at every scale, including gravity and electromagnetism. /// </summary> ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); } + /// <summary> + /// A substance with some visual properties. + /// </summary> + public interface IVisualSubstance : ISubstance + { + /// <summary> + /// Gets the color this substance should be displayed with. + /// </summary> + Color Color { get; } + } + /// <summary> /// Describes a particle in a certain frame of reference. /// </summary> public struct Particle { public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) { this.Position = Position; this.Velocity = Velocity; this.Orientation = Orientation; this.Mass = Mass; this.Substance = Substance; } public Particle(Transform Transform, double Mass, ISubstance Substance) { this.Position = Transform.Offset; this.Velocity = Transform.VelocityOffset; this.Orientation = Transform.Rotation; this.Mass = Mass; this.Substance = Substance; } /// <summary> /// Gets the transform of the particle from the origin. /// </summary> public Transform Transform { get { return new Transform( this.Position, this.Velocity, this.Orientation); } } /// <summary> /// Gets a matter representation of this particle. /// </summary> public Matter Matter { get { return new ParticleMatter(this.Substance, this.Mass).Apply(this.Transform); } } /// <summary> /// Gets the particle with a transform applied to it. /// </summary> public Particle Apply(Transform Transform) { return new Particle(Transform.ApplyTo(this.Transform), this.Mass, this.Substance); } /// <summary> /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects /// in kilograms and R the distance between them in meters. /// </summary> public static double G = 6.67428e-11; /// <summary> /// The relative location of the particle in meters. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle in meters per second. /// </summary> public Vector Velocity; /// <summary> /// The relative orientation of the particle. This can be ignored for particles /// whose orientation doesn't matter. /// </summary> public Quaternion Orientation; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Gets the substance of the particle, which describes the particles properties. /// </summary> public ISubstance Substance; } /// <summary> /// Matter containing a single unoriented particle. /// </summary> public class ParticleMatter : Matter { public ParticleMatter(ISubstance Substance, double Mass) { this._Substance = Substance; this._Mass = Mass; } /// <summary> /// Gets the substance of the particle. /// </summary> public ISubstance Substance { get { return this._Substance; } } /// <summary> /// Gets the mass of the particle. /// </summary> public double Mass { get { return this._Mass; } } public override IEnumerable<Particle> Particles { get { return new Particle[1] { new Particle(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, this._Mass, this._Substance) }; } } public override Matter Update(Matter Environment, double Time) { Vector pos = new Vector(0.0, 0.0, 0.0); Vector vel = new Vector(0.0, 0.0, 0.0); Quaternion ort = Quaternion.Identity; double mass = this._Mass; ISubstance nsub = this._Substance.Update(Environment, Time, ref pos, ref vel, ref ort, ref mass); return new TransformMatter( new ParticleMatter(nsub, mass), new Transform(pos, vel, ort)); } private ISubstance _Substance; private double _Mass; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index d8d6ea2..90a2698 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,40 +1,50 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { double gforce = 5.9e24 / Math.Pow(6.367e6, 2.0) * Particle.G; // Create a test world Random r = new Random(); + + // Water List<Matter> elems = new List<Matter>(); for (int t = 0; t < 100; t++) { elems.Add(new Particle( new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, 0.01, Fluid.GetSubstance()).Matter); } + + // "Earth" + elems.Add(new Particle( + new Vector(0.0, 0.0, -6.3675e6), + new Vector(0.0, 0.0, 0.0), + Quaternion.Identity, + 5.9721e24, new Adminium()).Matter); + Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 8c66ace..4c49301 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,63 +1,69 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Matrix4d view = Matrix4d.LookAt(new Vector(3.0, 3.0, 3.0), new Vector(0.0, 0.0, 0.0), up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); - GL.Color4(0.0, 0.5, 1.0, 1.0); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { + Color col = Color.RGB(1.0, 1.0, 1.0); + IVisualSubstance vissub = p.Substance as IVisualSubstance; + if (vissub != null) + { + col = vissub.Color; + } + GL.Color4(col); GL.Vertex3(p.Position); } GL.End(); } public override void Update(GUIControlContext Context, double Time) { this._Matter = this._Matter.Update(Matter.Null, Time); } private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
00e206819192341cb9ba80a4d6a78a2b7e7fd98c
Particle simulation using Matter
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 25ed15f..3f78a18 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,60 +1,61 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> + <Compile Include="Fluid.cs" /> <Compile Include="Matter.cs" /> <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Fluid.cs b/Alunite/Fluid.cs new file mode 100644 index 0000000..8f532e1 --- /dev/null +++ b/Alunite/Fluid.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Alunite +{ + /// <summary> + /// Functions related to fluids. + /// </summary> + public static class Fluid + { + /// <summary> + /// Gets a substance for a fluid. + /// </summary> + public static ISubstance GetSubstance() + { + return new _Substance(); + } + + private class _Substance : ISubstance + { + public ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass) + { + Velocity.Z -= 0.1 * Time; + Position += Velocity * Time; + return this; + } + } + } +} \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 53753b6..5ff4bb3 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,219 +1,235 @@ using System; using System.Collections.Generic; using System.Linq; namespace Alunite { /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public abstract class Matter { + private class _NullMatter : Matter + { + public override Matter Update(Matter Environment, double Time) + { + return this; + } + } + + /// <summary> + /// Gets a matter that has no effects or interactions. + /// </summary> + public static readonly Matter Null = new _NullMatter(); + /// <summary> /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given /// in the frame of reference of the matter in question) by a given amount of time in seconds. /// </summary> public abstract Matter Update(Matter Environment, double Time); /// <summary> /// Gets the particles in this matter. /// </summary> public virtual IEnumerable<Particle> Particles { get { return new Particle[0]; } } /// <summary> /// Applies a transform to this matter. /// </summary> public virtual Matter Apply(Transform Transform) { return new TransformMatter(this, Transform); } } /// <summary> /// Matter made by a physical composition of other matter. /// </summary> public abstract class CompositeMatter : Matter { /// <summary> /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). /// </summary> public abstract IEnumerable<Matter> Elements { get; } /// <summary> /// Creates composite matter from the specified elements. /// </summary> public static CompositeMatter Create(IEnumerable<Matter> Elements) { return new _Concrete(Elements); } private class _Concrete : CompositeMatter { public _Concrete(IEnumerable<Matter> Elements) { this._Elements = Elements; } public override IEnumerable<Matter> Elements { get { return this._Elements; } } private IEnumerable<Matter> _Elements; } public override Matter Update(Matter Environment, double Time) { LinkedList<Matter> elems = new LinkedList<Matter>(this.Elements); List<Matter> res = new List<Matter>(elems.Count); LinkedListNode<Matter> cur = elems.First; elems.AddFirst(Environment); while (cur != null) { Matter curmat = cur.Value; LinkedListNode<Matter> next = cur.Next; elems.Remove(cur); res.Add(curmat.Update(Create(elems), Time)); elems.AddFirst(curmat); + cur = next; } return Create(res); } public override IEnumerable<Particle> Particles { get { return from e in this.Elements from p in e.Particles select p; } } } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } /// <summary> /// A piece of transformed matter. /// </summary> public class TransformMatter : Matter { public TransformMatter(Matter Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } /// <summary> /// Gets the transform of the source matter. /// </summary> public Transform Transform { get { return this._Transform; } } /// <summary> /// Gets the source matter . /// </summary> public Matter Source { get { return this._Source; } } public override Matter Update(Matter Environment, double Time) { - return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(this._Transform); + Transform ntrans = this._Transform; + ntrans.Offset += ntrans.VelocityOffset * Time; + return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(ntrans); } public override Matter Apply(Transform Transform) { return new TransformMatter(this._Source, Transform.ApplyTo(this._Transform)); } public override IEnumerable<Particle> Particles { get { return from p in this._Source.Particles select p.Apply(this._Transform); } } private Transform _Transform; private Matter _Source; } } \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index c663c5f..590473e 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,170 +1,170 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which /// are common to all particles. /// </summary> public interface ISubstance { /// <summary> - /// Updates a particle of this substance by the specified amount of time in seconds in the given environment (which is orientated to the particle). Assume + /// Updates a particle of this substance by the specified amount of time in seconds in the given environment. Assume /// that the units used in the Environment are consistent with those used for particles (meters, seconds, kilograms). This function should account for every /// force at every scale, including gravity and electromagnetism. /// </summary> - ISubstance Update(Matter Environment, double Time, out Vector DPosition, out Vector DVelocity, out Quaternion DOrientation, ref double Mass); + ISubstance Update(Matter Environment, double Time, ref Vector Position, ref Vector Velocity, ref Quaternion Orientation, ref double Mass); } /// <summary> /// Describes a particle in a certain frame of reference. /// </summary> public struct Particle { public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) { this.Position = Position; this.Velocity = Velocity; this.Orientation = Orientation; this.Mass = Mass; this.Substance = Substance; } public Particle(Transform Transform, double Mass, ISubstance Substance) { this.Position = Transform.Offset; this.Velocity = Transform.VelocityOffset; this.Orientation = Transform.Rotation; this.Mass = Mass; this.Substance = Substance; } /// <summary> /// Gets the transform of the particle from the origin. /// </summary> public Transform Transform { get { return new Transform( this.Position, this.Velocity, this.Orientation); } } /// <summary> /// Gets a matter representation of this particle. /// </summary> public Matter Matter { get { return new ParticleMatter(this.Substance, this.Mass).Apply(this.Transform); } } /// <summary> /// Gets the particle with a transform applied to it. /// </summary> public Particle Apply(Transform Transform) { return new Particle(Transform.ApplyTo(this.Transform), this.Mass, this.Substance); } /// <summary> /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects /// in kilograms and R the distance between them in meters. /// </summary> public static double G = 6.67428e-11; /// <summary> /// The relative location of the particle in meters. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle in meters per second. /// </summary> public Vector Velocity; /// <summary> /// The relative orientation of the particle. This can be ignored for particles /// whose orientation doesn't matter. /// </summary> public Quaternion Orientation; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Gets the substance of the particle, which describes the particles properties. /// </summary> public ISubstance Substance; } /// <summary> /// Matter containing a single unoriented particle. /// </summary> public class ParticleMatter : Matter { public ParticleMatter(ISubstance Substance, double Mass) { this._Substance = Substance; this._Mass = Mass; } /// <summary> /// Gets the substance of the particle. /// </summary> public ISubstance Substance { get { return this._Substance; } } /// <summary> /// Gets the mass of the particle. /// </summary> public double Mass { get { return this._Mass; } } public override IEnumerable<Particle> Particles { get { return new Particle[1] { new Particle(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, this._Mass, this._Substance) }; } } public override Matter Update(Matter Environment, double Time) { - Vector dpos; - Vector dvel; - Quaternion dort; + Vector pos = new Vector(0.0, 0.0, 0.0); + Vector vel = new Vector(0.0, 0.0, 0.0); + Quaternion ort = Quaternion.Identity; double mass = this._Mass; - ISubstance nsub = this._Substance.Update(Environment, Time, out dpos, out dvel, out dort, ref mass); + ISubstance nsub = this._Substance.Update(Environment, Time, ref pos, ref vel, ref ort, ref mass); return new TransformMatter( new ParticleMatter(nsub, mass), - new Transform(dpos, dvel, dort)); + new Transform(pos, vel, ort)); } private ISubstance _Substance; private double _Mass; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 52bef89..d8d6ea2 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,40 +1,40 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { double gforce = 5.9e24 / Math.Pow(6.367e6, 2.0) * Particle.G; // Create a test world Random r = new Random(); List<Matter> elems = new List<Matter>(); for (int t = 0; t < 100; t++) { elems.Add(new Particle( new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, - 0.01, null).Matter); + 0.01, Fluid.GetSubstance()).Matter); } Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; hw.Control = new Visualizer(world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 62c2b9a..8c66ace 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,58 +1,63 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Matrix4d view = Matrix4d.LookAt(new Vector(3.0, 3.0, 3.0), new Vector(0.0, 0.0, 0.0), up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); GL.Color4(0.0, 0.5, 1.0, 1.0); GL.Begin(BeginMode.Points); foreach (Particle p in this._Matter.Particles) { GL.Vertex3(p.Position); } GL.End(); } + public override void Update(GUIControlContext Context, double Time) + { + this._Matter = this._Matter.Update(Matter.Null, Time); + } + private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
58cf837f80deb93e8be2698c3beeb5c2a724a32b
Visualizer now does what it was originally intended to, expanded on particles
diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index d5fda91..53753b6 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,140 +1,219 @@ using System; using System.Collections.Generic; +using System.Linq; namespace Alunite { /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public abstract class Matter { /// <summary> /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given /// in the frame of reference of the matter in question) by a given amount of time in seconds. /// </summary> public abstract Matter Update(Matter Environment, double Time); + /// <summary> + /// Gets the particles in this matter. + /// </summary> + public virtual IEnumerable<Particle> Particles + { + get + { + return new Particle[0]; + } + } + /// <summary> /// Applies a transform to this matter. /// </summary> public virtual Matter Apply(Transform Transform) { - return new Element(this, Transform); + return new TransformMatter(this, Transform); } } /// <summary> /// Matter made by a physical composition of other matter. /// </summary> public abstract class CompositeMatter : Matter { /// <summary> /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). /// </summary> public abstract IEnumerable<Matter> Elements { get; } + + /// <summary> + /// Creates composite matter from the specified elements. + /// </summary> + public static CompositeMatter Create(IEnumerable<Matter> Elements) + { + return new _Concrete(Elements); + } + + private class _Concrete : CompositeMatter + { + public _Concrete(IEnumerable<Matter> Elements) + { + this._Elements = Elements; + } + + public override IEnumerable<Matter> Elements + { + get + { + return this._Elements; + } + } + + private IEnumerable<Matter> _Elements; + } + + public override Matter Update(Matter Environment, double Time) + { + LinkedList<Matter> elems = new LinkedList<Matter>(this.Elements); + List<Matter> res = new List<Matter>(elems.Count); + + LinkedListNode<Matter> cur = elems.First; + elems.AddFirst(Environment); + + while (cur != null) + { + Matter curmat = cur.Value; + LinkedListNode<Matter> next = cur.Next; + elems.Remove(cur); + + res.Add(curmat.Update(Create(elems), Time)); + elems.AddFirst(curmat); + } + return Create(res); + } + + public override IEnumerable<Particle> Particles + { + get + { + return + from e in this.Elements + from p in e.Particles + select p; + } + } } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> - public Transform Apply(Transform Transform) + public Transform ApplyTo(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } /// <summary> /// Gets the identity transform. /// </summary> public static Transform Identity { get { return new Transform( new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity); } } public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } /// <summary> /// A piece of transformed matter. /// </summary> - public class Element : Matter + public class TransformMatter : Matter { - public Element(Matter Source, Transform Transform) + public TransformMatter(Matter Source, Transform Transform) { this._Source = Source; this._Transform = Transform; } /// <summary> - /// Gets the transform of the element. + /// Gets the transform of the source matter. /// </summary> public Transform Transform { get { return this._Transform; } } /// <summary> - /// Gets the source matter for the element. + /// Gets the source matter . /// </summary> public Matter Source { get { return this._Source; } } public override Matter Update(Matter Environment, double Time) { return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(this._Transform); } public override Matter Apply(Transform Transform) { - return new Element(this._Source, Transform.Apply(this._Transform)); + return new TransformMatter(this._Source, Transform.ApplyTo(this._Transform)); + } + + public override IEnumerable<Particle> Particles + { + get + { + return + from p in this._Source.Particles + select p.Apply(this._Transform); + } } private Transform _Transform; private Matter _Source; } } \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs index 0bf69de..c663c5f 100644 --- a/Alunite/Particle.cs +++ b/Alunite/Particle.cs @@ -1,66 +1,170 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which /// are common to all particles. /// </summary> public interface ISubstance { /// <summary> /// Updates a particle of this substance by the specified amount of time in seconds in the given environment (which is orientated to the particle). Assume /// that the units used in the Environment are consistent with those used for particles (meters, seconds, kilograms). This function should account for every /// force at every scale, including gravity and electromagnetism. /// </summary> - void Update(Matter Environment, double Time, out Vector DPosition, out Vector DVelocity, out Quaternion DOrientation, ref double Mass); + ISubstance Update(Matter Environment, double Time, out Vector DPosition, out Vector DVelocity, out Quaternion DOrientation, ref double Mass); } /// <summary> /// Describes a particle in a certain frame of reference. /// </summary> public struct Particle { public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) { this.Position = Position; this.Velocity = Velocity; this.Orientation = Orientation; this.Mass = Mass; this.Substance = Substance; } + public Particle(Transform Transform, double Mass, ISubstance Substance) + { + this.Position = Transform.Offset; + this.Velocity = Transform.VelocityOffset; + this.Orientation = Transform.Rotation; + this.Mass = Mass; + this.Substance = Substance; + } + + /// <summary> + /// Gets the transform of the particle from the origin. + /// </summary> + public Transform Transform + { + get + { + return new Transform( + this.Position, + this.Velocity, + this.Orientation); + } + } + + /// <summary> + /// Gets a matter representation of this particle. + /// </summary> + public Matter Matter + { + get + { + return new ParticleMatter(this.Substance, this.Mass).Apply(this.Transform); + } + } + + /// <summary> + /// Gets the particle with a transform applied to it. + /// </summary> + public Particle Apply(Transform Transform) + { + return new Particle(Transform.ApplyTo(this.Transform), this.Mass, this.Substance); + } + /// <summary> /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects /// in kilograms and R the distance between them in meters. /// </summary> public static double G = 6.67428e-11; /// <summary> /// The relative location of the particle in meters. /// </summary> public Vector Position; /// <summary> /// The relative velocity of the particle in meters per second. /// </summary> public Vector Velocity; /// <summary> /// The relative orientation of the particle. This can be ignored for particles /// whose orientation doesn't matter. /// </summary> public Quaternion Orientation; /// <summary> /// The mass of the particle in kilograms. /// </summary> public double Mass; /// <summary> /// Gets the substance of the particle, which describes the particles properties. /// </summary> public ISubstance Substance; } + + /// <summary> + /// Matter containing a single unoriented particle. + /// </summary> + public class ParticleMatter : Matter + { + public ParticleMatter(ISubstance Substance, double Mass) + { + this._Substance = Substance; + this._Mass = Mass; + } + + /// <summary> + /// Gets the substance of the particle. + /// </summary> + public ISubstance Substance + { + get + { + return this._Substance; + } + } + + /// <summary> + /// Gets the mass of the particle. + /// </summary> + public double Mass + { + get + { + return this._Mass; + } + } + + public override IEnumerable<Particle> Particles + { + get + { + return new Particle[1] + { + new Particle(new Vector(0.0, 0.0, 0.0), new Vector(0.0, 0.0, 0.0), Quaternion.Identity, this._Mass, this._Substance) + }; + } + } + + + public override Matter Update(Matter Environment, double Time) + { + Vector dpos; + Vector dvel; + Quaternion dort; + double mass = this._Mass; + ISubstance nsub = this._Substance.Update(Environment, Time, out dpos, out dvel, out dort, ref mass); + return + new TransformMatter( + new ParticleMatter(nsub, mass), + new Transform(dpos, dvel, dort)); + } + + private ISubstance _Substance; + private double _Mass; + } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 41dceb1..52bef89 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,29 +1,40 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTKGUI; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Transform a = new Transform(new Vector(0.7, 0.4, 1.0), new Vector(0.8, 0.1, 1.0), new Quaternion(new Vector(0.0, 1.0, 0.0), Math.PI / 3.0)); - Transform b = new Transform(new Vector(0.3, 1.0, 0.4), new Vector(0.3, 0.2, 1.0), new Quaternion(new Vector(0.0, 0.0, 1.0), Math.PI / 7.0)); - a = a.Apply(b).Apply(b.Inverse.Apply(a.Inverse)); + double gforce = 5.9e24 / Math.Pow(6.367e6, 2.0) * Particle.G; + + // Create a test world + Random r = new Random(); + List<Matter> elems = new List<Matter>(); + for (int t = 0; t < 100; t++) + { + elems.Add(new Particle( + new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), + new Vector(0.0, 0.0, 0.0), + Quaternion.Identity, + 0.01, null).Matter); + } + Matter world = CompositeMatter.Create(elems); HostWindow hw = new HostWindow("Alunite", 640, 480); hw.WindowState = WindowState.Maximized; - hw.Control = new Visualizer(null); + hw.Control = new Visualizer(world); hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index 513c0ca..62c2b9a 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,119 +1,58 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; - this._Particles = new List<_Particle>(); - - Random r = new Random(); - for (int t = 0; t < 100; t++) - { - this._Particles.Add(new _Particle() - { - Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), - Velocity = new Vector(0.0, 0.0, 0.0) - }); - } } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); Matrix4d view = Matrix4d.LookAt(new Vector(3.0, 3.0, 3.0), new Vector(0.0, 0.0, 0.0), up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); GL.Color4(0.0, 0.5, 1.0, 1.0); GL.Begin(BeginMode.Points); - foreach (_Particle pt in this._Particles) + foreach (Particle p in this._Matter.Particles) { - GL.Vertex3(pt.Position); + GL.Vertex3(p.Position); } GL.End(); } - public override void Update(GUIControlContext Context, double Time) - { - List<_Particle> nparts = new List<_Particle>(this._Particles.Count); - for(int t = 0; t < this._Particles.Count; t++) - { - _Particle pt = this._Particles[t]; - Vector pos = pt.Position; - Vector vel = pt.Velocity; - - // Make force vector - Vector force = new Vector(0.0, 0.0, -1.0); - for(int i = 0; i < this._Particles.Count; i++) - { - _Particle opt = this._Particles[i]; - if (t != i) - { - Vector away = pos - opt.Position; - double len = Math.Max(away.Length, 0.001); - Vector awayforce = away * (0.001 / (len * len * len)); - force += awayforce; - } - } - - vel += force * Time; - pos += vel * Time; - - double rest = 0.2; - if (pos.X > 1.0) { pos.X = 1.0; vel.X = -Math.Abs(vel.X) * rest; } - if (pos.Y > 1.0) { pos.Y = 1.0; vel.Y = -Math.Abs(vel.Y) * rest; } - if (pos.Z > 1.0) { pos.Z = 1.0; vel.Z = -Math.Abs(vel.Z) * rest; } - if (pos.X < 0.0) { pos.X = 0.0; vel.X = Math.Abs(vel.X) * rest; } - if (pos.Y < 0.0) { pos.Y = 0.0; vel.Y = Math.Abs(vel.Y) * rest; } - if (pos.Z < 0.0) { pos.Z = 0.0; vel.Z = Math.Abs(vel.Z) * rest; } - - nparts.Add(new _Particle() - { - Position = pos, - Velocity = vel - }); - } - this._Particles = nparts; - } - - private struct _Particle - { - public Vector Velocity; - public Vector Position; - } - - private List<_Particle> _Particles; private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
260ac536692be4624ca714119645a2de7dc6f9cb
Some more unimplemented interfaces
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 2d1cb23..25ed15f 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,59 +1,60 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Matter.cs" /> + <Compile Include="Particle.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Particle.cs b/Alunite/Particle.cs new file mode 100644 index 0000000..0bf69de --- /dev/null +++ b/Alunite/Particle.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Contains the material properties for a particle excluding position, orientation, velocity and mass, which + /// are common to all particles. + /// </summary> + public interface ISubstance + { + /// <summary> + /// Updates a particle of this substance by the specified amount of time in seconds in the given environment (which is orientated to the particle). Assume + /// that the units used in the Environment are consistent with those used for particles (meters, seconds, kilograms). This function should account for every + /// force at every scale, including gravity and electromagnetism. + /// </summary> + void Update(Matter Environment, double Time, out Vector DPosition, out Vector DVelocity, out Quaternion DOrientation, ref double Mass); + } + + /// <summary> + /// Describes a particle in a certain frame of reference. + /// </summary> + public struct Particle + { + public Particle(Vector Position, Vector Velocity, Quaternion Orientation, double Mass, ISubstance Substance) + { + this.Position = Position; + this.Velocity = Velocity; + this.Orientation = Orientation; + this.Mass = Mass; + this.Substance = Substance; + } + + /// <summary> + /// The gravitational constant which satisfies F = G * (M1 + M2) / (R * R) with F being the force of gravity in newtons, M1 and M2 the mass of the objects + /// in kilograms and R the distance between them in meters. + /// </summary> + public static double G = 6.67428e-11; + + /// <summary> + /// The relative location of the particle in meters. + /// </summary> + public Vector Position; + + /// <summary> + /// The relative velocity of the particle in meters per second. + /// </summary> + public Vector Velocity; + + /// <summary> + /// The relative orientation of the particle. This can be ignored for particles + /// whose orientation doesn't matter. + /// </summary> + public Quaternion Orientation; + + /// <summary> + /// The mass of the particle in kilograms. + /// </summary> + public double Mass; + + /// <summary> + /// Gets the substance of the particle, which describes the particles properties. + /// </summary> + public ISubstance Substance; + } +} \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs index bd84ba7..513c0ca 100644 --- a/Alunite/Visualizer.cs +++ b/Alunite/Visualizer.cs @@ -1,55 +1,119 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTKGUI; namespace Alunite { /// <summary> /// A visualizer for matter. /// </summary> public class Visualizer : Render3DControl { public Visualizer(Matter Matter) { this._Matter = Matter; + this._Particles = new List<_Particle>(); + + Random r = new Random(); + for (int t = 0; t < 100; t++) + { + this._Particles.Add(new _Particle() + { + Position = new Vector(r.NextDouble(), r.NextDouble(), r.NextDouble()), + Velocity = new Vector(0.0, 0.0, 0.0) + }); + } } /// <summary> /// Gets the matter to be visualized. /// </summary> public Matter Matter { get { return this._Matter; } } public override void SetupProjection(Point Viewsize) { Vector3d up = new Vector3d(0.0, 0.0, 1.0); Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); - Matrix4d view = Matrix4d.LookAt(new Vector(10.0, 10.0, 10.0), new Vector(0.0, 0.0, 0.0), up); + Matrix4d view = Matrix4d.LookAt(new Vector(3.0, 3.0, 3.0), new Vector(0.0, 0.0, 0.0), up); GL.MultMatrix(ref proj); GL.MultMatrix(ref view); } public override void RenderScene() { GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit); GL.PointSize(5.0f); - GL.Begin(BeginMode.Points); GL.Color4(0.0, 0.5, 1.0, 1.0); - GL.Vertex3(0.0, 0.0, 0.0); + GL.Begin(BeginMode.Points); + foreach (_Particle pt in this._Particles) + { + GL.Vertex3(pt.Position); + } GL.End(); } + public override void Update(GUIControlContext Context, double Time) + { + List<_Particle> nparts = new List<_Particle>(this._Particles.Count); + for(int t = 0; t < this._Particles.Count; t++) + { + _Particle pt = this._Particles[t]; + Vector pos = pt.Position; + Vector vel = pt.Velocity; + + // Make force vector + Vector force = new Vector(0.0, 0.0, -1.0); + for(int i = 0; i < this._Particles.Count; i++) + { + _Particle opt = this._Particles[i]; + if (t != i) + { + Vector away = pos - opt.Position; + double len = Math.Max(away.Length, 0.001); + Vector awayforce = away * (0.001 / (len * len * len)); + force += awayforce; + } + } + + vel += force * Time; + pos += vel * Time; + + double rest = 0.2; + if (pos.X > 1.0) { pos.X = 1.0; vel.X = -Math.Abs(vel.X) * rest; } + if (pos.Y > 1.0) { pos.Y = 1.0; vel.Y = -Math.Abs(vel.Y) * rest; } + if (pos.Z > 1.0) { pos.Z = 1.0; vel.Z = -Math.Abs(vel.Z) * rest; } + if (pos.X < 0.0) { pos.X = 0.0; vel.X = Math.Abs(vel.X) * rest; } + if (pos.Y < 0.0) { pos.Y = 0.0; vel.Y = Math.Abs(vel.Y) * rest; } + if (pos.Z < 0.0) { pos.Z = 0.0; vel.Z = Math.Abs(vel.Z) * rest; } + + nparts.Add(new _Particle() + { + Position = pos, + Velocity = vel + }); + } + this._Particles = nparts; + } + + private struct _Particle + { + public Vector Velocity; + public Vector Position; + } + + private List<_Particle> _Particles; private Matter _Matter; } } \ No newline at end of file
dzamkov/Alunite-old
02dd1e83cbed71ce2029559d515f5acd8ed982e2
Some visualization
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 4fcecf9..2d1cb23 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,54 +1,59 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Matter.cs" /> <Compile Include="Program.cs" /> <Compile Include="Quaternion.cs" /> <Compile Include="Vector.cs" /> + <Compile Include="Visualizer.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> + <Reference Include="OpenTKGUI, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\XChess\bin\Debug\OpenTKGUI.dll</HintPath> + </Reference> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index 1909591..d5fda91 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,82 +1,140 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public abstract class Matter { /// <summary> /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given /// in the frame of reference of the matter in question) by a given amount of time in seconds. /// </summary> - public abstract Element Update(Matter Environment, double Time); + public abstract Matter Update(Matter Environment, double Time); + + /// <summary> + /// Applies a transform to this matter. + /// </summary> + public virtual Matter Apply(Transform Transform) + { + return new Element(this, Transform); + } } /// <summary> /// Matter made by a physical composition of other matter. /// </summary> public abstract class CompositeMatter : Matter { /// <summary> /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). /// </summary> - public abstract IEnumerable<Element> Elements { get; } + public abstract IEnumerable<Matter> Elements { get; } } /// <summary> /// Represents a possible the orientation, translation and velocity offset for matter. /// </summary> public struct Transform { public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) { this.Offset = Offset; this.VelocityOffset = VelocityOffset; this.Rotation = Rotation; } /// <summary> /// Applies this transform to another, in effect combining them. /// </summary> public Transform Apply(Transform Transform) { return new Transform( this.Offset + this.Rotation.Rotate(Transform.Offset), this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), this.Rotation * Transform.Rotation); } /// <summary> /// Gets the inverse of this transform. /// </summary> public Transform Inverse { get { Quaternion nrot = this.Rotation.Conjugate; return new Transform( nrot.Rotate(-this.Offset), nrot.Rotate(-this.VelocityOffset), nrot); } } + /// <summary> + /// Gets the identity transform. + /// </summary> + public static Transform Identity + { + get + { + return new Transform( + new Vector(0.0, 0.0, 0.0), + new Vector(0.0, 0.0, 0.0), + Quaternion.Identity); + } + } + public Vector Offset; public Vector VelocityOffset; public Quaternion Rotation; } /// <summary> /// A piece of transformed matter. /// </summary> - public struct Element + public class Element : Matter { + public Element(Matter Source, Transform Transform) + { + this._Source = Source; + this._Transform = Transform; + } + /// <summary> - /// The original matter for this element. + /// Gets the transform of the element. /// </summary> - public Matter Source; + public Transform Transform + { + get + { + return this._Transform; + } + } + + /// <summary> + /// Gets the source matter for the element. + /// </summary> + public Matter Source + { + get + { + return this._Source; + } + } + + public override Matter Update(Matter Environment, double Time) + { + return this._Source.Update(Environment.Apply(this._Transform.Inverse), Time).Apply(this._Transform); + } + + public override Matter Apply(Transform Transform) + { + return new Element(this._Source, Transform.Apply(this._Transform)); + } + + private Transform _Transform; + private Matter _Source; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 202d630..41dceb1 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,21 +1,29 @@ using System; using System.Collections.Generic; +using OpenTK; +using OpenTKGUI; + namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { Transform a = new Transform(new Vector(0.7, 0.4, 1.0), new Vector(0.8, 0.1, 1.0), new Quaternion(new Vector(0.0, 1.0, 0.0), Math.PI / 3.0)); Transform b = new Transform(new Vector(0.3, 1.0, 0.4), new Vector(0.3, 0.2, 1.0), new Quaternion(new Vector(0.0, 0.0, 1.0), Math.PI / 7.0)); a = a.Apply(b).Apply(b.Inverse.Apply(a.Inverse)); + + HostWindow hw = new HostWindow("Alunite", 640, 480); + hw.WindowState = WindowState.Maximized; + hw.Control = new Visualizer(null); + hw.Run(60.0); } } } \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs index 41518eb..c83966f 100644 --- a/Alunite/Quaternion.cs +++ b/Alunite/Quaternion.cs @@ -1,104 +1,115 @@ using System; using System.Collections.Generic; using OpenTK; namespace Alunite { /// <summary> /// Represents a rotation in three-dimensional space. /// </summary> public struct Quaternion { public Quaternion(double A, double B, double C, double D) { this.A = A; this.B = B; this.C = C; this.D = D; } public Quaternion(double Real, Vector Imag) { this.A = Real; this.B = Imag.X; this.C = Imag.Y; this.D = Imag.Z; } public Quaternion(Vector Vector, double Angle) { double hang = Angle * 0.5; double sina = Math.Sin(hang); double cosa = Math.Cos(hang); this.A = cosa; this.B = Vector.X * sina; this.C = Vector.Y * sina; this.D = Vector.Z * sina; } + /// <summary> + /// Gets the identity quaternion. + /// </summary> + public static Quaternion Identity + { + get + { + return new Quaternion(1.0, 0.0, 0.0, 0.0); + } + } + /// <summary> /// Gets the real (scalar) part of the quaternion. /// </summary> public double Real { get { return this.A; } } /// <summary> /// Gets the imaginary part of the quaternion. /// </summary> public Vector Imag { get { return new Vector(this.B, this.C, this.D); } } /// <summary> /// Gets the conjugate of this quaternion. /// </summary> public Quaternion Conjugate { get { return new Quaternion(this.A, -this.B, -this.C, -this.D); } } /// <summary> /// Rotates a point using this vector. /// </summary> public Vector Rotate(Vector Point) { double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; return new Vector(nb, nc, nd); } public static Quaternion operator *(Quaternion A, Quaternion B) { return new Quaternion( A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); } public double A; public double B; public double C; public double D; } } \ No newline at end of file diff --git a/Alunite/Visualizer.cs b/Alunite/Visualizer.cs new file mode 100644 index 0000000..bd84ba7 --- /dev/null +++ b/Alunite/Visualizer.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; + +using OpenTK; +using OpenTK.Graphics; +using OpenTK.Graphics.OpenGL; +using OpenTKGUI; + +namespace Alunite +{ + /// <summary> + /// A visualizer for matter. + /// </summary> + public class Visualizer : Render3DControl + { + public Visualizer(Matter Matter) + { + this._Matter = Matter; + } + + /// <summary> + /// Gets the matter to be visualized. + /// </summary> + public Matter Matter + { + get + { + return this._Matter; + } + } + + public override void SetupProjection(Point Viewsize) + { + Vector3d up = new Vector3d(0.0, 0.0, 1.0); + Matrix4d proj = Matrix4d.CreatePerspectiveFieldOfView(Math.Sin(Math.PI / 8.0), this.Size.AspectRatio, 0.1, 100.0); + Matrix4d view = Matrix4d.LookAt(new Vector(10.0, 10.0, 10.0), new Vector(0.0, 0.0, 0.0), up); + GL.MultMatrix(ref proj); + GL.MultMatrix(ref view); + } + + public override void RenderScene() + { + GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); + GL.Clear(ClearBufferMask.ColorBufferBit); + + GL.PointSize(5.0f); + GL.Begin(BeginMode.Points); + GL.Color4(0.0, 0.5, 1.0, 1.0); + GL.Vertex3(0.0, 0.0, 0.0); + GL.End(); + } + + private Matter _Matter; + } +} \ No newline at end of file
dzamkov/Alunite-old
404a5dd3832f30ca3ead1bd9ac4f44bbbf8c8dcc
Transforms
diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs index ae5a6c2..1909591 100644 --- a/Alunite/Matter.cs +++ b/Alunite/Matter.cs @@ -1,39 +1,82 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Represents an untransformed object that can participate in physical interactions. /// </summary> public abstract class Matter { /// <summary> /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given /// in the frame of reference of the matter in question) by a given amount of time in seconds. /// </summary> public abstract Element Update(Matter Environment, double Time); } /// <summary> /// Matter made by a physical composition of other matter. /// </summary> public abstract class CompositeMatter : Matter { /// <summary> /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). /// </summary> public abstract IEnumerable<Element> Elements { get; } } + /// <summary> + /// Represents a possible the orientation, translation and velocity offset for matter. + /// </summary> + public struct Transform + { + public Transform(Vector Offset, Vector VelocityOffset, Quaternion Rotation) + { + this.Offset = Offset; + this.VelocityOffset = VelocityOffset; + this.Rotation = Rotation; + } + + /// <summary> + /// Applies this transform to another, in effect combining them. + /// </summary> + public Transform Apply(Transform Transform) + { + return new Transform( + this.Offset + this.Rotation.Rotate(Transform.Offset), + this.VelocityOffset + this.Rotation.Rotate(Transform.VelocityOffset), + this.Rotation * Transform.Rotation); + } + + /// <summary> + /// Gets the inverse of this transform. + /// </summary> + public Transform Inverse + { + get + { + Quaternion nrot = this.Rotation.Conjugate; + return new Transform( + nrot.Rotate(-this.Offset), + nrot.Rotate(-this.VelocityOffset), + nrot); + } + } + + public Vector Offset; + public Vector VelocityOffset; + public Quaternion Rotation; + } + /// <summary> /// A piece of transformed matter. /// </summary> public struct Element { /// <summary> /// The original matter for this element. /// </summary> public Matter Source; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index 1588898..202d630 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,22 +1,21 @@ using System; using System.Collections.Generic; namespace Alunite { /// <summary> /// Program main class. /// </summary> public static class Program { /// <summary> /// Program main entry-point. /// </summary> public static void Main(string[] Args) { - Quaternion uprot = new Quaternion(new Vector(0.0, 0.0, 1.0), Math.PI / 16.0); - Vector test = new Vector(0.9, 0.5, 0.5); - test = uprot.Rotate(test); - + Transform a = new Transform(new Vector(0.7, 0.4, 1.0), new Vector(0.8, 0.1, 1.0), new Quaternion(new Vector(0.0, 1.0, 0.0), Math.PI / 3.0)); + Transform b = new Transform(new Vector(0.3, 1.0, 0.4), new Vector(0.3, 0.2, 1.0), new Quaternion(new Vector(0.0, 0.0, 1.0), Math.PI / 7.0)); + a = a.Apply(b).Apply(b.Inverse.Apply(a.Inverse)); } } } \ No newline at end of file
dzamkov/Alunite-old
9df72d0292c7e59e9e9dfdebabb87d148c9f8598
Basic maths
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 841b555..4fcecf9 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,41 +1,54 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{056E865F-6D6B-44E1-AD98-50DA0DB1C97E}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> + <ItemGroup> + <Compile Include="Matter.cs" /> + <Compile Include="Program.cs" /> + <Compile Include="Quaternion.cs" /> + <Compile Include="Vector.cs" /> + </ItemGroup> + <ItemGroup> + <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> + <Reference Include="System" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Matter.cs b/Alunite/Matter.cs new file mode 100644 index 0000000..ae5a6c2 --- /dev/null +++ b/Alunite/Matter.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Represents an untransformed object that can participate in physical interactions. + /// </summary> + public abstract class Matter + { + /// <summary> + /// Creates the updated form of this matter given the environment (which is all matter in the world excluding, and given + /// in the frame of reference of the matter in question) by a given amount of time in seconds. + /// </summary> + public abstract Element Update(Matter Environment, double Time); + } + + /// <summary> + /// Matter made by a physical composition of other matter. + /// </summary> + public abstract class CompositeMatter : Matter + { + /// <summary> + /// Gets the pieces of matter that makes up this matter. The order should not matter (lol). + /// </summary> + public abstract IEnumerable<Element> Elements { get; } + } + + /// <summary> + /// A piece of transformed matter. + /// </summary> + public struct Element + { + /// <summary> + /// The original matter for this element. + /// </summary> + public Matter Source; + } +} \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs new file mode 100644 index 0000000..1588898 --- /dev/null +++ b/Alunite/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// Program main class. + /// </summary> + public static class Program + { + /// <summary> + /// Program main entry-point. + /// </summary> + public static void Main(string[] Args) + { + Quaternion uprot = new Quaternion(new Vector(0.0, 0.0, 1.0), Math.PI / 16.0); + Vector test = new Vector(0.9, 0.5, 0.5); + test = uprot.Rotate(test); + + } + } +} \ No newline at end of file diff --git a/Alunite/Quaternion.cs b/Alunite/Quaternion.cs new file mode 100644 index 0000000..41518eb --- /dev/null +++ b/Alunite/Quaternion.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; + +using OpenTK; + +namespace Alunite +{ + /// <summary> + /// Represents a rotation in three-dimensional space. + /// </summary> + public struct Quaternion + { + public Quaternion(double A, double B, double C, double D) + { + this.A = A; + this.B = B; + this.C = C; + this.D = D; + } + + public Quaternion(double Real, Vector Imag) + { + this.A = Real; + this.B = Imag.X; + this.C = Imag.Y; + this.D = Imag.Z; + } + + public Quaternion(Vector Vector, double Angle) + { + double hang = Angle * 0.5; + double sina = Math.Sin(hang); + double cosa = Math.Cos(hang); + this.A = cosa; + this.B = Vector.X * sina; + this.C = Vector.Y * sina; + this.D = Vector.Z * sina; + } + + /// <summary> + /// Gets the real (scalar) part of the quaternion. + /// </summary> + public double Real + { + get + { + return this.A; + } + } + + /// <summary> + /// Gets the imaginary part of the quaternion. + /// </summary> + public Vector Imag + { + get + { + return new Vector(this.B, this.C, this.D); + } + } + + /// <summary> + /// Gets the conjugate of this quaternion. + /// </summary> + public Quaternion Conjugate + { + get + { + return new Quaternion(this.A, -this.B, -this.C, -this.D); + } + } + + /// <summary> + /// Rotates a point using this vector. + /// </summary> + public Vector Rotate(Vector Point) + { + double ta = - this.B * Point.X - this.C * Point.Y - this.D * Point.Z; + double tb = + this.A * Point.X + this.C * Point.Z - this.D * Point.Y; + double tc = + this.A * Point.Y - this.B * Point.Z + this.D * Point.X; + double td = + this.A * Point.Z + this.B * Point.Y - this.C * Point.X; + + double nb = - ta * this.B + tb * this.A - tc * this.D + td * this.C; + double nc = - ta * this.C + tb * this.D + tc * this.A - td * this.B; + double nd = - ta * this.D - tb * this.C + tc * this.B + td * this.A; + + return new Vector(nb, nc, nd); + } + + public static Quaternion operator *(Quaternion A, Quaternion B) + { + return new Quaternion( + A.A * B.A - A.B * B.B - A.C * B.C - A.D * B.D, + A.A * B.B + A.B * B.A + A.C * B.D - A.D * B.C, + A.A * B.C - A.B * B.D + A.C * B.A + A.D * B.B, + A.A * B.D + A.B * B.C - A.C * B.B + A.D * B.A); + } + + public double A; + public double B; + public double C; + public double D; + } +} \ No newline at end of file diff --git a/Alunite/Vector.cs b/Alunite/Vector.cs new file mode 100644 index 0000000..203b1df --- /dev/null +++ b/Alunite/Vector.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; + +using OpenTK; + +namespace Alunite +{ + /// <summary> + /// Represents a point or offset in three-dimensional space. + /// </summary> + public struct Vector + { + public Vector(double X, double Y, double Z) + { + this.X = X; + this.Y = Y; + this.Z = Z; + } + + public static implicit operator Vector3d(Vector Vector) + { + return new Vector3d(Vector.X, Vector.Y, Vector.Z); + } + + public static explicit operator Vector3(Vector Vector) + { + return new Vector3((float)Vector.X, (float)Vector.Y, (float)Vector.Z); + } + + public static bool operator ==(Vector A, Vector B) + { + return A.X == B.X && A.Y == B.Y && A.Z == B.Z; + } + + public static bool operator !=(Vector A, Vector B) + { + return A.X != B.X || A.Y != B.Y || A.Z != B.Z; + } + + public static Vector operator +(Vector A, Vector B) + { + return new Vector(A.X + B.X, A.Y + B.Y, A.Z + B.Z); + } + + public static Vector operator -(Vector A, Vector B) + { + return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); + } + + public static Vector operator *(Vector A, double Magnitude) + { + return new Vector(A.X * Magnitude, A.Y * Magnitude, A.Z * Magnitude); + } + + public static Vector operator -(Vector A) + { + return new Vector(-A.X, -A.Y, -A.Z); + } + + public override string ToString() + { + return this.X.ToString() + ", " + this.Y.ToString() + ", " + this.Z.ToString(); + } + + /// <summary> + /// Gets the cross product of two vectors. + /// </summary> + public static Vector Cross(Vector A, Vector B) + { + return + new Vector( + (A.Y * B.Z) - (A.Z * B.Y), + (A.Z * B.X) - (A.X * B.Z), + (A.X * B.Y) - (A.Y * B.X)); + } + + /// <summary> + /// Compares two vectors lexographically. + /// </summary> + public static bool Compare(Vector A, Vector B) + { + if (A.X > B.X) + return true; + if (A.X < B.X) + return false; + if (A.Y > B.Y) + return true; + if (A.Y < B.Y) + return false; + if (A.Z > B.Z) + return true; + return false; + } + + /// <summary> + /// Gets the outgoing ray of an object hitting a plane with the specified normal at the + /// specified incoming ray. + /// </summary> + public static Vector Reflect(Vector Incoming, Vector Normal) + { + return Incoming - Normal * (2 * Vector.Dot(Incoming, Normal) / Normal.SquareLength); + } + + /// <summary> + /// Multiplies each component of the vectors with the other's corresponding component. + /// </summary> + public static Vector Scale(Vector A, Vector B) + { + return new Vector(A.X * B.X, A.Y * B.Y, A.Z * B.Z); + } + + /// <summary> + /// Gets the dot product between two vectors. + /// </summary> + public static double Dot(Vector A, Vector B) + { + return A.X * B.X + A.Y * B.Y + A.Z * B.Z; + } + + /// <summary> + /// Gets the length of the vector. + /// </summary> + public double Length + { + get + { + return Math.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); + } + } + + /// <summary> + /// Gets the square of the length of the vector. + /// </summary> + public double SquareLength + { + get + { + return this.X * this.X + this.Y * this.Y + this.Z * this.Z; + } + } + + /// <summary> + /// Normalizes the vector so its length is one but its direction is unchanged. + /// </summary> + public void Normalize() + { + double ilen = 1.0 / this.Length; + this.X *= ilen; + this.Y *= ilen; + this.Z *= ilen; + } + + /// <summary> + /// Normalizes the specified vector. + /// </summary> + public static Vector Normalize(Vector A) + { + A.Normalize(); + return A; + } + + public double X; + public double Y; + public double Z; + } +} \ No newline at end of file
dzamkov/Alunite-old
db5f1815f3d888d1888206a89b31e713f837f945
If you squint really hard, it might look somewhat like a planet
diff --git a/Alunite/Window.cs b/Alunite/Window.cs index 5ad66b4..47afafb 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,181 +1,179 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.Off; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; // Initial triangulation this._Triangulation = SphericalTriangulation.CreateIcosahedron(); this._Triangulation.Subdivide(); this._Triangulation.Subdivide(); + this._Triangulation.Subdivide(); + this._Triangulation.Subdivide(); + this._Triangulation.Subdivide(); // Assign random colors for testing Random r = new Random(101); this._VertexColors = new Color[this._Triangulation.Vertices.Count]; for (int t = 0; t < this._VertexColors.Length; t++) { if (r.NextDouble() < 0.4) { this._VertexColors[t] = Color.RGB(0.0, 0.4, 0.1); } else { this._VertexColors[t] = Color.RGB(0.0, 0.0, 0.2); } } // Create a cubemap - this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); + this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 512, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); // Planet Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); AtmosphereOptions ao = AtmosphereOptions.DefaultEarth; ao.RadiusGround = (float)RadiusGround; AtmosphereQualityOptions aqo = AtmosphereQualityOptions.Default; this._Atmosphere = Atmosphere.Generate(ao, aqo, pci, shaders); Atmosphere.DefineConstants(ao, aqo, pci); this._Planet = Shader.Load(shaders["Atmosphere"]["Planet.glsl"], pci); - this._Earth = Texture.Load(resources["Textures"]["Earth.tif"]); - this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 300.0f, 20000.0f); Matrix4 view = Matrix4.LookAt( (Vector3)eyepos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); Matrix4 total = view * proj; Matrix4 itotal = Matrix4.Invert(total); Vector4 test = new Vector4(0.0f, 0.0f, 0.0f, 1.0f); test = Vector4.Transform(test, itotal); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref total); GL.DepthFunc(DepthFunction.Lequal); // Planet GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); this._Planet.Call(); this._Atmosphere.Setup(this._Planet); this._Cubemap.SetUnit(TextureTarget.TextureCubeMap, TextureUnit.Texture4); - this._Earth.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture5); this._Planet.SetUniform("EyePosition", eyepos); this._Planet.SetUniform("SunDirection", new Vector(Math.Sin(this._SunAngle), Math.Cos(this._SunAngle), 0.0)); this._Planet.SetUniform("ProjectionInverse", ref itotal); this._Planet.SetUniform("NearDistance", 300.0f); this._Planet.SetUniform("FarDistance", 20000.0f); this._Planet.SetUniform("CubeMap", TextureUnit.Texture4); - this._Planet.SetUniform("Map", TextureUnit.Texture5); Shader.DrawQuad(); - this.Title = this._Height.ToString(); + this.Title = "Alunite (" + this.RenderFrequency.ToString() + ")"; this.SwapBuffers(); } /// <summary> /// Renderable to produce a cubemap for the planet. /// </summary> private struct _CubemapRenderable : IRenderable { public void Render() { GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) { Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this.Window._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this.Window._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); GL.Color4(this.Window._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); } GL.End(); } public Window Window; } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Z]) this._SunAngle += updatetime; if (this.Keyboard[Key.X]) this._SunAngle -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } public const double RadiusGround = 6360.0; private PrecomputedAtmosphere _Atmosphere; - private Texture _Earth; private Texture _Cubemap; private Shader _CubemapUnroll; private Shader _Planet; private Color[] _VertexColors; private SphericalTriangulation _Triangulation; private double _SunAngle; private double _Height; private double _XRot; private double _ZRot; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index 50ffac6..8566483 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,119 +1,117 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjectionInverse; uniform float NearDistance; uniform float FarDistance; uniform samplerCube CubeMap; -uniform sampler2D Map; const vec3 SunColor = vec3(20.0); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; vec4 trans = ProjectionInverse * gl_Vertex; Ray = (trans / trans.w).xyz - EyePosition; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _IRRADIANCE_UV_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #define _IRRADIANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Irradiance.glsl" #include "Precompute/Inscatter.glsl" vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); vec4 is = max(inscatter(mu, nu, r, mus), 0.0); result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { float mus = dot(n, sol); vec3 direct = transmittance(Rg, mus) * max(mus, 0.0) * SunColor / Pi; vec3 irr = irradiance(Rg, mus); vec3 full = direct + irr; vec3 color = textureCube(CubeMap, n); - color = texture2D(Map, vec2(atan(n.y, n.x), acos(n.z)) * vec2(0.5, 1.0) / Pi + vec2(0.5, 0.0)); return full * color; } vec3 HDR(vec3 L) { L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); gl_FragDepth = 1.0; } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); } #endif \ No newline at end of file
dzamkov/Alunite-old
84603a4928b9db32005dc67c1cba6c9ef7e7363f
A reference image?
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 8203a75..99fd93b 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,139 +1,183 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// A triangulation over a unit sphere. /// </summary> public struct SphericalTriangulation { /// <summary> /// Adds a triangle to the triangulation. /// </summary> public void AddTriangle(Triangle<int> Triangle) { this.Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this.SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this.Vertices[Triangle.A], this.Vertices[Triangle.B], this.Vertices[Triangle.C]); } + /// <summary> + /// Subdivides the entire sphere, quadrupling the amount of triangles while maintaining the delaunay property. + /// </summary> + public void Subdivide() + { + var oldtris = this.Triangles; + var oldsegs = this.SegmentTriangles; + this.Triangles = new HashSet<Triangle<int>>(); + this.SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); + + Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); + + foreach (Triangle<int> tri in oldtris) + { + int[] midpoints = new int[3]; + Segment<int>[] segs = tri.Segments; + for (int t = 0; t < 3; t++) + { + Segment<int> seg = segs[t]; + int midpoint; + if (!newsegs.TryGetValue(seg, out midpoint)) + { + midpoint = this.Vertices.Count; + this.Vertices.Add( + Vector.Normalize( + Segment.Midpoint( + new Segment<Vector>( + this.Vertices[seg.A], + this.Vertices[seg.B])))); + newsegs.Add(seg.Flip, midpoint); + } + else + { + newsegs.Remove(seg); + } + midpoints[t] = midpoint; + } + this.AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); + this.AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); + this.AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); + this.AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); + } + } + /// <summary> /// Inserts a point in the triangulation and splits triangles to maintain the delaunay property. /// </summary> public void SplitTriangle(Triangle<int> Triangle, Vector NewPosition, int NewPoint) { this.Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this.SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, NewPosition); if (npointangle > othercircumangle) { this.Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this.AddTriangle(new Triangle<int>(NewPoint, seg)); } } /// <summary> /// Splits a triangle at its center, maintaining the delaunay property. /// </summary> public void SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector npos = Alunite.Triangle.Normal(vectri); this.SplitTriangle(Triangle, npos, this.AddVertex(npos)); } /// <summary> /// Adds a vertex (with length 1) to the spherical triangulation. /// </summary> public int AddVertex(Vector Position) { int ind = this.Vertices.Count; this.Vertices.Add(Position); return ind; } /// <summary> /// Creates a spherical triangulation based off an icosahedron. /// </summary> public static SphericalTriangulation CreateIcosahedron() { SphericalTriangulation st = new SphericalTriangulation(); Primitive icosa = Primitive.Icosahedron; st.Vertices = new List<Vector>(icosa.Vertices.Length); st.Vertices.AddRange(icosa.Vertices); st.SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); st.Triangles = new HashSet<Triangle<int>>(); foreach (Triangle<int> tri in icosa.Triangles) { st.AddTriangle(tri); } return st; } /// <summary> /// Triangles that are part of the sphere. /// </summary> public HashSet<Triangle<int>> Triangles; /// <summary> /// A mapping of segments to the triangles that produce them. /// </summary> public Dictionary<Segment<int>, Triangle<int>> SegmentTriangles; /// <summary> /// An ordered list of vertices that make up the sphere. /// </summary> public List<Vector> Vertices; } } \ No newline at end of file diff --git a/Alunite/Shader.cs b/Alunite/Shader.cs index e62f3ac..b64e283 100644 --- a/Alunite/Shader.cs +++ b/Alunite/Shader.cs @@ -1,415 +1,424 @@ using System.Collections.Generic; using System; using System.IO; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Represents a shader in graphics memory. /// </summary> public struct Shader { /// <summary> /// Sets the shader to be used for subsequent render operations. /// </summary> public void Call() { GL.UseProgram(this.Program); } /// <summary> /// Sets a uniform variable. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, Vector Value) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform3(loc, (Vector3)Value); } + /// <summary> + /// Sets a uniform float. Shader must be called beforehand. + /// </summary> + public void SetUniform(string Name, float Value) + { + int loc = GL.GetUniformLocation(this.Program, Name); + GL.Uniform1(loc, Value); + } + /// <summary> /// Sets a uniform matrix. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, ref Matrix4 Matrix) { GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), false, ref Matrix); } /// <summary> /// Sets a uniform texture. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, TextureUnit Unit) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform1(loc, (int)Unit - (int)TextureUnit.Texture0); } /// <summary> /// Sets a uniform integer. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, int Value) { GL.Uniform1(GL.GetUniformLocation(this.Program, Name), Value); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. /// </summary> public void Draw2DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height) { GL.FramebufferTexture2D(Framebuffer, Attachment, TextureTarget.Texture2D, Texture, 0); GL.Viewport(0, 0, Width, Height); this.DrawFull(); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. The "Layer" uniform is set /// in the shader to indicate depth. /// </summary> public void Draw3DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height, int Depth) { this.Call(); int luniform = GL.GetUniformLocation(this.Program, "Layer"); for (int t = 0; t < Depth; t++) { GL.FramebufferTexture3D(Framebuffer, Attachment, TextureTarget.Texture3D, Texture, 0, t); GL.Viewport(0, 0, Width, Height); GL.Uniform1(luniform, t); DrawQuad(); } } /// <summary> /// Runs the fragment shader on all pixels on the current viewport. Transformation matrices must be set to identy for this to work correctly. /// </summary> public void DrawFull() { this.Call(); DrawQuad(); } /// <summary> /// Sets the rendering mode to default (removing all shaders). /// </summary> public static void Dismiss() { GL.UseProgram(0); } /// <summary> /// Draws a shape that includes the entire viewport. /// </summary> public static void DrawQuad() { GL.Begin(BeginMode.Quads); GL.Vertex2(-1.0, -1.0); GL.Vertex2(+1.0, -1.0); GL.Vertex2(+1.0, +1.0); GL.Vertex2(-1.0, +1.0); GL.End(); } /// <summary> /// Loads a shader program from a vertex and fragment shader in GLSL format. /// </summary> public static Shader Load(Alunite.Path Vertex, Alunite.Path Fragment) { Shader shade = new Shader(); int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(vshade, Path.ReadText(Vertex)); GL.ShaderSource(fshade, Path.ReadText(Fragment)); GL.CompileShader(vshade); GL.CompileShader(fshade); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Loads a shader from a single, defining _VERTEX_ for vertex shaders and _FRAGMENT_ for fragment shaders. /// </summary> public static Shader Load(Alunite.Path File) { return Load(File, new Dictionary<string, string>()); } /// <summary> /// More advanced shader loading function that will dynamically replace constants in the specified files. /// </summary> public static Shader Load(Alunite.Path File, Dictionary<string, string> Constants) { return Load(File, new PrecompilerInput() { Constants = Constants, LoadedFiles = new Dictionary<string, string[]>() }); } /// <summary> /// Loads a shader from the specified file using the specified input. /// </summary> public static Shader Load(Alunite.Path File, PrecompilerInput Input) { int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); StringBuilder vshadesource = new StringBuilder(); StringBuilder fshadesource = new StringBuilder(); PrecompilerInput vpce = Input.Copy(); PrecompilerInput fpce = Input.Copy(); vpce.Define("_VERTEX_", "1"); fpce.Define("_FRAGMENT_", "1"); BuildSource(File, vpce, vshadesource); GL.ShaderSource(vshade, vshadesource.ToString()); GL.CompileShader(vshade); vshadesource = null; BuildSource(File, fpce, fshadesource); GL.ShaderSource(fshade, fshadesource.ToString()); GL.CompileShader(fshade); fshadesource = null; Shader shade = new Shader(); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Creates a new precompiler input set. /// </summary> public static PrecompilerInput CreatePrecompilerInput() { return new PrecompilerInput() { Constants = new Dictionary<string, string>(), LoadedFiles = new Dictionary<string, string[]>() }; } /// <summary> /// Input to the precompiler. /// </summary> public struct PrecompilerInput { public PrecompilerInput(Path File) { this.Constants = new Dictionary<string, string>(); this.LoadedFiles = new Dictionary<string, string[]>(); } /// <summary> /// Gets the file at the specified path. /// </summary> public string[] GetFile(Path Path) { string[] lines; if (!this.LoadedFiles.TryGetValue(Path.PathString, out lines)) { this.LoadedFiles[Path.PathString] = lines = File.ReadAllLines(Path.PathString); } return lines; } /// <summary> /// Creates a copy of this precompiler input with its own precompiler constants. /// </summary> public PrecompilerInput Copy() { return new PrecompilerInput() { LoadedFiles = this.LoadedFiles, Constants = new Dictionary<string, string>(this.Constants) }; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant, string Value) { this.Constants[Constant] = Value; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant) { this.Constants[Constant] = "1"; } /// <summary> /// Undefines a constant. /// </summary> public void Undefine(string Constant) { this.Constants.Remove(Constant); } /// <summary> /// Constants defined for the precompiler. /// </summary> public Dictionary<string, string> Constants; /// <summary> /// The files loaded for the precompiler. /// </summary> public Dictionary<string, string[]> LoadedFiles; } /// <summary> /// Precompiles the source code defined by the lines with the specified constants defined. Outputs the precompiled source /// to the given stringbuilder. /// </summary> public static void BuildSource(Path File, PrecompilerInput Input, StringBuilder Output) { string[] lines = Input.GetFile(File); _ProcessBlock(((IEnumerable<string>)lines).GetEnumerator(), File, Input, Output, true); } /// <summary> /// Processes an ifdef/else/endif block where Interpret denotes the success of the if statement. Returns true if exited on an endif or false /// if exited on an else. /// </summary> private static bool _ProcessBlock(IEnumerator<string> LineEnumerator, Path File, PrecompilerInput Input, StringBuilder Output, bool Interpret) { while (LineEnumerator.MoveNext()) { string line = LineEnumerator.Current; // Does this line contain a directive? if (line.Length > 0) { if (line[0] == '#') { string[] lineparts = line.Split(' '); if (lineparts[0] == "#ifdef") { if (Interpret) { bool contains = Input.Constants.ContainsKey(lineparts[1]); if (!_ProcessBlock(LineEnumerator, File, Input, Output, contains)) { _ProcessBlock(LineEnumerator, File, Input, Output, !contains); } } else { if (!_ProcessBlock(LineEnumerator, File, Input, Output, false)) { _ProcessBlock(LineEnumerator, File, Input, Output, false); } } continue; } if (lineparts[0] == "#include") { if (Interpret) { string filepath = lineparts[1].Substring(1, lineparts[1].Length - 2); BuildSource(File.Parent.Lookup(filepath), Input, Output); } continue; } if (lineparts[0] == "#else") { return false; } if (lineparts[0] == "#endif") { return true; } if (Interpret) { if (lineparts[0] == "#define") { if (lineparts.Length > 2) { Input.Define(lineparts[1], lineparts[2]); } else { Input.Define(lineparts[1]); } continue; } if (lineparts[0] == "#undef") { Input.Undefine(lineparts[1]); continue; } Output.AppendLine(line); } } else { if (Interpret) { // Replace constants Dictionary<int, KeyValuePair<int, string>> matches = new Dictionary<int, KeyValuePair<int, string>>(); foreach (KeyValuePair<string, string> constant in Input.Constants) { int ind = line.IndexOf(constant.Key); while (ind >= 0) { int size = constant.Key.Length; KeyValuePair<int, string> lastmatch; if (matches.TryGetValue(ind, out lastmatch)) { if (lastmatch.Key < size) { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } } else { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } ind = line.IndexOf(constant.Key, ind + 1); } } if (matches.Count > 0) { int c = 0; var orderedmatches = new List<KeyValuePair<int, KeyValuePair<int, string>>>(matches); Sort.InPlace<KeyValuePair<int, KeyValuePair<int, string>>>((a, b) => a.Key > b.Key, orderedmatches); foreach (KeyValuePair<int, KeyValuePair<int, string>> match in orderedmatches) { Output.Append(line.Substring(c, match.Key - c)); Output.Append(match.Value.Value); c = match.Key + match.Value.Key; } Output.AppendLine(line.Substring(c)); } else { Output.AppendLine(line); } } } } } return true; } /// <summary> /// Index of the program of the shader. /// </summary> public int Program; } } \ No newline at end of file diff --git a/Alunite/Window.cs b/Alunite/Window.cs index e3ee40f..5ad66b4 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,177 +1,181 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; - this.VSync = VSyncMode.On; + this.VSync = VSyncMode.Off; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; // Initial triangulation this._Triangulation = SphericalTriangulation.CreateIcosahedron(); + this._Triangulation.Subdivide(); + this._Triangulation.Subdivide(); // Assign random colors for testing Random r = new Random(101); this._VertexColors = new Color[this._Triangulation.Vertices.Count]; for (int t = 0; t < this._VertexColors.Length; t++) { - this._VertexColors[t] = Color.RGB(r.NextDouble(), r.NextDouble(), r.NextDouble()); + if (r.NextDouble() < 0.4) + { + this._VertexColors[t] = Color.RGB(0.0, 0.4, 0.1); + } + else + { + this._VertexColors[t] = Color.RGB(0.0, 0.0, 0.2); + } } // Create a cubemap this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); - // A shader to test the cubemap with - this._CubemapUnroll = Shader.Load(shaders["UnrollCubemap.glsl"]); - // Planet Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); AtmosphereOptions ao = AtmosphereOptions.DefaultEarth; ao.RadiusGround = (float)RadiusGround; AtmosphereQualityOptions aqo = AtmosphereQualityOptions.Default; this._Atmosphere = Atmosphere.Generate(ao, aqo, pci, shaders); Atmosphere.DefineConstants(ao, aqo, pci); this._Planet = Shader.Load(shaders["Atmosphere"]["Planet.glsl"], pci); + this._Earth = Texture.Load(resources["Textures"]["Earth.tif"]); + this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; - Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 1.0f, 20000.0f); + Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 300.0f, 20000.0f); Matrix4 view = Matrix4.LookAt( (Vector3)eyepos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); Matrix4 total = view * proj; Matrix4 itotal = Matrix4.Invert(total); + Vector4 test = new Vector4(0.0f, 0.0f, 0.0f, 1.0f); + test = Vector4.Transform(test, itotal); + GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref total); + GL.DepthFunc(DepthFunction.Lequal); + // Planet GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); this._Planet.Call(); this._Atmosphere.Setup(this._Planet); + this._Cubemap.SetUnit(TextureTarget.TextureCubeMap, TextureUnit.Texture4); + this._Earth.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture5); this._Planet.SetUniform("EyePosition", eyepos); - this._Planet.SetUniform("SunDirection", new Vector(1.0, 0.0, 0.0)); + this._Planet.SetUniform("SunDirection", new Vector(Math.Sin(this._SunAngle), Math.Cos(this._SunAngle), 0.0)); this._Planet.SetUniform("ProjectionInverse", ref itotal); + this._Planet.SetUniform("NearDistance", 300.0f); + this._Planet.SetUniform("FarDistance", 20000.0f); + this._Planet.SetUniform("CubeMap", TextureUnit.Texture4); + this._Planet.SetUniform("Map", TextureUnit.Texture5); Shader.DrawQuad(); - // Render spherical triangulation - Shader.Dismiss(); - GL.ActiveTexture(TextureUnit.Texture0); - GL.BindTexture(TextureTarget.Texture2D, 0); - GL.Disable(EnableCap.DepthTest); - GL.Begin(BeginMode.Triangles); - foreach (Triangle<int> tri in this._Triangulation.Triangles) - { - Triangle<Vector> vectri = this._Triangulation.Dereference(tri); - GL.Normal3(Triangle.Normal(vectri)); - GL.Color4(this._VertexColors[tri.A]); - GL.Vertex3(vectri.A * RadiusGround); - GL.Color4(this._VertexColors[tri.B]); - GL.Vertex3(vectri.B * RadiusGround); - GL.Color4(this._VertexColors[tri.C]); - GL.Vertex3(vectri.C * RadiusGround); - } - GL.End(); - this.Title = this._Height.ToString(); this.SwapBuffers(); } /// <summary> /// Renderable to produce a cubemap for the planet. /// </summary> private struct _CubemapRenderable : IRenderable { public void Render() { GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) { Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this.Window._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this.Window._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); GL.Color4(this.Window._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); } GL.End(); } public Window Window; } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; + if (this.Keyboard[Key.Z]) this._SunAngle += updatetime; + if (this.Keyboard[Key.X]) this._SunAngle -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } public const double RadiusGround = 6360.0; private PrecomputedAtmosphere _Atmosphere; + private Texture _Earth; private Texture _Cubemap; private Shader _CubemapUnroll; private Shader _Planet; private Color[] _VertexColors; private SphericalTriangulation _Triangulation; + private double _SunAngle; private double _Height; private double _XRot; private double _ZRot; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index 40d5495..50ffac6 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,114 +1,119 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjectionInverse; -uniform mat4 ViewInverse; +uniform float NearDistance; +uniform float FarDistance; +uniform samplerCube CubeMap; +uniform sampler2D Map; -const vec3 SunColor = vec3(30.0); -const vec3 SeaColor = vec3(0.0, 0.0, 0.2); -const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); +const vec3 SunColor = vec3(20.0); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; vec4 trans = ProjectionInverse * gl_Vertex; Ray = (trans / trans.w).xyz - EyePosition; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _IRRADIANCE_UV_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #define _IRRADIANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Irradiance.glsl" #include "Precompute/Inscatter.glsl" vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); vec4 is = max(inscatter(mu, nu, r, mus), 0.0); result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { float mus = dot(n, sol); vec3 direct = transmittance(Rg, mus) * max(mus, 0.0) * SunColor / Pi; vec3 irr = irradiance(Rg, mus); vec3 full = direct + irr; - return full * SeaColor; + vec3 color = textureCube(CubeMap, n); + color = texture2D(Map, vec2(atan(n.y, n.x), acos(n.z)) * vec2(0.5, 1.0) / Pi + vec2(0.5, 0.0)); + + return full * color; } vec3 HDR(vec3 L) { L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); + gl_FragDepth = 1.0; } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); } #endif \ No newline at end of file diff --git a/Resources/Textures/Earth.png b/Resources/Textures/Earth.png new file mode 100644 index 0000000..fe6ebfd Binary files /dev/null and b/Resources/Textures/Earth.png differ diff --git a/Resources/Textures/Earth.tif b/Resources/Textures/Earth.tif new file mode 100644 index 0000000..67bedc4 Binary files /dev/null and b/Resources/Textures/Earth.tif differ
dzamkov/Alunite-old
554bc780d584ee21ba77a78f1b3cc10359a0ae52
Coordinate space fixfix
diff --git a/Alunite/Shader.cs b/Alunite/Shader.cs index 511982c..e62f3ac 100644 --- a/Alunite/Shader.cs +++ b/Alunite/Shader.cs @@ -1,415 +1,415 @@ using System.Collections.Generic; using System; using System.IO; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Represents a shader in graphics memory. /// </summary> public struct Shader { /// <summary> /// Sets the shader to be used for subsequent render operations. /// </summary> public void Call() { GL.UseProgram(this.Program); } /// <summary> /// Sets a uniform variable. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, Vector Value) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform3(loc, (Vector3)Value); } /// <summary> /// Sets a uniform matrix. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, ref Matrix4 Matrix) { - GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), true, ref Matrix); + GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), false, ref Matrix); } /// <summary> /// Sets a uniform texture. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, TextureUnit Unit) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform1(loc, (int)Unit - (int)TextureUnit.Texture0); } /// <summary> /// Sets a uniform integer. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, int Value) { GL.Uniform1(GL.GetUniformLocation(this.Program, Name), Value); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. /// </summary> public void Draw2DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height) { GL.FramebufferTexture2D(Framebuffer, Attachment, TextureTarget.Texture2D, Texture, 0); GL.Viewport(0, 0, Width, Height); this.DrawFull(); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. The "Layer" uniform is set /// in the shader to indicate depth. /// </summary> public void Draw3DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height, int Depth) { this.Call(); int luniform = GL.GetUniformLocation(this.Program, "Layer"); for (int t = 0; t < Depth; t++) { GL.FramebufferTexture3D(Framebuffer, Attachment, TextureTarget.Texture3D, Texture, 0, t); GL.Viewport(0, 0, Width, Height); GL.Uniform1(luniform, t); DrawQuad(); } } /// <summary> /// Runs the fragment shader on all pixels on the current viewport. Transformation matrices must be set to identy for this to work correctly. /// </summary> public void DrawFull() { this.Call(); DrawQuad(); } /// <summary> /// Sets the rendering mode to default (removing all shaders). /// </summary> public static void Dismiss() { GL.UseProgram(0); } /// <summary> /// Draws a shape that includes the entire viewport. /// </summary> public static void DrawQuad() { GL.Begin(BeginMode.Quads); GL.Vertex2(-1.0, -1.0); GL.Vertex2(+1.0, -1.0); GL.Vertex2(+1.0, +1.0); GL.Vertex2(-1.0, +1.0); GL.End(); } /// <summary> /// Loads a shader program from a vertex and fragment shader in GLSL format. /// </summary> public static Shader Load(Alunite.Path Vertex, Alunite.Path Fragment) { Shader shade = new Shader(); int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(vshade, Path.ReadText(Vertex)); GL.ShaderSource(fshade, Path.ReadText(Fragment)); GL.CompileShader(vshade); GL.CompileShader(fshade); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Loads a shader from a single, defining _VERTEX_ for vertex shaders and _FRAGMENT_ for fragment shaders. /// </summary> public static Shader Load(Alunite.Path File) { return Load(File, new Dictionary<string, string>()); } /// <summary> /// More advanced shader loading function that will dynamically replace constants in the specified files. /// </summary> public static Shader Load(Alunite.Path File, Dictionary<string, string> Constants) { return Load(File, new PrecompilerInput() { Constants = Constants, LoadedFiles = new Dictionary<string, string[]>() }); } /// <summary> /// Loads a shader from the specified file using the specified input. /// </summary> public static Shader Load(Alunite.Path File, PrecompilerInput Input) { int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); StringBuilder vshadesource = new StringBuilder(); StringBuilder fshadesource = new StringBuilder(); PrecompilerInput vpce = Input.Copy(); PrecompilerInput fpce = Input.Copy(); vpce.Define("_VERTEX_", "1"); fpce.Define("_FRAGMENT_", "1"); BuildSource(File, vpce, vshadesource); GL.ShaderSource(vshade, vshadesource.ToString()); GL.CompileShader(vshade); vshadesource = null; BuildSource(File, fpce, fshadesource); GL.ShaderSource(fshade, fshadesource.ToString()); GL.CompileShader(fshade); fshadesource = null; Shader shade = new Shader(); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Creates a new precompiler input set. /// </summary> public static PrecompilerInput CreatePrecompilerInput() { return new PrecompilerInput() { Constants = new Dictionary<string, string>(), LoadedFiles = new Dictionary<string, string[]>() }; } /// <summary> /// Input to the precompiler. /// </summary> public struct PrecompilerInput { public PrecompilerInput(Path File) { this.Constants = new Dictionary<string, string>(); this.LoadedFiles = new Dictionary<string, string[]>(); } /// <summary> /// Gets the file at the specified path. /// </summary> public string[] GetFile(Path Path) { string[] lines; if (!this.LoadedFiles.TryGetValue(Path.PathString, out lines)) { this.LoadedFiles[Path.PathString] = lines = File.ReadAllLines(Path.PathString); } return lines; } /// <summary> /// Creates a copy of this precompiler input with its own precompiler constants. /// </summary> public PrecompilerInput Copy() { return new PrecompilerInput() { LoadedFiles = this.LoadedFiles, Constants = new Dictionary<string, string>(this.Constants) }; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant, string Value) { this.Constants[Constant] = Value; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant) { this.Constants[Constant] = "1"; } /// <summary> /// Undefines a constant. /// </summary> public void Undefine(string Constant) { this.Constants.Remove(Constant); } /// <summary> /// Constants defined for the precompiler. /// </summary> public Dictionary<string, string> Constants; /// <summary> /// The files loaded for the precompiler. /// </summary> public Dictionary<string, string[]> LoadedFiles; } /// <summary> /// Precompiles the source code defined by the lines with the specified constants defined. Outputs the precompiled source /// to the given stringbuilder. /// </summary> public static void BuildSource(Path File, PrecompilerInput Input, StringBuilder Output) { string[] lines = Input.GetFile(File); _ProcessBlock(((IEnumerable<string>)lines).GetEnumerator(), File, Input, Output, true); } /// <summary> /// Processes an ifdef/else/endif block where Interpret denotes the success of the if statement. Returns true if exited on an endif or false /// if exited on an else. /// </summary> private static bool _ProcessBlock(IEnumerator<string> LineEnumerator, Path File, PrecompilerInput Input, StringBuilder Output, bool Interpret) { while (LineEnumerator.MoveNext()) { string line = LineEnumerator.Current; // Does this line contain a directive? if (line.Length > 0) { if (line[0] == '#') { string[] lineparts = line.Split(' '); if (lineparts[0] == "#ifdef") { if (Interpret) { bool contains = Input.Constants.ContainsKey(lineparts[1]); if (!_ProcessBlock(LineEnumerator, File, Input, Output, contains)) { _ProcessBlock(LineEnumerator, File, Input, Output, !contains); } } else { if (!_ProcessBlock(LineEnumerator, File, Input, Output, false)) { _ProcessBlock(LineEnumerator, File, Input, Output, false); } } continue; } if (lineparts[0] == "#include") { if (Interpret) { string filepath = lineparts[1].Substring(1, lineparts[1].Length - 2); BuildSource(File.Parent.Lookup(filepath), Input, Output); } continue; } if (lineparts[0] == "#else") { return false; } if (lineparts[0] == "#endif") { return true; } if (Interpret) { if (lineparts[0] == "#define") { if (lineparts.Length > 2) { Input.Define(lineparts[1], lineparts[2]); } else { Input.Define(lineparts[1]); } continue; } if (lineparts[0] == "#undef") { Input.Undefine(lineparts[1]); continue; } Output.AppendLine(line); } } else { if (Interpret) { // Replace constants Dictionary<int, KeyValuePair<int, string>> matches = new Dictionary<int, KeyValuePair<int, string>>(); foreach (KeyValuePair<string, string> constant in Input.Constants) { int ind = line.IndexOf(constant.Key); while (ind >= 0) { int size = constant.Key.Length; KeyValuePair<int, string> lastmatch; if (matches.TryGetValue(ind, out lastmatch)) { if (lastmatch.Key < size) { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } } else { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } ind = line.IndexOf(constant.Key, ind + 1); } } if (matches.Count > 0) { int c = 0; var orderedmatches = new List<KeyValuePair<int, KeyValuePair<int, string>>>(matches); Sort.InPlace<KeyValuePair<int, KeyValuePair<int, string>>>((a, b) => a.Key > b.Key, orderedmatches); foreach (KeyValuePair<int, KeyValuePair<int, string>> match in orderedmatches) { Output.Append(line.Substring(c, match.Key - c)); Output.Append(match.Value.Value); c = match.Key + match.Value.Key; } Output.AppendLine(line.Substring(c)); } else { Output.AppendLine(line); } } } } } return true; } /// <summary> /// Index of the program of the shader. /// </summary> public int Program; } } \ No newline at end of file diff --git a/Alunite/Window.cs b/Alunite/Window.cs index c61a8f0..e3ee40f 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,179 +1,177 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.On; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; // Initial triangulation this._Triangulation = SphericalTriangulation.CreateIcosahedron(); // Assign random colors for testing Random r = new Random(101); this._VertexColors = new Color[this._Triangulation.Vertices.Count]; for (int t = 0; t < this._VertexColors.Length; t++) { this._VertexColors[t] = Color.RGB(r.NextDouble(), r.NextDouble(), r.NextDouble()); } // Create a cubemap this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); // A shader to test the cubemap with this._CubemapUnroll = Shader.Load(shaders["UnrollCubemap.glsl"]); // Planet Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); AtmosphereOptions ao = AtmosphereOptions.DefaultEarth; ao.RadiusGround = (float)RadiusGround; AtmosphereQualityOptions aqo = AtmosphereQualityOptions.Default; this._Atmosphere = Atmosphere.Generate(ao, aqo, pci, shaders); Atmosphere.DefineConstants(ao, aqo, pci); this._Planet = Shader.Load(shaders["Atmosphere"]["Planet.glsl"], pci); this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 1.0f, 20000.0f); - Matrix4 iproj = Matrix4.Invert(proj); Matrix4 view = Matrix4.LookAt( (Vector3)eyepos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); + Matrix4 total = view * proj; + Matrix4 itotal = Matrix4.Invert(total); + + GL.MatrixMode(MatrixMode.Projection); + GL.LoadMatrix(ref total); // Planet GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadIdentity(); this._Planet.Call(); this._Atmosphere.Setup(this._Planet); this._Planet.SetUniform("EyePosition", eyepos); this._Planet.SetUniform("SunDirection", new Vector(1.0, 0.0, 0.0)); - this._Planet.SetUniform("ProjInverse", ref proj); - this._Planet.SetUniform("ViewInverse", ref view); + this._Planet.SetUniform("ProjectionInverse", ref itotal); Shader.DrawQuad(); // Render spherical triangulation Shader.Dismiss(); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, 0); GL.Disable(EnableCap.DepthTest); - GL.MatrixMode(MatrixMode.Projection); - GL.LoadMatrix(ref proj); - GL.MultMatrix(ref view); GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this._Triangulation.Triangles) { Triangle<Vector> vectri = this._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); GL.Color4(this._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); } GL.End(); this.Title = this._Height.ToString(); this.SwapBuffers(); } /// <summary> /// Renderable to produce a cubemap for the planet. /// </summary> private struct _CubemapRenderable : IRenderable { public void Render() { GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) { Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this.Window._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this.Window._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); GL.Color4(this.Window._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); } GL.End(); } public Window Window; } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } public const double RadiusGround = 6360.0; private PrecomputedAtmosphere _Atmosphere; private Texture _Cubemap; private Shader _CubemapUnroll; private Shader _Planet; private Color[] _VertexColors; private SphericalTriangulation _Triangulation; private double _Height; private double _XRot; private double _ZRot; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index bd15638..40d5495 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,114 +1,114 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; -uniform mat4 ProjInverse; +uniform mat4 ProjectionInverse; uniform mat4 ViewInverse; const vec3 SunColor = vec3(30.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; -varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; - Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; + vec4 trans = ProjectionInverse * gl_Vertex; + Ray = (trans / trans.w).xyz - EyePosition; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _IRRADIANCE_UV_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #define _IRRADIANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Irradiance.glsl" #include "Precompute/Inscatter.glsl" vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); vec4 is = max(inscatter(mu, nu, r, mus), 0.0); result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { float mus = dot(n, sol); vec3 direct = transmittance(Rg, mus) * max(mus, 0.0) * SunColor / Pi; vec3 irr = irradiance(Rg, mus); vec3 full = direct + irr; return full * SeaColor; } vec3 HDR(vec3 L) { L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); } #endif \ No newline at end of file
dzamkov/Alunite-old
272a5c5c78ea37bfab04dc73427abc291a1610fb
Another bugfix (although it certainly doesn't look like it)
diff --git a/Alunite/Atmosphere.cs b/Alunite/Atmosphere.cs index fed2ac6..460fd66 100644 --- a/Alunite/Atmosphere.cs +++ b/Alunite/Atmosphere.cs @@ -1,348 +1,348 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Arguments defining a spherical atmosphere. /// </summary> public struct AtmosphereOptions { /// <summary> /// Distance from the center of the planet to ground level. /// </summary> public float RadiusGround; /// <summary> /// Distance from the center of the planet to the highest point where atmosphere is computed. /// </summary> public float RadiusBound; /// <summary> /// A proportion between 0.0 and 1.0 indicating how much light is reflected from the ground. /// </summary> public float AverageGroundReflectance; /// <summary> /// Average height above ground level of all rayleigh particles (fine, distort color). /// </summary> public float RayleighAverageHeight; /// <summary> /// Average height above ground level of all mie particles (coarse, white, absorb light). /// </summary> public float MieAverageHeight; /// <summary> /// Atmosphere options for an Earthlike planet. /// </summary> public static readonly AtmosphereOptions DefaultEarth = new AtmosphereOptions() { AverageGroundReflectance = 0.1f, RadiusGround = 6360.0f, RadiusBound = 6420.0f, RayleighAverageHeight = 8.0f, MieAverageHeight = 1.2f, }; } /// <summary> /// Arguments specifing the quality an atmosphere should be generated with. /// </summary> public struct AtmosphereQualityOptions { /// <summary> /// Amount of scattering orders to compute. This increases time to generate textures and atmosphere quality without /// requiring more runtime resources. /// </summary> public int MultipleScatteringOrder; /// <summary> /// Resolution in height of textures involving the atmosphere. /// </summary> public int AtmosphereResR; /// <summary> /// Resolution in view angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMu; /// <summary> /// Resolution in sun angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMuS; /// <summary> /// Resolution in sun/view angle offset of textures involving the atmosphere. /// </summary> public int AtmosphereResNu; /// <summary> /// Resolution of sun angle in the irradiance texture. /// </summary> public int IrradianceResMu; /// <summary> /// Resolution of height in the irradiance texture. /// </summary> public int IrradianceResR; /// <summary> /// Resolution of view angle in the transmittance texture. /// </summary> public int TransmittanceResMu; /// <summary> /// Resolution of height in the transmittance texture. /// </summary> public int TransmittanceResR; /// <summary> /// Some okay options that generate reasonable results. /// </summary> public static readonly AtmosphereQualityOptions Default = new AtmosphereQualityOptions() { MultipleScatteringOrder = 2, AtmosphereResMu = 128, AtmosphereResR = 32, AtmosphereResMuS = 32, AtmosphereResNu = 8, IrradianceResMu = 64, IrradianceResR = 16, TransmittanceResR = 64, TransmittanceResMu = 256, }; } /// <summary> /// Information about the precomputed parts of the affects of light on a spherical atmosphere. /// </summary> public struct PrecomputedAtmosphere { /// <summary> /// 3D (simulating a 4D) texture describing the amount of light given off by the atmosphere. /// </summary> public Texture Inscatter; /// <summary> /// 2D texture describing the amount of light given to a point on ground, by the atmosphere. /// </summary> public Texture Irradiance; /// <summary> /// 2D texture describing how light is filtered while traveling through the atmosphere. /// </summary> public Texture Transmittance; /// <summary> /// Sets up the textures for a currently active shader that involves the precomputed atmosphere. /// </summary> public void Setup(Shader Shader) { this.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture0); this.Irradiance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); this.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); Shader.SetUniform("Inscatter", TextureUnit.Texture0); Shader.SetUniform("Irradiance", TextureUnit.Texture1); Shader.SetUniform("Transmittance", TextureUnit.Texture2); } } /// <summary> /// Contains functions for manipulating and displaying spherical atmospheres. /// </summary> public static class Atmosphere { /// <summary> /// Defines precompiler constants for atmosphere shaders based on options. /// </summary> public static void DefineConstants( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInput) { PrecompilerInput.Define("ATMOSPHERE_RES_R", QualityOptions.AtmosphereResR.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU", QualityOptions.AtmosphereResMu.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU_S", QualityOptions.AtmosphereResMuS.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_NU", QualityOptions.AtmosphereResNu.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_R", QualityOptions.IrradianceResR.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_MU", QualityOptions.IrradianceResMu.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_R", QualityOptions.TransmittanceResR.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_MU", QualityOptions.TransmittanceResMu.ToString()); PrecompilerInput.Define("RADIUS_GROUND", Options.RadiusGround.ToString()); PrecompilerInput.Define("RADIUS_BOUND", Options.RadiusBound.ToString()); PrecompilerInput.Define("AVERAGE_GROUND_REFLECTANCE", Options.AverageGroundReflectance.ToString()); PrecompilerInput.Define("RAYLEIGH_AVERAGE_HEIGHT", Options.RayleighAverageHeight.ToString()); PrecompilerInput.Define("MIE_AVERAGE_HEIGHT", Options.MieAverageHeight.ToString()); } /// <summary> /// Creates a precomputed atmosphere using shaders and the graphics card. /// </summary> public static PrecomputedAtmosphere Generate( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInitial, Path ShaderPath) { PrecomputedAtmosphere pa = new PrecomputedAtmosphere(); Shader.PrecompilerInput pci = PrecompilerInitial.Copy(); DefineConstants(Options, QualityOptions, pci); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); irradiancedeltapci.Define("DELTA"); Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); Shader.PrecompilerInput irradiancepci = pci.Copy(); Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); inscatterdeltapci.Define("DELTA"); Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); Shader.PrecompilerInput inscatterpci = pci.Copy(); Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); Shader.PrecompilerInput pointscatterpci = pci.Copy(); Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); // Initialize textures int transwidth = QualityOptions.TransmittanceResMu; int transheight = QualityOptions.TransmittanceResR; int irrwidth = QualityOptions.IrradianceResMu; int irrheight = QualityOptions.IrradianceResR; int atwidth = QualityOptions.AtmosphereResMuS * QualityOptions.AtmosphereResNu; int atheight = QualityOptions.AtmosphereResMu; int atdepth = QualityOptions.AtmosphereResR; pa.Transmittance = Texture.Initialize2D(transwidth, transheight, Texture.RGB16Float); pa.Irradiance = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); pa.Inscatter = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); Texture insdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); Texture ptsdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); - pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); + pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); pa.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Transmittance.ID, transwidth, transheight); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitialdelta.Call(); - irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture1); + irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). inscatterinitial.Call(); - inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture1); + inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); // Initialize irradiance to zero (ground lighting caused by atmosphere). irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Copy inscatter to delta inscatter, combining rayleigh and mie parts. inscatterinitialdelta.Call(); inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); for (int t = 2; t <= QualityOptions.MultipleScatteringOrder; t++) { // Generate point scattering information // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. pointscatter.Call(); pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, ptsdelta.ID, atwidth, atheight, atdepth); // Compute new irradiance delta using current inscatter delta. irradiancedelta.Call(); irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Compute new inscatter delta using pointscatter data. inscatterdelta.Call(); - inscatterdelta.SetUniform("Transmittance", TextureUnit.Texture1); + inscatterdelta.SetUniform("Transmittance", TextureUnit.Texture0); inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); GL.Enable(EnableCap.Blend); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); // Add irradiance delta to irradiance. irradiance.Call(); irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Add inscatter delta to inscatter. inscatter.Call(); inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); GL.Disable(EnableCap.Blend); } insdelta.Delete(); irrdelta.Delete(); ptsdelta.Delete(); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); GL.Finish(); GL.DeleteFramebuffers(1, ref fbo); return pa; } } } \ No newline at end of file diff --git a/Alunite/Window.cs b/Alunite/Window.cs index 9b01df2..c61a8f0 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,175 +1,179 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.On; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; // Initial triangulation this._Triangulation = SphericalTriangulation.CreateIcosahedron(); // Assign random colors for testing Random r = new Random(101); this._VertexColors = new Color[this._Triangulation.Vertices.Count]; for (int t = 0; t < this._VertexColors.Length; t++) { this._VertexColors[t] = Color.RGB(r.NextDouble(), r.NextDouble(), r.NextDouble()); } // Create a cubemap this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); // A shader to test the cubemap with this._CubemapUnroll = Shader.Load(shaders["UnrollCubemap.glsl"]); // Planet Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); AtmosphereOptions ao = AtmosphereOptions.DefaultEarth; ao.RadiusGround = (float)RadiusGround; AtmosphereQualityOptions aqo = AtmosphereQualityOptions.Default; this._Atmosphere = Atmosphere.Generate(ao, aqo, pci, shaders); Atmosphere.DefineConstants(ao, aqo, pci); this._Planet = Shader.Load(shaders["Atmosphere"]["Planet.glsl"], pci); this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 1.0f, 20000.0f); Matrix4 iproj = Matrix4.Invert(proj); Matrix4 view = Matrix4.LookAt( (Vector3)eyepos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); - // Unroll that cubemap + // Planet GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); this._Planet.Call(); this._Atmosphere.Setup(this._Planet); this._Planet.SetUniform("EyePosition", eyepos); this._Planet.SetUniform("SunDirection", new Vector(1.0, 0.0, 0.0)); - this._Planet.SetUniform("ProjInverse", ref iproj); + this._Planet.SetUniform("ProjInverse", ref proj); this._Planet.SetUniform("ViewInverse", ref view); Shader.DrawQuad(); // Render spherical triangulation Shader.Dismiss(); + GL.ActiveTexture(TextureUnit.Texture0); + GL.BindTexture(TextureTarget.Texture2D, 0); GL.Disable(EnableCap.DepthTest); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref proj); GL.MultMatrix(ref view); GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this._Triangulation.Triangles) { Triangle<Vector> vectri = this._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this._VertexColors[tri.A]); - GL.Vertex3(vectri.A * RadiusGround * 0.5); + GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this._VertexColors[tri.B]); - GL.Vertex3(vectri.B * RadiusGround * 0.5); + GL.Vertex3(vectri.B * RadiusGround); GL.Color4(this._VertexColors[tri.C]); - GL.Vertex3(vectri.C * RadiusGround * 0.5); + GL.Vertex3(vectri.C * RadiusGround); } GL.End(); - + + this.Title = this._Height.ToString(); + this.SwapBuffers(); } /// <summary> /// Renderable to produce a cubemap for the planet. /// </summary> private struct _CubemapRenderable : IRenderable { public void Render() { GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) { Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this.Window._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this.Window._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); GL.Color4(this.Window._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); } GL.End(); } public Window Window; } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } public const double RadiusGround = 6360.0; private PrecomputedAtmosphere _Atmosphere; private Texture _Cubemap; private Shader _CubemapUnroll; private Shader _Planet; private Color[] _VertexColors; private SphericalTriangulation _Triangulation; private double _Height; private double _XRot; private double _ZRot; } } \ No newline at end of file
dzamkov/Alunite-old
a23e386fae97384161901ff287139ca295aec8ef
A couple bugfixes
diff --git a/Alunite/Atmosphere.cs b/Alunite/Atmosphere.cs index b48b6db..fed2ac6 100644 --- a/Alunite/Atmosphere.cs +++ b/Alunite/Atmosphere.cs @@ -1,341 +1,348 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Arguments defining a spherical atmosphere. /// </summary> public struct AtmosphereOptions { /// <summary> /// Distance from the center of the planet to ground level. /// </summary> public float RadiusGround; /// <summary> /// Distance from the center of the planet to the highest point where atmosphere is computed. /// </summary> public float RadiusBound; /// <summary> /// A proportion between 0.0 and 1.0 indicating how much light is reflected from the ground. /// </summary> public float AverageGroundReflectance; /// <summary> /// Average height above ground level of all rayleigh particles (fine, distort color). /// </summary> public float RayleighAverageHeight; /// <summary> /// Average height above ground level of all mie particles (coarse, white, absorb light). /// </summary> public float MieAverageHeight; /// <summary> /// Atmosphere options for an Earthlike planet. /// </summary> public static readonly AtmosphereOptions DefaultEarth = new AtmosphereOptions() { AverageGroundReflectance = 0.1f, RadiusGround = 6360.0f, RadiusBound = 6420.0f, RayleighAverageHeight = 8.0f, MieAverageHeight = 1.2f, }; } /// <summary> /// Arguments specifing the quality an atmosphere should be generated with. /// </summary> public struct AtmosphereQualityOptions { /// <summary> /// Amount of scattering orders to compute. This increases time to generate textures and atmosphere quality without /// requiring more runtime resources. /// </summary> public int MultipleScatteringOrder; /// <summary> /// Resolution in height of textures involving the atmosphere. /// </summary> public int AtmosphereResR; /// <summary> /// Resolution in view angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMu; /// <summary> /// Resolution in sun angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMuS; /// <summary> /// Resolution in sun/view angle offset of textures involving the atmosphere. /// </summary> public int AtmosphereResNu; /// <summary> /// Resolution of sun angle in the irradiance texture. /// </summary> public int IrradianceResMu; /// <summary> /// Resolution of height in the irradiance texture. /// </summary> public int IrradianceResR; /// <summary> /// Resolution of view angle in the transmittance texture. /// </summary> public int TransmittanceResMu; /// <summary> /// Resolution of height in the transmittance texture. /// </summary> public int TransmittanceResR; /// <summary> /// Some okay options that generate reasonable results. /// </summary> public static readonly AtmosphereQualityOptions Default = new AtmosphereQualityOptions() { - MultipleScatteringOrder = 4, + MultipleScatteringOrder = 2, AtmosphereResMu = 128, AtmosphereResR = 32, AtmosphereResMuS = 32, AtmosphereResNu = 8, IrradianceResMu = 64, IrradianceResR = 16, TransmittanceResR = 64, TransmittanceResMu = 256, }; } /// <summary> /// Information about the precomputed parts of the affects of light on a spherical atmosphere. /// </summary> public struct PrecomputedAtmosphere { /// <summary> /// 3D (simulating a 4D) texture describing the amount of light given off by the atmosphere. /// </summary> public Texture Inscatter; /// <summary> /// 2D texture describing the amount of light given to a point on ground, by the atmosphere. /// </summary> public Texture Irradiance; /// <summary> /// 2D texture describing how light is filtered while traveling through the atmosphere. /// </summary> public Texture Transmittance; /// <summary> /// Sets up the textures for a currently active shader that involves the precomputed atmosphere. /// </summary> public void Setup(Shader Shader) { this.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture0); this.Irradiance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); this.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); Shader.SetUniform("Inscatter", TextureUnit.Texture0); Shader.SetUniform("Irradiance", TextureUnit.Texture1); Shader.SetUniform("Transmittance", TextureUnit.Texture2); } } /// <summary> /// Contains functions for manipulating and displaying spherical atmospheres. /// </summary> public static class Atmosphere { /// <summary> /// Defines precompiler constants for atmosphere shaders based on options. /// </summary> public static void DefineConstants( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInput) { PrecompilerInput.Define("ATMOSPHERE_RES_R", QualityOptions.AtmosphereResR.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU", QualityOptions.AtmosphereResMu.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU_S", QualityOptions.AtmosphereResMuS.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_NU", QualityOptions.AtmosphereResNu.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_R", QualityOptions.IrradianceResR.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_MU", QualityOptions.IrradianceResMu.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_R", QualityOptions.TransmittanceResR.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_MU", QualityOptions.TransmittanceResMu.ToString()); PrecompilerInput.Define("RADIUS_GROUND", Options.RadiusGround.ToString()); PrecompilerInput.Define("RADIUS_BOUND", Options.RadiusBound.ToString()); PrecompilerInput.Define("AVERAGE_GROUND_REFLECTANCE", Options.AverageGroundReflectance.ToString()); PrecompilerInput.Define("RAYLEIGH_AVERAGE_HEIGHT", Options.RayleighAverageHeight.ToString()); PrecompilerInput.Define("MIE_AVERAGE_HEIGHT", Options.MieAverageHeight.ToString()); } /// <summary> /// Creates a precomputed atmosphere using shaders and the graphics card. /// </summary> public static PrecomputedAtmosphere Generate( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInitial, Path ShaderPath) { PrecomputedAtmosphere pa = new PrecomputedAtmosphere(); Shader.PrecompilerInput pci = PrecompilerInitial.Copy(); DefineConstants(Options, QualityOptions, pci); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; - // Atmospheric scattering precompution - uint fbo; - GL.GenFramebuffers(1, out fbo); - GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); - GL.ReadBuffer(ReadBufferMode.ColorAttachment0); - GL.DrawBuffer(DrawBufferMode.ColorAttachment0); - // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); irradiancedeltapci.Define("DELTA"); Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); Shader.PrecompilerInput irradiancepci = pci.Copy(); Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); inscatterdeltapci.Define("DELTA"); Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); Shader.PrecompilerInput inscatterpci = pci.Copy(); Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); Shader.PrecompilerInput pointscatterpci = pci.Copy(); Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); // Initialize textures int transwidth = QualityOptions.TransmittanceResMu; int transheight = QualityOptions.TransmittanceResR; int irrwidth = QualityOptions.IrradianceResMu; int irrheight = QualityOptions.IrradianceResR; int atwidth = QualityOptions.AtmosphereResMuS * QualityOptions.AtmosphereResNu; int atheight = QualityOptions.AtmosphereResMu; int atdepth = QualityOptions.AtmosphereResR; pa.Transmittance = Texture.Initialize2D(transwidth, transheight, Texture.RGB16Float); pa.Irradiance = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); pa.Inscatter = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); Texture insdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); Texture ptsdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); - pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); + pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); pa.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); + + uint fbo; + GL.GenFramebuffers(1, out fbo); + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); + GL.ReadBuffer(ReadBufferMode.ColorAttachment0); + GL.DrawBuffer(DrawBufferMode.ColorAttachment0); + // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Transmittance.ID, transwidth, transheight); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitialdelta.Call(); - irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); + irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture1); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). inscatterinitial.Call(); - inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); + inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture1); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); // Initialize irradiance to zero (ground lighting caused by atmosphere). irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Copy inscatter to delta inscatter, combining rayleigh and mie parts. inscatterinitialdelta.Call(); inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); for (int t = 2; t <= QualityOptions.MultipleScatteringOrder; t++) { // Generate point scattering information // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. pointscatter.Call(); pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, ptsdelta.ID, atwidth, atheight, atdepth); // Compute new irradiance delta using current inscatter delta. irradiancedelta.Call(); irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Compute new inscatter delta using pointscatter data. inscatterdelta.Call(); + inscatterdelta.SetUniform("Transmittance", TextureUnit.Texture1); inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); GL.Enable(EnableCap.Blend); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); // Add irradiance delta to irradiance. irradiance.Call(); irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Add inscatter delta to inscatter. inscatter.Call(); inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); GL.Disable(EnableCap.Blend); } + insdelta.Delete(); + irrdelta.Delete(); + ptsdelta.Delete(); + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); + GL.Finish(); + GL.DeleteFramebuffers(1, ref fbo); return pa; } } } \ No newline at end of file diff --git a/Alunite/Shader.cs b/Alunite/Shader.cs index 5aceef6..511982c 100644 --- a/Alunite/Shader.cs +++ b/Alunite/Shader.cs @@ -1,415 +1,415 @@ using System.Collections.Generic; using System; using System.IO; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Represents a shader in graphics memory. /// </summary> public struct Shader { /// <summary> /// Sets the shader to be used for subsequent render operations. /// </summary> public void Call() { GL.UseProgram(this.Program); } /// <summary> /// Sets a uniform variable. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, Vector Value) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform3(loc, (Vector3)Value); } /// <summary> /// Sets a uniform matrix. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, ref Matrix4 Matrix) { GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), true, ref Matrix); } /// <summary> /// Sets a uniform texture. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, TextureUnit Unit) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform1(loc, (int)Unit - (int)TextureUnit.Texture0); } /// <summary> /// Sets a uniform integer. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, int Value) { GL.Uniform1(GL.GetUniformLocation(this.Program, Name), Value); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. /// </summary> public void Draw2DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height) { GL.FramebufferTexture2D(Framebuffer, Attachment, TextureTarget.Texture2D, Texture, 0); GL.Viewport(0, 0, Width, Height); this.DrawFull(); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. The "Layer" uniform is set /// in the shader to indicate depth. /// </summary> public void Draw3DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height, int Depth) { this.Call(); int luniform = GL.GetUniformLocation(this.Program, "Layer"); for (int t = 0; t < Depth; t++) { GL.FramebufferTexture3D(Framebuffer, Attachment, TextureTarget.Texture3D, Texture, 0, t); GL.Viewport(0, 0, Width, Height); GL.Uniform1(luniform, t); DrawQuad(); } } /// <summary> /// Runs the fragment shader on all pixels on the current viewport. Transformation matrices must be set to identy for this to work correctly. /// </summary> public void DrawFull() { this.Call(); DrawQuad(); } /// <summary> /// Sets the rendering mode to default (removing all shaders). /// </summary> public static void Dismiss() { GL.UseProgram(0); } /// <summary> /// Draws a shape that includes the entire viewport. /// </summary> public static void DrawQuad() { - GL.Begin(BeginMode.TriangleStrip); + GL.Begin(BeginMode.Quads); GL.Vertex2(-1.0, -1.0); GL.Vertex2(+1.0, -1.0); - GL.Vertex2(-1.0, +1.0); GL.Vertex2(+1.0, +1.0); + GL.Vertex2(-1.0, +1.0); GL.End(); } /// <summary> /// Loads a shader program from a vertex and fragment shader in GLSL format. /// </summary> public static Shader Load(Alunite.Path Vertex, Alunite.Path Fragment) { Shader shade = new Shader(); int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(vshade, Path.ReadText(Vertex)); GL.ShaderSource(fshade, Path.ReadText(Fragment)); GL.CompileShader(vshade); GL.CompileShader(fshade); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Loads a shader from a single, defining _VERTEX_ for vertex shaders and _FRAGMENT_ for fragment shaders. /// </summary> public static Shader Load(Alunite.Path File) { return Load(File, new Dictionary<string, string>()); } /// <summary> /// More advanced shader loading function that will dynamically replace constants in the specified files. /// </summary> public static Shader Load(Alunite.Path File, Dictionary<string, string> Constants) { return Load(File, new PrecompilerInput() { Constants = Constants, LoadedFiles = new Dictionary<string, string[]>() }); } /// <summary> /// Loads a shader from the specified file using the specified input. /// </summary> public static Shader Load(Alunite.Path File, PrecompilerInput Input) { int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); StringBuilder vshadesource = new StringBuilder(); StringBuilder fshadesource = new StringBuilder(); PrecompilerInput vpce = Input.Copy(); PrecompilerInput fpce = Input.Copy(); vpce.Define("_VERTEX_", "1"); fpce.Define("_FRAGMENT_", "1"); BuildSource(File, vpce, vshadesource); GL.ShaderSource(vshade, vshadesource.ToString()); GL.CompileShader(vshade); vshadesource = null; BuildSource(File, fpce, fshadesource); GL.ShaderSource(fshade, fshadesource.ToString()); GL.CompileShader(fshade); fshadesource = null; Shader shade = new Shader(); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Creates a new precompiler input set. /// </summary> public static PrecompilerInput CreatePrecompilerInput() { return new PrecompilerInput() { Constants = new Dictionary<string, string>(), LoadedFiles = new Dictionary<string, string[]>() }; } /// <summary> /// Input to the precompiler. /// </summary> public struct PrecompilerInput { public PrecompilerInput(Path File) { this.Constants = new Dictionary<string, string>(); this.LoadedFiles = new Dictionary<string, string[]>(); } /// <summary> /// Gets the file at the specified path. /// </summary> public string[] GetFile(Path Path) { string[] lines; if (!this.LoadedFiles.TryGetValue(Path.PathString, out lines)) { this.LoadedFiles[Path.PathString] = lines = File.ReadAllLines(Path.PathString); } return lines; } /// <summary> /// Creates a copy of this precompiler input with its own precompiler constants. /// </summary> public PrecompilerInput Copy() { return new PrecompilerInput() { LoadedFiles = this.LoadedFiles, Constants = new Dictionary<string, string>(this.Constants) }; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant, string Value) { this.Constants[Constant] = Value; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant) { this.Constants[Constant] = "1"; } /// <summary> /// Undefines a constant. /// </summary> public void Undefine(string Constant) { this.Constants.Remove(Constant); } /// <summary> /// Constants defined for the precompiler. /// </summary> public Dictionary<string, string> Constants; /// <summary> /// The files loaded for the precompiler. /// </summary> public Dictionary<string, string[]> LoadedFiles; } /// <summary> /// Precompiles the source code defined by the lines with the specified constants defined. Outputs the precompiled source /// to the given stringbuilder. /// </summary> public static void BuildSource(Path File, PrecompilerInput Input, StringBuilder Output) { string[] lines = Input.GetFile(File); _ProcessBlock(((IEnumerable<string>)lines).GetEnumerator(), File, Input, Output, true); } /// <summary> /// Processes an ifdef/else/endif block where Interpret denotes the success of the if statement. Returns true if exited on an endif or false /// if exited on an else. /// </summary> private static bool _ProcessBlock(IEnumerator<string> LineEnumerator, Path File, PrecompilerInput Input, StringBuilder Output, bool Interpret) { while (LineEnumerator.MoveNext()) { string line = LineEnumerator.Current; // Does this line contain a directive? if (line.Length > 0) { if (line[0] == '#') { string[] lineparts = line.Split(' '); if (lineparts[0] == "#ifdef") { if (Interpret) { bool contains = Input.Constants.ContainsKey(lineparts[1]); if (!_ProcessBlock(LineEnumerator, File, Input, Output, contains)) { _ProcessBlock(LineEnumerator, File, Input, Output, !contains); } } else { if (!_ProcessBlock(LineEnumerator, File, Input, Output, false)) { _ProcessBlock(LineEnumerator, File, Input, Output, false); } } continue; } if (lineparts[0] == "#include") { if (Interpret) { string filepath = lineparts[1].Substring(1, lineparts[1].Length - 2); BuildSource(File.Parent.Lookup(filepath), Input, Output); } continue; } if (lineparts[0] == "#else") { return false; } if (lineparts[0] == "#endif") { return true; } if (Interpret) { if (lineparts[0] == "#define") { if (lineparts.Length > 2) { Input.Define(lineparts[1], lineparts[2]); } else { Input.Define(lineparts[1]); } continue; } if (lineparts[0] == "#undef") { Input.Undefine(lineparts[1]); continue; } Output.AppendLine(line); } } else { if (Interpret) { // Replace constants Dictionary<int, KeyValuePair<int, string>> matches = new Dictionary<int, KeyValuePair<int, string>>(); foreach (KeyValuePair<string, string> constant in Input.Constants) { int ind = line.IndexOf(constant.Key); while (ind >= 0) { int size = constant.Key.Length; KeyValuePair<int, string> lastmatch; if (matches.TryGetValue(ind, out lastmatch)) { if (lastmatch.Key < size) { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } } else { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } ind = line.IndexOf(constant.Key, ind + 1); } } if (matches.Count > 0) { int c = 0; var orderedmatches = new List<KeyValuePair<int, KeyValuePair<int, string>>>(matches); Sort.InPlace<KeyValuePair<int, KeyValuePair<int, string>>>((a, b) => a.Key > b.Key, orderedmatches); foreach (KeyValuePair<int, KeyValuePair<int, string>> match in orderedmatches) { Output.Append(line.Substring(c, match.Key - c)); Output.Append(match.Value.Value); c = match.Key + match.Value.Key; } Output.AppendLine(line.Substring(c)); } else { Output.AppendLine(line); } } } } } return true; } /// <summary> /// Index of the program of the shader. /// </summary> public int Program; } } \ No newline at end of file diff --git a/Alunite/Texture.cs b/Alunite/Texture.cs index 8412d29..40fdf20 100644 --- a/Alunite/Texture.cs +++ b/Alunite/Texture.cs @@ -1,208 +1,216 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using OpenTK; using OpenTK.Graphics.OpenGL; using Path = Alunite.Path; namespace Alunite { /// <summary> /// Represents a textured(of any dimension) loaded into graphics memory. /// </summary> public class Texture { public Texture(Bitmap Source) { GL.GenBuffers(1, out this._TextureID); GL.BindTexture(TextureTarget.Texture2D, this._TextureID); BitmapData bd = Source.LockBits( new Rectangle(0, 0, Source.Width, Source.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bd.Width, bd.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bd.Scan0); this.SetInterpolation2D(TextureMinFilter.Linear, TextureMagFilter.Linear); this.SetWrap2D(TextureWrapMode.Repeat, TextureWrapMode.Repeat); Source.UnlockBits(bd); } public Texture(int TextureID) { this._TextureID = (uint)TextureID; } /// <summary> /// Gets the OpenGL id for the texture. /// </summary> public uint ID { get { return this._TextureID; } } /// <summary> /// Sets this as the current texture. /// </summary> public void Bind(TextureTarget TextureTarget) { GL.BindTexture(TextureTarget, this._TextureID); } /// <summary> /// Sets this as the current 2d texture. /// </summary> public void Bind2D() { this.Bind(TextureTarget.Texture2D); } /// <summary> /// Describes the format of a texture. /// </summary> public struct Format { public Format( PixelInternalFormat PixelInternalFormat, OpenTK.Graphics.OpenGL.PixelFormat PixelFormat, PixelType PixelType) { this.PixelInternalFormat = PixelInternalFormat; this.PixelFormat = PixelFormat; this.PixelType = PixelType; } public PixelInternalFormat PixelInternalFormat; public OpenTK.Graphics.OpenGL.PixelFormat PixelFormat; public PixelType PixelType; } public static readonly Format RGB16Float = new Format( PixelInternalFormat.Rgb16f, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float); public static readonly Format RGBA16Float = new Format( PixelInternalFormat.Rgba16f, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float); /// <summary> /// Creates a generic 2d texture with no data. /// </summary> public static Texture Initialize2D(int Width, int Height, Format Format) { int tex = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, tex); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); GL.TexImage2D(TextureTarget.Texture2D, 0, Format.PixelInternalFormat, Width, Height, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); return new Texture(tex); } /// <summary> /// Creates a generic 3d texture with no data. /// </summary> public static Texture Initialize3D(int Width, int Height, int Depth, Format Format) { int tex = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture3D, tex); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); GL.TexImage3D(TextureTarget.Texture3D, 0, Format.PixelInternalFormat, Width, Height, Depth, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); return new Texture(tex); } /// <summary> /// Creates a generic cubemap with no data. /// </summary> public static Texture InitializeCubemap(int Length, Format Format) { int tex = GL.GenTexture(); GL.BindTexture(TextureTarget.TextureCubeMap, tex); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); for (int t = 0; t < 6; t++) { GL.TexImage2D((TextureTarget)((int)TextureTarget.TextureCubeMapPositiveX + t), 0, Format.PixelInternalFormat, Length, Length, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); } return new Texture(tex); } /// <summary> /// Sets the interpolation used by the texture. /// </summary> public void SetInterpolation2D(TextureMinFilter Min, TextureMagFilter Mag) { this.Bind2D(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)Min); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)Mag); } /// <summary> /// Sets this texture to a texture unit for uses such as shaders. /// </summary> public void SetUnit(TextureTarget Target, TextureUnit Unit) { GL.ActiveTexture(Unit); this.Bind(Target); } /// <summary> /// Sets the type of wrapping used by the texture. /// </summary> public void SetWrap2D(TextureWrapMode S, TextureWrapMode T) { this.Bind2D(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)S); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)T); } /// <summary> /// Loads a texture from the specified file. /// </summary> public static Texture Load(Path File) { using (FileStream fs = System.IO.File.OpenRead(File)) { return Load(fs); } } /// <summary> /// Loads a texture from the specified stream. /// </summary> public static Texture Load(Stream Stream) { return new Texture(new Bitmap(Stream)); } + /// <summary> + /// Deletes the texture, making it unusable. + /// </summary> + public void Delete() + { + GL.DeleteTexture(this._TextureID); + } + private uint _TextureID; } } \ No newline at end of file diff --git a/Alunite/Window.cs b/Alunite/Window.cs index 5bbd9a2..9b01df2 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,162 +1,175 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.On; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; // Initial triangulation this._Triangulation = SphericalTriangulation.CreateIcosahedron(); // Assign random colors for testing Random r = new Random(101); this._VertexColors = new Color[this._Triangulation.Vertices.Count]; for (int t = 0; t < this._VertexColors.Length; t++) { this._VertexColors[t] = Color.RGB(r.NextDouble(), r.NextDouble(), r.NextDouble()); } // Create a cubemap this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); // A shader to test the cubemap with this._CubemapUnroll = Shader.Load(shaders["UnrollCubemap.glsl"]); + // Planet + Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); + AtmosphereOptions ao = AtmosphereOptions.DefaultEarth; ao.RadiusGround = (float)RadiusGround; + AtmosphereQualityOptions aqo = AtmosphereQualityOptions.Default; + this._Atmosphere = Atmosphere.Generate(ao, aqo, pci, shaders); + Atmosphere.DefineConstants(ao, aqo, pci); + this._Planet = Shader.Load(shaders["Atmosphere"]["Planet.glsl"], pci); + this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 1.0f, 20000.0f); + Matrix4 iproj = Matrix4.Invert(proj); Matrix4 view = Matrix4.LookAt( (Vector3)eyepos, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); // Unroll that cubemap GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); - this._Cubemap.SetUnit(TextureTarget.TextureCubeMap, TextureUnit.Texture0); - this._CubemapUnroll.Call(); - this._CubemapUnroll.SetUniform("Cubemap", TextureUnit.Texture0); - this._CubemapUnroll.DrawFull(); + this._Planet.Call(); + this._Atmosphere.Setup(this._Planet); + this._Planet.SetUniform("EyePosition", eyepos); + this._Planet.SetUniform("SunDirection", new Vector(1.0, 0.0, 0.0)); + this._Planet.SetUniform("ProjInverse", ref iproj); + this._Planet.SetUniform("ViewInverse", ref view); + Shader.DrawQuad(); - /* // Render spherical triangulation + Shader.Dismiss(); + GL.Disable(EnableCap.DepthTest); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref proj); GL.MultMatrix(ref view); GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this._Triangulation.Triangles) { Triangle<Vector> vectri = this._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this._VertexColors[tri.A]); - GL.Vertex3(vectri.A * RadiusGround); + GL.Vertex3(vectri.A * RadiusGround * 0.5); GL.Color4(this._VertexColors[tri.B]); - GL.Vertex3(vectri.B * RadiusGround); + GL.Vertex3(vectri.B * RadiusGround * 0.5); GL.Color4(this._VertexColors[tri.C]); - GL.Vertex3(vectri.C * RadiusGround); + GL.Vertex3(vectri.C * RadiusGround * 0.5); } - GL.End();*/ - - System.Threading.Thread.Sleep(1); + GL.End(); this.SwapBuffers(); } /// <summary> /// Renderable to produce a cubemap for the planet. /// </summary> private struct _CubemapRenderable : IRenderable { public void Render() { GL.Begin(BeginMode.Triangles); foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) { Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); GL.Normal3(Triangle.Normal(vectri)); GL.Color4(this.Window._VertexColors[tri.A]); GL.Vertex3(vectri.A * RadiusGround); GL.Color4(this.Window._VertexColors[tri.C]); GL.Vertex3(vectri.C * RadiusGround); GL.Color4(this.Window._VertexColors[tri.B]); GL.Vertex3(vectri.B * RadiusGround); } GL.End(); } public Window Window; } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } public const double RadiusGround = 6360.0; + private PrecomputedAtmosphere _Atmosphere; private Texture _Cubemap; private Shader _CubemapUnroll; + private Shader _Planet; private Color[] _VertexColors; private SphericalTriangulation _Triangulation; private double _Height; private double _XRot; private double _ZRot; } } \ No newline at end of file
dzamkov/Alunite-old
0ac81ed4a5fa91cc377b0450165c85b537a60361
Cubemap generation
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index d36a2fe..6026705 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,80 +1,82 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{50B33331-0290-4981-9E8B-8A26901D2B53}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Array.cs" /> <Compile Include="Atmosphere.cs" /> <Compile Include="Color.cs" /> <Compile Include="CSG.cs" /> + <Compile Include="Cubemap.cs" /> <Compile Include="Diagram.cs" /> <Compile Include="Planet.cs" /> <Compile Include="Point.cs" /> <Compile Include="Polygon.cs" /> <Compile Include="Polyhedron.cs" /> <Compile Include="Program.cs" /> + <Compile Include="Renderable.cs" /> <Compile Include="Segment.cs" /> <Compile Include="Grid.cs" /> <Compile Include="Model.cs" /> <Compile Include="Path.cs" /> <Compile Include="Primitive.cs" /> <Compile Include="Set.cs" /> <Compile Include="Shader.cs" /> <Compile Include="Sort.cs" /> <Compile Include="TetrahedralMesh.cs" /> <Compile Include="Tetrahedron.cs" /> <Compile Include="Texture.cs" /> <Compile Include="Triangle.cs" /> <Compile Include="Tuple.cs" /> <Compile Include="VBO.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Window.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> <Reference Include="System.Windows.Forms" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Atmosphere.cs b/Alunite/Atmosphere.cs index 28a02f0..b48b6db 100644 --- a/Alunite/Atmosphere.cs +++ b/Alunite/Atmosphere.cs @@ -1,341 +1,341 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> - /// Arguments defining a spherical atmosphere (affected by one sun). + /// Arguments defining a spherical atmosphere. /// </summary> public struct AtmosphereOptions { /// <summary> /// Distance from the center of the planet to ground level. /// </summary> public float RadiusGround; /// <summary> /// Distance from the center of the planet to the highest point where atmosphere is computed. /// </summary> public float RadiusBound; /// <summary> /// A proportion between 0.0 and 1.0 indicating how much light is reflected from the ground. /// </summary> public float AverageGroundReflectance; /// <summary> /// Average height above ground level of all rayleigh particles (fine, distort color). /// </summary> public float RayleighAverageHeight; /// <summary> /// Average height above ground level of all mie particles (coarse, white, absorb light). /// </summary> public float MieAverageHeight; /// <summary> /// Atmosphere options for an Earthlike planet. /// </summary> public static readonly AtmosphereOptions DefaultEarth = new AtmosphereOptions() { AverageGroundReflectance = 0.1f, RadiusGround = 6360.0f, RadiusBound = 6420.0f, RayleighAverageHeight = 8.0f, MieAverageHeight = 1.2f, }; } /// <summary> /// Arguments specifing the quality an atmosphere should be generated with. /// </summary> public struct AtmosphereQualityOptions { /// <summary> /// Amount of scattering orders to compute. This increases time to generate textures and atmosphere quality without /// requiring more runtime resources. /// </summary> public int MultipleScatteringOrder; /// <summary> /// Resolution in height of textures involving the atmosphere. /// </summary> public int AtmosphereResR; /// <summary> /// Resolution in view angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMu; /// <summary> /// Resolution in sun angle of textures involving the atmosphere. /// </summary> public int AtmosphereResMuS; /// <summary> /// Resolution in sun/view angle offset of textures involving the atmosphere. /// </summary> public int AtmosphereResNu; /// <summary> /// Resolution of sun angle in the irradiance texture. /// </summary> public int IrradianceResMu; /// <summary> /// Resolution of height in the irradiance texture. /// </summary> public int IrradianceResR; /// <summary> /// Resolution of view angle in the transmittance texture. /// </summary> public int TransmittanceResMu; /// <summary> /// Resolution of height in the transmittance texture. /// </summary> public int TransmittanceResR; /// <summary> /// Some okay options that generate reasonable results. /// </summary> public static readonly AtmosphereQualityOptions Default = new AtmosphereQualityOptions() { MultipleScatteringOrder = 4, AtmosphereResMu = 128, AtmosphereResR = 32, AtmosphereResMuS = 32, AtmosphereResNu = 8, IrradianceResMu = 64, IrradianceResR = 16, TransmittanceResR = 64, TransmittanceResMu = 256, }; } /// <summary> - /// Information about the precomputed parts of a spherical atmosphere. + /// Information about the precomputed parts of the affects of light on a spherical atmosphere. /// </summary> public struct PrecomputedAtmosphere { /// <summary> /// 3D (simulating a 4D) texture describing the amount of light given off by the atmosphere. /// </summary> public Texture Inscatter; /// <summary> /// 2D texture describing the amount of light given to a point on ground, by the atmosphere. /// </summary> public Texture Irradiance; /// <summary> /// 2D texture describing how light is filtered while traveling through the atmosphere. /// </summary> public Texture Transmittance; /// <summary> /// Sets up the textures for a currently active shader that involves the precomputed atmosphere. /// </summary> public void Setup(Shader Shader) { this.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture0); this.Irradiance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); this.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); Shader.SetUniform("Inscatter", TextureUnit.Texture0); Shader.SetUniform("Irradiance", TextureUnit.Texture1); Shader.SetUniform("Transmittance", TextureUnit.Texture2); } } /// <summary> /// Contains functions for manipulating and displaying spherical atmospheres. /// </summary> public static class Atmosphere { /// <summary> /// Defines precompiler constants for atmosphere shaders based on options. /// </summary> public static void DefineConstants( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInput) { PrecompilerInput.Define("ATMOSPHERE_RES_R", QualityOptions.AtmosphereResR.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU", QualityOptions.AtmosphereResMu.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_MU_S", QualityOptions.AtmosphereResMuS.ToString()); PrecompilerInput.Define("ATMOSPHERE_RES_NU", QualityOptions.AtmosphereResNu.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_R", QualityOptions.IrradianceResR.ToString()); PrecompilerInput.Define("IRRADIANCE_RES_MU", QualityOptions.IrradianceResMu.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_R", QualityOptions.TransmittanceResR.ToString()); PrecompilerInput.Define("TRANSMITTANCE_RES_MU", QualityOptions.TransmittanceResMu.ToString()); PrecompilerInput.Define("RADIUS_GROUND", Options.RadiusGround.ToString()); PrecompilerInput.Define("RADIUS_BOUND", Options.RadiusBound.ToString()); PrecompilerInput.Define("AVERAGE_GROUND_REFLECTANCE", Options.AverageGroundReflectance.ToString()); PrecompilerInput.Define("RAYLEIGH_AVERAGE_HEIGHT", Options.RayleighAverageHeight.ToString()); PrecompilerInput.Define("MIE_AVERAGE_HEIGHT", Options.MieAverageHeight.ToString()); } /// <summary> /// Creates a precomputed atmosphere using shaders and the graphics card. /// </summary> public static PrecomputedAtmosphere Generate( AtmosphereOptions Options, AtmosphereQualityOptions QualityOptions, Shader.PrecompilerInput PrecompilerInitial, Path ShaderPath) { PrecomputedAtmosphere pa = new PrecomputedAtmosphere(); Shader.PrecompilerInput pci = PrecompilerInitial.Copy(); DefineConstants(Options, QualityOptions, pci); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); irradiancedeltapci.Define("DELTA"); Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); Shader.PrecompilerInput irradiancepci = pci.Copy(); Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); inscatterdeltapci.Define("DELTA"); Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); Shader.PrecompilerInput inscatterpci = pci.Copy(); Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); Shader.PrecompilerInput pointscatterpci = pci.Copy(); Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); // Initialize textures int transwidth = QualityOptions.TransmittanceResMu; int transheight = QualityOptions.TransmittanceResR; int irrwidth = QualityOptions.IrradianceResMu; int irrheight = QualityOptions.IrradianceResR; int atwidth = QualityOptions.AtmosphereResMuS * QualityOptions.AtmosphereResNu; int atheight = QualityOptions.AtmosphereResMu; int atdepth = QualityOptions.AtmosphereResR; pa.Transmittance = Texture.Initialize2D(transwidth, transheight, Texture.RGB16Float); pa.Irradiance = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); pa.Inscatter = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); Texture insdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); Texture ptsdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); pa.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Transmittance.ID, transwidth, transheight); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitialdelta.Call(); irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). inscatterinitial.Call(); inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); // Initialize irradiance to zero (ground lighting caused by atmosphere). irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Copy inscatter to delta inscatter, combining rayleigh and mie parts. inscatterinitialdelta.Call(); inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); for (int t = 2; t <= QualityOptions.MultipleScatteringOrder; t++) { // Generate point scattering information // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. pointscatter.Call(); pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, ptsdelta.ID, atwidth, atheight, atdepth); // Compute new irradiance delta using current inscatter delta. irradiancedelta.Call(); irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, irrwidth, irrheight); // Compute new inscatter delta using pointscatter data. inscatterdelta.Call(); inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, atwidth, atheight, atdepth); GL.Enable(EnableCap.Blend); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); // Add irradiance delta to irradiance. irradiance.Call(); irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Irradiance.ID, irrwidth, irrheight); // Add inscatter delta to inscatter. inscatter.Call(); inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, pa.Inscatter.ID, atwidth, atheight, atdepth); GL.Disable(EnableCap.Blend); } GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); return pa; } } } \ No newline at end of file diff --git a/Alunite/Cubemap.cs b/Alunite/Cubemap.cs new file mode 100644 index 0000000..cbdc778 --- /dev/null +++ b/Alunite/Cubemap.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; + +using OpenTK; +using OpenTK.Graphics; +using OpenTK.Graphics.OpenGL; + +namespace Alunite +{ + /// <summary> + /// Cubemap related functions. + /// </summary> + public static class Cubemap + { + /// <summary> + /// Creates a cubemap from a scene. + /// </summary> + public static Texture Generate<Renderable>(Texture.Format Format, int Length, Renderable Scene, double MinDistance, double MaxDistance) + where Renderable : IRenderable + { + Texture cubemap = Texture.InitializeCubemap(Length, Format); + uint fbo; + GL.GenFramebuffers(1, out fbo); + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); + GL.ReadBuffer(ReadBufferMode.ColorAttachment0); + GL.DrawBuffer(DrawBufferMode.ColorAttachment0); + Draw<Renderable>(cubemap, FramebufferTarget.FramebufferExt, Length, Scene, MinDistance, MaxDistance); + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); + GL.DeleteFramebuffers(1, ref fbo); + return cubemap; + } + + /// <summary> + /// Draws a scene to the cubemap texture using the specified framebuffer. + /// </summary> + public static void Draw<Renderable>(Texture Cubemap, FramebufferTarget Framebuffer, int Length, Renderable Scene, double MinDistance, double MaxDistance) + where Renderable : IRenderable + { + Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView((float)(Math.PI / 2.0), 1.0f, (float)MinDistance, (float)MaxDistance); + + GL.MatrixMode(MatrixMode.Projection); + GL.LoadMatrix(ref proj); + + Matrix4 view; + + GL.Viewport(0, 0, Length, Length); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(-1.0f, 0.0f, 0.0f), + new Vector3(0.0f, -1.0f, 0.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapNegativeX, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(1.0f, 0.0f, 0.0f), + new Vector3(0.0f, -1.0f, 0.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapPositiveX, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(0.0f, -1.0f, 0.0f), + new Vector3(0.0f, 0.0f, -1.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapNegativeY, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(0.0f, 1.0f, 0.0f), + new Vector3(0.0f, 0.0f, 1.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapPositiveY, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(0.0f, 0.0f, -1.0f), + new Vector3(0.0f, -1.0f, 0.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapNegativeZ, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + + GL.PushMatrix(); + view = Matrix4.LookAt( + new Vector3(0.0f, 0.0f, 0.0f), + new Vector3(0.0f, 0.0f, 1.0f), + new Vector3(0.0f, -1.0f, 0.0f)); + GL.MultMatrix(ref view); + GL.FramebufferTexture2D(Framebuffer, FramebufferAttachment.ColorAttachment0Ext, TextureTarget.TextureCubeMapPositiveZ, Cubemap.ID, 0); + Scene.Render(); + GL.PopMatrix(); + } + } +} \ No newline at end of file diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 9e8afea..8203a75 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,227 +1,139 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> - /// Really big thing. + /// A triangulation over a unit sphere. /// </summary> - public class Planet + public struct SphericalTriangulation { - public Planet() - { - this._Triangles = new HashSet<Triangle<int>>(); - this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); - - // Initialize with an icosahedron. - Primitive icosa = Primitive.Icosahedron; - this._Vertices = new List<Vector>(icosa.Vertices); - foreach (Triangle<int> tri in icosa.Triangles) - { - this._AddTriangle(tri); - } - - this._Subdivide(); - this._Subdivide(); - this._Subdivide(); - - } - - /// <summary> - /// Creates a diagram for the current state of the planet. - /// </summary> - public Diagram CreateDiagram() - { - Diagram dia = new Diagram(this._Vertices); - foreach (Triangle<int> tri in this._Triangles) - { - dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); - } - return dia; - } /// <summary> - /// Creates a vertex buffer representation of the current state of the planet. + /// Adds a triangle to the triangulation. /// </summary> - public VBO<NormalVertex, NormalVertex.Model> CreateVBO() + public void AddTriangle(Triangle<int> Triangle) { - NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; - for (int t = 0; t < verts.Length; t++) - { - // Lol, position and normal are the same. - Vector pos = this._Vertices[t]; - verts[t].Position = pos; - verts[t].Normal = pos; - } - return new VBO<NormalVertex, NormalVertex.Model>( - NormalVertex.Model.Singleton, - verts, verts.Length, - this._Triangles, this._Triangles.Count); - } - - public void Load(Alunite.Path ShaderPath) - { - Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); - - AtmosphereOptions options = AtmosphereOptions.DefaultEarth; - AtmosphereQualityOptions qualityoptions = AtmosphereQualityOptions.Default; - - this._Atmosphere = Atmosphere.Generate(options, qualityoptions, pci, ShaderPath); - - Path atmosphere = ShaderPath["Atmosphere"]; - Path precompute = atmosphere["Precompute"]; - Atmosphere.DefineConstants(options, qualityoptions, pci); - this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci); - } - - - public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) - { - Proj.Invert(); - //View.Invert(); - GL.LoadIdentity(); - - this._Atmosphere.Setup(this._PlanetShader); - this._PlanetShader.SetUniform("ProjInverse", ref Proj); - this._PlanetShader.SetUniform("ViewInverse", ref View); - this._PlanetShader.SetUniform("EyePosition", EyePosition); - this._PlanetShader.SetUniform("SunDirection", SunDirection); - this._PlanetShader.DrawFull(); - } - - /// <summary> - /// Adds a triangle to the planet. - /// </summary> - private void _AddTriangle(Triangle<int> Triangle) - { - this._Triangles.Add(Triangle); + this.Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { - this._SegmentTriangles[seg] = Triangle; + this.SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( - this._Vertices[Triangle.A], - this._Vertices[Triangle.B], - this._Vertices[Triangle.C]); + this.Vertices[Triangle.A], + this.Vertices[Triangle.B], + this.Vertices[Triangle.C]); } /// <summary> - /// Splits the triangle at the specified point while maintaining the delaunay property. + /// Inserts a point in the triangulation and splits triangles to maintain the delaunay property. /// </summary> - private void _SplitTriangle(Triangle<int> Triangle, Vector Point) + public void SplitTriangle(Triangle<int> Triangle, Vector NewPosition, int NewPoint) { - int npoint = this._Vertices.Count; - this._Vertices.Add(Point); - - this._Triangles.Remove(Triangle); + this.Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); - Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; + Triangle<int> othertri = Alunite.Triangle.Align(this.SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point - double npointangle = Vector.Dot(othercircumcenter, Point); + double npointangle = Vector.Dot(othercircumcenter, NewPosition); if (npointangle > othercircumangle) { - this._Triangles.Remove(othertri); + this.Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { - this._AddTriangle(new Triangle<int>(npoint, seg)); + this.AddTriangle(new Triangle<int>(NewPoint, seg)); } } /// <summary> - /// Splits a triangle at its circumcenter while maintaining the delaunay property. + /// Splits a triangle at its center, maintaining the delaunay property. /// </summary> - private void _SplitTriangle(Triangle<int> Triangle) + public void SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); - Vector circumcenter = Alunite.Triangle.Normal(vectri); - this._SplitTriangle(Triangle, circumcenter); + Vector npos = Alunite.Triangle.Normal(vectri); + this.SplitTriangle(Triangle, npos, this.AddVertex(npos)); } /// <summary> - /// Subdivides the entire planet, quadrupling the amount of triangles. + /// Adds a vertex (with length 1) to the spherical triangulation. /// </summary> - private void _Subdivide() + public int AddVertex(Vector Position) { - var oldtris = this._Triangles; - var oldsegs = this._SegmentTriangles; - this._Triangles = new HashSet<Triangle<int>>(); - this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); + int ind = this.Vertices.Count; + this.Vertices.Add(Position); + return ind; + } - Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); + /// <summary> + /// Creates a spherical triangulation based off an icosahedron. + /// </summary> + public static SphericalTriangulation CreateIcosahedron() + { + SphericalTriangulation st = new SphericalTriangulation(); + Primitive icosa = Primitive.Icosahedron; - foreach (Triangle<int> tri in oldtris) + st.Vertices = new List<Vector>(icosa.Vertices.Length); + st.Vertices.AddRange(icosa.Vertices); + st.SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); + st.Triangles = new HashSet<Triangle<int>>(); + + foreach (Triangle<int> tri in icosa.Triangles) { - int[] midpoints = new int[3]; - Segment<int>[] segs = tri.Segments; - for (int t = 0; t < 3; t++) - { - Segment<int> seg = segs[t]; - int midpoint; - if (!newsegs.TryGetValue(seg, out midpoint)) - { - midpoint = this._Vertices.Count; - this._Vertices.Add( - Vector.Normalize( - Segment.Midpoint( - new Segment<Vector>( - this._Vertices[seg.A], - this._Vertices[seg.B])))); - newsegs.Add(seg.Flip, midpoint); - } - else - { - newsegs.Remove(seg); - } - midpoints[t] = midpoint; - } - this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); - this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); - this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); - this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); + st.AddTriangle(tri); } + + return st; } - private PrecomputedAtmosphere _Atmosphere; - private Shader _PlanetShader; + /// <summary> + /// Triangles that are part of the sphere. + /// </summary> + public HashSet<Triangle<int>> Triangles; + + /// <summary> + /// A mapping of segments to the triangles that produce them. + /// </summary> + public Dictionary<Segment<int>, Triangle<int>> SegmentTriangles; - private List<Vector> _Vertices; - private HashSet<Triangle<int>> _Triangles; - private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; + /// <summary> + /// An ordered list of vertices that make up the sphere. + /// </summary> + public List<Vector> Vertices; } } \ No newline at end of file diff --git a/Alunite/Program.cs b/Alunite/Program.cs index b9ecaf6..bbe8b6a 100644 --- a/Alunite/Program.cs +++ b/Alunite/Program.cs @@ -1,19 +1,18 @@ using System; using System.Collections.Generic; namespace Alunite { public static class Program { /// <summary> /// Program main entry point. /// </summary> public static void Main(string[] Args) { - Planet planet = new Planet(); - Window win = new Window(planet); + Window win = new Window(); win.Run(); } } } \ No newline at end of file diff --git a/Alunite/Renderable.cs b/Alunite/Renderable.cs new file mode 100644 index 0000000..ac84926 --- /dev/null +++ b/Alunite/Renderable.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +namespace Alunite +{ + /// <summary> + /// A sequence of instructions to be execute on the current graphics context. + /// </summary> + public interface IRenderable + { + /// <summary> + /// Performs the instructions described by the renderable. + /// </summary> + void Render(); + } +} \ No newline at end of file diff --git a/Alunite/Shader.cs b/Alunite/Shader.cs index 1398312..5aceef6 100644 --- a/Alunite/Shader.cs +++ b/Alunite/Shader.cs @@ -1,415 +1,415 @@ using System.Collections.Generic; using System; using System.IO; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Represents a shader in graphics memory. /// </summary> public struct Shader { /// <summary> /// Sets the shader to be used for subsequent render operations. /// </summary> public void Call() { GL.UseProgram(this.Program); } /// <summary> /// Sets a uniform variable. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, Vector Value) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform3(loc, (Vector3)Value); } /// <summary> /// Sets a uniform matrix. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, ref Matrix4 Matrix) { GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), true, ref Matrix); } /// <summary> /// Sets a uniform texture. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, TextureUnit Unit) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform1(loc, (int)Unit - (int)TextureUnit.Texture0); } /// <summary> /// Sets a uniform integer. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, int Value) { GL.Uniform1(GL.GetUniformLocation(this.Program, Name), Value); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. /// </summary> public void Draw2DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height) { GL.FramebufferTexture2D(Framebuffer, Attachment, TextureTarget.Texture2D, Texture, 0); GL.Viewport(0, 0, Width, Height); this.DrawFull(); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. The "Layer" uniform is set /// in the shader to indicate depth. /// </summary> public void Draw3DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height, int Depth) { this.Call(); int luniform = GL.GetUniformLocation(this.Program, "Layer"); for (int t = 0; t < Depth; t++) { GL.FramebufferTexture3D(Framebuffer, Attachment, TextureTarget.Texture3D, Texture, 0, t); GL.Viewport(0, 0, Width, Height); GL.Uniform1(luniform, t); DrawQuad(); } } /// <summary> - /// Runs the fragment shader on all pixels on the current viewport. + /// Runs the fragment shader on all pixels on the current viewport. Transformation matrices must be set to identy for this to work correctly. /// </summary> public void DrawFull() { this.Call(); DrawQuad(); } /// <summary> /// Sets the rendering mode to default (removing all shaders). /// </summary> public static void Dismiss() { GL.UseProgram(0); } /// <summary> /// Draws a shape that includes the entire viewport. /// </summary> public static void DrawQuad() { GL.Begin(BeginMode.TriangleStrip); GL.Vertex2(-1.0, -1.0); GL.Vertex2(+1.0, -1.0); GL.Vertex2(-1.0, +1.0); GL.Vertex2(+1.0, +1.0); GL.End(); } /// <summary> /// Loads a shader program from a vertex and fragment shader in GLSL format. /// </summary> public static Shader Load(Alunite.Path Vertex, Alunite.Path Fragment) { Shader shade = new Shader(); int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(vshade, Path.ReadText(Vertex)); GL.ShaderSource(fshade, Path.ReadText(Fragment)); GL.CompileShader(vshade); GL.CompileShader(fshade); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Loads a shader from a single, defining _VERTEX_ for vertex shaders and _FRAGMENT_ for fragment shaders. /// </summary> public static Shader Load(Alunite.Path File) { return Load(File, new Dictionary<string, string>()); } /// <summary> /// More advanced shader loading function that will dynamically replace constants in the specified files. /// </summary> public static Shader Load(Alunite.Path File, Dictionary<string, string> Constants) { return Load(File, new PrecompilerInput() { Constants = Constants, LoadedFiles = new Dictionary<string, string[]>() }); } /// <summary> /// Loads a shader from the specified file using the specified input. /// </summary> public static Shader Load(Alunite.Path File, PrecompilerInput Input) { int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); StringBuilder vshadesource = new StringBuilder(); StringBuilder fshadesource = new StringBuilder(); PrecompilerInput vpce = Input.Copy(); PrecompilerInput fpce = Input.Copy(); vpce.Define("_VERTEX_", "1"); fpce.Define("_FRAGMENT_", "1"); BuildSource(File, vpce, vshadesource); GL.ShaderSource(vshade, vshadesource.ToString()); GL.CompileShader(vshade); vshadesource = null; BuildSource(File, fpce, fshadesource); GL.ShaderSource(fshade, fshadesource.ToString()); GL.CompileShader(fshade); fshadesource = null; Shader shade = new Shader(); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Creates a new precompiler input set. /// </summary> public static PrecompilerInput CreatePrecompilerInput() { return new PrecompilerInput() { Constants = new Dictionary<string, string>(), LoadedFiles = new Dictionary<string, string[]>() }; } /// <summary> /// Input to the precompiler. /// </summary> public struct PrecompilerInput { public PrecompilerInput(Path File) { this.Constants = new Dictionary<string, string>(); this.LoadedFiles = new Dictionary<string, string[]>(); } /// <summary> /// Gets the file at the specified path. /// </summary> public string[] GetFile(Path Path) { string[] lines; if (!this.LoadedFiles.TryGetValue(Path.PathString, out lines)) { this.LoadedFiles[Path.PathString] = lines = File.ReadAllLines(Path.PathString); } return lines; } /// <summary> /// Creates a copy of this precompiler input with its own precompiler constants. /// </summary> public PrecompilerInput Copy() { return new PrecompilerInput() { LoadedFiles = this.LoadedFiles, Constants = new Dictionary<string, string>(this.Constants) }; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant, string Value) { this.Constants[Constant] = Value; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant) { this.Constants[Constant] = "1"; } /// <summary> /// Undefines a constant. /// </summary> public void Undefine(string Constant) { this.Constants.Remove(Constant); } /// <summary> /// Constants defined for the precompiler. /// </summary> public Dictionary<string, string> Constants; /// <summary> /// The files loaded for the precompiler. /// </summary> public Dictionary<string, string[]> LoadedFiles; } /// <summary> /// Precompiles the source code defined by the lines with the specified constants defined. Outputs the precompiled source /// to the given stringbuilder. /// </summary> public static void BuildSource(Path File, PrecompilerInput Input, StringBuilder Output) { string[] lines = Input.GetFile(File); _ProcessBlock(((IEnumerable<string>)lines).GetEnumerator(), File, Input, Output, true); } /// <summary> /// Processes an ifdef/else/endif block where Interpret denotes the success of the if statement. Returns true if exited on an endif or false /// if exited on an else. /// </summary> private static bool _ProcessBlock(IEnumerator<string> LineEnumerator, Path File, PrecompilerInput Input, StringBuilder Output, bool Interpret) { while (LineEnumerator.MoveNext()) { string line = LineEnumerator.Current; // Does this line contain a directive? if (line.Length > 0) { if (line[0] == '#') { string[] lineparts = line.Split(' '); if (lineparts[0] == "#ifdef") { if (Interpret) { bool contains = Input.Constants.ContainsKey(lineparts[1]); if (!_ProcessBlock(LineEnumerator, File, Input, Output, contains)) { _ProcessBlock(LineEnumerator, File, Input, Output, !contains); } } else { if (!_ProcessBlock(LineEnumerator, File, Input, Output, false)) { _ProcessBlock(LineEnumerator, File, Input, Output, false); } } continue; } if (lineparts[0] == "#include") { if (Interpret) { string filepath = lineparts[1].Substring(1, lineparts[1].Length - 2); BuildSource(File.Parent.Lookup(filepath), Input, Output); } continue; } if (lineparts[0] == "#else") { return false; } if (lineparts[0] == "#endif") { return true; } if (Interpret) { if (lineparts[0] == "#define") { if (lineparts.Length > 2) { Input.Define(lineparts[1], lineparts[2]); } else { Input.Define(lineparts[1]); } continue; } if (lineparts[0] == "#undef") { Input.Undefine(lineparts[1]); continue; } Output.AppendLine(line); } } else { if (Interpret) { // Replace constants Dictionary<int, KeyValuePair<int, string>> matches = new Dictionary<int, KeyValuePair<int, string>>(); foreach (KeyValuePair<string, string> constant in Input.Constants) { int ind = line.IndexOf(constant.Key); while (ind >= 0) { int size = constant.Key.Length; KeyValuePair<int, string> lastmatch; if (matches.TryGetValue(ind, out lastmatch)) { if (lastmatch.Key < size) { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } } else { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } ind = line.IndexOf(constant.Key, ind + 1); } } if (matches.Count > 0) { int c = 0; var orderedmatches = new List<KeyValuePair<int, KeyValuePair<int, string>>>(matches); Sort.InPlace<KeyValuePair<int, KeyValuePair<int, string>>>((a, b) => a.Key > b.Key, orderedmatches); foreach (KeyValuePair<int, KeyValuePair<int, string>> match in orderedmatches) { Output.Append(line.Substring(c, match.Key - c)); Output.Append(match.Value.Value); c = match.Key + match.Value.Key; } Output.AppendLine(line.Substring(c)); } else { Output.AppendLine(line); } } } } } return true; } /// <summary> /// Index of the program of the shader. /// </summary> public int Program; } } \ No newline at end of file diff --git a/Alunite/Texture.cs b/Alunite/Texture.cs index 78c2945..8412d29 100644 --- a/Alunite/Texture.cs +++ b/Alunite/Texture.cs @@ -1,189 +1,208 @@ using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using OpenTK; using OpenTK.Graphics.OpenGL; using Path = Alunite.Path; namespace Alunite { /// <summary> /// Represents a textured(of any dimension) loaded into graphics memory. /// </summary> public class Texture { public Texture(Bitmap Source) { GL.GenBuffers(1, out this._TextureID); GL.BindTexture(TextureTarget.Texture2D, this._TextureID); BitmapData bd = Source.LockBits( new Rectangle(0, 0, Source.Width, Source.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bd.Width, bd.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bd.Scan0); this.SetInterpolation2D(TextureMinFilter.Linear, TextureMagFilter.Linear); this.SetWrap2D(TextureWrapMode.Repeat, TextureWrapMode.Repeat); Source.UnlockBits(bd); } public Texture(int TextureID) { this._TextureID = (uint)TextureID; } /// <summary> /// Gets the OpenGL id for the texture. /// </summary> public uint ID { get { return this._TextureID; } } /// <summary> /// Sets this as the current texture. /// </summary> public void Bind(TextureTarget TextureTarget) { GL.BindTexture(TextureTarget, this._TextureID); } /// <summary> /// Sets this as the current 2d texture. /// </summary> public void Bind2D() { this.Bind(TextureTarget.Texture2D); } /// <summary> /// Describes the format of a texture. /// </summary> public struct Format { public Format( PixelInternalFormat PixelInternalFormat, OpenTK.Graphics.OpenGL.PixelFormat PixelFormat, PixelType PixelType) { this.PixelInternalFormat = PixelInternalFormat; this.PixelFormat = PixelFormat; this.PixelType = PixelType; } public PixelInternalFormat PixelInternalFormat; public OpenTK.Graphics.OpenGL.PixelFormat PixelFormat; public PixelType PixelType; } public static readonly Format RGB16Float = new Format( PixelInternalFormat.Rgb16f, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float); public static readonly Format RGBA16Float = new Format( PixelInternalFormat.Rgba16f, OpenTK.Graphics.OpenGL.PixelFormat.Rgb, PixelType.Float); /// <summary> /// Creates a generic 2d texture with no data. /// </summary> public static Texture Initialize2D(int Width, int Height, Format Format) { int tex = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, tex); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); GL.TexImage2D(TextureTarget.Texture2D, 0, Format.PixelInternalFormat, Width, Height, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); return new Texture(tex); } /// <summary> /// Creates a generic 3d texture with no data. /// </summary> public static Texture Initialize3D(int Width, int Height, int Depth, Format Format) { int tex = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture3D, tex); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture3D, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); GL.TexImage3D(TextureTarget.Texture3D, 0, Format.PixelInternalFormat, Width, Height, Depth, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); return new Texture(tex); } + /// <summary> + /// Creates a generic cubemap with no data. + /// </summary> + public static Texture InitializeCubemap(int Length, Format Format) + { + int tex = GL.GenTexture(); + GL.BindTexture(TextureTarget.TextureCubeMap, tex); + GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); + GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); + GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); + GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); + GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge); + for (int t = 0; t < 6; t++) + { + GL.TexImage2D((TextureTarget)((int)TextureTarget.TextureCubeMapPositiveX + t), 0, Format.PixelInternalFormat, Length, Length, 0, Format.PixelFormat, Format.PixelType, IntPtr.Zero); + } + return new Texture(tex); + } + /// <summary> /// Sets the interpolation used by the texture. /// </summary> public void SetInterpolation2D(TextureMinFilter Min, TextureMagFilter Mag) { this.Bind2D(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)Min); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)Mag); } /// <summary> /// Sets this texture to a texture unit for uses such as shaders. /// </summary> public void SetUnit(TextureTarget Target, TextureUnit Unit) { GL.ActiveTexture(Unit); this.Bind(Target); } /// <summary> /// Sets the type of wrapping used by the texture. /// </summary> public void SetWrap2D(TextureWrapMode S, TextureWrapMode T) { this.Bind2D(); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)S); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)T); } /// <summary> /// Loads a texture from the specified file. /// </summary> public static Texture Load(Path File) { using (FileStream fs = System.IO.File.OpenRead(File)) { return Load(fs); } } /// <summary> /// Loads a texture from the specified stream. /// </summary> public static Texture Load(Stream Stream) { return new Texture(new Bitmap(Stream)); } private uint _TextureID; } } \ No newline at end of file diff --git a/Alunite/Window.cs b/Alunite/Window.cs index 1744edf..5bbd9a2 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,110 +1,162 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { - public Window(Planet Planet) + public Window() : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.On; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; - GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); - GL.Disable(EnableCap.Texture2D); + GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); - GL.Enable(EnableCap.Light0); - GL.Light(LightName.Light0, LightParameter.Position, new Vector4(1.0f, 1.0f, 1.0f, 0.0f)); - GL.Light(LightName.Light0, LightParameter.Diffuse, Color.RGB(0.6, 0.6, 0.6)); - GL.Light(LightName.Light0, LightParameter.Ambient, Color.RGB(0.1, 0.1, 0.1)); - - Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; - this._Planet = Planet; - this._Planet.Load(shaders); - this._Height = 20000.0; + // Initial triangulation + this._Triangulation = SphericalTriangulation.CreateIcosahedron(); + + // Assign random colors for testing + Random r = new Random(101); + this._VertexColors = new Color[this._Triangulation.Vertices.Count]; + for (int t = 0; t < this._VertexColors.Length; t++) + { + this._VertexColors[t] = Color.RGB(r.NextDouble(), r.NextDouble(), r.NextDouble()); + } + + // Create a cubemap + this._Cubemap = Cubemap.Generate(Texture.RGB16Float, 128, new _CubemapRenderable() { Window = this }, RadiusGround * 0.2f, RadiusGround * 1.2f); + + // A shader to test the cubemap with + this._CubemapUnroll = Shader.Load(shaders["UnrollCubemap.glsl"]); + + this._Height = RadiusGround * 3; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; - Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(2.2f, (float)this.Width / (float)this.Height, 0.1f, 10000.0f); + Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(1.2f, (float)this.Width / (float)this.Height, 1.0f, 20000.0f); Matrix4 view = Matrix4.LookAt( - new Vector3(), - -(Vector3)eyepos, + (Vector3)eyepos, + new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f)); - if (this._SunsetMode) + + // Unroll that cubemap + GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill); + GL.MatrixMode(MatrixMode.Projection); + GL.LoadIdentity(); + this._Cubemap.SetUnit(TextureTarget.TextureCubeMap, TextureUnit.Texture0); + this._CubemapUnroll.Call(); + this._CubemapUnroll.SetUniform("Cubemap", TextureUnit.Texture0); + this._CubemapUnroll.DrawFull(); + + /* + // Render spherical triangulation + GL.MatrixMode(MatrixMode.Projection); + GL.LoadMatrix(ref proj); + GL.MultMatrix(ref view); + GL.Begin(BeginMode.Triangles); + foreach (Triangle<int> tri in this._Triangulation.Triangles) { - double h = 6360 + this._Height / 20000.0; - view = Matrix4.LookAt( - new Vector3(0.0f, (float)h, 0.0f), - new Vector3(3.0f, (float)h + 0.5f, 0.0f), - new Vector3(0.0f, 1.0f, 0.0f)); - eyepos = new Vector(0.0, h, 0.0); + Triangle<Vector> vectri = this._Triangulation.Dereference(tri); + GL.Normal3(Triangle.Normal(vectri)); + GL.Color4(this._VertexColors[tri.A]); + GL.Vertex3(vectri.A * RadiusGround); + GL.Color4(this._VertexColors[tri.B]); + GL.Vertex3(vectri.B * RadiusGround); + GL.Color4(this._VertexColors[tri.C]); + GL.Vertex3(vectri.C * RadiusGround); } + GL.End();*/ - this._Planet.Render(proj, view, eyepos, Vector.Normalize(new Vector(Math.Sin(this._SunAngle), Math.Cos(this._SunAngle), 0.0))); - + System.Threading.Thread.Sleep(1); + this.SwapBuffers(); } + /// <summary> + /// Renderable to produce a cubemap for the planet. + /// </summary> + private struct _CubemapRenderable : IRenderable + { + public void Render() + { + GL.Begin(BeginMode.Triangles); + foreach (Triangle<int> tri in this.Window._Triangulation.Triangles) + { + Triangle<Vector> vectri = this.Window._Triangulation.Dereference(tri); + GL.Normal3(Triangle.Normal(vectri)); + GL.Color4(this.Window._VertexColors[tri.A]); + GL.Vertex3(vectri.A * RadiusGround); + GL.Color4(this.Window._VertexColors[tri.C]); + GL.Vertex3(vectri.C * RadiusGround); + GL.Color4(this.Window._VertexColors[tri.B]); + GL.Vertex3(vectri.B * RadiusGround); + } + GL.End(); + } + + public Window Window; + } + protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; - if (this.Keyboard[Key.Z]) this._SunAngle += updatetime * 0.5; - if (this.Keyboard[Key.X]) this._SunAngle -= updatetime * 0.5; - if (this.Keyboard[Key.C]) this._SunsetMode = true; else this._SunsetMode = false; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } - private bool _SunsetMode; + public const double RadiusGround = 6360.0; + + private Texture _Cubemap; + private Shader _CubemapUnroll; + private Color[] _VertexColors; + private SphericalTriangulation _Triangulation; private double _Height; private double _XRot; private double _ZRot; - private double _SunAngle; - private Planet _Planet; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index cb4a6ee..bd15638 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,115 +1,114 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; -const vec3 SunColor = vec3(70.0); +const vec3 SunColor = vec3(30.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _IRRADIANCE_UV_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #define _IRRADIANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Irradiance.glsl" #include "Precompute/Inscatter.glsl" vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); vec4 is = max(inscatter(mu, nu, r, mus), 0.0); result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { float mus = dot(n, sol); vec3 direct = transmittance(Rg, mus) * max(mus, 0.0) * SunColor / Pi; vec3 irr = irradiance(Rg, mus); vec3 full = direct + irr; return full * SeaColor; } vec3 HDR(vec3 L) { - L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); } #endif \ No newline at end of file diff --git a/Resources/Shaders/UnrollCubemap.glsl b/Resources/Shaders/UnrollCubemap.glsl new file mode 100644 index 0000000..86ca871 --- /dev/null +++ b/Resources/Shaders/UnrollCubemap.glsl @@ -0,0 +1,23 @@ +const float Pi = 3.1415926535; + +varying vec2 Coords; + +#ifdef _VERTEX_ +void main() +{ + Coords = gl_Vertex.xy; + gl_Position = gl_Vertex; +} +#endif + +#ifdef _FRAGMENT_ +uniform samplerCube Cubemap; + +void main() +{ + float siny = sqrt(1.0 - Coords.y * Coords.y); + float cosy = Coords.y; + vec3 sample = vec3(sin(Coords.x * Pi) * siny, cos(Coords.x * Pi) * siny, cosy); + gl_FragColor = textureCube(Cubemap, sample); +} +#endif \ No newline at end of file
dzamkov/Alunite-old
a36d9d34f863994b1bae67df8e2bfee9975bb21d
Cleaned up atmosphere codes so they look nicer and are reusable
diff --git a/Alunite/Alunite.csproj b/Alunite/Alunite.csproj index 2e915d8..d36a2fe 100644 --- a/Alunite/Alunite.csproj +++ b/Alunite/Alunite.csproj @@ -1,79 +1,80 @@ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{50B33331-0290-4981-9E8B-8A26901D2B53}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>Alunite</RootNamespace> <AssemblyName>Alunite</AssemblyName> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> </PropertyGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> <ItemGroup> <Compile Include="Array.cs" /> + <Compile Include="Atmosphere.cs" /> <Compile Include="Color.cs" /> <Compile Include="CSG.cs" /> <Compile Include="Diagram.cs" /> <Compile Include="Planet.cs" /> <Compile Include="Point.cs" /> <Compile Include="Polygon.cs" /> <Compile Include="Polyhedron.cs" /> <Compile Include="Program.cs" /> <Compile Include="Segment.cs" /> <Compile Include="Grid.cs" /> <Compile Include="Model.cs" /> <Compile Include="Path.cs" /> <Compile Include="Primitive.cs" /> <Compile Include="Set.cs" /> <Compile Include="Shader.cs" /> <Compile Include="Sort.cs" /> <Compile Include="TetrahedralMesh.cs" /> <Compile Include="Tetrahedron.cs" /> <Compile Include="Texture.cs" /> <Compile Include="Triangle.cs" /> <Compile Include="Tuple.cs" /> <Compile Include="VBO.cs" /> <Compile Include="Vector.cs" /> <Compile Include="Window.cs" /> </ItemGroup> <ItemGroup> <Reference Include="OpenTK, Version=1.0.0.0, Culture=neutral, PublicKeyToken=bad199fe84eb3df4, processorArchitecture=MSIL" /> <Reference Include="System" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> <Reference Include="System.Drawing" /> <Reference Include="System.Windows.Forms" /> </ItemGroup> </Project> \ No newline at end of file diff --git a/Alunite/Atmosphere.cs b/Alunite/Atmosphere.cs new file mode 100644 index 0000000..28a02f0 --- /dev/null +++ b/Alunite/Atmosphere.cs @@ -0,0 +1,341 @@ +using System; +using System.Collections.Generic; + +using OpenTK; +using OpenTK.Graphics; +using OpenTK.Graphics.OpenGL; + +namespace Alunite +{ + /// <summary> + /// Arguments defining a spherical atmosphere (affected by one sun). + /// </summary> + public struct AtmosphereOptions + { + /// <summary> + /// Distance from the center of the planet to ground level. + /// </summary> + public float RadiusGround; + + /// <summary> + /// Distance from the center of the planet to the highest point where atmosphere is computed. + /// </summary> + public float RadiusBound; + + /// <summary> + /// A proportion between 0.0 and 1.0 indicating how much light is reflected from the ground. + /// </summary> + public float AverageGroundReflectance; + + /// <summary> + /// Average height above ground level of all rayleigh particles (fine, distort color). + /// </summary> + public float RayleighAverageHeight; + + /// <summary> + /// Average height above ground level of all mie particles (coarse, white, absorb light). + /// </summary> + public float MieAverageHeight; + + /// <summary> + /// Atmosphere options for an Earthlike planet. + /// </summary> + public static readonly AtmosphereOptions DefaultEarth = new AtmosphereOptions() + { + AverageGroundReflectance = 0.1f, + RadiusGround = 6360.0f, + RadiusBound = 6420.0f, + RayleighAverageHeight = 8.0f, + MieAverageHeight = 1.2f, + }; + } + + /// <summary> + /// Arguments specifing the quality an atmosphere should be generated with. + /// </summary> + public struct AtmosphereQualityOptions + { + /// <summary> + /// Amount of scattering orders to compute. This increases time to generate textures and atmosphere quality without + /// requiring more runtime resources. + /// </summary> + public int MultipleScatteringOrder; + + /// <summary> + /// Resolution in height of textures involving the atmosphere. + /// </summary> + public int AtmosphereResR; + + /// <summary> + /// Resolution in view angle of textures involving the atmosphere. + /// </summary> + public int AtmosphereResMu; + + /// <summary> + /// Resolution in sun angle of textures involving the atmosphere. + /// </summary> + public int AtmosphereResMuS; + + /// <summary> + /// Resolution in sun/view angle offset of textures involving the atmosphere. + /// </summary> + public int AtmosphereResNu; + + /// <summary> + /// Resolution of sun angle in the irradiance texture. + /// </summary> + public int IrradianceResMu; + + /// <summary> + /// Resolution of height in the irradiance texture. + /// </summary> + public int IrradianceResR; + + /// <summary> + /// Resolution of view angle in the transmittance texture. + /// </summary> + public int TransmittanceResMu; + + /// <summary> + /// Resolution of height in the transmittance texture. + /// </summary> + public int TransmittanceResR; + + /// <summary> + /// Some okay options that generate reasonable results. + /// </summary> + public static readonly AtmosphereQualityOptions Default = new AtmosphereQualityOptions() + { + MultipleScatteringOrder = 4, + AtmosphereResMu = 128, + AtmosphereResR = 32, + AtmosphereResMuS = 32, + AtmosphereResNu = 8, + IrradianceResMu = 64, + IrradianceResR = 16, + TransmittanceResR = 64, + TransmittanceResMu = 256, + }; + } + + /// <summary> + /// Information about the precomputed parts of a spherical atmosphere. + /// </summary> + public struct PrecomputedAtmosphere + { + /// <summary> + /// 3D (simulating a 4D) texture describing the amount of light given off by the atmosphere. + /// </summary> + public Texture Inscatter; + + /// <summary> + /// 2D texture describing the amount of light given to a point on ground, by the atmosphere. + /// </summary> + public Texture Irradiance; + + /// <summary> + /// 2D texture describing how light is filtered while traveling through the atmosphere. + /// </summary> + public Texture Transmittance; + + /// <summary> + /// Sets up the textures for a currently active shader that involves the precomputed atmosphere. + /// </summary> + public void Setup(Shader Shader) + { + this.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture0); + this.Irradiance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture1); + this.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); + Shader.SetUniform("Inscatter", TextureUnit.Texture0); + Shader.SetUniform("Irradiance", TextureUnit.Texture1); + Shader.SetUniform("Transmittance", TextureUnit.Texture2); + } + } + + /// <summary> + /// Contains functions for manipulating and displaying spherical atmospheres. + /// </summary> + public static class Atmosphere + { + /// <summary> + /// Defines precompiler constants for atmosphere shaders based on options. + /// </summary> + public static void DefineConstants( + AtmosphereOptions Options, + AtmosphereQualityOptions QualityOptions, + Shader.PrecompilerInput PrecompilerInput) + { + PrecompilerInput.Define("ATMOSPHERE_RES_R", QualityOptions.AtmosphereResR.ToString()); + PrecompilerInput.Define("ATMOSPHERE_RES_MU", QualityOptions.AtmosphereResMu.ToString()); + PrecompilerInput.Define("ATMOSPHERE_RES_MU_S", QualityOptions.AtmosphereResMuS.ToString()); + PrecompilerInput.Define("ATMOSPHERE_RES_NU", QualityOptions.AtmosphereResNu.ToString()); + PrecompilerInput.Define("IRRADIANCE_RES_R", QualityOptions.IrradianceResR.ToString()); + PrecompilerInput.Define("IRRADIANCE_RES_MU", QualityOptions.IrradianceResMu.ToString()); + PrecompilerInput.Define("TRANSMITTANCE_RES_R", QualityOptions.TransmittanceResR.ToString()); + PrecompilerInput.Define("TRANSMITTANCE_RES_MU", QualityOptions.TransmittanceResMu.ToString()); + + PrecompilerInput.Define("RADIUS_GROUND", Options.RadiusGround.ToString()); + PrecompilerInput.Define("RADIUS_BOUND", Options.RadiusBound.ToString()); + PrecompilerInput.Define("AVERAGE_GROUND_REFLECTANCE", Options.AverageGroundReflectance.ToString()); + PrecompilerInput.Define("RAYLEIGH_AVERAGE_HEIGHT", Options.RayleighAverageHeight.ToString()); + PrecompilerInput.Define("MIE_AVERAGE_HEIGHT", Options.MieAverageHeight.ToString()); + } + + /// <summary> + /// Creates a precomputed atmosphere using shaders and the graphics card. + /// </summary> + public static PrecomputedAtmosphere Generate( + AtmosphereOptions Options, + AtmosphereQualityOptions QualityOptions, + Shader.PrecompilerInput PrecompilerInitial, + Path ShaderPath) + { + PrecomputedAtmosphere pa = new PrecomputedAtmosphere(); + Shader.PrecompilerInput pci = PrecompilerInitial.Copy(); + DefineConstants(Options, QualityOptions, pci); + + Path atmosphere = ShaderPath["Atmosphere"]; + Path precompute = atmosphere["Precompute"]; + + // Atmospheric scattering precompution + uint fbo; + GL.GenFramebuffers(1, out fbo); + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); + GL.ReadBuffer(ReadBufferMode.ColorAttachment0); + GL.DrawBuffer(DrawBufferMode.ColorAttachment0); + + // Load shaders. + Shader.PrecompilerInput transmittancepci = pci.Copy(); + Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); + + Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); + irradianceinitialdeltapci.Define("INITIAL"); + irradianceinitialdeltapci.Define("DELTA"); + Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); + + Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); + irradianceinitialpci.Define("INITIAL"); + Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); + + Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); + irradiancedeltapci.Define("DELTA"); + Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); + + Shader.PrecompilerInput irradiancepci = pci.Copy(); + Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); + + Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); + inscatterinitialdeltapci.Define("INITIAL"); + inscatterinitialdeltapci.Define("DELTA"); + Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); + + Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); + inscatterinitialpci.Define("INITIAL"); + Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); + + Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); + inscatterdeltapci.Define("DELTA"); + Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); + + Shader.PrecompilerInput inscatterpci = pci.Copy(); + Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); + + Shader.PrecompilerInput pointscatterpci = pci.Copy(); + Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); + + // Initialize textures + int transwidth = QualityOptions.TransmittanceResMu; + int transheight = QualityOptions.TransmittanceResR; + int irrwidth = QualityOptions.IrradianceResMu; + int irrheight = QualityOptions.IrradianceResR; + int atwidth = QualityOptions.AtmosphereResMuS * QualityOptions.AtmosphereResNu; + int atheight = QualityOptions.AtmosphereResMu; + int atdepth = QualityOptions.AtmosphereResR; + pa.Transmittance = Texture.Initialize2D(transwidth, transheight, Texture.RGB16Float); + pa.Irradiance = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); + pa.Inscatter = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGBA16Float); + Texture irrdelta = Texture.Initialize2D(irrwidth, irrheight, Texture.RGB16Float); + Texture insdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); + Texture ptsdelta = Texture.Initialize3D(atwidth, atheight, atdepth, Texture.RGB16Float); + + pa.Transmittance.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); + pa.Inscatter.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); + irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); + insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); + ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); + + // Create transmittance texture (information about how light is filtered through the atmosphere). + transmittance.Call(); + transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + pa.Transmittance.ID, transwidth, transheight); + + // Create delta irradiance texture (ground lighting cause by sun). + irradianceinitialdelta.Call(); + irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); + irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + irrdelta.ID, irrwidth, irrheight); + + // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). + inscatterinitial.Call(); + inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); + inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + pa.Inscatter.ID, atwidth, atheight, atdepth); + + // Initialize irradiance to zero (ground lighting caused by atmosphere). + irradianceinitial.Call(); + irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + pa.Irradiance.ID, irrwidth, irrheight); + + // Copy inscatter to delta inscatter, combining rayleigh and mie parts. + inscatterinitialdelta.Call(); + inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); + inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + insdelta.ID, atwidth, atheight, atdepth); + + for (int t = 2; t <= QualityOptions.MultipleScatteringOrder; t++) + { + // Generate point scattering information + // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. + pointscatter.Call(); + pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); + pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); + pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + ptsdelta.ID, atwidth, atheight, atdepth); + + // Compute new irradiance delta using current inscatter delta. + irradiancedelta.Call(); + irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); + irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + irrdelta.ID, irrwidth, irrheight); + + // Compute new inscatter delta using pointscatter data. + inscatterdelta.Call(); + inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); + inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + insdelta.ID, atwidth, atheight, atdepth); + + GL.Enable(EnableCap.Blend); + GL.BlendEquation(BlendEquationMode.FuncAdd); + GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); + + // Add irradiance delta to irradiance. + irradiance.Call(); + irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); + irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + pa.Irradiance.ID, irrwidth, irrheight); + + // Add inscatter delta to inscatter. + inscatter.Call(); + inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); + inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + pa.Inscatter.ID, atwidth, atheight, atdepth); + + GL.Disable(EnableCap.Blend); + } + + GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); + + return pa; + } + } +} \ No newline at end of file diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 19a2d53..9e8afea 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,389 +1,227 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { - Shader.PrecompilerInput pci = _DefineCommon(); + Shader.PrecompilerInput pci = Shader.CreatePrecompilerInput(); + AtmosphereOptions options = AtmosphereOptions.DefaultEarth; + AtmosphereQualityOptions qualityoptions = AtmosphereQualityOptions.Default; + this._Atmosphere = Atmosphere.Generate(options, qualityoptions, pci, ShaderPath); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; - this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); - - // Atmospheric scattering precompution - uint fbo; - GL.GenFramebuffers(1, out fbo); - GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); - GL.ReadBuffer(ReadBufferMode.ColorAttachment0); - GL.DrawBuffer(DrawBufferMode.ColorAttachment0); - - // Load shaders. - Shader.PrecompilerInput transmittancepci = pci.Copy(); - Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); - - Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); - irradianceinitialdeltapci.Define("INITIAL"); - irradianceinitialdeltapci.Define("DELTA"); - Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); - - Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); - irradianceinitialpci.Define("INITIAL"); - Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); - - Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); - irradiancedeltapci.Define("DELTA"); - Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); - - Shader.PrecompilerInput irradiancepci = pci.Copy(); - Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); - - Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); - inscatterinitialdeltapci.Define("INITIAL"); - inscatterinitialdeltapci.Define("DELTA"); - Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); - - Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); - inscatterinitialpci.Define("INITIAL"); - Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); - - Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); - inscatterdeltapci.Define("DELTA"); - Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); - - Shader.PrecompilerInput inscatterpci = pci.Copy(); - Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); - - Shader.PrecompilerInput pointscatterpci = pci.Copy(); - Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); - - // Initialize textures - this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); - this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - this._InscatterTexture = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); - Texture irrdelta = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - Texture insdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); - Texture ptsdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); - - this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); - this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); - irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); - insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); - ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); - - // Create transmittance texture (information about how light is filtered through the atmosphere). - transmittance.Call(); - transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); - - // Create delta irradiance texture (ground lighting cause by sun). - irradianceinitialdelta.Call(); - irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); - irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - irrdelta.ID, IrradianceResMu, IrradianceResR); - - // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). - inscatterinitial.Call(); - inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); - inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - - // Initialize irradiance to zero (ground lighting caused by atmosphere). - irradianceinitial.Call(); - irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); - - // Copy inscatter to delta inscatter, combining rayleigh and mie parts. - inscatterinitialdelta.Call(); - inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); - inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - - for (int t = 2; t <= MultipleScatterOrder; t++) - { - // Generate point scattering information - // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. - pointscatter.Call(); - pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); - pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); - pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - ptsdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - - // Compute new irradiance delta using current inscatter delta. - irradiancedelta.Call(); - irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); - irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - irrdelta.ID, IrradianceResMu, IrradianceResR); - - // Compute new inscatter delta using pointscatter data. - inscatterdelta.Call(); - inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); - inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - - GL.Enable(EnableCap.Blend); - GL.BlendEquation(BlendEquationMode.FuncAdd); - GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); - - // Add irradiance delta to irradiance. - irradiance.Call(); - irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); - irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); - - // Add inscatter delta to inscatter. - inscatter.Call(); - inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); - inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - - GL.Disable(EnableCap.Blend); - } - - GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); + Atmosphere.DefineConstants(options, qualityoptions, pci); + this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci); } - private const int MultipleScatterOrder = 4; - private const int AtmosphereResR = 32; - private const int AtmosphereResMu = 128; - private const int AtmosphereResMuS = 32; - private const int AtmosphereResNu = 8; - private const int IrradianceResR = 16; - private const int IrradianceResMu = 64; - private const int TransmittanceResR = 64; - private const int TransmittanceResMu = 256; - - /// <summary> - /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source - /// input. - /// </summary> - private static Shader.PrecompilerInput _DefineCommon() - { - Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); - res.Define("ATMOSPHERE_RES_R", AtmosphereResR.ToString()); - res.Define("ATMOSPHERE_RES_MU", AtmosphereResMu.ToString()); - res.Define("ATMOSPHERE_RES_MU_S", AtmosphereResMuS.ToString()); - res.Define("ATMOSPHERE_RES_NU", AtmosphereResNu.ToString()); - res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); - res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); - res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); - res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); - return res; - } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); - this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); - this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); - this._IrradianceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); - - this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); - this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); - this._PlanetShader.SetUniform("Irradiance", TextureUnit.Texture2); + this._Atmosphere.Setup(this._PlanetShader); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } - private Texture _InscatterTexture; - private Texture _TransmittanceTexture; - private Texture _IrradianceTexture; + private PrecomputedAtmosphere _Atmosphere; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Common.glsl b/Resources/Shaders/Atmosphere/Precompute/Common.glsl index 2909ece..34e7939 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Common.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Common.glsl @@ -1,91 +1,90 @@ const float Pi = 3.14159265; -const float Rt = 6420.0; -const float Rg = 6360.0; +const float Rt = float(RADIUS_BOUND); +const float Rg = float(RADIUS_GROUND); -const float GroundReflectance = 0.1; +const float GroundReflectance = float(AVERAGE_GROUND_REFLECTANCE); // Rayleigh -const float HR = 8.0; +const float HR = float(RAYLEIGH_AVERAGE_HEIGHT); const vec3 betaR = vec3(5.8e-3, 1.35e-2, 3.31e-2); // Mie -// DEFAULT -const float HM = 1.2; +const float HM = float(MIE_AVERAGE_HEIGHT); const vec3 betaMSca = vec3(4e-3); const vec3 betaMEx = betaMSca / 0.9; const float mieG = 0.8; // Gets the length of the ray before either the atmospheric boundary, or ground, is hit. float limit(float r, float mu) { float atmosdis = -r * mu + sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); float groundp = r * r * (mu * mu - 1.0) + Rg * Rg; float res = atmosdis; if(groundp >= 0.0) { float grounddis = -r * mu - sqrt(groundp); if(grounddis >= 0.0) { res = grounddis; } } return res; } float phaseFunctionR(float mu) { return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); } float phaseFunctionM(float mu) { return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); } #ifdef _COMMON_ATMOSPHERE_TEXTURE_WRITE_ void getAtmosphereTextureMuNuRMus(out float mu, out float nu, out float r, out float mus) { float x = gl_FragCoord.x; float y = gl_FragCoord.y; float z = float(Layer); mus = mod(x, float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_MU_S) - 1.0); nu = floor(x / float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_NU) - 1.0); mu = y / float(ATMOSPHERE_RES_MU); r = z / float(ATMOSPHERE_RES_R); #ifdef ATMOSPHERE_TEXTURE_SIMPLE mu = -1.0 + mu * 2.0; nu = -1.0 + nu * 2.0; mus = -1.0 + mus * 2.0; r = Rg + r * (Rt - Rg); #else mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); nu = -1.0 + nu * 2.0; mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); r = Rg + (r * r) * (Rt - Rg); #endif } #endif #ifdef _COMMON_ATMOSPHERE_TEXTURE_READ_ vec4 lookupAtmosphereTexture(sampler3D tex, float mu, float nu, float r, float mus) { #ifdef ATMOSPHERE_TEXTURE_SIMPLE float umu = (mu + 1.0) / 2.0; float unu = (nu + 1.0) / 2.0; float umus = (mus + 1.0) / 2.0; float ur = (r - Rg) / (Rt - Rg); #else float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; float unu = (nu + 1.0) / 2.0; float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; float ur = sqrt((r - Rg) / (Rt - Rg)); #endif umus = max(1.0 / float(ATMOSPHERE_RES_MU_S), umus); umus = min(1.0 - 1.0 / float(ATMOSPHERE_RES_MU_S), umus); float lerp = unu * (float(ATMOSPHERE_RES_NU) - 1.0); unu = floor(lerp); lerp = lerp - unu; return texture3D(tex, vec3((unu + umus) / float(ATMOSPHERE_RES_NU), umu, ur)) * (1.0 - lerp) + texture3D(tex, vec3((unu + umus + 1.0) / float(ATMOSPHERE_RES_NU), umu, ur)) * lerp; } #endif \ No newline at end of file
dzamkov/Alunite-old
62e9c88932c44d4aac1ebbd852c6de928d498a75
I daresey atmosphere is done
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 687406a..19a2d53 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,342 +1,389 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { Shader.PrecompilerInput pci = _DefineCommon(); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); + Shader.PrecompilerInput irradiancedeltapci = pci.Copy(); + irradiancedeltapci.Define("DELTA"); + Shader irradiancedelta = Shader.Load(precompute["Irradiance.glsl"], irradiancedeltapci); + + Shader.PrecompilerInput irradiancepci = pci.Copy(); + Shader irradiance = Shader.Load(precompute["Irradiance.glsl"], irradiancepci); + Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); + Shader.PrecompilerInput inscatterdeltapci = pci.Copy(); + inscatterdeltapci.Define("DELTA"); + Shader inscatterdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterdeltapci); + + Shader.PrecompilerInput inscatterpci = pci.Copy(); + Shader inscatter = Shader.Load(precompute["Inscatter.glsl"], inscatterpci); + Shader.PrecompilerInput pointscatterpci = pci.Copy(); Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); // Initialize textures this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); this._InscatterTexture = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); Texture insdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); Texture ptsdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitialdelta.Call(); irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, IrradianceResMu, IrradianceResR); // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). inscatterinitial.Call(); inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - // Initialize irradiance to zero + // Initialize irradiance to zero (ground lighting caused by atmosphere). irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); // Copy inscatter to delta inscatter, combining rayleigh and mie parts. inscatterinitialdelta.Call(); inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - //for (int t = 2; t <= MultipleScatterOrder; t++) - //{ + for (int t = 2; t <= MultipleScatterOrder; t++) + { // Generate point scattering information + // Note that this texture will likely be very dark because it contains data for a single point, as opposed to a long line. pointscatter.Call(); pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, ptsdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - //} + + // Compute new irradiance delta using current inscatter delta. + irradiancedelta.Call(); + irradiancedelta.SetUniform("InscatterDelta", TextureUnit.Texture4); + irradiancedelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + irrdelta.ID, IrradianceResMu, IrradianceResR); + + // Compute new inscatter delta using pointscatter data. + inscatterdelta.Call(); + inscatterdelta.SetUniform("PointScatter", TextureUnit.Texture5); + inscatterdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + + GL.Enable(EnableCap.Blend); + GL.BlendEquation(BlendEquationMode.FuncAdd); + GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); + + // Add irradiance delta to irradiance. + irradiance.Call(); + irradiance.SetUniform("IrradianceDelta", TextureUnit.Texture3); + irradiance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); + + // Add inscatter delta to inscatter. + inscatter.Call(); + inscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); + inscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + + GL.Disable(EnableCap.Blend); + } GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); } - private const int MultipleScatterOrder = 5; + private const int MultipleScatterOrder = 4; private const int AtmosphereResR = 32; - private const int AtmosphereResMu = 256; + private const int AtmosphereResMu = 128; private const int AtmosphereResMuS = 32; private const int AtmosphereResNu = 8; private const int IrradianceResR = 16; private const int IrradianceResMu = 64; private const int TransmittanceResR = 64; private const int TransmittanceResMu = 256; /// <summary> /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source /// input. /// </summary> private static Shader.PrecompilerInput _DefineCommon() { Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); res.Define("ATMOSPHERE_RES_R", AtmosphereResR.ToString()); res.Define("ATMOSPHERE_RES_MU", AtmosphereResMu.ToString()); res.Define("ATMOSPHERE_RES_MU_S", AtmosphereResMuS.ToString()); res.Define("ATMOSPHERE_RES_NU", AtmosphereResNu.ToString()); res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); return res; } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); + this._IrradianceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture2); - this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture4); this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); + this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); + this._PlanetShader.SetUniform("Irradiance", TextureUnit.Texture2); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } private Texture _InscatterTexture; private Texture _TransmittanceTexture; private Texture _IrradianceTexture; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index b7f7ba9..cb4a6ee 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,117 +1,115 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; -const vec3 SunColor = vec3(100.0); +const vec3 SunColor = vec3(70.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ +#define _IRRADIANCE_UV_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ +#define _IRRADIANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" +#include "Precompute/Irradiance.glsl" #include "Precompute/Inscatter.glsl" -#define HORIZON_FIX - vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); - phaseR = 1.0; - phaseM = 0.0; vec4 is = max(inscatter(mu, nu, r, mus), 0.0); -#ifdef HORIZON_FIX - //is.w *= smoothstep(0.00, 0.02, mus); -#endif result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { - // Direct sunlight - float mu = dot(n, sol); - vec3 direct = transmittance(Rg, mu) * max(mu, 0.0) * SunColor / Pi; - return direct * SeaColor; + float mus = dot(n, sol); + vec3 direct = transmittance(Rg, mus) * max(mus, 0.0) * SunColor / Pi; + vec3 irr = irradiance(Rg, mus); + vec3 full = direct + irr; + + return full * SeaColor; } vec3 HDR(vec3 L) { L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index 1c93bae..4b0a0f9 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,84 +1,115 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ uniform int Layer; #define _TRANSMITTANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } #ifdef INITIAL #ifdef DELTA uniform sampler3D Inscatter; void main() { float mu, nu, r, mus; getAtmosphereTextureMuNuRMus(mu, nu, r, mus); float pr = phaseFunctionR(nu); float pm = phaseFunctionM(nu); vec4 raymies = lookupAtmosphereTexture(Inscatter, mu, nu, r, mus); gl_FragColor = vec4(raymies.rgb * pr + vec3(raymies.w * pm), 0.0); } #else void main() { float mu, nu, r, mus; getAtmosphereTextureMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } gl_FragColor = vec4(ray, mie); if(r < Rg + 0.001 && mu < 0.0) { // Degeneracy fix gl_FragColor = vec4(0.0); } } #endif #else +#ifdef DELTA +uniform sampler3D PointScatter; +void main() { + float mu, nu, r, mus; + getAtmosphereTextureMuNuRMus(mu, nu, r, mus); + + vec3 raymie = vec3(0.0); + float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); + for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { + float t = float(i) * dx; + + float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); + float mui = (r * mu + t) / ri; + float musi = (nu * t + mus * r) / ri; + vec3 raymiei = lookupAtmosphereTexture(PointScatter, mui, nu, ri, musi).rgb * transmittance(r, mu, t); + + raymie += raymiei * dx; + } + + gl_FragColor = mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? vec4(0.0) : vec4(raymie, 0.0); +} +#else +uniform sampler3D InscatterDelta; +void main() { + float mu, nu, r, mus; + getAtmosphereTextureMuNuRMus(mu, nu, r, mus); + float pr = phaseFunctionR(nu); + vec3 ray = lookupAtmosphereTexture(InscatterDelta, mu, nu, r, mus).rgb; + gl_FragColor = vec4(ray / pr, 0.0); +} +#endif #endif #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { return lookupAtmosphereTexture(Inscatter, mu, nu, r, mus); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl index 3cb7920..b35b15d 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl @@ -1,58 +1,90 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ +#define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Common.glsl" #include "Transmittance.glsl" +#define IRRADIANCE_SPHERICAL_INTEGRAL_SAMPLES 16 + void getIrradianceRMu(out float r, out float mu) { r = gl_FragCoord.y / float(IRRADIANCE_RES_R); mu = gl_FragCoord.x / float(IRRADIANCE_RES_MU); #ifdef IRRADIANCE_SIMPLE r = Rg + r * (Rt - Rg); mu = -1.0 + mu * 2.0; #else r = Rg + r * r * (Rt - Rg); mu = -1.0 + mu * 2.0; #endif } #ifdef INITIAL #ifdef DELTA void main() { float r, mu; getIrradianceRMu(r, mu); gl_FragColor = vec4(transmittance(r, mu) * max(mu, 0.0), 0.0); } #else void main() { gl_FragColor = vec4(0.0); } #endif #else - - +#ifdef DELTA +uniform sampler3D InscatterDelta; +void main() { + const float dtheta = Pi / float(IRRADIANCE_SPHERICAL_INTEGRAL_SAMPLES); + const float dphi = dtheta; + float r, mus; + getIrradianceRMu(r, mus); + vec3 s = vec3(sqrt(1.0 - mus * mus), 0.0, mus); + vec3 result = vec3(0.0); + + for (int iphi = 0; iphi < 2 * IRRADIANCE_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) { + float phi = (float(iphi) + 0.5) * dphi; + for (int itheta = 0; itheta < IRRADIANCE_SPHERICAL_INTEGRAL_SAMPLES / 2; ++itheta) { + float theta = (float(itheta) + 0.5) * dtheta; + float dw = dtheta * dphi * sin(theta); + vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), cos(theta)); + float nu = dot(s, w); + result += lookupAtmosphereTexture(InscatterDelta, w.z, nu, r, mus).rgb * w.z * dw; + } + } + + gl_FragColor = vec4(result, 0.0); +} +#else +uniform sampler2D IrradianceDelta; +void main() { + vec2 uv = gl_FragCoord.xy / vec2(IRRADIANCE_RES_MU, IRRADIANCE_RES_R); + gl_FragColor = texture2D(IrradianceDelta, uv); +} +#endif #endif #endif #ifdef _IRRADIANCE_UV_ vec2 getIrradianceUV(float r, float mu) { #ifdef IRRADIANCE_SIMPLE return vec2((mu + 1.0) / 2.0, (r - Rg) / (Rt - Rg)); #else return vec2((mu + 1.0) / 2.0, sqrt((r - Rg) / (Rt - Rg))); #endif } #endif #ifdef _IRRADIANCE_USE_ - - - +uniform sampler2D Irradiance; +vec3 irradiance(float r, float mu) { + return texture2D(Irradiance, getIrradianceUV(r, mu)); +} #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl index da0869b..4acfd71 100644 --- a/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl @@ -1,79 +1,82 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ uniform int Layer; uniform int Order; uniform sampler2D IrradianceDelta; uniform sampler3D InscatterDelta; #define _TRANSMITTANCE_USE_ #define _IRRADIANCE_UV_ #define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Common.glsl" #include "Transmittance.glsl" #include "Irradiance.glsl" -#define POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES 4 +#define POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES 16 void main() { float mu, nu, r, mus; getAtmosphereTextureMuNuRMus(mu, nu, r, mus); + r = clamp(r, Rg, Rt); + mu = clamp(mu, -1.0, 1.0); + mus = clamp(mus, -1.0, 1.0); float var = sqrt(1.0 - mu * mu) * sqrt(1.0 - mus * mus); nu = clamp(nu, mus * mu - var, mus * mu + var); float cthetaground = -sqrt(1.0 - (Rg / r) * (Rg / r)); vec3 v = vec3(sqrt(1.0 - mu * mu), 0.0, mu); float sx = v.x == 0.0 ? 0.0 : (nu - mus * mu) / v.x; vec3 s = vec3(sx, sqrt(max(0.0, 1.0 - sx * sx - mus * mus)), mus); vec3 raymie = vec3(0.0); const float dtheta = Pi / float(POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES); const float dphi = dtheta; for (int itheta = 0; itheta < POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++itheta) { float theta = (float(itheta) + 0.5) * dtheta; float ctheta = cos(theta); float greflectance = 0.0; float dground = 0.0; vec3 gtransp = vec3(0.0); if (ctheta < cthetaground) { greflectance = GroundReflectance / Pi; dground = -r * ctheta - sqrt(r * r * (ctheta * ctheta - 1.0) + Rg * Rg); gtransp = transmittance(Rg, -(r * ctheta + dground) / Rg, dground); } for (int iphi = 0; iphi < 2 * POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) { float phi = (float(iphi) + 0.5) * dphi; float dw = dtheta * dphi * sin(theta); vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), ctheta); float nu1 = dot(s, w); float nu2 = dot(v, w); float pr2 = phaseFunctionR(nu2); float pm2 = phaseFunctionM(nu2); vec3 gnormal = (vec3(0.0, 0.0, r) + dground * w) / Rg; vec3 girradiance = texture2D(IrradianceDelta, getIrradianceUV(Rg, dot(gnormal, s))); vec3 ix = greflectance * girradiance * gtransp + lookupAtmosphereTexture(InscatterDelta, ctheta, nu1, r, mus).rgb; raymie += ix * (betaR * exp(-(r - Rg) / HR) * pr2 + betaMSca * exp(-(r - Rg) / HM) * pm2) * dw; } } gl_FragColor = vec4(raymie, 0.0); } #endif \ No newline at end of file
dzamkov/Alunite-old
9f3337a7700e471d26232e77b4a64142ed4c8abe
Created PointScatter, rearranged inscatter and delta inscatter so delta inscatter has combined rayleigh and mie parts, provided a demonstration of what would have happened if I used a texture with rayleigh and mie parts seperated
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 18aa198..687406a 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,340 +1,342 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { Shader.PrecompilerInput pci = _DefineCommon(); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); Shader.PrecompilerInput pointscatterpci = pci.Copy(); Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); // Initialize textures this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); this._InscatterTexture = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - Texture insdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); + Texture insdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); Texture ptsdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); + this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture2); irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); + ptsdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitialdelta.Call(); irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, IrradianceResMu, IrradianceResR); - // Create delta inscatter texture (light from the atmosphere). - inscatterinitialdelta.Call(); - inscatterinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); - inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + // Create initial inscatter texture (light from atmosphere from sun, rayleigh and mie parts seperated for precision). + inscatterinitial.Call(); + inscatterinitial.SetUniform("Transmittance", TextureUnit.Texture0); + inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); // Initialize irradiance to zero irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); - // Copy delta inscatter to inscatter - inscatterinitial.Call(); - inscatterinitial.SetUniform("InscatterDelta", TextureUnit.Texture4); - inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + // Copy inscatter to delta inscatter, combining rayleigh and mie parts. + inscatterinitialdelta.Call(); + inscatterinitialdelta.SetUniform("Inscatter", TextureUnit.Texture2); + inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); - //for (int t = 0; t < MultipleScatterOrder; t++) + //for (int t = 2; t <= MultipleScatterOrder; t++) //{ // Generate point scattering information pointscatter.Call(); pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, ptsdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); //} GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); } private const int MultipleScatterOrder = 5; private const int AtmosphereResR = 32; private const int AtmosphereResMu = 256; private const int AtmosphereResMuS = 32; private const int AtmosphereResNu = 8; private const int IrradianceResR = 16; private const int IrradianceResMu = 64; private const int TransmittanceResR = 64; private const int TransmittanceResMu = 256; /// <summary> /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source /// input. /// </summary> private static Shader.PrecompilerInput _DefineCommon() { Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); res.Define("ATMOSPHERE_RES_R", AtmosphereResR.ToString()); res.Define("ATMOSPHERE_RES_MU", AtmosphereResMu.ToString()); res.Define("ATMOSPHERE_RES_MU_S", AtmosphereResMuS.ToString()); res.Define("ATMOSPHERE_RES_NU", AtmosphereResNu.ToString()); res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); return res; } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); - this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); + this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture4); this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } private Texture _InscatterTexture; private Texture _TransmittanceTexture; private Texture _IrradianceTexture; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index d00fae5..b7f7ba9 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,124 +1,117 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; const vec3 SunColor = vec3(100.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Inscatter.glsl" #define HORIZON_FIX -float phaseFunctionR(float mu) { - return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); -} - -float phaseFunctionM(float mu) { - return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); -} - vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); + phaseR = 1.0; + phaseM = 0.0; vec4 is = max(inscatter(mu, nu, r, mus), 0.0); #ifdef HORIZON_FIX //is.w *= smoothstep(0.00, 0.02, mus); #endif result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { // Direct sunlight float mu = dot(n, sol); vec3 direct = transmittance(Rg, mu) * max(mu, 0.0) * SunColor / Pi; return direct * SeaColor; } vec3 HDR(vec3 L) { L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); - //gl_FragColor = texture3D(Inscatter, vec3(Coords, 0.5)); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Common.glsl b/Resources/Shaders/Atmosphere/Precompute/Common.glsl index afe8fa4..2909ece 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Common.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Common.glsl @@ -1,81 +1,91 @@ const float Pi = 3.14159265; const float Rt = 6420.0; const float Rg = 6360.0; +const float GroundReflectance = 0.1; + // Rayleigh const float HR = 8.0; const vec3 betaR = vec3(5.8e-3, 1.35e-2, 3.31e-2); // Mie // DEFAULT const float HM = 1.2; const vec3 betaMSca = vec3(4e-3); const vec3 betaMEx = betaMSca / 0.9; const float mieG = 0.8; // Gets the length of the ray before either the atmospheric boundary, or ground, is hit. float limit(float r, float mu) { float atmosdis = -r * mu + sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); float groundp = r * r * (mu * mu - 1.0) + Rg * Rg; float res = atmosdis; if(groundp >= 0.0) { float grounddis = -r * mu - sqrt(groundp); if(grounddis >= 0.0) { res = grounddis; } } return res; } +float phaseFunctionR(float mu) { + return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); +} + +float phaseFunctionM(float mu) { + return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); +} + #ifdef _COMMON_ATMOSPHERE_TEXTURE_WRITE_ void getAtmosphereTextureMuNuRMus(out float mu, out float nu, out float r, out float mus) { float x = gl_FragCoord.x; float y = gl_FragCoord.y; float z = float(Layer); mus = mod(x, float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_MU_S) - 1.0); nu = floor(x / float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_NU) - 1.0); mu = y / float(ATMOSPHERE_RES_MU); r = z / float(ATMOSPHERE_RES_R); #ifdef ATMOSPHERE_TEXTURE_SIMPLE mu = -1.0 + mu * 2.0; nu = -1.0 + nu * 2.0; mus = -1.0 + mus * 2.0; r = Rg + r * (Rt - Rg); #else mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); nu = -1.0 + nu * 2.0; mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); r = Rg + (r * r) * (Rt - Rg); #endif } #endif #ifdef _COMMON_ATMOSPHERE_TEXTURE_READ_ vec4 lookupAtmosphereTexture(sampler3D tex, float mu, float nu, float r, float mus) { #ifdef ATMOSPHERE_TEXTURE_SIMPLE float umu = (mu + 1.0) / 2.0; float unu = (nu + 1.0) / 2.0; float umus = (mus + 1.0) / 2.0; float ur = (r - Rg) / (Rt - Rg); #else float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; float unu = (nu + 1.0) / 2.0; float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; float ur = sqrt((r - Rg) / (Rt - Rg)); #endif umus = max(1.0 / float(ATMOSPHERE_RES_MU_S), umus); umus = min(1.0 - 1.0 / float(ATMOSPHERE_RES_MU_S), umus); float lerp = unu * (float(ATMOSPHERE_RES_NU) - 1.0); unu = floor(lerp); lerp = lerp - unu; return texture3D(tex, vec3((unu + umus) / float(ATMOSPHERE_RES_NU), umu, ur)) * (1.0 - lerp) + texture3D(tex, vec3((unu + umus + 1.0) / float(ATMOSPHERE_RES_NU), umu, ur)) * lerp; } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index 73fa94f..1c93bae 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,79 +1,84 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ uniform int Layer; #define _TRANSMITTANCE_USE_ #define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ +#define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } #ifdef INITIAL #ifdef DELTA +uniform sampler3D Inscatter; +void main() { + float mu, nu, r, mus; + getAtmosphereTextureMuNuRMus(mu, nu, r, mus); + float pr = phaseFunctionR(nu); + float pm = phaseFunctionM(nu); + vec4 raymies = lookupAtmosphereTexture(Inscatter, mu, nu, r, mus); + gl_FragColor = vec4(raymies.rgb * pr + vec3(raymies.w * pm), 0.0); +} +#else void main() { float mu, nu, r, mus; getAtmosphereTextureMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } gl_FragColor = vec4(ray, mie); if(r < Rg + 0.001 && mu < 0.0) { // Degeneracy fix gl_FragColor = vec4(0.0); } } -#else -uniform sampler3D InscatterDelta; -void main() { - vec3 uvw = vec3(gl_FragCoord.xy, float(Layer) + 0.5) / vec3(ivec3(ATMOSPHERE_RES_MU_S * ATMOSPHERE_RES_NU, ATMOSPHERE_RES_MU, ATMOSPHERE_RES_R)); - gl_FragColor = texture3D(InscatterDelta, uvw); -} #endif #else #endif #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { return lookupAtmosphereTexture(Inscatter, mu, nu, r, mus); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl index 76e263e..da0869b 100644 --- a/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl @@ -1,29 +1,79 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ uniform int Layer; +uniform int Order; uniform sampler2D IrradianceDelta; -uniform sampler2D InscatterDelta; +uniform sampler3D InscatterDelta; #define _TRANSMITTANCE_USE_ #define _IRRADIANCE_UV_ #define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ #define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Common.glsl" #include "Transmittance.glsl" #include "Irradiance.glsl" +#define POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES 4 + void main() { float mu, nu, r, mus; getAtmosphereTextureMuNuRMus(mu, nu, r, mus); - gl_FragColor = texture2D(IrradianceDelta, getIrradianceUV(r, mus)); + + float var = sqrt(1.0 - mu * mu) * sqrt(1.0 - mus * mus); + nu = clamp(nu, mus * mu - var, mus * mu + var); + + float cthetaground = -sqrt(1.0 - (Rg / r) * (Rg / r)); + + vec3 v = vec3(sqrt(1.0 - mu * mu), 0.0, mu); + float sx = v.x == 0.0 ? 0.0 : (nu - mus * mu) / v.x; + vec3 s = vec3(sx, sqrt(max(0.0, 1.0 - sx * sx - mus * mus)), mus); + + vec3 raymie = vec3(0.0); + + const float dtheta = Pi / float(POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES); + const float dphi = dtheta; + + for (int itheta = 0; itheta < POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++itheta) { + float theta = (float(itheta) + 0.5) * dtheta; + float ctheta = cos(theta); + + float greflectance = 0.0; + float dground = 0.0; + vec3 gtransp = vec3(0.0); + if (ctheta < cthetaground) { + greflectance = GroundReflectance / Pi; + dground = -r * ctheta - sqrt(r * r * (ctheta * ctheta - 1.0) + Rg * Rg); + gtransp = transmittance(Rg, -(r * ctheta + dground) / Rg, dground); + } + + for (int iphi = 0; iphi < 2 * POINTSCATTER_SPHERICAL_INTEGRAL_SAMPLES; ++iphi) { + float phi = (float(iphi) + 0.5) * dphi; + float dw = dtheta * dphi * sin(theta); + vec3 w = vec3(cos(phi) * sin(theta), sin(phi) * sin(theta), ctheta); + + float nu1 = dot(s, w); + float nu2 = dot(v, w); + float pr2 = phaseFunctionR(nu2); + float pm2 = phaseFunctionM(nu2); + + vec3 gnormal = (vec3(0.0, 0.0, r) + dground * w) / Rg; + vec3 girradiance = texture2D(IrradianceDelta, getIrradianceUV(Rg, dot(gnormal, s))); + + vec3 ix = greflectance * girradiance * gtransp + lookupAtmosphereTexture(InscatterDelta, ctheta, nu1, r, mus).rgb; + + raymie += ix * (betaR * exp(-(r - Rg) / HR) * pr2 + betaMSca * exp(-(r - Rg) / HM) * pm2) * dw; + } + } + + gl_FragColor = vec4(raymie, 0.0); } #endif \ No newline at end of file
dzamkov/Alunite-old
35d778b28262fb207740dab38fc10817a87835ef
Annoying bug fixed, PointScatter started
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index f1c9c75..18aa198 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,320 +1,340 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { Shader.PrecompilerInput pci = _DefineCommon(); - + Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); irradianceinitialdeltapci.Define("INITIAL"); irradianceinitialdeltapci.Define("DELTA"); Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); inscatterinitialdeltapci.Define("INITIAL"); inscatterinitialdeltapci.Define("DELTA"); Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); + Shader.PrecompilerInput pointscatterpci = pci.Copy(); + Shader pointscatter = Shader.Load(precompute["PointScatter.glsl"], pointscatterpci); + // Initialize textures this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - this._InscatterTexture = Texture.Initialize3D(InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR, Texture.RGBA16Float); + this._InscatterTexture = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); Texture irrdelta = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - Texture insdelta = Texture.Initialize3D(InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR, Texture.RGBA16Float); + Texture insdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGBA16Float); + Texture ptsdelta = Texture.Initialize3D(AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR, Texture.RGB16Float); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); - - insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); + irrdelta.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture3); + insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture4); // Create transmittance texture (information about how light is filtered through the atmosphere). + transmittance.Call(); transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); // Create delta irradiance texture (ground lighting cause by sun). + irradianceinitialdelta.Call(); irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, irrdelta.ID, IrradianceResMu, IrradianceResR); // Create delta inscatter texture (light from the atmosphere). + inscatterinitialdelta.Call(); inscatterinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - insdelta.ID, InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR); + insdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); // Initialize irradiance to zero + irradianceinitial.Call(); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); // Copy delta inscatter to inscatter - inscatterinitial.SetUniform("InscatterDelta", TextureUnit.Texture5); + inscatterinitial.Call(); + inscatterinitial.SetUniform("InscatterDelta", TextureUnit.Texture4); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._InscatterTexture.ID, InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR); + this._InscatterTexture.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + + //for (int t = 0; t < MultipleScatterOrder; t++) + //{ + // Generate point scattering information + pointscatter.Call(); + pointscatter.SetUniform("IrradianceDelta", TextureUnit.Texture3); + pointscatter.SetUniform("InscatterDelta", TextureUnit.Texture4); + pointscatter.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + ptsdelta.ID, AtmosphereResMuS * AtmosphereResNu, AtmosphereResMu, AtmosphereResR); + //} GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); } - private const int InscatterResR = 32; - private const int InscatterResMu = 256; - private const int InscatterResMuS = 32; - private const int InscatterResNu = 8; + private const int MultipleScatterOrder = 5; + private const int AtmosphereResR = 32; + private const int AtmosphereResMu = 256; + private const int AtmosphereResMuS = 32; + private const int AtmosphereResNu = 8; private const int IrradianceResR = 16; private const int IrradianceResMu = 64; private const int TransmittanceResR = 64; private const int TransmittanceResMu = 256; /// <summary> /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source /// input. /// </summary> private static Shader.PrecompilerInput _DefineCommon() { Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); - res.Define("INSCATTER_RES_R", InscatterResR.ToString()); - res.Define("INSCATTER_RES_MU", InscatterResMu.ToString()); - res.Define("INSCATTER_RES_MU_S", InscatterResMuS.ToString()); - res.Define("INSCATTER_RES_NU", InscatterResNu.ToString()); + res.Define("ATMOSPHERE_RES_R", AtmosphereResR.ToString()); + res.Define("ATMOSPHERE_RES_MU", AtmosphereResMu.ToString()); + res.Define("ATMOSPHERE_RES_MU_S", AtmosphereResMuS.ToString()); + res.Define("ATMOSPHERE_RES_NU", AtmosphereResNu.ToString()); res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); return res; } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); - this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); + this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } private Texture _InscatterTexture; private Texture _TransmittanceTexture; private Texture _IrradianceTexture; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Alunite/Shader.cs b/Alunite/Shader.cs index 2b92fd7..1398312 100644 --- a/Alunite/Shader.cs +++ b/Alunite/Shader.cs @@ -1,415 +1,415 @@ using System.Collections.Generic; using System; using System.IO; using System.Text; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Represents a shader in graphics memory. /// </summary> public struct Shader { /// <summary> /// Sets the shader to be used for subsequent render operations. /// </summary> public void Call() { GL.UseProgram(this.Program); } /// <summary> - /// Sets a uniform variable. + /// Sets a uniform variable. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, Vector Value) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform3(loc, (Vector3)Value); } /// <summary> - /// Sets a uniform matrix. + /// Sets a uniform matrix. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, ref Matrix4 Matrix) { GL.UniformMatrix4(GL.GetUniformLocation(this.Program, Name), true, ref Matrix); } /// <summary> - /// Sets a uniform texture. + /// Sets a uniform texture. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, TextureUnit Unit) { int loc = GL.GetUniformLocation(this.Program, Name); GL.Uniform1(loc, (int)Unit - (int)TextureUnit.Texture0); } /// <summary> - /// Sets a uniform integer. + /// Sets a uniform integer. Shader must be called beforehand. /// </summary> public void SetUniform(string Name, int Value) { GL.Uniform1(GL.GetUniformLocation(this.Program, Name), Value); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. /// </summary> public void Draw2DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height) { GL.FramebufferTexture2D(Framebuffer, Attachment, TextureTarget.Texture2D, Texture, 0); GL.Viewport(0, 0, Width, Height); this.DrawFull(); } /// <summary> /// Draws the shader in its current state to a frame buffer (and associated texture). Useful for precomputation. The "Layer" uniform is set /// in the shader to indicate depth. /// </summary> public void Draw3DFrame(FramebufferTarget Framebuffer, FramebufferAttachment Attachment, uint Texture, int Width, int Height, int Depth) { this.Call(); int luniform = GL.GetUniformLocation(this.Program, "Layer"); for (int t = 0; t < Depth; t++) { GL.FramebufferTexture3D(Framebuffer, Attachment, TextureTarget.Texture3D, Texture, 0, t); GL.Viewport(0, 0, Width, Height); GL.Uniform1(luniform, t); DrawQuad(); } } /// <summary> /// Runs the fragment shader on all pixels on the current viewport. /// </summary> public void DrawFull() { this.Call(); DrawQuad(); } /// <summary> /// Sets the rendering mode to default (removing all shaders). /// </summary> public static void Dismiss() { GL.UseProgram(0); } /// <summary> /// Draws a shape that includes the entire viewport. /// </summary> public static void DrawQuad() { GL.Begin(BeginMode.TriangleStrip); GL.Vertex2(-1.0, -1.0); GL.Vertex2(+1.0, -1.0); GL.Vertex2(-1.0, +1.0); GL.Vertex2(+1.0, +1.0); GL.End(); } /// <summary> /// Loads a shader program from a vertex and fragment shader in GLSL format. /// </summary> public static Shader Load(Alunite.Path Vertex, Alunite.Path Fragment) { Shader shade = new Shader(); int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); GL.ShaderSource(vshade, Path.ReadText(Vertex)); GL.ShaderSource(fshade, Path.ReadText(Fragment)); GL.CompileShader(vshade); GL.CompileShader(fshade); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Loads a shader from a single, defining _VERTEX_ for vertex shaders and _FRAGMENT_ for fragment shaders. /// </summary> public static Shader Load(Alunite.Path File) { return Load(File, new Dictionary<string, string>()); } /// <summary> /// More advanced shader loading function that will dynamically replace constants in the specified files. /// </summary> public static Shader Load(Alunite.Path File, Dictionary<string, string> Constants) { return Load(File, new PrecompilerInput() { Constants = Constants, LoadedFiles = new Dictionary<string, string[]>() }); } /// <summary> /// Loads a shader from the specified file using the specified input. /// </summary> public static Shader Load(Alunite.Path File, PrecompilerInput Input) { int vshade = GL.CreateShader(ShaderType.VertexShader); int fshade = GL.CreateShader(ShaderType.FragmentShader); StringBuilder vshadesource = new StringBuilder(); StringBuilder fshadesource = new StringBuilder(); PrecompilerInput vpce = Input.Copy(); PrecompilerInput fpce = Input.Copy(); vpce.Define("_VERTEX_", "1"); fpce.Define("_FRAGMENT_", "1"); BuildSource(File, vpce, vshadesource); GL.ShaderSource(vshade, vshadesource.ToString()); GL.CompileShader(vshade); vshadesource = null; BuildSource(File, fpce, fshadesource); GL.ShaderSource(fshade, fshadesource.ToString()); GL.CompileShader(fshade); fshadesource = null; Shader shade = new Shader(); shade.Program = GL.CreateProgram(); GL.AttachShader(shade.Program, vshade); GL.AttachShader(shade.Program, fshade); GL.LinkProgram(shade.Program); return shade; } /// <summary> /// Creates a new precompiler input set. /// </summary> public static PrecompilerInput CreatePrecompilerInput() { return new PrecompilerInput() { Constants = new Dictionary<string, string>(), LoadedFiles = new Dictionary<string, string[]>() }; } /// <summary> /// Input to the precompiler. /// </summary> public struct PrecompilerInput { public PrecompilerInput(Path File) { this.Constants = new Dictionary<string, string>(); this.LoadedFiles = new Dictionary<string, string[]>(); } /// <summary> /// Gets the file at the specified path. /// </summary> public string[] GetFile(Path Path) { string[] lines; if (!this.LoadedFiles.TryGetValue(Path.PathString, out lines)) { this.LoadedFiles[Path.PathString] = lines = File.ReadAllLines(Path.PathString); } return lines; } /// <summary> /// Creates a copy of this precompiler input with its own precompiler constants. /// </summary> public PrecompilerInput Copy() { return new PrecompilerInput() { LoadedFiles = this.LoadedFiles, Constants = new Dictionary<string, string>(this.Constants) }; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant, string Value) { this.Constants[Constant] = Value; } /// <summary> /// Defines a constant. /// </summary> public void Define(string Constant) { this.Constants[Constant] = "1"; } /// <summary> /// Undefines a constant. /// </summary> public void Undefine(string Constant) { this.Constants.Remove(Constant); } /// <summary> /// Constants defined for the precompiler. /// </summary> public Dictionary<string, string> Constants; /// <summary> /// The files loaded for the precompiler. /// </summary> public Dictionary<string, string[]> LoadedFiles; } /// <summary> /// Precompiles the source code defined by the lines with the specified constants defined. Outputs the precompiled source /// to the given stringbuilder. /// </summary> public static void BuildSource(Path File, PrecompilerInput Input, StringBuilder Output) { string[] lines = Input.GetFile(File); _ProcessBlock(((IEnumerable<string>)lines).GetEnumerator(), File, Input, Output, true); } /// <summary> /// Processes an ifdef/else/endif block where Interpret denotes the success of the if statement. Returns true if exited on an endif or false /// if exited on an else. /// </summary> private static bool _ProcessBlock(IEnumerator<string> LineEnumerator, Path File, PrecompilerInput Input, StringBuilder Output, bool Interpret) { while (LineEnumerator.MoveNext()) { string line = LineEnumerator.Current; // Does this line contain a directive? if (line.Length > 0) { if (line[0] == '#') { string[] lineparts = line.Split(' '); if (lineparts[0] == "#ifdef") { if (Interpret) { bool contains = Input.Constants.ContainsKey(lineparts[1]); if (!_ProcessBlock(LineEnumerator, File, Input, Output, contains)) { _ProcessBlock(LineEnumerator, File, Input, Output, !contains); } } else { if (!_ProcessBlock(LineEnumerator, File, Input, Output, false)) { _ProcessBlock(LineEnumerator, File, Input, Output, false); } } continue; } if (lineparts[0] == "#include") { if (Interpret) { string filepath = lineparts[1].Substring(1, lineparts[1].Length - 2); BuildSource(File.Parent.Lookup(filepath), Input, Output); } continue; } if (lineparts[0] == "#else") { return false; } if (lineparts[0] == "#endif") { return true; } if (Interpret) { if (lineparts[0] == "#define") { if (lineparts.Length > 2) { Input.Define(lineparts[1], lineparts[2]); } else { Input.Define(lineparts[1]); } continue; } if (lineparts[0] == "#undef") { Input.Undefine(lineparts[1]); continue; } Output.AppendLine(line); } } else { if (Interpret) { // Replace constants Dictionary<int, KeyValuePair<int, string>> matches = new Dictionary<int, KeyValuePair<int, string>>(); foreach (KeyValuePair<string, string> constant in Input.Constants) { int ind = line.IndexOf(constant.Key); while (ind >= 0) { int size = constant.Key.Length; KeyValuePair<int, string> lastmatch; if (matches.TryGetValue(ind, out lastmatch)) { if (lastmatch.Key < size) { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } } else { matches[ind] = new KeyValuePair<int, string>(size, constant.Value); } ind = line.IndexOf(constant.Key, ind + 1); } } if (matches.Count > 0) { int c = 0; var orderedmatches = new List<KeyValuePair<int, KeyValuePair<int, string>>>(matches); Sort.InPlace<KeyValuePair<int, KeyValuePair<int, string>>>((a, b) => a.Key > b.Key, orderedmatches); foreach (KeyValuePair<int, KeyValuePair<int, string>> match in orderedmatches) { Output.Append(line.Substring(c, match.Key - c)); Output.Append(match.Value.Value); c = match.Key + match.Value.Key; } Output.AppendLine(line.Substring(c)); } else { Output.AppendLine(line); } } } } } return true; } /// <summary> /// Index of the program of the shader. /// </summary> public int Program; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index 85fa1b9..d00fae5 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,122 +1,124 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; const vec3 SunColor = vec3(100.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ +#define _COMMON_ATMOSPHERE_TEXTURE_READ_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Inscatter.glsl" #define HORIZON_FIX float phaseFunctionR(float mu) { return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); } float phaseFunctionM(float mu) { return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); } vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); vec4 is = max(inscatter(mu, nu, r, mus), 0.0); #ifdef HORIZON_FIX //is.w *= smoothstep(0.00, 0.02, mus); #endif result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { // Direct sunlight float mu = dot(n, sol); vec3 direct = transmittance(Rg, mu) * max(mu, 0.0) * SunColor / Pi; return direct * SeaColor; } vec3 HDR(vec3 L) { L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); + //gl_FragColor = texture3D(Inscatter, vec3(Coords, 0.5)); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Common.glsl b/Resources/Shaders/Atmosphere/Precompute/Common.glsl index 6cb96f7..afe8fa4 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Common.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Common.glsl @@ -1,31 +1,81 @@ const float Pi = 3.14159265; const float Rt = 6420.0; const float Rg = 6360.0; // Rayleigh const float HR = 8.0; const vec3 betaR = vec3(5.8e-3, 1.35e-2, 3.31e-2); // Mie // DEFAULT const float HM = 1.2; const vec3 betaMSca = vec3(4e-3); const vec3 betaMEx = betaMSca / 0.9; const float mieG = 0.8; // Gets the length of the ray before either the atmospheric boundary, or ground, is hit. float limit(float r, float mu) { float atmosdis = -r * mu + sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); float groundp = r * r * (mu * mu - 1.0) + Rg * Rg; float res = atmosdis; if(groundp >= 0.0) { float grounddis = -r * mu - sqrt(groundp); if(grounddis >= 0.0) { res = grounddis; } } return res; } + +#ifdef _COMMON_ATMOSPHERE_TEXTURE_WRITE_ +void getAtmosphereTextureMuNuRMus(out float mu, out float nu, out float r, out float mus) { + float x = gl_FragCoord.x; + float y = gl_FragCoord.y; + float z = float(Layer); + + mus = mod(x, float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_MU_S) - 1.0); + nu = floor(x / float(ATMOSPHERE_RES_MU_S)) / (float(ATMOSPHERE_RES_NU) - 1.0); + mu = y / float(ATMOSPHERE_RES_MU); + r = z / float(ATMOSPHERE_RES_R); + +#ifdef ATMOSPHERE_TEXTURE_SIMPLE + mu = -1.0 + mu * 2.0; + nu = -1.0 + nu * 2.0; + mus = -1.0 + mus * 2.0; + r = Rg + r * (Rt - Rg); +#else + mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); + nu = -1.0 + nu * 2.0; + mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); + r = Rg + (r * r) * (Rt - Rg); +#endif +} +#endif + +#ifdef _COMMON_ATMOSPHERE_TEXTURE_READ_ +vec4 lookupAtmosphereTexture(sampler3D tex, float mu, float nu, float r, float mus) { +#ifdef ATMOSPHERE_TEXTURE_SIMPLE + float umu = (mu + 1.0) / 2.0; + float unu = (nu + 1.0) / 2.0; + float umus = (mus + 1.0) / 2.0; + float ur = (r - Rg) / (Rt - Rg); +#else + float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; + float unu = (nu + 1.0) / 2.0; + float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; + float ur = sqrt((r - Rg) / (Rt - Rg)); +#endif + + umus = max(1.0 / float(ATMOSPHERE_RES_MU_S), umus); + umus = min(1.0 - 1.0 / float(ATMOSPHERE_RES_MU_S), umus); + + float lerp = unu * (float(ATMOSPHERE_RES_NU) - 1.0); + unu = floor(lerp); + lerp = lerp - unu; + return texture3D(tex, vec3((unu + umus) / float(ATMOSPHERE_RES_NU), umu, ur)) * (1.0 - lerp) + + texture3D(tex, vec3((unu + umus + 1.0) / float(ATMOSPHERE_RES_NU), umu, ur)) * lerp; +} +#endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index 1965855..73fa94f 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,120 +1,79 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ +uniform int Layer; + #define _TRANSMITTANCE_USE_ +#define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 -uniform int Layer; - -void getInscatterMuNuRMus(out float mu, out float nu, out float r, out float mus) { - float x = gl_FragCoord.x; - float y = gl_FragCoord.y; - float z = float(Layer); - - mus = mod(x, float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_MU_S) - 1.0); - nu = floor(x / float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_NU) - 1.0); - mu = y / float(INSCATTER_RES_MU); - r = z / float(INSCATTER_RES_R); - -#ifdef INSCATTER_SIMPLE - mu = -1.0 + mu * 2.0; - nu = -1.0 + nu * 2.0; - mus = -1.0 + mus * 2.0; - r = Rg + r * (Rt - Rg); -#else - mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); - nu = -1.0 + nu * 2.0; - mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); - r = Rg + (r * r) * (Rt - Rg); -#endif -} - void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } #ifdef INITIAL #ifdef DELTA void main() { float mu, nu, r, mus; - getInscatterMuNuRMus(mu, nu, r, mus); + getAtmosphereTextureMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } gl_FragColor = vec4(ray, mie); if(r < Rg + 0.001 && mu < 0.0) { // Degeneracy fix gl_FragColor = vec4(0.0); } } #else uniform sampler3D InscatterDelta; void main() { - vec3 uvw = vec3(gl_FragCoord.xy, float(Layer) + 0.5) / vec3(ivec3(INSCATTER_RES_MU_S * INSCATTER_RES_NU, INSCATTER_RES_MU, INSCATTER_RES_R)); + vec3 uvw = vec3(gl_FragCoord.xy, float(Layer) + 0.5) / vec3(ivec3(ATMOSPHERE_RES_MU_S * ATMOSPHERE_RES_NU, ATMOSPHERE_RES_MU, ATMOSPHERE_RES_R)); gl_FragColor = texture3D(InscatterDelta, uvw); } #endif #else #endif #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { -#ifdef INSCATTER_SIMPLE - float umu = (mu + 1.0) / 2.0; - float unu = (nu + 1.0) / 2.0; - float umus = (mus + 1.0) / 2.0; - float ur = (r - Rg) / (Rt - Rg); -#else - float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; - float unu = (nu + 1.0) / 2.0; - float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; - float ur = sqrt((r - Rg) / (Rt - Rg)); -#endif - - umus = max(1.0 / float(INSCATTER_RES_MU_S), umus); - umus = min(1.0 - 1.0 / float(INSCATTER_RES_MU_S), umus); - - float lerp = unu * (float(INSCATTER_RES_NU) - 1.0); - unu = floor(lerp); - lerp = lerp - unu; - return texture3D(Inscatter, vec3((unu + umus) / float(INSCATTER_RES_NU), umu, ur)) * (1.0 - lerp) + - texture3D(Inscatter, vec3((unu + umus + 1.0) / float(INSCATTER_RES_NU), umu, ur)) * lerp; + return lookupAtmosphereTexture(Inscatter, mu, nu, r, mus); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl index 2eaf0ab..3cb7920 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl @@ -1,37 +1,58 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #include "Common.glsl" #include "Transmittance.glsl" void getIrradianceRMu(out float r, out float mu) { r = gl_FragCoord.y / float(IRRADIANCE_RES_R); mu = gl_FragCoord.x / float(IRRADIANCE_RES_MU); +#ifdef IRRADIANCE_SIMPLE r = Rg + r * (Rt - Rg); mu = -1.0 + mu * 2.0; +#else + r = Rg + r * r * (Rt - Rg); + mu = -1.0 + mu * 2.0; +#endif } #ifdef INITIAL #ifdef DELTA void main() { float r, mu; getIrradianceRMu(r, mu); gl_FragColor = vec4(transmittance(r, mu) * max(mu, 0.0), 0.0); } #else void main() { gl_FragColor = vec4(0.0); } #endif #else #endif +#endif + +#ifdef _IRRADIANCE_UV_ +vec2 getIrradianceUV(float r, float mu) { +#ifdef IRRADIANCE_SIMPLE + return vec2((mu + 1.0) / 2.0, (r - Rg) / (Rt - Rg)); +#else + return vec2((mu + 1.0) / 2.0, sqrt((r - Rg) / (Rt - Rg))); +#endif +} +#endif + +#ifdef _IRRADIANCE_USE_ + + + #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl new file mode 100644 index 0000000..76e263e --- /dev/null +++ b/Resources/Shaders/Atmosphere/Precompute/PointScatter.glsl @@ -0,0 +1,29 @@ +#ifdef _VERTEX_ +void main() +{ + gl_Position = gl_Vertex; +} +#endif + +#ifdef _FRAGMENT_ +#undef _FRAGMENT_ +uniform int Layer; +uniform sampler2D IrradianceDelta; +uniform sampler2D InscatterDelta; + +#define _TRANSMITTANCE_USE_ +#define _IRRADIANCE_UV_ +#define _COMMON_ATMOSPHERE_TEXTURE_WRITE_ +#define _COMMON_ATMOSPHERE_TEXTURE_READ_ +#include "Common.glsl" +#include "Transmittance.glsl" +#include "Irradiance.glsl" + +void main() +{ + float mu, nu, r, mus; + getAtmosphereTextureMuNuRMus(mu, nu, r, mus); + gl_FragColor = texture2D(IrradianceDelta, getIrradianceUV(r, mus)); +} + +#endif \ No newline at end of file
dzamkov/Alunite-old
2e12d71561662219e1ee018ed44ef35bced3ddf8
Splitting up textures as I should have earlier
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 662ac4c..f1c9c75 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,302 +1,320 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { Shader.PrecompilerInput pci = _DefineCommon(); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); - // Set precompiler inputs for all shaders to be loaded + // Load shaders. Shader.PrecompilerInput transmittancepci = pci.Copy(); + Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); + + Shader.PrecompilerInput irradianceinitialdeltapci = pci.Copy(); + irradianceinitialdeltapci.Define("INITIAL"); + irradianceinitialdeltapci.Define("DELTA"); + Shader irradianceinitialdelta = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialdeltapci); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); + Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); - Shader.PrecompilerInput irradiancepci = pci.Copy(); + Shader.PrecompilerInput inscatterinitialdeltapci = pci.Copy(); + inscatterinitialdeltapci.Define("INITIAL"); + inscatterinitialdeltapci.Define("DELTA"); + Shader inscatterinitialdelta = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialdeltapci); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); - - // Load shaders - Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); - Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); // Initialize textures - TextureUnit transunit = TextureUnit.Texture0; GL.ActiveTexture(transunit); this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); - TextureUnit deltairrunit = TextureUnit.Texture1; GL.ActiveTexture(deltairrunit); this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); - TextureUnit inscaunit = TextureUnit.Texture2; GL.ActiveTexture(inscaunit); this._InscatterTexture = Texture.Initialize3D(InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR, Texture.RGBA16Float); + Texture irrdelta = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); + Texture insdelta = Texture.Initialize3D(InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR, Texture.RGBA16Float); + + this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); + + insdelta.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture5); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); // Create delta irradiance texture (ground lighting cause by sun). - irradianceinitial.SetUniform("Transmittance", transunit); - irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, - this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); + irradianceinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); + irradianceinitialdelta.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + irrdelta.ID, IrradianceResMu, IrradianceResR); // Create delta inscatter texture (light from the atmosphere). - inscatterinitial.SetUniform("Transmittance", transunit); + inscatterinitialdelta.SetUniform("Transmittance", TextureUnit.Texture0); + inscatterinitialdelta.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + insdelta.ID, InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR); + + // Initialize irradiance to zero + irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, + this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); + + // Copy delta inscatter to inscatter + inscatterinitial.SetUniform("InscatterDelta", TextureUnit.Texture5); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._InscatterTexture.ID, InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); } private const int InscatterResR = 32; private const int InscatterResMu = 256; private const int InscatterResMuS = 32; private const int InscatterResNu = 8; private const int IrradianceResR = 16; private const int IrradianceResMu = 64; private const int TransmittanceResR = 64; private const int TransmittanceResMu = 256; /// <summary> /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source /// input. /// </summary> private static Shader.PrecompilerInput _DefineCommon() { Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); res.Define("INSCATTER_RES_R", InscatterResR.ToString()); res.Define("INSCATTER_RES_MU", InscatterResMu.ToString()); res.Define("INSCATTER_RES_MU_S", InscatterResMuS.ToString()); res.Define("INSCATTER_RES_NU", InscatterResNu.ToString()); res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); return res; } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } private Texture _InscatterTexture; private Texture _TransmittanceTexture; private Texture _IrradianceTexture; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index c79dbe8..1965855 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,108 +1,120 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 uniform int Layer; void getInscatterMuNuRMus(out float mu, out float nu, out float r, out float mus) { float x = gl_FragCoord.x; float y = gl_FragCoord.y; float z = float(Layer); mus = mod(x, float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_MU_S) - 1.0); nu = floor(x / float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_NU) - 1.0); mu = y / float(INSCATTER_RES_MU); r = z / float(INSCATTER_RES_R); #ifdef INSCATTER_SIMPLE mu = -1.0 + mu * 2.0; nu = -1.0 + nu * 2.0; mus = -1.0 + mus * 2.0; r = Rg + r * (Rt - Rg); #else mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); nu = -1.0 + nu * 2.0; mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); r = Rg + (r * r) * (Rt - Rg); #endif } void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } +#ifdef INITIAL +#ifdef DELTA void main() { float mu, nu, r, mus; getInscatterMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } gl_FragColor = vec4(ray, mie); if(r < Rg + 0.001 && mu < 0.0) { // Degeneracy fix gl_FragColor = vec4(0.0); } } +#else +uniform sampler3D InscatterDelta; +void main() { + vec3 uvw = vec3(gl_FragCoord.xy, float(Layer) + 0.5) / vec3(ivec3(INSCATTER_RES_MU_S * INSCATTER_RES_NU, INSCATTER_RES_MU, INSCATTER_RES_R)); + gl_FragColor = texture3D(InscatterDelta, uvw); +} +#endif +#else + +#endif #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { #ifdef INSCATTER_SIMPLE float umu = (mu + 1.0) / 2.0; float unu = (nu + 1.0) / 2.0; float umus = (mus + 1.0) / 2.0; float ur = (r - Rg) / (Rt - Rg); #else float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; float unu = (nu + 1.0) / 2.0; float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; float ur = sqrt((r - Rg) / (Rt - Rg)); #endif umus = max(1.0 / float(INSCATTER_RES_MU_S), umus); umus = min(1.0 - 1.0 / float(INSCATTER_RES_MU_S), umus); float lerp = unu * (float(INSCATTER_RES_NU) - 1.0); unu = floor(lerp); lerp = lerp - unu; return texture3D(Inscatter, vec3((unu + umus) / float(INSCATTER_RES_NU), umu, ur)) * (1.0 - lerp) + texture3D(Inscatter, vec3((unu + umus + 1.0) / float(INSCATTER_RES_NU), umu, ur)) * lerp; } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl index 4962f1c..2eaf0ab 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Irradiance.glsl @@ -1,28 +1,37 @@ -uniform float Dummy; - #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #include "Common.glsl" #include "Transmittance.glsl" void getIrradianceRMu(out float r, out float mu) { r = gl_FragCoord.y / float(IRRADIANCE_RES_R); mu = gl_FragCoord.x / float(IRRADIANCE_RES_MU); r = Rg + r * (Rt - Rg); mu = -1.0 + mu * 2.0; } +#ifdef INITIAL +#ifdef DELTA void main() { float r, mu; getIrradianceRMu(r, mu); gl_FragColor = vec4(transmittance(r, mu) * max(mu, 0.0), 0.0); } +#else +void main() { + gl_FragColor = vec4(0.0); +} +#endif +#else + + +#endif #endif \ No newline at end of file
dzamkov/Alunite-old
0521dedc1b5ca0c365fb3300d7603f5e6847d1a8
Ground-level degeneracy fixed
diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index c59864d..c79dbe8 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,102 +1,108 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 uniform int Layer; void getInscatterMuNuRMus(out float mu, out float nu, out float r, out float mus) { float x = gl_FragCoord.x; float y = gl_FragCoord.y; float z = float(Layer); mus = mod(x, float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_MU_S) - 1.0); nu = floor(x / float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_NU) - 1.0); mu = y / float(INSCATTER_RES_MU); r = z / float(INSCATTER_RES_R); #ifdef INSCATTER_SIMPLE mu = -1.0 + mu * 2.0; nu = -1.0 + nu * 2.0; mus = -1.0 + mus * 2.0; r = Rg + r * (Rt - Rg); #else mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); nu = -1.0 + nu * 2.0; mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); r = Rg + (r * r) * (Rt - Rg); #endif } void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } void main() { float mu, nu, r, mus; getInscatterMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } - gl_FragColor = vec4(ray, mie); + gl_FragColor = vec4(ray, mie); + + if(r < Rg + 0.001 && mu < 0.0) + { + // Degeneracy fix + gl_FragColor = vec4(0.0); + } } #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { #ifdef INSCATTER_SIMPLE float umu = (mu + 1.0) / 2.0; float unu = (nu + 1.0) / 2.0; float umus = (mus + 1.0) / 2.0; float ur = (r - Rg) / (Rt - Rg); #else float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; float unu = (nu + 1.0) / 2.0; float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; float ur = sqrt((r - Rg) / (Rt - Rg)); #endif umus = max(1.0 / float(INSCATTER_RES_MU_S), umus); umus = min(1.0 - 1.0 / float(INSCATTER_RES_MU_S), umus); float lerp = unu * (float(INSCATTER_RES_NU) - 1.0); unu = floor(lerp); lerp = lerp - unu; return texture3D(Inscatter, vec3((unu + umus) / float(INSCATTER_RES_NU), umu, ur)) * (1.0 - lerp) + texture3D(Inscatter, vec3((unu + umus + 1.0) / float(INSCATTER_RES_NU), umu, ur)) * lerp; } #endif \ No newline at end of file
dzamkov/Alunite-old
e54157d4ee45c47f14303bdacbaf4acf2d81042a
Horizon fixed and lesson learned, Eric Bruneton probably knew what he was doing and deviating from his suggestions is a bad idea
diff --git a/Alunite/Window.cs b/Alunite/Window.cs index c465bb8..1744edf 100644 --- a/Alunite/Window.cs +++ b/Alunite/Window.cs @@ -1,109 +1,110 @@ using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Drawing; namespace Alunite { using CNVVBO = VBO<ColorNormalVertex, ColorNormalVertex.Model>; using NVVBO = VBO<NormalVertex, NormalVertex.Model>; using VVBO = VBO<Vertex, Vertex.Model>; /// <summary> /// Main program window /// </summary> public class Window : GameWindow { public Window(Planet Planet) : base(640, 480, GraphicsMode.Default, "Alunite") { this.WindowState = WindowState.Maximized; this.VSync = VSyncMode.On; this.TargetRenderFrequency = 100.0; this.TargetUpdateFrequency = 500.0; GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.ColorMaterial); GL.Disable(EnableCap.Texture2D); GL.Enable(EnableCap.DepthTest); GL.ColorMaterial(MaterialFace.FrontAndBack, ColorMaterialParameter.Diffuse); GL.Enable(EnableCap.Light0); GL.Light(LightName.Light0, LightParameter.Position, new Vector4(1.0f, 1.0f, 1.0f, 0.0f)); GL.Light(LightName.Light0, LightParameter.Diffuse, Color.RGB(0.6, 0.6, 0.6)); GL.Light(LightName.Light0, LightParameter.Ambient, Color.RGB(0.1, 0.1, 0.1)); Path resources = Path.ApplicationStartup.Parent.Parent.Parent["Resources"]; Path shaders = resources["Shaders"]; this._Planet = Planet; this._Planet.Load(shaders); this._Height = 20000.0; } protected override void OnRenderFrame(FrameEventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); GL.ClearColor(0.0f, 0.0f, 0.0f, 1.0f); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); double cosx = Math.Cos(this._XRot); Vector eyepos = new Vector(Math.Sin(this._ZRot) * cosx, Math.Cos(this._ZRot) * cosx, Math.Sin(this._XRot)) * this._Height; Matrix4 proj = Matrix4.CreatePerspectiveFieldOfView(2.2f, (float)this.Width / (float)this.Height, 0.1f, 10000.0f); Matrix4 view = Matrix4.LookAt( new Vector3(), -(Vector3)eyepos, new Vector3(0.0f, 0.0f, 1.0f)); if (this._SunsetMode) { + double h = 6360 + this._Height / 20000.0; view = Matrix4.LookAt( - new Vector3(0.0f, 6363.0f, 0.0f), - new Vector3(3.0f, 6363.0f, 0.0f), + new Vector3(0.0f, (float)h, 0.0f), + new Vector3(3.0f, (float)h + 0.5f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f)); - eyepos = new Vector(0.0, 6363.0, 0.0); + eyepos = new Vector(0.0, h, 0.0); } this._Planet.Render(proj, view, eyepos, Vector.Normalize(new Vector(Math.Sin(this._SunAngle), Math.Cos(this._SunAngle), 0.0))); this.SwapBuffers(); } protected override void OnUpdateFrame(FrameEventArgs e) { double updatetime = e.Time; double zoomfactor = Math.Pow(0.8, updatetime); if (this.Keyboard[Key.W]) this._XRot += updatetime; if (this.Keyboard[Key.A]) this._ZRot += updatetime; if (this.Keyboard[Key.S]) this._XRot -= updatetime; if (this.Keyboard[Key.D]) this._ZRot -= updatetime; if (this.Keyboard[Key.Q]) this._Height *= zoomfactor; if (this.Keyboard[Key.E]) this._Height /= zoomfactor; if (this.Keyboard[Key.Z]) this._SunAngle += updatetime * 0.5; if (this.Keyboard[Key.X]) this._SunAngle -= updatetime * 0.5; if (this.Keyboard[Key.C]) this._SunsetMode = true; else this._SunsetMode = false; if (this.Keyboard[Key.Escape]) this.Close(); this._XRot = Math.Min(Math.PI / 2.02, Math.Max(Math.PI / -2.02, this._XRot)); } protected override void OnResize(EventArgs e) { GL.Viewport(0, 0, this.Width, this.Height); } private bool _SunsetMode; private double _Height; private double _XRot; private double _ZRot; private double _SunAngle; private Planet _Planet; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index ff8ab82..85fa1b9 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,123 +1,122 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; const vec3 SunColor = vec3(100.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Inscatter.glsl" #define HORIZON_FIX float phaseFunctionR(float mu) { return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); } float phaseFunctionM(float mu) { return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); } vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); + vec4 is = max(inscatter(mu, nu, r, mus), 0.0); - vec4 is = inscatter(mu, nu, r, mus); #ifdef HORIZON_FIX - is.w *= smoothstep(0.00, 0.02, mus); + //is.w *= smoothstep(0.00, 0.02, mus); #endif result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { // Direct sunlight float mu = dot(n, sol); vec3 direct = transmittance(Rg, mu) * max(mu, 0.0) * SunColor / Pi; return direct * SeaColor; } vec3 HDR(vec3 L) { L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); - //gl_FragColor = texture2D(Transmittance, Coords); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Transmittance.glsl b/Resources/Shaders/Atmosphere/Precompute/Transmittance.glsl index 4f5f70e..8eaf48a 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Transmittance.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Transmittance.glsl @@ -1,90 +1,90 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #include "Common.glsl" #define TRANSMITTANCE_INTEGRAL_SAMPLES 500 void getTransmittanceRMu(out float r, out float mu) { r = gl_FragCoord.y / float(TRANSMITTANCE_RES_R); mu = gl_FragCoord.x / float(TRANSMITTANCE_RES_MU); #ifdef TRANSMITTANCE_SIMPLE r = Rg + r * (Rt - Rg); mu = -1.0 + mu * 2.0; #else r = Rg + (r * r) * (Rt - Rg); mu = -0.15 + tan(1.5 * mu) / tan(1.5) * (1.0 + 0.15); #endif } float opticalDepth(float H, float r, float mu) { float result = 0.0; float dx = limit(r, mu) / float(TRANSMITTANCE_INTEGRAL_SAMPLES); float acrossdelta = sqrt(1 - mu * mu); float updelta = mu; for (int i = 1; i <= TRANSMITTANCE_INTEGRAL_SAMPLES; ++i) { float xj = float(i) * dx; float across = acrossdelta * xj; float up = updelta * xj; float ir = sqrt(across * across + (up + r) * (up + r)); result += exp(-(ir - Rg) / H) * dx; } - return result; + return mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? 1e9 : result; } void main() { float r, mu; getTransmittanceRMu(r, mu); vec3 depth = betaR * opticalDepth(HR, r, mu) + betaMEx * opticalDepth(HM, r, mu); gl_FragColor = vec4(exp(-depth), 0.0); } #endif #ifdef _TRANSMITTANCE_USE_ uniform sampler2D Transmittance; vec2 getTransmittanceUV(float r, float mu) { #ifdef TRANSMITTANCE_SIMPLE float ur = (r - Rg) / (Rt - Rg); float umu = (mu + 1.0) / 2.0; #else float ur = sqrt((r - Rg) / (Rt - Rg)); float umu = atan((mu + 0.15) / (1.0 + 0.15) * tan(1.5)) / 1.5; #endif return vec2(umu, ur); } // Gets transmittance with the atmosphere (inaccurate when hitting ground). vec3 transmittance(float r, float mu) { vec2 uv = getTransmittanceUV(r, mu); return texture2D(Transmittance, uv).rgb; } // Gets transmittance up to a certain distance on a ray. vec3 transmittance(float r, float mu, float t) { vec3 result = vec3(0.0); float r1 = sqrt(r * r + t * t + 2.0 * r * mu * t); float mu1 = (r * mu + t) / r1; if (mu > 0.0) { result = min(transmittance(r, mu) / transmittance(r1, mu1), 1.0); } else { result = min(transmittance(r1, -mu1) / transmittance(r, -mu), 1.0); } return result; } // Gets transmittance with atmosphere, or zero if hitting ground. vec3 transmittanceWithShadow(float r, float mu) { return mu < -sqrt(1.0 - (Rg / r) * (Rg / r)) ? vec3(0.0) : transmittance(r, mu); } #endif \ No newline at end of file
dzamkov/Alunite-old
8c1dcc53c7825123d2f0fcd62a5bee6029b0c74f
An acceptable increase in resolution
diff --git a/Alunite/Planet.cs b/Alunite/Planet.cs index 38ad415..662ac4c 100644 --- a/Alunite/Planet.cs +++ b/Alunite/Planet.cs @@ -1,302 +1,302 @@ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace Alunite { /// <summary> /// Really big thing. /// </summary> public class Planet { public Planet() { this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); // Initialize with an icosahedron. Primitive icosa = Primitive.Icosahedron; this._Vertices = new List<Vector>(icosa.Vertices); foreach (Triangle<int> tri in icosa.Triangles) { this._AddTriangle(tri); } this._Subdivide(); this._Subdivide(); this._Subdivide(); } /// <summary> /// Creates a diagram for the current state of the planet. /// </summary> public Diagram CreateDiagram() { Diagram dia = new Diagram(this._Vertices); foreach (Triangle<int> tri in this._Triangles) { dia.SetBorderedTriangle(tri, Color.RGB(0.0, 0.2, 1.0), Color.RGB(0.3, 1.0, 0.3), 4.0); } return dia; } /// <summary> /// Creates a vertex buffer representation of the current state of the planet. /// </summary> public VBO<NormalVertex, NormalVertex.Model> CreateVBO() { NormalVertex[] verts = new NormalVertex[this._Vertices.Count]; for (int t = 0; t < verts.Length; t++) { // Lol, position and normal are the same. Vector pos = this._Vertices[t]; verts[t].Position = pos; verts[t].Normal = pos; } return new VBO<NormalVertex, NormalVertex.Model>( NormalVertex.Model.Singleton, verts, verts.Length, this._Triangles, this._Triangles.Count); } public void Load(Alunite.Path ShaderPath) { Shader.PrecompilerInput pci = _DefineCommon(); Path atmosphere = ShaderPath["Atmosphere"]; Path precompute = atmosphere["Precompute"]; this._PlanetShader = Shader.Load(atmosphere["Planet.glsl"], pci.Copy()); // Atmospheric scattering precompution uint fbo; GL.GenFramebuffers(1, out fbo); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, fbo); GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); // Set precompiler inputs for all shaders to be loaded Shader.PrecompilerInput transmittancepci = pci.Copy(); Shader.PrecompilerInput irradianceinitialpci = pci.Copy(); irradianceinitialpci.Define("INITIAL"); Shader.PrecompilerInput irradiancepci = pci.Copy(); Shader.PrecompilerInput inscatterinitialpci = pci.Copy(); inscatterinitialpci.Define("INITIAL"); // Load shaders Shader transmittance = Shader.Load(precompute["Transmittance.glsl"], transmittancepci); Shader irradianceinitial = Shader.Load(precompute["Irradiance.glsl"], irradianceinitialpci); Shader inscatterinitial = Shader.Load(precompute["Inscatter.glsl"], inscatterinitialpci); // Initialize textures TextureUnit transunit = TextureUnit.Texture0; GL.ActiveTexture(transunit); this._TransmittanceTexture = Texture.Initialize2D(TransmittanceResMu, TransmittanceResR, Texture.RGB16Float); TextureUnit deltairrunit = TextureUnit.Texture1; GL.ActiveTexture(deltairrunit); this._IrradianceTexture = Texture.Initialize2D(IrradianceResMu, IrradianceResR, Texture.RGB16Float); TextureUnit inscaunit = TextureUnit.Texture2; GL.ActiveTexture(inscaunit); this._InscatterTexture = Texture.Initialize3D(InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR, Texture.RGBA16Float); // Create transmittance texture (information about how light is filtered through the atmosphere). transmittance.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._TransmittanceTexture.ID, TransmittanceResMu, TransmittanceResR); // Create delta irradiance texture (ground lighting cause by sun). irradianceinitial.SetUniform("Transmittance", transunit); irradianceinitial.Draw2DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._IrradianceTexture.ID, IrradianceResMu, IrradianceResR); // Create delta inscatter texture (light from the atmosphere). inscatterinitial.SetUniform("Transmittance", transunit); inscatterinitial.Draw3DFrame(FramebufferTarget.FramebufferExt, FramebufferAttachment.ColorAttachment0Ext, this._InscatterTexture.ID, InscatterResMuS * InscatterResNu, InscatterResMu, InscatterResR); GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0); } private const int InscatterResR = 32; - private const int InscatterResMu = 128; + private const int InscatterResMu = 256; private const int InscatterResMuS = 32; private const int InscatterResNu = 8; private const int IrradianceResR = 16; private const int IrradianceResMu = 64; private const int TransmittanceResR = 64; private const int TransmittanceResMu = 256; /// <summary> /// Creates a shader precompiler input with common atmosphere shader paramters from the specified source /// input. /// </summary> private static Shader.PrecompilerInput _DefineCommon() { Shader.PrecompilerInput res = Shader.CreatePrecompilerInput(); res.Define("INSCATTER_RES_R", InscatterResR.ToString()); res.Define("INSCATTER_RES_MU", InscatterResMu.ToString()); res.Define("INSCATTER_RES_MU_S", InscatterResMuS.ToString()); res.Define("INSCATTER_RES_NU", InscatterResNu.ToString()); res.Define("IRRADIANCE_RES_R", IrradianceResR.ToString()); res.Define("IRRADIANCE_RES_MU", IrradianceResMu.ToString()); res.Define("TRANSMITTANCE_RES_R", TransmittanceResR.ToString()); res.Define("TRANSMITTANCE_RES_MU", TransmittanceResMu.ToString()); return res; } public void Render(Matrix4 Proj, Matrix4 View, Vector EyePosition, Vector SunDirection) { Proj.Invert(); //View.Invert(); GL.LoadIdentity(); this._InscatterTexture.SetUnit(TextureTarget.Texture3D, TextureUnit.Texture1); this._TransmittanceTexture.SetUnit(TextureTarget.Texture2D, TextureUnit.Texture0); this._PlanetShader.SetUniform("Inscatter", TextureUnit.Texture1); this._PlanetShader.SetUniform("Transmittance", TextureUnit.Texture0); this._PlanetShader.SetUniform("ProjInverse", ref Proj); this._PlanetShader.SetUniform("ViewInverse", ref View); this._PlanetShader.SetUniform("EyePosition", EyePosition); this._PlanetShader.SetUniform("SunDirection", SunDirection); this._PlanetShader.DrawFull(); } /// <summary> /// Adds a triangle to the planet. /// </summary> private void _AddTriangle(Triangle<int> Triangle) { this._Triangles.Add(Triangle); foreach (Segment<int> seg in Triangle.Segments) { this._SegmentTriangles[seg] = Triangle; } } /// <summary> /// Dereferences a triangle in the primitive. /// </summary> public Triangle<Vector> Dereference(Triangle<int> Triangle) { return new Triangle<Vector>( this._Vertices[Triangle.A], this._Vertices[Triangle.B], this._Vertices[Triangle.C]); } /// <summary> /// Splits the triangle at the specified point while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle, Vector Point) { int npoint = this._Vertices.Count; this._Vertices.Add(Point); this._Triangles.Remove(Triangle); // Maintain delaunay property by flipping encroached triangles. List<Segment<int>> finalsegs = new List<Segment<int>>(); Stack<Segment<int>> possiblealtersegs = new Stack<Segment<int>>(); possiblealtersegs.Push(new Segment<int>(Triangle.A, Triangle.B)); possiblealtersegs.Push(new Segment<int>(Triangle.B, Triangle.C)); possiblealtersegs.Push(new Segment<int>(Triangle.C, Triangle.A)); while (possiblealtersegs.Count > 0) { Segment<int> seg = possiblealtersegs.Pop(); Triangle<int> othertri = Alunite.Triangle.Align(this._SegmentTriangles[seg.Flip], seg.Flip).Value; int otherpoint = othertri.Vertex; Triangle<Vector> othervectri = this.Dereference(othertri); Vector othercircumcenter = Alunite.Triangle.Normal(othervectri); double othercircumangle = Vector.Dot(othercircumcenter, othervectri.A); // Check if triangle encroachs the new point double npointangle = Vector.Dot(othercircumcenter, Point); if (npointangle > othercircumangle) { this._Triangles.Remove(othertri); possiblealtersegs.Push(new Segment<int>(othertri.A, othertri.B)); possiblealtersegs.Push(new Segment<int>(othertri.C, othertri.A)); } else { finalsegs.Add(seg); } } foreach (Segment<int> seg in finalsegs) { this._AddTriangle(new Triangle<int>(npoint, seg)); } } /// <summary> /// Splits a triangle at its circumcenter while maintaining the delaunay property. /// </summary> private void _SplitTriangle(Triangle<int> Triangle) { Triangle<Vector> vectri = this.Dereference(Triangle); Vector circumcenter = Alunite.Triangle.Normal(vectri); this._SplitTriangle(Triangle, circumcenter); } /// <summary> /// Subdivides the entire planet, quadrupling the amount of triangles. /// </summary> private void _Subdivide() { var oldtris = this._Triangles; var oldsegs = this._SegmentTriangles; this._Triangles = new HashSet<Triangle<int>>(); this._SegmentTriangles = new Dictionary<Segment<int>, Triangle<int>>(); Dictionary<Segment<int>, int> newsegs = new Dictionary<Segment<int>, int>(); foreach (Triangle<int> tri in oldtris) { int[] midpoints = new int[3]; Segment<int>[] segs = tri.Segments; for (int t = 0; t < 3; t++) { Segment<int> seg = segs[t]; int midpoint; if (!newsegs.TryGetValue(seg, out midpoint)) { midpoint = this._Vertices.Count; this._Vertices.Add( Vector.Normalize( Segment.Midpoint( new Segment<Vector>( this._Vertices[seg.A], this._Vertices[seg.B])))); newsegs.Add(seg.Flip, midpoint); } else { newsegs.Remove(seg); } midpoints[t] = midpoint; } this._AddTriangle(new Triangle<int>(tri.A, midpoints[0], midpoints[2])); this._AddTriangle(new Triangle<int>(tri.B, midpoints[1], midpoints[0])); this._AddTriangle(new Triangle<int>(tri.C, midpoints[2], midpoints[1])); this._AddTriangle(new Triangle<int>(midpoints[0], midpoints[1], midpoints[2])); } } private Texture _InscatterTexture; private Texture _TransmittanceTexture; private Texture _IrradianceTexture; private Shader _PlanetShader; private List<Vector> _Vertices; private HashSet<Triangle<int>> _Triangles; private Dictionary<Segment<int>, Triangle<int>> _SegmentTriangles; } } \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Planet.glsl b/Resources/Shaders/Atmosphere/Planet.glsl index 8a84479..ff8ab82 100644 --- a/Resources/Shaders/Atmosphere/Planet.glsl +++ b/Resources/Shaders/Atmosphere/Planet.glsl @@ -1,118 +1,123 @@ uniform vec3 EyePosition; uniform vec3 SunDirection; uniform mat4 ProjInverse; uniform mat4 ViewInverse; const vec3 SunColor = vec3(100.0); const vec3 SeaColor = vec3(0.0, 0.0, 0.2); const vec3 AtmoColor = vec3(0.7, 0.7, 0.9); const float Radius = 1.0; varying vec2 Coords; varying vec3 Ray; varying vec3 Position; #ifdef _VERTEX_ void main() { Coords = gl_Vertex.xy * 0.5 + 0.5; Ray = (ViewInverse * vec4((ProjInverse * gl_Vertex).xyz, 1.0)).xyz; gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #define _INSCATTER_USE_ #include "Precompute/Common.glsl" #include "Precompute/Transmittance.glsl" #include "Precompute/Inscatter.glsl" +#define HORIZON_FIX + float phaseFunctionR(float mu) { return (3.0 / (16.0 * Pi)) * (1.0 + mu * mu); } float phaseFunctionM(float mu) { return 1.5 * 1.0 / (4.0 * Pi) * (1.0 - mieG * mieG) * pow(1.0 + (mieG * mieG) - 2.0 * mieG * mu, -3.0 / 2.0) * (1.0 + mu * mu) / (2.0 + mieG * mieG); } vec3 getMie(vec4 rayMie) { return rayMie.rgb * rayMie.w / max(rayMie.r, 1e-4) * (betaR.r / betaR); } vec3 atmoColor(float t, vec3 x, vec3 v, vec3 sol) { vec3 result = vec3(0.0); float r = length(x); float mu = dot(x, v) / r; float d = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rt * Rt); if (d > 0.0) { x += d * v; t -= d; mu = (r * mu + d) / Rt; r = Rt; } if (r <= Rt) { // if ray intersects atmosphere float nu = dot(v, sol); float mus = dot(x, sol) / r; float phaseR = phaseFunctionR(nu); float phaseM = phaseFunctionM(nu); - vec4 is = inscatter(mu, nu, r, mus); + vec4 is = inscatter(mu, nu, r, mus); +#ifdef HORIZON_FIX + is.w *= smoothstep(0.00, 0.02, mus); +#endif result = max(is.rgb * phaseR + getMie(is) * phaseM, 0.0); } return result * SunColor; } vec3 sunColor(vec3 v, vec3 sol) { return step(cos(Pi / 180.0), dot(v, sol)) * SunColor; } vec3 groundColor(vec3 n, vec3 sol) { // Direct sunlight float mu = dot(n, sol); vec3 direct = transmittance(Rg, mu) * max(mu, 0.0) * SunColor / Pi; return direct * SeaColor; } vec3 HDR(vec3 L) { L = L * 0.4; L.r = L.r < 1.413 ? pow(L.r * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.r); L.g = L.g < 1.413 ? pow(L.g * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.g); L.b = L.b < 1.413 ? pow(L.b * 0.38317, 1.0 / 2.2) : 1.0 - exp(-L.b); return L; } void main() { vec3 v = normalize(Ray); vec3 sol = SunDirection; vec3 x = EyePosition; float r = length(x); float mu = dot(x, v) / r; // Find where the ray intersects the planet. float t = -r * mu - sqrt(r * r * (mu * mu - 1.0) + Rg * Rg); vec3 hit = x + v * t; vec3 atmocolor = atmoColor(t, x, v, sol); vec3 groundcolor = vec3(0.0); vec3 suncolor = vec3(0.0); if(t > 0.0) { vec3 hitnorm = normalize(hit); - groundcolor = groundColor(hitnorm, sol); + groundcolor = groundColor(hitnorm, sol) * transmittance(r, mu, t); } else { suncolor = sunColor(v, sol); } gl_FragColor = vec4(HDR(groundcolor + suncolor + atmocolor), 1.0); //gl_FragColor = texture2D(Transmittance, Coords); } #endif \ No newline at end of file diff --git a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl index 22b324e..c59864d 100644 --- a/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl +++ b/Resources/Shaders/Atmosphere/Precompute/Inscatter.glsl @@ -1,102 +1,102 @@ #ifdef _VERTEX_ void main() { gl_Position = gl_Vertex; } #endif #ifdef _FRAGMENT_ #undef _FRAGMENT_ #define _TRANSMITTANCE_USE_ #include "Common.glsl" #include "Transmittance.glsl" #define INSCATTER_INTEGRAL_SAMPLES 50 uniform int Layer; void getInscatterMuNuRMus(out float mu, out float nu, out float r, out float mus) { float x = gl_FragCoord.x; float y = gl_FragCoord.y; float z = float(Layer); mus = mod(x, float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_MU_S) - 1.0); nu = floor(x / float(INSCATTER_RES_MU_S)) / (float(INSCATTER_RES_NU) - 1.0); mu = y / float(INSCATTER_RES_MU); r = z / float(INSCATTER_RES_R); #ifdef INSCATTER_SIMPLE mu = -1.0 + mu * 2.0; nu = -1.0 + nu * 2.0; mus = -1.0 + mus * 2.0; r = Rg + r * (Rt - Rg); #else - mu = tan((mu * 2.0) - 1.0) / tan(1.0); + mu = tan(((mu * 2.0) - 1.0) * 1.2) / tan(1.2); nu = -1.0 + nu * 2.0; mus = tan((2.0 * mus - 1.0 + 0.26) * 1.1) / tan(1.26 * 1.1); r = Rg + (r * r) * (Rt - Rg); #endif } void pointScatter(float r, float mu, float mus, float nu, float t, out vec3 ray, out float mie) { ray = vec3(0.0); mie = 0.0; float ri = sqrt(r * r + t * t + 2.0 * r * mu * t); float musi = (nu * t + mus * r) / ri; ri = max(Rg, ri); if (musi >= -sqrt(1.0 - Rg * Rg / (ri * ri))) { vec3 tra = transmittance(r, mu, t) * transmittanceWithShadow(ri, musi); ray = exp(-(ri - Rg) / HR) * tra; mie = exp(-(ri - Rg) / HM) * tra; } ray *= betaR; mie *= betaMSca; } void main() { float mu, nu, r, mus; getInscatterMuNuRMus(mu, nu, r, mus); vec3 ray = vec3(0.0); float mie = 0.0; float dx = limit(r, mu) / float(INSCATTER_INTEGRAL_SAMPLES); for (int i = 1; i <= INSCATTER_INTEGRAL_SAMPLES; ++i) { vec3 dray; float dmie; pointScatter(r, mu, mus, nu, dx * float(i), dray, dmie); ray += dray * dx; mie += dmie * dx; } gl_FragColor = vec4(ray, mie); } #endif #ifdef _INSCATTER_USE_ uniform sampler3D Inscatter; vec4 inscatter(float mu, float nu, float r, float mus) { #ifdef INSCATTER_SIMPLE float umu = (mu + 1.0) / 2.0; float unu = (nu + 1.0) / 2.0; float umus = (mus + 1.0) / 2.0; float ur = (r - Rg) / (Rt - Rg); #else - float umu = (atan(mu * tan(1.0)) + 1.0) * 0.5; + float umu = (atan(mu * tan(1.2)) / 1.2 + 1.0) * 0.5; float unu = (nu + 1.0) / 2.0; float umus = (atan(mus * tan(1.26 * 1.1)) / 1.1 + (1.0 - 0.26)) * 0.5; float ur = sqrt((r - Rg) / (Rt - Rg)); #endif umus = max(1.0 / float(INSCATTER_RES_MU_S), umus); umus = min(1.0 - 1.0 / float(INSCATTER_RES_MU_S), umus); float lerp = unu * (float(INSCATTER_RES_NU) - 1.0); unu = floor(lerp); lerp = lerp - unu; return texture3D(Inscatter, vec3((unu + umus) / float(INSCATTER_RES_NU), umu, ur)) * (1.0 - lerp) + texture3D(Inscatter, vec3((unu + umus + 1.0) / float(INSCATTER_RES_NU), umu, ur)) * lerp; } #endif \ No newline at end of file
sartak/autobox-Closure-Attributes
db1831e883bf1e20fcbc859b1464206afef1d495
META and MYMETA in gitignore
diff --git a/.gitignore b/.gitignore index 1a4f021..4f09e25 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,12 @@ *.swp MANIFEST MANIFEST.bak -META.yml +META.* +MYMETA.* Makefile Makefile.old SIGNATURE blib/ inc/ pm_to_blib autobox-Closure-Attributes-*
sartak/autobox-Closure-Attributes
9cf65c476597ae6597264a861d419d526cdd8d76
0.05 releng
diff --git a/Changes b/Changes index b64f4ca..2183a2a 100644 --- a/Changes +++ b/Changes @@ -1,19 +1,21 @@ Revision history for autobox-Closure-Attributes -0.05 +0.05 2016-04-22 + Make the synopsis more easily digestible + Minor other documentation and packaging improvements 0.04 Sun Jun 14 15:16:06 2009 Modernize the dist 0.03 Fri May 16 11:57:00 2008 Thanks chocolateboy, for adding $code->$name! Add support for $code->$at_array and $code->$percent_hash 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 65cfba8..256d0ae 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,168 +1,168 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.05'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; use feature 'say'; sub accgen { my $n = shift; return sub { ++$n } } my $from_3 = accgen(3); say $from_3->n; # 3 say $from_3->(); # 4 say $from_3->n; # 4 say $from_3->n(10); # 10 say $from_3->(); # 11 say $from_3->(); # 12 say $from_3->m; # "CODE(0xDEADBEEF) does not close over $m" =head1 DESCRIPTION The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 IMPLEMENTATION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<[email protected]> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</DESCRIPTION> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. =head1 COPYRIGHT AND LICENSE -Copyright 2007-2009 Shawn M Moore. +Copyright 2007-2016 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
7af3b4188062bc9598878de004c2cd394d1ef69e
Better headings
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 3ceca85..65cfba8 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,168 +1,168 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.05'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; use feature 'say'; sub accgen { my $n = shift; return sub { ++$n } } my $from_3 = accgen(3); say $from_3->n; # 3 say $from_3->(); # 4 say $from_3->n; # 4 say $from_3->n(10); # 10 say $from_3->(); # 11 say $from_3->(); # 12 say $from_3->m; # "CODE(0xDEADBEEF) does not close over $m" -=head1 WHAT? +=head1 DESCRIPTION The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. -=head1 DESCRIPTION +=head1 IMPLEMENTATION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<[email protected]> =head1 SEE ALSO L<autobox>, L<PadWalker> -The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> +The L</DESCRIPTION> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
0bf788ea28ceee6fdeddf4a1b4b95d83932834e2
Make the synopsis more easily digestible
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 56b0743..3ceca85 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,166 +1,168 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.05'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; + use feature 'say'; sub accgen { my $n = shift; - return sub { $n += shift || 1 } + return sub { ++$n } } my $from_3 = accgen(3); - $from_3->n # 3 - $from_3->() # 4 - $from_3->n # 4 - $from_3->n(10) # 10 - $from_3->() # 11 - $from_3->m # "CODE(0xDEADBEEF) does not close over $m" + say $from_3->n; # 3 + say $from_3->(); # 4 + say $from_3->n; # 4 + say $from_3->n(10); # 10 + say $from_3->(); # 11 + say $from_3->(); # 12 + say $from_3->m; # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<[email protected]> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
c3388ad42faeeee686ba1e0ffdc9ece327cfb86a
Bump to 0.05
diff --git a/Changes b/Changes index 1f89e6b..b64f4ca 100644 --- a/Changes +++ b/Changes @@ -1,17 +1,19 @@ Revision history for autobox-Closure-Attributes +0.05 + 0.04 Sun Jun 14 15:16:06 2009 Modernize the dist 0.03 Fri May 16 11:57:00 2008 Thanks chocolateboy, for adding $code->$name! Add support for $code->$at_array and $code->$percent_hash 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 99d71af..56b0743 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,166 +1,166 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; -our $VERSION = '0.04'; +our $VERSION = '0.05'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<[email protected]> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
2d02c5a0e7a9bb3495ebc2b6de5bcb0303bf35aa
Changes
diff --git a/Changes b/Changes index 04dafb8..1f89e6b 100644 --- a/Changes +++ b/Changes @@ -1,16 +1,17 @@ Revision history for autobox-Closure-Attributes -0.04 +0.04 Sun Jun 14 15:16:06 2009 + Modernize the dist 0.03 Fri May 16 11:57:00 2008 Thanks chocolateboy, for adding $code->$name! Add support for $code->$at_array and $code->$percent_hash 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world.
sartak/autobox-Closure-Attributes
60c324cdfd930428cecf0009ba77b5cb96fb9ba4
author tweak
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index bfcb2f7..99d71af 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,166 +1,166 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR -Shawn M Moore, C<< <sartak at gmail.com> >> +Shawn M Moore, C<[email protected]> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
e69bc4305fe199969ff6c92fbdf1ea39478f18f9
Remove POD boilerplate
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index c74cd33..bfcb2f7 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,170 +1,166 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. -Please report any other bugs through RT: email -C<bug-autobox-closure-attributes at rt.cpan.org>, or browse -L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. - =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
5498d0455e1317e7f9868b73f7fc178cd995370a
shebang
diff --git a/t/000-load.t b/t/000-load.t index b674286..c512e84 100644 --- a/t/000-load.t +++ b/t/000-load.t @@ -1,7 +1,6 @@ -#!perl -T use strict; use warnings; use Test::More tests => 1; use_ok 'autobox::Closure::Attributes';
sartak/autobox-Closure-Attributes
15b33adad8edfffd5380abf841b68b047c3662be
Remove version from POD
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 3a9775f..c74cd33 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,174 +1,170 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures -=head1 VERSION - -Version 0.04 released ??? - =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
da0658b95e93dc1ef09eb29bb1babb0beaceba16
copyright
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index b24670a..3a9775f 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,174 +1,174 @@ package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.04 released ??? =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE -Copyright 2007-2008 Shawn M Moore. +Copyright 2007-2009 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
8b44d84418fc88abfb130b62cc21ccdc56440002
No shebang
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index a688386..b24670a 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,175 +1,174 @@ -#!perl package autobox::Closure::Attributes; use strict; use warnings; use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.04 released ??? =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007-2008 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
1fe42adf66f4449c01db3926e24eaee249b69082
Don't use parent
diff --git a/Makefile.PL b/Makefile.PL index 727024a..f457f5d 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,16 +1,15 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; githubmeta; -requires 'parent'; requires 'autobox' => '2.40'; requires 'PadWalker'; build_requires 'Test::Exception'; WriteAll; diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index ecd7601..a688386 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,175 +1,175 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; -use parent 'autobox'; +use base 'autobox'; our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.04 released ??? =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007-2008 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
d0fcae69fab60caadcde7238073e9018e656a293
gitignore
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1a4f021 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*.swp +MANIFEST +MANIFEST.bak +META.yml +Makefile +Makefile.old +SIGNATURE +blib/ +inc/ +pm_to_blib +autobox-Closure-Attributes-*
sartak/autobox-Closure-Attributes
ec3ccb94ecd848bf0ebeccab3b2612be17a63de8
Don't depend on core modules
diff --git a/Makefile.PL b/Makefile.PL index 782ee11..727024a 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,17 +1,16 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; githubmeta; requires 'parent'; requires 'autobox' => '2.40'; requires 'PadWalker'; -build_requires 'Test::More'; build_requires 'Test::Exception'; WriteAll;
sartak/autobox-Closure-Attributes
806bd3091b297055c52da18b4c54dc87988d1acf
githubmeta
diff --git a/Makefile.PL b/Makefile.PL index 07fec7d..782ee11 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,16 +1,17 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; +githubmeta; requires 'parent'; requires 'autobox' => '2.40'; requires 'PadWalker'; build_requires 'Test::More'; build_requires 'Test::Exception'; WriteAll;
sartak/autobox-Closure-Attributes
8f46280d596728e4e00018c3001c74439aee54ab
Bump to 0.04
diff --git a/Changes b/Changes index 40a268a..04dafb8 100644 --- a/Changes +++ b/Changes @@ -1,14 +1,16 @@ Revision history for autobox-Closure-Attributes +0.04 + 0.03 Fri May 16 11:57:00 2008 Thanks chocolateboy, for adding $code->$name! Add support for $code->$at_array and $code->$percent_hash 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 2bb3cdf..ecd7601 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,175 +1,175 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; -our $VERSION = '0.03'; +our $VERSION = '0.04'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } 1; __END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.03 released 16 May 08 +Version 0.04 released ??? =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. You can get and set arrays and hashes too, though it's a little more annoying: my $code = do { my ($scalar, @array, %hash); sub { return ($scalar, @array, %hash) } }; $code->scalar # works as normal my $array_method = '@array'; $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) $code->$array_method; # [1, 2, 3] my $hash_method = '%hash'; $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) $code->$hash_method; # { foo => 1, bar => 2 } If you're feeling particularly obtuse, you could do these more concisely: $code->${\ '%hash' }(foo => 1, bar => 2); $code->${\ '@array' } I recommend instead keeping your hashes and arrays in scalar variables if possible. The effect of L<autobox> is lexical, so you can localize the nastiness to a particular section of code -- these mysterious closu-jects will revert to their inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007-2008 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
sartak/autobox-Closure-Attributes
11a4d8a002e465ecd227ad7dc18d4d1395c25a90
Changes
diff --git a/Changes b/Changes index acb1371..40a268a 100644 --- a/Changes +++ b/Changes @@ -1,12 +1,14 @@ Revision history for autobox-Closure-Attributes -0.03 +0.03 Fri May 16 11:57:00 2008 + Thanks chocolateboy, for adding $code->$name! + Add support for $code->$at_array and $code->$percent_hash 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world.
sartak/autobox-Closure-Attributes
116af5d221b4898341b6392dce990394bdf308f3
Doc updates
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index f88ec6d..2bb3cdf 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,168 +1,175 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; +our $VERSION = '0.03'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; # we want the scalar unless the method name already a sigil $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; my $ref = ref $closed_over->{$attr}; if (@_) { return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; return ${ $closed_over->{$attr} } = shift; } return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } +1; + +__END__ =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.03 released ??? - -=cut - -our $VERSION = '0.03'; +Version 0.03 released 16 May 08 =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. -For now, you can get I<only> the scalars that are closed over. This is due to -limitations in Perl (L<autobox> may eventually fix this). +You can get and set arrays and hashes too, though it's a little more annoying: + + my $code = do { + my ($scalar, @array, %hash); + sub { return ($scalar, @array, %hash) } + }; + + $code->scalar # works as normal + + my $array_method = '@array'; + $code->$array_method(1, 2, 3); # set @array to (1, 2, 3) + $code->$array_method; # [1, 2, 3] + + my $hash_method = '%hash'; + $code->$hash_method(foo => 1, bar => 2); # set %hash to (foo => 1, bar => 2) + $code->$hash_method; # { foo => 1, bar => 2 } + +If you're feeling particularly obtuse, you could do these more concisely: + + $code->${\ '%hash' }(foo => 1, bar => 2); + $code->${\ '@array' } + +I recommend instead keeping your hashes and arrays in scalar variables if +possible. + +The effect of L<autobox> is lexical, so you can localize the nastiness to a +particular section of code -- these mysterious closu-jects will revert to their +inert state after L<autobox>'s scope ends. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). -L<PadWalker> will let you see and change the closed-over variables of a coderef . +L<PadWalker> will let you see and change the closed-over variables of a coderef +. L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. - my $code = do { - my @primes = qw(2 3 5 7); - sub { $primes[ $_[0] ] } - }; - - $code->'@primes'(1) # Perl complains - - my $method = '@primes'; - $code->$method(1) # autobox complains - - $code->can('@primes')->($code, 1) # can complains - - $code->ARRAY_primes(1) # Sartak complains - - $code->autobox::Closure::Attributes::Array::primes(1) # user complains - -I just can't win here. Ideas? - Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE -Copyright 2007 Shawn M Moore. +Copyright 2007-2008 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut -1; -
sartak/autobox-Closure-Attributes
069ff6a086ac6aac6c40c8a761153dc95e73c078
Add support for $code->$at_array and $code->$percent_hash
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 051ba08..f88ec6d 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,159 +1,168 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; - $attr = "\$$attr"; # this will become smarter some day + # we want the scalar unless the method name already a sigil + $attr = "\$$attr" unless $attr =~ /^[\$\@\%\&\*]/; my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; - return ${ $closed_over->{$attr} } = shift if @_; + my $ref = ref $closed_over->{$attr}; + + if (@_) { + return @{ $closed_over->{$attr} } = @_ if $ref eq 'ARRAY'; + return %{ $closed_over->{$attr} } = @_ if $ref eq 'HASH'; + return ${ $closed_over->{$attr} } = shift; + } + + return $closed_over->{$attr} if $ref eq 'HASH' || $ref eq 'ARRAY'; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.03 released ??? =cut our $VERSION = '0.03'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. This is due to limitations in Perl (L<autobox> may eventually fix this). =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
0ccc8dd8bd4cb36631d8d7a9874504b5716993a7
Remove cargo-culted autoinstall
diff --git a/Makefile.PL b/Makefile.PL index b2f9f41..07fec7d 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,17 +1,16 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; requires 'parent'; requires 'autobox' => '2.40'; requires 'PadWalker'; build_requires 'Test::More'; build_requires 'Test::Exception'; -auto_install; WriteAll;
sartak/autobox-Closure-Attributes
f382f893320361cbe39ec1c44f42a4d98a6daffa
Depend on autobox 2.40
diff --git a/Makefile.PL b/Makefile.PL index 7c2432f..b2f9f41 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,17 +1,17 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; requires 'parent'; -requires 'autobox'; +requires 'autobox' => '2.40'; requires 'PadWalker'; build_requires 'Test::More'; build_requires 'Test::Exception'; auto_install; WriteAll;
sartak/autobox-Closure-Attributes
db2cdd8f1b174192d51ea972bbac0703e349a2ec
Link to the AUTOLOAD manpage
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index c3c33cf..051ba08 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,158 +1,159 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter some day my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.03 released ??? =cut our $VERSION = '0.03'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. This is due to limitations in Perl (L<autobox> may eventually fix this). =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . -C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the -"attributes" of a closure-based object than it is for hash-based objects. +L<AUTOLOAD|perlsub/"Autoloading"> is really just an accessor. It's just harder +to manipulate the "attributes" of a closure-based object than it is for +hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
a9abc02ed8bf3b7f72c982c3300fe6a62caa4024
Acknowledgements that $c->'@foo' is.. hard
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 8c7cb78..c3c33cf 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,159 +1,158 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; - $attr = "\$$attr"; # this will become smarter soon + $attr = "\$$attr"; # this will become smarter some day my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.03 released ??? =cut our $VERSION = '0.03'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. -For now, you can get I<only> the scalars that are closed over. Once I think of -a better interface for getting and setting arrays and hashes I'll add that. -C<< $code->'@foo' >> is the easy part. +For now, you can get I<only> the scalars that are closed over. This is due to +limitations in Perl (L<autobox> may eventually fix this). =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
72391fe54d1f56979a1db904e7585ae6ca11c7c0
Bump to 0.03
diff --git a/Changes b/Changes index a008e53..acb1371 100644 --- a/Changes +++ b/Changes @@ -1,10 +1,12 @@ Revision history for autobox-Closure-Attributes +0.03 + 0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index f1e415a..8c7cb78 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,159 +1,159 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.02 released 21 Feb 08 +Version 0.03 released ??? =cut -our $VERSION = '0.02'; +our $VERSION = '0.03'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
295938708d1ea824e9d18e7fc45225d5eb2fab11
Prepare for 0.02 release
diff --git a/Changes b/Changes index 917b07f..a008e53 100644 --- a/Changes +++ b/Changes @@ -1,10 +1,10 @@ Revision history for autobox-Closure-Attributes -0.02 +0.02 Thu Feb 21 03:09:40 2008 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 3608878..f1e415a 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,159 +1,159 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.02 released ??? +Version 0.02 released 21 Feb 08 =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
5c3204ff1aec97b67ff4f066b81f183357c7d48d
Ugh, Module::Install is all "I WANT NEW"
diff --git a/inc/Module/Install.pm b/inc/Module/Install.pm index 9d13686..89a8653 100644 --- a/inc/Module/Install.pm +++ b/inc/Module/Install.pm @@ -1,281 +1,281 @@ #line 1 package Module::Install; # For any maintainers: # The load order for Module::Install is a bit magic. # It goes something like this... # # IF ( host has Module::Install installed, creating author mode ) { # 1. Makefile.PL calls "use inc::Module::Install" # 2. $INC{inc/Module/Install.pm} set to installed version of inc::Module::Install # 3. The installed version of inc::Module::Install loads # 4. inc::Module::Install calls "require Module::Install" # 5. The ./inc/ version of Module::Install loads # } ELSE { # 1. Makefile.PL calls "use inc::Module::Install" # 2. $INC{inc/Module/Install.pm} set to ./inc/ version of Module::Install # 3. The ./inc/ version of Module::Install loads # } use 5.004; use strict 'vars'; use vars qw{$VERSION}; BEGIN { # All Module::Install core packages now require synchronised versions. # This will be used to ensure we don't accidentally load old or # different versions of modules. # This is not enforced yet, but will be some time in the next few # releases once we can make sure it won't clash with custom # Module::Install extensions. - $VERSION = '0.67'; + $VERSION = '0.68'; } # Whether or not inc::Module::Install is actually loaded, the # $INC{inc/Module/Install.pm} is what will still get set as long as # the caller loaded module this in the documented manner. # If not set, the caller may NOT have loaded the bundled version, and thus # they may not have a MI version that works with the Makefile.PL. This would # result in false errors or unexpected behaviour. And we don't want that. my $file = join( '/', 'inc', split /::/, __PACKAGE__ ) . '.pm'; unless ( $INC{$file} ) { die <<"END_DIE"; Please invoke ${\__PACKAGE__} with: use inc::${\__PACKAGE__}; not: use ${\__PACKAGE__}; END_DIE } # If the script that is loading Module::Install is from the future, # then make will detect this and cause it to re-run over and over # again. This is bad. Rather than taking action to touch it (which # is unreliable on some platforms and requires write permissions) # for now we should catch this and refuse to run. if ( -f $0 and (stat($0))[9] > time ) { die << "END_DIE"; Your installer $0 has a modification time in the future. This is known to create infinite loops in make. Please correct this, then run $0 again. END_DIE } use Cwd (); use File::Find (); use File::Path (); use FindBin; *inc::Module::Install::VERSION = *VERSION; @inc::Module::Install::ISA = __PACKAGE__; sub autoload { my $self = shift; my $who = $self->_caller; my $cwd = Cwd::cwd(); my $sym = "${who}::AUTOLOAD"; $sym->{$cwd} = sub { my $pwd = Cwd::cwd(); if ( my $code = $sym->{$pwd} ) { # delegate back to parent dirs goto &$code unless $cwd eq $pwd; } $$sym =~ /([^:]+)$/ or die "Cannot autoload $who - $sym"; unshift @_, ($self, $1); goto &{$self->can('call')} unless uc($1) eq $1; }; } sub import { my $class = shift; my $self = $class->new(@_); my $who = $self->_caller; unless ( -f $self->{file} ) { require "$self->{path}/$self->{dispatch}.pm"; File::Path::mkpath("$self->{prefix}/$self->{author}"); $self->{admin} = "$self->{name}::$self->{dispatch}"->new( _top => $self ); $self->{admin}->init; @_ = ($class, _self => $self); goto &{"$self->{name}::import"}; } *{"${who}::AUTOLOAD"} = $self->autoload; $self->preload; # Unregister loader and worker packages so subdirs can use them again delete $INC{"$self->{file}"}; delete $INC{"$self->{path}.pm"}; } sub preload { my ($self) = @_; unless ( $self->{extensions} ) { $self->load_extensions( "$self->{prefix}/$self->{path}", $self ); } my @exts = @{$self->{extensions}}; unless ( @exts ) { my $admin = $self->{admin}; @exts = $admin->load_all_extensions; } my %seen; foreach my $obj ( @exts ) { while (my ($method, $glob) = each %{ref($obj) . '::'}) { next unless $obj->can($method); next if $method =~ /^_/; next if $method eq uc($method); $seen{$method}++; } } my $who = $self->_caller; foreach my $name ( sort keys %seen ) { *{"${who}::$name"} = sub { ${"${who}::AUTOLOAD"} = "${who}::$name"; goto &{"${who}::AUTOLOAD"}; }; } } sub new { my ($class, %args) = @_; # ignore the prefix on extension modules built from top level. my $base_path = Cwd::abs_path($FindBin::Bin); unless ( Cwd::abs_path(Cwd::cwd()) eq $base_path ) { delete $args{prefix}; } return $args{_self} if $args{_self}; $args{dispatch} ||= 'Admin'; $args{prefix} ||= 'inc'; $args{author} ||= ($^O eq 'VMS' ? '_author' : '.author'); $args{bundle} ||= 'inc/BUNDLES'; $args{base} ||= $base_path; $class =~ s/^\Q$args{prefix}\E:://; $args{name} ||= $class; $args{version} ||= $class->VERSION; unless ( $args{path} ) { $args{path} = $args{name}; $args{path} =~ s!::!/!g; } $args{file} ||= "$args{base}/$args{prefix}/$args{path}.pm"; bless( \%args, $class ); } sub call { my ($self, $method) = @_; my $obj = $self->load($method) or return; splice(@_, 0, 2, $obj); goto &{$obj->can($method)}; } sub load { my ($self, $method) = @_; $self->load_extensions( "$self->{prefix}/$self->{path}", $self ) unless $self->{extensions}; foreach my $obj (@{$self->{extensions}}) { return $obj if $obj->can($method); } my $admin = $self->{admin} or die <<"END_DIE"; The '$method' method does not exist in the '$self->{prefix}' path! Please remove the '$self->{prefix}' directory and run $0 again to load it. END_DIE my $obj = $admin->load($method, 1); push @{$self->{extensions}}, $obj; $obj; } sub load_extensions { my ($self, $path, $top) = @_; unless ( grep { lc $_ eq lc $self->{prefix} } @INC ) { unshift @INC, $self->{prefix}; } foreach my $rv ( $self->find_extensions($path) ) { my ($file, $pkg) = @{$rv}; next if $self->{pathnames}{$pkg}; local $@; my $new = eval { require $file; $pkg->can('new') }; unless ( $new ) { warn $@ if $@; next; } $self->{pathnames}{$pkg} = delete $INC{$file}; push @{$self->{extensions}}, &{$new}($pkg, _top => $top ); } $self->{extensions} ||= []; } sub find_extensions { my ($self, $path) = @_; my @found; File::Find::find( sub { my $file = $File::Find::name; return unless $file =~ m!^\Q$path\E/(.+)\.pm\Z!is; my $subpath = $1; return if lc($subpath) eq lc($self->{dispatch}); $file = "$self->{path}/$subpath.pm"; my $pkg = "$self->{name}::$subpath"; $pkg =~ s!/!::!g; # If we have a mixed-case package name, assume case has been preserved # correctly. Otherwise, root through the file to locate the case-preserved # version of the package name. if ( $subpath eq lc($subpath) || $subpath eq uc($subpath) ) { open PKGFILE, "<$subpath.pm" or die "find_extensions: Can't open $subpath.pm: $!"; my $in_pod = 0; while ( <PKGFILE> ) { $in_pod = 1 if /^=\w/; $in_pod = 0 if /^=cut/; next if ($in_pod || /^=cut/); # skip pod text next if /^\s*#/; # and comments if ( m/^\s*package\s+($pkg)\s*;/i ) { $pkg = $1; last; } } close PKGFILE; } push @found, [ $file, $pkg ]; }, $path ) if -d $path; @found; } sub _caller { my $depth = 0; my $call = caller($depth); while ( $call eq __PACKAGE__ ) { $depth++; $call = caller($depth); } return $call; } 1; diff --git a/inc/Module/Install/AutoInstall.pm b/inc/Module/Install/AutoInstall.pm index c244cb5..3a490fb 100644 --- a/inc/Module/Install/AutoInstall.pm +++ b/inc/Module/Install/AutoInstall.pm @@ -1,61 +1,61 @@ #line 1 package Module::Install::AutoInstall; use strict; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } sub AutoInstall { $_[0] } sub run { my $self = shift; $self->auto_install_now(@_); } sub write { my $self = shift; $self->auto_install(@_); } sub auto_install { my $self = shift; return if $self->{done}++; # Flatten array of arrays into a single array my @core = map @$_, map @$_, grep ref, $self->build_requires, $self->requires; my @config = @_; # We'll need Module::AutoInstall $self->include('Module::AutoInstall'); require Module::AutoInstall; Module::AutoInstall->import( (@config ? (-config => \@config) : ()), (@core ? (-core => \@core) : ()), $self->features, ); $self->makemaker_args( Module::AutoInstall::_make_args() ); my $class = ref($self); $self->postamble( "# --- $class section:\n" . Module::AutoInstall::postamble() ); } sub auto_install_now { my $self = shift; $self->auto_install(@_); Module::AutoInstall::do_install(); } 1; diff --git a/inc/Module/Install/Base.pm b/inc/Module/Install/Base.pm index 81fbcb6..49dfde6 100644 --- a/inc/Module/Install/Base.pm +++ b/inc/Module/Install/Base.pm @@ -1,70 +1,70 @@ #line 1 package Module::Install::Base; -$VERSION = '0.67'; +$VERSION = '0.68'; # Suspend handler for "redefined" warnings BEGIN { my $w = $SIG{__WARN__}; $SIG{__WARN__} = sub { $w }; } ### This is the ONLY module that shouldn't have strict on # use strict; #line 41 sub new { my ($class, %args) = @_; foreach my $method ( qw(call load) ) { *{"$class\::$method"} = sub { shift()->_top->$method(@_); } unless defined &{"$class\::$method"}; } bless( \%args, $class ); } #line 61 sub AUTOLOAD { my $self = shift; local $@; my $autoload = eval { $self->_top->autoload } or return; goto &$autoload; } #line 76 sub _top { $_[0]->{_top} } #line 89 sub admin { $_[0]->_top->{admin} or Module::Install::Base::FakeAdmin->new; } sub is_admin { $_[0]->admin->VERSION; } sub DESTROY {} package Module::Install::Base::FakeAdmin; my $Fake; sub new { $Fake ||= bless(\@_, $_[0]) } sub AUTOLOAD {} sub DESTROY {} # Restore warning handler BEGIN { $SIG{__WARN__} = $SIG{__WARN__}->(); } 1; #line 138 diff --git a/inc/Module/Install/Can.pm b/inc/Module/Install/Can.pm index 5d1eab8..ec66fdb 100644 --- a/inc/Module/Install/Can.pm +++ b/inc/Module/Install/Can.pm @@ -1,82 +1,82 @@ #line 1 package Module::Install::Can; use strict; use Module::Install::Base; use Config (); ### This adds a 5.005 Perl version dependency. ### This is a bug and will be fixed. use File::Spec (); use ExtUtils::MakeMaker (); use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } # check if we can load some module ### Upgrade this to not have to load the module if possible sub can_use { my ($self, $mod, $ver) = @_; $mod =~ s{::|\\}{/}g; $mod .= '.pm' unless $mod =~ /\.pm$/i; my $pkg = $mod; $pkg =~ s{/}{::}g; $pkg =~ s{\.pm$}{}i; local $@; eval { require $mod; $pkg->VERSION($ver || 0); 1 }; } # check if we can run some command sub can_run { my ($self, $cmd) = @_; my $_cmd = $cmd; return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd)); for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') { my $abs = File::Spec->catfile($dir, $_[1]); return $abs if (-x $abs or $abs = MM->maybe_command($abs)); } return; } # can we locate a (the) C compiler sub can_cc { my $self = shift; my @chunks = split(/ /, $Config::Config{cc}) or return; # $Config{cc} may contain args; try to find out the program part while (@chunks) { return $self->can_run("@chunks") || (pop(@chunks), next); } return; } # Fix Cygwin bug on maybe_command(); if ( $^O eq 'cygwin' ) { require ExtUtils::MM_Cygwin; require ExtUtils::MM_Win32; if ( ! defined(&ExtUtils::MM_Cygwin::maybe_command) ) { *ExtUtils::MM_Cygwin::maybe_command = sub { my ($self, $file) = @_; if ($file =~ m{^/cygdrive/}i and ExtUtils::MM_Win32->can('maybe_command')) { ExtUtils::MM_Win32->maybe_command($file); } else { ExtUtils::MM_Unix->maybe_command($file); } } } } 1; __END__ #line 157 diff --git a/inc/Module/Install/Fetch.pm b/inc/Module/Install/Fetch.pm index e884477..e0dd6db 100644 --- a/inc/Module/Install/Fetch.pm +++ b/inc/Module/Install/Fetch.pm @@ -1,93 +1,93 @@ #line 1 package Module::Install::Fetch; use strict; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } sub get_file { my ($self, %args) = @_; my ($scheme, $host, $path, $file) = $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) { $args{url} = $args{ftp_url} or (warn("LWP support unavailable!\n"), return); ($scheme, $host, $path, $file) = $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; } $|++; print "Fetching '$file' from $host... "; unless (eval { require Socket; Socket::inet_aton($host) }) { warn "'$host' resolve failed!\n"; return; } return unless $scheme eq 'ftp' or $scheme eq 'http'; require Cwd; my $dir = Cwd::getcwd(); chdir $args{local_dir} or return if exists $args{local_dir}; if (eval { require LWP::Simple; 1 }) { LWP::Simple::mirror($args{url}, $file); } elsif (eval { require Net::FTP; 1 }) { eval { # use Net::FTP to get past firewall my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600); $ftp->login("anonymous", '[email protected]'); $ftp->cwd($path); $ftp->binary; $ftp->get($file) or (warn("$!\n"), return); $ftp->quit; } } elsif (my $ftp = $self->can_run('ftp')) { eval { # no Net::FTP, fallback to ftp.exe require FileHandle; my $fh = FileHandle->new; local $SIG{CHLD} = 'IGNORE'; unless ($fh->open("|$ftp -n")) { warn "Couldn't open ftp: $!\n"; chdir $dir; return; } my @dialog = split(/\n/, <<"END_FTP"); open $host user anonymous anonymous\@example.com cd $path binary get $file $file quit END_FTP foreach (@dialog) { $fh->print("$_\n") } $fh->close; } } else { warn "No working 'ftp' program available!\n"; chdir $dir; return; } unless (-f $file) { warn "Fetching failed: $@\n"; chdir $dir; return; } return if exists $args{size} and -s $file != $args{size}; system($args{run}) if exists $args{run}; unlink($file) if $args{remove}; print(((!exists $args{check_for} or -e $args{check_for}) ? "done!" : "failed! ($!)"), "\n"); chdir $dir; return !$?; } 1; diff --git a/inc/Module/Install/Include.pm b/inc/Module/Install/Include.pm index 574acc8..001d0c6 100644 --- a/inc/Module/Install/Include.pm +++ b/inc/Module/Install/Include.pm @@ -1,34 +1,34 @@ #line 1 package Module::Install::Include; use strict; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } sub include { shift()->admin->include(@_); } sub include_deps { shift()->admin->include_deps(@_); } sub auto_include { shift()->admin->auto_include(@_); } sub auto_include_deps { shift()->admin->auto_include_deps(@_); } sub auto_include_dependent_dists { shift()->admin->auto_include_dependent_dists(@_); } 1; diff --git a/inc/Module/Install/Makefile.pm b/inc/Module/Install/Makefile.pm index fbc5cb2..17bd8a7 100644 --- a/inc/Module/Install/Makefile.pm +++ b/inc/Module/Install/Makefile.pm @@ -1,237 +1,237 @@ #line 1 package Module::Install::Makefile; use strict 'vars'; use Module::Install::Base; use ExtUtils::MakeMaker (); use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } sub Makefile { $_[0] } my %seen = (); sub prompt { shift; # Infinite loop protection my @c = caller(); if ( ++$seen{"$c[1]|$c[2]|$_[0]"} > 3 ) { die "Caught an potential prompt infinite loop ($c[1]|$c[2]|$_[0])"; } # In automated testing, always use defaults if ( $ENV{AUTOMATED_TESTING} and ! $ENV{PERL_MM_USE_DEFAULT} ) { local $ENV{PERL_MM_USE_DEFAULT} = 1; goto &ExtUtils::MakeMaker::prompt; } else { goto &ExtUtils::MakeMaker::prompt; } } sub makemaker_args { my $self = shift; my $args = ($self->{makemaker_args} ||= {}); %$args = ( %$args, @_ ) if @_; $args; } # For mm args that take multiple space-seperated args, # append an argument to the current list. sub makemaker_append { my $self = sShift; my $name = shift; my $args = $self->makemaker_args; $args->{name} = defined $args->{$name} ? join( ' ', $args->{name}, @_ ) : join( ' ', @_ ); } sub build_subdirs { my $self = shift; my $subdirs = $self->makemaker_args->{DIR} ||= []; for my $subdir (@_) { push @$subdirs, $subdir; } } sub clean_files { my $self = shift; my $clean = $self->makemaker_args->{clean} ||= {}; %$clean = ( %$clean, FILES => join(' ', grep length, $clean->{FILES}, @_), ); } sub realclean_files { my $self = shift; my $realclean = $self->makemaker_args->{realclean} ||= {}; %$realclean = ( %$realclean, FILES => join(' ', grep length, $realclean->{FILES}, @_), ); } sub libs { my $self = shift; my $libs = ref $_[0] ? shift : [ shift ]; $self->makemaker_args( LIBS => $libs ); } sub inc { my $self = shift; $self->makemaker_args( INC => shift ); } my %test_dir = (); sub _wanted_t { /\.t$/ and -f $_ and $test_dir{$File::Find::dir} = 1; } sub tests_recursive { my $self = shift; if ( $self->tests ) { die "tests_recursive will not work if tests are already defined"; } my $dir = shift || 't'; unless ( -d $dir ) { die "tests_recursive dir '$dir' does not exist"; } require File::Find; %test_dir = (); File::Find::find( \&_wanted_t, $dir ); $self->tests( join ' ', map { "$_/*.t" } sort keys %test_dir ); } sub write { my $self = shift; die "&Makefile->write() takes no arguments\n" if @_; my $args = $self->makemaker_args; $args->{DISTNAME} = $self->name; $args->{NAME} = $self->module_name || $self->name || $self->determine_NAME($args); $args->{VERSION} = $self->version || $self->determine_VERSION($args); $args->{NAME} =~ s/-/::/g; if ( $self->tests ) { $args->{test} = { TESTS => $self->tests }; } if ($] >= 5.005) { $args->{ABSTRACT} = $self->abstract; $args->{AUTHOR} = $self->author; } if ( eval($ExtUtils::MakeMaker::VERSION) >= 6.10 ) { $args->{NO_META} = 1; } if ( eval($ExtUtils::MakeMaker::VERSION) > 6.17 and $self->sign ) { $args->{SIGN} = 1; } unless ( $self->is_admin ) { delete $args->{SIGN}; } # merge both kinds of requires into prereq_pm my $prereq = ($args->{PREREQ_PM} ||= {}); %$prereq = ( %$prereq, map { @$_ } map { @$_ } grep $_, ($self->build_requires, $self->requires) ); # merge both kinds of requires into prereq_pm my $subdirs = ($args->{DIR} ||= []); if ($self->bundles) { foreach my $bundle (@{ $self->bundles }) { my ($file, $dir) = @$bundle; push @$subdirs, $dir if -d $dir; delete $prereq->{$file}; } } if ( my $perl_version = $self->perl_version ) { eval "use $perl_version; 1" or die "ERROR: perl: Version $] is installed, " . "but we need version >= $perl_version"; } $args->{INSTALLDIRS} = $self->installdirs; my %args = map { ( $_ => $args->{$_} ) } grep {defined($args->{$_})} keys %$args; my $user_preop = delete $args{dist}->{PREOP}; if (my $preop = $self->admin->preop($user_preop)) { $args{dist} = $preop; } my $mm = ExtUtils::MakeMaker::WriteMakefile(%args); $self->fix_up_makefile($mm->{FIRST_MAKEFILE} || 'Makefile'); } sub fix_up_makefile { my $self = shift; my $makefile_name = shift; my $top_class = ref($self->_top) || ''; my $top_version = $self->_top->VERSION || ''; my $preamble = $self->preamble ? "# Preamble by $top_class $top_version\n" . $self->preamble : ''; my $postamble = "# Postamble by $top_class $top_version\n" . ($self->postamble || ''); local *MAKEFILE; open MAKEFILE, "< $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; my $makefile = do { local $/; <MAKEFILE> }; close MAKEFILE or die $!; $makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /; $makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g; $makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g; $makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m; $makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m; # Module::Install will never be used to build the Core Perl # Sometimes PERL_LIB and PERL_ARCHLIB get written anyway, which breaks # PREFIX/PERL5LIB, and thus, install_share. Blank them if they exist $makefile =~ s/^PERL_LIB = .+/PERL_LIB =/m; #$makefile =~ s/^PERL_ARCHLIB = .+/PERL_ARCHLIB =/m; # Perl 5.005 mentions PERL_LIB explicitly, so we have to remove that as well. $makefile =~ s/("?)-I\$\(PERL_LIB\)\1//g; # XXX - This is currently unused; not sure if it breaks other MM-users # $makefile =~ s/^pm_to_blib\s+:\s+/pm_to_blib :: /mg; open MAKEFILE, "> $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; print MAKEFILE "$preamble$makefile$postamble" or die $!; close MAKEFILE or die $!; 1; } sub preamble { my ($self, $text) = @_; $self->{preamble} = $text . $self->{preamble} if defined $text; $self->{preamble}; } sub postamble { my ($self, $text) = @_; $self->{postamble} ||= $self->admin->postamble; $self->{postamble} .= $text if defined $text; $self->{postamble} } 1; __END__ #line 363 diff --git a/inc/Module/Install/Metadata.pm b/inc/Module/Install/Metadata.pm index b886046..f77d68a 100644 --- a/inc/Module/Install/Metadata.pm +++ b/inc/Module/Install/Metadata.pm @@ -1,336 +1,336 @@ #line 1 package Module::Install::Metadata; use strict 'vars'; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } my @scalar_keys = qw{ name module_name abstract author version license distribution_type perl_version tests installdirs }; my @tuple_keys = qw{ build_requires requires recommends bundles }; sub Meta { shift } sub Meta_ScalarKeys { @scalar_keys } sub Meta_TupleKeys { @tuple_keys } foreach my $key (@scalar_keys) { *$key = sub { my $self = shift; return $self->{values}{$key} if defined wantarray and !@_; $self->{values}{$key} = shift; return $self; }; } foreach my $key (@tuple_keys) { *$key = sub { my $self = shift; return $self->{values}{$key} unless @_; my @rv; while (@_) { my $module = shift or last; my $version = shift || 0; if ( $module eq 'perl' ) { $version =~ s{^(\d+)\.(\d+)\.(\d+)} {$1 + $2/1_000 + $3/1_000_000}e; $self->perl_version($version); next; } my $rv = [ $module, $version ]; push @rv, $rv; } push @{ $self->{values}{$key} }, @rv; @rv; }; } # configure_requires is currently a null-op sub configure_requires { 1 } # Aliases for build_requires that will have alternative # meanings in some future version of META.yml. sub test_requires { shift->build_requires(@_) } sub install_requires { shift->build_requires(@_) } # Aliases for installdirs options sub install_as_core { $_[0]->installdirs('perl') } sub install_as_cpan { $_[0]->installdirs('site') } sub install_as_site { $_[0]->installdirs('site') } sub install_as_vendor { $_[0]->installdirs('vendor') } sub sign { my $self = shift; return $self->{'values'}{'sign'} if defined wantarray and ! @_; $self->{'values'}{'sign'} = ( @_ ? $_[0] : 1 ); return $self; } sub dynamic_config { my $self = shift; unless ( @_ ) { warn "You MUST provide an explicit true/false value to dynamic_config, skipping\n"; return $self; } $self->{'values'}{'dynamic_config'} = $_[0] ? 1 : 0; return $self; } sub all_from { my ( $self, $file ) = @_; unless ( defined($file) ) { my $name = $self->name or die "all_from called with no args without setting name() first"; $file = join('/', 'lib', split(/-/, $name)) . '.pm'; $file =~ s{.*/}{} unless -e $file; die "all_from: cannot find $file from $name" unless -e $file; } $self->version_from($file) unless $self->version; $self->perl_version_from($file) unless $self->perl_version; # The remaining probes read from POD sections; if the file # has an accompanying .pod, use that instead my $pod = $file; if ( $pod =~ s/\.pm$/.pod/i and -e $pod ) { $file = $pod; } $self->author_from($file) unless $self->author; $self->license_from($file) unless $self->license; $self->abstract_from($file) unless $self->abstract; } sub provides { my $self = shift; my $provides = ( $self->{values}{provides} ||= {} ); %$provides = (%$provides, @_) if @_; return $provides; } sub auto_provides { my $self = shift; return $self unless $self->is_admin; unless (-e 'MANIFEST') { warn "Cannot deduce auto_provides without a MANIFEST, skipping\n"; return $self; } # Avoid spurious warnings as we are not checking manifest here. local $SIG{__WARN__} = sub {1}; require ExtUtils::Manifest; local *ExtUtils::Manifest::manicheck = sub { return }; require Module::Build; my $build = Module::Build->new( dist_name => $self->name, dist_version => $self->version, license => $self->license, ); $self->provides(%{ $build->find_dist_packages || {} }); } sub feature { my $self = shift; my $name = shift; my $features = ( $self->{values}{features} ||= [] ); my $mods; if ( @_ == 1 and ref( $_[0] ) ) { # The user used ->feature like ->features by passing in the second # argument as a reference. Accomodate for that. $mods = $_[0]; } else { $mods = \@_; } my $count = 0; push @$features, ( $name => [ map { ref($_) ? ( ref($_) eq 'HASH' ) ? %$_ : @$_ : $_ } @$mods ] ); return @$features; } sub features { my $self = shift; while ( my ( $name, $mods ) = splice( @_, 0, 2 ) ) { $self->feature( $name, @$mods ); } return $self->{values}->{features} ? @{ $self->{values}->{features} } : (); } sub no_index { my $self = shift; my $type = shift; push @{ $self->{values}{no_index}{$type} }, @_ if $type; return $self->{values}{no_index}; } sub read { my $self = shift; $self->include_deps( 'YAML', 0 ); require YAML; my $data = YAML::LoadFile('META.yml'); # Call methods explicitly in case user has already set some values. while ( my ( $key, $value ) = each %$data ) { next unless $self->can($key); if ( ref $value eq 'HASH' ) { while ( my ( $module, $version ) = each %$value ) { $self->can($key)->($self, $module => $version ); } } else { $self->can($key)->($self, $value); } } return $self; } sub write { my $self = shift; return $self unless $self->is_admin; $self->admin->write_meta; return $self; } sub version_from { my ( $self, $file ) = @_; require ExtUtils::MM_Unix; $self->version( ExtUtils::MM_Unix->parse_version($file) ); } sub abstract_from { my ( $self, $file ) = @_; require ExtUtils::MM_Unix; $self->abstract( bless( { DISTNAME => $self->name }, 'ExtUtils::MM_Unix' )->parse_abstract($file) ); } sub _slurp { my ( $self, $file ) = @_; local *FH; open FH, "< $file" or die "Cannot open $file.pod: $!"; do { local $/; <FH> }; } sub perl_version_from { my ( $self, $file ) = @_; if ( $self->_slurp($file) =~ m/ ^ use \s* v? ([\d_\.]+) \s* ; /ixms ) { my $v = $1; $v =~ s{_}{}g; $self->perl_version($1); } else { warn "Cannot determine perl version info from $file\n"; return; } } sub author_from { my ( $self, $file ) = @_; my $content = $self->_slurp($file); if ($content =~ m/ =head \d \s+ (?:authors?)\b \s* ([^\n]*) | =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b \s* .*? copyright .*? \d\d\d[\d.]+ \s* (?:\bby\b)? \s* ([^\n]*) /ixms) { my $author = $1 || $2; $author =~ s{E<lt>}{<}g; $author =~ s{E<gt>}{>}g; $self->author($author); } else { warn "Cannot determine author info from $file\n"; } } sub license_from { my ( $self, $file ) = @_; if ( $self->_slurp($file) =~ m/ ( =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b .*? ) (=head\\d.*|=cut.*|) \z /ixms ) { my $license_text = $1; my @phrases = ( 'under the same (?:terms|license) as perl itself' => 'perl', 1, 'GNU public license' => 'gpl', 1, 'GNU lesser public license' => 'gpl', 1, 'BSD license' => 'bsd', 1, 'Artistic license' => 'artistic', 1, 'GPL' => 'gpl', 1, 'LGPL' => 'lgpl', 1, 'BSD' => 'bsd', 1, 'Artistic' => 'artistic', 1, 'MIT' => 'mit', 1, 'proprietary' => 'proprietary', 0, ); while ( my ($pattern, $license, $osi) = splice(@phrases, 0, 3) ) { $pattern =~ s{\s+}{\\s+}g; if ( $license_text =~ /\b$pattern\b/i ) { if ( $osi and $license_text =~ /All rights reserved/i ) { warn "LEGAL WARNING: 'All rights reserved' may invalidate Open Source licenses. Consider removing it."; } $self->license($license); return 1; } } } warn "Cannot determine license info from $file\n"; return 'unknown'; } 1; diff --git a/inc/Module/Install/Win32.pm b/inc/Module/Install/Win32.pm index 612dc30..4f808c7 100644 --- a/inc/Module/Install/Win32.pm +++ b/inc/Module/Install/Win32.pm @@ -1,65 +1,65 @@ #line 1 package Module::Install::Win32; use strict; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } # determine if the user needs nmake, and download it if needed sub check_nmake { my $self = shift; $self->load('can_run'); $self->load('get_file'); require Config; return unless ( $^O eq 'MSWin32' and $Config::Config{make} and $Config::Config{make} =~ /^nmake\b/i and ! $self->can_run('nmake') ); print "The required 'nmake' executable not found, fetching it...\n"; require File::Basename; my $rv = $self->get_file( url => 'http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe', ftp_url => 'ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe', local_dir => File::Basename::dirname($^X), size => 51928, run => 'Nmake15.exe /o > nul', check_for => 'Nmake.exe', remove => 1, ); if (!$rv) { die <<'END_MESSAGE'; ------------------------------------------------------------------------------- Since you are using Microsoft Windows, you will need the 'nmake' utility before installation. It's available at: http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe or ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe Please download the file manually, save it to a directory in %PATH% (e.g. C:\WINDOWS\COMMAND\), then launch the MS-DOS command line shell, "cd" to that directory, and run "Nmake15.exe" from there; that will create the 'nmake.exe' file needed by this module. You may then resume the installation process described in README. ------------------------------------------------------------------------------- END_MESSAGE } } 1; diff --git a/inc/Module/Install/WriteAll.pm b/inc/Module/Install/WriteAll.pm index e1db381..078797c 100644 --- a/inc/Module/Install/WriteAll.pm +++ b/inc/Module/Install/WriteAll.pm @@ -1,43 +1,43 @@ #line 1 package Module::Install::WriteAll; use strict; use Module::Install::Base; use vars qw{$VERSION $ISCORE @ISA}; BEGIN { - $VERSION = '0.67'; + $VERSION = '0.68'; $ISCORE = 1; @ISA = qw{Module::Install::Base}; } sub WriteAll { my $self = shift; my %args = ( meta => 1, sign => 0, inline => 0, check_nmake => 1, @_ ); $self->sign(1) if $args{sign}; $self->Meta->write if $args{meta}; $self->admin->WriteAll(%args) if $self->is_admin; if ( $0 =~ /Build.PL$/i ) { $self->Build->write; } else { $self->check_nmake if $args{check_nmake}; unless ( $self->makemaker_args->{'PL_FILES'} ) { $self->makemaker_args( PL_FILES => {} ); } if ($args{inline}) { $self->Inline->write; } else { $self->Makefile->write; } } } 1;
sartak/autobox-Closure-Attributes
599b68c0abf662ae292262133a61e18aff0b1d1c
Doc fixups
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 0afad3b..3608878 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,159 +1,159 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.02 released ??? =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. my $code = do { my @primes = qw(2 3 5 7); - sub { $primes[$_[0]] } + sub { $primes[ $_[0] ] } }; $code->'@primes'(1) # Perl complains my $method = '@primes'; $code->$method(1) # autobox complains - $code->can('@primes')->($code, 1) # can ignores AUTOLOAD + $code->can('@primes')->($code, 1) # can complains $code->ARRAY_primes(1) # Sartak complains $code->autobox::Closure::Attributes::Array::primes(1) # user complains I just can't win here. Ideas? Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
5989037e8f6e61614b7aa22860df8ac4c89ad669
Ensure that we can't add new variables to the pad (why would you?)
diff --git a/t/004-new-capture.t b/t/004-new-capture.t new file mode 100644 index 0000000..3b0e34a --- /dev/null +++ b/t/004-new-capture.t @@ -0,0 +1,20 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 3; +use Test::Exception; +use autobox::Closure::Attributes; + +sub accgen { + my $n = shift; + return sub { $n += shift || 1 } +} + +my $from_3 = accgen(3); + +is($from_3->n, 3); +is($from_3->(), 4); + +${ PadWalker::closed_over($from_3)->{m} } = 3; +throws_ok { $from_3->m } qr/CODE\(0x[0-9a-fA-F]+\) does not close over \$m at/; +
sartak/autobox-Closure-Attributes
50beedbe0a9b60d8d5f7525302b936d1178f4077
Document my failure to make $code->'@primes' work
diff --git a/Changes b/Changes index 52f6d4d..917b07f 100644 --- a/Changes +++ b/Changes @@ -1,9 +1,10 @@ Revision history for autobox-Closure-Attributes 0.02 Mistakenly put the AUTOLOAD in a non-namespace package. Fix SYNOPSIS. + Tried to make $c->'@primes' work, but no dice. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index d05de57..0afad3b 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,141 +1,159 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.02 released ??? =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. + my $code = do { + my @primes = qw(2 3 5 7); + sub { $primes[$_[0]] } + }; + + $code->'@primes'(1) # Perl complains + + my $method = '@primes'; + $code->$method(1) # autobox complains + + $code->can('@primes')->($code, 1) # can ignores AUTOLOAD + + $code->ARRAY_primes(1) # Sartak complains + + $code->autobox::Closure::Attributes::Array::primes(1) # user complains + +I just can't win here. Ideas? + Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
e722104d66550928c74cf66878ed342f3528ce98
Reword
diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index ce699b8..d05de57 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,141 +1,141 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.02 released ??? =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> -L</WHAT?> from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> +The L</WHAT?> section is from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
97d40f544f8ea353564db1856d72d96edad6497a
Fix SYNOPSIS
diff --git a/Changes b/Changes index 6e3e3ff..52f6d4d 100644 --- a/Changes +++ b/Changes @@ -1,8 +1,9 @@ Revision history for autobox-Closure-Attributes 0.02 Mistakenly put the AUTOLOAD in a non-namespace package. + Fix SYNOPSIS. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 5658549..ce699b8 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,141 +1,141 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.02 released ??? =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; - return sub { $n += shift } + return sub { $n += shift || 1 } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> L</WHAT?> from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
55703b06fbbcb40d360c9109715480ed69af69ad
Mistakenly put the AUTOLOAD in a non-namespace package
diff --git a/Changes b/Changes index dca8d63..6e3e3ff 100644 --- a/Changes +++ b/Changes @@ -1,7 +1,8 @@ Revision history for autobox-Closure-Attributes 0.02 + Mistakenly put the AUTOLOAD in a non-namespace package. 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 1008dd6..5658549 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,141 +1,141 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { - shift->SUPER::import(CODE => 'Closure::Attributes::Methods'); + shift->SUPER::import(CODE => 'autobox::Closure::Attributes::Methods'); } -package Closure::Attributes::Methods; +package autobox::Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION Version 0.02 released ??? =cut our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> L</WHAT?> from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
eedacbecde157ec090ecc0cf0620c283075450fd
Bump to 0.02
diff --git a/Changes b/Changes index 033566b..dca8d63 100644 --- a/Changes +++ b/Changes @@ -1,5 +1,7 @@ Revision history for autobox-Closure-Attributes +0.02 + 0.01 Tue Feb 19 01:30:41 2008 First version, released on an unsuspecting world. diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index 79c0372..1008dd6 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,141 +1,141 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; use parent 'autobox'; sub import { shift->SUPER::import(CODE => 'Closure::Attributes::Methods'); } package Closure::Attributes::Methods; use PadWalker; sub AUTOLOAD { my $code = shift; (my $attr = our $AUTOLOAD) =~ s/.*:://; $attr = "\$$attr"; # this will become smarter soon my $closed_over = PadWalker::closed_over($code); exists $closed_over->{$attr} or Carp::croak "$code does not close over $attr"; return ${ $closed_over->{$attr} } = shift if @_; return ${ $closed_over->{$attr} }; } =head1 NAME autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.01 released 17 Feb 08 +Version 0.02 released ??? =cut -our $VERSION = '0.01'; +our $VERSION = '0.02'; =head1 SYNOPSIS use autobox::Closure::Attributes; sub accgen { my $n = shift; return sub { $n += shift } } my $from_3 = accgen(3); $from_3->n # 3 $from_3->() # 4 $from_3->n # 4 $from_3->n(10) # 10 $from_3->() # 11 $from_3->m # "CODE(0xDEADBEEF) does not close over $m" =head1 WHAT? The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied, "Foolish pupil -- objects are merely a poor man's closures." Chastised, Anton took his leave from his master and returned to his cell, intent on studying closures. He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. He learned much, and looked forward to informing his master of his progress. On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's objects." At that moment, Anton became enlightened. =head1 DESCRIPTION This module uses powerful tools to give your closures accessors for each of the closed-over variables. You can get I<and> set them. For now, you can get I<only> the scalars that are closed over. Once I think of a better interface for getting and setting arrays and hashes I'll add that. C<< $code->'@foo' >> is the easy part. =head1 HOW DOES IT WORK? Go ahead and read the source code of this, it's not very long. L<autobox> lets you call methods on coderefs (or any other scalar). L<PadWalker> will let you see and change the closed-over variables of a coderef . C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the "attributes" of a closure-based object than it is for hash-based objects. =head1 WHY WOULD YOU DO THIS? <#moose:jrockway> that reminds me of another thing that might be insteresting: <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 <#moose:jrockway> basically adding accessors to closures <#moose:jrockway> very "closures are just classes" or "classes are just closures" =head1 AUTHOR Shawn M Moore, C<< <sartak at gmail.com> >> =head1 SEE ALSO L<autobox>, L<PadWalker> L</WHAT?> from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> =head1 BUGS my $code = do { my ($x, $y); sub { $y } }; $code->y # ok $code->x # CODE(0xDEADBEEF) does not close over $x This happens because Perl optimizes away the capturing of unused variables. Please report any other bugs through RT: email C<bug-autobox-closure-attributes at rt.cpan.org>, or browse L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1;
sartak/autobox-Closure-Attributes
6484138608b863900752ebb426d56f748d322b77
Oops, this is a TODO test, so we want it to fail..
diff --git a/t/900-bugs.t b/t/900-bugs.t index 235715b..754e389 100644 --- a/t/900-bugs.t +++ b/t/900-bugs.t @@ -1,19 +1,19 @@ #!/usr/bin/env perl use strict; use warnings; use Test::More tests => 2; use Test::Exception; use autobox::Closure::Attributes; my $code = do { my ($x, $y) = (10, 20); sub { $y } }; is($code->y, 20); TODO: { local $TODO = "Perl (5.8 anyway) does not capture unused variables"; - throws_ok { $code->x } qr/CODE\(0x[0-9a-fA-F]+\) does not close over \$x at/ + lives_ok { $code->x } }
sartak/autobox-Closure-Attributes
e8d39763f80f7eed129dd20684a13f1b03dd025d
Implementation and tests (oops, I didn't commit)
diff --git a/Makefile.PL b/Makefile.PL index 5527e38..7c2432f 100644 --- a/Makefile.PL +++ b/Makefile.PL @@ -1,14 +1,17 @@ # Load the Module::Install bundled in ./inc/ use inc::Module::Install; # Define metadata name 'autobox-Closure-Attributes'; all_from 'lib/autobox/Closure/Attributes.pm'; -requires ''; +requires 'parent'; +requires 'autobox'; +requires 'PadWalker'; build_requires 'Test::More'; +build_requires 'Test::Exception'; auto_install; WriteAll; diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm index aad147b..79c0372 100644 --- a/lib/autobox/Closure/Attributes.pm +++ b/lib/autobox/Closure/Attributes.pm @@ -1,83 +1,141 @@ #!perl package autobox::Closure::Attributes; use strict; use warnings; +use parent 'autobox'; +sub import { + shift->SUPER::import(CODE => 'Closure::Attributes::Methods'); +} + +package Closure::Attributes::Methods; +use PadWalker; + +sub AUTOLOAD { + my $code = shift; + (my $attr = our $AUTOLOAD) =~ s/.*:://; + + $attr = "\$$attr"; # this will become smarter soon + + my $closed_over = PadWalker::closed_over($code); + exists $closed_over->{$attr} + or Carp::croak "$code does not close over $attr"; + + return ${ $closed_over->{$attr} } = shift if @_; + return ${ $closed_over->{$attr} }; +} =head1 NAME -autobox::Closure::Attributes - ??? +autobox::Closure::Attributes - closures are objects are closures =head1 VERSION -Version 0.01 released ??? +Version 0.01 released 17 Feb 08 =cut our $VERSION = '0.01'; =head1 SYNOPSIS use autobox::Closure::Attributes; - do_stuff(); -=head1 DESCRIPTION + sub accgen { + my $n = shift; + return sub { $n += shift } + } + my $from_3 = accgen(3); + $from_3->n # 3 + $from_3->() # 4 + $from_3->n # 4 + $from_3->n(10) # 10 + $from_3->() # 11 + $from_3->m # "CODE(0xDEADBEEF) does not close over $m" -=head1 SEE ALSO +=head1 WHAT? -L<Foo::Bar> +The venerable master Qc Na was walking with his student, Anton. Hoping to +prompt the master into a discussion, Anton said "Master, I have heard that +objects are a very good thing - is this true?" Qc Na looked pityingly at his +student and replied, "Foolish pupil -- objects are merely a poor man's +closures." -=head1 AUTHOR +Chastised, Anton took his leave from his master and returned to his cell, +intent on studying closures. He carefully read the entire "Lambda: The +Ultimate..." series of papers and its cousins, and implemented a small Scheme +interpreter with a closure-based object system. He learned much, and looked +forward to informing his master of his progress. -Shawn M Moore, C<< <sartak at gmail.com> >> +On his next walk with Qc Na, Anton attempted to impress his master by saying +"Master, I have diligently studied the matter, and now understand that objects +are truly a poor man's closures." Qc Na responded by hitting Anton with his +stick, saying "When will you learn? Closures are a poor man's objects." At that +moment, Anton became enlightened. -=head1 BUGS +=head1 DESCRIPTION -No known bugs. +This module uses powerful tools to give your closures accessors for each of the +closed-over variables. You can get I<and> set them. -Please report any bugs through RT: email -C<bug-autobox-closure-attributes at rt.cpan.org>, or browse -L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. +For now, you can get I<only> the scalars that are closed over. Once I think of +a better interface for getting and setting arrays and hashes I'll add that. +C<< $code->'@foo' >> is the easy part. + +=head1 HOW DOES IT WORK? -=head1 SUPPORT +Go ahead and read the source code of this, it's not very long. -You can find this documentation for this module with the perldoc command. +L<autobox> lets you call methods on coderefs (or any other scalar). - perldoc autobox::Closure::Attributes +L<PadWalker> will let you see and change the closed-over variables of a coderef . -You can also look for information at: +C<AUTOLOAD> is really just an accessor. It's just harder to manipulate the +"attributes" of a closure-based object than it is for hash-based objects. -=over 4 +=head1 WHY WOULD YOU DO THIS? -=item * AnnoCPAN: Annotated CPAN documentation + <#moose:jrockway> that reminds me of another thing that might be insteresting: + <#moose:jrockway> sub foo { my $hello = 123; sub { $hello = $_[0] } }; my $closure = foo(); $closure->hello # 123 + <#moose:jrockway> basically adding accessors to closures + <#moose:jrockway> very "closures are just classes" or "classes are just closures" + +=head1 AUTHOR -L<http://annocpan.org/dist/autobox-Closure-Attributes> +Shawn M Moore, C<< <sartak at gmail.com> >> -=item * CPAN Ratings +=head1 SEE ALSO -L<http://cpanratings.perl.org/d/autobox-Closure-Attributes> +L<autobox>, L<PadWalker> -=item * RT: CPAN's request tracker +L</WHAT?> from Anton van Straaten: L<http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html> -L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=autobox-Closure-Attributes> +=head1 BUGS -=item * Search CPAN + my $code = do { + my ($x, $y); + sub { $y } + }; + $code->y # ok + $code->x # CODE(0xDEADBEEF) does not close over $x -L<http://search.cpan.org/dist/autobox-Closure-Attributes> +This happens because Perl optimizes away the capturing of unused variables. -=back +Please report any other bugs through RT: email +C<bug-autobox-closure-attributes at rt.cpan.org>, or browse +L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. =head1 COPYRIGHT AND LICENSE Copyright 2007 Shawn M Moore. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; diff --git a/t/001-basic.t b/t/001-basic.t deleted file mode 100644 index 45e8a5b..0000000 --- a/t/001-basic.t +++ /dev/null @@ -1,8 +0,0 @@ -#!perl -T -use strict; -use warnings; -use Test::More tests => 1; -use autobox::Closure::Attributes; - -ok(1); - diff --git a/t/001-synopsis.t b/t/001-synopsis.t new file mode 100644 index 0000000..a06f77f --- /dev/null +++ b/t/001-synopsis.t @@ -0,0 +1,21 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 6; +use Test::Exception; +use autobox::Closure::Attributes; + +sub accgen { + my $n = shift; + return sub { $n += shift || 1 } +} + +my $from_3 = accgen(3); + +is($from_3->n, 3); +is($from_3->(), 4); +is($from_3->n, 4); +is($from_3->n(10), 10); +is($from_3->(), 11); +throws_ok { $from_3->m } qr/CODE\(0x[0-9a-fA-F]+\) does not close over \$m at/; + diff --git a/t/002-share.t b/t/002-share.t new file mode 100644 index 0000000..195148b --- /dev/null +++ b/t/002-share.t @@ -0,0 +1,38 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 19; +use Test::Exception; +use autobox::Closure::Attributes; + +my ($inc, $double) = do { + my $x = 10; + (sub { ++$x }, sub { $x *= 2 }); +}; + +is($inc->x, 10); +is($inc->(), 11); +is($inc->x, 11); +is($inc->x(50), 50); +is($inc->(), 51); + +throws_ok { $inc->y } qr/CODE\(0x[0-9a-fA-F]+\) does not close over \$y at/; + +my $copy = $inc; + +is($copy->x, 51); +is($inc->(), 52); +is($copy->x, 52); +is($copy->(), 53); +is($inc->x, 53); + +is($double->x, 53); +is($double->x(10), 10); +is($copy->x, 10); +is($inc->x, 10); + +is($double->(), 20); +is($double->x, 20); +is($copy->x, 20); +is($inc->x, 20); + diff --git a/t/003-separate.t b/t/003-separate.t new file mode 100644 index 0000000..4531f71 --- /dev/null +++ b/t/003-separate.t @@ -0,0 +1,38 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 10; +use Test::Exception; +use autobox::Closure::Attributes; + +sub accgen { + my $n = shift; + return sub { $n += shift || 1 } +} + +my $from_3 = accgen(3); +my $from_5 = accgen(5); + +is($from_3->n, 3); +is($from_5->n, 5); + +$from_3->(); + +is($from_3->n, 4); +is($from_5->n, 5); + +$from_3->n(10); + +is($from_3->n, 10); +is($from_5->n, 5); + +$from_5->(); + +is($from_3->n, 10); +is($from_5->n, 6); + +$from_5->n(20); + +is($from_3->n, 10); +is($from_5->n, 20); + diff --git a/t/900-bugs.t b/t/900-bugs.t new file mode 100644 index 0000000..235715b --- /dev/null +++ b/t/900-bugs.t @@ -0,0 +1,19 @@ +#!/usr/bin/env perl +use strict; +use warnings; +use Test::More tests => 2; +use Test::Exception; +use autobox::Closure::Attributes; + +my $code = do { + my ($x, $y) = (10, 20); + sub { $y } +}; + +is($code->y, 20); +TODO: +{ + local $TODO = "Perl (5.8 anyway) does not capture unused variables"; + throws_ok { $code->x } qr/CODE\(0x[0-9a-fA-F]+\) does not close over \$x at/ +} +
sartak/autobox-Closure-Attributes
e1719cf2cc6918d3639857a9fb0a6af1beefbb01
Initial import of autobox::Closure::Attributes
diff --git a/Changes b/Changes new file mode 100644 index 0000000..033566b --- /dev/null +++ b/Changes @@ -0,0 +1,5 @@ +Revision history for autobox-Closure-Attributes + +0.01 Tue Feb 19 01:30:41 2008 + First version, released on an unsuspecting world. + diff --git a/Makefile.PL b/Makefile.PL new file mode 100644 index 0000000..5527e38 --- /dev/null +++ b/Makefile.PL @@ -0,0 +1,14 @@ +# Load the Module::Install bundled in ./inc/ +use inc::Module::Install; + +# Define metadata +name 'autobox-Closure-Attributes'; +all_from 'lib/autobox/Closure/Attributes.pm'; + +requires ''; + +build_requires 'Test::More'; + +auto_install; +WriteAll; + diff --git a/inc/Module/AutoInstall.pm b/inc/Module/AutoInstall.pm new file mode 100644 index 0000000..7efc552 --- /dev/null +++ b/inc/Module/AutoInstall.pm @@ -0,0 +1,768 @@ +#line 1 +package Module::AutoInstall; + +use strict; +use Cwd (); +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION}; +BEGIN { + $VERSION = '1.03'; +} + +# special map on pre-defined feature sets +my %FeatureMap = ( + '' => 'Core Features', # XXX: deprecated + '-core' => 'Core Features', +); + +# various lexical flags +my ( @Missing, @Existing, %DisabledTests, $UnderCPAN, $HasCPANPLUS ); +my ( $Config, $CheckOnly, $SkipInstall, $AcceptDefault, $TestOnly ); +my ( $PostambleActions, $PostambleUsed ); + +# See if it's a testing or non-interactive session +_accept_default( $ENV{AUTOMATED_TESTING} or ! -t STDIN ); +_init(); + +sub _accept_default { + $AcceptDefault = shift; +} + +sub missing_modules { + return @Missing; +} + +sub do_install { + __PACKAGE__->install( + [ + $Config + ? ( UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + : () + ], + @Missing, + ); +} + +# initialize various flags, and/or perform install +sub _init { + foreach my $arg ( + @ARGV, + split( + /[\s\t]+/, + $ENV{PERL_AUTOINSTALL} || $ENV{PERL_EXTUTILS_AUTOINSTALL} || '' + ) + ) + { + if ( $arg =~ /^--config=(.*)$/ ) { + $Config = [ split( ',', $1 ) ]; + } + elsif ( $arg =~ /^--installdeps=(.*)$/ ) { + __PACKAGE__->install( $Config, @Missing = split( /,/, $1 ) ); + exit 0; + } + elsif ( $arg =~ /^--default(?:deps)?$/ ) { + $AcceptDefault = 1; + } + elsif ( $arg =~ /^--check(?:deps)?$/ ) { + $CheckOnly = 1; + } + elsif ( $arg =~ /^--skip(?:deps)?$/ ) { + $SkipInstall = 1; + } + elsif ( $arg =~ /^--test(?:only)?$/ ) { + $TestOnly = 1; + } + } +} + +# overrides MakeMaker's prompt() to automatically accept the default choice +sub _prompt { + goto &ExtUtils::MakeMaker::prompt unless $AcceptDefault; + + my ( $prompt, $default ) = @_; + my $y = ( $default =~ /^[Yy]/ ); + + print $prompt, ' [', ( $y ? 'Y' : 'y' ), '/', ( $y ? 'n' : 'N' ), '] '; + print "$default\n"; + return $default; +} + +# the workhorse +sub import { + my $class = shift; + my @args = @_ or return; + my $core_all; + + print "*** $class version " . $class->VERSION . "\n"; + print "*** Checking for Perl dependencies...\n"; + + my $cwd = Cwd::cwd(); + + $Config = []; + + my $maxlen = length( + ( + sort { length($b) <=> length($a) } + grep { /^[^\-]/ } + map { + ref($_) + ? ( ( ref($_) eq 'HASH' ) ? keys(%$_) : @{$_} ) + : '' + } + map { +{@args}->{$_} } + grep { /^[^\-]/ or /^-core$/i } keys %{ +{@args} } + )[0] + ); + + while ( my ( $feature, $modules ) = splice( @args, 0, 2 ) ) { + my ( @required, @tests, @skiptests ); + my $default = 1; + my $conflict = 0; + + if ( $feature =~ m/^-(\w+)$/ ) { + my $option = lc($1); + + # check for a newer version of myself + _update_to( $modules, @_ ) and return if $option eq 'version'; + + # sets CPAN configuration options + $Config = $modules if $option eq 'config'; + + # promote every features to core status + $core_all = ( $modules =~ /^all$/i ) and next + if $option eq 'core'; + + next unless $option eq 'core'; + } + + print "[" . ( $FeatureMap{ lc($feature) } || $feature ) . "]\n"; + + $modules = [ %{$modules} ] if UNIVERSAL::isa( $modules, 'HASH' ); + + unshift @$modules, -default => &{ shift(@$modules) } + if ( ref( $modules->[0] ) eq 'CODE' ); # XXX: bugward combatability + + while ( my ( $mod, $arg ) = splice( @$modules, 0, 2 ) ) { + if ( $mod =~ m/^-(\w+)$/ ) { + my $option = lc($1); + + $default = $arg if ( $option eq 'default' ); + $conflict = $arg if ( $option eq 'conflict' ); + @tests = @{$arg} if ( $option eq 'tests' ); + @skiptests = @{$arg} if ( $option eq 'skiptests' ); + + next; + } + + printf( "- %-${maxlen}s ...", $mod ); + + if ( $arg and $arg =~ /^\D/ ) { + unshift @$modules, $arg; + $arg = 0; + } + + # XXX: check for conflicts and uninstalls(!) them. + if ( + defined( my $cur = _version_check( _load($mod), $arg ||= 0 ) ) ) + { + print "loaded. ($cur" . ( $arg ? " >= $arg" : '' ) . ")\n"; + push @Existing, $mod => $arg; + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + else { + print "missing." . ( $arg ? " (would need $arg)" : '' ) . "\n"; + push @required, $mod => $arg; + } + } + + next unless @required; + + my $mandatory = ( $feature eq '-core' or $core_all ); + + if ( + !$SkipInstall + and ( + $CheckOnly + or _prompt( + qq{==> Auto-install the } + . ( @required / 2 ) + . ( $mandatory ? ' mandatory' : ' optional' ) + . qq{ module(s) from CPAN?}, + $default ? 'y' : 'n', + ) =~ /^[Yy]/ + ) + ) + { + push( @Missing, @required ); + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + + elsif ( !$SkipInstall + and $default + and $mandatory + and + _prompt( qq{==> The module(s) are mandatory! Really skip?}, 'n', ) + =~ /^[Nn]/ ) + { + push( @Missing, @required ); + $DisabledTests{$_} = 1 for map { glob($_) } @skiptests; + } + + else { + $DisabledTests{$_} = 1 for map { glob($_) } @tests; + } + } + + $UnderCPAN = _check_lock(); # check for $UnderCPAN + + if ( @Missing and not( $CheckOnly or $UnderCPAN ) ) { + require Config; + print +"*** Dependencies will be installed the next time you type '$Config::Config{make}'.\n"; + + # make an educated guess of whether we'll need root permission. + print " (You may need to do that as the 'root' user.)\n" + if eval '$>'; + } + print "*** $class configuration finished.\n"; + + chdir $cwd; + + # import to main:: + no strict 'refs'; + *{'main::WriteMakefile'} = \&Write if caller(0) eq 'main'; +} + +# Check to see if we are currently running under CPAN.pm and/or CPANPLUS; +# if we are, then we simply let it taking care of our dependencies +sub _check_lock { + return unless @Missing; + + if ($ENV{PERL5_CPANPLUS_IS_RUNNING}) { + print <<'END_MESSAGE'; + +*** Since we're running under CPANPLUS, I'll just let it take care + of the dependency's installation later. +END_MESSAGE + return 1; + } + + _load_cpan(); + + # Find the CPAN lock-file + my $lock = MM->catfile( $CPAN::Config->{cpan_home}, ".lock" ); + return unless -f $lock; + + # Check the lock + local *LOCK; + return unless open(LOCK, $lock); + + if ( + ( $^O eq 'MSWin32' ? _under_cpan() : <LOCK> == getppid() ) + and ( $CPAN::Config->{prerequisites_policy} || '' ) ne 'ignore' + ) { + print <<'END_MESSAGE'; + +*** Since we're running under CPAN, I'll just let it take care + of the dependency's installation later. +END_MESSAGE + return 1; + } + + close LOCK; + return; +} + +sub install { + my $class = shift; + + my $i; # used below to strip leading '-' from config keys + my @config = ( map { s/^-// if ++$i; $_ } @{ +shift } ); + + my ( @modules, @installed ); + while ( my ( $pkg, $ver ) = splice( @_, 0, 2 ) ) { + + # grep out those already installed + if ( defined( _version_check( _load($pkg), $ver ) ) ) { + push @installed, $pkg; + } + else { + push @modules, $pkg, $ver; + } + } + + return @installed unless @modules; # nothing to do + return @installed if _check_lock(); # defer to the CPAN shell + + print "*** Installing dependencies...\n"; + + return unless _connected_to('cpan.org'); + + my %args = @config; + my %failed; + local *FAILED; + if ( $args{do_once} and open( FAILED, '.#autoinstall.failed' ) ) { + while (<FAILED>) { chomp; $failed{$_}++ } + close FAILED; + + my @newmod; + while ( my ( $k, $v ) = splice( @modules, 0, 2 ) ) { + push @newmod, ( $k => $v ) unless $failed{$k}; + } + @modules = @newmod; + } + + if ( _has_cpanplus() ) { + _install_cpanplus( \@modules, \@config ); + } else { + _install_cpan( \@modules, \@config ); + } + + print "*** $class installation finished.\n"; + + # see if we have successfully installed them + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + if ( defined( _version_check( _load($pkg), $ver ) ) ) { + push @installed, $pkg; + } + elsif ( $args{do_once} and open( FAILED, '>> .#autoinstall.failed' ) ) { + print FAILED "$pkg\n"; + } + } + + close FAILED if $args{do_once}; + + return @installed; +} + +sub _install_cpanplus { + my @modules = @{ +shift }; + my @config = _cpanplus_config( @{ +shift } ); + my $installed = 0; + + require CPANPLUS::Backend; + my $cp = CPANPLUS::Backend->new; + my $conf = $cp->configure_object; + + return unless $conf->can('conf') # 0.05x+ with "sudo" support + or _can_write($conf->_get_build('base')); # 0.04x + + # if we're root, set UNINST=1 to avoid trouble unless user asked for it. + my $makeflags = $conf->get_conf('makeflags') || ''; + if ( UNIVERSAL::isa( $makeflags, 'HASH' ) ) { + # 0.03+ uses a hashref here + $makeflags->{UNINST} = 1 unless exists $makeflags->{UNINST}; + + } else { + # 0.02 and below uses a scalar + $makeflags = join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) + if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); + + } + $conf->set_conf( makeflags => $makeflags ); + $conf->set_conf( prereqs => 1 ); + + + + while ( my ( $key, $val ) = splice( @config, 0, 2 ) ) { + $conf->set_conf( $key, $val ); + } + + my $modtree = $cp->module_tree; + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + print "*** Installing $pkg...\n"; + + MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; + + my $success; + my $obj = $modtree->{$pkg}; + + if ( $obj and defined( _version_check( $obj->{version}, $ver ) ) ) { + my $pathname = $pkg; + $pathname =~ s/::/\\W/; + + foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { + delete $INC{$inc}; + } + + my $rv = $cp->install( modules => [ $obj->{module} ] ); + + if ( $rv and ( $rv->{ $obj->{module} } or $rv->{ok} ) ) { + print "*** $pkg successfully installed.\n"; + $success = 1; + } else { + print "*** $pkg installation cancelled.\n"; + $success = 0; + } + + $installed += $success; + } else { + print << "."; +*** Could not find a version $ver or above for $pkg; skipping. +. + } + + MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; + } + + return $installed; +} + +sub _cpanplus_config { + my @config = (); + while ( @_ ) { + my ($key, $value) = (shift(), shift()); + if ( $key eq 'prerequisites_policy' ) { + if ( $value eq 'follow' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_INSTALL(); + } elsif ( $value eq 'ask' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_ASK(); + } elsif ( $value eq 'ignore' ) { + $value = CPANPLUS::Internals::Constants::PREREQ_IGNORE(); + } else { + die "*** Cannot convert option $key = '$value' to CPANPLUS version.\n"; + } + } else { + die "*** Cannot convert option $key to CPANPLUS version.\n"; + } + } + return @config; +} + +sub _install_cpan { + my @modules = @{ +shift }; + my @config = @{ +shift }; + my $installed = 0; + my %args; + + _load_cpan(); + require Config; + + if (CPAN->VERSION < 1.80) { + # no "sudo" support, probe for writableness + return unless _can_write( MM->catfile( $CPAN::Config->{cpan_home}, 'sources' ) ) + and _can_write( $Config::Config{sitelib} ); + } + + # if we're root, set UNINST=1 to avoid trouble unless user asked for it. + my $makeflags = $CPAN::Config->{make_install_arg} || ''; + $CPAN::Config->{make_install_arg} = + join( ' ', split( ' ', $makeflags ), 'UNINST=1' ) + if ( $makeflags !~ /\bUNINST\b/ and eval qq{ $> eq '0' } ); + + # don't show start-up info + $CPAN::Config->{inhibit_startup_message} = 1; + + # set additional options + while ( my ( $opt, $arg ) = splice( @config, 0, 2 ) ) { + ( $args{$opt} = $arg, next ) + if $opt =~ /^force$/; # pseudo-option + $CPAN::Config->{$opt} = $arg; + } + + local $CPAN::Config->{prerequisites_policy} = 'follow'; + + while ( my ( $pkg, $ver ) = splice( @modules, 0, 2 ) ) { + MY::preinstall( $pkg, $ver ) or next if defined &MY::preinstall; + + print "*** Installing $pkg...\n"; + + my $obj = CPAN::Shell->expand( Module => $pkg ); + my $success = 0; + + if ( $obj and defined( _version_check( $obj->cpan_version, $ver ) ) ) { + my $pathname = $pkg; + $pathname =~ s/::/\\W/; + + foreach my $inc ( grep { m/$pathname.pm/i } keys(%INC) ) { + delete $INC{$inc}; + } + + my $rv = $args{force} ? CPAN::Shell->force( install => $pkg ) + : CPAN::Shell->install($pkg); + $rv ||= eval { + $CPAN::META->instance( 'CPAN::Distribution', $obj->cpan_file, ) + ->{install} + if $CPAN::META; + }; + + if ( $rv eq 'YES' ) { + print "*** $pkg successfully installed.\n"; + $success = 1; + } + else { + print "*** $pkg installation failed.\n"; + $success = 0; + } + + $installed += $success; + } + else { + print << "."; +*** Could not find a version $ver or above for $pkg; skipping. +. + } + + MY::postinstall( $pkg, $ver, $success ) if defined &MY::postinstall; + } + + return $installed; +} + +sub _has_cpanplus { + return ( + $HasCPANPLUS = ( + $INC{'CPANPLUS/Config.pm'} + or _load('CPANPLUS::Shell::Default') + ) + ); +} + +# make guesses on whether we're under the CPAN installation directory +sub _under_cpan { + require Cwd; + require File::Spec; + + my $cwd = File::Spec->canonpath( Cwd::cwd() ); + my $cpan = File::Spec->canonpath( $CPAN::Config->{cpan_home} ); + + return ( index( $cwd, $cpan ) > -1 ); +} + +sub _update_to { + my $class = __PACKAGE__; + my $ver = shift; + + return + if defined( _version_check( _load($class), $ver ) ); # no need to upgrade + + if ( + _prompt( "==> A newer version of $class ($ver) is required. Install?", + 'y' ) =~ /^[Nn]/ + ) + { + die "*** Please install $class $ver manually.\n"; + } + + print << "."; +*** Trying to fetch it from CPAN... +. + + # install ourselves + _load($class) and return $class->import(@_) + if $class->install( [], $class, $ver ); + + print << '.'; exit 1; + +*** Cannot bootstrap myself. :-( Installation terminated. +. +} + +# check if we're connected to some host, using inet_aton +sub _connected_to { + my $site = shift; + + return ( + ( _load('Socket') and Socket::inet_aton($site) ) or _prompt( + qq( +*** Your host cannot resolve the domain name '$site', which + probably means the Internet connections are unavailable. +==> Should we try to install the required module(s) anyway?), 'n' + ) =~ /^[Yy]/ + ); +} + +# check if a directory is writable; may create it on demand +sub _can_write { + my $path = shift; + mkdir( $path, 0755 ) unless -e $path; + + return 1 if -w $path; + + print << "."; +*** You are not allowed to write to the directory '$path'; + the installation may fail due to insufficient permissions. +. + + if ( + eval '$>' and lc(`sudo -V`) =~ /version/ and _prompt( + qq( +==> Should we try to re-execute the autoinstall process with 'sudo'?), + ((-t STDIN) ? 'y' : 'n') + ) =~ /^[Yy]/ + ) + { + + # try to bootstrap ourselves from sudo + print << "."; +*** Trying to re-execute the autoinstall process with 'sudo'... +. + my $missing = join( ',', @Missing ); + my $config = join( ',', + UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + if $Config; + + return + unless system( 'sudo', $^X, $0, "--config=$config", + "--installdeps=$missing" ); + + print << "."; +*** The 'sudo' command exited with error! Resuming... +. + } + + return _prompt( + qq( +==> Should we try to install the required module(s) anyway?), 'n' + ) =~ /^[Yy]/; +} + +# load a module and return the version it reports +sub _load { + my $mod = pop; # class/instance doesn't matter + my $file = $mod; + + $file =~ s|::|/|g; + $file .= '.pm'; + + local $@; + return eval { require $file; $mod->VERSION } || ( $@ ? undef: 0 ); +} + +# Load CPAN.pm and it's configuration +sub _load_cpan { + return if $CPAN::VERSION; + require CPAN; + if ( $CPAN::HandleConfig::VERSION ) { + # Newer versions of CPAN have a HandleConfig module + CPAN::HandleConfig->load; + } else { + # Older versions had the load method in Config directly + CPAN::Config->load; + } +} + +# compare two versions, either use Sort::Versions or plain comparison +sub _version_check { + my ( $cur, $min ) = @_; + return unless defined $cur; + + $cur =~ s/\s+$//; + + # check for version numbers that are not in decimal format + if ( ref($cur) or ref($min) or $cur =~ /v|\..*\./ or $min =~ /v|\..*\./ ) { + if ( ( $version::VERSION or defined( _load('version') )) and + version->can('new') + ) { + + # use version.pm if it is installed. + return ( + ( version->new($cur) >= version->new($min) ) ? $cur : undef ); + } + elsif ( $Sort::Versions::VERSION or defined( _load('Sort::Versions') ) ) + { + + # use Sort::Versions as the sorting algorithm for a.b.c versions + return ( ( Sort::Versions::versioncmp( $cur, $min ) != -1 ) + ? $cur + : undef ); + } + + warn "Cannot reliably compare non-decimal formatted versions.\n" + . "Please install version.pm or Sort::Versions.\n"; + } + + # plain comparison + local $^W = 0; # shuts off 'not numeric' bugs + return ( $cur >= $min ? $cur : undef ); +} + +# nothing; this usage is deprecated. +sub main::PREREQ_PM { return {}; } + +sub _make_args { + my %args = @_; + + $args{PREREQ_PM} = { %{ $args{PREREQ_PM} || {} }, @Existing, @Missing } + if $UnderCPAN or $TestOnly; + + if ( $args{EXE_FILES} and -e 'MANIFEST' ) { + require ExtUtils::Manifest; + my $manifest = ExtUtils::Manifest::maniread('MANIFEST'); + + $args{EXE_FILES} = + [ grep { exists $manifest->{$_} } @{ $args{EXE_FILES} } ]; + } + + $args{test}{TESTS} ||= 't/*.t'; + $args{test}{TESTS} = join( ' ', + grep { !exists( $DisabledTests{$_} ) } + map { glob($_) } split( /\s+/, $args{test}{TESTS} ) ); + + my $missing = join( ',', @Missing ); + my $config = + join( ',', UNIVERSAL::isa( $Config, 'HASH' ) ? %{$Config} : @{$Config} ) + if $Config; + + $PostambleActions = ( + $missing + ? "\$(PERL) $0 --config=$config --installdeps=$missing" + : "\$(NOECHO) \$(NOOP)" + ); + + return %args; +} + +# a wrapper to ExtUtils::MakeMaker::WriteMakefile +sub Write { + require Carp; + Carp::croak "WriteMakefile: Need even number of args" if @_ % 2; + + if ($CheckOnly) { + print << "."; +*** Makefile not written in check-only mode. +. + return; + } + + my %args = _make_args(@_); + + no strict 'refs'; + + $PostambleUsed = 0; + local *MY::postamble = \&postamble unless defined &MY::postamble; + ExtUtils::MakeMaker::WriteMakefile(%args); + + print << "." unless $PostambleUsed; +*** WARNING: Makefile written with customized MY::postamble() without + including contents from Module::AutoInstall::postamble() -- + auto installation features disabled. Please contact the author. +. + + return 1; +} + +sub postamble { + $PostambleUsed = 1; + + return << "."; + +config :: installdeps +\t\$(NOECHO) \$(NOOP) + +checkdeps :: +\t\$(PERL) $0 --checkdeps + +installdeps :: +\t$PostambleActions + +. + +} + +1; + +__END__ + +#line 1003 diff --git a/inc/Module/Install.pm b/inc/Module/Install.pm new file mode 100644 index 0000000..9d13686 --- /dev/null +++ b/inc/Module/Install.pm @@ -0,0 +1,281 @@ +#line 1 +package Module::Install; + +# For any maintainers: +# The load order for Module::Install is a bit magic. +# It goes something like this... +# +# IF ( host has Module::Install installed, creating author mode ) { +# 1. Makefile.PL calls "use inc::Module::Install" +# 2. $INC{inc/Module/Install.pm} set to installed version of inc::Module::Install +# 3. The installed version of inc::Module::Install loads +# 4. inc::Module::Install calls "require Module::Install" +# 5. The ./inc/ version of Module::Install loads +# } ELSE { +# 1. Makefile.PL calls "use inc::Module::Install" +# 2. $INC{inc/Module/Install.pm} set to ./inc/ version of Module::Install +# 3. The ./inc/ version of Module::Install loads +# } + +use 5.004; +use strict 'vars'; + +use vars qw{$VERSION}; +BEGIN { + # All Module::Install core packages now require synchronised versions. + # This will be used to ensure we don't accidentally load old or + # different versions of modules. + # This is not enforced yet, but will be some time in the next few + # releases once we can make sure it won't clash with custom + # Module::Install extensions. + $VERSION = '0.67'; +} + +# Whether or not inc::Module::Install is actually loaded, the +# $INC{inc/Module/Install.pm} is what will still get set as long as +# the caller loaded module this in the documented manner. +# If not set, the caller may NOT have loaded the bundled version, and thus +# they may not have a MI version that works with the Makefile.PL. This would +# result in false errors or unexpected behaviour. And we don't want that. +my $file = join( '/', 'inc', split /::/, __PACKAGE__ ) . '.pm'; +unless ( $INC{$file} ) { + die <<"END_DIE"; +Please invoke ${\__PACKAGE__} with: + + use inc::${\__PACKAGE__}; + +not: + + use ${\__PACKAGE__}; + +END_DIE +} + +# If the script that is loading Module::Install is from the future, +# then make will detect this and cause it to re-run over and over +# again. This is bad. Rather than taking action to touch it (which +# is unreliable on some platforms and requires write permissions) +# for now we should catch this and refuse to run. +if ( -f $0 and (stat($0))[9] > time ) { + die << "END_DIE"; +Your installer $0 has a modification time in the future. + +This is known to create infinite loops in make. + +Please correct this, then run $0 again. + +END_DIE +} + +use Cwd (); +use File::Find (); +use File::Path (); +use FindBin; + +*inc::Module::Install::VERSION = *VERSION; +@inc::Module::Install::ISA = __PACKAGE__; + +sub autoload { + my $self = shift; + my $who = $self->_caller; + my $cwd = Cwd::cwd(); + my $sym = "${who}::AUTOLOAD"; + $sym->{$cwd} = sub { + my $pwd = Cwd::cwd(); + if ( my $code = $sym->{$pwd} ) { + # delegate back to parent dirs + goto &$code unless $cwd eq $pwd; + } + $$sym =~ /([^:]+)$/ or die "Cannot autoload $who - $sym"; + unshift @_, ($self, $1); + goto &{$self->can('call')} unless uc($1) eq $1; + }; +} + +sub import { + my $class = shift; + my $self = $class->new(@_); + my $who = $self->_caller; + + unless ( -f $self->{file} ) { + require "$self->{path}/$self->{dispatch}.pm"; + File::Path::mkpath("$self->{prefix}/$self->{author}"); + $self->{admin} = "$self->{name}::$self->{dispatch}"->new( _top => $self ); + $self->{admin}->init; + @_ = ($class, _self => $self); + goto &{"$self->{name}::import"}; + } + + *{"${who}::AUTOLOAD"} = $self->autoload; + $self->preload; + + # Unregister loader and worker packages so subdirs can use them again + delete $INC{"$self->{file}"}; + delete $INC{"$self->{path}.pm"}; +} + +sub preload { + my ($self) = @_; + + unless ( $self->{extensions} ) { + $self->load_extensions( + "$self->{prefix}/$self->{path}", $self + ); + } + + my @exts = @{$self->{extensions}}; + unless ( @exts ) { + my $admin = $self->{admin}; + @exts = $admin->load_all_extensions; + } + + my %seen; + foreach my $obj ( @exts ) { + while (my ($method, $glob) = each %{ref($obj) . '::'}) { + next unless $obj->can($method); + next if $method =~ /^_/; + next if $method eq uc($method); + $seen{$method}++; + } + } + + my $who = $self->_caller; + foreach my $name ( sort keys %seen ) { + *{"${who}::$name"} = sub { + ${"${who}::AUTOLOAD"} = "${who}::$name"; + goto &{"${who}::AUTOLOAD"}; + }; + } +} + +sub new { + my ($class, %args) = @_; + + # ignore the prefix on extension modules built from top level. + my $base_path = Cwd::abs_path($FindBin::Bin); + unless ( Cwd::abs_path(Cwd::cwd()) eq $base_path ) { + delete $args{prefix}; + } + + return $args{_self} if $args{_self}; + + $args{dispatch} ||= 'Admin'; + $args{prefix} ||= 'inc'; + $args{author} ||= ($^O eq 'VMS' ? '_author' : '.author'); + $args{bundle} ||= 'inc/BUNDLES'; + $args{base} ||= $base_path; + $class =~ s/^\Q$args{prefix}\E:://; + $args{name} ||= $class; + $args{version} ||= $class->VERSION; + unless ( $args{path} ) { + $args{path} = $args{name}; + $args{path} =~ s!::!/!g; + } + $args{file} ||= "$args{base}/$args{prefix}/$args{path}.pm"; + + bless( \%args, $class ); +} + +sub call { + my ($self, $method) = @_; + my $obj = $self->load($method) or return; + splice(@_, 0, 2, $obj); + goto &{$obj->can($method)}; +} + +sub load { + my ($self, $method) = @_; + + $self->load_extensions( + "$self->{prefix}/$self->{path}", $self + ) unless $self->{extensions}; + + foreach my $obj (@{$self->{extensions}}) { + return $obj if $obj->can($method); + } + + my $admin = $self->{admin} or die <<"END_DIE"; +The '$method' method does not exist in the '$self->{prefix}' path! +Please remove the '$self->{prefix}' directory and run $0 again to load it. +END_DIE + + my $obj = $admin->load($method, 1); + push @{$self->{extensions}}, $obj; + + $obj; +} + +sub load_extensions { + my ($self, $path, $top) = @_; + + unless ( grep { lc $_ eq lc $self->{prefix} } @INC ) { + unshift @INC, $self->{prefix}; + } + + foreach my $rv ( $self->find_extensions($path) ) { + my ($file, $pkg) = @{$rv}; + next if $self->{pathnames}{$pkg}; + + local $@; + my $new = eval { require $file; $pkg->can('new') }; + unless ( $new ) { + warn $@ if $@; + next; + } + $self->{pathnames}{$pkg} = delete $INC{$file}; + push @{$self->{extensions}}, &{$new}($pkg, _top => $top ); + } + + $self->{extensions} ||= []; +} + +sub find_extensions { + my ($self, $path) = @_; + + my @found; + File::Find::find( sub { + my $file = $File::Find::name; + return unless $file =~ m!^\Q$path\E/(.+)\.pm\Z!is; + my $subpath = $1; + return if lc($subpath) eq lc($self->{dispatch}); + + $file = "$self->{path}/$subpath.pm"; + my $pkg = "$self->{name}::$subpath"; + $pkg =~ s!/!::!g; + + # If we have a mixed-case package name, assume case has been preserved + # correctly. Otherwise, root through the file to locate the case-preserved + # version of the package name. + if ( $subpath eq lc($subpath) || $subpath eq uc($subpath) ) { + open PKGFILE, "<$subpath.pm" or die "find_extensions: Can't open $subpath.pm: $!"; + my $in_pod = 0; + while ( <PKGFILE> ) { + $in_pod = 1 if /^=\w/; + $in_pod = 0 if /^=cut/; + next if ($in_pod || /^=cut/); # skip pod text + next if /^\s*#/; # and comments + if ( m/^\s*package\s+($pkg)\s*;/i ) { + $pkg = $1; + last; + } + } + close PKGFILE; + } + + push @found, [ $file, $pkg ]; + }, $path ) if -d $path; + + @found; +} + +sub _caller { + my $depth = 0; + my $call = caller($depth); + while ( $call eq __PACKAGE__ ) { + $depth++; + $call = caller($depth); + } + return $call; +} + +1; diff --git a/inc/Module/Install/AutoInstall.pm b/inc/Module/Install/AutoInstall.pm new file mode 100644 index 0000000..c244cb5 --- /dev/null +++ b/inc/Module/Install/AutoInstall.pm @@ -0,0 +1,61 @@ +#line 1 +package Module::Install::AutoInstall; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub AutoInstall { $_[0] } + +sub run { + my $self = shift; + $self->auto_install_now(@_); +} + +sub write { + my $self = shift; + $self->auto_install(@_); +} + +sub auto_install { + my $self = shift; + return if $self->{done}++; + + # Flatten array of arrays into a single array + my @core = map @$_, map @$_, grep ref, + $self->build_requires, $self->requires; + + my @config = @_; + + # We'll need Module::AutoInstall + $self->include('Module::AutoInstall'); + require Module::AutoInstall; + + Module::AutoInstall->import( + (@config ? (-config => \@config) : ()), + (@core ? (-core => \@core) : ()), + $self->features, + ); + + $self->makemaker_args( Module::AutoInstall::_make_args() ); + + my $class = ref($self); + $self->postamble( + "# --- $class section:\n" . + Module::AutoInstall::postamble() + ); +} + +sub auto_install_now { + my $self = shift; + $self->auto_install(@_); + Module::AutoInstall::do_install(); +} + +1; diff --git a/inc/Module/Install/Base.pm b/inc/Module/Install/Base.pm new file mode 100644 index 0000000..81fbcb6 --- /dev/null +++ b/inc/Module/Install/Base.pm @@ -0,0 +1,70 @@ +#line 1 +package Module::Install::Base; + +$VERSION = '0.67'; + +# Suspend handler for "redefined" warnings +BEGIN { + my $w = $SIG{__WARN__}; + $SIG{__WARN__} = sub { $w }; +} + +### This is the ONLY module that shouldn't have strict on +# use strict; + +#line 41 + +sub new { + my ($class, %args) = @_; + + foreach my $method ( qw(call load) ) { + *{"$class\::$method"} = sub { + shift()->_top->$method(@_); + } unless defined &{"$class\::$method"}; + } + + bless( \%args, $class ); +} + +#line 61 + +sub AUTOLOAD { + my $self = shift; + local $@; + my $autoload = eval { $self->_top->autoload } or return; + goto &$autoload; +} + +#line 76 + +sub _top { $_[0]->{_top} } + +#line 89 + +sub admin { + $_[0]->_top->{admin} or Module::Install::Base::FakeAdmin->new; +} + +sub is_admin { + $_[0]->admin->VERSION; +} + +sub DESTROY {} + +package Module::Install::Base::FakeAdmin; + +my $Fake; +sub new { $Fake ||= bless(\@_, $_[0]) } + +sub AUTOLOAD {} + +sub DESTROY {} + +# Restore warning handler +BEGIN { + $SIG{__WARN__} = $SIG{__WARN__}->(); +} + +1; + +#line 138 diff --git a/inc/Module/Install/Can.pm b/inc/Module/Install/Can.pm new file mode 100644 index 0000000..5d1eab8 --- /dev/null +++ b/inc/Module/Install/Can.pm @@ -0,0 +1,82 @@ +#line 1 +package Module::Install::Can; + +use strict; +use Module::Install::Base; +use Config (); +### This adds a 5.005 Perl version dependency. +### This is a bug and will be fixed. +use File::Spec (); +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +# check if we can load some module +### Upgrade this to not have to load the module if possible +sub can_use { + my ($self, $mod, $ver) = @_; + $mod =~ s{::|\\}{/}g; + $mod .= '.pm' unless $mod =~ /\.pm$/i; + + my $pkg = $mod; + $pkg =~ s{/}{::}g; + $pkg =~ s{\.pm$}{}i; + + local $@; + eval { require $mod; $pkg->VERSION($ver || 0); 1 }; +} + +# check if we can run some command +sub can_run { + my ($self, $cmd) = @_; + + my $_cmd = $cmd; + return $_cmd if (-x $_cmd or $_cmd = MM->maybe_command($_cmd)); + + for my $dir ((split /$Config::Config{path_sep}/, $ENV{PATH}), '.') { + my $abs = File::Spec->catfile($dir, $_[1]); + return $abs if (-x $abs or $abs = MM->maybe_command($abs)); + } + + return; +} + +# can we locate a (the) C compiler +sub can_cc { + my $self = shift; + my @chunks = split(/ /, $Config::Config{cc}) or return; + + # $Config{cc} may contain args; try to find out the program part + while (@chunks) { + return $self->can_run("@chunks") || (pop(@chunks), next); + } + + return; +} + +# Fix Cygwin bug on maybe_command(); +if ( $^O eq 'cygwin' ) { + require ExtUtils::MM_Cygwin; + require ExtUtils::MM_Win32; + if ( ! defined(&ExtUtils::MM_Cygwin::maybe_command) ) { + *ExtUtils::MM_Cygwin::maybe_command = sub { + my ($self, $file) = @_; + if ($file =~ m{^/cygdrive/}i and ExtUtils::MM_Win32->can('maybe_command')) { + ExtUtils::MM_Win32->maybe_command($file); + } else { + ExtUtils::MM_Unix->maybe_command($file); + } + } + } +} + +1; + +__END__ + +#line 157 diff --git a/inc/Module/Install/Fetch.pm b/inc/Module/Install/Fetch.pm new file mode 100644 index 0000000..e884477 --- /dev/null +++ b/inc/Module/Install/Fetch.pm @@ -0,0 +1,93 @@ +#line 1 +package Module::Install::Fetch; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub get_file { + my ($self, %args) = @_; + my ($scheme, $host, $path, $file) = + $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; + + if ( $scheme eq 'http' and ! eval { require LWP::Simple; 1 } ) { + $args{url} = $args{ftp_url} + or (warn("LWP support unavailable!\n"), return); + ($scheme, $host, $path, $file) = + $args{url} =~ m|^(\w+)://([^/]+)(.+)/(.+)| or return; + } + + $|++; + print "Fetching '$file' from $host... "; + + unless (eval { require Socket; Socket::inet_aton($host) }) { + warn "'$host' resolve failed!\n"; + return; + } + + return unless $scheme eq 'ftp' or $scheme eq 'http'; + + require Cwd; + my $dir = Cwd::getcwd(); + chdir $args{local_dir} or return if exists $args{local_dir}; + + if (eval { require LWP::Simple; 1 }) { + LWP::Simple::mirror($args{url}, $file); + } + elsif (eval { require Net::FTP; 1 }) { eval { + # use Net::FTP to get past firewall + my $ftp = Net::FTP->new($host, Passive => 1, Timeout => 600); + $ftp->login("anonymous", '[email protected]'); + $ftp->cwd($path); + $ftp->binary; + $ftp->get($file) or (warn("$!\n"), return); + $ftp->quit; + } } + elsif (my $ftp = $self->can_run('ftp')) { eval { + # no Net::FTP, fallback to ftp.exe + require FileHandle; + my $fh = FileHandle->new; + + local $SIG{CHLD} = 'IGNORE'; + unless ($fh->open("|$ftp -n")) { + warn "Couldn't open ftp: $!\n"; + chdir $dir; return; + } + + my @dialog = split(/\n/, <<"END_FTP"); +open $host +user anonymous anonymous\@example.com +cd $path +binary +get $file $file +quit +END_FTP + foreach (@dialog) { $fh->print("$_\n") } + $fh->close; + } } + else { + warn "No working 'ftp' program available!\n"; + chdir $dir; return; + } + + unless (-f $file) { + warn "Fetching failed: $@\n"; + chdir $dir; return; + } + + return if exists $args{size} and -s $file != $args{size}; + system($args{run}) if exists $args{run}; + unlink($file) if $args{remove}; + + print(((!exists $args{check_for} or -e $args{check_for}) + ? "done!" : "failed! ($!)"), "\n"); + chdir $dir; return !$?; +} + +1; diff --git a/inc/Module/Install/Include.pm b/inc/Module/Install/Include.pm new file mode 100644 index 0000000..574acc8 --- /dev/null +++ b/inc/Module/Install/Include.pm @@ -0,0 +1,34 @@ +#line 1 +package Module::Install::Include; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub include { + shift()->admin->include(@_); +} + +sub include_deps { + shift()->admin->include_deps(@_); +} + +sub auto_include { + shift()->admin->auto_include(@_); +} + +sub auto_include_deps { + shift()->admin->auto_include_deps(@_); +} + +sub auto_include_dependent_dists { + shift()->admin->auto_include_dependent_dists(@_); +} + +1; diff --git a/inc/Module/Install/Makefile.pm b/inc/Module/Install/Makefile.pm new file mode 100644 index 0000000..fbc5cb2 --- /dev/null +++ b/inc/Module/Install/Makefile.pm @@ -0,0 +1,237 @@ +#line 1 +package Module::Install::Makefile; + +use strict 'vars'; +use Module::Install::Base; +use ExtUtils::MakeMaker (); + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub Makefile { $_[0] } + +my %seen = (); + +sub prompt { + shift; + + # Infinite loop protection + my @c = caller(); + if ( ++$seen{"$c[1]|$c[2]|$_[0]"} > 3 ) { + die "Caught an potential prompt infinite loop ($c[1]|$c[2]|$_[0])"; + } + + # In automated testing, always use defaults + if ( $ENV{AUTOMATED_TESTING} and ! $ENV{PERL_MM_USE_DEFAULT} ) { + local $ENV{PERL_MM_USE_DEFAULT} = 1; + goto &ExtUtils::MakeMaker::prompt; + } else { + goto &ExtUtils::MakeMaker::prompt; + } +} + +sub makemaker_args { + my $self = shift; + my $args = ($self->{makemaker_args} ||= {}); + %$args = ( %$args, @_ ) if @_; + $args; +} + +# For mm args that take multiple space-seperated args, +# append an argument to the current list. +sub makemaker_append { + my $self = sShift; + my $name = shift; + my $args = $self->makemaker_args; + $args->{name} = defined $args->{$name} + ? join( ' ', $args->{name}, @_ ) + : join( ' ', @_ ); +} + +sub build_subdirs { + my $self = shift; + my $subdirs = $self->makemaker_args->{DIR} ||= []; + for my $subdir (@_) { + push @$subdirs, $subdir; + } +} + +sub clean_files { + my $self = shift; + my $clean = $self->makemaker_args->{clean} ||= {}; + %$clean = ( + %$clean, + FILES => join(' ', grep length, $clean->{FILES}, @_), + ); +} + +sub realclean_files { + my $self = shift; + my $realclean = $self->makemaker_args->{realclean} ||= {}; + %$realclean = ( + %$realclean, + FILES => join(' ', grep length, $realclean->{FILES}, @_), + ); +} + +sub libs { + my $self = shift; + my $libs = ref $_[0] ? shift : [ shift ]; + $self->makemaker_args( LIBS => $libs ); +} + +sub inc { + my $self = shift; + $self->makemaker_args( INC => shift ); +} + +my %test_dir = (); + +sub _wanted_t { + /\.t$/ and -f $_ and $test_dir{$File::Find::dir} = 1; +} + +sub tests_recursive { + my $self = shift; + if ( $self->tests ) { + die "tests_recursive will not work if tests are already defined"; + } + my $dir = shift || 't'; + unless ( -d $dir ) { + die "tests_recursive dir '$dir' does not exist"; + } + require File::Find; + %test_dir = (); + File::Find::find( \&_wanted_t, $dir ); + $self->tests( join ' ', map { "$_/*.t" } sort keys %test_dir ); +} + +sub write { + my $self = shift; + die "&Makefile->write() takes no arguments\n" if @_; + + my $args = $self->makemaker_args; + $args->{DISTNAME} = $self->name; + $args->{NAME} = $self->module_name || $self->name || $self->determine_NAME($args); + $args->{VERSION} = $self->version || $self->determine_VERSION($args); + $args->{NAME} =~ s/-/::/g; + if ( $self->tests ) { + $args->{test} = { TESTS => $self->tests }; + } + if ($] >= 5.005) { + $args->{ABSTRACT} = $self->abstract; + $args->{AUTHOR} = $self->author; + } + if ( eval($ExtUtils::MakeMaker::VERSION) >= 6.10 ) { + $args->{NO_META} = 1; + } + if ( eval($ExtUtils::MakeMaker::VERSION) > 6.17 and $self->sign ) { + $args->{SIGN} = 1; + } + unless ( $self->is_admin ) { + delete $args->{SIGN}; + } + + # merge both kinds of requires into prereq_pm + my $prereq = ($args->{PREREQ_PM} ||= {}); + %$prereq = ( %$prereq, + map { @$_ } + map { @$_ } + grep $_, + ($self->build_requires, $self->requires) + ); + + # merge both kinds of requires into prereq_pm + my $subdirs = ($args->{DIR} ||= []); + if ($self->bundles) { + foreach my $bundle (@{ $self->bundles }) { + my ($file, $dir) = @$bundle; + push @$subdirs, $dir if -d $dir; + delete $prereq->{$file}; + } + } + + if ( my $perl_version = $self->perl_version ) { + eval "use $perl_version; 1" + or die "ERROR: perl: Version $] is installed, " + . "but we need version >= $perl_version"; + } + + $args->{INSTALLDIRS} = $self->installdirs; + + my %args = map { ( $_ => $args->{$_} ) } grep {defined($args->{$_})} keys %$args; + + my $user_preop = delete $args{dist}->{PREOP}; + if (my $preop = $self->admin->preop($user_preop)) { + $args{dist} = $preop; + } + + my $mm = ExtUtils::MakeMaker::WriteMakefile(%args); + $self->fix_up_makefile($mm->{FIRST_MAKEFILE} || 'Makefile'); +} + +sub fix_up_makefile { + my $self = shift; + my $makefile_name = shift; + my $top_class = ref($self->_top) || ''; + my $top_version = $self->_top->VERSION || ''; + + my $preamble = $self->preamble + ? "# Preamble by $top_class $top_version\n" + . $self->preamble + : ''; + my $postamble = "# Postamble by $top_class $top_version\n" + . ($self->postamble || ''); + + local *MAKEFILE; + open MAKEFILE, "< $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; + my $makefile = do { local $/; <MAKEFILE> }; + close MAKEFILE or die $!; + + $makefile =~ s/\b(test_harness\(\$\(TEST_VERBOSE\), )/$1'inc', /; + $makefile =~ s/( -I\$\(INST_ARCHLIB\))/ -Iinc$1/g; + $makefile =~ s/( "-I\$\(INST_LIB\)")/ "-Iinc"$1/g; + $makefile =~ s/^(FULLPERL = .*)/$1 "-Iinc"/m; + $makefile =~ s/^(PERL = .*)/$1 "-Iinc"/m; + + # Module::Install will never be used to build the Core Perl + # Sometimes PERL_LIB and PERL_ARCHLIB get written anyway, which breaks + # PREFIX/PERL5LIB, and thus, install_share. Blank them if they exist + $makefile =~ s/^PERL_LIB = .+/PERL_LIB =/m; + #$makefile =~ s/^PERL_ARCHLIB = .+/PERL_ARCHLIB =/m; + + # Perl 5.005 mentions PERL_LIB explicitly, so we have to remove that as well. + $makefile =~ s/("?)-I\$\(PERL_LIB\)\1//g; + + # XXX - This is currently unused; not sure if it breaks other MM-users + # $makefile =~ s/^pm_to_blib\s+:\s+/pm_to_blib :: /mg; + + open MAKEFILE, "> $makefile_name" or die "fix_up_makefile: Couldn't open $makefile_name: $!"; + print MAKEFILE "$preamble$makefile$postamble" or die $!; + close MAKEFILE or die $!; + + 1; +} + +sub preamble { + my ($self, $text) = @_; + $self->{preamble} = $text . $self->{preamble} if defined $text; + $self->{preamble}; +} + +sub postamble { + my ($self, $text) = @_; + $self->{postamble} ||= $self->admin->postamble; + $self->{postamble} .= $text if defined $text; + $self->{postamble} +} + +1; + +__END__ + +#line 363 diff --git a/inc/Module/Install/Metadata.pm b/inc/Module/Install/Metadata.pm new file mode 100644 index 0000000..b886046 --- /dev/null +++ b/inc/Module/Install/Metadata.pm @@ -0,0 +1,336 @@ +#line 1 +package Module::Install::Metadata; + +use strict 'vars'; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +my @scalar_keys = qw{ + name module_name abstract author version license + distribution_type perl_version tests installdirs +}; + +my @tuple_keys = qw{ + build_requires requires recommends bundles +}; + +sub Meta { shift } +sub Meta_ScalarKeys { @scalar_keys } +sub Meta_TupleKeys { @tuple_keys } + +foreach my $key (@scalar_keys) { + *$key = sub { + my $self = shift; + return $self->{values}{$key} if defined wantarray and !@_; + $self->{values}{$key} = shift; + return $self; + }; +} + +foreach my $key (@tuple_keys) { + *$key = sub { + my $self = shift; + return $self->{values}{$key} unless @_; + + my @rv; + while (@_) { + my $module = shift or last; + my $version = shift || 0; + if ( $module eq 'perl' ) { + $version =~ s{^(\d+)\.(\d+)\.(\d+)} + {$1 + $2/1_000 + $3/1_000_000}e; + $self->perl_version($version); + next; + } + my $rv = [ $module, $version ]; + push @rv, $rv; + } + push @{ $self->{values}{$key} }, @rv; + @rv; + }; +} + +# configure_requires is currently a null-op +sub configure_requires { 1 } + +# Aliases for build_requires that will have alternative +# meanings in some future version of META.yml. +sub test_requires { shift->build_requires(@_) } +sub install_requires { shift->build_requires(@_) } + +# Aliases for installdirs options +sub install_as_core { $_[0]->installdirs('perl') } +sub install_as_cpan { $_[0]->installdirs('site') } +sub install_as_site { $_[0]->installdirs('site') } +sub install_as_vendor { $_[0]->installdirs('vendor') } + +sub sign { + my $self = shift; + return $self->{'values'}{'sign'} if defined wantarray and ! @_; + $self->{'values'}{'sign'} = ( @_ ? $_[0] : 1 ); + return $self; +} + +sub dynamic_config { + my $self = shift; + unless ( @_ ) { + warn "You MUST provide an explicit true/false value to dynamic_config, skipping\n"; + return $self; + } + $self->{'values'}{'dynamic_config'} = $_[0] ? 1 : 0; + return $self; +} + +sub all_from { + my ( $self, $file ) = @_; + + unless ( defined($file) ) { + my $name = $self->name + or die "all_from called with no args without setting name() first"; + $file = join('/', 'lib', split(/-/, $name)) . '.pm'; + $file =~ s{.*/}{} unless -e $file; + die "all_from: cannot find $file from $name" unless -e $file; + } + + $self->version_from($file) unless $self->version; + $self->perl_version_from($file) unless $self->perl_version; + + # The remaining probes read from POD sections; if the file + # has an accompanying .pod, use that instead + my $pod = $file; + if ( $pod =~ s/\.pm$/.pod/i and -e $pod ) { + $file = $pod; + } + + $self->author_from($file) unless $self->author; + $self->license_from($file) unless $self->license; + $self->abstract_from($file) unless $self->abstract; +} + +sub provides { + my $self = shift; + my $provides = ( $self->{values}{provides} ||= {} ); + %$provides = (%$provides, @_) if @_; + return $provides; +} + +sub auto_provides { + my $self = shift; + return $self unless $self->is_admin; + + unless (-e 'MANIFEST') { + warn "Cannot deduce auto_provides without a MANIFEST, skipping\n"; + return $self; + } + + # Avoid spurious warnings as we are not checking manifest here. + + local $SIG{__WARN__} = sub {1}; + require ExtUtils::Manifest; + local *ExtUtils::Manifest::manicheck = sub { return }; + + require Module::Build; + my $build = Module::Build->new( + dist_name => $self->name, + dist_version => $self->version, + license => $self->license, + ); + $self->provides(%{ $build->find_dist_packages || {} }); +} + +sub feature { + my $self = shift; + my $name = shift; + my $features = ( $self->{values}{features} ||= [] ); + + my $mods; + + if ( @_ == 1 and ref( $_[0] ) ) { + # The user used ->feature like ->features by passing in the second + # argument as a reference. Accomodate for that. + $mods = $_[0]; + } else { + $mods = \@_; + } + + my $count = 0; + push @$features, ( + $name => [ + map { + ref($_) ? ( ref($_) eq 'HASH' ) ? %$_ + : @$_ + : $_ + } @$mods + ] + ); + + return @$features; +} + +sub features { + my $self = shift; + while ( my ( $name, $mods ) = splice( @_, 0, 2 ) ) { + $self->feature( $name, @$mods ); + } + return $self->{values}->{features} + ? @{ $self->{values}->{features} } + : (); +} + +sub no_index { + my $self = shift; + my $type = shift; + push @{ $self->{values}{no_index}{$type} }, @_ if $type; + return $self->{values}{no_index}; +} + +sub read { + my $self = shift; + $self->include_deps( 'YAML', 0 ); + + require YAML; + my $data = YAML::LoadFile('META.yml'); + + # Call methods explicitly in case user has already set some values. + while ( my ( $key, $value ) = each %$data ) { + next unless $self->can($key); + if ( ref $value eq 'HASH' ) { + while ( my ( $module, $version ) = each %$value ) { + $self->can($key)->($self, $module => $version ); + } + } + else { + $self->can($key)->($self, $value); + } + } + return $self; +} + +sub write { + my $self = shift; + return $self unless $self->is_admin; + $self->admin->write_meta; + return $self; +} + +sub version_from { + my ( $self, $file ) = @_; + require ExtUtils::MM_Unix; + $self->version( ExtUtils::MM_Unix->parse_version($file) ); +} + +sub abstract_from { + my ( $self, $file ) = @_; + require ExtUtils::MM_Unix; + $self->abstract( + bless( + { DISTNAME => $self->name }, + 'ExtUtils::MM_Unix' + )->parse_abstract($file) + ); +} + +sub _slurp { + my ( $self, $file ) = @_; + + local *FH; + open FH, "< $file" or die "Cannot open $file.pod: $!"; + do { local $/; <FH> }; +} + +sub perl_version_from { + my ( $self, $file ) = @_; + + if ( + $self->_slurp($file) =~ m/ + ^ + use \s* + v? + ([\d_\.]+) + \s* ; + /ixms + ) + { + my $v = $1; + $v =~ s{_}{}g; + $self->perl_version($1); + } + else { + warn "Cannot determine perl version info from $file\n"; + return; + } +} + +sub author_from { + my ( $self, $file ) = @_; + my $content = $self->_slurp($file); + if ($content =~ m/ + =head \d \s+ (?:authors?)\b \s* + ([^\n]*) + | + =head \d \s+ (?:licen[cs]e|licensing|copyright|legal)\b \s* + .*? copyright .*? \d\d\d[\d.]+ \s* (?:\bby\b)? \s* + ([^\n]*) + /ixms) { + my $author = $1 || $2; + $author =~ s{E<lt>}{<}g; + $author =~ s{E<gt>}{>}g; + $self->author($author); + } + else { + warn "Cannot determine author info from $file\n"; + } +} + +sub license_from { + my ( $self, $file ) = @_; + + if ( + $self->_slurp($file) =~ m/ + ( + =head \d \s+ + (?:licen[cs]e|licensing|copyright|legal)\b + .*? + ) + (=head\\d.*|=cut.*|) + \z + /ixms + ) + { + my $license_text = $1; + my @phrases = ( + 'under the same (?:terms|license) as perl itself' => 'perl', 1, + 'GNU public license' => 'gpl', 1, + 'GNU lesser public license' => 'gpl', 1, + 'BSD license' => 'bsd', 1, + 'Artistic license' => 'artistic', 1, + 'GPL' => 'gpl', 1, + 'LGPL' => 'lgpl', 1, + 'BSD' => 'bsd', 1, + 'Artistic' => 'artistic', 1, + 'MIT' => 'mit', 1, + 'proprietary' => 'proprietary', 0, + ); + while ( my ($pattern, $license, $osi) = splice(@phrases, 0, 3) ) { + $pattern =~ s{\s+}{\\s+}g; + if ( $license_text =~ /\b$pattern\b/i ) { + if ( $osi and $license_text =~ /All rights reserved/i ) { + warn "LEGAL WARNING: 'All rights reserved' may invalidate Open Source licenses. Consider removing it."; + } + $self->license($license); + return 1; + } + } + } + + warn "Cannot determine license info from $file\n"; + return 'unknown'; +} + +1; diff --git a/inc/Module/Install/Win32.pm b/inc/Module/Install/Win32.pm new file mode 100644 index 0000000..612dc30 --- /dev/null +++ b/inc/Module/Install/Win32.pm @@ -0,0 +1,65 @@ +#line 1 +package Module::Install::Win32; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +# determine if the user needs nmake, and download it if needed +sub check_nmake { + my $self = shift; + $self->load('can_run'); + $self->load('get_file'); + + require Config; + return unless ( + $^O eq 'MSWin32' and + $Config::Config{make} and + $Config::Config{make} =~ /^nmake\b/i and + ! $self->can_run('nmake') + ); + + print "The required 'nmake' executable not found, fetching it...\n"; + + require File::Basename; + my $rv = $self->get_file( + url => 'http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe', + ftp_url => 'ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe', + local_dir => File::Basename::dirname($^X), + size => 51928, + run => 'Nmake15.exe /o > nul', + check_for => 'Nmake.exe', + remove => 1, + ); + + if (!$rv) { + die <<'END_MESSAGE'; + +------------------------------------------------------------------------------- + +Since you are using Microsoft Windows, you will need the 'nmake' utility +before installation. It's available at: + + http://download.microsoft.com/download/vc15/Patch/1.52/W95/EN-US/Nmake15.exe + or + ftp://ftp.microsoft.com/Softlib/MSLFILES/Nmake15.exe + +Please download the file manually, save it to a directory in %PATH% (e.g. +C:\WINDOWS\COMMAND\), then launch the MS-DOS command line shell, "cd" to +that directory, and run "Nmake15.exe" from there; that will create the +'nmake.exe' file needed by this module. + +You may then resume the installation process described in README. + +------------------------------------------------------------------------------- +END_MESSAGE + } +} + +1; diff --git a/inc/Module/Install/WriteAll.pm b/inc/Module/Install/WriteAll.pm new file mode 100644 index 0000000..e1db381 --- /dev/null +++ b/inc/Module/Install/WriteAll.pm @@ -0,0 +1,43 @@ +#line 1 +package Module::Install::WriteAll; + +use strict; +use Module::Install::Base; + +use vars qw{$VERSION $ISCORE @ISA}; +BEGIN { + $VERSION = '0.67'; + $ISCORE = 1; + @ISA = qw{Module::Install::Base}; +} + +sub WriteAll { + my $self = shift; + my %args = ( + meta => 1, + sign => 0, + inline => 0, + check_nmake => 1, + @_ + ); + + $self->sign(1) if $args{sign}; + $self->Meta->write if $args{meta}; + $self->admin->WriteAll(%args) if $self->is_admin; + + if ( $0 =~ /Build.PL$/i ) { + $self->Build->write; + } else { + $self->check_nmake if $args{check_nmake}; + unless ( $self->makemaker_args->{'PL_FILES'} ) { + $self->makemaker_args( PL_FILES => {} ); + } + if ($args{inline}) { + $self->Inline->write; + } else { + $self->Makefile->write; + } + } +} + +1; diff --git a/lib/autobox/Closure/Attributes.pm b/lib/autobox/Closure/Attributes.pm new file mode 100644 index 0000000..aad147b --- /dev/null +++ b/lib/autobox/Closure/Attributes.pm @@ -0,0 +1,83 @@ +#!perl +package autobox::Closure::Attributes; +use strict; +use warnings; + + + +=head1 NAME + +autobox::Closure::Attributes - ??? + +=head1 VERSION + +Version 0.01 released ??? + +=cut + +our $VERSION = '0.01'; + +=head1 SYNOPSIS + + use autobox::Closure::Attributes; + do_stuff(); + +=head1 DESCRIPTION + + + +=head1 SEE ALSO + +L<Foo::Bar> + +=head1 AUTHOR + +Shawn M Moore, C<< <sartak at gmail.com> >> + +=head1 BUGS + +No known bugs. + +Please report any bugs through RT: email +C<bug-autobox-closure-attributes at rt.cpan.org>, or browse +L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=autobox-Closure-Attributes>. + +=head1 SUPPORT + +You can find this documentation for this module with the perldoc command. + + perldoc autobox::Closure::Attributes + +You can also look for information at: + +=over 4 + +=item * AnnoCPAN: Annotated CPAN documentation + +L<http://annocpan.org/dist/autobox-Closure-Attributes> + +=item * CPAN Ratings + +L<http://cpanratings.perl.org/d/autobox-Closure-Attributes> + +=item * RT: CPAN's request tracker + +L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=autobox-Closure-Attributes> + +=item * Search CPAN + +L<http://search.cpan.org/dist/autobox-Closure-Attributes> + +=back + +=head1 COPYRIGHT AND LICENSE + +Copyright 2007 Shawn M Moore. + +This program is free software; you can redistribute it and/or modify it +under the same terms as Perl itself. + +=cut + +1; + diff --git a/t/000-load.t b/t/000-load.t new file mode 100644 index 0000000..b674286 --- /dev/null +++ b/t/000-load.t @@ -0,0 +1,7 @@ +#!perl -T +use strict; +use warnings; +use Test::More tests => 1; + +use_ok 'autobox::Closure::Attributes'; + diff --git a/t/001-basic.t b/t/001-basic.t new file mode 100644 index 0000000..45e8a5b --- /dev/null +++ b/t/001-basic.t @@ -0,0 +1,8 @@ +#!perl -T +use strict; +use warnings; +use Test::More tests => 1; +use autobox::Closure::Attributes; + +ok(1); +