/// <summary>
        /// Returns all available MMUs
        /// </summary>
        /// <param name="sessionID"></param>
        /// <returns></returns>
        public virtual Dictionary <MMUDescription, List <MIPAddress> > GetAvailableMMUs(string sessionID)
        {
            Dictionary <MMUDescription, List <MIPAddress> > dict = new Dictionary <MMUDescription, List <MIPAddress> >();

            //Check all adapters
            foreach (RemoteAdapter adapter in RuntimeData.AdapterInstances.Values)
            {
                //Fetch all loadable MMUs
                List <MMUDescription> mmuDescriptions = adapter.GetLoadableMMUs(sessionID);

                foreach (MMUDescription description in mmuDescriptions)
                {
                    MMUDescription match = dict.Keys.ToList().Find(s => s.ID == description.ID && s.Name == description.Name);

                    if (match == null)
                    {
                        dict.Add(description, new List <MIPAddress>());
                        match = description;
                    }
                    //mask MMUs that are marked to be disabled
                    dict[match].Add(new MIPAddress(adapter.Address, adapter.Port));
                }
            }

            return(dict);
        }
Пример #2
0
        /// <summary>
        /// Instantiates a MMU  from file
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="mmuDescription"></param>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        private static MMUDescription GetDescriptionFromClass(Type classType)
        {
            if (classType != null)
            {
                //Get all defined attributes
                List <object> attributes = GetAttributes(classType);


                MMUDescriptionAttribute mmuDescriptionAttr = attributes.Find(s => s is MMUDescriptionAttribute) as MMUDescriptionAttribute;
                var mParamterAttr = attributes.Where(s => s is MParameterAttribute);
                var simEvents     = attributes.Where(s => s is MSimulationEventAttribute);


                //Create the mmu description
                MMUDescription mmuDescription = new MMUDescription()
                {
                    Name             = mmuDescriptionAttr.Name,
                    Author           = mmuDescriptionAttr.Author,
                    Version          = mmuDescriptionAttr.Version,
                    MotionType       = mmuDescriptionAttr.MotionType,
                    LongDescription  = mmuDescriptionAttr.LongDescription,
                    ShortDescription = mmuDescriptionAttr.ShortDescription,
                    AssemblyName     = "debug",

                    //Language can be automatically set
                    Language = "C#",

                    //Auto-generate an ID
                    ID = Guid.NewGuid().ToString(),
                };


                //Add all parameters
                if (mParamterAttr != null)
                {
                    mmuDescription.Parameters = new System.Collections.Generic.List <MParameter>();
                    foreach (MParameterAttribute param in mParamterAttr)
                    {
                        mmuDescription.Parameters.Add(new MParameter(param.Name, param.Type, param.Description, param.Required));
                    }
                }


                //Add all events (if defined)
                if (simEvents != null)
                {
                    mmuDescription.Events = new System.Collections.Generic.List <string>();
                    foreach (MSimulationEventAttribute param in simEvents)
                    {
                        mmuDescription.Events.Add(param.Type);
                    }
                }

                //Return the created MMU Description
                return(mmuDescription);
            }

            return(null);
        }
Пример #3
0
        /// <summary>
        /// Tries to add/read the respective MMU
        /// </summary>
        /// <param name="zipFilePath">The filepath of the zip archive</param>
        /// <returns></returns>
        private bool TryAddMMU(string zipFilePath)
        {
            //Check whether a description is available
            MMUDescription mmuDescription = this.GetMMUDescription(zipFilePath);

            //Only continue if description is not null
            if (mmuDescription != null)
            {
                //Check if the MMU supports the specified language
                if (!this.supportedLanguages.Contains(mmuDescription.Language))
                {
                    return(false);
                }

                //Check if already available -> skip
                if (this.sessionData.MMULoadingProperties.ContainsKey(mmuDescription.ID))
                {
                    return(false);
                }

                //Skip if already registered
                if (this.availableMMUs.ContainsKey(mmuDescription.ID))
                {
                    return(false);
                }

                //Create the new loading properties for the MMU
                MMULoadingProperty loadingProperties = new MMULoadingProperty()
                {
                    //Assign the description
                    Description = mmuDescription,

                    //Store all the data
                    Data = GetZipContent(zipFilePath),

                    //Store the path to the zip file
                    Path = zipFilePath
                };

                //Add to available MMUs
                this.availableMMUs.Add(mmuDescription.ID, loadingProperties);


                Logger.Log(Log_level.L_INFO, $"Successfully added MMU: {mmuDescription.Name} {mmuDescription.AssemblyName}");

                //Success return true
                return(true);
            }

            //Problem -> return false
            return(false);
        }
