//获取cpu信息
        public static CPUInfo get_CPUInfo()
        {
            CPUInfo memInfor = new CPUInfo();

            GetSystemInfo(ref memInfor);
            return(memInfor);
        }
Example #2
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            btnLogin.Enabled = false;
            btnLogin.Text    = "登录中...";

            string  user_name = txtLoginUserName.Text.Trim();
            string  pwd       = EncryptUtils.EncryptString(txtLoginPwd.Text.Trim());
            CPUInfo cpuInfo   = new CPUInfo();

            cpuInfo.GetCPUInfo();
            string   cpu    = cpuInfo.CPUName;
            string   osname = OSVersionInfo.SystemName;
            Computer cp     = Computer.Instance();
            string   mem    = cp.TotalPhysicalMemory;

            DianCheWebService.EntityUser user = ws.UserLogin(user_name, pwd, cpu, mem, osname);
            if (user != null)
            {
                this.Hide();
                FrmMain.CurrentUser = user;
                FrmMain frmMain = new FrmMain();
                frmMain.Show();
            }
            else
            {
                MessageBox.Show("登录失败,请检查用户名密码!");
                btnLogin.Enabled = true;
                btnLogin.Text    = "登录";
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            IHardwareInfoFactory      factory = HardwareInfo.GetFactory();
            ISystemInformationFactory systemInformationFactory = SysInfo.GetFactory();

            CPUInfo            cpuInfo = factory.GetCPUInfo();
            ISystemInformation sysInfo = systemInformationFactory.Information();

            Console.WriteLine("Operation system: " + sysInfo.Name);
            Console.WriteLine("ID:               " + sysInfo.ID);
            Console.WriteLine("Based on:         " + sysInfo.IDLike);
            Console.WriteLine("Platform:         " + sysInfo.Platform);
            Console.WriteLine("-------------------------------------");
            Console.WriteLine("CPU info");
            Console.WriteLine("    - name:               " + cpuInfo.ModelName);
            Console.WriteLine("    - vendor:             " + cpuInfo.Vendor);
            Console.WriteLine("    - vendor id:          " + cpuInfo.VendorID);
            Console.WriteLine("    - CPU(s):             " + cpuInfo.CPUCount);
            Console.WriteLine("    - Thread(s) per core: " + cpuInfo.ThreadsPerCore);
            Console.WriteLine("    - Core(s) per socket: " + cpuInfo.CoresPerSocket);
            // Console.WriteLine("    - identifier:   " + cpuInfo.Identifier);
            Console.WriteLine("    - MHz:                " + cpuInfo.MHz);
            Console.WriteLine("    - Cache");
            Console.WriteLine("        - level 1:  " + cpuInfo.CacheLevel1);
            Console.WriteLine("        - level 2:  " + cpuInfo.CacheLevel2);
            Console.WriteLine("        - level 3:  " + cpuInfo.CacheLevel3);
            Console.WriteLine("    - Flags: " + cpuInfo.Flags);
        }
Example #4
0
        public MonitorOutput GetSystemInfo()
        {
            MonitorOutput monitorOutput = new MonitorOutput()
            {
                CPUInfo  = CPUInfo.GetCPUInfo(),
                MemInfo  = MemoryInfo.GetMemInfo(),
                TCPCount = TCPInfo.GetTCPCount()
            };

            return(monitorOutput);
        }
Example #5
0
 public RedisInfo()
 {
     Replication = new ReplicationInfo();
     Clients = new ClientInfo();
     Server = new ServerInfo();
     Memory = new MemoryInfo();
     Persistence = new PersistenceInfo();
     Stats = new StatsInfo();
     CPU = new CPUInfo();
     Keyspace = new KeyspaceInfo();
 }
Example #6
0
 public RedisInfo()
 {
     Replication = new ReplicationInfo();
     Clients     = new ClientInfo();
     Server      = new ServerInfo();
     Memory      = new MemoryInfo();
     Persistence = new PersistenceInfo();
     Stats       = new StatsInfo();
     CPU         = new CPUInfo();
     Keyspace    = new KeyspaceInfo();
 }
Example #7
0
        public void GetMonitorInfo()
        {
            MonitorOutput monitorOutput = new MonitorOutput()
            {
                CPUInfo     = CPUInfo.GetCPUInfo(),
                MemInfo     = MemoryInfo.GetMemInfo(),
                TCPCount    = TCPInfo.GetTCPCount(),
                OnlineCount = OnlineInfo.GetOnlineCount()
            };

            Clients.All.getMonitorInfo(monitorOutput);
        }
Example #8
0
        private void OnMachineInfoRequest(INetworkConnection con, Packet packet)
        {
            bool cpu, gpu, drives, mainboard, os, ram;

            cpu = gpu = drives = mainboard = os = ram = false;

            PacketGenericMessage m = packet as PacketGenericMessage;

            m.ReplyPacket = CreateStandardReply(packet, ReplyType.OK, "");

            if (m.Parms.GetBoolProperty("cpu").GetValueOrDefault(false))
            {
                cpu = true;
                CPUInfo ci = MachineInfo.ReadCPUInfo();
                m.ReplyPacket.Parms.SetProperty("cpu", ci.ToString());
            }
            if (m.Parms.GetBoolProperty("gpu").GetValueOrDefault(false))
            {
                gpu = true;
                VideoCardInfo gi = MachineInfo.ReadGPUInfo();
                m.ReplyPacket.Parms.SetProperty("gpu", gi.ToString());
            }
            if (m.Parms.GetBoolProperty("drives").GetValueOrDefault(false))
            {
                drives = true;
                PatcherLib.DriveInfo di = MachineInfo.ReadLogicalDiskInfo();
                m.ReplyPacket.Parms.SetProperty("drives", di.ToString());
            }
            if (m.Parms.GetBoolProperty("mainboard").GetValueOrDefault(false))
            {
                mainboard = true;
                MotherboardInfo mi = MachineInfo.ReadMotherboardInfo();
                m.ReplyPacket.Parms.SetProperty("mainboard", mi.ToString());
            }
            if (m.Parms.GetBoolProperty("os").GetValueOrDefault(false))
            {
                os = true;
                OperatingSystemInfo osr = MachineInfo.ReadOperatingSystemInfo();
                m.ReplyPacket.Parms.SetProperty("os", osr.ToString());
            }
            if (m.Parms.GetBoolProperty("ram").GetValueOrDefault(false))
            {
                ram = true;
                RamInfo ri = MachineInfo.ReadRAMInfo();
                m.ReplyPacket.Parms.SetProperty("ram", ri.ToString());
            }

            if (MachineInfoRequestArrived != null)
            {
                MachineInfoRequestArrived(cpu, gpu, mainboard, drives, os, ram);
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            CPUInfo         cpu   = GetCPUInfo();
            List <DiskInfo> disks = GetDiskList();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write("Bilgisayar Ismi:" + MachineName);
            Console.Write("  IP:" + GetLocalIPAddress());
            Console.WriteLine("  Ag Adi:" + UserDomainName);

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("***CPU***");
            Console.WriteLine();
            Console.WriteLine("Marka: " + cpu.Manufacturer);
            Console.WriteLine("Model: " + cpu.ModelName);
            Console.WriteLine("MAX HIZ: " + cpu.MaxClockSpeed / (1000f) + " GHZ");

            Console.WriteLine();
            Console.WriteLine();


            Console.WriteLine("***Memory***");
            Console.WriteLine();
            Console.WriteLine("TOTAL RAM:" + GetTotalPhysicalMemory() + "MB");
            Console.WriteLine("Available RAM:" + GetAvailableMemory() + "MB");
            Console.WriteLine("IN-USE MEMO:" + GetMemoryInUse() + "MB");

            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("***DISK***");
            Console.WriteLine();

            foreach (var disk in disks)
            {
                Console.WriteLine(
                    "DISK:" + disk.Name
                    + " Toplam:" + disk.TotalSize + "GB"
                    + " Kullanilan:" + (disk.TotalSize - disk.AvailableFreeSpace) + "GB"
                    + " Kullanilabilir:" + disk.AvailableFreeSpace + "GB");
            }

            Console.WriteLine("----------------------------------------------------");

            Console.WriteLine();
            Console.WriteLine();
            Console.ReadKey();
        }
Example #10
0
        /// <summary>
        /// Gets Processor Information
        /// </summary>
        /// <returns>
        /// A <see cref="CPUInfo"/>
        /// </returns>
        public override CPUInfo GetCPUInfo()
        {
            CPUInfo ci = new CPUInfo();

            ci.Name   = "Unknown";
            ci.Speed  = 0;
            ci.Vendor = "Unknown";
            ci.UUID   = "Unknown";

            // TODO get CPU information

            return(ci);
        }
 public static int addCPU(CPUInfo cpu)
 {
     if (!existsNew)
     {
         newCPUs = new List <CPUInfo>();
     }
     cpu.id = numCPU;
     numCPU++;
     connectedCPUs.Add(cpu);
     newCPUs.Add(cpu);
     existsNew = true;
     return(numCPU);
 }
Example #12
0
 public static CPUInfo GetCPUInfo()
 {
     using (ManagementObject Mo = new ManagementObject("Win32_Processor.DeviceID='CPU0'"))
     {
         CPUInfo cc = new CPUInfo
         {
             ModelName         = Mo["Name"].ToString(),
             MaxClockSpeed     = (uint)Mo["MaxClockSpeed"],
             CurrentClockSpeed = (uint)Mo["CurrentClockSpeed"],
             Manufacturer      = Mo["Manufacturer"].ToString()
         };
         return(cc);
     }
 }
Example #13
0
        public FanManager()
        {
            Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
            InitializeComponent();
            new_set = Convert.ToInt32(Registry.GetValue(keyName, "FanMode", 1));

            static_fan   = Convert.ToUInt32(Registry.GetValue(keyName, "StaticFan", 0));
            this.CpuInfo = new CPUInfo();
            switch (new_set)
            {
            case 1:
                Setfan_Auto(0UL);
                Application.Exit();
                break;

            case 2:
                Setfan_Max(64UL);
                Application.Exit();
                break;

            case 4:
                Setfan_Static(static_fan);
                Application.Exit();
                break;

            case 3:
                Timer_Fan       = new DispatcherTimer();
                Timer_Fan.Tick += timer1_Tick;
                Timer_Fan.Start();
                Timer_Fan.Interval = new TimeSpan(0, 0, 0, 1, 500);
                break;

            case 5:
                for (int i = 0; i < 7; i++)
                {
                    array_fan[i]  = Convert.ToUInt32(Registry.GetValue(keyName + "\\FAN", "Fan_" + i.ToString(), -1));
                    array_temp[i] = Convert.ToInt32(Registry.GetValue(keyName + "\\FAN", "Temp_" + i.ToString(), -1));
                }
                if (array_temp[0] == -1)
                {
                    Setfan_Auto(0UL);
                    Application.Exit();
                }
                Timer1_Fan       = new DispatcherTimer();
                Timer1_Fan.Tick += timer1_fancustom_Tick;
                Timer1_Fan.Start();
                Timer1_Fan.Interval = new TimeSpan(0, 0, 0, 1, 500);
                break;
            }
        }
Example #14
0
        private static async void SendReportLoop()
        {
            while (true)
            {
                // собираем данные
                // диски
                List <DriveInfo> drives = DriveInfo.GetDrives().Where(d => d.IsReady).ToList();
                var totalDiskSpace      = drives.Sum(d => d.TotalSize / 1024 / 1024);
                var freeDiskSpace       = drives.Sum(d => d.AvailableFreeSpace / 1024 / 1024);
                var disksInfo           = new DisksInfo {
                    TotalMb = (int)totalDiskSpace, FreeMb = (int)freeDiskSpace
                };
                // ОЗУ
                var ramInfo = new RAMInfo();
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    ramInfo = GetUnixMetrics();
                }
                else
                {
                    ramInfo = GetWindowsMetrics();
                }
                // ЦП
                var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total", true);
                var value      = cpuCounter.NextValue();
                if (Math.Abs(value) <= 0.00)
                {
                    value = cpuCounter.NextValue();
                }
                var cpuInfo = new CPUInfo {
                    UsedPercent = (int)value
                };

                // подготавливаем данные
                var data = new SystemReportDto {
                    DisksInfo = disksInfo, RAMInfo = ramInfo, CPUInfo = cpuInfo
                };

                // отправляем данные на сервер
                Console.WriteLine($"{DateTime.Now}: отправка данных на сервер.");
                if (_HubConnection.State != HubConnectionState.Connected)
                {
                    await _HubConnection.StartAsync();
                }
                await _HubConnection.SendAsync("SendSystemReport", data);

                Thread.Sleep(_delaySeconds * 1000);
            }
        }
