Exemplo n.º 1
0
        public void Generate(int userLength)
        {
            var maze = new Maze();

            _maze = maze;
            if (OnProgressUpdate != null)
            {
                OnProgressUpdate.Invoke(20); //Updates the loading bar on the MainWindow
            }

            var genMaze = new MazeGenerationService(userLength, userLength, _maze);

            _genMaze = genMaze;

            if (OnProgressUpdate != null)
            {
                OnProgressUpdate.Invoke(70); //Updates the loading bar on the MainWindow
            }

            var play = new MazePlayService(_maze);

            _play = play;

            if (OnProgressUpdate != null)
            {
                OnProgressUpdate.Invoke(10); //Updates the loading bar on the MainWindow
            }

            CreateExitPoint();

            var position = new Mazepoints(0, 0, false, true);

            _position = position;
        }
Exemplo n.º 2
0
        protected void SendProgressUpdate(int current)
        {
            _progressArgs.State   = ProgressState.Running;
            _progressArgs.Current = current;

            OnProgressUpdate?.Invoke(this, _progressArgs);
        }
Exemplo n.º 3
0
        public MovieCollection ImportMoviesFromDumpFiles(string[] filesToRead, MovieCollection movieCollection)
        {
            var movieList = new List <Movie>();

            foreach (var txtFile in filesToRead)
            {
                if (File.Exists(txtFile) && txtFile.Contains(".txt"))
                {
                    var fileName = Path.GetFileNameWithoutExtension(txtFile);
                    var Encoding = EncodingDetector.DetectTextFileEncoding(txtFile);

                    var myFile       = new StreamReader(txtFile, Encoding);
                    var moviesString = myFile.ReadToEnd();
                    myFile.Close();

                    moviesString = moviesString.Replace("last-modified   |ext |size|name|location", string.Empty);
                    var moviesLines = moviesString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                    OnProgressUpdate?.Invoke(ImportProgressType.NewFile, fileName, moviesLines.Count());
                    foreach (var line in moviesLines)
                    {
                        if (line != "done" && !string.IsNullOrWhiteSpace(line))
                        {
                            var movie = FileHelper.GetMovieFromLine(line, fileName);
                            if (movie != null)
                            {
                                movieCollection.AddMovie(movie);
                            }
                        }
                        OnProgressUpdate?.Invoke(ImportProgressType.NewLine, string.Empty, 0);
                    }
                }
            }
            return(movieCollection);
        }
        private void processFilter_OnProgressUpdate(object sender, ApplyFilterProcessorEventArgs e)
        {
            if (OnProgressUpdate == null)
            {
                return;
            }

            lock (_threadLockObject)
            {
                if (_updateProgressDictionary.ContainsKey(e.ThreadIndex))
                {
                    _updateProgressDictionary[e.ThreadIndex] = e.ProcessedPixelCount;
                }
                else
                {
                    _updateProgressDictionary.Add(e.ThreadIndex, e.ProcessedPixelCount);
                }

                int pxSum           = _updateProgressDictionary.Values.Sum(p => p);
                int percentComplete = Convert.ToInt32((pxSum / (double)_sourceDataBase.NumberOfPixels) * 100);
                OnProgressUpdate.Invoke(this, new ApplyFilterEventArgs {
                    PercentComplete = percentComplete, ProgressMessage = ""
                });
            }
        }
Exemplo n.º 5
0
 protected void ReportProgress(double value, string status)
 {
     lastProgressUpdate = value;
     lastStatusUpdate   = status;
     OnProgressUpdate?.Invoke(value, status);
     logger.Log($"{value:0.00} progress: {status}");
 }
Exemplo n.º 6
0
        protected void SendProgressEnd()
        {
            _progressArgs.State   = ProgressState.End;
            _progressArgs.Current = 0;

            OnProgressUpdate?.Invoke(this, _progressArgs);
        }
