Esempio n. 1
0
        private bool CanPerformProfilingAction(object sender)
        {
            if (GlobalSettings.DebugMode == false)
            {
                return(false);
            }

            //will not run in medium trust
            if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High)
            {
                return(false);
            }

            var request = TryGetRequest(sender);

            if (request.Success == false || request.Result.Url.IsClientSideRequest())
            {
                return(false);
            }

            if (string.IsNullOrEmpty(request.Result.QueryString["umbDebug"]))
            {
                return(true);
            }

            if (request.Result.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath))
            {
                return(true);
            }

            return(true);
        }
Esempio n. 2
0
        private void DisplayLanguageGuide(object sender, EventArgs e)
        {
            string executableFolderPath = Path.GetDirectoryName(SWF.Application.ExecutablePath);
            string languageGuidePath    = Path.Combine(executableFolderPath, "Documentation", "langguide.html");

            try
            {
                if (File.Exists(languageGuidePath))
                {
                    Process.Start(languageGuidePath);
                }
                else
                {
                    ShowError(
                        "The language guide could not be found."
                        + Environment.NewLine + Environment.NewLine
                        + "(langguide.html should be placed in the Documentation sub-folder of the folder where Magneto.exe is placed)");
                }
            }
            catch (Exception exception)
            {
                if (SystemUtilities.IsCritical(exception))
                {
                    throw;
                }
                else
                {
                    ShowError(exception);
                }
            }
        }
        void LoadModules()
        {
            string moduleFolderPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Modules");

            if (Directory.Exists(moduleFolderPath))
            {
                foreach (string moduleFile in Directory.EnumerateFiles(moduleFolderPath, "*.MagnetoModule.dll"))
                {
                    try
                    {
                        ModuleManager.Register(Assembly.LoadFile(moduleFile));
                    }
                    catch (Exception exception)
                    {
                        if (!SystemUtilities.IsCritical(exception))
                        {
                            TMessageDialog.ShowError(null
                                                     , "Could not load module " + Path.GetFileName(moduleFile) + ":"
                                                     + Environment.NewLine + exception.Message);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
        }
        private Waypoint setupNewWaypoint(Vessel v)
        {
            if (!useWaypoints)
            {
                return(null);
            }

            waypointsOn = true;

            Waypoint wp = new Waypoint();

            wp.celestialName     = TargetBody.GetName();
            wp.latitude          = 0;
            wp.longitude         = 0;
            wp.altitude          = 0;
            wp.index             = 0;
            wp.id                = "dmVessel";
            wp.iconSize          = 32;
            wp.blocksInput       = false;
            wp.seed              = SystemUtilities.SuperSeed(this.Root);
            wp.isOnSurface       = false;
            wp.isNavigatable     = false;
            wp.enableMarker      = false;
            wp.enableTooltip     = false;
            wp.landLocked        = false;
            wp.name              = v.vesselName;
            wp.contractReference = this.Root;

            WaypointManager.AddWaypoint(wp);

            return(wp);
        }
Esempio n. 5
0
        public override IMessages Run()
        {
            Messages messages = new Messages();

            string fileName = Path.Combine(Directory.GetCurrentDirectory(), this.AssemblyPath);

            if (!File.Exists(fileName))
            {
                messages.AddWarning(string.Format("The tester assembly {0} doesn't exist.", fileName));
                return(messages);
            }

            try
            {
                var nunitConsolePath = Path.Combine(RegistryUtilities.ReadDefaultValue(@"HKEY_CURRENT_USER\SOFTWARE\nunit.org\NUnit\2.5.7", "InstallDir"), @"bin\net-2.0\nunit-console.exe");

                if (!File.Exists(nunitConsolePath))
                {
                    messages.AddWarning(string.Format("The nunit console path {0} doesn't exist.", nunitConsolePath));
                    return(messages);
                }

                SystemUtilities.StartProcess(nunitConsolePath, string.Format("{0} /xml:{1}", fileName, this.OutputPath, this.HideWindow), 1000);

                messages = this.ReadMessages(this.OutputPath);
            }
            catch (Exception e)
            {
                messages.AddException(e);
            }

            return(messages);
        }
Esempio n. 6
0
        private static void StartRunProcess(string executableFilePath, Action <bool> runStateCallback)
        {
            string tempFolderPath = Path.GetDirectoryName(executableFilePath);

            try
            {
                runningProcess = new Process();
                runningProcess.EnableRaisingEvents = true;
                runningProcess.Exited += delegate
                {
                    runningProcess.Dispose();
                    runningProcess = null;
                    CleanupAfterRun(tempFolderPath, runStateCallback);
                };
                runningProcess.StartInfo = new ProcessStartInfo(executableFilePath);
                runningProcess.StartInfo.UseShellExecute  = false;
                runningProcess.StartInfo.WorkingDirectory = tempFolderPath;
                runningProcess.Start();
            }
            catch (Exception ex)
            {
                if (SystemUtilities.IsCritical(ex))
                {
                    throw;
                }
                CleanupAfterRun(tempFolderPath, runStateCallback);
            }
        }
Esempio n. 7
0
 protected void Application_End(object sender, EventArgs e)
 {
     if (SystemUtilities.GetCurrentTrustLevel() == AspNetHostingPermissionLevel.Unrestricted)
     {
         LogHelper.Info <UmbracoApplication>("Application shutdown. Reason: " + HostingEnvironment.ShutdownReason);
     }
     OnApplicationEnd(sender, e);
 }
 // this exists only for legacy reasons - we should just pass the server identity un-hashed
 public static string GetCurrentServerHash()
 {
     if (SystemUtilities.GetCurrentTrustLevel() != System.Web.AspNetHostingPermissionLevel.Unrestricted)
     {
         throw new NotSupportedException("FullTrust ASP.NET permission level is required.");
     }
     return(GetServerHash(NetworkHelper.MachineName, System.Web.HttpRuntime.AppDomainAppId));
 }
Esempio n. 9
0
        public override IMessages Run()
        {
            string parameters = string.Format(" -e:{0} -u:{1} -p:{2} -i:{3} -d:{4} ", this.Enviroment, this.Username, this.Password, this.IafPath, this.DmlPath);

            SystemUtilities.StartProcess("Tools.DmlRunner.exe", parameters, 1000);

            return(this.ReadMessages("Tools.DmlRunnerLog.xml"));
        }
Esempio n. 10
0
 public void Copy()
 {
     if (this.SelectionLength == 0)
     {
         return;
     }
     SystemUtilities.CopyStringToClipboard(this.SelectedText);
 }
Esempio n. 11
0
        private void CommandExecuted_CopyHtml(object sender, ExecutedRoutedEventArgs e)
        {
            if (this.SelectionLength == 0)
            {
                return;
            }
            string textToCopy = this.MarkdownProcessor.ConvertMarkdownToHTML(this.SelectedText);

            SystemUtilities.CopyStringToClipboard(textToCopy);
        }
 private void LayoutControl()
 {
     labelName.Text = RecentUsage.GetName(ID);
     if (!SystemUtilities.OSIsWindowsSeven())
     {
         linkLabelStart.Font   = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
         linkLabelStop.Font    = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
         linkLabelRestart.Font = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
         labelName.Font        = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
     }
 }
Esempio n. 13
0
        public override IMessages Run()
        {
            Messages messages = new Messages();

            if (!File.Exists(this.FileName))
            {
                messages.AddWarning(string.Format("File {0} does not exists", this.FileName));
                return(messages);
            }

            return(SystemUtilities.ExecuteShellCommand(this.FileName));
        }
Esempio n. 14
0
 public void Cut()
 {
     if (this.SelectionLength == 0)
     {
         return;
     }
     if (!SystemUtilities.CopyStringToClipboard(this.SelectedText))
     {
         return;
     }
     this.SelectedText = string.Empty;
 }
Esempio n. 15
0
 private static void TryDeleteFolder(string folderPath)
 {
     try
     {
         Directory.Delete(folderPath, true);
     }
     catch (Exception ex)
     {
         if (SystemUtilities.IsCritical(ex))
         {
             throw;
         }
     }
 }
Esempio n. 16
0
        private static void Main(string[] args)
        {
            //fixes wrong screensize for screen share
            if (Environment.OSVersion.Version.Major >= 6)
            {
                SetProcessDPIAware();
            }

            if (!Directory.Exists(AppEnvironment.DataPath))
            {
                Directory.CreateDirectory(AppEnvironment.DataPath);
            }

            if (!Debugger.IsAttached)
            {
                ExceptionHandler.AddGlobalHandlers();
            }


            Console.WriteLine("Exception Handlers attached");


            Settings.Initialize("Config.json");

            Console.Title = Resources.Program_Title;
            Tools.ConfigureServer();
            var useTerminal  = Convert.ToBoolean(Settings.Get("Terminal").AllowTerminal);
            var usePlugins   = Convert.ToBoolean(Settings.Get("Plugins").LoadPlugins);
            var useWebServer = Convert.ToBoolean(Settings.Get("WebServer").UseWebServer);

            WebCamManager.LoadWebcams();
            if (usePlugins)
            {
                PluginHandler.LoadPlugins();
            }
            if (useWebServer)
            {
                HttpServer.Setup();
            }
            var systemUtilities = new SystemUtilities();

            systemUtilities.Start();
            //Keep down here if you actually want a functional program
            TaskManagerServer.Start();
            if (useTerminal)
            {
                TerminalManagerServer.Start();
            }
            Console.ReadLine();
        }
Esempio n. 17
0
File: Poof.cs Progetto: suma-ksp/MKS
        public static void GoPoof(Vessel vessel)
        {
            var startingReputation = 0f;
            var startingFunds      = 0d;

            if (Reputation.Instance != null)
            {
                startingReputation = Reputation.Instance.reputation;
            }

            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                startingFunds = Funding.Instance.Funds;
            }

            foreach (var kerbal in vessel.GetVesselCrew().ToArray())
            {
                //We should let them die before disappearing, this will trigger some game-events, just to make sure everything is cleaned up and every other part and mod of the game is notified about the disappearance (LifeSupport-Scenarios etc)
                kerbal.Die();

                //Completely erase the kerbal from current game (Does not exist anymore in save)
                //https://kerbalspaceprogram.com/api/class_fine_print_1_1_utilities_1_1_system_utilities.html#afd1eea0118d0c37dacd3ea696b125ff2
                SystemUtilities.ExpungeKerbal(kerbal);
            }
            foreach (var part in vessel.parts.ToArray())
            {
                part.Die();
            }

            vessel.Die();

            if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
            {
                var endingFunds = Funding.Instance.Funds;
                if (endingFunds + 0.0001f < startingFunds)
                {
                    Funding.Instance.AddFunds(startingFunds - endingFunds, TransactionReasons.None);
                }
            }

            if (Reputation.Instance != null)
            {
                var endingReputation = Reputation.Instance.reputation;
                if (endingReputation + 0.0001f < startingReputation)
                {
                    Reputation.Instance.AddReputation(startingReputation - endingReputation, TransactionReasons.None);
                }
            }
        }
Esempio n. 18
0
        public CutterPanel()
        {
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            Thread.CurrentThread.CurrentCulture = customCulture;
            SystemUtilities.PreventSleepMode();

            InitializeComponent();
            MessageBox.Visibility = Visibility.Hidden;

            _motionCommands.Add(Calibration);
            _motionCommands.Add(GoToZeros);
            _motionCommands.Add(AlignHeads);
            _motionCommands.Add(StartPlan);
            _motionCommands.Add(CuttingDeltaT);

            Cnc = new DriverCNC2();
            Cnc.OnConnectionStatusChange += () => Dispatcher.Invoke(refreshConnectionStatus);
            Cnc.OnHomeCalibrated         += () => Dispatcher.Invoke(enableMotionCommands);

            Cnc.Initialize();

            CoordController = new Coord2DController(Cnc);

            _messageTimer.Interval  = TimeSpan.FromMilliseconds(_messageShowDelay);
            _messageTimer.IsEnabled = false;
            _messageTimer.Tick     += _messageTimer_Tick;
            _statusTimer.Interval   = TimeSpan.FromMilliseconds(20);
            _statusTimer.Tick      += _statusTimer_Tick;
            _statusTimer.IsEnabled  = true;
            _autosaveTime.IsEnabled = false;
            _autosaveTime.Interval  = TimeSpan.FromMilliseconds(1000);
            _autosaveTime.Tick     += _autosaveTime_Tick;

            KeyUp      += keyUp;
            KeyDown    += keyDown;
            ContextMenu = createWorkspaceMenu();

            resetWorkspace(true);

            initializeTransitionHandlers();

            _factory = new ShapeFactory(this);

            /*/
             * OpenEditor_Click(null, null);
             * this.Hide();
             * /**/
        }
Esempio n. 19
0
 void ClearTempFolder()
 {
     if (Directory.Exists(TempFolderPath))
     {
         foreach (string tempSubFolderPath in Directory.EnumerateDirectories(TempFolderPath))
         {
             try { Directory.Delete(tempSubFolderPath, true); }
             catch (Exception exception) { if (SystemUtilities.IsCritical(exception))
                                           {
                                               throw;
                                           }
             }
         }
     }
 }
Esempio n. 20
0
        public RouterPanel()
        {
            Configuration.EnableRouterMode();
            System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(this);
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            Thread.CurrentThread.CurrentCulture = customCulture;
            SystemUtilities.PreventSleepMode();


            InitializeComponent();
            MessageBox.Visibility = Visibility.Hidden;

            _motionCommands.Add(Calibration);
            _motionCommands.Add(GoToZerosXY);
            _motionCommands.Add(StartPlan);
            _motionCommands.Add(SetZLevel);

            Cnc = new DriverCNC2();
            Cnc.OnConnectionStatusChange += () => Dispatcher.Invoke(refreshConnectionStatus);
            Cnc.OnHomeCalibrated         += () => Dispatcher.Invoke(enableMotionCommands);

            Cnc.Initialize();

            CoordController = new CoordController(Cnc);

            _messageTimer.Interval  = TimeSpan.FromMilliseconds(_messageShowDelay);
            _messageTimer.IsEnabled = false;
            _messageTimer.Tick     += _messageTimer_Tick;
            _statusTimer.Interval   = TimeSpan.FromMilliseconds(20);
            _statusTimer.Tick      += _statusTimer_Tick;
            _statusTimer.IsEnabled  = true;
            _autosaveTime.IsEnabled = false;
            _autosaveTime.Interval  = TimeSpan.FromMilliseconds(1000);
            _autosaveTime.Tick     += _autosaveTime_Tick;

            PreviewKeyUp   += previewKeyUp;
            PreviewKeyDown += previewKeyDown;
            ContextMenu     = createWorkspaceMenu();

            resetWorkspace(true);

            initializeTransitionHandlers();

            _factory = new MillingShapeFactory(this);
        }
        private static void ConsoleMain(string[] args)
        {
            Console.WriteLine("Command line = {0}", Environment.CommandLine);
            for (var ix = 0; ix < args.Length; ++ix)
                Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
            WebCamManager.LoadWebcams();
            PluginManager.LoadPlugins();
            Tools.GenerateSettings();
            HttpServer.Setup();
            var systemUtilities = new SystemUtilities();
            systemUtilities.Start();

            //Keep down here if you actually want a functional program
            TaskManagerServer.Start();
            TerminalManagerServer.Start();
            Console.ReadLine();
        }
Esempio n. 22
0
        private void LayoutForm()
        {
            bool isWindowsSeven = SystemUtilities.OSIsWindowsSeven();

            ControlRecentApplicationRow row = null;

            foreach (RecentUsage recentUsage in RecentUsages.Take(Configuration.MAX_VISIBLE_RECENT_USAGE_COUNT).OrderBy(recent => (recent.ID == recent.Name)).ThenBy(recent => recent.Name))
            {
                row = new ControlRecentApplicationRow(imageList, recentUsage.ID)
                {
                    Width = flowLayoutPanel.Width
                };
                flowLayoutPanel.Controls.Add(row);
            }

            if (row != null)
            {
                MinimumSize = new Size(MinimumSize.Width, Math.Max(34 + 43 + (isWindowsSeven ? 0 : -16) + Math.Min(RecentUsages.Count, Configuration.MAX_VISIBLE_RECENT_USAGE_COUNT) * row.Height, 100));
            }
            else
            {
                labelNonAvailable.Visible = true;
            }

            linkLabelOpen.Enabled = (_openMainWindowAction != null);

            if (!isWindowsSeven)
            {
                FormBorderStyle                 = FormBorderStyle.FixedToolWindow;
                flowLayoutPanel.Height         += 8;
                panelBackground.BackgroundImage = null;
                panelBackground.Width          += 8;
                panelBackground.Height         -= 4;
                panelBackground.Location        = new Point(panelBackground.Location.X, panelBackground.Location.Y + 10);
                linkLabelOpen.Font              = new Font("Tahoma", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
                linkLabelOpen.Location          = new Point(linkLabelOpen.Location.X, linkLabelOpen.Location.Y + 4);
            }

            Location = new Point(Math.Min(MousePosition.X - Size.Width / 2, Screen.PrimaryScreen.WorkingArea.Width - Size.Width - 8),
                                 Screen.PrimaryScreen.WorkingArea.Height - Size.Height - (isWindowsSeven ? 8 : 0));

            Opacity = 100;
            Show();

            try { Program.SetForegroundWindow(Handle); } catch { }
        }
Esempio n. 23
0
        private ApplicationViewModel()
        {
            Logger.AddTrace("Configuring Application Model");

            this.Action            = ActionType.None;
            this.ActionInProgress  = false;
            this.ActionDescription = string.Empty;

            this.ApplicationName      = SystemUtilities.GetProductName(Assembly.GetEntryAssembly());
            this.ApplicationVersion   = SystemUtilities.GetVersionNumber(Assembly.GetEntryAssembly());
            this.ApplicationCopyright = SystemUtilities.GetProductCopyright(Assembly.GetEntryAssembly());

            this.AppIcon = SystemUtilities.GetApplicationIcon(Assembly.GetEntryAssembly());

            this.AppLibraries = SystemUtilities.GetApplicationLibraries(Assembly.GetEntryAssembly());

            this.UpdateApplicationDescription();
        }
Esempio n. 24
0
        /// <summary>
        /// Handle the Init event o fthe UmbracoApplication which allows us to subscribe to the HttpApplication events
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void UmbracoApplicationApplicationInit(object sender, EventArgs e)
        {
            var app = sender as HttpApplication;

            if (app == null)
            {
                return;
            }

            if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High)
            {
                //If we don't have a high enough trust level we cannot bind to the events
                LogHelper.Info <WebProfiler>("Cannot start the WebProfiler since the application is running in Medium trust");
            }
            else
            {
                app.BeginRequest += UmbracoApplicationBeginRequest;
                app.EndRequest   += UmbracoApplicationEndRequest;
            }
        }
Esempio n. 25
0
        private bool ShouldProfile(object sender)
        {
            if (GlobalSettings.DebugMode == false)
            {
                return(false);
            }

            //will not run in medium trust
            if (SystemUtilities.GetCurrentTrustLevel() < AspNetHostingPermissionLevel.High)
            {
                return(false);
            }

            var request = TryGetRequest(sender);

            if (request.Success == false || request.Result.Url.IsClientSideRequest())
            {
                return(false);
            }

            //if there is an umbDebug query string than profile it
            bool umbDebug;

            if (string.IsNullOrEmpty(request.Result.QueryString["umbDebug"]) == false && bool.TryParse(request.Result.QueryString["umbDebug"], out umbDebug))
            {
                return(true);
            }

            //if there is an umbDebug header than profile it
            if (string.IsNullOrEmpty(request.Result.Headers["X-UMB-DEBUG"]) == false && bool.TryParse(request.Result.Headers["X-UMB-DEBUG"], out umbDebug))
            {
                return(true);
            }

            //everything else is ok to profile
            return(false);
        }
Esempio n. 26
0
        public static void LineSlicing()
        {
            Configuration.EnableRouterMode();
            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator = ".";
            Thread.CurrentThread.CurrentCulture = customCulture;
            SystemUtilities.PreventSleepMode();

            var speed1Ticks    = 900;
            var speed2Ticks    = 10000;
            var timeGrainTicks = 3000;

            var lengthMm = 100;
            var v        = new Vector(
                ControllerCNC.Primitives.Speed.FromDeltaT(speed1Ticks).ToMetric(),
                ControllerCNC.Primitives.Speed.FromDeltaT(speed2Ticks).ToMetric()
                );


            var timeGrain = 1.0 * timeGrainTicks / Configuration.TimerFrequency;
            var speed     = v.Length;

            v = v * lengthMm;

            var segment = new ToolPathSegment(new Point3D(0, 0, 0), new Point3D(v.X, v.Y, 0), MotionMode.IsLinearRapid);
            var logger  = new StepLogger(".");


            var slicer = new ToolPathSegmentSlicer(segment);

            for (var i = 0; i < 15; ++i)
            {
                var instruction = slicer.Slice(speed, timeGrain);
                logger.LogInstruction(instruction);
            }
            logger.Flush();
        }
Esempio n. 27
0
        public static void Run(string sourceCode, Action <bool> runStateCallback, Action <Exception> exceptionHandler)
        {
            runStateCallback?.Invoke(true);

            string tempFolderPath = CreateTempFolder();

            CopyModules(tempFolderPath);

            try
            {
                string executableFilePath = Path.Combine(tempFolderPath, "Temp.exe");
                BuildAssembly(sourceCode, executableFilePath);
                StartRunProcess(executableFilePath, runStateCallback);
            }
            catch (Exception ex)
            {
                if (SystemUtilities.IsCritical(ex))
                {
                    throw;
                }
                exceptionHandler?.Invoke(ex);
                CleanupAfterRun(tempFolderPath, runStateCallback);
            }
        }
 public void GetEventLogs()
 {
     serializator.Serialize(client, packet.endpoint, packet.syncKey, SystemUtilities.GetEventLogs());
     System.GC.Collect();
 }
        protected void DrawWaypoint(WaypointData wpd)
        {
            // Not our planet
            CelestialBody celestialBody = FlightGlobals.currentMainBody;

            if (celestialBody == null || wpd.waypoint.celestialName != celestialBody.name)
            {
                return;
            }

            // Check if the waypoint should be visible
            if (!wpd.waypoint.visible)
            {
                return;
            }

            // Figure out waypoint label
            string label = wpd.waypoint.name + (wpd.waypoint.isClustered ? (" " + StringUtilities.IntegerToGreek(wpd.waypoint.index)) : "");

            // Set the alpha and do a nice fade
            wpd.SetAlpha();

            // Decide whether to actually draw the waypoint
            if (FlightGlobals.ActiveVessel != null)
            {
                // Figure out the distance to the waypoint
                Vessel v = FlightGlobals.ActiveVessel;

                // Only change alpha if the waypoint isn't the nav point
                if (!Util.IsNavPoint(wpd.waypoint))
                {
                    // Get the distance to the waypoint at the current speed
                    double speed      = v.srfSpeed < MIN_SPEED ? MIN_SPEED : v.srfSpeed;
                    double directTime = Util.GetStraightDistance(wpd) / speed;

                    // More than two minutes away
                    if (directTime > MIN_TIME || Config.waypointDisplay != Config.WaypointDisplay.ALL)
                    {
                        return;
                    }
                    else if (directTime >= MIN_TIME - FADE_TIME)
                    {
                        wpd.currentAlpha = (float)((MIN_TIME - directTime) / FADE_TIME) * Config.opacity;
                    }
                }
                // Draw the distance information to the nav point
                else
                {
                    // Draw the distance to waypoint text
                    if (Event.current.type == EventType.Repaint)
                    {
                        if (asb == null)
                        {
                            asb = UnityEngine.Object.FindObjectOfType <AltimeterSliderButtons>();
                        }

                        if (referenceUISize != ScreenSafeUI.VerticalRatio || !referenceSet)
                        {
                            referencePos    = ScreenSafeUI.referenceCam.ViewportToScreenPoint(asb.transform.position).y;
                            referenceUISize = ScreenSafeUI.VerticalRatio;

                            // Need two consistent numbers in a row to set the reference
                            if (lastPos == referencePos)
                            {
                                referenceSet = true;
                            }
                            else
                            {
                                lastPos = referencePos;
                            }
                        }

                        float ybase = (referencePos - ScreenSafeUI.referenceCam.ViewportToScreenPoint(asb.transform.position).y + Screen.height / 11.67f) / ScreenSafeUI.VerticalRatio;

                        string timeToWP = GetTimeToWaypoint(wpd);
                        if (Config.hudDistance)
                        {
                            GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 20f), "Distance to " + label + ":", nameStyle);
                            GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 20f),
                                      v.state != Vessel.State.DEAD ? Util.PrintDistance(wpd) : "N/A", valueStyle);
                            ybase += 18f;
                        }

                        if (timeToWP != null && Config.hudTime)
                        {
                            GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 20f), "ETA to " + label + ":", nameStyle);
                            GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 20f),
                                      v.state != Vessel.State.DEAD ? timeToWP : "N/A", valueStyle);
                            ybase += 18f;
                        }

                        if (Config.hudHeading)
                        {
                            GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 20f), "Heading to " + label + ":", nameStyle);
                            GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 20f),
                                      v.state != Vessel.State.DEAD ? wpd.heading.ToString("N1") : "N/A", valueStyle);
                            ybase += 18f;
                        }

                        if (Config.hudAngle && v.mainBody == wpd.celestialBody)
                        {
                            double distance   = Util.GetLateralDistance(wpd);
                            double heightDist = wpd.waypoint.altitude + wpd.waypoint.height - v.altitude;
                            double angle      = Math.Atan2(heightDist, distance) * 180.0 / Math.PI;

                            GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 20f), "Angle to " + label + ":", nameStyle);
                            GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 20f),
                                      v.state != Vessel.State.DEAD ? angle.ToString("N2") : "N/A", valueStyle);
                            ybase += 18f;

                            if (v.srfSpeed >= 0.1)
                            {
                                double velAngle = 90 - Math.Acos(Vector3d.Dot(v.srf_velocity.normalized, v.upAxis)) * 180.0 / Math.PI;

                                GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 20f), "Velocity pitch angle:", nameStyle);
                                GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 20f),
                                          v.state != Vessel.State.DEAD ? velAngle.ToString("N2") : "N/A", valueStyle);
                                ybase += 18f;
                            }
                        }
                        if (Config.hudCoordinates && v.mainBody == wpd.celestialBody)
                        {
                            ybase += 9;
                            GUI.Label(new Rect((float)Screen.width / 2.0f - 188f, ybase, 240f, 38f), "Coordinates of " + label + ":", nameStyle);
                            GUI.Label(new Rect((float)Screen.width / 2.0f + 60f, ybase, 120f, 38f),
                                      v.state != Vessel.State.DEAD ? string.Format("{0}\r\n{1}", Util.DecimalDegreesToDMS(wpd.waypoint.latitude, true), Util.DecimalDegreesToDMS(wpd.waypoint.longitude, false)) : "N/A", valueStyle);
                            ybase += 18f;
                        }
                    }
                }
            }

            // Don't draw the waypoint
            if (Config.waypointDisplay == Config.WaypointDisplay.NONE)
            {
                return;
            }

            // Translate to scaled space
            Vector3d localSpacePoint  = celestialBody.GetWorldSurfacePosition(wpd.waypoint.latitude, wpd.waypoint.longitude, wpd.waypoint.height + wpd.waypoint.altitude);
            Vector3d scaledSpacePoint = ScaledSpace.LocalToScaledSpace(localSpacePoint);

            // Don't draw if it's behind the camera
            if (Vector3d.Dot(MapView.MapCamera.camera.transform.forward, scaledSpacePoint.normalized) < 0.0)
            {
                return;
            }

            // Translate to screen position
            Vector3 screenPos = MapView.MapCamera.camera.WorldToScreenPoint(new Vector3((float)scaledSpacePoint.x, (float)scaledSpacePoint.y, (float)scaledSpacePoint.z));

            // Draw the marker at half-resolution (30 x 45) - that seems to match the one in the map view
            Rect markerRect = new Rect(screenPos.x - 15f, (float)Screen.height - screenPos.y - 45.0f, 30f, 45f);

            // Set the window position relative to the selected waypoint
            if (selectedWaypoint == wpd.waypoint)
            {
                windowPos = new Rect(markerRect.xMin - 97, markerRect.yMax + 12, 224, 60);
            }

            // Handling clicking on the waypoint
            if (Event.current.type == EventType.MouseUp && Event.current.button == 0)
            {
                if (markerRect.Contains(Event.current.mousePosition))
                {
                    selectedWaypoint = wpd.waypoint;
                    windowPos        = new Rect(markerRect.xMin - 97, markerRect.yMax + 12, 224, 60);
                    waypointName     = label;
                    newClick         = false;
                }
                else if (newClick)
                {
                    selectedWaypoint = null;
                }
            }

            // Only handle on repaint events
            if (Event.current.type == EventType.Repaint)
            {
                // Half-res for the icon too (16 x 16)
                Rect iconRect = new Rect(screenPos.x - 8f, (float)Screen.height - screenPos.y - 39.0f, 16f, 16f);

                // Draw the marker
                Graphics.DrawTexture(markerRect, GameDatabase.Instance.GetTexture("Squad/Contracts/Icons/marker", false), new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f * (wpd.currentAlpha - 0.3f) / 0.7f));

                // Draw the icon, but support blinking
                if (!Util.IsNavPoint(wpd.waypoint) || !FinePrint.WaypointManager.navWaypoint.blinking || (int)((Time.fixedTime - (int)Time.fixedTime) * 4) % 2 == 0)
                {
                    Graphics.DrawTexture(iconRect, ContractDefs.textures[wpd.waypoint.id], new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, SystemUtilities.RandomColor(wpd.waypoint.seed, wpd.currentAlpha));
                }

                // Hint text!
                if (iconRect.Contains(Event.current.mousePosition))
                {
                    // Add agency to label
                    if (wpd.waypoint.contractReference != null)
                    {
                        label += "\n" + wpd.waypoint.contractReference.Agent.Name;
                    }
                    float width   = 240f;
                    float height  = hintTextStyle.CalcHeight(new GUIContent(label), width);
                    float yoffset = height + 48.0f;
                    GUI.Box(new Rect(screenPos.x - width / 2.0f, (float)Screen.height - screenPos.y - yoffset, width, height), label, hintTextStyle);
                }
            }
        }