Пример #4
0
        ///// <summary>
        ///// Returns the available MMUs
        ///// </summary>
        ///// <returns></returns>
        //public Dictionary<string, MMULoadingProperty> GetAvailableMMUs()
        //{
        //    Dictionary<string, MMULoadingProperty> availableMMUs = new Dictionary<string, MMULoadingProperty>();

        //    int loaded = 0;

        //    foreach (string mmuPath in this.mmuPaths)
        //    {
        //        foreach (string folderPath in Directory.GetDirectories(mmuPath))
        //        {
        //            MMULoadingProperty mmuLoadingProperty = this.ScanFolder(folderPath);

        //            if (mmuLoadingProperty != null)
        //            {
        //                availableMMUs.Add(mmuLoadingProperty.Description.ID, mmuLoadingProperty);
        //                loaded++;
        //            }
        //        }
        //    }

        //    Logger.Log(Log_level.L_INFO, $"Scanned for loadable MMUs: {loaded} loadable MMUs found.");

        //    return availableMMUs;
        //}


        /// <summary>
        /// Checks the respective folder and tracks the properties/ mmu descriptions
        /// Returns true if a new MMU has been added
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        private MMULoadingProperty ScanFolder(string folderPath)
        {
            //Check whether a description is available
            MMUDescription mmuDescription = this.GetMMUDescription(folderPath);

            //Skip if no description file
            if (mmuDescription == null)
            {
                return(null);
            }

            //Check if the MMU supports the specified language
            if (!this.supportedLanguages.Contains(mmuDescription.Language))
            {
                return(null);
            }

            //Check if already available -> skip
            if (this.sessionData.MMULoadingProperties.ContainsKey(mmuDescription.ID))
            {
                return(null);
            }


            //Determine the mmu file
            string mmuFile = Directory.GetFiles(folderPath).ToList().Find(s => s.Contains(mmuDescription.AssemblyName));

            //Load the mmu from filesystem and instantiate
            if (mmuFile != null)
            {
                //Add the description to the dictionary
                return(new MMULoadingProperty()
                {
                    //Assign the description
                    Description = mmuDescription,

                    //Store all the data
                    Data = GetFolderContent(folderPath),

                    //Set the path of the MMU file
                    Path = mmuFile
                });
            }

            else
            {
                Logger.Log(Log_level.L_ERROR, $"Cannot find corresponding assembly name. {mmuDescription.AssemblyName} of MMU: {mmuDescription.Name}");
            }

            return(null);
        }
Пример #5
0
            public Dictionary <string, MMULoadingProperty> GetAvailableMMUs()
            {
                //Load the description from path -> Change this line for testing a different MMU
                MMUDescription mmuDescription = GetDescriptionFromClass(mmuType);


                return(new Dictionary <string, MMULoadingProperty>()
                {
                    { mmuDescription.ID, new MMULoadingProperty()
                      {
                          Description = mmuDescription
                      } }
                });
            }
            public Dictionary <string, MMULoadingProperty> GetAvailableMMUs()
            {
                //Load the description from path -> Change this line for testing a different MMU
                MMUDescription mmuDescription = MMICSharp.Common.Communication.Serialization.FromJsonString <MMUDescription>(System.IO.File.ReadAllText("../../../CarryMMUConcurrent/bin/Debug/description.json"));


                return(new Dictionary <string, MMULoadingProperty>()
                {
                    { mmuDescription.ID, new MMULoadingProperty()
                      {
                          Description = mmuDescription
                      } }
                });
            }
Пример #7
0
    /// <summary>
    /// Basic constructor instantiating a new AddParameterWindow
    /// </summary>
    /// <param name="instruction"></param>
    /// <param name="description"></param>
    public AddParameterWindow(ref MInstruction instruction, MMUDescription description)
    {
        //Assign the variables
        this.description = description;
        this.instruction = instruction;

        //Get all available parameters
        List <string> parameterList = description.Parameters.Select(s => s.Name).ToList();

        //Add custom -> for undefined parameter
        parameterList.Add("Custom");

        //Set the parameter names for the popup list
        this.availableParameters = parameterList.ToArray();
    }
        /// <summary>
        /// Basic constructor of a (remote) MMU
        /// </summary>
        /// <param name="mmuAccess"></param>
        /// <param name="adapter"></param>
        /// <param name="sessionId"></param>
        /// <param name="description"></param>
        public MotionModelUnitAccess(MMUAccess mmuAccess, IAdapter adapter, string sessionId, MMUDescription description)
        {
            this.Adapter = adapter;

            //Assign all variables
            this.Description = description;
            this.sessionId   = sessionId;
            this.MotionType  = description.MotionType;
            this.mmuAccess   = mmuAccess;
            this.Name        = description.Name;
            this.ID          = description.ID;

            //Create a new client for the MMU
            this.adapterClient = adapter.CreateClient();
        }
