Exemplo n.º 1
0
        public static DiscreteVariable ContinuosToDiscrete(DiscreteVariable veryBigDiscrete)
        {
            int    r_1 = veryBigDiscrete.r_1;
            double h   = veryBigDiscrete.p / r_1;

            // calculating new statistical table
            System.Collections.Generic.SortedDictionary <double, int> newStatisticalTable =
                new System.Collections.Generic.SortedDictionary <double, int>();

            System.Collections.Generic.KeyValuePair <double, int>[] oldStatisticalTable = veryBigDiscrete.GetStatisticalTable();
            double leftBorder  = oldStatisticalTable.First().Key;
            double rightBorder = leftBorder + h;

            int leftIndex  = 0;
            int rightIndex = 0;

            for (int i = 0; i < r_1 - 1; ++i)// for each class, except last one
            {
                // finding left and right index of element that will be summed
                while (oldStatisticalTable[rightIndex].Key < rightBorder)
                {
                    ++rightIndex;
                }
                int sum = 0;
                for (int x = leftIndex; x < rightIndex; ++x)
                {
                    sum += oldStatisticalTable[x].Value;
                }
                // set new value
                newStatisticalTable.Add((leftBorder + rightBorder) / 2, sum);

                leftIndex   = rightIndex;
                leftBorder  = rightBorder;
                rightBorder = leftBorder + h;
            }
            // calculate last class
            rightBorder = oldStatisticalTable.Last().Key;
            int lastSum = 0;

            for (int x = leftIndex; x < oldStatisticalTable.Length; ++x)
            {
                lastSum += oldStatisticalTable[x].Value;
            }
            // set new value
            newStatisticalTable.Add((leftBorder + rightBorder) / 2, lastSum);

            // new discrete variable has been created
            DiscreteVariable dv = new DiscreteVariable(newStatisticalTable);

            if (dv.Size != veryBigDiscrete.Size)
            {
                throw new System.ArgumentException("Some elements has been lost");
            }
            return(dv);
        }
Exemplo n.º 2
0
        private static void KeyHandler(KeyboardAction action, KeyboardKey key)
        {
            //Console.WriteLine($"TestKeyEvents.KeyHandler({action}, {key})");
            if (action == KeyboardAction.KeyRelease)
            {
                switch (key)
                {
                case KeyboardKey.Num_1:
                    window.SetClearColor(128, 52, 43);
                    break;

                case KeyboardKey.Num_2:
                    window.SetClearColor(28, 108, 218);
                    break;

                case KeyboardKey.I:
                    var n = ran.Next();
                    test.Add(n, $"insert({n})");
                    break;

                case KeyboardKey.Escape:
                    window.CloseWindow();
                    break;
                }
            }
        }
        private void CreateControlsSound(Vector2 controlsOrigin)
        {
            AddSeparator(controlsOrigin);

            Controls.Add(new MyGuiControlLabel(this, controlsOrigin + m_controlsAdded * CONTROLS_DELTA + new Vector2(0.05f, 0), null, MyTextsWrapperEnum.SoundInfluenceSphereType, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));

            m_controlsAdded++;

            m_selectDialogueCombobox = new MyGuiControlCombobox(this,
                                                                controlsOrigin + m_controlsAdded++ *CONTROLS_DELTA +
                                                                new Vector2(MyGuiConstants.COMBOBOX_LONGMEDIUM_SIZE.X / 2.0f, 0),
                                                                MyGuiControlPreDefinedSize.LONGMEDIUM,
                                                                MyGuiConstants.COMBOBOX_BACKGROUND_COLOR,
                                                                MyGuiConstants.COMBOBOX_TEXT_SCALE, 6, false, false, false);

            System.Collections.Generic.SortedDictionary <string, int> dialogues = new System.Collections.Generic.SortedDictionary <string, int>();

            foreach (MyDialogueEnum dialogue in Enum.GetValues(typeof(MyDialogueEnum)))
            {
                dialogues.Add(dialogue.ToString(), (int)dialogue);
            }

            foreach (var dialogue in dialogues)
            {
                m_selectDialogueCombobox.AddItem(dialogue.Value, null, new StringBuilder(dialogue.Key));
            }

            m_selectDialogueCombobox.SelectItemByIndex(0);

            Controls.Add(m_selectDialogueCombobox);
        }
Exemplo n.º 4
0
 private void HandleEvents()
 {
     lock (pendingActions)
     {
         while (pendingActions.Count > 0)
         {
             var action = pendingActions.Dequeue();
             if (action.type == ActionData.Type.Added)
             {
                 GameObject qrCodeObject = Instantiate(qrCodePrefab, new Vector3(0, 0, 0), Quaternion.identity);
                 qrCodeObject.GetComponent <SpatialGraphCoordinateSystem>().Id = action.qrCode.Id;
                 qrCodeObject.GetComponent <QRCode>().qrCode = action.qrCode;
                 qrCodesObjectsList.Add(action.qrCode.Id, qrCodeObject);
             }
             else if (action.type == ActionData.Type.Updated)
             {
                 if (!qrCodesObjectsList.ContainsKey(action.qrCode.Id))
                 {
                     GameObject qrCodeObject = Instantiate(qrCodePrefab, new Vector3(0, 0, 0), Quaternion.identity);
                     qrCodeObject.GetComponent <SpatialGraphCoordinateSystem>().Id = action.qrCode.Id;
                     qrCodeObject.GetComponent <QRCode>().qrCode = action.qrCode;
                     qrCodesObjectsList.Add(action.qrCode.Id, qrCodeObject);
                 }
             }
             else if (action.type == ActionData.Type.Removed)
             {
                 if (qrCodesObjectsList.ContainsKey(action.qrCode.Id))
                 {
                     Destroy(qrCodesObjectsList[action.qrCode.Id]);
                     qrCodesObjectsList.Remove(action.qrCode.Id);
                 }
             }
         }
     }
     if (clearExisting)
     {
         clearExisting = false;
         foreach (var obj in qrCodesObjectsList)
         {
             Destroy(obj.Value);
         }
         qrCodesObjectsList.Clear();
     }
 }
Exemplo n.º 5
0
 public void AddPublicKey(Guid ID, byte[] Bytes)
 {
     if (Bytes == null)
     {
         throw new ArgumentNullException("Bytes");
     }
     lock (PublicKeys) {
         PublicKeys.Add(ID, Bytes);
     }
 }
Exemplo n.º 6
0
		public static System.Collections.Generic.SortedDictionary<string, double> ReadPositionReports(this MemoryBuffer buffer)
		{
			int length = buffer.ReadCount();
			var result = new System.Collections.Generic.SortedDictionary<string, double>();
			for(int index = 0; index < length; ++index)
			{
				result.Add(buffer.ReadAString(), buffer.ReadDouble());
			}
			return result;
		}
Exemplo n.º 7
0
        // METHODS
        public void Run(int from)
        {
            Reset();
            openSet.Add(from, 0);// start position

            while (openSet.Count != 0)
            {
                // get closest edge
                int closestEdge = openSet.Values.Min();
                System.Collections.Generic.KeyValuePair <int, int> currentEdge = openSet.FirstOrDefault(v => v.Value == closestEdge);
                // finding shorter path
                CheckNeighbours(
                    neighbourWeight: graph.GetWeightToHeighbour(currentEdge.Key),
                    currentWeight: currentEdge.Value,
                    fromEdge: 0,
                    toEdge: graph.Size);
                // remove processed edge
                openSet.Remove(currentEdge.Key);
                closedSet.Add(currentEdge.Key, currentEdge.Value);
                path.Add(currentEdge.Key);
            }
        }
Exemplo n.º 8
0
        // METHODS
        private void CreateLetterCipherTable()
        {
            letterCipherTable.Clear();

            char[] letters = alphabet.Letters;

            for (int x = 0; x < letters.Length; ++x)
            {
                int letterCypherIndex = (a * x + b) % m;

                letterCipherTable.Add(letters[x], letters[letterCypherIndex]);
            }
        }
Exemplo n.º 9
0
 public void addOption(ConfigOptionInfo option)
 {
     /** Decrement the number of options remaining so that we know when we can draw the form **/
     numberOfOptions--;
     /** Add the option to the hashtable **/
     options.Add((uint)option.getOptionid(), option);
     /** If it is a choice type we must get the choices for it before requesting the settings **/
     if ((ConfigType)option.getType() == ConfigType.Choice)
     {
         var cmd = Command.Config | Command.GetOptionChoices;
         _core.SendAsync(new Message(cmd).Add((uint)option.getOptionid()));
     }
 }
Exemplo n.º 10
0
        private void QrTracker_Added(QRCodeAddedEventArgs args)
        {
            lock (qrCodesList)
            {
                qrCodesList.Add(args.Code.Id, args.Code);
            }
            var handlers = QRCodeAdded;

            if (handlers != null)
            {
                handlers(this, QRCodeEventArgs.Create(args.Code));
            }
        }