Esempio n. 30
0
        public static void DrawWaypoint(CelestialBody targetBody, double latitude, double longitude, double altitude, string id, int seed, float alpha = -1.0f)
        {
            // Translate to scaled space
            Vector3d localSpacePoint  = targetBody.GetWorldSurfacePosition(latitude, longitude, altitude);
            Vector3d scaledSpacePoint = ScaledSpace.LocalToScaledSpace(localSpacePoint);

            // Don't draw if it's behind the camera
            if (Vector3d.Dot(PlanetariumCamera.Camera.transform.forward, scaledSpacePoint.normalized) < 0.0)
            {
                return;
            }

            // Translate to screen position
            Vector3 screenPos = PlanetariumCamera.Camera.WorldToScreenPoint(new Vector3((float)scaledSpacePoint.x, (float)scaledSpacePoint.y, (float)scaledSpacePoint.z));

            // Draw the marker at half-resolution (30 x 45) - that seems to match the one in the map view
            Rect markerRect = new Rect(screenPos.x - 15f, (float)Screen.height - screenPos.y - 45.0f, 30f, 45f);

            // Half-res for the icon too (16 x 16)
            Rect iconRect = new Rect(screenPos.x - 8f, (float)Screen.height - screenPos.y - 39.0f, 16f, 16f);

            if (alpha < 0.0f)
            {
                Vector3 cameraPos    = ScaledSpace.ScaledToLocalSpace(PlanetariumCamera.Camera.transform.position);
                bool    occluded     = WaypointData.IsOccluded(targetBody, cameraPos, localSpacePoint, altitude);
                float   desiredAlpha = occluded ? 0.3f : 1.0f * Config.opacity;
                if (lastAlpha < 0.0f)
                {
                    lastAlpha = desiredAlpha;
                }
                else if (lastAlpha < desiredAlpha)
                {
                    lastAlpha = Mathf.Clamp(lastAlpha + Time.deltaTime * 4f, lastAlpha, desiredAlpha);
                }
                else
                {
                    lastAlpha = Mathf.Clamp(lastAlpha - Time.deltaTime * 4f, desiredAlpha, lastAlpha);
                }
                alpha = lastAlpha;
            }

            // Draw the marker
            Graphics.DrawTexture(markerRect, GameDatabase.Instance.GetTexture("Squad/Contracts/Icons/marker", false), new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f * (alpha - 0.3f) / 0.7f));

            // Draw the icon
            Graphics.DrawTexture(iconRect, ContractDefs.sprites[id].texture, new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, SystemUtilities.RandomColor(seed, alpha));
        }