Пример #9
0
        /// <summary>
        /// Returns the MMU description contained in the zip archive (if available)
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        private MMUDescription GetMMUDescription(string folderPath)
        {
            MMUDescription mmuDescription = null;

            try
            {
                string descriptionFile = Directory.GetFiles(folderPath).ToList().Find(s => s.Contains("description.json"));
                mmuDescription = Serialization.FromJsonString <MMUDescription>(File.ReadAllText(descriptionFile));
            }
            catch (Exception)
            {
                return(null);
            }

            return(mmuDescription);
        }
Пример #10
0
        /// <summary>
        /// Fetches the lodable MMUs from the adapters
        /// </summary>
        private void UpdateLoadableMMUs()
        {
            //Create a dictionary which holds the MMU Descriptions and the corresponding addresses
            Dictionary <MMUDescription, List <MIPAddress> > availableMMUs = new Dictionary <MMUDescription, List <MIPAddress> >();

            //Iterate over each adapter (do use for instead for-each due to possible changes of list)
            for (int i = RuntimeData.AdapterInstances.Count - 1; i >= 0; i--)
            {
                RemoteAdapter adapter = RuntimeData.AdapterInstances.Values.ElementAt(i);

                List <MMUDescription> mmuDescriptions = new List <MMUDescription>();
                try
                {
                    mmuDescriptions = adapter.GetLoadableMMUs("default");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Problem receiving loadable MMUs: " + e.Message);
                }

                //Check if MMU is already available and add to dictionary
                foreach (MMUDescription description in mmuDescriptions)
                {
                    MMUDescription match = availableMMUs.Keys.ToList().Find(s => s.ID == description.ID && s.Name == description.Name);

                    if (match == null)
                    {
                        availableMMUs.Add(description, new List <MIPAddress>());
                        match = description;
                    }

                    availableMMUs[match].Add(new MIPAddress(adapter.Address, adapter.Port));
                }
            }

            //Update the MMU descriptions
            RuntimeData.MMUDescriptions.Clear();
            foreach (MMUDescription description in availableMMUs.Keys)
            {
                RuntimeData.MMUDescriptions.TryAdd(description.ID, description);
            }

            //Update the MMU collection in ui thread
            UIData.SetMMUDescriptions(availableMMUs.Keys.ToList());
        }
Пример #11
0
        /// <summary>
        /// Callback  for the connection setup
        /// </summary>
        /// <param name="connected"></param>
        protected virtual void ConnectionCallback(bool connected)
        {
            if (connected)
            {
                this.statusText = "Loading MMUs";

                Debug.Log($"Connections to {this.MMUAccess.AdapterDescriptions.Count} adapters established: " + String.Join(String.Empty, this.MMUAccess.AdapterDescriptions.Select(s => s.Name + " ")));

                //Get all loadable mmus
                List <MMUDescription> loadableMMUs = this.MMUAccess.GetLoadableMMUs();

                //Just load the co-simulator
                if (this.UseRemoteCoSimulation)
                {
                    //Find the MMU with the specified co-simulation name
                    MMUDescription cosim = loadableMMUs.Find(s => s.Name == this.RemoteCoSimulationName);

                    if (cosim == null)
                    {
                        throw new Exception("Remote co-simulator with specified name not available");
                    }

                    //Only load the co-simulation
                    loadableMMUs = new List <MMUDescription>()
                    {
                        cosim
                    };
                }

                //Load the mmus asynchronously
                this.MMUAccess.LoadMMUsAsync(loadableMMUs, TimeSpan.FromSeconds(this.Timeout), this.LoadingCallback);
            }
            else
            {
                this.statusText = "Problem at establishing a connection";
                Debug.LogError("Problem at establishing a connection");
            }
        }
Пример #12
0
 public MMUOrderAndDescriptionData(MMUDescription description, UInt32 priority, string folder)
 {
     //derived properties
     this.AssemblyName     = description.AssemblyName;
     this.Author           = description.Author;
     this.Dependencies     = description.Dependencies;
     this.Events           = description.Events;
     this.ID               = description.ID;
     this.Language         = description.Language;
     this.LongDescription  = description.LongDescription;
     this.MotionType       = description.MotionType;
     this.Name             = description.Name;
     this.Parameters       = description.Parameters;
     this.Prerequisites    = description.Prerequisites;
     this.Properties       = description.Properties;
     this.SceneParameters  = description.SceneParameters;
     this.ShortDescription = description.ShortDescription;
     this.Version          = description.Version;
     this.__isset          = description.__isset;
     //new properties
     this.Priority   = priority;
     this.FolderPath = folder;
 }