Exemplo n.º 11
0
        /// <summary> </summary>
        /// <param name="term">The term to map
        /// </param>
        /// <param name="frequency">The frequency of the term
        /// </param>
        /// <param name="offsets">Offset information, may be null
        /// </param>
        /// <param name="positions">Position information, may be null
        /// </param>
        //We need to combine any previous mentions of the term
        public override void  Map(System.String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions)
        {
            TermVectorEntry entry = (TermVectorEntry)termToTVE[term];

            if (entry == null)
            {
                entry           = new TermVectorEntry(ALL, term, frequency, storeOffsets == true?offsets:null, storePositions == true?positions:null);
                termToTVE[term] = entry;
                currentSet.Add(entry, entry);
            }
            else
            {
                entry.SetFrequency(entry.GetFrequency() + frequency);
                if (storeOffsets)
                {
                    TermVectorOffsetInfo[] existingOffsets = entry.GetOffsets();
                    //A few diff. cases here:  offsets is null, existing offsets is null, both are null, same for positions
                    if (existingOffsets != null && offsets != null && offsets.Length > 0)
                    {
                        //copy over the existing offsets
                        TermVectorOffsetInfo[] newOffsets = new TermVectorOffsetInfo[existingOffsets.Length + offsets.Length];
                        Array.Copy(existingOffsets, 0, newOffsets, 0, existingOffsets.Length);
                        Array.Copy(offsets, 0, newOffsets, existingOffsets.Length, offsets.Length);
                        entry.SetOffsets(newOffsets);
                    }
                    else if (existingOffsets == null && offsets != null && offsets.Length > 0)
                    {
                        entry.SetOffsets(offsets);
                    }
                    //else leave it alone
                }
                if (storePositions)
                {
                    int[] existingPositions = entry.GetPositions();
                    if (existingPositions != null && positions != null && positions.Length > 0)
                    {
                        int[] newPositions = new int[existingPositions.Length + positions.Length];
                        Array.Copy(existingPositions, 0, newPositions, 0, existingPositions.Length);
                        Array.Copy(positions, 0, newPositions, existingPositions.Length, positions.Length);
                        entry.SetPositions(newPositions);
                    }
                    else if (existingPositions == null && positions != null && positions.Length > 0)
                    {
                        entry.SetPositions(positions);
                    }
                }
            }
        }
Exemplo n.º 12
0
            public System.Collections.Generic.SortedDictionary <decimal, table_row> GroupByDecimal(T ur_col)
            {
                var ret_table = new System.Collections.Generic.SortedDictionary <decimal, table_row>();

                foreach (var row_entry in this)
                {
                    var key_val = row_entry.GetDecimal(ur_col);
                    if (ret_table.ContainsKey(key_val) == false)
                    {
                        ret_table.Add(key_val, new table_row());
                    }

                    ret_table[key_val].Add(row_entry);
                }

                return(ret_table);
            }
Exemplo n.º 13
0
 public virtual void  Run()
 {
     while (running)
     {
         // sort items from oldest to newest
         // we delete the oldest filters
         if (Enclosing_Instance.cache.Count > Enclosing_Instance.cacheCleanSize)
         {
             // empty the temporary set
             sortedFilterItems.Clear();
             lock (Enclosing_Instance.cache.SyncRoot)
             {
                 System.Collections.IDictionaryEnumerator entries = Enclosing_Instance.cache.GetEnumerator();
                 while (entries.MoveNext())
                 {
                     sortedFilterItems.Add(entries.Entry.Key, entries.Entry.Value);
                 }
                 System.Collections.IEnumerator it = sortedFilterItems.GetEnumerator();
                 int numToDelete = (int)((Enclosing_Instance.cache.Count - Enclosing_Instance.cacheCleanSize) * 1.5);
                 int counter     = 0;
                 // loop over the set and delete all of the cache entries not used in a while
                 while (it.MoveNext() && counter++ < numToDelete)
                 {
                     System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry)it.Current;
                     Enclosing_Instance.cache.Remove(entry.Key);
                 }
             }
             // empty the set so we don't tie up the memory
             sortedFilterItems.Clear();
         }
         // take a nap
         try
         {
             System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * Enclosing_Instance.cleanSleepTime));
         }
         catch (System.Threading.ThreadInterruptedException)
         {
             // just keep going
         }
     }
 }
Exemplo n.º 14
0
 private long GetRow(long row)
 {
     if (m_rowIndex == null)
     {
         long r;
         if (m_index.TryGetValue(row, out r))
         {
             return(r);
         }
         else
         {
             r = vc.select.GetIndexFirstMatch(row);
             m_index.Add(row, r);
             return(r);
         }
     }
     else
     {
         return(m_rowIndex[row]);
     }
 }
        static StackObject *Add_1(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 3);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            ILRuntime.Runtime.Intepreter.ILTypeInstance @value = (ILRuntime.Runtime.Intepreter.ILTypeInstance) typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 2);
            System.Int32 @key = ptr_of_this_method->Value;

            ptr_of_this_method = ILIntepreter.Minus(__esp, 3);
            System.Collections.Generic.SortedDictionary <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance> instance_of_this_method = (System.Collections.Generic.SortedDictionary <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance>) typeof(System.Collections.Generic.SortedDictionary <System.Int32, ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags) 0);
            __intp.Free(ptr_of_this_method);

            instance_of_this_method.Add(@key, @value);

            return(__ret);
        }
