Skip to content
Snippets Groups Projects
Fact.cs 130 KiB
Newer Older
  • Learn to ignore specific revisions
  • using System;
    using System.Collections.Generic;
    
    using UnityEngine;
    
    using UnityEngine.Networking;
    
    John Schihada's avatar
    John Schihada committed
    using TMPro;
    
    using Newtonsoft.Json;
    
    using static CommunicationEvents;
    
    using System.Linq.Expressions;
    using UnityEngine.ProBuilder;
    
    using System.Reflection;
    using System.Linq;
    
    
    public class ParsingDictionary
    {
    
        //TODO? get rid of this, use reflection? instead, if possible
        //TODO: docu
    
    ki7077's avatar
    ki7077 committed
    
        //public static Dictionary<string, Func<Scroll.ScrollFact, Fact>> parseFactDictionary = new Dictionary<string, Func<Scroll.ScrollFact, Fact>>() {
    
        public static Dictionary<string, Func<Scroll.ScrollFact, Fact>> parseFactDictionary = new() {
    
            {SOMDocManager.MMT_OMS_URI.Point, PointFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.Metric, LineFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.Angle, AngleFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.LineType, RayFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.LineOf, RayFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.OnLine, OnLineFact.parseFact},
    
            //90Degree-Angle
    
            {SOMDocManager.MMT_OMS_URI.Eq, AngleFact.parseFact},
    
            //Parallel-LineFact
    
            {SOMDocManager.MMT_OMS_URI.ParallelLine, ParallelLineFact.parseFact},
    
            {SOMDocManager.MMT_OMS_URI.CircleType3d, CircleFact.parseFact},
            {SOMDocManager.MMT_OMS_URI.OnCircle, OnCircleFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.AnglePlaneLine, AngleCircleLineFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.RadiusCircleMetric, RadiusFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.AreaCircle, AreaCircleFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.OrthoCircleLine, OrthogonalCircleLineFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.VolumeCone ,ConeVolumeFact.parseFact  },
            {SOMDocManager.MMT_OMS_URI.TruncatedVolumeCone ,TruncatedConeVolumeFact.parseFact  },
            {SOMDocManager.MMT_OMS_URI.RightAngle, RightAngleFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.CylinderVolume, CylinderVolumeFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.TestType, TestFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.EqualityCircles, EqualCirclesFact.parseFact },
            {SOMDocManager.MMT_OMS_URI.UnEqualityCircles, UnEqualCirclesFact.parseFact }
    
        // TODO: get rid of this
        public static Dictionary<string, string> parseTermsToId = new();
    
    /// <summary>
    /// class to Read AddFact Responses.
    /// </summary>
    // TODO: docu
    
    public class AddFactResponse
    {
        public string uri;
    
    
        public static bool sendAdd(MMTDeclaration mmtDecl, out string uri)
        {
            string body = MMTSymbolDeclaration.ToJson(mmtDecl);
            return sendAdd(CommunicationEvents.ServerAdress + "/fact/add", body, out uri);
        }
    
        public static bool sendAdd(string path, string body, out string uri)
    
        {
            if (!CommunicationEvents.ServerRunning)
            {
                Debug.LogWarning("Server not running");
    
            if (VerboseURI)
    
            //Put constructor parses stringbody to byteArray internally  (goofy workaround)
    
            using UnityWebRequest www = UnityWebRequest.Put(path, body);
    
            www.method = UnityWebRequest.kHttpVerbPOST;
            www.SetRequestHeader("Content-Type", "application/json");
            www.timeout = 1;
    
            //TODO: implement real asynchronous communication ...
            AsyncOperation op = www.SendWebRequest();
    
            while (!op.isDone) ;
    
            if (www.result == UnityWebRequest.Result.ConnectionError
             || www.result == UnityWebRequest.Result.ProtocolError)
    
            }
            else
            {
                string answer = www.downloadHandler.text;
    
                AddFactResponse res = JsonUtility.FromJson<AddFactResponse>(answer);
    
                if (VerboseURI)
                    Debug.Log("Server added Fact:\n" + res.uri);
    
                uri = res.uri;
                return true;
    
    /// <summary>
    /// %Fact representation of Unity; mostly mirrors Facts of MMT.
    /// </summary>
    
    [JsonConverter(typeof(JsonSubtypes), "s_type")]
    [JsonSubtypes.KnownSubType(typeof(PointFact), "PointFact")]
    [JsonSubtypes.KnownSubType(typeof(LineFact), "LineFact")]
    [JsonSubtypes.KnownSubType(typeof(RayFact), "RayFact")]
    [JsonSubtypes.KnownSubType(typeof(OnLineFact), "OnLineFact")]
    [JsonSubtypes.KnownSubType(typeof(AngleFact), "AngleFact")]
    
    ki7077's avatar
    ki7077 committed
    [JsonSubtypes.KnownSubType(typeof(CircleFact), "CircleFact")]
    [JsonSubtypes.KnownSubType(typeof(ParallelLineFact), "ParallelLine")]
    [JsonSubtypes.KnownSubType(typeof(OnCircleFact), "OnCircleFact")]
    [JsonSubtypes.KnownSubType(typeof(AngleCircleLineFact), "AnglePlaneLineFact")]
    [JsonSubtypes.KnownSubType(typeof(AreaCircleFact), "AreaCircle")]
    [JsonSubtypes.KnownSubType(typeof(RadiusFact), "RadiusCircleMetric")]
    [JsonSubtypes.KnownSubType(typeof(OrthogonalCircleLineFact), "OrthogonalCircleLineFact")]
    [JsonSubtypes.KnownSubType(typeof(ConeVolumeFact), "ConeVolumeFact")]
    [JsonSubtypes.KnownSubType(typeof(TruncatedConeVolumeFact), "TruncatedConeVolumeFact")]
    [JsonSubtypes.KnownSubType(typeof(RightAngleFact), "RightAngleFact")]
    [JsonSubtypes.KnownSubType(typeof(CylinderVolumeFact), "CylinderVolumeFact")]
    [JsonSubtypes.KnownSubType(typeof(TestFact), "TestFact")]
    [JsonSubtypes.KnownSubType(typeof(EqualCirclesFact), "EqualCirclesFact")]
    [JsonSubtypes.KnownSubType(typeof(UnEqualCirclesFact), "UnEqualCirclesFact")]
    
    //[JsonSubtypes.KnownSubType(typeof(FunctionFact<T0, TResult>), "FunctionFact<T0, TResult>")] //TODO: generics?
    
    [JsonSubtypes.KnownSubType(typeof(FunctionFact<float, float>), "FunctionFact<System.Single, System.Single>")]
    
    [JsonSubtypes.KnownSubType(typeof(FunctionFactFloat <Vector3>), "FunctionFact<System.Single, UnityEngine.Vector3>")]
    
    public abstract class Fact
    
        /// <summary>
        /// Reference to <c>GameObject</c> that represents this Fact in the GameWorld.
        /// </summary>
        /// <seealso cref="FactObject"/>
    
        /// <summary>
        /// Collection of <c>Type</c>s of *all* available <see cref="Fact"/>s to choose from.
        /// </summary>
        [JsonIgnore]
        public static readonly Type[] Types = TypeExtensions<Fact>.UAssemblyInheritenceTypes; // Assembly.GetExecutingAssembly().GetTypes().Where(typeof(Fact).IsAssignableFrom).ToArray();
    
    
        /// [ClassName] for JSON de-/serialization.
        /// Set in every non-abstract subclass of Fact.
        /// Also add JsonSubtypes.KnownSubType decorator for deserialization to Fact!
    
        [JsonProperty]
    
        protected /*new*/ string s_type = "ERROR: set s_type in T:Fact"; // In the subtype! NOT here!
    
        /// <value>
        /// Unique Id. e.g.: MMT URI
        /// </value>
    
        public string Id
        {
    
            get { return _URI; }
    
            set { _URI ??= value; } // needed for JSON
    
        protected string _URI;
    
        /// <value>
        /// <c>get</c> initiates and subsequently updates a human readable name. <remarks>Should be called once a constructor call to be initiated.</remarks>
        /// <c>set</c> calls <see cref="rename(string)"/>
        /// </value>
    
        public string Label
        {
            get
            { // in case of renamed dependables
    
                return (_Facts.GetNumberOfFacts() == 0 && this is not PointFact) // JsonSerialization toggle && allow first (Point)Fact to be created
    
                    || (hasCustomLabel && _CustomLabel != null)
    
    
        /// <value>
        /// Is true if Fact has a custom <see cref="Label"/> which is not <c>null</c> or <c>""</c>.
        /// </value>
    
        public bool hasCustomLabel => LabelId < 0;
    
    
        /// <summary>
        /// Stores custom <see cref="Label"/> if set.
        /// </summary>
    
        /// <summary>
        /// Counter to organize auto generated <see cref="Label"/>.
        /// Set to negative, if custom \ref Label is assigned.
        /// </summary>
        // property for JSON to set AFTER Label => declare AFTER Label
    
        public int LabelId { get; set; }
    
        /// <summary>
        /// Reference to <see cref="FactOrganizer"/> in which this Fact and all its <see cref="getDependentFactIds">depending Facts</see> are beeing organized.
        /// </summary>
    
    BenniHome's avatar
    BenniHome committed
    
    
        /// <summary>
        /// Only being used by [JsonReader](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonReader.htm) to initiate empty \ref Fact "Facts".
    
        protected Fact()
        {
            this._Facts = new FactOrganizer();
    
        /// <summary>
        /// Standard base-constructor.
        /// </summary>
        /// <param name="organizer"><see cref="_Facts"/></param>
    
        protected Fact(FactOrganizer organizer)
        {
            this._Facts = organizer;
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
        /// <param name="organizer"><see cref="_Facts"/></param>
    
        protected Fact(Fact fact, FactOrganizer organizer)
    
    BenniHome's avatar
    BenniHome committed
        {
    
            this._Facts = organizer;
    
            LabelId = fact.LabelId;
    
    
            if (hasCustomLabel)
                _CustomLabel = fact.Label;
        }
    
    
        /// <summary>
        /// Assignes a custom <see cref="Label"/>, if <paramref name="newLabel"/> is not yet taken;
        /// or clears custom <see cref="Label"/>.
        /// </summary>
        /// <param name="newLabel">To be new <see cref="Label"/>. To reset to auto-generation set to <c>null</c> or <c>""</c>.</param>
        /// <returns></returns>
    
    
        //TODO: notify about updated dependable Labelnames for UI
        //TODO: check for colissions with not yet generated names
        public bool rename(string newLabel)
        // returns true if succeded
        {
            if (string.IsNullOrEmpty(newLabel))
            // switch back to autogenerated
            {
                generateLabel();
                _CustomLabel = null;
                return true;
            }
            else
            // set CustomLabel if available
            {
                if (_Facts.ContainsLabel(newLabel))
                    return false;
    
                freeAutoLabel();
                _CustomLabel = newLabel;
    
    BenniHome's avatar
    BenniHome committed
        }
    
        /// <returns><see langword="true"/> if Fact depends on other \ref Fact "Facts"; equivalent to <see cref="getDependentFactIds"/> returns non empty array</returns>
    
        public abstract bool hasDependentFacts();
    
        /// <returns> array of Fact <see cref="Id"> Ids </see> on which this Fact depends.</returns>
        /// <example><see cref="AngleFact"/> needs 3 <see cref="PointFact"/>s to be defined.</example>
    
        public abstract string[] getDependentFactIds();
    
        /// <summary>
        /// Initiates a <paramref name="prefab"/> at <paramref name="transform"/> e.g. by setting <see cref="Label"/>.
        /// </summary>
        /// <remarks>Does not set <see cref="Representation"/>.</remarks>
        /// <param name="prefab"><c>GameObject</c> Prefab that will represent this Fact</param>
        /// <param name="transform"><c>Transform</c> where to initiate <paramref name="prefab"/></param>
        /// <returns></returns>
    
        // TODO: set Representation here instead of ...
    
    John Schihada's avatar
    John Schihada committed
        public abstract GameObject instantiateDisplay(GameObject prefab, Transform transform);
    
        /// <summary>
        /// Frees ressources e.g. <see cref="Label"/> and will eventually delete %Fact Server-Side in far-near future when feature is supported.
        /// </summary>
        /// <param name="keep_clean">when set to <c>true</c> will upkeep <see cref="Label"/> organization.</param>
    
        // TODO? replace by ~Fact() { }
    
        public virtual void delete(bool keep_clean = true)
    
            //TODO: MMT: delete over there
    
                Debug.Log("Server removed Fact:\n" + this.Id);
    
        /// <summary>
        /// Compares \ref Fact "this" against <paramref name="f2"/>.
        /// </summary>
        /// <param name="f2">Fact to compare to</param>
        /// <returns><c>true</c> if <paramref name="f2"/> is semantical very similar to \ref Fact "this"</returns>
    
        public abstract bool Equivalent(Fact f2);
    
    
        /// <summary>
        /// Compares <paramref name="f1"/> against <paramref name="f2"/>.
        /// </summary>
        /// <param name="f1">Fact to compare to</param>
        /// <param name="f2">Fact to compare to</param>
        /// <returns><c>true</c> if <paramref name="f2"/> is semantical very similar to <paramref name="f1"/></returns>
    
        public abstract bool Equivalent(Fact f1, Fact f2);
    
        /// <summary>
        /// canonical
        /// </summary>
        /// <returns>unique-ish Hash</returns>
    
        public abstract override int GetHashCode();
    
        /// <summary>
        /// auto-generates <see cref="Label"/> using generation variable(s) e.g. <see cref="LabelId"/>;
        /// if custom <see cref="Label"/> is set, tries to restore original generated <see cref="Label"/> **without** resetting <see cref="_CustomLabel"/>. If original <see cref="Label"/> is already taken, a new one will be generated.
        /// </summary>
        /// <returns>auto-generated <see cref="Label"/></returns>
    
                // reload Label if possible
    
                LabelId = _Facts.UnusedLabelIds.Remove(-LabelId) ? -LabelId : 0;
    
    
                if (_Facts.UnusedLabelIds.Count == 0)
                    LabelId = ++_Facts.MaxLabelId;
    
                    LabelId = _Facts.UnusedLabelIds.Min;
                    _Facts.UnusedLabelIds.Remove(LabelId);
    
            return ((char)(64 + LabelId)).ToString();
        }
    
    
        /// <summary>
        /// Parses <see cref="Scroll.ScrollFact"/> to actual Fact
        /// </summary>
        /// <param name="fact">instance to be parsed</param>
        /// <returns>parsed Fact</returns>
        public static Fact parseFact(Scroll.ScrollFact fact)
    
    
        /// <summary>
        /// Tells <see cref="_Facts"/> that \ref Fact "this" no longer uses auto-generated <see cref="Label"/>, but remembers current generation variable(s).
        /// </summary>
    
    
        // TODO? only get _Fact to freeLabel/
        public /*protected internal*/ void freeAutoLabel()
        {
            if (LabelId > 0)
    
                _Facts.UnusedLabelIds.Add(LabelId);
    
                // store Label for name-persistance
    
    /// <summary>
    /// Implements CRTP for <see cref="Fact"/>; Escalates constructors;
    /// </summary>
    /// <typeparam name="T">class, which inherits from FactWrappedCRTP</typeparam>
    
    public abstract class FactWrappedCRTP<T> : Fact where T : FactWrappedCRTP<T>
    
    BenniHome's avatar
    BenniHome committed
    {
    
        /// <summary>\copydoc Fact.Fact()</summary>
    
        protected FactWrappedCRTP() : base() { }
    
    
        /// <summary>\copydoc Fact.Fact(FactOrganizer)</summary>
    
        protected FactWrappedCRTP(FactOrganizer organizer) : base(organizer) { }
    
    
        /// <summary>\copydoc Fact.Fact(Fact, FactOrganizer)</summary>
    
        protected FactWrappedCRTP(FactWrappedCRTP<T> fact, FactOrganizer organizer) : base(fact, organizer) { }
    
    
        public override bool Equivalent(Fact f2)
    
            => Equivalent(this, f2);
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        public override bool Equivalent(Fact f1, Fact f2)
    
            => f1.GetType() == f2.GetType() && EquivalentWrapped((T)f1, (T)f2);
    
        /// <summary>CRTP step of <see cref="Equivalent(Fact)"/> and <see cref="Equivalent(Fact, Fact)"/></summary>
    
        protected abstract bool EquivalentWrapped(T f1, T f2);
    }
    
    
    /// <summary>
    /// Point in 3D Space
    /// </summary>
    
    public class PointFact : FactWrappedCRTP<PointFact>
    
        [JsonProperty]
    
        public Vector3 Point;
    
        /// <summary> Orientation for <see cref="Fact.Representation"/> </summary>
    
        /// <summary> \copydoc Fact.Fact </summary>
    
        public PointFact() : base()
        {
            this.Point = Vector3.zero;
            this.Normal = Vector3.zero;
        }
    
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
        /// <param name="old_to_new"><c>Dictionary</c> mapping <paramref name="fact"/>.<see cref="getDependentFactIds"/> in <paramref name="fact"/>.<see cref="Fact._Facts"/> to corresponding <see cref="Fact.Id"/> in <paramref name="organizer"/> </param>
        /// <param name="organizer">sets <see cref="_Facts"/></param>
    
        public PointFact(PointFact fact, Dictionary<string, string> old_to_new, FactOrganizer organizer) : base(fact, organizer)
    
            => init(fact.Point, fact.Normal);
    
        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="P">sets <see cref="Point"/></param>
        /// <param name="N">sets <see cref="Normal"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public PointFact(Vector3 P, Vector3 N, FactOrganizer organizer) : base(organizer)
    
            => init(P, N);
    
        /// <summary>
        /// Initiates <see cref="Point"/>, <see cref="Normal"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
        /// </summary>
        /// <param name="P">sets <see cref="Point"/></param>
        /// <param name="N">sets <see cref="Normal"/></param>
    
        private void init(Vector3 P, Vector3 N)
    
    BenniHome's avatar
    BenniHome committed
        {
    
            this.Point = P;
            this.Normal = N;
    
    
            SOMDoc tp = new OMS(MMT_OMS_URI.Point);
            SOMDoc df = new OMA(
                    new OMS(MMT_OMS_URI.Tuple),
                    new List<SOMDoc> {
    
                            new OMF(P.x),
                            new OMF(P.y),
                            new OMF(P.z),
                    }
                );
    
            AddFactResponse.sendAdd(new MMTSymbolDeclaration(Label, tp, df), out _URI);
    
            ParsingDictionary.parseTermsToId[df.ToString()] = _URI;
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// <see cref="Normal"/> set to <c>Vector3.up</c>
        /// </summary>
        /// <param name="a">sets <c>x</c> coordinate of <see cref="Point"/></param>
        /// <param name="b">sets <c>y</c> coordinate of <see cref="Point"/></param>
        /// <param name="c">sets <c>z</c> coordinate of <see cref="Point"/></param>
        /// <param name="uri">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public PointFact(float a, float b, float c, string uri, FactOrganizer organizer) : base(organizer)
    
    BenniHome's avatar
    BenniHome committed
            this.Point = new Vector3(a, b, c);
    
            this._URI = uri;
    
        /// \copydoc Fact.parseFact(Scroll.ScrollFact)
    
        public new static PointFact parseFact(Scroll.ScrollFact fact)
        {
            string uri = fact.@ref.uri;
    
            OMA df = (OMA)((Scroll.ScrollSymbolFact)fact).df;
    
            string parse_id = df.ToString();
            if (!ParsingDictionary.parseTermsToId.ContainsKey(parse_id))
                ParsingDictionary.parseTermsToId[parse_id] = uri;
    
            float a = ((OMF)df.arguments[0]).f;
            float b = ((OMF)df.arguments[1]).f;
            float c = ((OMF)df.arguments[2]).f;
            return new PointFact(a, b, c, uri, StageStatic.stage.factState);
    
    BenniHome's avatar
    BenniHome committed
    
    
        public override Boolean hasDependentFacts()
            => false;
    
        /// \copydoc Fact.getDependentFactIds
    
        public override string[] getDependentFactIds()
            => new string[] { };
    
        /// \copydoc Fact.instantiateDisplay(GameObject, Transform)
    
        public override GameObject instantiateDisplay(GameObject prefab, Transform transform)
        {
    
    John Schihada's avatar
    John Schihada committed
            var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, transform);
    
            obj.transform.GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = this.Label;
    
    John Schihada's avatar
    John Schihada committed
            obj.GetComponent<FactWrapper>().fact = this;
            return obj;
        }
    
            => this.Point.GetHashCode() ^ this.Normal.GetHashCode();
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        protected override bool EquivalentWrapped(PointFact f1, PointFact f2)
    
            => Math3d.IsApproximatelyEqual(f1.Point, f2.Point);
    
    /// <summary>
    /// A <see cref="PointFact"/> on a <see cref="AbstractLineFact"/>
    /// </summary>
    
    public class OnLineFact : FactWrappedCRTP<OnLineFact>
    
        [JsonProperty]
    
        /// <summary> <see cref="PointFact"/>.<see cref="Fact.Id">Id</see> </summary>
        public string Pid;
        [JsonIgnore]
        public PointFact Point { get => (PointFact)_Facts[Pid]; }
    
        /// <summary> <see cref="AbstractLineFact"/>.<see cref="Fact.Id">Id</see> </summary>
        public string Rid;
        [JsonIgnore]
        public AbstractLineFact Ray { get => (AbstractLineFact)_Facts[Rid]; }
    
        /// <summary> \copydoc Fact.Fact </summary>
    
        public OnLineFact() : base()
        {
            this.Pid = null;
            this.Rid = null;
        }
    
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
        /// <param name="old_to_new"><c>Dictionary</c> mapping <paramref name="fact"/>.<see cref="getDependentFactIds"/> in <paramref name="fact"/>.<see cref="Fact._Facts"/> to corresponding <see cref="Fact.Id"/> in <paramref name="organizer"/> </param>
        /// <param name="organizer">sets <see cref="_Facts"/></param>
    
        public OnLineFact(OnLineFact fact, Dictionary<string, string> old_to_new, FactOrganizer organizer) : base(fact, organizer)
    
            => init(old_to_new[fact.Pid], old_to_new[fact.Rid]);
    
        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="pid">sets <see cref="Pid"/></param>
        /// <param name="rid">sets <see cref="Rid"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public OnLineFact(string pid, string rid, FactOrganizer organizer) : base(organizer)
    
            => init(pid, rid);
    
        /// <summary>
        /// Initiates <see cref="Pid"/>, <see cref="Rid"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
        /// </summary>
        /// <param name="pid">sets <see cref="Pid"/></param>
        /// <param name="rid">sets <see cref="Rid"/></param>
    
        private void init(string pid, string rid)
    
            SOMDoc tp = new OMA(
                new OMS(MMT_OMS_URI.Ded), 
                new List<SOMDoc> {
    
                            new OMS(rid),
                            new OMS(pid)
            }),});
    
            MMTSymbolDeclaration mmtDecl = new (this.Label, tp, df);
    
            AddFactResponse.sendAdd(mmtDecl, out this._URI);
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// </summary>
        /// <param name="pid">sets <see cref="Pid"/></param>
        /// <param name="rid">sets <see cref="Rid"/></param>
        /// <param name="uri">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public OnLineFact(string pid, string rid, string uri, FactOrganizer organizer) : base(organizer)
    
            this._URI = uri;
    
        /// \copydoc Fact.parseFact(Scroll.ScrollFact)
        public new static OnLineFact parseFact(Scroll.ScrollFact fact)
    
            string uri = fact.@ref.uri;
    
            string pointUri = ((OMS)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[1]).uri;
            string lineUri = ((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[0] is OMS
    
                ? ((OMS)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[0]).uri
    
                // case when line Uri has a projl on the line Argument 
    
                : ((OMS)((OMA)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[0]).arguments[0]).uri;
    
            if (StageStatic.stage.factState.ContainsKey(pointUri)
             && StageStatic.stage.factState.ContainsKey(lineUri))
                return new OnLineFact(pointUri, lineUri, uri, StageStatic.stage.factState);
    
            //If dependent facts do not exist return null
    
            else return null;
    
        protected override string generateLabel()
    
            => _Facts[Pid].Label + "∈" + _Facts[Rid].Label;
    
    BenniHome's avatar
    BenniHome committed
    
    
        public override Boolean hasDependentFacts()
    
        /// \copydoc Fact.getDependentFactIds
    
        public override string[] getDependentFactIds()
    
            => new string[] { Pid, Rid };
    
        /// \copydoc Fact.instantiateDisplay(GameObject, Transform)
    
    John Schihada's avatar
    John Schihada committed
        public override GameObject instantiateDisplay(GameObject prefab, Transform transform)
    
    John Schihada's avatar
    John Schihada committed
        {
            var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, transform);
    
            obj.transform.GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = _Facts[this.Pid].Label;
            obj.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>().text = _Facts[this.Rid].Label;
    
    John Schihada's avatar
    John Schihada committed
            obj.GetComponent<FactWrapper>().fact = this;
            return obj;
        }
    
    
            => this.Pid.GetHashCode() ^ this.Rid.GetHashCode();
    
    BenniHome's avatar
    BenniHome committed
    
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        protected override bool EquivalentWrapped(OnLineFact f1, OnLineFact f2)
    
            if (f1.Pid == f2.Pid && f1.Rid == f2.Rid)
                return true;
    
    
            PointFact pf1 = (PointFact)_Facts[f1.Pid];
            RayFact rf1 = (RayFact)_Facts[f1.Rid];
            PointFact pf2 = (PointFact)_Facts[f2.Pid];
            RayFact rf2 = (RayFact)_Facts[f2.Rid];
    
    
            return pf1.Equivalent(pf2) && rf1.Equivalent(rf2);
    
    /// <summary>
    /// Angle comprised of three <see cref="PointFact">PointFacts</see> [A,B,C]
    /// </summary>
    
    public class AngleFact : FactWrappedCRTP<AngleFact>
    
        [JsonProperty]
    
        /// @{ <summary>
        /// One <see cref="Fact.Id">Id</see> of three <see cref="PointFact">PointFacts</see> defining Angle [<see cref="Pid1"/>, <see cref="Pid2"/>, <see cref="Pid3"/>].
        /// </summary>
    
        public string Pid1, Pid2, Pid3;
    
        
        [JsonIgnore]
        public PointFact Point1 { get => (PointFact)_Facts[Pid1]; }
        [JsonIgnore]
        public PointFact Point2 { get => (PointFact)_Facts[Pid2]; }
        [JsonIgnore]
        public PointFact Point3 { get => (PointFact)_Facts[Pid3]; }
    
    
        /// <summary> <see langword="true"/>, if AngleFact is approximately 90° or 270°</summary>
    
        public bool is_right_angle;
    
    
        /// <summary> \copydoc Fact.Fact </summary>
    
        public AngleFact() : base()
        {
            this.Pid1 = null;
            this.Pid2 = null;
            this.Pid3 = null;
            this.is_right_angle = false;
        }
    
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
        /// <param name="old_to_new"><c>Dictionary</c> mapping <paramref name="fact"/>.<see cref="getDependentFactIds"/> in <paramref name="fact"/>.<see cref="Fact._Facts"/> to corresponding <see cref="Fact.Id"/> in <paramref name="organizer"/> </param>
        /// <param name="organizer">sets <see cref="_Facts"/></param>
    
        public AngleFact(AngleFact fact, Dictionary<string, string> old_to_new, FactOrganizer organizer) : base(fact, organizer)
    
            => init(old_to_new[fact.Pid1], old_to_new[fact.Pid2], old_to_new[fact.Pid3]);
    
        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="pid1">sets <see cref="Pid1"/></param>
        /// <param name="pid2">sets <see cref="Pid2"/></param>
        /// <param name="pid3">sets <see cref="Pid3"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public AngleFact(string pid1, string pid2, string pid3, FactOrganizer organizer) : base(organizer)
    
            => init(pid1, pid2, pid3);
    
        /// <summary>
        /// Initiates <see cref="Pid1"/>, <see cref="Pid2"/>, <see cref="Pid3"/>, <see cref="is_right_angle"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
        /// </summary>
        /// <param name="pid1">sets <see cref="Pid1"/></param>
        /// <param name="pid2">sets <see cref="Pid2"/></param>
        /// <param name="pid3">sets <see cref="Pid3"/></param>
    
        private void init(string pid1, string pid2, string pid3)
    
            this.Pid1 = pid1;
            this.Pid2 = pid2;
            this.Pid3 = pid3;
    
    
            float v = GetAngle(); // sets is_right_angle
    
            MMTDeclaration mmtDecl = generateNot90DegreeAngleDeclaration(v, pid1, pid2, pid3);
    
            AddFactResponse.sendAdd(mmtDecl, out this._URI);
    
        /// <summary>
        /// Bypasses initialization of new MMT %Fact by using existend URI, _which is not checked for existence_.
        /// </summary>
        /// <param name="Pid1">sets <see cref="Pid1"/></param>
        /// <param name="Pid2">sets <see cref="Pid2"/></param>
        /// <param name="Pid3">sets <see cref="Pid3"/></param>
        /// <param name="backendURI">MMT URI</param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
    
        public AngleFact(string Pid1, string Pid2, string Pid3, string backendURI, FactOrganizer organizer) : base(organizer)
    
        {
            this.Pid1 = Pid1;
            this.Pid2 = Pid2;
            this.Pid3 = Pid3;
    
            _ = GetAngle();
    
            this._URI = backendURI;
            _ = this.Label;
        }
    
    
        public AngleFact(string Pid1, string Pid2, string Pid3, float angle, string backendURI, FactOrganizer organizer) : base(organizer)
    
        {
            this.Pid1 = Pid1;
            this.Pid2 = Pid2;
            this.Pid3 = Pid3;
    
    
            this._URI = backendURI;
    
        /// \copydoc Fact.parseFact(Scroll.ScrollFact)
        public new static AngleFact parseFact(Scroll.ScrollFact fact)
    
            string uri = fact.@ref.uri;
            string
                pointAUri,
                pointBUri,
                pointCUri;
    
            float angle = 0.0f;
    
            //If angle is not a 90Degree-Angle
            if (fact.GetType().Equals(typeof(Scroll.ScrollValueFact)))
            {
    
                OMA df = (OMA)((Scroll.ScrollValueFact)fact).lhs;
                if (df == null)
                    return null;
    
                if (((Scroll.ScrollValueFact)fact).value != null)
                    angle = ((OMF)(((Scroll.ScrollValueFact)fact).value)).f;
    
    
                pointAUri = ((OMS)((OMA)((Scroll.ScrollValueFact)fact).lhs).arguments[0]).uri;
                pointBUri = ((OMS)((OMA)((Scroll.ScrollValueFact)fact).lhs).arguments[1]).uri;
                pointCUri = ((OMS)((OMA)((Scroll.ScrollValueFact)fact).lhs).arguments[2]).uri;
            }
    
            // this should never happen anymore
    
            //If angle is a 90Degree-Angle
    
            else
            {
                Debug.LogError("Angle 90 degrees parsed. This shouldn't happen anymore");
    
    
                pointAUri = ((OMS)((OMA)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[1]).arguments[0]).uri;
                pointBUri = ((OMS)((OMA)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[1]).arguments[1]).uri;
                pointCUri = ((OMS)((OMA)((OMA)((OMA)((Scroll.ScrollSymbolFact)fact).tp).arguments[0]).arguments[1]).arguments[2]).uri;
            }
    
    
            if (StageStatic.stage.factState.ContainsKey(pointAUri)
             && StageStatic.stage.factState.ContainsKey(pointBUri)
             && StageStatic.stage.factState.ContainsKey(pointCUri))
    
                return new AngleFact(pointAUri, pointBUri, pointCUri, angle, uri, StageStatic.stage.factState);
    
                return null; //If dependent facts do not exist return null
    
        protected override string generateLabel()
    
            => (is_right_angle ? "⊾" : "∠") + _Facts[Pid1].Label + _Facts[Pid2].Label + _Facts[Pid3].Label;
    
        /// <summary>
        /// Computes smallest angle and sets <see cref="is_right_angle"/>
        /// </summary>
        /// <returns>Smallets angle between [<see cref="Pid1"/>, <see cref="Pid2"/>] and [<see cref="Pid2"/>, <see cref="Pid3"/>]</returns>
    
        private float GetAngle()
        {
    
            PointFact pf1 = _Facts[Pid1] as PointFact;
            PointFact pf2 = _Facts[Pid2] as PointFact;
            PointFact pf3 = _Facts[Pid3] as PointFact;
    
    
            float v = Vector3.Angle((pf1.Point - pf2.Point), (pf3.Point - pf2.Point));
            this.is_right_angle = Mathf.Abs(v - 90.0f) < 0.01;
    
            return is_right_angle ? 90f : v;
        }
    
    
        /// <summary>
        /// Constructs struct for right-angled MMT %Fact <see cref="AddFactResponse"/>
        /// </summary>
        /// <param name="val">Angle == 90f, _not checked_</param>
        /// <param name="p1URI"><see cref="Pid1"/></param>
        /// <param name="p2URI"><see cref="Pid2"/></param>
        /// <param name="p3URI"><see cref="Pid3"/></param>
        /// <returns>struct for <see cref="AddFactResponse"/></returns>
    
        private MMTDeclaration generate90DegreeAngleDeclaration(float val, string p1URI, string p2URI, string p3URI)
        {
    
            SOMDoc argument = new OMA(
                new OMS(MMT_OMS_URI.Eq),
                new List<SOMDoc> {
                    new OMS(MMT_OMS_URI.RealLit),
    
                    new OMF(val) // 90f
    
            SOMDoc tp = new OMA(new OMS(MMT_OMS_URI.Ded), new List<SOMDoc> { argument });
            SOMDoc df = null;
    
        /// <summary>
        /// Constructs struct for not-right-angled MMT %Fact <see cref="AddFactResponse"/>
        /// </summary>
        /// <param name="val">Angle != 90f, _not checked_</param>
        /// <param name="p1URI"><see cref="Pid1"/></param>
        /// <param name="p2URI"><see cref="Pid2"/></param>
        /// <param name="p3URI"><see cref="Pid3"/></param>
        /// <returns>struct for <see cref="AddFactResponse"/></returns>
    
        private MMTDeclaration generateNot90DegreeAngleDeclaration(float val, string p1URI, string p2URI, string p3URI)
        {
    
            SOMDoc valueTp = new OMS(MMT_OMS_URI.RealLit);
            SOMDoc value = new OMF(val);
    
            return new MMTValueDeclaration(this.Label, lhs, valueTp, value);
        }
    
        public override Boolean hasDependentFacts()
    
        /// \copydoc Fact.getDependentFactIds
    
        public override string[] getDependentFactIds()
    
            => new string[] { Pid1, Pid2, Pid3 };
    
        /// \copydoc Fact.instantiateDisplay(GameObject, Transform)
    
        public override GameObject instantiateDisplay(GameObject prefab, Transform transform)
        {
    
    John Schihada's avatar
    John Schihada committed
            var obj = GameObject.Instantiate(prefab, Vector3.zero, Quaternion.identity, transform);
    
            obj.transform.GetChild(0).gameObject.GetComponent<TextMeshProUGUI>().text = _Facts[this.Pid1].Label;
            obj.transform.GetChild(1).gameObject.GetComponent<TextMeshProUGUI>().text = _Facts[this.Pid2].Label;
            obj.transform.GetChild(2).gameObject.GetComponent<TextMeshProUGUI>().text = _Facts[this.Pid3].Label;
    
    John Schihada's avatar
    John Schihada committed
            obj.GetComponent<FactWrapper>().fact = this;
            return obj;
        }
    
    
            => this.Pid1.GetHashCode() ^ this.Pid2.GetHashCode() ^ this.Pid3.GetHashCode();
    
        /// \copydoc Fact.Equivalent(Fact, Fact)
    
        protected override bool EquivalentWrapped(AngleFact f1, AngleFact f2)
    
            if ((f1.Pid1 == f2.Pid1 && f1.Pid2 == f2.Pid2 && f1.Pid3 == f2.Pid3))// || 
                //(f1.Pid1 == f2.Pid3 && f1.Pid2 == f2.Pid2 && f1.Pid3 == f2.Pid1))
                return true;
    
    
            PointFact p1f1 = (PointFact)_Facts[f1.Pid1];
            PointFact p2f1 = (PointFact)_Facts[f1.Pid2];
            PointFact p3f1 = (PointFact)_Facts[f1.Pid3];
            PointFact p1f2 = (PointFact)_Facts[f2.Pid1];
            PointFact p2f2 = (PointFact)_Facts[f2.Pid2];
            PointFact p3f2 = (PointFact)_Facts[f2.Pid3];
    
            return (p1f1.Equivalent(p1f2) && p2f1.Equivalent(p2f2) && p3f1.Equivalent(p3f2));
            //|| (p1f1.Equivalent(p3f2) && p2f1.Equivalent(p2f2) && p1f1.Equivalent(p3f2));
        }
    }
    
    
    MaZiFAU's avatar
    MaZiFAU committed
    /// <summary>
    /// A RightAngleFact defined by 3  <see cref="PointFact">Pointfact</see> 
    /// </summary>
    public class RightAngleFact : FactWrappedCRTP<RightAngleFact>
    {
        /// \copydoc Fact.s_type
        [JsonProperty]
    
        protected new string s_type = "RightAngleFact";
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        ///  <summary> three <see cref="PointFact">Pointfacts</see> defining the right angle </summary>
        public string Pid1, Pid2, Pid3;
    
    
        [JsonIgnore]
        public PointFact Point1 { get => (PointFact)_Facts[Pid1]; }
        [JsonIgnore]
        public PointFact Point2 { get => (PointFact)_Facts[Pid2]; }
        [JsonIgnore]
        public PointFact Point3 { get => (PointFact)_Facts[Pid2]; }
    
    
    MaZiFAU's avatar
    MaZiFAU committed
        /// <summary> \copydoc Fact.Fact </summary>
        public RightAngleFact() : base()
        {
            this.Pid1 = null;
            this.Pid2 = null;
            this.Pid3 = null;
        }
    
        /// <summary>
        /// Copies <paramref name="fact"/> by initiating new MMT %Fact.
        /// </summary>
        /// <param name="fact">Fact to be copied</param>
        /// <param name="old_to_new"><c>Dictionary</c> mapping <paramref name="fact"/>.<see cref="getDependentFactIds"/> in <paramref name="fact"/>.<see cref="Fact._Facts"/> to corresponding <see cref="Fact.Id"/> in <paramref name="organizer"/> </param>
        /// <param name="organizer">sets <see cref="_Facts"/></param>
        public RightAngleFact(RightAngleFact fact, Dictionary<string, string> old_to_new, FactOrganizer organizer) : base(fact, organizer)
    
            => init(old_to_new[fact.Pid1], old_to_new[fact.Pid2], old_to_new[fact.Pid3]);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        /// <summary>
        /// Standard Constructor
        /// </summary>
        /// <param name="pid1">sets <see cref="Pid1"/></param>
        /// <param name="pid2">sets <see cref="Pid2"/></param>
        /// <param name="pid3">sets <see cref="Pid3"/></param>
        /// <param name="organizer">sets <see cref="Fact._Facts"/></param>
        public RightAngleFact(string pid1, string pid2, string pid3, FactOrganizer organizer) : base(organizer)
    
            => init(pid1, pid2, pid3);
    
    MaZiFAU's avatar
    MaZiFAU committed
    
        /// <summary>
        /// Initiates <see cref="Pid1"/>, <see cref="Pid2"/>, <see cref="Pid3"/>, <see cref="is_right_angle"/>, <see cref="Fact._URI"/> and creates MMT %Fact Server-Side
        /// </summary>
        /// <param name="pid1">sets <see cref="Pid1"/></param>
        /// <param name="pid2">sets <see cref="Pid2"/></param>
        /// <param name="pid3">sets <see cref="Pid3"/></param>
        private void init(string pid1, string pid2, string pid3)
        {
            this.Pid1 = pid1;
            this.Pid2 = pid2;
            this.Pid3 = pid3;