Пример #13
0
        static void Main(string[] args)
        {
            try
            {
                //Get the desired path
                string path = args[0];

                string outputPath = System.IO.Path.GetDirectoryName(path) + @"\description.json";

                Console.WriteLine($"Loading .dll from filepath: {path}");

                Console.WriteLine("Auto-generating MMU description");

                //Auto-generate the description based on the dll located at the filepath
                MMUDescription mmuDescription = GetDescriptionFromClass(path);

                Console.WriteLine("MMU description successfully generated");

                try
                {
                    //Save the file to the same folder as the dll
                    System.IO.File.WriteAllText(outputPath, MMICSharp.Common.Communication.Serialization.ToJsonString(mmuDescription));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Problem saving file");
                }

                Console.WriteLine($"Description file successfully stored at {outputPath}");

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed at automatically generating the description file. Exception occured: " + e.Message + e.StackTrace);
            }
        }
Пример #14
0
        /// <summary>
        /// Returns the MMU description contained in the zip archive (if available)
        /// </summary>
        /// <param name="zipArchivePath"></param>
        /// <returns></returns>
        private MMUDescription GetMMUDescription(string zipArchivePath)
        {
            MMUDescription mmuDescription = null;

            try
            {
                using (var file = File.OpenRead(zipArchivePath))
                    using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
                    {
                        //First get the description
                        ZipArchiveEntry descriptionEntry = zip.Entries.ToList().Find(s => s.Name == "description.json");

                        string jsonString = System.Text.Encoding.UTF8.GetString(GetByteData(descriptionEntry));

                        mmuDescription = Serialization.FromJsonString <MMUDescription>(jsonString);
                    }
            }
            catch (Exception)
            {
                return(null);
            }

            return(mmuDescription);
        }
Пример #15
0
        /// <summary>
        /// MMU causes problems if initializing multiple times -> To check in future
        /// Basic initialization
        /// For specifying the priorities of the MMUs /motion types the properties can be specified (e.g. {"walk", 1.0}, {"grasp", 2.0})
        /// The listed motion types are also the ones which are loaded. If this porperty is not defined then every MMU is loaded.
        /// </summary>
        /// <param name="avatarDescription"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public override MBoolResponse Initialize(MAvatarDescription avatarDescription, Dictionary <string, string> properties)
        {
            base.Initialize(avatarDescription, properties);

            Console.WriteLine("---------------------------------------------------------");
            Console.WriteLine("Initializing co-simulation MMU");

            //Full scene transmission initial required
            this.transmitFullScene = true;

            //Setup the mmu access
            this.mmuAccess = new MMUAccess(this.sessionId)
            {
                AvatarID    = avatarDescription.AvatarID,
                SceneAccess = this.SceneAccess
            };

            Console.WriteLine("Try to connect to mmu access...");


            //Connect to mmu access and load mmus
            if (this.mmuAccess.Connect(this.AdapterEndpoint, avatarDescription.AvatarID))
            {
                //Get all loadable MMUs within the current session
                List <MMUDescription> loadableMMUs = this.mmuAccess.GetLoadableMMUs();


                //Select the MMUs which should be loaded
                loadableMMUs = this.SelectMMUsToLoad(loadableMMUs);

                //Create a dictionary for storing the priorities
                Dictionary <string, float> priorities = new Dictionary <string, float>();
                priorities = this.GetPriorities?.Invoke();



                //Select the MMUs to load if explictely specified by the user
                if (properties != null && properties.Count > 0)
                {
                    for (int i = loadableMMUs.Count - 1; i >= 0; i--)
                    {
                        MMUDescription description = loadableMMUs[i];

                        float priority = 1;

                        //If MMU is listed -> add the priority
                        if (priorities.TryGetValue(description.MotionType, out priority))
                        {
                            priorities.Add(description.MotionType, priority);
                        }

                        //MMU is not explicetly listed -> remove from loading list
                        else
                        {
                            loadableMMUs.RemoveAt(i);
                        }
                    }
                }

                //No MMU list defined -> Load all MMUs with same priority (despite the own MMU)
                else
                {
                    //Remove the own MMU -> Avoid recursively instantiating own MMU (unless explictely forced)
                    if (loadableMMUs.Exists(s => s.Name == this.Name))
                    {
                        MMUDescription ownDescription = loadableMMUs.Find(s => s.Name == this.Name);
                        loadableMMUs.Remove(ownDescription);
                    }
                }

                Console.WriteLine("Got loadable MMUs:");

                try
                {
                    //Load the relevant MMUs
                    bool success = this.mmuAccess.LoadMMUs(loadableMMUs, TimeSpan.FromSeconds(20));
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error at loading MMUs : " + e.Message + e.StackTrace);

                    return(new MBoolResponse(false)
                    {
                        LogData = new List <string>()
                        {
                            e.Message,
                            e.StackTrace
                        }
                    });
                }

                Console.WriteLine("All MMUs successfully loaded");


                foreach (MMUDescription description in loadableMMUs)
                {
                    Console.WriteLine(description.Name);
                }


                //Initialize all MMUs
                bool initialized = this.mmuAccess.InitializeMMUs(TimeSpan.FromSeconds(20), avatarDescription.AvatarID);

                if (!initialized)
                {
                    Console.WriteLine("Problem at initializing MMUs");

                    return(new MBoolResponse(false)
                    {
                        LogData = new List <string>()
                        {
                            { "Problem at initializing MMUs" }
                        }
                    });
                }

                //Instantiate the cosimulator
                this.coSimulator = new MMICoSimulator(mmuAccess.MotionModelUnits);

                //Set the priorities of the motions
                this.coSimulator.SetPriority(priorities);


                return(new MBoolResponse(true));
            }

            else
            {
                Console.WriteLine("Connection to MMUAccess/MMIRegister failed");
                return(new MBoolResponse(false)
                {
                    LogData = new List <string>()
                    {
                        "Connection to MMUAccess/MMIRegister failed"
                    }
                });
            }
        }