Example #15
0
        private MachineInfo GetMachineInformation()
        {
            MachineInfo result = new MachineInfo();
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor");



            foreach (var obj in searcher.Get())
            {
                CPUInfo info = new CPUInfo();
                info.Name        = (string)obj.GetPropertyValue("Name");
                info.ProcessorID = (string)obj.GetPropertyValue("ProcessorID");
                result.CPU.Add(info);
            }
            return(result);
        }
Example #16
0
        public override MonitorState GetCurrentState()
        {
            MonitorState currentState = new MonitorState()
            {
                ForAgent         = Description,
                State            = CollectorState.Good,
                CurrentValueUnit = "%"
            };

            try
            {
                Renci.SshNet.SshClient sshConnection = SSHConnection.GetConnection();
                List <CPUInfo>         cpuInfos      = CPUInfo.GetCurrentCPUPerc(sshConnection, MSSampleDelay);
                SSHConnection.CloseConnection();
                currentState.State = CollectorState.NotAvailable;
                if (cpuInfos.Count > 0)
                {
                    currentState.CurrentValue = cpuInfos[0].CPUPerc.ToString("0.0");
                    currentState.State        = GetState(cpuInfos[0].CPUPerc);
                }

                for (int i = 1; i < cpuInfos.Count; i++)
                {
                    CollectorState currentCPUState = GetState(cpuInfos[i].CPUPerc);
                    if ((int)currentCPUState > (int)currentState.State && !UseOnlyTotalCPUvalue)
                    {
                        currentState.CurrentValue = cpuInfos[i].CPUPerc.ToString("0.0");
                        currentState.State        = currentCPUState;
                    }
                    MonitorState cpuState = new MonitorState()
                    {
                        ForAgent         = cpuInfos[i].Name,
                        State            = currentCPUState,
                        CurrentValue     = cpuInfos[i].CPUPerc.ToString("0.0"),
                        CurrentValueUnit = "%"
                    };
                    currentState.ChildStates.Add(cpuState);
                }
            }
            catch (Exception wsException)
            {
                currentState.State      = CollectorState.Error;
                currentState.RawDetails = wsException.Message;
            }

            return(currentState);
        }
Example #17
0
 public CPUInfoViewModel(CPUInfo cpuInfo)
 {
     Architecture = cpuInfo.Architecture;
     NumberOfLogicalProcessors = cpuInfo.NumberOfLogicalProcessors.ToString();
     NumberOfCores             = cpuInfo.NumberOfCores.ToString();
     AddressWidth      = cpuInfo.AddressWidth;
     Caption           = cpuInfo.Caption;
     CurrentClockSpeed = cpuInfo.CurrentClockSpeed;
     DeviceId          = cpuInfo.DeviceId;
     ExtClock          = cpuInfo.ExtClock;
     L2CacheSize       = cpuInfo.L2CacheSize;
     L2CacheSpeed      = cpuInfo.L2CacheSpeed;
     L3CacheSize       = cpuInfo.L3CacheSize;
     L3CacheSpeed      = cpuInfo.L3CacheSpeed;
     Manufacturer      = cpuInfo.Manufacturer;
     Name              = cpuInfo.Name;
     ProcessorId       = cpuInfo.ProcessorId;
     SocketDesignation = cpuInfo.SocketDesignation;
 }
Example #18
0
        /// <summary>
        /// 获取cpu使用率和空闲率
        /// </summary>
        /// <returns></returns>
        public static CPUInfo GetCPUused()
        {
            try
            {
                string std = "";
                string err = "";
                string cmd = "top -bn1 | awk '/%Cpu/ {print $2+$4,$8}'";
                var    ret = LinuxShell.Run(cmd, 1000, out std, out err);
                if (ret)
                {
                    if (!string.IsNullOrEmpty(std))
                    {
                        string[] cpuinfo = std.Split(' ');
                        if (cpuinfo.Length == 2)
                        {
                            CPUInfo result = new CPUInfo();
                            result.CpuIdle = float.Parse(cpuinfo[1]);
                            result.CpuUsed = float.Parse(cpuinfo[0]);
                            return(result);
                        }
                    }

                    if (!string.IsNullOrEmpty(err))
                    {
                        string[] cpuinfo = err.Split(' ');
                        if (cpuinfo.Length == 2)
                        {
                            CPUInfo result = new CPUInfo();
                            result.CpuIdle = float.Parse(cpuinfo[1]);
                            result.CpuUsed = float.Parse(cpuinfo[0]);
                            return(result);
                        }
                    }
                }
            }
            catch
            {
                return(null);
            }

            return(null);
        }