Exemplo n.º 16
0
        static void FindTeamAffiliations(string input)
        {
            // key=team
            // value=list of countries that support this team
            System.Collections.Generic.SortedDictionary<int, System.Collections.Generic.SortedSet<int>> teamSupporters = new System.Collections.Generic.SortedDictionary<int, System.Collections.Generic.SortedSet<int>>();

            string[] teamsSupportedByCountries = input.Split(new char[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);

            int countryId = 0;
            foreach( string teamsSupportedByThisCountryString in teamsSupportedByCountries)
            {
                countryId++;

                string[] teamsSupportedByThisCountry = teamsSupportedByThisCountryString.Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                foreach( string teamSupportedByThisCountry in teamsSupportedByThisCountry)
                {
                    int teamId = System.Int32.Parse(teamSupportedByThisCountry);
                    if (!teamSupporters.ContainsKey(teamId))
                    {
                        teamSupporters.Add(teamId, new System.Collections.Generic.SortedSet<int>());
                    }

                    teamSupporters[teamId].Add(countryId);
                }
            }

            System.Collections.Generic.List<string> output = new System.Collections.Generic.List<string>();
            foreach( int teamId in teamSupporters.Keys )
            {
                System.Collections.Generic.SortedSet<int> countriesThatSupportTeam = teamSupporters[teamId];
                int[] countryList = new int[countriesThatSupportTeam.Count];
                countriesThatSupportTeam.CopyTo(countryList);

                output.Add(teamId + ":" + string.Join(",", countryList) + ";");
            }

            System.Console.WriteLine(string.Join(" ", output.ToArray()));
        }
        public FireflyComponentBrowser()
            :
            base(null)
        {
            // Set the window title reading it from the resources.
            this.Caption = "Firefly Toolbox";
            // Set the image that will appear on the tab of the window frame
            // when docked with an other window
            // The resource ID correspond to the one defined in the resx file
            // while the Index is the offset in the bitmap strip. Each image in
            // the strip being 16x16.
            this.BitmapResourceID = 301;
            this.BitmapIndex      = 1;

            control = new MyControl();

            Panel p = new Panel();

            p.BorderStyle = BorderStyle.None;
            p.Dock        = DockStyle.Fill;
            p.BackColor   = SystemColors.ControlDark;

            System.Windows.Forms.TreeView treeView = new TreeView();
            ImageListManager imageList             = new ImageListManager();

            imageList.SetToTreeView(treeView);


            //treeView.Dock = DockStyle.Fill;
            treeView.Anchor      = AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;
            treeView.BorderStyle = BorderStyle.None;
            uint cookie = 0;
            Cmd  addSelectedControlToToolBox =
                delegate
            {
                try
                {
                    IToolboxService toolboxService = (IToolboxService)this.GetService(typeof(IToolboxService));
                    toolboxService.AddToolboxItem((ToolboxItem)treeView.SelectedNode.Tag,
                                                  toolboxService.SelectedCategory ?? "General");
                }
                catch
                {
                }
            };
            ToolStrip toolStrip = new ToolStrip();

            toolStrip.GripStyle = ToolStripGripStyle.Hidden;
            //toolStrip.Dock = DockStyle.Top;
            ProfessionalColorTable professionalColorTable = new ProfessionalColorTable();

            professionalColorTable.UseSystemColors = true;
            ToolStripProfessionalRenderer toolStripRenderer = new ToolStripProfessionalRenderer(professionalColorTable);

            toolStripRenderer.RoundedEdges = false;
            toolStrip.Anchor   = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
            toolStrip.Renderer = toolStripRenderer;

            control.Controls.Add(p);
            toolStrip.AutoSize = false;
            toolStrip.Bounds   = new Rectangle(1, 0, p.Width - 2, toolStrip.Height + 1);
            treeView.Bounds    = new Rectangle(1, toolStrip.Height + 1, p.Width - 2, p.Height - toolStrip.Height - 2);
            //            p.Padding = new Padding(1,0,1,1);
            //            treeView.Margin = new Padding(0, 1, 0, 0);
            p.Controls.Add(treeView);
            p.Controls.Add(toolStrip);

            imageList.Add("Assembly", Resources.Assembly);
            imageList.Add("Namespace", Resources.Namespace);

            Bitmap          bmp = Resources.AddToFavoritesHS;
            ToolStripButton addToToolBoxButton = new ToolStripButton(bmp);

            addToToolBoxButton.ToolTipText           = "Add to tool box";
            addToToolBoxButton.ImageTransparentColor = System.Drawing.Color.Black;
            toolStrip.Items.Add(addToToolBoxButton);
            addToToolBoxButton.Click +=
                delegate { addSelectedControlToToolBox(); };


            ContextMenuStrip  contextMenu          = new ContextMenuStrip();
            ToolStripMenuItem addToToolBoxMenuItem = new ToolStripMenuItem("&Add to tool box", bmp);

            addToToolBoxMenuItem.ImageTransparentColor = System.Drawing.Color.Black;
            addToToolBoxMenuItem.Click +=
                delegate { addSelectedControlToToolBox(); };
            contextMenu.Items.Add(addToToolBoxMenuItem);

            ToolStripMenuItem about = new ToolStripMenuItem("A&bout");

            about.Click += delegate { new AboutBox().ShowDialog(); };
            contextMenu.Items.Add(new ToolStripSeparator());
            contextMenu.Items.Add(about);
            treeView.BeforeSelect +=
                delegate(object sender, TreeViewCancelEventArgs e)
            {
                addToToolBoxButton.Enabled   = e.Node.Tag != null;
                addToToolBoxMenuItem.Enabled = e.Node.Tag != null;
            };
            treeView.ContextMenuStrip = contextMenu;
            treeView.MouseDown       +=
                delegate(object sender, MouseEventArgs e)
            {
                if (e.Button == MouseButtons.Right)
                {
                    TreeNode node = treeView.HitTest(e.Location).Node;
                    if (node != null)
                    {
                        treeView.SelectedNode = node;

                        if (treeView.SelectedNode.Tag != null)
                        {
                            contextMenu.Show(treeView, e.Location);
                        }
                    }
                }
            };
            SelectionHandler selectionHandler = new SelectionHandler(treeView);

            treeView.KeyDown +=
                delegate(object sender, KeyEventArgs e)
            {
                if (e.KeyData == Keys.Apps && treeView.SelectedNode.Tag != null)
                {
                    contextMenu.Show(treeView, 0, 0);
                }
            };
            bool reloading = false;

            System.Windows.Forms.ToolStripProgressBar progress = new ToolStripProgressBar();
            progress.Visible            = false;
            progress.Height             = 10;
            progress.ProgressBar.Height = 10;
            System.Windows.Forms.ToolStripLabel loading = new ToolStripLabel();
            loading.Text    = "Loading...";
            loading.Visible = false;
            Thread theThread = null;

            Bitmap          bmp1          = Resources.Refresh;
            ToolStripButton refreshButton = new ToolStripButton(bmp1);

            refreshButton.ToolTipText           = "Refresh";
            refreshButton.ImageTransparentColor = System.Drawing.Color.Black;
            toolStrip.Items.Add(refreshButton);
            Action <bool> end =
                delegate(bool treeEnabled)
            {
                reloading = false;
                DoOnUIThread(delegate()
                {
                    progress.Visible      = false;
                    loading.Visible       = false;
                    refreshButton.Enabled = true;
                    treeView.Enabled      = treeEnabled;
                });
                selectionHandler.EndLoading();

                theThread = null;
            };

            Action <string> reportMessage =
                delegate(string message)
            {
                IVsOutputWindow outWindow = GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
                if (outWindow != null)
                {
                    Guid generalWindowGuid =
                        Microsoft.VisualStudio.VSConstants.GUID_OutWindowGeneralPane;
                    IVsOutputWindowPane windowPane;

                    outWindow.GetPane(ref generalWindowGuid, out windowPane);
                    windowPane.OutputString(message);
                }
            };

            Action <Exception> reportException =
                delegate(Exception ex)
            {
                reportMessage(string.Format("{0}\n\n{1}\n", ex.Message, ex.StackTrace));
            };
            Action <bool> reloadTree =
                delegate(bool forceRefresh)
            {
                if (reloading)
                {
                    return;
                }


                reloading = true;

                EnvDTE.DTE    dte          = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
                IDesignerHost designerHost = GetActiveDesigner(dte);
                if (designerHost == null)
                {
                    end(false);
                    return;
                }

                IToolboxService toolboxService = (IToolboxService)designerHost.GetService(
                    typeof(IToolboxService));
                Type rootBaseType = null;
                try
                {
                    if (designerHost.RootComponent == null)
                    {
                        end(false);
                        return;
                    }
                    rootBaseType = designerHost.RootComponent.GetType();
                }
                catch
                {
                    end(false);
                    return;
                }
                if (!forceRefresh && _lastDesignedType != typeof(object))
                {
                    end(_lastDesignedType == rootBaseType);
                    return;
                }
                _lastDesignedType = rootBaseType;
                DoOnUIThread(delegate()
                {
                    progress.Visible      = true;
                    loading.Visible       = true;
                    refreshButton.Enabled = false;
                    progress.Value        = 1;
                    treeView.Nodes.Clear();
                });
                selectionHandler.Reloadion();

                theThread = new Thread(
                    delegate()
                {
                    lock (reloadLock)
                    {
                        try
                        {
                            VSLangProj.VSProject proj    = (VSLangProj.VSProject)dte.ActiveDocument.ProjectItem.ContainingProject.Object;
                            string projectOutputFileName =
                                System.IO.Path.Combine(
                                    proj.Project.ConfigurationManager.
                                    ActiveConfiguration
                                    .Properties.Item("OutputPath").Value.
                                    ToString(),
                                    proj.Project.Properties.Item("OutputFileName").
                                    Value.
                                    ToString
                                        ());
                            string fullProjectOutputFileName =
                                System.IO.Path.IsPathRooted(projectOutputFileName)
                                            ?
                                projectOutputFileName
                                            : System.IO.Path.Combine(
                                    System.IO.Path.GetDirectoryName(
                                        proj.Project.FileName),
                                    projectOutputFileName);

                            AddAssembly addAssembly =
                                delegate(string assemblyPath, bool publicTypesOnly)
                            {
                                AppDomainSetup ads  = new AppDomainSetup();
                                ads.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                                AppDomain appDomainForAssemblyLoading = AppDomain.CreateDomain(
                                    "AppDomainForAssemblyLoading", null, ads);

                                System.Collections.Generic.SortedDictionary <string,
                                                                             System.Collections.Generic.SortedDictionary <string, TreeNode> > nodes =
                                    new System.Collections.Generic.SortedDictionary <string,
                                                                                     System.Collections.Generic.SortedDictionary <string, TreeNode> >();
                                AssemblyName assemblyName = null;

                                try
                                {
                                    assemblyName = ((AssemblyNameProxy)
                                                    appDomainForAssemblyLoading.CreateInstanceAndUnwrap(
                                                        typeof(AssemblyNameProxy).Assembly.FullName,
                                                        typeof(AssemblyNameProxy).FullName)).GetAssemblyName(assemblyPath);
                                    ResolveEventHandler resolve =
                                        delegate(object sender, ResolveEventArgs args)
                                    {
                                        return(args.Name == Assembly.GetExecutingAssembly().FullName ?
                                               Assembly.GetExecutingAssembly() : null);
                                    };
                                    AppDomain.CurrentDomain.AssemblyResolve += resolve;
                                    AssemblyLoader assemblyLoader            = (AssemblyLoader)
                                                                               appDomainForAssemblyLoading.CreateInstanceFromAndUnwrap(
                                        Assembly.GetExecutingAssembly().Location,
                                        typeof(AssemblyLoaderClass).FullName);
                                    AppDomain.CurrentDomain.AssemblyResolve -= resolve;

                                    assemblyLoader.DoOnTypes(assemblyName, System.IO.Path.GetDirectoryName(fullProjectOutputFileName),
                                                             new AssemblyLoaderClientClass(
                                                                 delegate(string typeNamespace, ToolboxItem item)
                                    {
                                        try
                                        {
                                            if (toolboxService.IsSupported(toolboxService.SerializeToolboxItem(item), designerHost))
                                            {
                                                item.Lock();
                                                System.Windows.Forms.TreeNode node = new TreeNode();
                                                DoOnUIThread(
                                                    delegate()
                                                {
                                                    node     = new TreeNode(item.DisplayName);
                                                    node.Tag = item;
                                                    imageList.Add(item.TypeName, item.Bitmap);
                                                    node.ImageIndex         = imageList.GetImageIndexFor(item.TypeName);
                                                    node.SelectedImageIndex = imageList.GetImageIndexFor(item.TypeName);
                                                });

                                                System.Collections.Generic.SortedDictionary <string, TreeNode>
                                                componentNodes;
                                                if (!nodes.TryGetValue(typeNamespace, out componentNodes))
                                                {
                                                    componentNodes =
                                                        new System.Collections.Generic.SortedDictionary <
                                                            string, TreeNode>();
                                                    nodes.Add(typeNamespace, componentNodes);
                                                }
                                                componentNodes.Add(item.DisplayName, node);
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            try
                                            {
                                                reportMessage(
                                                    string.Format(
                                                        "Firefly Toolbox error - Exception occured on load of " +
                                                        item.TypeName +
                                                        " the exception is:\n" + e));
                                            }
                                            catch { }
                                        }
                                    }), publicTypesOnly);
                                }
                                catch (Exception e)
                                {
                                    try
                                    {
                                        DoOnUIThread(
                                            delegate()
                                        {
                                            System.Windows.Forms.TreeNode node = new TreeNode();
                                            node.Text = "Error loading " + assemblyName + " - " +
                                                        e.ToString();
                                            treeView.Nodes.Add(node);
                                        });

                                        reportMessage(
                                            string.Format(
                                                "Firefly Toolbox error - Exception occured on load of " +
                                                assemblyName.ToString() +
                                                " the exception is:\n" + e));
                                        ReflectionTypeLoadException le = e as ReflectionTypeLoadException;
                                        if (le != null)
                                        {
                                            foreach (Exception ie in le.LoaderExceptions)
                                            {
                                                reportMessage(
                                                    string.Format(
                                                        "loader exception exception exception is:\n" +
                                                        ie));
                                            }
                                        }
                                    }
                                    catch { }
                                }
                                finally
                                {
                                    AppDomain.Unload(appDomainForAssemblyLoading);
                                }
                                if (nodes.Count > 0)
                                {
                                    DoOnUIThread(
                                        delegate
                                    {
                                        treeView.BeginUpdate();
                                        try
                                        {
                                            System.Windows.Forms.TreeNode assemblyNode =
                                                new TreeNode(assemblyName.Name);
                                            assemblyNode.ImageIndex         = imageList.GetImageIndexFor("Assembly");
                                            assemblyNode.SelectedImageIndex = imageList.GetImageIndexFor("Assembly");
                                            treeView.Nodes.Add(assemblyNode);
                                            foreach (System.Collections.Generic.KeyValuePair <string,
                                                                                              System.Collections.Generic.SortedDictionary
                                                                                              <string, TreeNode> >
                                                     pair in nodes)
                                            {
                                                TreeNode namespaceNode           = new TreeNode(pair.Key);
                                                namespaceNode.ImageIndex         = imageList.GetImageIndexFor("Namespace");
                                                namespaceNode.SelectedImageIndex = imageList.GetImageIndexFor("Namespace");
                                                assemblyNode.Nodes.Add(namespaceNode);
                                                foreach (TreeNode n in pair.Value.Values)
                                                {
                                                    namespaceNode.Nodes.Add(n);
                                                    selectionHandler.Loaded(n);
                                                }
                                                imageList.CommitToUi();
                                            }
                                        }
                                        finally
                                        {
                                            treeView.EndUpdate();
                                            if (treeView.SelectedNode != null)
                                            {
                                                treeView.Update();
                                                treeView.Select();
                                            }
                                        }
                                    });
                                }
                            };


                            System.Collections.Generic.SortedDictionary <string, Cmd> addAssemblies =
                                new System.Collections.Generic.SortedDictionary <string, Cmd>();

                            if (System.IO.File.Exists(fullProjectOutputFileName))
                            {
                                addAssemblies[Path.GetFileName(fullProjectOutputFileName)] =
                                    delegate
                                {
                                    addAssembly(fullProjectOutputFileName, false);
                                };
                            }
                            foreach (
                                VSLangProj.Reference reference in proj.References)
                            {
                                string path = reference.Path;
                                addAssemblies[Path.GetFileName(path)] =
                                    delegate
                                {
                                    addAssembly(path, true);
                                };
                            }


                            DoOnUIThread(
                                delegate()
                            {
                                progress.ProgressBar.Maximum = addAssemblies.Count + 1;
                            });
                            foreach (Cmd cmd in addAssemblies.Values)
                            {
                                cmd();
                                DoOnUIThread(
                                    delegate()
                                {
                                    try
                                    {
                                        progress.ProgressBar.Value++;
                                    }
                                    catch
                                    {
                                    }
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!(ex is ThreadAbortException))
                            {
                                reportException(ex);
                            }
                        }
                        finally
                        {
                            end(true);
                        }
                    }
                });
                theThread.Start();
            };

            loading.Click += delegate
            {
                reloading = false;
                theThread.Abort();
                end(true);
            };

            refreshButton.Click +=
                delegate { reloadTree(true); };


            toolStrip.Items.Add(progress);
            toolStrip.Items.Add(loading);


            mySelectionListener listener = new mySelectionListener(treeView, delegate() { reloadTree(false); });

            control.Load +=
                delegate
            {
                IVsMonitorSelection monitor = (IVsMonitorSelection)GetService(typeof(IVsMonitorSelection));
                monitor.AdviseSelectionEvents(listener, out cookie);
                reloadTree(false);
            };
            control.Disposed +=
                delegate
            {
                IVsMonitorSelection monitor = (IVsMonitorSelection)GetService(typeof(IVsMonitorSelection));
                monitor.UnadviseSelectionEvents(cookie);
            };
            treeView.ItemDrag +=
                delegate(object sender, ItemDragEventArgs e)
            {
                IToolboxService toolboxService     = (IToolboxService)this.GetService(typeof(IToolboxService));
                System.Windows.Forms.TreeNode node = (System.Windows.Forms.TreeNode)e.Item;
                if (node.Tag == null)
                {
                    return;
                }
                System.Windows.Forms.DataObject dataObject = toolboxService.SerializeToolboxItem(
                    (ToolboxItem)node.Tag) as System.Windows.Forms.DataObject;
                treeView.DoDragDrop(dataObject,
                                    System.Windows.Forms.DragDropEffects.All);
            };
        }
        public override void  Map(System.String term, int frequency, TermVectorOffsetInfo[] offsets, int[] positions)
        {
            TermVectorEntry entry = new TermVectorEntry(currentField, term, frequency, offsets, positions);

            currentSet.Add(entry, entry);
        }
Exemplo n.º 19
0
    } // end of SetObjectData
    #endregion

    static LineCapEx()
    {
      _defaultStyle = new DefaultLineCapWrapper();
      _registeredStyles = new System.Collections.Generic.SortedDictionary<string, LineCapExtension>();


      // first register the predefined styles
      foreach (LineCap cap in Enum.GetValues(typeof(LineCap)))
      {
        if (cap == LineCap.Custom)
        {
          continue;
        }
        if(cap==LineCap.Flat)
        {
          _registeredStyles.Add(_defaultStyle.Name,_defaultStyle);
        }
        else
        {
          LineCapExtension ex = new KnownLineCapWrapper(cap);
          _registeredStyles.Add(ex.Name,ex);
        }
      }

      // now the other linecaps
      LineCapExtension more;
      more = new LineCaps.ArrowF10LineCap();
      _registeredStyles.Add(more.Name, more);
      more = new LineCaps.ArrowF20LineCap();
      _registeredStyles.Add(more.Name, more);
      more = new LineCaps.LeftBarLineCap();
      _registeredStyles.Add(more.Name, more);
      more = new LineCaps.RightBarLineCap();
      _registeredStyles.Add(more.Name, more);
      more = new LineCaps.SymBarLineCap();
      _registeredStyles.Add(more.Name, more);
    }
Exemplo n.º 20
0
        public override void OnInspectorGUI()
        {
            var style = new GUIStyle(EditorStyles.toolbar);

            style.fixedHeight   = 0f;
            style.stretchHeight = true;

            var backStyle = new GUIStyle(EditorStyles.label);

            backStyle.normal.background = Texture2D.whiteTexture;

            var dataConfig = (ME.ECS.DataConfigs.DataConfig) this.target;

            if (DataConfigEditor.worldEditors.TryGetValue(this.target, out var worldEditor) == false)
            {
                worldEditor = new WorldsViewerEditor.WorldEditor();
                DataConfigEditor.worldEditors.Add(this.target, worldEditor);
            }

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.structComponents;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, Registry>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IStructComponent>();
                                dataConfig.structComponents[registry.index] = component;
                            }
                        }
                        else
                        {
                            var componentName = component.GetType().Name;
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(worldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.structComponents[registry.index] = component;
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(18f);
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            var changed = GUILayoutExt.DrawFields(worldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.structComponents[registry.index] = component;
                                            }
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.structComponents.Length; ++i)
                        {
                            if (dataConfig.structComponents[i].GetType() == addType)
                            {
                                var list = dataConfig.structComponents.ToList();
                                list.RemoveAt(i);
                                dataConfig.structComponents = list.ToArray();
                                dataConfig.OnScriptLoad();
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.structComponents, dataConfig.structComponents.Length + 1);
                        dataConfig.structComponents[dataConfig.structComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                    }
                });
            });

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.components;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, RegistryComponent>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IComponent>();
                                dataConfig.components[registry.index] = component;
                            }
                        }
                        else
                        {
                            var componentName = component.GetType().Name;
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(worldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.components[registry.index] = component;
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(18f);
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            var changed = GUILayoutExt.DrawFields(worldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.components[registry.index] = component;
                                            }
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.components.Length; ++i)
                        {
                            if (dataConfig.components[i].GetType() == addType)
                            {
                                var list = dataConfig.components.ToList();
                                list.RemoveAt(i);
                                dataConfig.components = list.ToArray();
                                dataConfig.OnScriptLoad();
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.components, dataConfig.components.Length + 1);
                        dataConfig.components[dataConfig.components.Length - 1] = (IComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                    }
                }, drawRefComponents: true);
            });
        }