Exemplo n.º 7
0
        public static void HandleProgress(EventArgs progressEventArgs)
        {
            ProgressEventArgs progressEvent = (ProgressEventArgs)progressEventArgs;

            currentState = progressEvent.state;
            if (currentProgress < progressEvent.downloadPercentage)
            {
                currentProgress = progressEvent.downloadPercentage;
            }
            if (!isActive)
            {
                return;
            }
            OnProgressUpdate?.Invoke(progressEvent);
            pbProgressBar?.PerformSafely(() => pbProgressBar.Value = currentProgress);
            if (progressEvent.state == ProgressEventArgs.State.Run)
            {
                fakeProgressTimer.Stop();
                pbProgressBar?.PerformSafely(() => pbProgressBar.Style      = ProgressBarStyle.Marquee);
                lblProgressValue?.PerformSafely(() => lblProgressValue.Text = statInst);
            }
            else if (progressEvent.state == ProgressEventArgs.State.Download)
            {
                lblProgressValue?.PerformSafely(() => lblProgressValue.Text = statCompleted.Replace("$percent$", currentProgress + "%"));
            }
            else if (progressEvent.state == ProgressEventArgs.State.Done)
            {
                fakeProgressTimer.Stop();
                pbProgressBar?.PerformSafely(() => pbProgressBar.Style              = ProgressBarStyle.Continuous);
                lblProgressValue?.PerformSafely(() => lblProgressValue.Text         = statCompleted.Replace("$percent$", "100%"));
                lblProgressUpperText?.PerformSafely(() => lblProgressUpperText.Text = statFinished);
                btnFinish?.PerformSafely(() => btnFinish.Show());
            }
        }
Exemplo n.º 8
0
        protected void UpdateProgress(ProgressState state, int total, int current)
        {
            _progressArgs.State   = state;
            _progressArgs.Total   = total;
            _progressArgs.Current = current;

            OnProgressUpdate?.Invoke(this, _progressArgs);
        }
Exemplo n.º 9
0
        protected void SendProgressStart(int total)
        {
            _progressArgs.State   = ProgressState.Start;
            _progressArgs.Total   = total;
            _progressArgs.Current = 0;

            OnProgressUpdate?.Invoke(this, _progressArgs);
        }
Exemplo n.º 10
0
 public IgnoreIdenticalBeginningAndEndCorrelaterWrapper(ICorrelater <T> innerCorrelater)
 {
     this.innerCorrelater              = innerCorrelater;
     innerCorrelater.OnProgressUpdate += (p, t) => OnProgressUpdate?.Invoke(p, t);
     if (innerCorrelater is IContinuousCorrelater <T> continuousCorrelater)
     {
         continuousCorrelater.OnResultUpdate += r => OnResultUpdate?.Invoke(r);
     }
 }
Exemplo n.º 11
0
        public PatienceDiffCorrelater()
        {
            if (default(T) != null && typeof(T) != typeof(char))
            {
                throw new EnumerableCorrelaterException($"{nameof(T)} must be nullable or a char");
            }

            innerCorrelater.OnProgressUpdate += (p, t) => OnProgressUpdate?.Invoke(p, t);
            innerCorrelater.OnResultUpdate   += r => OnResultUpdate?.Invoke(r);
        }
Exemplo n.º 12
0
 private void OnProgressChanged(IProgress progressThatJustChanged)
 {
     latestChangeTime = DateTimeV2.UtcNow;
     if (progressThatJustChanged != null)
     {
         latestUpdatedProgress = progressThatJustChanged;
     }
     CalcLatestStats();
     OnProgressUpdate?.Invoke(this, progressThatJustChanged);
 }
Exemplo n.º 13
0
        public void RunSQL(SQL_Query sqlQuery)
        {
            string          connectionstring;
            MySqlConnection cnn    = null;
            MySqlDataReader reader = null;

            connectionstring = "server=" + sqlQuery.Server + ";database=" + sqlQuery.Database + ";uid=" + sqlQuery.User + ";pwd=" + sqlQuery.Psw;
            Console.WriteLine("Connection string: " + connectionstring);
            cnn = new MySqlConnection(connectionstring);
            try
            {
                OnProgressUpdate?.Invoke(sqlQuery.JobId);
                cnn.Open();
                Console.WriteLine("Connection Open");

                string query = "select * from arkiv";

                MySqlCommand cmd = new MySqlCommand(sqlQuery.Query, cnn);
                reader = cmd.ExecuteReader();

                int    ColumnCount   = reader.FieldCount;
                string ListOfColumns = string.Empty;

                while (reader.Read())
                {
                    for (int i = 0; i < ColumnCount; i++)
                    {
                        ListOfColumns = ListOfColumns + reader[i].ToString() + "|";
                    }
                    ListOfColumns = ListOfColumns + "\r\n";
                }

                sqlQuery.Result = ListOfColumns;
            }
            catch (MySqlException ex)
            {
                Console.WriteLine("Unable to open connection!");

                throw ex;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                if (cnn != null)
                {
                    cnn.Close();
                    Console.WriteLine("Connection Closed");
                }
            }
        }