Пример #16
0
        /// <summary>
        /// Tries to add/read the respective MMU
        /// </summary>
        /// <param name="zipFilePath">The filepath of the zip archive</param>
        /// <returns></returns>
        private bool TryAddMMU(string directoryPath)
        {
            try
            {
                //Check whether a description is available
                MMUDescription mmuDescription = this.GetMMUDescription(directoryPath);

                //Only continue if description is not null
                if (mmuDescription != null)
                {
                    //Check if the MMU supports the specified language
                    if (!this.supportedLanguages.Contains(mmuDescription.Language))
                    {
                        return(false);
                    }

                    //Check if already available -> skip
                    if (this.sessionData.MMULoadingProperties.ContainsKey(mmuDescription.ID))
                    {
                        return(false);
                    }

                    //Skip if already registered
                    if (this.availableMMUs.ContainsKey(mmuDescription.ID))
                    {
                        return(false);
                    }


                    //Determine the mmu file
                    string mmuFile = Directory.GetFiles(directoryPath).ToList().Find(s => s.Contains(mmuDescription.AssemblyName));


                    //Create the new loading properties for the MMU
                    MMULoadingProperty loadingProperties = new MMULoadingProperty()
                    {
                        //Assign the description
                        Description = mmuDescription,

                        //Store all the data
                        Data = GetFolderContent(directoryPath),

                        //Set the path of the directory
                        Path = mmuFile //directory path -> in future use directory path in here
                    };

                    //Add to available MMUs
                    this.availableMMUs.Add(mmuDescription.ID, loadingProperties);

                    Logger.Log(Log_level.L_INFO, $"Successfully added MMU: {mmuDescription.Name} {mmuDescription.AssemblyName}");

                    //Success return true
                    return(true);
                }

                //Problem -> return false
                return(false);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #17
0
 /// <summary>
 /// Basic constructor
 /// </summary>
 /// <param name="mmu"></param>
 public MMUContainer(IMotionModelUnitAccess mmu) : this()
 {
     this.MMU         = mmu;
     this.Description = mmu.Description;
 }
Пример #18
0
        /// <summary>
        /// Instantiates a MMU  from file
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="mmuDescription"></param>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        private static MMUDescription GetDescriptionFromClass(string path)
        {
            //Load the mmu from filesystem and instantiate
            Assembly assembly = Assembly.LoadFrom(path);

            //Get the specific type of the class which implementd the IMotionModelUnitDev interface
            Type classType = GetMMUClassType(assembly);

            if (classType != null)
            {
                //Get all defined attributes
                List <object> attributes = GetAttributes(classType);


                MMUDescriptionAttribute mmuDescriptionAttr = attributes.Find(s => s is MMUDescriptionAttribute) as MMUDescriptionAttribute;
                var mParamterAttr = attributes.Where(s => s is MParameterAttribute);
                var simEvents     = attributes.Where(s => s is MSimulationEventAttribute);


                //Create the mmu description
                MMUDescription mmuDescription = new MMUDescription()
                {
                    Name             = mmuDescriptionAttr.Name,
                    Author           = mmuDescriptionAttr.Author,
                    Version          = mmuDescriptionAttr.Version,
                    MotionType       = mmuDescriptionAttr.MotionType,
                    LongDescription  = mmuDescriptionAttr.LongDescription,
                    ShortDescription = mmuDescriptionAttr.ShortDescription,

                    //Language can be automatically set
                    Language = "C#",

                    //Auto-generate an ID
                    ID = Guid.NewGuid().ToString(),

                    //Use the assembly name from the path
                    AssemblyName = System.IO.Path.GetFileName(path)
                };


                //Add all parameters
                if (mParamterAttr != null)
                {
                    mmuDescription.Parameters = new System.Collections.Generic.List <MParameter>();
                    foreach (MParameterAttribute param in mParamterAttr)
                    {
                        mmuDescription.Parameters.Add(new MParameter(param.Name, param.Type, param.Description, param.Required));
                    }
                }


                //Add all events (if defined)
                if (simEvents != null)
                {
                    mmuDescription.Events = new System.Collections.Generic.List <string>();
                    foreach (MSimulationEventAttribute param in simEvents)
                    {
                        mmuDescription.Events.Add(param.Type);
                    }
                }

                //Return the created MMU Description
                return(mmuDescription);
            }

            return(null);
        }
Пример #19
0
        /// <summary>
        /// Validates the parameters of a particular instruction
        /// </summary>
        /// <param name="instruction"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        protected virtual MBoolResponse ValidateParameters(MInstruction instruction, MMUDescription description)
        {
            foreach (MParameter parameter in description.Parameters)
            {
                if (parameter.Required)
                {
                    if (!instruction.Properties.ContainsKey(parameter.Name))
                    {
                        return(new MBoolResponse(false)
                        {
                            LogData = new List <string>()
                            {
                                "Required parameter: " + parameter.Name + " not set."
                            }
                        });
                    }
                }

                //Check if parameter is constraint
                if (IsConstraintType(parameter.Type))
                {
                    if (instruction.Properties.ContainsKey(parameter.Name))
                    {
                        string id = instruction.Properties[parameter.Name];

                        //Check if a constraint with the given id is available

                        if (instruction.Constraints == null)
                        {
                            return new MBoolResponse(false)
                                   {
                                       LogData = new List <string>()
                                       {
                                           "Constraints are null:" + parameter.Name
                                       }
                                   }
                        }
                        ;

                        if (!instruction.Constraints.Exists(s => s.ID == id))
                        {
                            return(new MBoolResponse(false)
                            {
                                LogData = new List <string>()
                                {
                                    "Constraint with requested id not defined: " + parameter.Name + " " + id
                                }
                            });
                        }
                    }
                }
            }

            if (instruction.Properties != null)
            {
                foreach (KeyValuePair <string, string> entry in instruction.Properties)
                {
                    if (entry.Key == null)
                    {
                        return new MBoolResponse(false)
                               {
                                   LogData = new List <string>()
                                   {
                                       "Parameter with key == null existent."
                                   }
                               }
                    }
                    ;
                    if (entry.Value == null)
                    {
                        return(new MBoolResponse(false)
                        {
                            LogData = new List <string>()
                            {
                                $"Parameter {entry.Key} with value == null existent."
                            }
                        });
                    }
                }
            }

            return(new MBoolResponse(true));
        }
Пример #20
0
    void OnGUI()
    {
        EditorGUILayout.LabelField("Add Instruction:");

        instruction.Name = EditorGUILayout.TextField("Name", instruction.Name);
        instruction.ID   = EditorGUILayout.TextField("ID", instruction.ID);
        EditorGUILayout.LabelField("Motion Type:");
        motionTypeIndex = EditorGUILayout.Popup(motionTypeIndex, motionTypeOptions);

        EditorGUILayout.Separator();

        EditorGUILayout.LabelField("Properties:");
        foreach (var entry in instruction.Properties)
        {
            EditorGUILayout.LabelField(entry.Key + " : " + entry.Value);
        }

        if (GUILayout.Button("Add Parameter"))
        {
            //Get selected MMUDescription
            MMUDescription description = this.mmuDescriptions[this.motionTypeIndex];

            AddParameterWindow window = new AddParameterWindow(ref instruction, description);
            window.Show();
        }

        EditorGUILayout.LabelField("Start Condition:");


        if (this.instruction.StartCondition != null)
        {
            EditorGUILayout.LabelField(this.instruction.StartCondition);
        }

        EditorGUILayout.LabelField("End Condition:");

        if (this.instruction.EndCondition != null)
        {
            EditorGUILayout.LabelField(this.instruction.EndCondition);
        }


        if (GUILayout.Button("Add Condition"))
        {
            AddConditionWindow window = new AddConditionWindow(ref this.instruction, ref this.instructionList);
            window.Show();
        }

        if (GUILayout.Button("Add Action"))
        {
            //Get selected MMUDescription
            MMUDescription description = this.mmuDescriptions[this.motionTypeIndex];

            AddActionWindow window = new AddActionWindow(ref instruction, ref this.instructionList);
            window.Show();
        }


        if (GUILayout.Button("Ok"))
        {
            //Finally assign the motion type
            this.instruction.MotionType = this.motionTypeOptions[this.motionTypeIndex];

            //Check if all required parameters are set
            if (this.CheckParameters())
            {
                this.instructionList.Add(this.instruction);
                Close();
            }
        }


        //if (GUILayout.Button("Save"))
        //{
        //    //Finally assign the motion type
        //    this.instruction.MotionType = this.motionTypeOptions[this.motionTypeIndex];

        //    string outputPath = EditorUtility.SaveFilePanel("Select the output file", "Instructions/", name, "json");

        //    System.IO.File.WriteAllText(outputPath, MMICSharp.Common.Communication.Serialization.ToJsonString(this.instruction));

        //    EditorUtility.DisplayDialog("Instruction list successfully saved.", "The instructions have been successfully exported to your desired output directory.", "Continue");
        //}


        if (GUILayout.Button("Abort"))
        {
            Close();
        }
    }
Пример #21
0
        /// <summary>
        /// Basic initialization method
        /// </summary>
        /// <param name="avatarDescription"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public override MBoolResponse Initialize(MAvatarDescription avatarDescription, Dictionary <string, string> properties)
        {
            //Call the base class (important for automatic conversion from MSimulationState to SimulationState)
            base.Initialize(avatarDescription, properties);

            this.SkeletonAccess = new IntermediateSkeleton();
            this.SkeletonAccess.InitializeAnthropometry(avatarDescription);


            //Create a new session uuid
            this.sessionId = Guid.NewGuid().ToString();

            //Create a new virtual scene
            this.virtualScene = new MMIScene();

            //Create a unique id for the new virtual object representing the move target
            string moveTargetID = Guid.NewGuid().ToString();

            //Create a new virtual object representing the move target
            moveTarget = new MSceneObject(moveTargetID, "MoveTarget", new MTransform()
            {
                ID       = moveTargetID,
                Position = new MVector3(0, 0, 0),
                Rotation = new MQuaternion(0, 0, 0, 1)
            });

            //Add the virtual move target to the scene
            this.virtualScene.Apply(new MSceneUpdate()
            {
                AddedSceneObjects = new List <MSceneObject>()
                {
                    moveTarget
                }
            });


            //Full scene transmission initial required
            this.transmitFullScene = true;

            //Setup the mmu access
            this.mmuAccess = new MMUAccess(this.sessionId)
            {
                //IntermediateAvatarDescription = avatarDescription,
                SceneAccess = this.virtualScene
            };

            Console.WriteLine("Try to connect to mmu access...");

            //Connect to mmu access and load mmus
            bool connected = this.mmuAccess.Connect(this.AdapterEndpoint, this.AvatarDescription.AvatarID);


            if (connected)
            {
                //Get all loadable MMUs within the current session
                List <MMUDescription> loadableMMUs = this.mmuAccess.GetLoadableMMUs();


                MMUDescription moveMMU = loadableMMUs.Find(s => s.MotionType == "move");

                Console.WriteLine("Got loadable MMUs:");


                //Load the relevant MMUs
                bool loaded = this.mmuAccess.LoadMMUs(new List <MMUDescription>()
                {
                    moveMMU
                }, TimeSpan.FromSeconds(10));

                if (!loaded)
                {
                    Console.WriteLine("Error at loading MMU");

                    return(new MBoolResponse(false)
                    {
                        LogData = new List <string>()
                        {
                            { "Error at loading mmu" }
                        }
                    });
                }

                //Initialize all MMUs
                this.mmuAccess.InitializeMMUs(TimeSpan.FromSeconds(10), this.AvatarDescription.AvatarID);

                //Instantiate the cosimulator
                this.coSimulator = new MMICoSimulator(mmuAccess.MotionModelUnits);


                return(new MBoolResponse(true));
            }
            else
            {
                Console.WriteLine("Connection to MMUAccess/MMIRegister failed");
                return(new MBoolResponse(false)
                {
                    LogData = new List <string>()
                    {
                        "Connection to MMUAccess/MMIRegister failed"
                    }
                });
            }
        }
 /// <summary>
 /// Removes a MMU
 /// </summary>
 /// <param name="description"></param>
 public void RemoveMMU(MMUDescription description)
 {
     this.availableMMUs.Remove(description);
     this.MMUsChanged?.Invoke(this, new EventArgs());
 }
Пример #23
0
        /// <summary>
        /// Instantiates a MMU  from file
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="mmuDescription"></param>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        public IMotionModelUnitDev InstantiateMMU(MMULoadingProperty mmuLoadingProperty)
        {
            Debug.Log("Calling Unity MMU instantiator " + mmuLoadingProperty.Path);

            MMUDescription mmuDescription = mmuLoadingProperty.Description;
            string         filePath       = mmuLoadingProperty.Path;

            //Check if the MMU supports the specified language
            if (mmuDescription.Language != "UnityC#" && mmuDescription.Language != "Unity")
            {
                throw new NotSupportedException("MMU is not supported");
            }

            //Skip if file path invalid
            if (filePath == null)
            {
                throw new NullReferenceException("File path of MMU is null " + mmuDescription.Name);
            }

            //Skip if the MMU has no dependencies
            if (mmuDescription.Dependencies.Count == 0)
            {
                throw new Exception("No dependencies of MMU specified " + mmuDescription.Name);
            }

            //Create a variable which hols the mmu
            IMotionModelUnitDev mmu = null;

            //Get the paths
            string folderPath      = System.IO.Directory.GetParent(filePath).ToString();
            string assetBundlePath = folderPath + "\\" + mmuDescription.Dependencies[0].Name;


            //Perform on unity main thread
            MainThreadDispatcher.Instance.ExecuteBlocking(delegate
            {
                //To do in futre -> Create a new scene for each MMU
                //Scene scene = SceneManager.CreateScene("Scene" + mmuDescription.Name);
                //SceneManager.SetActiveScene(scene);

                //First load the resources
                AssetBundle mmuAssetBundle = null;
                try
                {
                    if (!mmuLoadingProperty.Data.ContainsKey(assetBundlePath))
                    {
                        mmuAssetBundle = AssetBundle.LoadFromFile(assetBundlePath);
                        if (mmuAssetBundle == null)
                        {
                            MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Failed to load AssetBundle! AssetBundle is null!" + mmuDescription.Name);
                            return;
                        }

                        mmuLoadingProperty.Data.Add(assetBundlePath, mmuAssetBundle);
                    }
                    else
                    {
                        mmuAssetBundle = mmuLoadingProperty.Data[assetBundlePath] as AssetBundle;
                    }
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot load asset bundle: " + mmuDescription.Name + " " + e.Message);
                    return;
                }

                GameObject prefab = null;
                try
                {
                    prefab = mmuAssetBundle.LoadAsset <GameObject>(mmuDescription.Name);
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot load prefab: " + mmuDescription.Name + " " + e.Message);
                }

                GameObject mmuObj = null;

                try
                {
                    mmuObj = GameObject.Instantiate(prefab);
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot instantiate prefab: " + mmuDescription.Name + " " + e.Message);
                }

                try
                {
                    Assembly assembly = Assembly.LoadFile(filePath);

                    //Find the class type which implements the IMotionModelInterface
                    Type classType = assembly.GetTypes().ToList().Find(s => s.GetInterfaces().Contains(typeof(IMotionModelUnitDev)));
                    if (classType != null)
                    {
                        //Add the script to the game object
                        mmu = mmuObj.AddComponent(classType) as IMotionModelUnitDev;

                        ///Loading and assigning the configuration file
                        if (mmuObj.GetComponent <UnityMMUBase>() != null)
                        {
                            MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"MMU {mmuDescription.Name} implements the UnityMMUBase");

                            //Get the UnityMMUBse interface
                            UnityMMUBase mmuBase = mmuObj.GetComponent <UnityMMUBase>();

                            //By default set the configuration file path and define it globally
                            string avatarConfigFilePath = AppDomain.CurrentDomain.BaseDirectory + "/" + "avatar.mos";

                            //Check if the MMU has a custom configuration file
                            if (this.GetLocalAvatarConfigurationFile(folderPath, out string localConfigFilePath))
                            {
                                //Setting the local avatar as reference for retargeting
                                MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"Local avatar configuration was found: {mmuDescription.Name} ({avatarConfigFilePath}).");

                                //Set to the utilized path
                                avatarConfigFilePath = localConfigFilePath;
                            }


                            //Further perform a check whether the file is available at all
                            if (System.IO.File.Exists(avatarConfigFilePath))
                            {
                                mmuBase.ConfigurationFilePath = avatarConfigFilePath;
                                MMICSharp.Adapter.Logger.Log(Log_level.L_DEBUG, $"Setting the configuration file path for loading the avatar of {mmuDescription.Name} to {avatarConfigFilePath}");
                            }

                            //Problem in here -> File is obviously not available
                            else
                            {
                                MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, $"Problem setting the configuration file path for loading the avatar of {mmuDescription.Name} to {avatarConfigFilePath}. File not available.");
                            }
                        }
                    }
                    else
                    {
                        MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Cannot instantiate MMU: " + mmuDescription.Name);
                    }
                }
                catch (Exception e)
                {
                    MMICSharp.Adapter.Logger.Log(Log_level.L_ERROR, "Problem at instantiating class of MMU: " + mmuDescription.Name + " " + e.Message + " " + e.StackTrace);
                }


                //Disable all renderers in the scene
                foreach (Renderer renderer in GameObject.FindObjectsOfType <Renderer>())
                {
                    renderer.enabled = false;
                }
            });