Exemplo n.º 21
0
        public override void OnInspectorGUI()
        {
            var style = new GUIStyle(EditorStyles.toolbar);

            style.fixedHeight   = 0f;
            style.stretchHeight = true;

            var backStyle = new GUIStyle(EditorStyles.label);

            backStyle.normal.background = Texture2D.whiteTexture;

            var slice      = new ME.ECS.DataConfigs.DataConfigSlice();
            var isMultiple = false;

            if (this.targets.Length > 1)
            {
                slice      = ME.ECS.DataConfigs.DataConfigSlice.Distinct(this.targets.Cast <ME.ECS.DataConfigs.DataConfig>().ToArray());
                isMultiple = true;
            }
            else
            {
                var config = (ME.ECS.DataConfigs.DataConfig) this.target;
                slice = new ME.ECS.DataConfigs.DataConfigSlice()
                {
                    configs = new [] {
                        config
                    },
                    structComponentsDataTypeIds = config.structComponentsDataTypeIds,
                    componentsTypeIds           = config.componentsTypeIds
                };
            }

            var usedComponentsAll = new System.Collections.Generic.HashSet <System.Type>();

            foreach (var cfg in slice.configs)
            {
                var componentTypes = cfg.GetStructComponentTypes();
                foreach (var cType in componentTypes)
                {
                    if (usedComponentsAll.Contains(cType) == false)
                    {
                        usedComponentsAll.Add(cType);
                    }
                }

                if (DataConfigEditor.worldEditors.TryGetValue(cfg, out var worldEditor) == false)
                {
                    worldEditor = new WorldsViewerEditor.WorldEditor();
                    DataConfigEditor.worldEditors.Add(cfg, worldEditor);
                }
            }

            if (isMultiple == true)
            {
                GUILayoutExt.DrawHeader("The same components:");

                GUILayoutExt.Padding(8f, () => {
                    var kz = 0;
                    for (int i = 0; i < slice.structComponentsDataTypeIds.Length; ++i)
                    {
                        var typeId     = slice.structComponentsDataTypeIds[i];
                        var component  = slice.configs[0].GetByTypeId(typeId);
                        var components = slice.configs.Select(x => x.GetByTypeId(typeId)).ToArray();

                        var backColor       = GUI.backgroundColor;
                        GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                        GUILayout.BeginVertical(backStyle);
                        {
                            GUI.backgroundColor = backColor;
                            var editor          = WorldsViewerEditor.GetEditor(components);
                            if (editor != null)
                            {
                                EditorGUI.BeginChangeCheck();
                                editor.OnDrawGUI();
                                if (EditorGUI.EndChangeCheck() == true)
                                {
                                    slice.Set(typeId, components);
                                    this.Save(slice.configs);
                                }
                            }
                            else
                            {
                                var componentName = GUILayoutExt.GetStringCamelCaseSpace(component.GetType().Name);
                                var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                                if (fieldsCount == 0)
                                {
                                    EditorGUI.BeginDisabledGroup(true);
                                    EditorGUILayout.Toggle(componentName, true);
                                    EditorGUI.EndDisabledGroup();
                                }
                                else if (fieldsCount == 1)
                                {
                                    var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, components, componentName);
                                    if (changed == true)
                                    {
                                        slice.Set(typeId, components);
                                        this.Save(slice.configs);
                                    }
                                }
                                else
                                {
                                    GUILayout.BeginHorizontal();
                                    {
                                        GUILayout.Space(18f);
                                        GUILayout.BeginVertical();
                                        {
                                            var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                            var foldout = EditorPrefs.GetBool(key, true);
                                            GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, components);
                                                if (changed == true)
                                                {
                                                    slice.Set(typeId, components);
                                                    this.Save(slice.configs);
                                                }
                                            });
                                            EditorPrefs.SetBool(key, foldout);
                                        }
                                        GUILayout.EndVertical();
                                    }
                                    GUILayout.EndHorizontal();
                                }
                            }

                            GUILayoutExt.DrawComponentHelp(component.GetType());
                        }
                        GUILayout.EndVertical();

                        GUILayoutExt.Separator();
                    }
                });

                GUILayoutExt.DrawAddComponentMenu(usedComponentsAll, (addType, isUsed) => {
                    foreach (var dataConfigInner in slice.configs)
                    {
                        if (isUsed == true)
                        {
                            usedComponentsAll.Remove(addType);
                            for (int i = 0; i < dataConfigInner.structComponents.Length; ++i)
                            {
                                if (dataConfigInner.structComponents[i].GetType() == addType)
                                {
                                    var list = dataConfigInner.structComponents.ToList();
                                    list.RemoveAt(i);
                                    dataConfigInner.structComponents = list.ToArray();
                                    dataConfigInner.OnScriptLoad();
                                    this.Save(dataConfigInner);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            usedComponentsAll.Add(addType);
                            System.Array.Resize(ref dataConfigInner.structComponents, dataConfigInner.structComponents.Length + 1);
                            dataConfigInner.structComponents[dataConfigInner.structComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                            dataConfigInner.OnScriptLoad();
                            this.Save(dataConfigInner);
                        }
                    }
                });

                return;
            }

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Add Struct Components:");
            GUILayoutExt.Separator();

            var dataConfig = (ME.ECS.DataConfigs.DataConfig) this.target;

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.structComponents;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, Registry>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new Registry()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IStructComponent>();
                                dataConfig.structComponents[registry.index] = component;
                                this.Save(dataConfig);
                            }
                        }
                        else
                        {
                            var componentName = GUILayoutExt.GetStringCamelCaseSpace(component.GetType().Name);
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.structComponents[registry.index] = component;
                                    this.Save(dataConfig);
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(18f);
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.structComponents[registry.index] = component;
                                                this.Save(dataConfig);
                                            }
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }

                        GUILayoutExt.DrawComponentHelp(component.GetType());
                        this.DrawComponentTemplatesUsage(dataConfig, component);
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.structComponents.Length; ++i)
                        {
                            if (dataConfig.structComponents[i].GetType() == addType)
                            {
                                var list = dataConfig.structComponents.ToList();
                                list.RemoveAt(i);
                                dataConfig.structComponents = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.structComponents, dataConfig.structComponents.Length + 1);
                        dataConfig.structComponents[dataConfig.structComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                });
            });

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Add Managed Components:");
            GUILayoutExt.Separator();

            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz               = 0;
                var registries       = dataConfig.components;
                var sortedRegistries = new System.Collections.Generic.SortedDictionary <int, RegistryComponent>(new WorldsViewerEditor.DuplicateKeyComparer <int>());
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    if (registry == null)
                    {
                        continue;
                    }

                    var component = registry;
                    usedComponents.Add(component.GetType());

                    var editor = WorldsViewerEditor.GetEditor(component, out var order);
                    if (editor != null)
                    {
                        sortedRegistries.Add(order, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                    else
                    {
                        sortedRegistries.Add(0, new RegistryComponent()
                        {
                            index = i,
                            data  = component
                        });
                    }
                }

                foreach (var registryKv in sortedRegistries)
                {
                    var registry  = registryKv.Value;
                    var component = registry.data;

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var editor          = WorldsViewerEditor.GetEditor(component);
                        if (editor != null)
                        {
                            EditorGUI.BeginChangeCheck();
                            editor.OnDrawGUI();
                            if (EditorGUI.EndChangeCheck() == true)
                            {
                                component = editor.GetTarget <IComponent>();
                                dataConfig.components[registry.index] = component;
                                this.Save(dataConfig);
                            }
                        }
                        else
                        {
                            var componentName = component.GetType().Name;
                            var fieldsCount   = GUILayoutExt.GetFieldsCount(component);
                            if (fieldsCount == 0)
                            {
                                EditorGUI.BeginDisabledGroup(true);
                                EditorGUILayout.Toggle(componentName, true);
                                EditorGUI.EndDisabledGroup();
                            }
                            else if (fieldsCount == 1)
                            {
                                var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component, componentName);
                                if (changed == true)
                                {
                                    dataConfig.components[registry.index] = component;
                                    this.Save(dataConfig);
                                }
                            }
                            else
                            {
                                GUILayout.BeginHorizontal();
                                {
                                    GUILayout.Space(18f);
                                    GUILayout.BeginVertical();
                                    {
                                        var key     = "ME.ECS.WorldsViewerEditor.FoldoutTypes." + component.GetType().FullName;
                                        var foldout = EditorPrefs.GetBool(key, true);
                                        GUILayoutExt.FoldOut(ref foldout, componentName, () => {
                                            var changed = GUILayoutExt.DrawFields(DataConfigEditor.multipleWorldEditor, component);
                                            if (changed == true)
                                            {
                                                dataConfig.components[registry.index] = component;
                                                this.Save(dataConfig);
                                            }
                                        });
                                        EditorPrefs.SetBool(key, foldout);
                                    }
                                    GUILayout.EndVertical();
                                }
                                GUILayout.EndHorizontal();
                            }
                        }

                        GUILayoutExt.DrawComponentHelp(component.GetType());
                        this.DrawComponentTemplatesUsage(dataConfig, component);
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.components.Length; ++i)
                        {
                            if (dataConfig.components[i].GetType() == addType)
                            {
                                var list = dataConfig.components.ToList();
                                list.RemoveAt(i);
                                dataConfig.components = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.components, dataConfig.components.Length + 1);
                        dataConfig.components[dataConfig.components.Length - 1] = (IComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                }, drawRefComponents: true);
            });

            GUILayoutExt.Separator(6f);
            GUILayoutExt.DrawHeader("Remove Struct Components:");
            GUILayoutExt.Separator();

            // Remove struct components
            GUILayoutExt.Padding(8f, () => {
                var usedComponents = new System.Collections.Generic.HashSet <System.Type>();

                var kz         = 0;
                var registries = dataConfig.removeStructComponentsDataTypeIds;
                for (int i = 0; i < registries.Length; ++i)
                {
                    var registry = registries[i];
                    var type     = ComponentTypesRegistry.allTypeId.FirstOrDefault(x => x.Value == registry).Key;

                    if (type == null)
                    {
                        continue;
                    }

                    usedComponents.Add(type);

                    var backColor       = GUI.backgroundColor;
                    GUI.backgroundColor = new Color(1f, 1f, 1f, kz++ % 2 == 0 ? 0f : 0.05f);

                    GUILayout.BeginVertical(backStyle);
                    {
                        GUI.backgroundColor = backColor;
                        var componentName   = GUILayoutExt.GetStringCamelCaseSpace(type.Name);

                        EditorGUI.BeginDisabledGroup(true);
                        EditorGUILayout.Toggle(componentName, true);
                        EditorGUI.EndDisabledGroup();

                        GUILayoutExt.DrawComponentHelp(type);
                        this.DrawComponentTemplatesUsage(dataConfig, dataConfig.removeStructComponents[i]);
                    }
                    GUILayout.EndVertical();

                    GUILayoutExt.Separator();
                }

                GUILayoutExt.DrawAddComponentMenu(usedComponents, (addType, isUsed) => {
                    if (isUsed == true)
                    {
                        usedComponents.Remove(addType);
                        for (int i = 0; i < dataConfig.removeStructComponents.Length; ++i)
                        {
                            if (dataConfig.removeStructComponents[i].GetType() == addType)
                            {
                                var list = dataConfig.removeStructComponents.ToList();
                                list.RemoveAt(i);
                                dataConfig.removeStructComponents = list.ToArray();
                                dataConfig.OnScriptLoad();
                                this.Save(dataConfig);
                                break;
                            }
                        }
                    }
                    else
                    {
                        usedComponents.Add(addType);
                        System.Array.Resize(ref dataConfig.removeStructComponents, dataConfig.removeStructComponents.Length + 1);
                        dataConfig.removeStructComponents[dataConfig.removeStructComponents.Length - 1] = (IStructComponent)System.Activator.CreateInstance(addType);
                        dataConfig.OnScriptLoad();
                        this.Save(dataConfig);
                    }
                });
            });

            if ((dataConfig is ME.ECS.DataConfigs.DataConfigTemplate) == false)
            {
                this.DrawTemplates(dataConfig);
            }
        }