Exemplo n.º 14
0
        public static (XDocument, AdjacencyGraph <Vertex, Edge <Vertex> >) ResolveCircuit(
            XDocument inputDoc, bool invertMemory, bool retainParallel)
        {
            OnProgressUpdate?.Invoke(0, "Extracting Component Graph...");
            AdjacencyGraph <Vertex, Edge <Vertex> > graph =
                inputDoc.CreateComponentGraph();

            graph.SolveUpdateOrder(out Vertex[] sortedVertices, invertMemory, retainParallel);
            inputDoc.UpdateSubmarineIDs(graph, sortedVertices);

            return(inputDoc, graph);
        }
Exemplo n.º 15
0
        // Extracts all query information from query text file into query list
        public string GetQuery(string filename)
        {
            OnProgressUpdate?.Invoke("Reading queries");

            using (StreamReader reader = new StreamReader(File.OpenRead(filename)))
            {
                String line;
                while (((line = reader.ReadLine()) != null))
                {
                    Console.WriteLine(line);


                    if (line.StartsWith("["))
                    {
                        string qType = line.Split('[', ']')[1];
                        Console.WriteLine(qType);

                        string qStart    = @"#START#";
                        string qStop     = @"#STOP#";
                        string queryText = "";
                        while ((line = reader.ReadLine().Trim()) != null)
                        {
                            queryInfo.Add(line);

                            if (line.Equals(qStart))
                            {
                                Console.WriteLine("START found");

                                while (!(line = reader.ReadLine()).Equals(qStop))
                                {
                                    queryText += line + "\r\n";
                                }
                                queryText = queryText.TrimEnd('\r', '\n');
                                queryInfo.Add(queryText);
                                CreateQuery(qType, queryInfo);
                                queryInfo.Clear();
                                break;
                            }
                        }
                    }
                }
            }

            Console.WriteLine("All queries read");
            OnProgressUpdate?.Invoke("All queries read");

            foreach (string s in queryInfo)
            {
                Console.WriteLine(s);
            }

            return("");
        }
        private void IncrementAll(int value)
        {
            RowsTotal        += value;
            _progressCounter += value;

            if (_progressCounter >= RowsPerProgressEvent)
            {
                _progressCounter = 0;
                LastUpdateTime   = DateTime.Now;
                OnProgressUpdate?.Invoke(this);
            }
        }
        private void DoProgressUpdate(string msg, int progressValue, int progressMax)
        {
            msg            = string.IsNullOrEmpty(msg) ? _lastMessage : msg;
            _progressValue = progressValue;
            _progressMax   = progressMax;

            OnProgressUpdate?.Invoke(this, new WdcStoryExporterProgressUpdateArgs()
            {
                ProgressMax   = progressMax,
                ProgressValue = progressValue,
                Message       = msg
            });
        }