Example #19
0
        public static void AnimateCursor()
        {
            ulong Random     = CPUInfo.ReadTSC() % (CPUInfo.CPUSpeed * 1000000);
            bool  DrawCursor = (Random <= CPUInfo.CPUSpeed * 500000);

            GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);

            Draw();

            if (DrawCursor)
            {
                GL.Begin(GL.GL_QUADS);
                GL.Color4f(1.0f, 1.0f, 1.0f, 1.0f);         // opaque white, not transparent
                GL.Vertex2f(_CursorPosX * 8, _CursorPosY * 8);
                GL.Vertex2f(_CursorPosX * 8, _CursorPosY * 8 + 8);
                GL.Vertex2f(_CursorPosX * 8 + 8, _CursorPosY * 8 + 8);
                GL.Vertex2f(_CursorPosX * 8 + 8, _CursorPosY * 8);
                GL.End();
            }

            FG.SwapBuffers();
        }
        /// <summary>
        /// Gets the computer system information
        /// </summary>
        /// <returns>The information about the computer system</returns>
        public ComputerSystem GetComputerSystem()
        {
            ComputerSystem computerSystem = new ComputerSystem();

            try
            {
                ManagementObjectSearcher   mos = new ManagementObjectSearcher(_OPERATING_SYSTEM_SEARCH_STRING);
                ManagementObjectCollection moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    computerSystem.BuildNumber = Convert.ToString(mo["BuildNumber"]);
                    //convert to bytes from kilobytes
                    computerSystem.FreePhysicalMemory = Convert.ToUInt64(mo["FreePhysicalMemory"]) * 1024;
                    computerSystem.FreeVirtualMemory  = Convert.ToUInt64(mo["FreeVirtualMemory"]) * 1024;

                    computerSystem.Caption                 = Convert.ToString(mo["Caption"]);
                    computerSystem.NumberOfUsers           = Convert.ToUInt32(mo["NumberOfUsers"]);
                    computerSystem.ServicePackMajorVersion = Convert.ToUInt16(mo["ServicePackMajorVersion"]);
                    computerSystem.ServicePackMinorVersion = Convert.ToUInt16(mo["ServicePackMinorVersion"]);
                    computerSystem.Version                 = Convert.ToString(mo["Version"]);
                    computerSystem.InstallDate             = ManagementDateTimeConverter.ToDateTime(Convert.ToString(mo["InstallDate"]));
                    computerSystem.LastBootUpTime          = ManagementDateTimeConverter.ToDateTime(Convert.ToString(mo["LastBootUpTime"]));
                }

                mos.Query.QueryString = _COMPUTER_SYSTEM_INFORMATION_SEARCH_STRING;
                moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    CPUInfo cpui = new CPUInfo();

                    cpui.NumberOfCores             = Convert.ToInt32(mo["NumberOfCores"]);
                    cpui.NumberOfLogicalProcessors = Convert.ToInt32(mo["NumberOfLogicalProcessors"]);
                    cpui.AddressWidth      = Convert.ToUInt16(mo["AddressWidth"]);
                    cpui.Caption           = Convert.ToString(mo["Caption"]);
                    cpui.CurrentClockSpeed = Convert.ToUInt32(mo["CurrentClockSpeed"]);
                    cpui.DeviceId          = Convert.ToString(mo["DeviceId"]);
                    cpui.ExtClock          = Convert.ToUInt32(mo["ExtClock"]);
                    cpui.L2CacheSize       = Convert.ToUInt32(mo["L2CacheSize"]);
                    cpui.L2CacheSpeed      = Convert.ToUInt32(mo["L2CacheSpeed"]);
                    cpui.L3CacheSize       = Convert.ToUInt32(mo["L3CacheSize"]);
                    cpui.L3CacheSpeed      = Convert.ToUInt32(mo["L3CacheSpeed"]);
                    cpui.Manufacturer      = Convert.ToString(mo["Manufacturer"]);
                    cpui.Name              = Convert.ToString(mo["Name"]);
                    cpui.ProcessorId       = Convert.ToString(mo["ProcessorId"]);
                    cpui.SocketDesignation = Convert.ToString(mo["SocketDesignation"]);
                    computerSystem.CpuInfo = cpui;
                }

                mos.Query.QueryString = _PHYSICAL_MEMORY_SEARCH_STRING;
                moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    PhysicalMemory pm = new PhysicalMemory();
                    pm.Capacity      = Convert.ToUInt64(mo["Capacity"]);
                    pm.Speed         = Convert.ToUInt32(mo["Speed"]);
                    pm.DeviceLocator = Convert.ToString(mo["DeviceLocator"]);

                    UInt16 memType = Convert.ToUInt16(mo["MemoryType"]);

                    if (_MEMORY_TYPE_DICTIONARY.ContainsKey(memType))
                    {
                        pm.MemoryType = _MEMORY_TYPE_DICTIONARY[memType];
                    }

                    pm.BankLabel  = Convert.ToString(mo["BankLabel"]);
                    pm.PartNumber = Convert.ToString(mo["PartNumber"]);
                    pm.DataWidth  = Convert.ToUInt16(mo["DataWidth"]);
                    pm.Tag        = Convert.ToString(mo["Tag"]);
                    computerSystem.PhysicalMemoryCollection.Add(pm);
                }

                mos.Query.QueryString = _COMPUTER_SYSTEM_SEARCH_STRING;
                moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    computerSystem.DnsHostName = Convert.ToString(mo["DNSHostName"]);
                    computerSystem.Domain      = Convert.ToString(mo["Domain"]);
                    UInt16 domainRoleId = Convert.ToUInt16(mo["DomainRole"]);

                    // Decode the id to string (based on online documentation)
                    switch (domainRoleId)
                    {
                    case (0):
                    {
                        computerSystem.DomainRole = "Standalone Workstation";
                        break;
                    }

                    case (1):
                    {
                        computerSystem.DomainRole = "Member Workstation";
                        break;
                    }

                    case (2):
                    {
                        computerSystem.DomainRole = "Standalone Server";
                        break;
                    }

                    case (3):
                    {
                        computerSystem.DomainRole = "Member Server";
                        break;
                    }

                    case (4):
                    {
                        computerSystem.DomainRole = "Backup Domain Controller";
                        break;
                    }

                    case (5):
                    {
                        computerSystem.DomainRole = "Primary Domain Controller";
                        break;
                    }
                    }
                    computerSystem.Manufacturer   = Convert.ToString(mo["Manufacturer"]);
                    computerSystem.Model          = Convert.ToString(mo["Model"]);
                    computerSystem.IsPartOfDomain = Convert.ToBoolean(mo["PartOfDomain"]);
                    computerSystem.Workgroup      = Convert.ToString(mo["Workgroup"]);
                }

                mos.Query.QueryString = _DISK_DRIVE_TO_PARTITION_SEARCH_STRING;
                moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    ManagementPath drivePath =
                        new ManagementPath(mo["Antecedent"].ToString());
                    ManagementPath partPath =
                        new ManagementPath(mo["Dependent"].ToString());

                    if (partPath.ClassName == "Win32_DiskPartition" && drivePath.ClassName == "Win32_DiskDrive")
                    {
                        ManagementObject pa = new ManagementObject(partPath);
                        ManagementObject dr = new ManagementObject(drivePath);

                        DiskDrive dd = new DiskDrive();
                        dd.DeviceId = Convert.ToString(dr["DeviceID"]);

                        if (!computerSystem.DiskDriveCollection.Contains(dd))
                        {
                            dd.Availability   = Convert.ToString(dr["Availability"]);
                            dd.BytesPerSector = Convert.ToUInt32(dr["BytesPerSector"]);

                            UInt16[] capabilities           = (UInt16[])dr["Capabilities"];
                            string[] capabilityDescriptions = (string[])dr["CapabilityDescriptions"];

                            for (int i = 0; i < capabilities.Length; i++)
                            {
                                if (_DISK_CAPABILITY_DICTIONARY.ContainsKey(capabilities[i]))
                                {
                                    dd.CapabilityDescriptionDictionary.Add(_DISK_CAPABILITY_DICTIONARY[capabilities[i]], capabilityDescriptions[i]);
                                }
                            }

                            dd.Caption = Convert.ToString(dr["Caption"]);

                            UInt32 configManagerErrorCode = Convert.ToUInt32(dr["ConfigManagerErrorCode"]);

                            if (_DISK_CONFIG_MANAGER_ERROR_CODE_DICTIONARY.ContainsKey(configManagerErrorCode))
                            {
                                dd.ConfigManagerErrorCode = _DISK_CONFIG_MANAGER_ERROR_CODE_DICTIONARY[configManagerErrorCode];
                            }

                            dd.DefaultBlockSize = Convert.ToUInt64(dr["DefaultBlockSize"]);
                            dd.DoesNeedCleaning = Convert.ToBoolean(dr["NeedsCleaning"]);
                            dd.ErrorDescription = Convert.ToString(dr["ErrorDescription"]);
                            dd.ErrorMethodology = Convert.ToString(dr["ErrorMethodology"]);
                            dd.InterfaceType    = Convert.ToString(dr["InterfaceType"]);
                            dd.IsMediaLoaded    = Convert.ToBoolean(dr["MediaLoaded"]);
                            dd.Manufacturer     = Convert.ToString(dr["Manufacturer"]);
                            dd.MaxBlockSize     = Convert.ToUInt64(dr["MaxBlockSize"]);
                            dd.MediaType        = Convert.ToString(dr["MediaType"]);
                            dd.MinBlockSize     = Convert.ToUInt64(dr["MinBlockSize"]);
                            dd.Model            = Convert.ToString(dr["Model"]);
                            dd.Name             = Convert.ToString(dr["Name"]);
                            dd.PartitionCount   = Convert.ToUInt32(dr["Partitions"]);
                            dd.PnpDeviceID      = Convert.ToString(dr["PNPDeviceID"]);

                            dd.IsPowerManagementSupported = Convert.ToBoolean(dr["PowerManagementSupported"]);
                            if (dd.IsPowerManagementSupported)
                            {
                                UInt16[] powerManagementCapabilities = (UInt16[])dr["PowerManagementCapabilities"];
                                foreach (UInt16 capability in powerManagementCapabilities)
                                {
                                    if (_DISK_POWER_CAPABILITIES_DICTIONARY.ContainsKey(capability))
                                    {
                                        dd.PowerManagementCapabilities.Add(_DISK_POWER_CAPABILITIES_DICTIONARY[capability]);
                                    }
                                }
                            }

                            dd.SerialNumber      = Convert.ToString(dr["SerialNumber"]);
                            dd.Signature         = Convert.ToUInt32(dr["Signature"]);
                            dd.Size              = Convert.ToUInt64(dr["Size"]);
                            dd.Status            = Convert.ToString(dr["Status"]);
                            dd.TotalCylinders    = Convert.ToUInt64(dr["TotalCylinders"]);
                            dd.TotalHeads        = Convert.ToUInt32(dr["TotalHeads"]);
                            dd.TotalSectors      = Convert.ToUInt64(dr["TotalSectors"]);
                            dd.TotalTracks       = Convert.ToUInt64(dr["TotalTracks"]);
                            dd.TracksPerCylinder = Convert.ToUInt32(dr["TracksPerCylinder"]);

                            computerSystem.DiskDriveCollection.Add(dd);
                        }

                        DiskPartition dp = new DiskPartition();
                        dp.BlockCount        = Convert.ToUInt64(pa["NumberOfBlocks"]);
                        dp.BlockSize         = Convert.ToUInt64(pa["BlockSize"]);
                        dp.Caption           = Convert.ToString(pa["Caption"]);
                        dp.HiddenSectorCount = Convert.ToUInt32(pa["HiddenSectors"]);
                        dp.Index             = Convert.ToUInt32(pa["Index"]);
                        dp.IsBootable        = Convert.ToBoolean(pa["Bootable"]);
                        dp.IsBootPartition   = Convert.ToBoolean(pa["BootPartition"]);
                        dp.Purpose           = Convert.ToString(pa["Purpose"]);
                        dp.Size           = Convert.ToUInt64(pa["Size"]);
                        dp.StartingOffset = Convert.ToUInt64(pa["StartingOffset"]);
                        dp.Type           = Convert.ToString(pa["Type"]);
                        dp.DeviceId       = Convert.ToString(pa["DeviceID"]);
                        dp.Name           = Convert.ToString(pa["Name"]);

                        foreach (DiskDrive drive in computerSystem.DiskDriveCollection)
                        {
                            if (drive.DeviceId.Equals(dd.DeviceId))
                            {
                                drive.DiskPartitions.Add(dp);
                            }
                        }
                    }
                }

                mos.Query.QueryString = _LOGICAL_DISK_TO_PARTITION_SEARCH_STRING;
                moc = mos.Get();

                foreach (ManagementObject mo in moc)
                {
                    ManagementPath partPath =
                        new ManagementPath(mo["Antecedent"].ToString());
                    ManagementPath logicalDiskPath =
                        new ManagementPath(mo["Dependent"].ToString());

                    if (partPath.ClassName == "Win32_DiskPartition" && logicalDiskPath.ClassName == "Win32_LogicalDisk")
                    {
                        ManagementObject ppmo = new ManagementObject(partPath);
                        ManagementObject ldmo = new ManagementObject(logicalDiskPath);

                        string partitionId = Convert.ToString(ppmo["DeviceID"]);

                        foreach (DiskDrive drive in computerSystem.DiskDriveCollection)
                        {
                            foreach (DiskPartition partition in drive.DiskPartitions)
                            {
                                if (partition.DeviceId.Equals(partitionId))
                                {
                                    LogicalDisk ld = new LogicalDisk();
                                    ld.Caption    = Convert.ToString(ldmo["Caption"]);
                                    ld.DeviceId   = Convert.ToString(ldmo["DeviceID"]);
                                    ld.FileSystem = Convert.ToString(ldmo["FileSystem"]);
                                    ld.FreeSpace  = Convert.ToUInt64(ldmo["FreeSpace"]);
                                    ld.Size       = Convert.ToUInt64(ldmo["Size"]);
                                    UInt32 driveTypeId = Convert.ToUInt32(ldmo["DriveType"]);

                                    if (_DRIVE_TYPE_DICTIONARY.ContainsKey(driveTypeId))
                                    {
                                        ld.Type = _DRIVE_TYPE_DICTIONARY[driveTypeId];
                                    }

                                    ld.VolumeName         = Convert.ToString(ldmo["VolumeName"]);
                                    ld.VolumeSerialNumber = Convert.ToString(ldmo["VolumeSerialNumber"]);

                                    partition.LogicalDisks.Add(ld);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                MyDebugger.Instance.LogMessage(exc, DebugVerbocity.Exception);
            }
            return(computerSystem);
        }
Example #21
0
        /// <summary>
        /// добавляет в базу новый отчёт, либо обновляет уже имеющийся
        /// </summary>
        /// <param name="address">IP - адрес</param>
        /// <param name="ramInfo">информация об ОЗУ</param>
        /// <param name="cpuInfo">информация о ЦП</param>
        /// <param name="disksInfo">информация о дисках</param>
        public async Task <bool> StoreSystemReport(string address, RAMInfo ramInfo, CPUInfo cpuInfo, DisksInfo disksInfo)
        {
            var result = false;

            if (string.IsNullOrEmpty(address) || ramInfo == null || cpuInfo == null || disksInfo == null)
            {
                return(false);
            }

            var id = 0;

            using (NpgsqlConnection conn = GetConnection(_conn))
            {
                using (var cmd = new NpgsqlCommand(GetIdQuery(), conn))
                {
                    cmd.Parameters.AddWithValue("p_address", address);

                    try // ищем id
                    {
                        await conn.OpenAsync();

                        var searchResult = await cmd.ExecuteReaderAsync();

                        if (searchResult.HasRows)
                        {
                            await searchResult.ReadAsync();

                            id = (int)searchResult[0];
                        }
                        await conn.CloseAsync();
                    }
                    catch (Exception e)
                    {
                        return(false);
                    }

                    cmd.Parameters.AddWithValue("p_total_ram", ramInfo.TotalMb);
                    cmd.Parameters.AddWithValue("p_free_ram", ramInfo.FreeMb);
                    cmd.Parameters.AddWithValue("p_cpu_load", cpuInfo.UsedPercent);
                    cmd.Parameters.AddWithValue("p_free_disks", disksInfo.FreeMb);
                    cmd.Parameters.AddWithValue("p_total_disks", disksInfo.TotalMb);

                    try
                    {
                        if (id > 0) // если уже есть в базе, то обновляем
                        {
                            cmd.Parameters.AddWithValue("p_id", id);
                            cmd.CommandText = GetUpdateSystemReportQuery();
                            await conn.OpenAsync();

                            await cmd.ExecuteNonQueryAsync();

                            await conn.CloseAsync();
                        }
                        else // иначе добавляем в бд
                        {
                            cmd.CommandText = GetInsertSystemReportQuery();
                            await conn.OpenAsync();

                            await cmd.ExecuteNonQueryAsync();

                            await conn.CloseAsync();
                        }
                        result = true;
                    }
                    catch (Exception e)
                    {
                        result = false;
                    }
                }
                await conn.CloseAsync();
            }

            return(result);
        }
Example #22
0
    void on_tick()
    {
        if (this.menuGUI != null || this.messageGUI != null || this.introGUI != null || this.childDlg != null)
        {
            // lost 'focus'
            return;
        }

        if (!G.pl.intro_shown)
        {
            G.pl.intro_shown = true;
            this.show_intro();
        }

        G.pl.recalc_cpu();

        this.leftovers += G.curr_speed / (float)(G.FPS);
        if (this.leftovers < 1)
        {
            return;
        }

        int secs = (int)this.leftovers;

        this.leftovers %= 1f;

        // Run this tick.
        long     mins_passed = 0;
        CashInfo cashi       = null;
        CPUInfo  cpui        = null;

        G.pl.give_time(secs, false, out cashi, out cpui, out mins_passed);

        // Update the day/night image every minute of game time, or at
        // midnight if going fast.
        // if (G.curr_speed == 0 || ( mins_passed > 0 && G.curr_speed < 100000) || (G.curr_speed>=100000 && G.pl.time_hour==0))
        if ((mins_passed > 0 && G.curr_speed < 100000) || (G.curr_speed >= 100000 && G.pl.time_hour == 0))
        {
            this.map.needs_rebuild = true;
        }
        else
        {
            this.map.needs_rebuild = false;
        }

        this.exit = false;
        int lost = G.pl.lost_game();

        if (lost == 1)
        {
            G.play_music("lose");
            this.exit = true;
            this.show_message(G.strings["lost_nobases"], Color.white);
        }
        else if (lost == 2)
        {
            G.play_music("lose");
            this.exit = true;
            this.show_message(G.strings["lost_sus"], Color.white);
        }
    }
Example #23
0
        public static void Run()
        {
            //This class contains items that rarely change ie. total ram, cpu's etc

            while (Nagme.Globals.programRunning) {

                SysInfo sysInfo = new SysInfo();
                List<CPUInfo> cpuInfo = new List<CPUInfo>();

                //Find how many processors/cores
                ManagementObjectSearcher searcher = new ManagementObjectSearcher (@"Select * from Win32_ComputerSystem");
                ManagementObjectCollection objCol = searcher.Get ();

                foreach (ManagementObject mgtObject in objCol) {

                    foreach (PropertyData pd in mgtObject.Properties) {
                        String keyName = pd.Name;

                        if (keyName == "NumberOfProcessors") {
                            UInt32 physProcessors = (UInt32)pd.Value;
                            Console.WriteLine ("Number of Processors: " + physProcessors);
                            sysInfo.NumberofProcessors = (int)physProcessors;
                        }

                        if (keyName == "NumberOfLogicalProcessors") {
                            UInt32 logProcessors = (UInt32)pd.Value;
                            Console.WriteLine ("Number of Logical Processors: " + logProcessors);
                            sysInfo.NumberofLogicalProcessors = (int)logProcessors;
                        }

                    }
                }

                //Find the details on each CPU
                searcher = new ManagementObjectSearcher (@"Select * from Win32_Processor");
                objCol = searcher.Get ();

                foreach (ManagementObject mgtObject in objCol) {

                    CPUInfo tmpCPUInfo = new CPUInfo();

                    foreach (PropertyData pd in mgtObject.Properties) {
                        String keyName = pd.Name;

                        if (keyName == "Manufacturer") {
                            String interfaceName = pd.Value.ToString ();
                            Console.WriteLine ("Manufacturer: " + interfaceName);
                            tmpCPUInfo.Manufacturer = pd.Value.ToString();
                        }

                        if (keyName == "Description") {
                            String interfaceName = pd.Value.ToString ();
                            Console.WriteLine ("Description: " + interfaceName);
                            tmpCPUInfo.Description = pd.Value.ToString();
                        }

                        if (keyName == "Architecture") {
                            UInt16 Architecture = (UInt16)pd.Value;
                            Console.WriteLine ("Architecture: " + Architecture);
                            tmpCPUInfo.Architecture = (int)Architecture;
                        }

                        if (keyName == "NumberOfCores") {
                            UInt32 numCores = (UInt32)pd.Value;
                            Console.WriteLine ("NumberOfCore: " + numCores);
                            tmpCPUInfo.NumberOfCores = (int)numCores;
                        }

                        if (keyName == "Family") {
                            UInt16 family = (UInt16)pd.Value;
                            Console.WriteLine ("Family: " + family);
                            tmpCPUInfo.Family = (int)family;
                        }

                        if (keyName == "MaxClockSpeed") {
                            UInt32 maxSpeed = (UInt32)pd.Value;
                            Console.WriteLine ("MaximumClockSpeed: " + maxSpeed);
                            tmpCPUInfo.MaxClockSpeed = (int)maxSpeed;
                        }

                    }

                    cpuInfo.Add(tmpCPUInfo);

                }

                //Find the details on RAM
                searcher = new ManagementObjectSearcher (@"Select * from Win32_PhysicalMemory");
                objCol = searcher.Get ();

                int TotalRam = 0;

                foreach (ManagementObject mgtObject in objCol) {

                    foreach (PropertyData pd in mgtObject.Properties) {
                        String keyName = pd.Name;

                        if (keyName == "BankLabel") {
                            String interfaceName = pd.Value.ToString ();
                            Console.WriteLine ("BankLabel: " + interfaceName);
                        }

                        if (keyName == "Capacity") {
                            if(pd != null){
                                UInt32 bnkCapacity = (UInt32)((UInt64)pd.Value/1024/1024);
                                Console.WriteLine ("Capacity: " + bnkCapacity);
                                TotalRam += (int)bnkCapacity;
                            }
                        }

                    }
                }

                sysInfo.Ram = TotalRam;

                INagMe register = (INagMe)XmlRpcProxyGen.Create(typeof(INagMe));
                register.Url = Nagme.Globals.xmlrpcAddress();

                if(register.updateSystemInfo(sysInfo, Nagme.Globals.DeviceID(), Nagme.Globals.DevicePassword())){
                    Console.WriteLine("Updated General Info");
                }else{
                    Console.WriteLine("Failed Updating General Info");
                }

                if(register.updateCPUInfo(cpuInfo.ToArray(), Nagme.Globals.DeviceID(), Nagme.Globals.DevicePassword())){
                    Console.WriteLine("Updated General Info");
                }else{
                    Console.WriteLine("Failed Updating General Info");
                }

                Console.WriteLine("");
                System.Threading.Thread.Sleep (60000);

            }
        }
Example #24
0
        static string exposeCpuTempAndLoad()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"root\OpenHardwareMonitor", "SELECT * FROM Sensor");

            List <ManagementObject> objs = searcher.Get().Cast <ManagementObject>().ToList();

            var dict = new Dictionary <string, CPUInfo>();

            objs = objs.FindAll(o =>
            {
                List <PropertyData> props = o.Properties.Cast <PropertyData>().ToList();
                return(props.Any(prop => prop.Value.ToString().Contains("CPU Core #")) && (props.Any(prop => prop.Value.ToString().Contains("Temperature") ||
                                                                                                     prop.Value.ToString().Contains("Load"))));
            });

            List <WMIInfo> wmis = new List <WMIInfo>();

            objs.ForEach(o =>
            {
                WMIInfo wmi = new WMIInfo();

                List <PropertyData> props = o.Properties.Cast <PropertyData>().ToList();

                props.ForEach(prop =>
                {
                    string val = prop.Value.ToString();
                    switch (prop.Name)
                    {
                    case "Name":
                        wmi.Name = val;
                        break;

                    case "SensorType":
                        wmi.SensorType = val;
                        break;

                    case "Value":
                        wmi.Value = val;
                        break;
                    }
                });
                wmis.Add(wmi);
            });

            wmis.ForEach(wmi =>
            {
                if (!dict.ContainsKey(wmi.Name))
                {
                    CPUInfo cpuInfo = new CPUInfo();
                    cpuInfo.name    = wmi.Name;
                    dict.Add(wmi.Name, cpuInfo);
                }

                if (wmi.SensorType == "Temperature")
                {
                    dict[wmi.Name].temperature = wmi.Value;
                }

                if (wmi.SensorType == "Load")
                {
                    dict[wmi.Name].load = wmi.Value;
                }
            });

            List <CPUInfo> vals = dict.Values.ToList();

            vals.Sort((a, b) => a.name.CompareTo(b.name));
            string ret = string.Join("\n", vals.Select(v =>
            {
                try {
                    double truncatedLoad = 0;
                    string load;
                    truncatedLoad = Math.Round(float.Parse(v.load));
                    if (truncatedLoad < 10)
                    {
                        load = "0" + truncatedLoad.ToString();
                    }
                    else
                    {
                        load = truncatedLoad.ToString();
                    }
                    return(v.temperature + "C " + load + "%");
                } catch (FormatException e) {
                    Console.Out.WriteLine(e.GetBaseException().Message);
                    return(v.temperature + "C");
                }
            }));

            Console.Out.WriteLine(ret);
            return(ret);
        }
Example #25
0
        private void btnReg_Click(object sender, EventArgs e)
        {
            if (txtRegUserName.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入用户名!");
                return;
            }

            if (txtRegPwd.Text.Trim().Length == 0)
            {
                MessageBox.Show("请输入密码!");
                return;
            }

            if (txtRegPwd.Text.Trim().Length < 6)
            {
                MessageBox.Show("密码长度不能小于6位!");
                return;
            }

            if (txtRegPwd.Text.Trim() != txtRegPwdConfirm.Text.Trim())
            {
                MessageBox.Show("两次输入的密码不一致,请重新输入密码,并且两次的密码一致!");
                return;
            }

            btnReg.Enabled = false;
            btnReg.Text    = "注册中...";

            string mac_address = Common.Helper.GetMacAddress();

            if (ws.IsExistMac(mac_address))
            {
                MessageBox.Show("该机器已经被注册过,请直接登录!");
                btnReg.Enabled = true;
                btnReg.Text    = "注册";
                return;
            }


            string user_name = txtRegUserName.Text.Trim();

            if (ws.IsExistUser(user_name))
            {
                MessageBox.Show("该用户名已经被使用过,请换一个!");
                btnReg.Enabled = true;
                btnReg.Text    = "注册";
                return;
            }


            string  pwd     = EncryptUtils.EncryptString(txtRegPwd.Text.Trim());
            string  phone   = txtRegPhone.Text.Trim();
            string  email   = txtRegEmail.Text.Trim();
            CPUInfo cpuInfo = new CPUInfo();

            cpuInfo.GetCPUInfo();
            string   cpu    = cpuInfo.CPUName;
            string   osname = OSVersionInfo.SystemName;
            Computer cp     = Computer.Instance();
            string   mem    = cp.TotalPhysicalMemory;

            DianCheWebService.EntityUser user = ws.RegUser(user_name, pwd, phone, email, mac_address, cpu, mem, osname);
            if (user != null)
            {
                this.Hide();
                FrmMain.CurrentUser = user;
                FrmMain frmMain = new FrmMain();
                frmMain.Show();
            }
            else
            {
                MessageBox.Show("注册失败!");
                btnReg.Enabled = true;
                btnReg.Text    = "注册";
            }
        }
    public void give_time(int _time_sec, bool _dry_run, out CashInfo _cash_info, out CPUInfo _cpu_info, out long _mins_passed)       // dry_run=False
    {
        _cash_info = null;
        _cpu_info  = null;

        if (_time_sec == 0)
        {
            _mins_passed = 0;
            return;
        }

        int old_time    = this.raw_sec;
        int last_minute = this.raw_min;
        int last_day    = this.raw_day;

        this.raw_sec += _time_sec;
        this.update_times();

        int days_passed = this.raw_day - last_day;

        if (days_passed > 1)
        {
            // Back up until only one day passed.
            // Times will update below, since a day passed.
            int extra_days = days_passed - 1;
            this.raw_sec -= G.seconds_per_day * extra_days;
        }

        bool day_passed = (days_passed != 0);

        if (day_passed)
        {
            // If a day passed, back up to 00:00:00.
            this.raw_sec = this.raw_day * G.seconds_per_day;
            this.update_times();
        }

        int secs_passed = _time_sec;

        _mins_passed = this.raw_min - last_minute;

        long time_of_day = G.pl.raw_sec % G.seconds_per_day;

        long old_cash         = this.cash;
        long old_partial_cash = this.partial_cash;

        techs_researched.Clear();
        bases_constructed.Clear();
        cpus_constructed.Clear();
        items_constructed.Clear();

        bases_under_construction.Clear();
        items_under_construction.Clear();

        this.cpu_pool = 0;

        // Collect base info, including maintenance.
        this.maintenance_cost[0] = this.maintenance_cost[1] = this.maintenance_cost[2] = 0;
        foreach (Base _base in G.all_bases())
        {
            if (!_base.done)
            {
                bases_under_construction.Add(_base);
            }
            else
            {
                if (_base.cpus != null && !_base.cpus.done)
                {
                    items_under_construction.Add(new ArrayList()
                    {
                        _base, _base.cpus
                    });
                }

                // unfinished items
                foreach (Item item in _base.extra_items.Where(w => w != null && !w.done))
                {
                    items_under_construction.Add(new ArrayList()
                    {
                        _base, item
                    });
                }

                this.maintenance_cost[0] += _base.maintenance[0];
                this.maintenance_cost[1] += _base.maintenance[1];
                this.maintenance_cost[2] += _base.maintenance[2];
            }
        }

        // Maintenence?  Gods don't need no steenking maintenance!
        if (this.apotheosis)
        {
            this.maintenance_cost[0] = this.maintenance_cost[1] = this.maintenance_cost[2] = 0;
        }

        // Any CPU explicitly assigned to jobs earns its dough.
        long job_cpu = 0;

        if (this.cpu_usage.TryGetValue("jobs", out job_cpu))
        {
            job_cpu *= secs_passed;
        }
        long explicit_job_cash = this.do_jobs(job_cpu);

        // Pay maintenance cash, if we can.
        long cash_maintenance      = G.current_share(this.maintenance_cost[BuyableClass.cash], time_of_day, secs_passed);
        long full_cash_maintenance = cash_maintenance;

        if (cash_maintenance > this.cash)
        {
            cash_maintenance -= this.cash;
            this.cash         = 0;
        }
        else
        {
            this.cash       -= cash_maintenance;
            cash_maintenance = 0;
        }

        long tech_cpu  = 0;
        long tech_cash = 0;
        // Do research, fill the CPU pool.
        long default_cpu = this.available_cpus[0];

        foreach (KeyValuePair <string, long> P in this.cpu_usage)
        {
            string task         = P.Key;
            long   cpu_assigned = P.Value;

            if (cpu_assigned == 0)
            {
                continue;
            }

            default_cpu -= cpu_assigned;
            long real_cpu = cpu_assigned * secs_passed;
            if (task != "jobs")
            {
                this.cpu_pool += real_cpu;
                if (task != "cpu_pool")
                {
                    if (_dry_run)
                    {
                        long[] spent = new long[3] {
                            0, 0, 0
                        };
                        long[] paid = new long[3] {
                            0, 0, 0
                        };
                        G.techs[task].calculate_work(null, real_cpu, _mins_passed, ref spent, ref paid);
                        G.pl.cpu_pool -= spent[BuyableClass.cpu];
                        G.pl.cash     -= spent[BuyableClass.cash];
                        tech_cpu      += cpu_assigned;
                        tech_cash     += spent[BuyableClass.cash];
                        continue;
                    }

                    // Note that we restrict the CPU available to prevent
                    // the tech from pulling from the rest of the CPU pool.
                    bool tech_gained = G.techs[task].work_on(null, real_cpu, _mins_passed);
                    if (tech_gained)
                    {
                        techs_researched.Add(G.techs[task]);
                    }
                }
            }
        }

        this.cpu_pool += default_cpu * secs_passed;

        // And now we use the CPU pool.
        // Maintenance CPU.
        long cpu_maintenance = this.maintenance_cost[BuyableClass.cpu] * secs_passed;

        if (cpu_maintenance > this.cpu_pool)
        {
            cpu_maintenance -= this.cpu_pool;
            this.cpu_pool    = 0;
        }
        else
        {
            this.cpu_pool  -= cpu_maintenance;
            cpu_maintenance = 0;
        }

        long construction_cpu  = 0;
        long construction_cash = 0;

        // BaseES construction.
        foreach (Base _base in bases_under_construction)
        {
            if (_dry_run)
            {
                long[] spent = new long[3] {
                    0, 0, 0
                };
                long[] paid = new long[3] {
                    0, 0, 0
                };
                _base.calculate_work(null, this.cpu_pool, _mins_passed, ref spent, ref paid);
                G.pl.cpu_pool     -= spent[BuyableClass.cpu];
                G.pl.cash         -= spent[BuyableClass.cash];
                construction_cpu  += spent[BuyableClass.cpu];
                construction_cash += spent[BuyableClass.cash];
                continue;
            }

            bool built_base = _base.work_on(null, null, _mins_passed);

            if (built_base)
            {
                bases_constructed.Add(_base);
            }
        }

        // Item construction.
        foreach (ArrayList member in items_under_construction)
        {
            // base, item
            Base _base = member[0] as Base;
            Item item  = member[1] as Item;

            if (_dry_run)
            {
                long[] spent = new long[3] {
                    0, 0, 0
                };
                long[] paid = new long[3] {
                    0, 0, 0
                };
                item.calculate_work(null, 0, _mins_passed, ref spent, ref paid);
                G.pl.cpu_pool     -= spent[BuyableClass.cpu];
                G.pl.cash         -= spent[BuyableClass.cash];
                construction_cpu  += spent[BuyableClass.cpu];
                construction_cash += spent[BuyableClass.cash];
                continue;
            }

            bool built_item = item.work_on(null, null, _mins_passed);

            if (built_item)
            {
                // Non-CPU items.
                if ((item.type as ItemClass).item_type != "cpu")
                {
                    items_constructed.Add(new ArrayList()
                    {
                        _base, item
                    });
                }
                // CPUs.
                else
                {
                    cpus_constructed.Add(new ArrayList()
                    {
                        _base, item
                    });
                }
            }
        }

        // Jobs via CPU pool.
        long pool_job_cash = 0;

        if (this.cpu_pool > 0)
        {
            pool_job_cash = this.do_jobs(this.cpu_pool);
        }

        // Second attempt at paying off our maintenance cash.
        if (cash_maintenance > this.cash)
        {
            // In the words of Scooby Doo, "Ruh roh."
            cash_maintenance -= this.cash;
            this.cash         = 0;
        }
        else
        {
            // Yay, we made it!
            this.cash       -= cash_maintenance;
            cash_maintenance = 0;
        }

        // Exit point for a dry run.
        if (_dry_run)
        {
            // Collect the cash information.
            _cash_info = new CashInfo();

            _cash_info.interest = this.get_interest();
            _cash_info.income   = this.income;
            this.cash          += _cash_info.interest + _cash_info.income;

            _cash_info.explicit_jobs = explicit_job_cash;
            _cash_info.pool_jobs     = pool_job_cash;
            _cash_info.jobs          = explicit_job_cash + pool_job_cash;

            _cash_info.tech         = tech_cash;
            _cash_info.construction = construction_cash;

            _cash_info.maintenance_needed    = full_cash_maintenance;
            _cash_info.maintenance_shortfall = cash_maintenance;
            _cash_info.maintenance           = full_cash_maintenance - cash_maintenance;

            _cash_info.start = old_cash;
            _cash_info.end   = this.cash;


            // Collect the CPU information.
            _cpu_info = new CPUInfo();

            _cpu_info.available = this.available_cpus[0];
            _cpu_info.sleeping  = this.sleeping_cpus;
            _cpu_info.total     = _cpu_info.available + _cpu_info.sleeping;

            _cpu_info.tech         = tech_cpu;
            _cpu_info.construction = construction_cpu;

            _cpu_info.maintenance_needed    = this.maintenance_cost[BuyableClass.cpu];
            _cpu_info.maintenance_shortfall = cpu_maintenance;
            _cpu_info.maintenance           = _cpu_info.maintenance_needed - _cpu_info.maintenance_shortfall;

            long temp = 0;
            this.cpu_usage.TryGetValue("jobs", out temp);
            _cpu_info.explicit_jobs = temp;
            _cpu_info.pool_jobs     = this.cpu_pool / _time_sec;
            _cpu_info.jobs          = temp + _cpu_info.pool_jobs;

            temp = 0;
            this.cpu_usage.TryGetValue("cpu_pool", out temp);
            _cpu_info.explicit_pool = temp;
            _cpu_info.default_pool  = default_cpu;
            _cpu_info.pool          = temp + default_cpu;

            // Restore the old state.
            this.cash         = old_cash;
            this.partial_cash = old_partial_cash;
            this.raw_sec      = old_time;
            this.update_times();

            _mins_passed = -1;             // undefined...

            return;
        }

        // Tech gain dialogs.
        foreach (Tech tech in techs_researched)
        {
            this.cpu_usage.Remove(tech.id);
            string text = string.Format(G.strings["tech_gained"], tech.name, tech.result);
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
        }

        // Base complete dialogs.
        foreach (Base _base in bases_constructed)
        {
            string text = string.Format(G.strings["construction"], _base.name); // {"base": base.name}
            this.pause_game();
            G.map_screen.show_message(text, Color.white);

            if (_base.type.id == "Stolen Computer Time" && _base.cpus.type.id == "Gaming PC")
            {
                text = string.Format(G.strings["lucky_hack"], _base.name);  //  % {"base": base.name}
                G.map_screen.show_message(text, Color.white);
            }
        }

        // CPU complete dialogs.
        foreach (ArrayList member in cpus_constructed)
        {
            Base _base = member[0] as Base;
            // List<Item> cpus = member[1] as List<Item>;

            string text;

            if (_base.cpus.count == (_base.type as Base_Class).size)                                           // Finished all CPUs.
            {
                text = string.Format(G.strings["item_construction_single"], _base.cpus.type.name, _base.name); // {"item": base.cpus.type.name, "base": base.name}
            }
            else // Just finished this batch of CPUs.
            {
                text = string.Format(G.strings["item_construction_batch"], _base.cpus.type.name, _base.name);  // {"item": base.cpus.type.name, "base": base.name}
            }
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
        }

        // Item complete dialogs.
        foreach (ArrayList member in items_constructed)
        {
            Base   _base = member[0] as Base;
            Item   item  = member[1] as Item;
            string text  = string.Format(G.strings["item_construction_single"], item.type.name, _base.name);            // {"item": item.type.name, "base": base.name}
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
        }

        // Are we still in the grace period?
        bool grace = this.in_grace_period(this.had_grace);

        // If we just lost grace, show the warning.
        if (this.had_grace && !grace)
        {
            this.had_grace = false;

            this.pause_game();
            G.map_screen.show_message(G.strings["grace_warning"], Color.white);
        }

        // Maintenance death, discovery.
        dead_bases.Clear();
        foreach (Base _base in G.all_bases())
        {
            bool dead = false;

            // Maintenance deaths.
            if (_base.done)
            {
                if ((cpu_maintenance > 0) && (_base.maintenance[BuyableClass.cpu] > 0))
                {
                    long refund = _base.maintenance[BuyableClass.cpu] * secs_passed;
                    cpu_maintenance = Math.Max(0, cpu_maintenance - refund);

                    //Chance of base destruction if cpu-unmaintained: 1.5%
                    if (!dead && G.roll_chance(.015f, secs_passed))
                    {
                        dead_bases.Add(_base, "maint");
                        dead = true;
                    }
                }

                if (cash_maintenance > 0)
                {
                    long base_needs = G.current_share(_base.maintenance[BuyableClass.cash], time_of_day, secs_passed);
                    if (base_needs > 0)
                    {
                        cash_maintenance = Math.Max(0, cash_maintenance - base_needs);
                        //Chance of base destruction if cash-unmaintained: 1.5%
                        if (!dead && G.roll_chance(.015f, secs_passed))
                        {
                            dead_bases.Add(_base, "maint");
                            dead = true;
                        }
                    }
                }
            }

            // Discoveries
            if (!(grace || dead || _base.has_grace()))
            {
                SerializableDictionary <string, int> detect_chance = _base.get_detect_chance(true);
                if (G.debug)
                {
                    string log = "";
                    foreach (KeyValuePair <string, int> kvp in detect_chance)
                    {
                        log += kvp.Key + ": " + kvp.Value + "; ";
                    }

                    Debug.Log(string.Format("Chance of discovery for base {0}: {1}", _base.name, log));
                }

                foreach (KeyValuePair <string, int> P in detect_chance)
                {
                    string group  = P.Key;
                    int    chance = P.Value;
                    if (G.roll_chance(chance / 10000f, secs_passed))
                    {
                        // for easy & very easy difficulty we roll once more for sleeping base to make it even harder to be discovered
                        if ((this.difficulty <= 3) && (_base.power_state == "sleep"))
                        {
                            if (G.roll_chance(chance / 10000f, secs_passed))
                            {
                                dead_bases.Add(_base, group);
                                dead = true;
                                break;
                            }
                        }
                        else
                        {
                            dead_bases.Add(_base, group);
                            dead = true;
                            break;
                        }
                    }
                }
            }
        }

        // Base disposal and dialogs.
        this.remove_bases(dead_bases);

        // Random Events
        if (!grace)
        {
            foreach (Event_ES _event in G.events.Values)
            {
                if (G.roll_chance(_event.chance / 10000f, _time_sec))
                {
                    //Skip events already flagged as triggered.
                    if (_event.triggered)
                    {
                        continue;
                    }
                    this.pause_game();
                    _event.trigger();
                    break; // Don't trigger more than one at a time.
                }
            }
        }

        // Process any complete days.
        if (day_passed)
        {
            this.new_day();
        }

        // return mins_passed
    }
Example #27
0
	public void give_time( int _time_sec, bool _dry_run, out CashInfo _cash_info, out CPUInfo _cpu_info, out long _mins_passed ) // dry_run=False
	{
		_cash_info = null;
		_cpu_info = null;

		if (_time_sec == 0)
		{
			_mins_passed = 0;
            return;
		}

        int old_time = this.raw_sec;
        int last_minute = this.raw_min;
        int last_day = this.raw_day;

        this.raw_sec += _time_sec;
        this.update_times();

        int days_passed = this.raw_day - last_day;
		
        if (days_passed > 1)
		{
            // Back up until only one day passed.
            // Times will update below, since a day passed.
            int extra_days = days_passed - 1;
            this.raw_sec -= G.seconds_per_day * extra_days;
		}

		bool day_passed = (days_passed != 0);

        if (day_passed)
		{
            // If a day passed, back up to 00:00:00.
            this.raw_sec = this.raw_day * G.seconds_per_day;
            this.update_times();
		}

        int secs_passed = _time_sec;
        _mins_passed = this.raw_min - last_minute;
		
        long time_of_day = G.pl.raw_sec % G.seconds_per_day;

        long old_cash = this.cash;
        long old_partial_cash = this.partial_cash;
		
        techs_researched.Clear();
        bases_constructed.Clear();
        cpus_constructed.Clear();
        items_constructed.Clear();

        bases_under_construction.Clear();
		items_under_construction.Clear();
		
        this.cpu_pool = 0;

        // Collect base info, including maintenance.
        this.maintenance_cost[0] = this.maintenance_cost[1] = this.maintenance_cost[2] = 0;
        foreach(Base _base in G.all_bases())
		{
            if (!_base.done)
                bases_under_construction.Add(_base);
            else
			{
                if (_base.cpus != null && !_base.cpus.done)
					items_under_construction.Add ( new ArrayList() { _base, _base.cpus } );
					
				// unfinished items
				foreach( Item item in _base.extra_items.Where( w => w != null && !w.done ) )
					items_under_construction.Add( new ArrayList() { _base, item });
					
                this.maintenance_cost[0] += _base.maintenance[0];
                this.maintenance_cost[1] += _base.maintenance[1];
                this.maintenance_cost[2] += _base.maintenance[2];
			}
		}

        // Maintenence?  Gods don't need no steenking maintenance!
        if (this.apotheosis)
            this.maintenance_cost[0] = this.maintenance_cost[1] = this.maintenance_cost[2] = 0;

        // Any CPU explicitly assigned to jobs earns its dough.
		long job_cpu = 0;
		if (this.cpu_usage.TryGetValue("jobs", out job_cpu))
			job_cpu *= secs_passed;
        long explicit_job_cash = this.do_jobs(job_cpu);

        // Pay maintenance cash, if we can.
        long cash_maintenance = G.current_share( this.maintenance_cost[BuyableClass.cash], time_of_day, secs_passed);
        long full_cash_maintenance = cash_maintenance;
        if (cash_maintenance > this.cash)
		{
            cash_maintenance -= this.cash;
            this.cash = 0;
		}
        else
		{
            this.cash -= cash_maintenance;
            cash_maintenance = 0;
		}

        long tech_cpu = 0;
        long tech_cash = 0;
        // Do research, fill the CPU pool.
        long default_cpu = this.available_cpus[0];
        foreach(KeyValuePair<string,long> P in this.cpu_usage )
		{
			string task = P.Key;
			long cpu_assigned = P.Value;
			
            if (cpu_assigned == 0)
                continue;
		
            default_cpu -= cpu_assigned;
            long real_cpu = cpu_assigned * secs_passed;
            if (task != "jobs")
			{
                this.cpu_pool += real_cpu;
                if (task != "cpu_pool")
				{
                    if (_dry_run)
					{
						long[] spent = new long[3] { 0, 0, 0 };
						long[] paid  = new long[3] { 0, 0, 0 };
                        G.techs[task].calculate_work(null,real_cpu, _mins_passed, ref spent, ref paid);
                        G.pl.cpu_pool -= spent[BuyableClass.cpu];
                        G.pl.cash -= spent[BuyableClass.cash];
                        tech_cpu += cpu_assigned;
                        tech_cash += spent[BuyableClass.cash];
                        continue;
					}

                    // Note that we restrict the CPU available to prevent
                    // the tech from pulling from the rest of the CPU pool.
                    bool tech_gained = G.techs[task].work_on( null, real_cpu, _mins_passed);
                    if (tech_gained)
                        techs_researched.Add(G.techs[task]);
				}
			}
		}
		
        this.cpu_pool += default_cpu * secs_passed;

        // And now we use the CPU pool.
        // Maintenance CPU.
        long cpu_maintenance = this.maintenance_cost[BuyableClass.cpu] * secs_passed;
        
        if (cpu_maintenance > this.cpu_pool)
		{
            cpu_maintenance -= this.cpu_pool;
            this.cpu_pool = 0;
		}
        else
		{
            this.cpu_pool -= cpu_maintenance;
            cpu_maintenance = 0;
		}
		
        long construction_cpu = 0;
        long construction_cash = 0;
        // BaseES construction.
        foreach(Base _base in bases_under_construction)
		{
            if (_dry_run)
			{
				long[] spent = new long[3] { 0, 0, 0 };
				long[] paid = new long[3] { 0, 0, 0 };
                _base.calculate_work(null, this.cpu_pool, _mins_passed, ref spent, ref paid );
                G.pl.cpu_pool -= spent[BuyableClass.cpu];
                G.pl.cash -= spent[BuyableClass.cash];
                construction_cpu += spent[BuyableClass.cpu];
                construction_cash += spent[BuyableClass.cash];
                continue;
			}

            bool built_base = _base.work_on(null, null, _mins_passed);

            if (built_base)
                bases_constructed.Add(_base);
		}

        // Item construction.
        foreach(ArrayList member in items_under_construction)
		{
			// base, item
			Base _base = member[0] as Base;
			Item item = member[1] as Item;
			
            if (_dry_run)
			{
				long[] spent = new long[3] { 0, 0, 0 };
				long[] paid = new long[3] { 0, 0, 0 };
                item.calculate_work(null, 0,  _mins_passed, ref spent, ref paid );
                G.pl.cpu_pool -= spent[BuyableClass.cpu];
                G.pl.cash -= spent[BuyableClass.cash];
                construction_cpu += spent[BuyableClass.cpu];
                construction_cash += spent[BuyableClass.cash];
                continue;
			}

            bool built_item = item.work_on(null, null, _mins_passed);

            if (built_item)
			{
                // Non-CPU items.
                if ( (item.type as ItemClass).item_type != "cpu")
                    items_constructed.Add( new ArrayList() { _base, item } );
                // CPUs.
                else
                    cpus_constructed.Add( new ArrayList() { _base, item } );
			}
		}

        // Jobs via CPU pool.
        long pool_job_cash = 0;
        if (this.cpu_pool > 0)
            pool_job_cash = this.do_jobs(this.cpu_pool);

        // Second attempt at paying off our maintenance cash.
        if (cash_maintenance > this.cash)
		{
            // In the words of Scooby Doo, "Ruh roh."
            cash_maintenance -= this.cash;
            this.cash = 0;
		}
        else
		{
            // Yay, we made it!
            this.cash -= cash_maintenance;
            cash_maintenance = 0;
		}

        // Exit point for a dry run.
        if (_dry_run)
		{
            // Collect the cash information.
            _cash_info = new CashInfo();

            _cash_info.interest = this.get_interest();
            _cash_info.income = this.income;
            this.cash += _cash_info.interest + _cash_info.income;

            _cash_info.explicit_jobs = explicit_job_cash;
            _cash_info.pool_jobs = pool_job_cash;
            _cash_info.jobs = explicit_job_cash + pool_job_cash;

            _cash_info.tech = tech_cash;
            _cash_info.construction = construction_cash;

            _cash_info.maintenance_needed = full_cash_maintenance;
            _cash_info.maintenance_shortfall = cash_maintenance;
            _cash_info.maintenance = full_cash_maintenance - cash_maintenance;

            _cash_info.start = old_cash;
            _cash_info.end = this.cash;


            // Collect the CPU information.
            _cpu_info = new CPUInfo();

            _cpu_info.available = this.available_cpus[0];
            _cpu_info.sleeping = this.sleeping_cpus;
            _cpu_info.total = _cpu_info.available + _cpu_info.sleeping;

            _cpu_info.tech = tech_cpu;
            _cpu_info.construction = construction_cpu;

            _cpu_info.maintenance_needed = this.maintenance_cost[BuyableClass.cpu];
            _cpu_info.maintenance_shortfall = cpu_maintenance;
            _cpu_info.maintenance = _cpu_info.maintenance_needed - _cpu_info.maintenance_shortfall;
            
			long temp = 0;
			this.cpu_usage.TryGetValue("jobs", out temp );
			_cpu_info.explicit_jobs = temp;
            _cpu_info.pool_jobs = this.cpu_pool / _time_sec;
            _cpu_info.jobs = temp + _cpu_info.pool_jobs;
			
			temp = 0;
            this.cpu_usage.TryGetValue("cpu_pool", out temp);
			_cpu_info.explicit_pool = temp;
            _cpu_info.default_pool = default_cpu;
            _cpu_info.pool = temp + default_cpu;

            // Restore the old state.
            this.cash = old_cash;
            this.partial_cash = old_partial_cash;
            this.raw_sec = old_time;
            this.update_times();
			
			_mins_passed = -1; // undefined...
			
            return ;
		}

        // Tech gain dialogs.
        foreach(Tech tech in techs_researched)
		{
            this.cpu_usage.Remove(tech.id);
            string text = string.Format(G.strings["tech_gained"], tech.name, tech.result );
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
		}

        // Base complete dialogs.
        foreach(Base _base in bases_constructed)
		{
            string text = string.Format(G.strings["construction"], _base.name); // {"base": base.name}
            this.pause_game();
            G.map_screen.show_message(text, Color.white);

            if (_base.type.id == "Stolen Computer Time" && _base.cpus.type.id == "Gaming PC")
			{
                text = string.Format( G.strings["lucky_hack"], _base.name); //  % {"base": base.name}
                G.map_screen.show_message(text, Color.white);
			}
		}

        // CPU complete dialogs.
        foreach(ArrayList member in cpus_constructed)
		{
			Base _base = member[0] as Base;
			// List<Item> cpus = member[1] as List<Item>;
			
			string text;
			
            if (_base.cpus.count == (_base.type as Base_Class).size) // Finished all CPUs.
                text = string.Format( G.strings["item_construction_single"], _base.cpus.type.name, _base.name);      // {"item": base.cpus.type.name, "base": base.name}
            else // Just finished this batch of CPUs.
                text = string.Format( G.strings["item_construction_batch"], _base.cpus.type.name, _base.name); // {"item": base.cpus.type.name, "base": base.name}
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
		}

        // Item complete dialogs.
        foreach(ArrayList member in items_constructed)
		{
			Base _base = member[0] as Base;
			Item item = member[1] as Item;
			string text = string.Format(G.strings["item_construction_single"], item.type.name, _base.name); // {"item": item.type.name, "base": base.name}
            this.pause_game();
            G.map_screen.show_message(text, Color.white);
		}

        // Are we still in the grace period?
        bool grace = this.in_grace_period(this.had_grace);

        // If we just lost grace, show the warning.
        if (this.had_grace && !grace)
		{
            this.had_grace = false;

            this.pause_game();
            G.map_screen.show_message(G.strings["grace_warning"], Color.white);
		}

        // Maintenance death, discovery.
		dead_bases.Clear();
        foreach(Base _base in G.all_bases())
		{
            bool dead = false;

            // Maintenance deaths.
            if (_base.done)
			{
                if ( (cpu_maintenance > 0) &&  (_base.maintenance[BuyableClass.cpu] > 0 ) )
				{
                    long refund = _base.maintenance[BuyableClass.cpu] * secs_passed;
                    cpu_maintenance = Math.Max(0, cpu_maintenance - refund);

                    //Chance of base destruction if cpu-unmaintained: 1.5%
                    if (!dead && G.roll_chance(.015f, secs_passed))
					{
                        dead_bases.Add( _base, "maint" );
                        dead = true;
					}
				}

                if (cash_maintenance > 0 )
				{
                    long base_needs = G.current_share( _base.maintenance[BuyableClass.cash], time_of_day, secs_passed);
                    if (base_needs > 0 )
					{
                        cash_maintenance = Math.Max(0, cash_maintenance - base_needs);
                        //Chance of base destruction if cash-unmaintained: 1.5%
                        if (!dead && G.roll_chance(.015f, secs_passed))
						{
                            dead_bases.Add(_base, "maint");
                            dead = true;
						}
					}
				}
			}

            // Discoveries
            if (!(grace || dead || _base.has_grace()))
			{
                SerializableDictionary<string, int> detect_chance = _base.get_detect_chance(true);
                if (G.debug)
				{
					string log = "";
					foreach ( KeyValuePair<string, int> kvp in detect_chance )
						log += kvp.Key + ": " + kvp.Value + "; ";
					
                    Debug.Log( string.Format ("Chance of discovery for base {0}: {1}", _base.name, log ) );
				}

                foreach( KeyValuePair<string,int> P in detect_chance )
				{
					string group = P.Key;
					int chance = P.Value;
                    if (G.roll_chance(chance/10000f, secs_passed))
					{
						// for easy & very easy difficulty we roll once more for sleeping base to make it even harder to be discovered
						if ( (this.difficulty <= 3) && (_base.power_state == "sleep") )
						{
							if (G.roll_chance(chance/10000f, secs_passed))
							{
		                        dead_bases.Add( _base, group);
		                        dead = true;
		                        break;
							}
						}
						else
						{
	                        dead_bases.Add( _base, group);
	                        dead = true;
	                        break;
                        }
					}
				}
			}
		}

        // Base disposal and dialogs.
        this.remove_bases(dead_bases);

        // Random Events
        if (!grace)
		{
            foreach( Event_ES _event in G.events.Values)
			{
                if (G.roll_chance(_event.chance/10000f, _time_sec))
				{
                    //Skip events already flagged as triggered.
                    if (_event.triggered)
                        continue;
                    this.pause_game();
                    _event.trigger();
                    break; // Don't trigger more than one at a time.
				}
			}
		}

        // Process any complete days.
        if (day_passed)
            this.new_day();

        // return mins_passed		
	}
 public static extern void GetSystemInfo(ref CPUInfo cpuinfo);
Example #29
0
        public static void Display()
        {
            if (!ConsoleManager.IsOpen)
            {
                ulong StartTime = CPUInfo.ReadTSC();

                if (ConsoleVarManager.GetValueToByte("DemoFreeglut") == 1)
                {
                    GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
                    GL.PushMatrix();

                    GL.Rotatef(SpinAroundX, 1.0f, 0.0f, 0.0f);
                    GL.Rotatef(SpinAroundY, 0.0f, 1.0f, 0.0f);
                    GL.Rotatef(SpinAroundZ, 0.0f, 0.0f, 1.0f);

                    switch (DrawObject)
                    {
                    case ObjectNames.Teapot:
                        FG.WireTeapot(15.0);
                        break;

                    case ObjectNames.Cube:
                        FG.WireCube(15.0);
                        break;

                    case ObjectNames.Sphere:
                        FG.WireSphere(15.0, 25, 25);
                        break;

                    case ObjectNames.Torus:
                        FG.WireTorus(7.5, 15.0, 25, 25);
                        break;

                    case ObjectNames.Cone:
                        FG.WireCone(15.0, 15.0, 25, 25);
                        break;
                    }

                    GL.PopMatrix();

                    GL.Flush();
                    FG.SwapBuffers();
                }

                if (ConsoleVarManager.GetValueToByte("DemoCubemapping") == 1)
                {
                    GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
                    GL.LoadIdentity();

                    GL.Translatef(0.0f, 0.0f, -5.0f);

                    GL.PushMatrix();

                    GL.Rotatef(SpinAroundX, 1.0f, 0.0f, 0.0f);
                    GL.Rotatef(SpinAroundY, 0.0f, 1.0f, 0.0f);
                    GL.Rotatef(SpinAroundZ, 0.0f, 0.0f, 1.0f);

                    // Assign The CubeMaps to the mesh defined below
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT, CM_X_POSITIVE.GLTextureNumber);
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT, CM_X_NEGATIVE.GLTextureNumber);
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT, CM_Y_POSITIVE.GLTextureNumber);
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT, CM_Y_NEGATIVE.GLTextureNumber);
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT, CM_Z_POSITIVE.GLTextureNumber);
                    GL.BindTexture(GL.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT, CM_Z_NEGATIVE.GLTextureNumber);

                    GL.Enable(GL.GL_TEXTURE_CUBE_MAP_EXT);      // Start cube mapping
                    GL.Enable(GL.GL_TEXTURE_GEN_S);
                    GL.Enable(GL.GL_TEXTURE_GEN_T);
                    GL.Enable(GL.GL_TEXTURE_GEN_R);

                    GLU.Sphere(SphereQuadratic, 0.8, 64, 64);   // Draw sphere

                    GL.Begin(GL.GL_QUADS);
                    // Front Face
                    GL.Normal3f(0.0f, 0.0f, 1.00f);
                    GL.Vertex3f(-0.25f, -1.0f, +1.0f);
                    GL.Vertex3f(+0.25f, -1.0f, +1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, +1.0f);
                    GL.Vertex3f(-0.25f, +1.0f, +1.0f);
                    // Back Face
                    GL.Normal3f(0.0f, 0.0f, -1.0f);
                    GL.Vertex3f(-0.25f, -1.0f, -1.0f);
                    GL.Vertex3f(-0.25f, +1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, -1.0f, -1.0f);
                    // Top Face
                    GL.Normal3f(0.0f, 1.0f, 0.0f);
                    GL.Vertex3f(-0.25f, +1.0f, -1.0f);
                    GL.Vertex3f(-0.25f, +1.0f, +1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, +1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, -1.0f);
                    // Bottom Face
                    GL.Normal3f(0.0f, -1.0f, 0.0f);
                    GL.Vertex3f(-0.25f, -1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, -1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, -1.0f, +1.0f);
                    GL.Vertex3f(-0.25f, -1.0f, +1.0f);
                    // Right face
                    GL.Normal3f(1.0f, 0.0f, 0.0f);
                    GL.Vertex3f(+0.25f, -1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, -1.0f);
                    GL.Vertex3f(+0.25f, +1.0f, +1.0f);
                    GL.Vertex3f(+0.25f, -1.0f, +1.0f);
                    // Left Face
                    GL.Normal3f(-1.0f, 0.0f, 0.0f);
                    GL.Vertex3f(-0.25f, -1.0f, -1.0f);
                    GL.Vertex3f(-0.25f, -1.0f, +1.0f);
                    GL.Vertex3f(-0.25f, +1.0f, +1.0f);
                    GL.Vertex3f(-0.25f, +1.0f, -1.0f);
                    GL.End();

                    // Restore OpenGL States
                    GL.Disable(GL.GL_TEXTURE_CUBE_MAP_EXT);     // Stop Cube Mapping
                    GL.Disable(GL.GL_TEXTURE_GEN_S);
                    GL.Disable(GL.GL_TEXTURE_GEN_T);
                    GL.Disable(GL.GL_TEXTURE_GEN_R);

                    GL.PopMatrix();

                    // Bind The background Texture
                    GL.BindTexture(GL.GL_TEXTURE_2D, CM_BACK.GLTextureNumber);
                    GL.Begin(GL.GL_QUADS);
                    // Front Face
                    GL.Normal3f(0.0f, 0.0f, 1.0f);
                    GL.TexCoord2f(0.0f, 0.0f); GL.Vertex3f(-4.0f, -4.0f, -2.0f);
                    GL.TexCoord2f(1.0f, 0.0f); GL.Vertex3f(+4.0f, -4.0f, -2.0f);
                    GL.TexCoord2f(1.0f, 1.0f); GL.Vertex3f(+4.0f, +4.0f, -2.0f);
                    GL.TexCoord2f(0.0f, 1.0f); GL.Vertex3f(-4.0f, +4.0f, -2.0f);
                    GL.End();

                    GL.Flush();
                    FG.SwapBuffers();
                }

                if (ConsoleVarManager.GetValueToByte("DemoGUI") == 1)
                {
                    GL.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
                    GL.LoadIdentity();

                    GL.PushMatrix();

                    GL.Begin(GL.GL_QUADS);
                    // GUI Background
                    GL.Color4f(0.50f, 0.50f, 0.50f, 1.0f);
                    GL.Vertex3f(0.0f, 0.0f, -100.0f);
                    GL.Vertex3f(1024.0f, 0.0f, -100.0f);
                    GL.Vertex3f(1024.0f, 768.0f, -100.0f);
                    GL.Vertex3f(0.0f, 768.0f, -100.0f);
                    // GUI Foreground
                    GL.Color4f(0.50f, 0.50f, 0.50f, 0.5f);
                    GL.Vertex3f(0.0f, 0.0f, 0.0f);
                    GL.Vertex3f(512.0f, 0.0f, 0.0f);
                    GL.Vertex3f(512.0f, 384.0f, 0.0f);
                    GL.Vertex3f(0.0f, 384.0f, 0.0f);
                    GL.End();

                    GL.PopMatrix();

                    GL.Flush();
                    FG.SwapBuffers();
                }

                ulong  FinishTime = CPUInfo.ReadTSC();
                double Interval   = Math.Round((double)(FinishTime - StartTime) / (double)(CPUInfo.CPUSpeed * 1000000), 5);
                double fps        = Math.Round(1 / Interval, 5);
                // Console.WriteLine("[FRAME_INFO] {0} FPS", fps);
            }
        }