Exemplo n.º 22
0
        private void importAll()
        {
            mDelegate       dcUpdateStatus = new mDelegate(updateStatus);
            controlDelegate cDisable       = new controlDelegate(disableControls);
            controlDelegate cEnable        = new controlDelegate(enableControls);

            this.Invoke(cDisable);

            DirectoryInfo directoryInfo = new DirectoryInfo(importPath);

            FileInfo[] fileInfos = directoryInfo.GetFiles("*.png", SearchOption.TopDirectoryOnly);
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("Texture-([0-9]+).(PNG)");
            System.Collections.Generic.SortedDictionary <uint, string> dictionary = new System.Collections.Generic.SortedDictionary <uint, string>();
            uint highestID = 0;

            foreach (FileInfo fileInfo in fileInfos)
            {
                if (regex.IsMatch(fileInfo.Name))
                {
                    string[] tokens = regex.Split(fileInfo.Name);
                    if (tokens.Length == 4 && UInt32.TryParse(tokens[1], out uint index))
                    {
                        dictionary.Add(index, fileInfo.Name);
                        if (index > highestID)
                        {
                            highestID = index;
                        }
                    }
                }
            }

            if (dictionary.Count > 0)
            {
                totalTextures    = highestID;
                fStream.Position = 0;

                int    iEA, jEA;
                Bitmap tempBitmap = null;

                for (iEA = 0; iEA <= totalTextures; iEA++)
                {
                    this.Invoke(dcUpdateStatus, "Exporting texture " + iEA + " of " + totalTextures);

                    if (dictionary.ContainsKey((uint)iEA))
                    {
                        tempBitmap = new Bitmap(Path.Combine(importPath, dictionary[(uint)iEA]));
                        if ((tempBitmap.Size.Width != textureWidth) || (tempBitmap.Size.Height != textureHeight))
                        {
                            tempBitmap.Dispose();
                            tempBitmap = new Bitmap(textureWidth, textureHeight);
                        }
                    }
                    else
                    {
                        tempBitmap = new Bitmap(textureWidth, textureHeight);
                    }

                    int    iGT, jGT;
                    ushort a, r, g, b, pixelData;
                    int    aFactor, rFactor, gFactor, bFactor;
                    Color  colour;

                    aFactor = 1;
                    rFactor = 3;
                    gFactor = 3;
                    bFactor = 3;

                    colour = new Color();

                    fStream.Seek(getTextureOffset(iEA), SeekOrigin.Begin);

                    for (iGT = 0; iGT < textureHeight; iGT++)
                    {
                        for (jGT = 0; jGT < textureWidth; jGT++)
                        {
                            colour = tempBitmap.GetPixel(jGT, iGT);
                            a      = (ushort)(colour.A >> aFactor);
                            r      = (ushort)(colour.R >> rFactor);
                            g      = (ushort)(colour.G >> gFactor);
                            b      = (ushort)(colour.B >> bFactor);

                            a <<= 15;
                            r <<= 10;
                            g <<= 5;

                            pixelData = (ushort)(a | r | g | b);

                            bWriter.Write(pixelData);
                        }
                    }

                    tempBitmap.Dispose();
                }

                fileLength = fStream.Length;

                fStream.Seek(2, SeekOrigin.Begin);
                bWriter.Write((ushort)dictionary.Count);
                fStream.Seek(0, SeekOrigin.Begin);

                //bufferImage = getTexture(getTextureOffset(currentTexture));
                //imageUpdated = true;
            }

            this.Invoke(cEnable);
            this.Invoke(dcUpdateStatus, "Ready");
        }