Exemplo n.º 18
0
        public void RunXPath(List <QueryClass> Xqueries, string sourceFolder)
        {
            Dictionary <string, XmlDocument> sources = new Dictionary <string, XmlDocument>();

            foreach (XML_Query q in Xqueries)
            {
                if (q.JobEnabled.Equals("1") || q.JobEnabled.Equals("2") || q.JobEnabled.Equals("3"))
                {
                    string xmlFileName = Path.Combine(sourceFolder, q.Source);
                    Console.WriteLine("Source: " + q.Source + ", XML File: " + xmlFileName);

                    Processor processor = new Processor();

                    XmlDocument inputDoc = new XmlDocument();

                    if (!sources.ContainsKey(q.Source))
                    {
                        XmlDocument newDoc = new XmlDocument();
                        newDoc.Load(xmlFileName);
                        sources.Add(q.Source, newDoc);
                    }
                    inputDoc = sources[q.Source];

                    XdmNode xmlDoc = processor.NewDocumentBuilder().Build(new XmlNodeReader(inputDoc));

                    XPathCompiler xPathCompiler = processor.NewXPathCompiler();

                    string nameSpace    = inputDoc.DocumentElement.NamespaceURI;
                    string nameSpaceXsi = inputDoc.DocumentElement.GetNamespaceOfPrefix("xsi");

                    xPathCompiler.DeclareNamespace("", nameSpace);
                    xPathCompiler.DeclareNamespace("xsi", nameSpaceXsi);

                    string query = q.Query;

                    try
                    {
                        OnProgressUpdate?.Invoke(q.JobId);
                        string result = xPathCompiler.Evaluate(query, xmlDoc).ToString();

                        q.Result = result.Replace("\"", "");
                    }
                    catch (Exception e)
                    {
                        OnProgressUpdate?.Invoke("ERROR: " + q.JobId);
                        q.Result = "ERROR 1, unable to compile: " + q.Query;
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
Exemplo n.º 19
0
        public static (XDocument, AdjacencyGraph <Vertex, Edge <Vertex> >) ResolveCircuit(
            string inputSub, bool invertMemory, bool retainParallel)
        {
            OnProgressUpdate?.Invoke(0, "Loading Submarine...");
            XDocument submarine = IoUtil.LoadSub(inputSub);

            OnProgressUpdate?.Invoke(0.2f, "Extracting Component Graph...");
            AdjacencyGraph <Vertex, Edge <Vertex> > graph =
                submarine.CreateComponentGraph();

            graph.SolveUpdateOrder(out Vertex[] sortedVertices, invertMemory, retainParallel);
            submarine.UpdateSubmarineIDs(graph, sortedVertices);

            return(submarine, graph);
        }
        /// <summary>
        /// Creates the dynamic table.
        /// Cell[i, j] defines the best match in which array1 contains all elements up to i (including), and array2 contains all elements up to j (including)
        /// </summary>
        private long[,] CreateDynamicTable(ICollectionWrapper <T> collection1, ICollectionWrapper <T> collection2, CancellationToken cancellationToken)
        {
            var dynamicTable = new long[collection1.Length + 1, collection2.Length + 1];

            dynamicTable[0, 0] = 0;
            for (int i = 1; i < collection1.Length + 1; i++)
            {
                dynamicTable[i, 0] = dynamicTable[i - 1, 0] + removalCalculator.RemovalCost(collection1[i - 1]);
            }
            for (int i = 1; i < collection2.Length + 1; i++)
            {
                dynamicTable[0, i] = dynamicTable[0, i - 1] + insertionCalculator.InsertionCost(collection2[i - 1]);
            }

            OnProgressUpdate?.Invoke(1, collection1.Length + 1);
            for (int i = 1; i < collection1.Length + 1; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                for (int j = 1; j < collection2.Length + 1; j++)
                {
                    if (collection1[i - 1].Equals(collection2[j - 1]))
                    {
                        dynamicTable[i, j] = dynamicTable[i - 1, j - 1];
                        continue;
                    }

                    var insertion = dynamicTable[i, j - 1] + insertionCalculator.InsertionCost(collection1[i - 1]);
                    var removal   = dynamicTable[i - 1, j] + removalCalculator.RemovalCost(collection2[j - 1]);
                    var min       = Min(insertion, removal);

                    if (distanceCalculator != null)
                    {
                        var substitution = dynamicTable[i - 1, j - 1] + distanceCalculator.Distance(collection1[i - 1], collection2[j - 1]);
                        min = Math.Min(min, substitution);
                    }
                    if (CanDoTransposition(collection1, collection2, i, j))
                    {
                        var transposition = transpositionCalculator.TranspositionCost(collection1[i - 1], collection1[i - 2]) + dynamicTable[i - 2, j - 2];
                        min = Math.Min(min, transposition);
                    }
                    dynamicTable[i, j] = min;
                }
                OnProgressUpdate?.Invoke(i + 1, collection1.Length + 1);
            }
            return(dynamicTable);
        }
Exemplo n.º 21
0
            private async void UploadBuild(string path = null)
            {
                try
                {
                    var client = await GetCLIClient();

                    var req = new Trail.Cli.Service.Cli.V1.UploadBuildReq
                    {
                        BuildPath   = string.IsNullOrEmpty(path) ? EditorUtility.OpenFolderPanel("Select build path", "", "") : path,
                        ProjectPath = "",
                    };
                    var call = client.UploadBuild(req);

                    var error = false;
                    while (await call.ResponseStream.MoveNext(cancellationTokenSource.Token))
                    {
                        if (call.ResponseStream.Current.Error != null)
                        {
                            error         = true;
                            errorMessage += call.ResponseStream.Current.Error.Message + "\n";
                            break;
                        }
                        if (call.ResponseStream.Current.Progress != null && call.ResponseStream.Current.Progress.Update != null)
                        {
                            var p = call.ResponseStream.Current.Progress.Update.Progress;
                            if (p >= 0f)
                            {
                                Progress = p;
                            }
                        }
                        if (OnProgressUpdate != null)
                        {
                            OnProgressUpdate.Invoke(Progress);
                        }
                    }
                    RunCallback(!error, this);
                }
                catch (System.Exception e)
                {
                    errorMessage = e.Message;
                    RunCallback(false, this);
                }
            }
Exemplo n.º 22
0
        public void ConvertList(string inFileName, string outFileName)
        {
            stykkList.Clear();
            mappeList.Clear();

            try
            {
                ReadInList(inFileName);

                if (stykkList.Count > 0)
                {
                    WriteOutList(outFileName);
                }
            }catch (Exception e)
            {
                OnProgressUpdate?.Invoke("ERROR: " + e.Message);
                throw e;
            }
        }
        public CorrelaterResult <T> Merge(List <Task <CorrelaterResult <T> > > results)
        {
            var bestMatch1 = new List <T>();
            var bestMatch2 = new List <T>();
            var distance   = 0L;

            var i = 0;

            foreach (var result in results.Select(t => t.Result))
            {
                OnProgressUpdate?.Invoke(++i, results.Count);
                OnResultUpdate?.Invoke(result);
                bestMatch1.AddRange(result.BestMatch1);
                bestMatch2.AddRange(result.BestMatch2);
                distance += result.Distance;
            }

            return(new CorrelaterResult <T>(distance, bestMatch1.ToArray(), bestMatch2.ToArray()));
        }
        public void ProcessPixels(int threadIndex)
        {
            int loopCount    = 0;
            int pixelCount   = _toPixel - _fromPixel;
            int pbarModValue = pixelCount / MaxProgressUpdates;

            for (int i = _fromPixel; i < _toPixel && _runThreadPoolCallback; i++)
            {
                loopCount++;
                _sourceData.SetPixelIndex(i);
                Pixel p = _filter.Map(_sourceData);
                _sourceData.SetPixel(p, _sourceData.Offset_X, _sourceData.Offset_Y);

                // We dont want to invoke OnProgressUpdate for every pixel since that would be a major bottleneck
                if (OnProgressUpdate == null || i % pbarModValue != 0)
                {
                    continue;
                }
                OnProgressUpdate.Invoke(this, new ApplyFilterProcessorEventArgs {
                    ThreadIndex = threadIndex, CurrentIndex = i, MinIndex = _fromPixel, MaxIndex = _toPixel, ProcessedPixelCount = loopCount
                });
            }
        }
Exemplo n.º 25
0
        // When connecting section A with section B, the Reduce method tries to better connect the "edges" of A and B.
        private CorrelaterResult <T> Reduce(List <Task <CorrelaterResult <T> > > resultTasks, CancellationToken cancellationToken)
        {
            var list1        = new List <T>();
            var list2        = new List <T>();
            var distance     = 0L;
            var endEdgeIndex = -1;

            for (var i = 0; i < resultTasks.Count; i++)
            {
                var result         = resultTasks[i].Result;
                var startEdgeIndex = i > 0 ? GetStartEdgeIndex(resultTasks[i].Result) : 0;
                if (i > 0)
                {
                    AddEdge(endEdgeIndex, startEdgeIndex, result, resultTasks[i - 1].Result, list1, list2, cancellationToken);
                }
                endEdgeIndex = GetEndEdgeIndex(result);

                distance += result.Distance;
                if (maxDistance.HasValue && distance > maxDistance.Value)
                {
                    return(null);
                }

                AddRange(result.BestMatch1, list1, startEdgeIndex, endEdgeIndex);
                AddRange(result.BestMatch2, list2, startEdgeIndex, endEdgeIndex);

                OnResultUpdate?.Invoke(GetPartualResult(result, startEdgeIndex, endEdgeIndex));
                OnProgressUpdate?.Invoke(i + 1, resultTasks.Count);

                if (i == resultTasks.Count - 1)
                {
                    AddFinalEdge(Math.Max(endEdgeIndex, startEdgeIndex), result, list1, list2);
                }
            }

            return(new CorrelaterResult <T>(distance, list1.ToArray(), list2.ToArray()));
        }
Exemplo n.º 26
0
        protected override CorrelaterResult <T> InternalCorrelate(ICollectionWrapper <T> collection1, ICollectionWrapper <T> collection2, CancellationToken cancellationToken = default)
        {
            var elementToLocationsInCollection2 = GetDictionaryFromElementToLocationsInCollection(collection2);

            var traceList = new TraceNode[collection1.Length + 1];

            var thresholds = new int[collection1.Length + 1];

            thresholds[0] = -1;
            for (var i = 1; i < thresholds.Length; i++)
            {
                thresholds[i] = thresholds.Length + 1;
            }

            for (var i = 0; i < collection1.Length; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();
                OnProgressUpdate?.Invoke(i + 1, collection1.Length);
                if (!elementToLocationsInCollection2.ContainsKey(collection1[i]))
                {
                    continue;
                }

                foreach (var j in elementToLocationsInCollection2[collection1[i]])
                {
                    var k = BinarySearchFindK(j, thresholds);
                    if (j < thresholds[k])
                    {
                        thresholds[k] = j;
                        traceList[k]  = new TraceNode(i, j, k > 0 ? traceList[k - 1] : null);
                    }
                }
            }

            return(GetResult(collection1, collection2, thresholds, traceList));
        }
Exemplo n.º 27
0
        public static AdjacencyGraph <Vertex, Edge <Vertex> > SolveUpdateOrder(
            this AdjacencyGraph <Vertex, Edge <Vertex> > componentGraph,
            out Vertex[] sortedVertices, bool invertMemory, bool retainParallel)
        {
            OnProgressUpdate?.Invoke(0.4f, "Preprocessing graph...");

            // Remove loops containing memory from graph
            componentGraph.PreprocessGraph(invertMemory, retainParallel);

            // Create Vertex list for sorted vertices
            sortedVertices = new Vertex[componentGraph.VertexCount];
            int head = componentGraph.VertexCount - 1;
            var tail = 0;

            // Create Dictionary to allow marking of vertices
            var marks = new Dictionary <int, Mark>();

            // Visit first unmarked Vertex
            Vertex first = componentGraph.Vertices.FirstOrDefault(vertex => !marks.ContainsKey(vertex.Id));

            while (!(first is null))
            {
                VisitDownstream(first, sortedVertices, ref head, ref tail, componentGraph, marks, invertMemory);
                first = componentGraph.Vertices.FirstOrDefault(vertex => !marks.ContainsKey(vertex.Id));
            }

            // Apply sorted list of IDs to graph
            List <int> sortedIDs = componentGraph.Vertices.OrderBy(v => v.Id).Select(v => v.Id).ToList();
            int        i         = 0;

            foreach (int id in sortedIDs)
            {
                sortedVertices[i++].Id = id; // Note: Can't sortedIDs in the foreach directly as componentGraph.Vertices and sortedVertices are linked
            }
            return(componentGraph);
        }
Exemplo n.º 28
0
 public LevenshteinCorrelater(IDistanceCalculator <T> distanceCalculator, IRemovalCalculator <T> removalCalculator, IInsertionCalculator <T> insertionCalculator)
 {
     correlater = new DamerauLevenshteinCorrelater <T>(distanceCalculator, null, removalCalculator, insertionCalculator);
     correlater.OnProgressUpdate += (p, t) => OnProgressUpdate?.Invoke(p, t);
 }
Exemplo n.º 29
0
 public static void Log(string msg, LogLevel level)
 {
     OnProgressUpdate?.Invoke(msg, level);
 }
Exemplo n.º 30
0
        public static async Task <QueryResult> QueryDevicesAsync()
        {
            // #0 get video controllers, used for cross checking
            var badVidCtrls = SystemSpecs.QueryVideoControllers();
            // Order important CPU Query must be first
            // #1 CPU
            var cpuDevs = CpuQuery.QueryCpus(out var failed64Bit, out var failedCpuCount);

            AvailableDevices.AddDevices(cpuDevs);

            // #2 CUDA

            OnProgressUpdate?.Invoke(null, Tr("Querying CUDA devices"));
            var nv     = new NvidiaQuery();
            var nvDevs = nv.QueryCudaDevices();

            if (nvDevs != null)
            {
                AvailableDevices.NumDetectedNvDevs = nvDevs.Count;

                if (ConfigManager.GeneralConfig.DeviceDetection.DisableDetectionNVIDIA)
                {
                    Helpers.ConsolePrint(Tag, "Skipping NVIDIA device detection, settings are set to disabled");
                }
                else
                {
                    AvailableDevices.AddDevices(nvDevs);
                }
            }

            // OpenCL and AMD

            var amd = new AmdQuery(AvailableDevices.NumDetectedNvDevs);

            // #3 OpenCL
            OnProgressUpdate?.Invoke(null, Tr("Querying OpenCL devices"));
            amd.QueryOpenCLDevices();
            // #4 AMD query AMD from OpenCL devices, get serial and add devices
            OnProgressUpdate?.Invoke(null, Tr("Checking AMD OpenCL GPUs"));
            var amdDevs = amd.QueryAmd(out var failedAmdDriverCheck);

            if (amdDevs != null)
            {
                AvailableDevices.NumDetectedAmdDevs = amdDevs.Count;

                if (ConfigManager.GeneralConfig.DeviceDetection.DisableDetectionAMD)
                {
                    Helpers.ConsolePrint(Tag, "Skipping AMD device detection, settings set to disabled");
                }
                else
                {
                    AvailableDevices.AddDevices(amdDevs);
                }
            }

            // #5 uncheck CPU if GPUs present, call it after we Query all devices
            AvailableDevices.UncheckCpuIfGpu();

            // TODO update this to report undetected hardware
            // #6 check NVIDIA, AMD devices count
            bool nvCountMatched;
            {
                var amdCount    = 0;
                var nvidiaCount = 0;
                foreach (var vidCtrl in SystemSpecs.AvailableVideoControllers)
                {
                    if (vidCtrl.IsNvidia)
                    {
                        if (CudaUnsupported.IsSupported(vidCtrl.Name))
                        {
                            nvidiaCount++;
                        }
                        else
                        {
                            Helpers.ConsolePrint(Tag,
                                                 "Device not supported NVIDIA/CUDA device not supported " + vidCtrl.Name);
                        }
                    }
                    else if (vidCtrl.IsAmd)
                    {
                        amdCount++;
                    }
                }

                nvCountMatched = nvidiaCount == AvailableDevices.NumDetectedNvDevs;

                Helpers.ConsolePrint(Tag,
                                     nvCountMatched
                        ? "Cuda NVIDIA/CUDA device count GOOD"
                        : "Cuda NVIDIA/CUDA device count BAD!!!");
                Helpers.ConsolePrint(Tag,
                                     amdCount == amdDevs?.Count ? "AMD GPU device count GOOD" : "AMD GPU device count BAD!!!");
            }

            var result = new QueryResult(NvidiaMinDetectionDriver.ToString(), NvidiaRecomendedDriver.ToString());

            var ramOK = CheckRam();

            if (!ConfigManager.GeneralConfig.ShowDriverVersionWarning)
            {
                return(result);
            }

            if (SystemSpecs.HasNvidiaVideoController)
            {
                var currentDriver = await NvidiaQuery.GetNvSmiDriverAsync();

                result.CurrentDriverString = currentDriver.ToString();
                result.FailedMinNVDriver   = !nvCountMatched && currentDriver < NvidiaMinDetectionDriver;

                result.FailedRecommendedNVDriver = currentDriver <NvidiaRecomendedDriver && currentDriver.LeftPart> -1;
            }

            result.NoDevices = AvailableDevices.Devices.Count <= 0;

            result.FailedRamCheck = !ramOK;

            foreach (var failedVc in badVidCtrls)
            {
                result.FailedVidControllerStatus = true;
                result.FailedVidControllerInfo  +=
                    $"{Tr("Name: {0}, Status {1}, PNPDeviceID {2}", failedVc.Name, failedVc.Status, failedVc.PnpDeviceID)}\n";
            }

            result.FailedAmdDriverCheck = failedAmdDriverCheck;

            result.FailedCpu64Bit = failed64Bit;
            result.FailedCpuCount = failedCpuCount;

            return(result);
        }