Exemplo n.º 23
0
        public static ComparableComparator GetComparator(Type ta, Type tb)
        {
            if (ta == tb)
            {
                return(comparableComparatorIdentity);
            }
            if (comparableComparators == null)
            {
                comparableComparators = new System.Collections.Generic.SortedDictionary <TypePair, ComparableComparator>();
                var identity = comparableComparatorIdentity;
                comparableComparators.Add(new TypePair(typeof(int), typeof(string)), (IComparable a, IComparable b) => a.CompareTo(PromoteToInt((string)b)));
                comparableComparators.Add(new TypePair(typeof(float), typeof(string)), (IComparable a, IComparable b) => a.CompareTo(PromoteToFloat((string)b)));
                comparableComparators.Add(new TypePair(typeof(long), typeof(string)), (IComparable a, IComparable b) => a.CompareTo(PromoteToLong((string)b)));
                comparableComparators.Add(new TypePair(typeof(bool), typeof(string)), (IComparable a, IComparable b) => a.CompareTo(PromoteToBool((string)b)));

                comparableComparators.Add(new TypePair(typeof(string), typeof(int)), (IComparable a, IComparable b) => PromoteToInt((string)b).CompareTo(a));
                comparableComparators.Add(new TypePair(typeof(string), typeof(float)), (IComparable a, IComparable b) => PromoteToFloat((string)b).CompareTo(a));
                comparableComparators.Add(new TypePair(typeof(string), typeof(long)), (IComparable a, IComparable b) => PromoteToLong((string)b).CompareTo(a));
                comparableComparators.Add(new TypePair(typeof(string), typeof(bool)), (IComparable a, IComparable b) => PromoteToBool((string)b).CompareTo(a));

                comparableComparators.Add(new TypePair(typeof(int), typeof(float)), (IComparable a, IComparable b) => ((float)(int)a).CompareTo(b));
                comparableComparators.Add(new TypePair(typeof(long), typeof(float)), (IComparable a, IComparable b) => ((float)(long)a).CompareTo(b));
                comparableComparators.Add(new TypePair(typeof(bool), typeof(float)), (IComparable a, IComparable b) => ((bool)a).CompareTo(((float)b) != 0.0f));

                comparableComparators.Add(new TypePair(typeof(int), typeof(long)), (IComparable a, IComparable b) => ((long)(int)a).CompareTo(b));
                comparableComparators.Add(new TypePair(typeof(int), typeof(bool)), (IComparable a, IComparable b) => (((int)a) != 0).CompareTo(b));

                comparableComparators.Add(new TypePair(typeof(long), typeof(int)), (IComparable a, IComparable b) => a.CompareTo((long)(int)b));
                comparableComparators.Add(new TypePair(typeof(long), typeof(bool)), (IComparable a, IComparable b) => (((long)a) != 0).CompareTo(b));

                comparableComparators.Add(new TypePair(typeof(bool), typeof(int)), (IComparable a, IComparable b) => a.CompareTo((int)b != 0));
                comparableComparators.Add(new TypePair(typeof(bool), typeof(long)), (IComparable a, IComparable b) => a.CompareTo((long)b != 0));
            }
            ComparableComparator o;

            if (comparableComparators.TryGetValue(new TypePair(ta, tb), out o))
            {
                return(o);
            }
            return(comparableComparatorIdentity);
        }
Exemplo n.º 24
0
    //Displays Course history, Course Selections and Guidance Messages
    protected void DisplayCourseData(DataTable dtbPlannerData, DataTable dtbSubmitMessages)
    {
        string sRowStyle = "";
        Int16 iMsgCounter = 0;
        Int16 iMsgCreditRecovery = 0;
        //Hashtable htbMessages = new Hashtable();
        System.Collections.Generic.SortedDictionary<int, string> htbMessages = new System.Collections.Generic.SortedDictionary<int, string>();

        iMsgCounter = 0;  //Re-initialize

        foreach (DataRow drRow in dtbPlannerData.Rows)
        {
            sRowStyle = (sRowStyle == "") ? "class='DarkRow'" : "";

            //History Courses
            if (drRow["CType"].ToString() == "Taken" && intShowHistoryOnSignOff == 1)
            {
                sbrHistory.Append("<tr " + sRowStyle + ">");
                sbrHistory.Append("<td>" + drRow["CourseCode"].ToString() + "</td>");
                sbrHistory.Append("<td>" + drRow["CourseName"].ToString() + "&nbsp;</td>");
                sbrHistory.Append("<td align='center'>" + (drRow["GradeMark"] != DBNull.Value ? drRow["GradeMark"].ToString() : "-") + "</td>");
                sbrHistory.Append("<td>" + ((DateTime)drRow["CourseCompletedDate"]).ToString("MM/yy") + "</td></tr>");
            }

            //Current year's Course Selection
            if (drRow["CType"].ToString() == "Planned" && Convert.ToInt32(drRow["GradeColumn"]) == Convert.ToInt32(CPStudentInfo["GradeNumber"]) + 1)
            {
                sbrSelection.Append("<tr " + sRowStyle + ">");
                sbrSelection.Append("<td><b>" + drRow["CourseCode"].ToString() + "</b></td>");
                sbrSelection.Append("<td>" + drRow["CourseName"].ToString() + "</td>");
                if (drRow["AlertType"] != DBNull.Value || drRow["CourseExportType"].ToString()=="3")
                {
                    iMsgCounter += 1;
                    htbMessages.Add(iMsgCounter, drRow["ID"].ToString());
                    sbrSelection.Append("<td align='center'><b>" + iMsgCounter.ToString() + "</b></td>");
                    if (drRow["CourseExportType"].ToString() == "3")
                        iMsgCreditRecovery = iMsgCounter;
                }
                else
                { sbrSelection.Append("<td>&nbsp;</td>"); }

                if (drRow["AlternateId"] != DBNull.Value)
                { sbrSelection.Append("<td>" + drRow["AlternateCode"].ToString() + " - " + drRow["AlternateName"].ToString() + "</td>"); }
                else if (Convert.ToInt16(drRow["CourseExportType"]) == 2)
                    sbrSelection.Append("<td><b>X</b></td>");
                else
                { sbrSelection.Append("<td>&nbsp;</td>"); }
            }
        }

        //Load Alerts for courses
        IDictionaryEnumerator enumerator = htbMessages.GetEnumerator();
        while(enumerator.MoveNext())
        {
            foreach (DataRow drRow in dtbSubmitMessages.Rows)
            {
                if (drRow["ID"] != DBNull.Value)
                {
                    if (enumerator.Value.ToString() == drRow["ID"].ToString())
                    {
                        sbrMessages.Append("<tr " + sRowStyle + "><td valign='top' style='font-weight: bold; font-size: 12px;'>" + enumerator.Key.ToString() + "</td><td>" + drRow["MessageText"].ToString() + "</td></tr>");
                    }
                }
            }
        }

        #region Credit Recovery Message
        /*strSQL = "DECLARE @strTemp VARCHAR(2000);SET @strTemp = dbo.CP_GetWarningFromType(" + strSchoolID + ",154,'" + strUserLang.ToString() + "');SELECT @strTemp";
        string strCreditRecoveryMsg = CareerCruisingWeb.CCLib.Common.DataAccess.GetValue(strSQL).ToString();

        DataView dvCreditRecovery = dtbPlannerData.DefaultView;
        dvCreditRecovery.RowFilter = "CourseExportType=3";
        DataTable dt = dvCreditRecovery.ToTable();
        foreach (DataRow drRow in dt.Rows)
        {
            sbrMessages.Append("<tr " + sRowStyle + "><td valign='top' style='font-weight: bold; font-size: 12px;'>" + iMsgCreditRecovery.ToString() + "</td><td>" + strCreditRecoveryMsg + "</td></tr>");
        }*/
        #endregion

        //Load generic alerts not assigned to any course
        foreach (DataRow drRow in dtbSubmitMessages.Rows)
        {
            sRowStyle = (sRowStyle == "") ? "class='DarkRow'" : "";

            if (drRow["ID"] == DBNull.Value )
            {
                iMsgCounter += 1;
                sbrMessages.Append("<tr " + sRowStyle + "><td valign='top' style='font-weight: bold; font-size: 12px;'>" + iMsgCounter.ToString() + "</td><td>" + drRow["MessageText"].ToString() + " " + Strings.GenerateLanguageText(Convert.ToInt32(drRow["CourseCode"]),strLanguage, "0") + "</td></tr>");
            }
        }
    }
        private void CreateControlsSound(Vector2 controlsOrigin)
        {
            AddSeparator(controlsOrigin);

            Controls.Add(new MyGuiControlLabel(this, controlsOrigin + m_controlsAdded * CONTROLS_DELTA + new Vector2(0.05f, 0), null, MyTextsWrapperEnum.SoundInfluenceSphereType, MyGuiConstants.LABEL_TEXT_COLOR, MyGuiConstants.LABEL_TEXT_SCALE, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER));

            m_controlsAdded++;
            
            m_selectDialogueCombobox = new MyGuiControlCombobox(this,
                                                             controlsOrigin + m_controlsAdded++ * CONTROLS_DELTA +
                                                             new Vector2(MyGuiConstants.COMBOBOX_LONGMEDIUM_SIZE.X / 2.0f, 0),
                                                             MyGuiControlPreDefinedSize.LONGMEDIUM,
                                                             MyGuiConstants.COMBOBOX_BACKGROUND_COLOR,
                                                             MyGuiConstants.COMBOBOX_TEXT_SCALE, 6, false, false, false);

            System.Collections.Generic.SortedDictionary<string, int> dialogues = new System.Collections.Generic.SortedDictionary<string, int>();

            foreach (MyDialogueEnum dialogue in Enum.GetValues(typeof(MyDialogueEnum)))
            {
                dialogues.Add(dialogue.ToString(), (int)dialogue);
            }

            foreach (var dialogue in dialogues)
            {
                m_selectDialogueCombobox.AddItem(dialogue.Value, null, new StringBuilder(dialogue.Key));
            }

            m_selectDialogueCombobox.SelectItemByIndex(0);

            Controls.Add(m_selectDialogueCombobox);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Resolves a schema-complete address for a usable host.
        /// </summary>
        /// <exception cref="URLError">
        /// Thrown if resolution fails.
        /// </exception>
        public string GetHost()
        {
            if(this.srv){
                System.Collections.Generic.IDictionary<uint, System.Collections.Generic.IList<Heijden.DNS.RecordSRV>> candidates = new System.Collections.Generic.SortedDictionary<uint, System.Collections.Generic.IList<Heijden.DNS.RecordSRV>>();
                try{
                    foreach(Heijden.DNS.AnswerRR response in new Heijden.DNS.Resolver().Query(this.host, Heijden.DNS.QType.SRV).Answers){
                        Heijden.DNS.RecordSRV record = (Heijden.DNS.RecordSRV)response.RECORD;
                        System.Collections.Generic.IList<Heijden.DNS.RecordSRV> container;
                        if(candidates.ContainsKey(record.PRIORITY)){
                         	container = candidates[record.PRIORITY];
                        }else{
                            container = new System.Collections.Generic.List<Heijden.DNS.RecordSRV>();
                            candidates.Add(record.PRIORITY, container);
                        }
                        container.Add(record);
                    }
                }catch(System.Exception e){
                    throw new MediaStorage.Exceptions.URLError("Unable to resolve SRV record: " + e.Message);
                }

                foreach(System.Collections.Generic.KeyValuePair<uint, System.Collections.Generic.IList<Heijden.DNS.RecordSRV>> c in candidates){
                    while(c.Value.Count > 0){
                        uint weight_total = 0;
                        foreach(Heijden.DNS.RecordSRV option in c.Value){
                            weight_total += option.WEIGHT;
                        }
                        uint selection = (uint)((new System.Random()).NextDouble() * weight_total);
                        Heijden.DNS.RecordSRV choice = null;
                        foreach(Heijden.DNS.RecordSRV option in c.Value){
                            selection -= option.WEIGHT;
                            if(selection <= 0){
                                choice = option;
                                break;
                            }
                        }

                        if(choice == null){ //Should never happen, but C# is a mystery I don't care to understand.
                            break;
                        }

                        string address = this.Assemble(choice.TARGET, choice.PORT, this.ssl);
                        try{
                            System.Net.HttpWebRequest request = Libraries.Communication.AssembleRequest(address + Libraries.Communication.SERVER_PING, new System.Collections.Generic.Dictionary<string, object>());
                            Libraries.Communication.SendRequest(request, timeout:1).ToDictionary();
                            return address;
                        }catch(System.Exception){
                            c.Value.Remove(choice);
                        }
                    }
                }
                throw new MediaStorage.Exceptions.URLError("Unable to resolve a viable server via SRV lookup");
            }else{
                return this.Assemble(this.host, this.port, this.ssl);
            }
        }
Exemplo n.º 27
0
        private void HandleEvents()
        {
            lock (pendingActions)
            {
                while (pendingActions.Count > 0)
                {
                    var action = pendingActions.Dequeue();
                    if (action.type == ActionData.Type.Added)
                    {
                        GameObject qrCodeObject = Instantiate(qrCodePrefab, new Vector3(0, 0, 0), Quaternion.identity);
                        qrCodeObject.GetComponent <SpatialGraphNodeTracker>().Id = action.qrCode.SpatialGraphNodeId;
                        qrCodeObject.GetComponent <QRCode>().qrCode = action.qrCode;
                        qrCodesObjectsList.Add(action.qrCode.Id, qrCodeObject);

                        //AROA EDIT - Assign object to QRCode script
                        Debug.Log("Action.qrCode.Data = " + action.qrCode.Data);
                        qrCodeObject.GetComponent <QRCode>().textToSpeech    = textToSpeech;
                        qrCodeObject.GetComponent <QRCode>().obstacleManager = obstacleManager;

                        if (action.qrCode.Data == "QR Code 1")
                        {
                            layout = "Layout 1";
                        }

                        else if (action.qrCode.Data == "QR Code 2")
                        {
                            layout = "Layout 2";
                        }

                        else if (action.qrCode.Data == "QR Code 3")
                        {
                            layout = "Layout 3";
                        }

                        else if (action.qrCode.Data == "QR Code 4")
                        {
                            layout = "Layout 4";
                        }

                        else if (action.qrCode.Data == "QR Code 5")
                        {
                            layout = "Layout 5";
                        }

                        else if (action.qrCode.Data == "QR Code 6")
                        {
                            layout = "Layout 6";
                        }

                        else if (action.qrCode.Data == "QR Code 7")
                        {
                            layout = "Layout 7";
                        }

                        else if (action.qrCode.Data == "QR Code 8")
                        {
                            layout = "Layout 8";
                        }

                        else if (action.qrCode.Data == "Demo")
                        {
                            layout = "Demo Layout";
                        }

                        else
                        {
                            layout = "Unrecognized Layout";
                        }

                        experimentLogger.layout = layout;
                        qrCodeObject.GetComponent <QRCode>().layout           = layout;
                        qrCodeObject.GetComponent <QRCode>().trackedObject    = obstacleCollection;
                        qrCodeObject.GetComponent <QRCode>().experimentLogger = experimentLogger;

                        //Assign obstacles to QR Code object
                        qrCodeObject.GetComponent <QRCode>().obstLow1  = obstLow1;
                        qrCodeObject.GetComponent <QRCode>().obstLow2  = obstLow2;
                        qrCodeObject.GetComponent <QRCode>().obstHigh1 = obstHigh1;
                        qrCodeObject.GetComponent <QRCode>().obstHigh2 = obstHigh2;
                        qrCodeObject.GetComponent <QRCode>().obstWide1 = obstWide1;
                        qrCodeObject.GetComponent <QRCode>().obstWide2 = obstWide2;
                    }
                    else if (action.type == ActionData.Type.Updated)
                    {
                        if (!qrCodesObjectsList.ContainsKey(action.qrCode.Id))
                        {
                            GameObject qrCodeObject = Instantiate(qrCodePrefab, new Vector3(0, 0, 0), Quaternion.identity);
                            qrCodeObject.GetComponent <SpatialGraphNodeTracker>().Id = action.qrCode.SpatialGraphNodeId;
                            qrCodeObject.GetComponent <QRCode>().qrCode = action.qrCode;
                            qrCodesObjectsList.Add(action.qrCode.Id, qrCodeObject);

                            //AROA EDIT
                            //QR codes created using https://www.qr-code-generator.com/
                            Debug.Log("Action.qrCode.Data = " + action.qrCode.Data);
                            qrCodeObject.GetComponent <QRCode>().textToSpeech    = textToSpeech;
                            qrCodeObject.GetComponent <QRCode>().obstacleManager = obstacleManager;


                            if (action.qrCode.Data == "QR Code 1")
                            {
                                layout = "Layout 1";
                            }

                            else if (action.qrCode.Data == "QR Code 2")
                            {
                                layout = "Layout 2";
                            }

                            else if (action.qrCode.Data == "QR Code 3")
                            {
                                layout = "Layout 3";
                            }

                            else if (action.qrCode.Data == "QR Code 4")
                            {
                                layout = "Layout 4";
                            }

                            else if (action.qrCode.Data == "QR Code 5")
                            {
                                layout = "Layout 5";
                            }

                            else if (action.qrCode.Data == "QR Code 6")
                            {
                                layout = "Layout 6";
                            }

                            else if (action.qrCode.Data == "QR Code 7")
                            {
                                layout = "Layout 7";
                            }

                            else if (action.qrCode.Data == "QR Code 8")
                            {
                                layout = "Layout 8";
                            }

                            else if (action.qrCode.Data == "Demo")
                            {
                                layout = "Demo Layout";
                            }

                            else
                            {
                                layout = "Unrecognized Layout";
                            }

                            qrCodeObject.GetComponent <QRCode>().layout           = layout;
                            qrCodeObject.GetComponent <QRCode>().trackedObject    = obstacleCollection;
                            qrCodeObject.GetComponent <QRCode>().experimentLogger = experimentLogger;

                            //Assign obstacles to QR Code object
                            qrCodeObject.GetComponent <QRCode>().obstLow1  = obstLow1;
                            qrCodeObject.GetComponent <QRCode>().obstLow2  = obstLow2;
                            qrCodeObject.GetComponent <QRCode>().obstHigh1 = obstHigh1;
                            qrCodeObject.GetComponent <QRCode>().obstHigh2 = obstHigh2;
                            qrCodeObject.GetComponent <QRCode>().obstWide1 = obstWide1;
                            qrCodeObject.GetComponent <QRCode>().obstWide2 = obstWide2;
                        }
                    }
                    else if (action.type == ActionData.Type.Removed)
                    {
                        if (qrCodesObjectsList.ContainsKey(action.qrCode.Id))
                        {
                            Destroy(qrCodesObjectsList[action.qrCode.Id]);
                            qrCodesObjectsList.Remove(action.qrCode.Id);
                        }
                    }
                }
            }
            if (clearExisting)
            {
                clearExisting = false;
                foreach (var obj in qrCodesObjectsList)
                {
                    Destroy(obj.Value);
                }
                qrCodesObjectsList.Clear();
            }
        }