Пример #1
0
        private void ExtractHashes(RunnablePip runnable, List <FileArtifactKeyedHash> hashes)
        {
            var  step           = runnable.Step;
            bool requiresHashes = step == PipExecutionStep.MaterializeInputs ||
                                  step == PipExecutionStep.MaterializeOutputs ||
                                  step == PipExecutionStep.CacheLookup;

            if (!requiresHashes)
            {
                return;
            }

            var  environment          = runnable.Environment;
            bool materializingOutputs = step == PipExecutionStep.MaterializeOutputs;

            // The block below collects process input file artifacts and hashes
            // Currently there is no logic to keep from sending the same hashes twice
            // Consider a model where hashes for files are requested by worker
            using (var pooledFileSet = Pools.GetFileArtifactSet())
                using (var pooledDynamicFileMultiDirectoryMap = Pools.GetFileMultiDirectoryMap())
                {
                    var pathTable    = environment.Context.PathTable;
                    var files        = pooledFileSet.Instance;
                    var dynamicFiles = pooledDynamicFileMultiDirectoryMap.Instance;

                    using (m_masterService.Environment.Counters.StartStopwatch(PipExecutorCounter.RemoteWorker_CollectPipFilesToMaterializeDuration))
                    {
                        environment.State.FileContentManager.CollectPipFilesToMaterialize(
                            isMaterializingInputs: !materializingOutputs,
                            pipTable: environment.PipTable,
                            pip: runnable.Pip,
                            files: files,
                            dynamicFileMap: dynamicFiles,

                            // Only send content which is not already on the worker.
                            // TryAddAvailableHash can return null if the artifact is dynamic file in which case
                            // the file cannot be added to the set due to missing index (note that we're using ContentTrackingSet as the underlying set).
                            // In such a case we decide to include the artifact during the collection.
                            shouldInclude: artifact => TryAddAvailableHash(artifact) ?? true,
                            shouldIncludeServiceFiles: servicePipId => TryAddAvailableHash(servicePipId) ?? true);
                    }

                    using (m_masterService.Environment.Counters.StartStopwatch(PipExecutorCounter.RemoteWorker_CreateFileArtifactKeyedHashDuration))
                    {
                        // Now we have to consider both dynamicFiles map and files set so we union into the files set. If we only rely on files, then the following incorrect build can happen.
                        // Suppose that we have pip P that specifies D as an opaque output directory and D\f as an output file. Pip Q consumes D\f directly (not via directory dependency on D).
                        // Pip R consumes D. Suppose that the cache lookup's for Q and R happen on the same machine. Suppose that Q is processed first, TryAddAvailableHash(D/f)
                        // returns true because it's a declared output and it's added into the files set. Now, on processing R later, particularly in
                        // collecting the files of D to materialize, D\f is not included in the files set because TryAddAvailableHash(D/f) returns false, i.e.,
                        // it's a declared output and it's been added when processing Q. However, D/f is still populated to the dynamicFiles map.
                        files.UnionWith(dynamicFiles.Keys);

                        foreach (var file in files)
                        {
                            var  fileMaterializationInfo = environment.State.FileContentManager.GetInputContent(file);
                            bool isDynamicFile           = dynamicFiles.TryGetValue(file, out var dynamicDirectories) && dynamicDirectories.Count != 0;

                            var hash = new FileArtifactKeyedHash
                            {
                                RewriteCount = file.RewriteCount,
                                PathValue    = file.Path.Value.Value,
                                PathString   = isDynamicFile ? file.Path.ToString(pathTable) : null,
                            }.SetFileMaterializationInfo(pathTable, fileMaterializationInfo);

                            if (isDynamicFile)
                            {
                                hash.AssociatedDirectories = new List <BondDirectoryArtifact>();

                                foreach (var dynamicDirectory in dynamicDirectories)
                                {
                                    hash.AssociatedDirectories.Add(new BondDirectoryArtifact
                                    {
                                        // Path id of dynamic directory input can be sent to the remote worker because it appears in the pip graph, and thus in path table.
                                        DirectoryPathValue      = dynamicDirectory.Path.RawValue,
                                        DirectorySealId         = dynamicDirectory.PartialSealId,
                                        IsDirectorySharedOpaque = dynamicDirectory.IsSharedOpaque
                                    });
                                }
                            }

                            lock (m_hashListLock)
                            {
                                hashes.Add(hash);
                            }
                        }
                    }
                }
        }
Пример #2
0
        /// <inheritdoc />
        protected override void OnInformational(EventWrittenEventArgs eventData)
        {
            switch (eventData.EventId)
            {
            case (int)EventId.StartEngineRun:
            {
                m_console.ReportProgress((ulong)(m_notWorker ? 0 : 100), 100);
                break;
            }

            case (int)EventId.EndEngineRun:
            {
                m_console.ReportProgress(100, 100);
                break;
            }

            case (int)EventId.PipStatus:
            case (int)BuildXL.Scheduler.Tracing.LogEventId.PipStatusNonOverwriteable:
            {
                ReadOnlyCollection <object> payload = eventData.Payload;

                var    pipsSucceeded          = (long)payload[0];
                var    pipsFailed             = (long)payload[1];
                var    pipsSkipped            = (long)payload[2];
                var    pipsRunning            = (long)payload[3];
                var    pipsReady              = (long)payload[4];
                var    pipsWaiting            = (long)payload[5];
                var    pipsWaitingOnSemaphore = (long)payload[6];
                var    servicePipsRunning     = (long)payload[7];
                string perfInfo = (string)payload[8];
                var    pipsWaitingOnResources = (long)payload[9];
                var    procsExecuting         = (long)payload[10];
                var    procsSucceeded         = (long)payload[11];
                var    procsFailed            = (long)payload[12];
                var    procsSkipped           = (long)payload[13];
                var    procsPending           = (long)payload[14];
                var    procsWaiting           = (long)payload[15];
                var    procsHit         = (long)payload[16];
                var    procsNotIgnored  = (long)payload[17];
                var    copyFileDone     = (long)payload[20];
                var    copyFileNotDone  = (long)payload[21];
                var    writeFileDone    = (long)payload[22];
                var    writeFileNotDone = (long)payload[23];
                long   done             = pipsSucceeded + pipsFailed + pipsSkipped;
                long   total            = done + pipsRunning + pipsWaiting + pipsReady;

                long procsDone  = procsSucceeded + procsFailed + procsSkipped;
                long procsTotal = procsDone + procsPending + procsWaiting + procsExecuting;

                long filePipsDone  = copyFileDone + writeFileDone;
                long filePipsTotal = filePipsDone + copyFileNotDone + writeFileNotDone;

                // For sake of simplicity, both pending & waiting processes are labeled as "waiting" in the console
                long pendingAndWaiting = procsPending + procsWaiting;

                using (PooledObjectWrapper <StringBuilder> wrap = Pools.GetStringBuilder())
                {
                    StringBuilder sb = wrap.Instance;

                    // Only show cache hits when this isn't a worker.
                    sb.Append(m_notWorker ? @"{{9,{0}}}Processes:[{{4,{0}}} done ({{5}} hit)," : @" {{4,{0}}} done,");

                    if (pipsFailed > 0)
                    {
                        sb.Append(@" {{0,{0}}} succeeded, {{1,{0}}} failed,");
                    }

                    if (pipsSkipped > 0)
                    {
                        sb.Append(@" {{6,{0}}} skipped,");
                    }

                    sb.Append(@" {{8,{0}}} executing, {{2,{0}}} waiting]");

                    if (pipsWaitingOnSemaphore > 0)
                    {
                        sb.Append(@" ({{3,{0}}} on semaphores).");
                    }

                    if (servicePipsRunning > 0)
                    {
                        sb.Append(@". Services: {{7}}.");
                    }

                    if (filePipsTotal > 0)
                    {
                        sb.Append(@" Files:[{{12}}/{{13}}]");
                    }

                    string statusLine = sb.ToString();
                    sb.Length = 0;

                    var format = FinalizeFormatStringLayout(sb, statusLine, 0);

                    sb.AppendFormat(
                        CultureInfo.InvariantCulture,
                        format,
                        procsSucceeded,
                        procsFailed,
                        pendingAndWaiting,
                        pipsWaitingOnSemaphore,
                        procsDone,
                        procsHit,
                        procsSkipped,
                        servicePipsRunning,
                        procsExecuting,
                        ComputePercentDone(procsDone, procsTotal, filePipsDone, filePipsTotal),
                        done,
                        total,
                        filePipsDone,
                        filePipsTotal);

                    if (pipsWaitingOnResources > 0)
                    {
                        sb.AppendLine();
                        sb.AppendFormat(
                            CultureInfo.InvariantCulture,
                            Strings.ConsoleListener_PipsResourceWaitingStatusLine,
                            pipsWaitingOnResources);
                    }

                    string standardStatus = sb.ToString();
                    string updatingStatus = GetRunningPipsMessage(standardStatus, perfInfo);
                    SendToConsole(eventData, "info", standardStatus, updatingStatus);
                }

                if (m_notWorker)
                {
                    m_console.ReportProgress((ulong)done, (ulong)total);
                }

                break;
            }

            case (int)EventId.DisplayHelpLink:
            {
                m_console.WriteOutputLine(MessageLevel.Info, Strings.DX_Help_Link_Prefix + " " + Strings.DX_Help_Link);

                break;
            }

            default:
            {
                SendToConsole(eventData, "info", eventData.Message);
                break;
            }
            }
        }
Пример #3
0
            public static bool TryParse(
                string line,
                out ulong processId,
                out uint reportStatus,
                out string processName,
                out string startApplicationName,
                out string startCommandLine,
                out bool needsInjection,
                out bool isCurrent64BitProcess,
                out bool isCurrentWow64Process,
                out bool isProcessWow64,
                out bool needsRemoteInjection,
                out ulong hJob,
                out bool disableDetours,
                out uint creationFlags,
                out bool detoured,
                out uint error,
                out uint createProcessStatusReturn,
                out string errorMessage)
            {
                reportStatus          = 0;
                needsInjection        = false;
                isCurrent64BitProcess = false;
                isCurrentWow64Process = false;
                isProcessWow64        = false;
                needsRemoteInjection  = false;
                disableDetours        = false;
                detoured = false;
                createProcessStatusReturn = 0;
                error                = 0;
                creationFlags        = 0;
                hJob                 = 0L;
                processName          = default;
                processId            = 0;
                startApplicationName = default;
                startCommandLine     = default;
                errorMessage         = string.Empty;

                var items = line.Split('|');

                // A "process data" report is expected to have exactly 14 items. 1 for the process id,
                // 1 for the command line (last item) and 12 numbers indicating the various counters and
                // execution times.
                // If this assert fires, it indicates that we could not successfully parse (split) the data being
                // sent from the detour (SendReport.cpp).
                // Make sure the strings are formatted only when the condition is false.
                if (items.Length < 16)
                {
                    errorMessage = I($"Unexpected message items (potentially due to pipe corruption). Message '{line}'. Expected >= 12 items, Received {items.Length} items");
                    return(false);
                }

                if (items.Length == 16)
                {
                    startCommandLine = items[15];
                }
                else
                {
                    System.Text.StringBuilder builder = Pools.GetStringBuilder().Instance;
                    for (int i = 15; i < items.Length; i++)
                    {
                        if (i > 15)
                        {
                            builder.Append("|");
                        }

                        builder.Append(items[i]);
                    }

                    startCommandLine = builder.ToString();
                }

                processName          = items[2];
                startApplicationName = items[3];

                uint uintNeedsInjection;
                uint uintIsCurrent64BitProcess;
                uint uintIsCurrentWow64Process;
                uint uintIsProcessWow64;
                uint uintNeedsRemoteInjection;
                uint uintDisableDetours;
                uint uintDetoured;

                if (ulong.TryParse(items[0], NumberStyles.None, CultureInfo.InvariantCulture, out processId) &&
                    uint.TryParse(items[1], NumberStyles.None, CultureInfo.InvariantCulture, out reportStatus) &&
                    uint.TryParse(items[4], NumberStyles.None, CultureInfo.InvariantCulture, out uintNeedsInjection) &&
                    uint.TryParse(items[5], NumberStyles.None, CultureInfo.InvariantCulture, out uintIsCurrent64BitProcess) &&
                    uint.TryParse(items[6], NumberStyles.None, CultureInfo.InvariantCulture, out uintIsCurrentWow64Process) &&
                    uint.TryParse(items[7], NumberStyles.None, CultureInfo.InvariantCulture, out uintIsProcessWow64) &&
                    uint.TryParse(items[8], NumberStyles.None, CultureInfo.InvariantCulture, out uintNeedsRemoteInjection) &&
                    ulong.TryParse(items[9], NumberStyles.None, CultureInfo.InvariantCulture, out hJob) &&
                    uint.TryParse(items[10], NumberStyles.None, CultureInfo.InvariantCulture, out uintDisableDetours) &&
                    uint.TryParse(items[11], NumberStyles.None, CultureInfo.InvariantCulture, out creationFlags) &&
                    uint.TryParse(items[12], NumberStyles.None, CultureInfo.InvariantCulture, out uintDetoured) &&
                    uint.TryParse(items[13], NumberStyles.None, CultureInfo.InvariantCulture, out error) &&
                    uint.TryParse(items[14], NumberStyles.None, CultureInfo.InvariantCulture, out createProcessStatusReturn))
                {
                    needsInjection        = uintNeedsInjection != 0;
                    isCurrent64BitProcess = uintIsCurrent64BitProcess != 0;
                    isCurrentWow64Process = uintIsCurrentWow64Process != 0;
                    isProcessWow64        = uintIsProcessWow64 != 0;
                    needsRemoteInjection  = uintNeedsRemoteInjection != 0;
                    disableDetours        = uintDisableDetours != 0;
                    detoured = uintDetoured != 0;
                    return(true);
                }

                return(false);
            }
Пример #4
0
            /// <summary>
            /// The result contains estimated amount of work for each worker
            /// </summary>
            public void EstimateAndSortSetupCostPerWorker(RunnablePip runnablePip)
            {
                if (m_context.MustRunOnMaster(runnablePip))
                {
                    // Only estimate setup costs for pips which can execute remotely
                    return;
                }

                var pip = runnablePip.Pip;

                InitializeWorkerSetupCost(pip);

                // The block below collects process input file artifacts and hashes
                // Currently there is no logic to keep from sending the same hashes twice
                // Consider a model where hashes for files are requested by worker
                using (var pooledFileSet = Pools.GetFileArtifactSet())
                {
                    var pipInputs = pooledFileSet.Instance;
                    m_context.m_fileContentManager.CollectPipInputsToMaterialize(
                        m_context.m_pipTable,
                        pip,
                        pipInputs,

                        // Service pip cost is not considered as this is shared among many clients and is a one-time cost per worker
                        serviceFilter: servicePipId => false);

                    m_visitedHashes.Clear();

                    foreach (var fileInput in pipInputs)
                    {
                        if (!fileInput.IsOutputFile)
                        {
                            continue;
                        }

                        if (pip.PipType == PipType.Ipc && !m_context.m_executedProcessOutputs.Contains(fileInput))
                        {
                            // Only executed process outputs are considered for IPC pip affinity
                            continue;
                        }

                        FileContentInfo fileContentInfo = m_context.m_fileContentManager.GetInputContent(fileInput).FileContentInfo;
                        if (!m_visitedHashes.Add(fileContentInfo.Hash))
                        {
                            continue;
                        }

                        // How many bytes we have to copy.
                        long fileSize = fileContentInfo.HasKnownLength ? fileContentInfo.Length : TypicalFileLength;

                        for (int idx = 0; idx < m_context.Workers.Count; ++idx)
                        {
                            if (!WorkerSetupCosts[idx].Worker.HasContent(fileInput))
                            {
                                WorkerSetupCosts[idx].SetupBytes += fileSize;
                            }
                        }
                    }
                }

                Array.Sort(WorkerSetupCosts);
            }
Пример #5
0
        public override int Analyze()
        {
            Console.WriteLine($"FileConsumptionAnalyzer: Starting analysis at {DateTime.Now}.");

            int totalDeclaredInputFiles = 0, totalDeclaredInputDirectories = 0, totalConsumedFiles = 0, totalActualProcessPips = 0;

            Parallel.ForEach(
                m_executedProcessPips.Keys,
                new ParallelOptions()
            {
                MaxDegreeOfParallelism = 1
            },                                                       //Environment.ProcessorCount },
                pipId =>
            {
                var pip                = m_executedProcessPips[pipId];
                long totalInputSize    = 0;
                long totalConsumedSize = 0;

                if (pip.Worker == null)
                {
                    // this pip was not executed (i.e., cache hit)
                    pip.ConsumedInputSize = -1;
                    pip.DeclaredInputSize = -1;
                    return;
                }

                totalActualProcessPips++;

                using (var pooledSetInputFiles = Pools.GetAbsolutePathSet())
                    using (var pooledSetConsumedFiles = Pools.GetAbsolutePathSet())
                    {
                        var inputFiles    = pooledSetInputFiles.Instance;
                        var consumedFiles = pooledSetConsumedFiles.Instance;

                        // BXL executed this pip, so we can safely assume that its inputs were materialized.
                        foreach (var path in pip.DeclaredInputFiles)
                        {
                            if (m_fileSizes.TryGetValue(path, out var size))
                            {
                                conditionallyAddValue(ref totalInputSize, size, path, inputFiles);
                                conditionallyAddValue(ref totalConsumedSize, size, path, consumedFiles);
                                pip.Worker.AddFlag(path, ContentFlag.Materialized);
                            }
                        }
                        totalDeclaredInputFiles += pip.DeclaredInputFiles.Count;

                        foreach (var directoryArtifact in pip.DeclaredInputDirectories)
                        {
                            if (m_dynamicDirectoryContent.TryGetValue(directoryArtifact, out var directoryContent))
                            {
                                pip.Worker.AddFlag(directoryArtifact, ContentFlag.Materialized);

                                foreach (var path in directoryContent)
                                {
                                    if (m_fileSizes.TryGetValue(path, out var size))
                                    {
                                        conditionallyAddValue(ref totalInputSize, size, path, inputFiles);
                                    }
                                }
                            }
                        }
                        totalDeclaredInputDirectories += pip.DeclaredInputDirectories.Count;

                        foreach (var path in pip.ConsumedFiles)
                        {
                            if (m_fileSizes.TryGetValue(path, out var size))
                            {
                                conditionallyAddValue(ref totalConsumedSize, size, path, consumedFiles);

                                if (m_producedFiles.ContainsKey(path))
                                {
                                    m_producedFiles.AddOrUpdate(
                                        path,
                                        _ => throw new Exception(),
                                        (_, file) =>
                                    {
                                        file.Consumers.Enqueue(pipId);
                                        return(file);
                                    });
                                }
Пример #6
0
        internal static void ProcessResults(JProperty[] results, int maxLogSize, LoggingContext loggingContext)
        {
            using (var sbPool = Pools.GetStringBuilder())
            {
                var sb         = sbPool.Instance;
                var sw         = new StringWriter(sb);
                var writer     = new JsonTextWriter(sw);
                var logStarted = false;
                var lenSum     = 0;
                for (int i = 0; i < results.Length;)
                {
                    if (!logStarted)
                    {
                        writer.WriteStartObject();
                        writer.WritePropertyName("CacheMissAnalysisResults");
                        writer.WriteStartObject();
                        logStarted = true;
                    }

                    var name  = results[i].Name.ToString();
                    var value = results[i].Value.ToString();
                    lenSum += name.Length + value.Length;
                    if (lenSum < maxLogSize)
                    {
                        writeProperty(name, value);
                        i++;
                    }
                    else
                    {
                        // Give warning instead of a single result if max length exceeded,
                        // otherwise finish this batch without i++.
                        // So this item will go to next batch.
                        if ((name.Length + value.Length) > maxLogSize)
                        {
                            writeProperty(name, "Warning: The actual cache miss analysis result is too long to present.");
                            i++;
                        }
                        lenSum = 0;
                        endLogging();
                    }
                }

                endLogging();

                void writeProperty(string name, string value)
                {
                    writer.WritePropertyName(name);
                    writer.WriteRawValue(value);
                }

                void endLogging()
                {
                    // Only log when at least one result has been written to the Json string
                    if (logStarted)
                    {
                        writer.WriteEndObject();
                        writer.WriteEndObject();
                        logStarted = false;
                        Logger.Log.CacheMissAnalysisBatchResults(loggingContext, sw.ToString());
                    }
                }
            }
        }
Пример #7
0
 public void Clear()
 {
     Pools.Clear();
     ArrayPools.Clear();
 }
Пример #8
0
 void Start()
 {
     Pools.sharedInstance.visualDebugging = Pools.CreateVisualDebuggingPool();
     Pools.sharedInstance.visualDebugging.GetGroup(VisualDebuggingMatcher.MyInt);
     _entity = Pools.sharedInstance.visualDebugging.CreateEntity();
 }
Пример #9
0
 public void SetPools(Pools pools)
 {
     _pools = pools;
     _pools.core.GetGroup(Matcher.AllOf(CoreMatcher.Controlable, CoreMatcher.Move)).OnEntityRemoved   += OnAcitveAI;
     _pools.core.GetGroup(Matcher.AllOf(CoreMatcher.Controlable, CoreMatcher.Attack)).OnEntityRemoved += OnAcitveAI;
 }
Пример #10
0
 public void SetPools(Pools pools)
 {
     _coolDowns = pools.core.GetGroup(CoreMatcher.BulletCoolDown);
 }
Пример #11
0
        /// <summary>
        /// Der eigentliche Mosaikgenerator. Liest Kacheln aus und fuegt diese an die passenden Stellen fuer das Originalbild ein
        /// </summary>
        /// <param name="basisMotivID">Die ID des Basismotivs</param>
        /// <param name="kachelPoolID">Die ID des Kachelpools</param>
        /// <param name="mosaikPoolID">Die ID des Mosaikpools (in dem das Bild gespeichert wird)</param>
        /// <param name="kachelnMultiUseEnabled">Sollen Kacheln mehrfach genutzt werden duerfen?</param>
        /// <param name="auswahlNBesteKacheln">Aus wievielen der besten Bilder soll ein zufaelliges ausgewaehlt werden?</param>
        public bool mosaikGenerator(int basisMotivID, int kachelPoolID, int mosaikPoolID, Boolean kachelnMultiUseEnabled = true, int auswahlNBesteKacheln = 1)
        {
            printToConsole("MosaikStart! (" + basisMotivID + "--" + kachelPoolID + "--" + mosaikPoolID + "--" + auswahlNBesteKacheln + ")", ConsolePrintTypes.INFO);

            // Pruefe ob alle wichtigen Parameter richtig gesetzt sind
            if (basisMotivID < 1 && kachelPoolID < 1 && mosaikPoolID < 1 && auswahlNBesteKacheln < 1)
            {
                printToConsole("Falscher Parameter - Abbruch! (" + basisMotivID + "--" + kachelPoolID + "--" + mosaikPoolID + "--" + auswahlNBesteKacheln + ")", ConsolePrintTypes.ERROR);
                return(false);
            }

            // Lade das Basismotiv in eine Bitmap
            Bitmap basisMotiv = openImage(basisMotivID);

            // Wenn basisMotiv null ist dann gab es einen Fehler beim laden des Bildes
            if (basisMotiv == null)
            {
                printToConsole("Basismotiv nicht gefunden - Abbruch!", ConsolePrintTypes.ERROR);
                return(false);
            }

            // Lade die Kachel-Poolinformationen aus der Datenbank
            Pools kachelPool = db.PoolsSet.Find(kachelPoolID);

            // Berechne die Anzahl aller Pixel
            int pixel = basisMotiv.Height * basisMotiv.Width;

            // Prüfe ob genug Kacheln im Pool sind
            // Wenn Kacheln nur einmalig erlaubt sind, muss geprueft werden ob genug vorhanden sind
            if (!kachelnMultiUseEnabled)
            {
                // Wenn weniger Kacheln als Pixel vorhanden sind...
                if (db.ImagesSet.Count <Images>() < pixel)
                {
                    basisMotiv.Dispose();
                    printToConsole("Zu wenig Kacheln im Pool!", ConsolePrintTypes.ERROR);
                    return(false);
                }
            }

            // lege ein neues Bild mit der neuen Groesse an
            // Berechnung in der Dokumentation
            Bitmap mosaik = new Bitmap((basisMotiv.Size.Width * kachelPool.size), (basisMotiv.Size.Height * kachelPool.size));

            // Falls Kacheln nur einmalig genutzt werden duerfen, muessen diese vermerkt werden
            List <int> usedKacheln = new List <int>();

            // Es soll eine Liste vorhanden sein die aus den N besten Bildern ein zufaelliges auswaehlt
            Dictionary <int, double> nKacheln = new Dictionary <int, double>();

            // Hole alle Bilder aus dem Pool
            Kacheln[] poolBilder = db.ImagesSet.OfType <Kacheln>().Where(p => p.PoolsId == kachelPoolID).ToArray();

            // Lege die Variablen zur Berechnung an
            Color  pixelFarbe;
            Random rnd = new Random();
            Bitmap thisKachel;
            int    bestfit;
            int    differenzRot   = 0;
            int    differenzGruen = 0;
            int    differenzBlau  = 0;

            // gehe jeden einzelnen Pixel des Originalbildes durch
            for (int i = 1; i < basisMotiv.Size.Width + 1; i++)
            {
                for (int j = 1; j < basisMotiv.Size.Height + 1; j++)
                {
                    // Lade die Farbwerte des aktuellen Pixels
                    pixelFarbe = basisMotiv.GetPixel(i - 1, j - 1);

                    // Gehe jedes Bild im Pool durch und pruefe ob es gut dorthin passt
                    for (int k = 0; k < poolBilder.Length; k++)
                    {
                        // Wenn Kacheln Multi disabled ist & die Kachel schonmal
                        // genutzt wurde soll der folgende Teil ignoriert werden
                        if (kachelnMultiUseEnabled || (!kachelnMultiUseEnabled && !usedKacheln.Contains(poolBilder[k].Id)))
                        {
                            // Berechne die drei jeweiligen (positiven) Differenzen
                            if (poolBilder[k].avgR > pixelFarbe.R)
                            {
                                differenzRot = poolBilder[k].avgR - pixelFarbe.R;
                            }
                            else
                            {
                                differenzRot = pixelFarbe.R - poolBilder[k].avgR;
                            }

                            if (poolBilder[k].avgG > pixelFarbe.G)
                            {
                                differenzGruen = poolBilder[k].avgG - pixelFarbe.G;
                            }
                            else
                            {
                                differenzGruen = pixelFarbe.G - poolBilder[k].avgG;
                            }

                            if (poolBilder[k].avgB > pixelFarbe.B)
                            {
                                differenzBlau = poolBilder[k].avgB - pixelFarbe.B;
                            }
                            else
                            {
                                differenzBlau = pixelFarbe.B - poolBilder[k].avgB;
                            }

                            // Rechne den Farbabstand aus (Formel aus den Hinweisen zur Hausarbeit)
                            double farbAbstand = Math.Sqrt((double)(differenzRot * differenzRot) + (differenzGruen * differenzGruen) + (differenzBlau * differenzBlau));

                            // Wenn noch Platz in dem N-Kachel-Array ist, lege den Wert ab
                            if (auswahlNBesteKacheln > nKacheln.Count)
                            {
                                nKacheln.Add(poolBilder[k].Id, farbAbstand);
                            }
                            else
                            {
                                // Ermittle den schlechtesten Wert in den N-Kacheln
                                double schlechtesterWert = 0;
                                int    index             = -1;

                                // Gehe alle Elemente durch und finde den schlechtesten Wert
                                // Dieser muss GRÖSSER als die anderen sein, da der ABSTAND möglichst niedrig sein soll
                                foreach (var nKachel in nKacheln)
                                {
                                    if (nKachel.Value > schlechtesterWert)
                                    {
                                        index             = nKachel.Key;
                                        schlechtesterWert = nKachel.Value;
                                    }
                                }

                                // Wenn das ergebnis besser ist als der schlechteste Wert
                                if (farbAbstand < schlechtesterWert)
                                {
                                    // Entferne das schlechteste Element
                                    nKacheln.Remove(index);

                                    // Fuege die neue nKachel hinzu
                                    nKacheln.Add(poolBilder[k].Id, farbAbstand);
                                }
                            }
                        }
                    }

                    // Hier wurden alle Bilder im Pool für einen Pixel durchsucht
                    // Hole nur die Keys aus der Liste
                    List <int> keys = Enumerable.ToList(nKacheln.Keys);

                    // Waehle ein zufaelligen Key - und damit auch das einzusetzende Bild
                    bestfit = keys[rnd.Next(nKacheln.Count)];

                    // Bereinige die NKacheln damit sie beim nächsten durchlauf nicht nochmal vorkommen :D
                    nKacheln.Clear();

                    // Wenn Kacheln nur einmal genutzt werden sollen, muss diese Kachel gespeichert werden
                    if (!kachelnMultiUseEnabled)
                    {
                        usedKacheln.Add(bestfit);
                    }

                    // Lade die Kachel
                    thisKachel = openImage(bestfit);

                    // Wenn basisMotiv null ist dann gab es einen Fehler beim laden des Bildes
                    if (thisKachel == null)
                    {
                        printToConsole("Kachel (" + bestfit + ") nicht gefunden - Abbruch!", ConsolePrintTypes.ERROR);
                        return(false);
                    }

                    // Füge nun jeden einzelnen Pixel an seiner dafür vorgesehnen Position ein
                    for (int x = 0; x < kachelPool.size; x++)
                    {
                        for (int y = 0; y < kachelPool.size; y++)
                        {
                            // Lade die Farbwerte des aktuellen Pixels
                            pixelFarbe = thisKachel.GetPixel(x, y);

                            // Und Fuege in an die richtige Position im neuen Mosaikbild ein
                            mosaik.SetPixel((((i - 1) * kachelPool.size) + x), (((j - 1) * kachelPool.size) + y), pixelFarbe);
                        }
                    }
                }
            }

            // Generiere eine Einzigartige Bezeichnung
            String UUID = Guid.NewGuid().ToString();

            // Speichere das Bild ab
            mosaik.Save(IMAGEPATH + "Motive\\" + UUID + ".png");

            var image = db.Set <Motive>();

            image.Add(new Motive {
                displayname = "Mosaik", filename = UUID + ".png", path = "Motive\\", heigth = (basisMotiv.Size.Height * kachelPool.size), width = (basisMotiv.Size.Width * kachelPool.size), hsv = "000", PoolsId = mosaikPoolID, writelock = false
            });

            // Speichere die DB
            db.SaveChanges();

            return(true);
        }
Пример #12
0
 public void SetPools(Pools pools)
 {
     _pools         = new [] { pools.core, pools.bullets };
     _groupObserver = _pools.CreateEntityCollector(Matcher.AnyOf(CoreMatcher.Destroy, CoreMatcher.OutOfScreen));
 }
Пример #13
0
        internal static void ProcessResults(JProperty[] results, IConfiguration configuration, LoggingContext loggingContext)
        {
            int maxLogSize = configuration.Logging.AriaIndividualMessageSizeLimitBytes;

            using (var sbPool = Pools.GetStringBuilder())
            {
                var sb = sbPool.Instance;
                using var sw     = new StringWriter(sb);
                using var writer = new JsonTextWriter(sw);
                var logStarted  = false;
                var hasProperty = false;
                var lenSum      = 0;
                for (int i = 0; i < results.Length; i++)
                {
                    startLoggingIfNot();

                    var name  = results[i].Name.ToString();
                    var value = results[i].Value.ToString();
                    lenSum += name.Length + value.Length;
                    if (lenSum < maxLogSize)
                    {
                        writeProperty(name, value);
                    }
                    else
                    {
                        // End the current batch before start a new one.
                        endLoggingIfStarted();

                        // Log a single event, if this single result itself is too big.
                        if ((name.Length + value.Length) >= maxLogSize)
                        {
                            // Have to shorten the result to fit the telemetry.
                            var marker = "[...]";
                            var prefix = value.Substring(0, maxLogSize / 2);
                            var suffix = value.Substring(value.Length - maxLogSize / 2);
                            logAsSingle(name, prefix + marker + suffix);
                        }
                        else
                        {
                            // Start a new batch.
                            startLoggingIfNot();
                            writeProperty(name, value);
                            lenSum = name.Length + value.Length;
                        }
                    }
                }

                endLoggingIfStarted();

                void writeProperty(string name, string value)
                {
                    writer.WritePropertyName(name);
                    writer.WriteRawValue(value);
                    hasProperty = true;
                }

                void endLogging()
                {
                    writer.WriteEndObject();
                    writer.WriteEndObject();
                    // Only log when has result in it.
                    if (hasProperty)
                    {
                        Logger.Log.CacheMissAnalysisBatchResults(loggingContext, sw.ToString());
                    }
                    logStarted  = false;
                    hasProperty = false;
                    lenSum      = 0;
                    writer.Flush();
                    sb.Clear();
                }

                void endLoggingIfStarted()
                {
                    // Only log when at least one result has been written to the Json string
                    if (logStarted)
                    {
                        endLogging();
                    }
                }

                void startLogging()
                {
                    writer.Flush();
                    sb.Clear();
                    writer.WriteStartObject();
                    writer.WritePropertyName("CacheMissAnalysisResults");
                    writer.WriteStartObject();
                    logStarted = true;
                }

                void startLoggingIfNot()
                {
                    // Only log when at least one result has been written to the Json string
                    if (!logStarted)
                    {
                        startLogging();
                    }
                }

                void logAsSingle(string name, string value)
                {
                    startLogging();
                    writeProperty(name, value);
                    endLogging();
                }
            }
        }
Пример #14
0
        private static Dictionary <uint, ReportedProcess> GetSurvivingChildProcesses(JobObject jobObject)
        {
            if (!jobObject.TryGetProcessIds(out uint[] survivingChildProcessIds) || survivingChildProcessIds.Length == 0)
            {
                return(null);
            }

            var survivingChildProcesses = new Dictionary <uint, ReportedProcess>();

            foreach (uint processId in survivingChildProcessIds)
            {
                using (SafeProcessHandle processHandle = ProcessUtilities.OpenProcess(
                           ProcessSecurityAndAccessRights.PROCESS_QUERY_INFORMATION |
                           ProcessSecurityAndAccessRights.PROCESS_VM_READ,
                           false,
                           processId))
                {
                    if (processHandle.IsInvalid)
                    {
                        // we are too late: could not open process
                        continue;
                    }

                    if (!jobObject.ContainsProcess(processHandle))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    int exitCode;
                    if (!ProcessUtilities.GetExitCodeProcess(processHandle, out exitCode))
                    {
                        // we are too late: process id got reused by another process
                        continue;
                    }

                    using (PooledObjectWrapper <StringBuilder> wrap = Pools.GetStringBuilder())
                    {
                        StringBuilder sb = wrap.Instance;
                        if (sb.Capacity < MaxProcessPathLength)
                        {
                            sb.Capacity = MaxProcessPathLength;
                        }

                        if (ProcessUtilities.GetModuleFileNameEx(processHandle, IntPtr.Zero, sb, (uint)sb.Capacity) <= 0)
                        {
                            // we are probably too late
                            continue;
                        }

                        // Attempt to read the process arguments (command line) from the process
                        // memory. This is not fatal if it does not succeed.
                        string processArgs = string.Empty;

                        var  basicInfoSize = (uint)Marshal.SizeOf <Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>();
                        var  basicInfoPtr  = Marshal.AllocHGlobal((int)basicInfoSize);
                        uint basicInfoReadLen;
                        try
                        {
                            if (Native.Processes.Windows.ProcessUtilitiesWin.NtQueryInformationProcess(
                                    processHandle,
                                    Native.Processes.Windows.ProcessUtilitiesWin.ProcessInformationClass.ProcessBasicInformation,
                                    basicInfoPtr, basicInfoSize, out basicInfoReadLen) == 0)
                            {
                                Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION basicInformation = Marshal.PtrToStructure <Native.Processes.Windows.ProcessUtilitiesWin.PROCESS_BASIC_INFORMATION>(basicInfoPtr);
                                Contract.Assert(basicInformation.UniqueProcessId == processId);

                                // NativeMethods.ReadProcessStructure and NativeMethods.ReadUnicodeString handle null\zero addresses
                                // passed into them. Since these are all value types, then there is no need to do any type
                                // of checking as passing zero through will just result in an empty process args string.
                                var peb = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure <Native.Processes.Windows.ProcessUtilitiesWin.PEB>(processHandle, basicInformation.PebBaseAddress);
                                var processParameters = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessStructure <Native.Processes.Windows.ProcessUtilitiesWin.RTL_USER_PROCESS_PARAMETERS>(processHandle, peb.ProcessParameters);
                                processArgs = Native.Processes.Windows.ProcessUtilitiesWin.ReadProcessUnicodeString(processHandle, processParameters.CommandLine);
                            }
                        }
                        finally
                        {
                            Marshal.FreeHGlobal(basicInfoPtr);
                        }

                        string path = sb.ToString();
                        survivingChildProcesses.Add(processId, new ReportedProcess(processId, path, processArgs));
                    }
                }
            }


            return(survivingChildProcesses);
        }
Пример #15
0
 public DhcpPool GetPoolByPrefix(NetworkPrefix prefix)
 {
     return(Pools.Where(x => x.Network.Equals(prefix)).FirstOrDefault());
 }
Пример #16
0
            /// <summary>
            /// Returns the tree of changes encapusulated by this <see cref="PrintNode"/> as an indented, formatted string.
            /// </summary>
            public override string ToString()
            {
                using (var sbPool = Pools.GetStringBuilder())
                {
                    var sb    = sbPool.Instance;
                    var stack = new Stack <RecursionState>();
                    stack.Push(new RecursionState(this, -1, null));

                    while (stack.Count != 0)
                    {
                        var curr         = stack.Pop();
                        var indentPrefix = curr.Level > 0 ? new string('\t', curr.Level) : string.Empty;

                        if (curr.Name != null)
                        {
                            sb.AppendLine(indentPrefix + curr.Name);
                        }

                        // Each PrintNode represents one position in a tree. The values of a PrintNode represent nodes that were added or removed at that position.
                        // The max number of values at a position is 2, when a node is removed from one position and a new one is added at the same position.
                        // This is equivalent to modifying the state of that node.
                        switch (curr.PrintNode.ChangedNodes.Count)
                        {
                        // A node exists in one tree that does not exist in the other
                        // In this case, print all the values of the node as either added or removed
                        case 1:
                            var changeListValue = curr.PrintNode.ChangedNodes[0];
                            sb.Append(indentPrefix + changeListValue.ToString());
                            break;

                        // A node exists in both trees, but with different values (equivalent to modifying the node)
                        // Consolidate the print out by diffing just the values
                        case 2:
                            ChangeList <JsonNode> .ChangeListValue removed, added;
                            if (curr.PrintNode.ChangedNodes[0].ChangeType == ChangeList <JsonNode> .ChangeType.Removed)
                            {
                                removed = curr.PrintNode.ChangedNodes[0];
                                added   = curr.PrintNode.ChangedNodes[1];
                            }
                            else
                            {
                                removed = curr.PrintNode.ChangedNodes[1];
                                added   = curr.PrintNode.ChangedNodes[0];
                            }

                            // Order of removed vs added node is not guaranteed in the change list,
                            // but when diffing the nodes' values, the removed node represents a node from the old tree,
                            // so it should go first and represent the old list to get the correct diff.
                            var changeList = new ChangeList <string>(removed.Value.Values, added.Value.Values);

                            if (changeList.Count == 0)
                            {
                                // There was no difference in values between the removed node and added node,
                                // this means that the node simply moved positions.
                                // In this case, print the full list of values for both the removed and added node
                                sb.Append(indentPrefix + removed.ToString());
                                sb.Append(indentPrefix + added.ToString());
                            }
                            else
                            {
                                // Otherwise, rely on the normal diff
                                sb.Append(changeList.ToString(indentPrefix));
                            }

                            break;

                        default:
                            break;
                        }

                        foreach (var child in curr.PrintNode.Children)
                        {
                            stack.Push(new RecursionState(child.Value, curr.Level + 1, child.Key));
                        }
                    }

                    return(sb.ToString());
                }
            }
Пример #17
0
        /// <summary>
        /// Describes the operation that cause this reported file access, including all parameter value, except the path
        /// </summary>
        public string Describe()
        {
            using (PooledObjectWrapper <StringBuilder> wrapper = Pools.GetStringBuilder())
            {
                StringBuilder sb = wrapper.Instance;
                sb.Append('[');
                sb.Append(Process.Path);
                sb.Append(':');
                sb.Append(Process.ProcessId);
                sb.Append(']');

                if (RequestedAccess != RequestedAccess.None)
                {
                    sb.AppendFormat("({0:G})", RequestedAccess);
                }

                sb.Append(' ');

                switch (Operation)
                {
                case ReportedFileOperation.ZwCreateFile:
                case ReportedFileOperation.ZwOpenFile:
                case ReportedFileOperation.NtCreateFile:
                case ReportedFileOperation.CreateFile:
                case ReportedFileOperation.Unknown:
                {
                    sb.Append(Operation.ToString());
                    sb.Append("(..., ");
                    UInt32FlagsFormatter <DesiredAccess> .Append(sb, (uint)DesiredAccess);

                    sb.Append(", ");
                    UInt32FlagsFormatter <ShareMode> .Append(sb, (uint)ShareMode);

                    sb.Append(", , ");
                    UInt32EnumFormatter <CreationDisposition> .Append(sb, (uint)CreationDisposition);

                    sb.Append(", ");
                    UInt32FlagsFormatter <FlagsAndAttributes> .Append(sb, (uint)FlagsAndAttributes);

                    sb.Append(")");
                    break;
                }

                case ReportedFileOperation.CopyFileSource:
                {
                    sb.Append("CopyFile([Source], ...)");
                    break;
                }

                case ReportedFileOperation.CopyFileDestination:
                {
                    sb.Append("CopyFile(..., [Destination])");
                    break;
                }

                case ReportedFileOperation.CreateHardLinkSource:
                {
                    sb.Append("CreateHardLink(..., [ExistingFile)");
                    break;
                }

                case ReportedFileOperation.CreateHardLinkDestination:
                {
                    sb.Append("CreateHardLink([NewLink], ...)");
                    break;
                }

                case ReportedFileOperation.MoveFileSource:
                {
                    sb.Append("MoveFile([Source], ...)");
                    break;
                }

                case ReportedFileOperation.MoveFileDestination:
                {
                    sb.Append("MoveFile(..., [Destination])");
                    break;
                }

                case ReportedFileOperation.SetFileInformationByHandleSource:
                {
                    sb.Append("SetFileInformationByHandle([Source], ...)");
                    break;
                }

                case ReportedFileOperation.SetFileInformationByHandleDest:
                {
                    sb.Append("SetFileInformationByHandle(..., [Destination])");
                    break;
                }

                case ReportedFileOperation.ZwSetRenameInformationFileSource:
                {
                    sb.Append("ZwSetRenameInformationFile([Source], ...)");
                    break;
                }

                case ReportedFileOperation.ZwSetRenameInformationFileDest:
                {
                    sb.Append("ZwSetRenameInformationFile(..., [Destination])");
                    break;
                }

                case ReportedFileOperation.ZwSetFileNameInformationFileSource:
                {
                    sb.Append("ZwSetFileNameInformationFile([Source], ...)");
                    break;
                }

                case ReportedFileOperation.ZwSetFileNameInformationFileDest:
                {
                    sb.Append("ZwSetFileNameInformationFile(..., [Destination])");
                    break;
                }

                case ReportedFileOperation.MoveFileWithProgressSource:
                {
                    sb.Append("MoveFileWithProgress([Source]...)");
                    break;
                }

                case ReportedFileOperation.MoveFileWithProgressDest:
                {
                    sb.Append("MoveFileWithProgress([Dest]...)");
                    break;
                }

                case ReportedFileOperation.FindFirstFileEx:
                {
                    sb.Append("FindFirstFileEx(...)");
                    if (RequestedAccess == RequestedAccess.Enumerate)
                    {
                        sb.Append(", ");
                        sb.Append("Enumerate Pattern:" + EnumeratePattern);
                    }

                    break;
                }

                default:
                {
                    sb.Append(Enum.GetName(typeof(ReportedFileOperation), Operation)).Append("(...)");
                    break;
                }
                }

                if (Error != 0)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, " => (0x{0:X8}) ", Error);
                    sb.Append(NativeWin32Exception.GetFormattedMessageForNativeErrorCode(unchecked ((int)Error)));
                }

                if (Usn != NoUsn)
                {
                    sb.AppendFormat(CultureInfo.InvariantCulture, " (USN 0x{0:X8}) ", Usn);
                }

                // If the status was Denied, don't include it in the description,
                // because an access that was denied by manifest may have been
                // allowed in practice (no failure injection), and the message
                // would be confusing.
                if (Status != FileAccessStatus.Denied)
                {
                    // Other modes are interesting and should be logged
                    sb.Append(" => ");
                    sb.Append(Status);
                }

                return(sb.ToString());
            }
        }
Пример #18
0
        public bool RaiseEvent(RoutedEventArgs e)
        {
            if (e.Stage == null)
            {
                e.Stage = Stage;
            }

            if (e.OriginalSource == null)
            {
                e.OriginalSource = this;
                e.Source         = this;
            }

            if (e.RoutedEvent.RoutingStrategy == RoutingStrategy.Direct)
            {
                EventManager.InvokeClassHandlers(this, e);
                if (!e.Stopped)
                {
                    InvokeHandler(e);
                }
                return(e.Cancelled);
            }

            // Collect ancestors so event propagation is unaffected by hierarchy changes.
            List <Group> ancestors = Pools <List <Group> > .Obtain();

            Group parent = Parent;

            while (parent != null)
            {
                ancestors.Add(parent);
                parent = parent.Parent;
            }

            try {
                if (e.RoutedEvent.RoutingStrategy == RoutingStrategy.Tunnel)
                {
                    // Notify all parent capture listeners, starting at the root. Ancestors may stop an event before children receive it.
                    for (int i = ancestors.Count - 1; i >= 0; i--)
                    {
                        Group currentTarget = ancestors[i];
                        EventManager.InvokeClassHandlers(currentTarget, e);
                        if (!e.Stopped)
                        {
                            currentTarget.InvokeHandler(e);
                        }
                        if (e.Stopped)
                        {
                            return(e.Cancelled);
                        }
                    }

                    EventManager.InvokeClassHandlers(this, e);
                    if (!e.Stopped)
                    {
                        InvokeHandler(e);
                    }
                    if (e.Stopped)
                    {
                        return(e.Cancelled);
                    }
                }
                else if (e.RoutedEvent.RoutingStrategy == RoutingStrategy.Bubble)
                {
                    EventManager.InvokeClassHandlers(this, e);
                    if (!e.Stopped)
                    {
                        InvokeHandler(e);
                    }
                    if (e.Stopped)
                    {
                        return(e.Cancelled);
                    }

                    // Notify all parent listeners, starting at the target. Children may stop an event before ancestors receive it.
                    foreach (Group ancestor in ancestors)
                    {
                        EventManager.InvokeClassHandlers(ancestor, e);
                        if (!e.Stopped)
                        {
                            ancestor.InvokeHandler(e);
                        }
                        if (e.Stopped)
                        {
                            return(e.Cancelled);
                        }
                    }
                }

                return(e.Cancelled);
            }
            finally {
                ancestors.Clear();
                Pools <List <Group> > .Release(ancestors);
            }
        }
Пример #19
0
    void Awake()
    {
        if (m_Instance)
        {
            Debug.LogError("There id two " + gameObject.name + " in the scene");
            Debug.Break();
        }
        m_Instance = this;
        PoolBall[] balls = GameObject.FindObjectsOfType<PoolBall>();
        if (balls != null)
        {
            m_Balls = new Dictionary<int, PoolBall>();
            for (int i = 0, length = balls.Length; i < length; i++)
            {
                m_Balls.Add(balls[i].GetBallID(), balls[i]);
            }
        }
        else
        {
            Debug.LogError("the balls number is not explicit in the scene, please debug the code");
        }
        m_CustomBalls = new Dictionary<int, PoolBall>();
        PoolCue[] cues = GameObject.FindObjectsOfType<PoolCue>();
        if (cues == null || cues.Length != 1)
        {
            Debug.LogError("the number of the cue is not explicit in the scene, please debug the code");
        }
        else
        {
            m_Cue = cues[0];
        }

        m_SceneCamera = Camera.main;

        m_BallStorageRack = FindObjectOfType<BallStorageRack>();

        m_BallIcons = new Sprite[15];
        for (int i = 1; i <= 15; i++)
        {
            m_BallIcons[i - 1] = Resources.Load<Sprite>("BallsIcon/" + i);
        }

        m_PocketTriggers.AddRange(FindObjectsOfType<PocketTrigger>());
        m_PocketTriggers.Sort((PocketTrigger left, PocketTrigger right) =>
            {
                if (left.PocketIndex < right.PocketIndex)
                    return -1;
                else if (left.PocketIndex > right.PocketIndex)
                    return 1;
                else
                    return 0;
            });
    }
Пример #20
0
 /// <summary>
 /// Fully Release Buffer
 /// </summary>
 public void Free()
 {
     lock (Pools)
         Pools.Remove(this);
 }
 public void SetPools(Pools pools)
 {
     _groupObserver = new [] { pools.core, pools.bullets }
     .CreateEntityCollector(Matcher.AllOf(CoreMatcher.View, CoreMatcher.Destroy));
 }
Пример #22
0
        /// <summary>
        /// Creates a new PipConstructionHelper
        /// </summary>
        /// <remarks>
        /// Ideally this function would take ModuleId, FullSymbol QualifierId and compute uniqueOutputLocation itself. Unfortunately today the data is not yet
        /// exposed via IPipGraph, therefore the responsibility is on the call site for now.
        /// </remarks>
        public static PipConstructionHelper Create(
            PipExecutionContext context,
            AbsolutePath objectRoot,
            AbsolutePath redirectedRoot,
            AbsolutePath tempRoot,
            IMutablePipGraph pipGraph,
            ModuleId moduleId,
            string moduleName,
            RelativePath specRelativePath,
            FullSymbol symbol,
            LocationData thunkLocation,
            QualifierId qualifierId)
        {
            var stringTable = context.StringTable;
            var pathTable   = context.PathTable;

            // We have to manually compute the pipPipUniqueString here, Ideally we pass PackageId, SpecFile, FullSymbol and qualiferId and have it computed inside, but the IPipGraph does not allow querying it for now.
            string hashString;
            long   semiStableHashSeed = 0;

            using (var builderWrapper = Pools.GetStringBuilder())
            {
                var builder = builderWrapper.Instance;

                builder.Append(moduleName);
                builder.Append('/');
                semiStableHashSeed = HashCodeHelper.GetOrdinalHashCode64(moduleName);

                if (specRelativePath.IsValid)
                {
                    string specPath = specRelativePath.ToString(stringTable);
                    builder.Append(specPath);
                    builder.Append('/');
                    semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(specPath));
                }

                var symbolName = symbol.ToStringAsCharArray(context.SymbolTable);
                builder.Append(symbolName);
                builder.Append('/');
                semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(symbolName));

                var qualifierDisplayValue = context.QualifierTable.GetCanonicalDisplayString(qualifierId);
                builder.Append(qualifierDisplayValue);
                semiStableHashSeed = HashCodeHelper.Combine(semiStableHashSeed, HashCodeHelper.GetOrdinalHashCode64(qualifierDisplayValue));

                var pipPipUniqueString = builder.ToString();
                hashString = Hash(pipPipUniqueString);
            }

            var pipRelativePath = RelativePath.Create(
                PathAtom.Create(stringTable, hashString.Substring(0, 1)),
                PathAtom.Create(stringTable, hashString.Substring(1, 1)),
                PathAtom.Create(stringTable, hashString.Substring(2)));

            var valuePip = new ValuePip(symbol, qualifierId, thunkLocation);

            return(new PipConstructionHelper(
                       context,
                       objectRoot,
                       redirectedRoot,
                       tempRoot,
                       pipGraph,
                       moduleId,
                       moduleName,
                       valuePip,
                       pipRelativePath,
                       semiStableHashSeed));
        }
Пример #23
0
        private void UpdateMenu()
        {
            lock (NodeLock)
            {
                foreach (var miner in Miners)
                {
                    var current = Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Miners).Children.FirstOrDefault(c => c.Type == NodeType.Miner && c.Key == miner.Id.ToString());

                    if (current == null)
                    {
                        var node = new TreeNode
                        {
                            Name = miner.Name,
                            Type = NodeType.Miner,
                            Data = miner,
                            Key  = miner.Id.ToString()
                        };

                        Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Miners).Children.Add(node);
                    }
                }

                var poolNode        = Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Pools);
                var missingPoolKeys = poolNode.Children.Select(c => c.Key).Where(c => !Pools.Select(a => a.Id.ToString()).Contains(c)).ToList();

                foreach (var key in missingPoolKeys)
                {
                    var item = poolNode.Children.FirstOrDefault(c => c.Key == key);

                    if (item != null)
                    {
                        poolNode.Children.Remove(item);
                    }
                }

                foreach (var pool in Pools)
                {
                    var current = Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Pools).Children.FirstOrDefault(c => c.Type == NodeType.Pool && c.Key == pool.Wallet);

                    if (current == null)
                    {
                        var node = new TreeNode
                        {
                            Name = pool.Name,
                            Type = NodeType.Pool,
                            Data = pool,
                            Key  = pool.Wallet
                        };

                        foreach (var worker in pool.Workers)
                        {
                            node.Children.Add(new TreeNode
                            {
                                Name = worker.Id,
                                Type = NodeType.Worker,
                                Data = worker,
                                Key  = worker.Uid.ToString()
                            });
                        }

                        Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Pools).Children.Add(node);
                    }
                    else
                    {
                        foreach (var worker in pool.Workers)
                        {
                            TreeNode currentChild = null;

                            if (current.Children.Any())
                            {
                                currentChild = current.Children.FirstOrDefault(c => c.Type == NodeType.Worker && c.Key == worker.Uid.ToString());
                            }

                            if (currentChild == null)
                            {
                                current.Children.Add(new TreeNode
                                {
                                    Name = worker.Id,
                                    Type = NodeType.Worker,
                                    Data = worker,
                                    Key  = worker.Uid.ToString()
                                });
                            }
                            else
                            {
                                currentChild.Data = worker;
                            }
                        }
                    }
                }
            }
        }
Пример #24
0
 public void SetPools(Pools pools)
 {
     _pools = pools;
 }
Пример #25
0
        private void PoolBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            bool?modified = false;

            using (var context = new Context())
            {
                foreach (var pool in context.Pools)
                {
                    if (!Pools.Any(c => c.Id == pool.Id))
                    {
                        Pools.Add(pool);
                        modified = true;
                    }

                    var currentPool = Pools.FirstOrDefault(c => c.Id == pool.Id);

                    var nanopool = new Nanopool(pool.Type, GetWebProxy());
                    var result   = nanopool.GetListOfWorkers(pool.Wallet);

                    if (result != null && result.Status)
                    {
                        var newWorkers = new List <Worker>();
                        var removed    = 0;

                        if (pool.Workers.Any())
                        {
                            removed = pool.Workers.RemoveAll(x => !result.Data.Exists(y => y.Uid == x.Uid));
                        }

                        foreach (var worker in result.Data)
                        {
                            Worker current = null;

                            if (currentPool.Workers.Any())
                            {
                                current = currentPool.Workers.FirstOrDefault(c => c.Uid == worker.Uid);
                            }

                            if (current == null)
                            {
                                newWorkers.Add(worker);
                            }
                            else
                            {
                                worker.UpdateOther(current);
                            }
                        }

                        if (removed > 0)
                        {
                            modified = true;
                        }

                        if (newWorkers.Any())
                        {
                            currentPool.Workers.AddRange(newWorkers);
                            modified = true;
                        }
                    }
                }
            }

            e.Result = modified;
        }
Пример #26
0
 public GameObject Spawn(Pools.PickUps type, Vector3 pos, bool active)
 {
     var GO = m_PickUps[(int)type].New(pos);
     GO.SetActive(active);
     return GO;
 }
Пример #27
0
        private void CompileOpenPath(IList <CCVector2> points, IList <float> accumLengths, int offset, int count, Pen outlinePen)
        {
            if (_strokeType != StrokeType.Outline)
            {
                InitializeBuffers(count);
            }

            IList <float> lengths = accumLengths ?? _zeroList;

            Buffer <CCVector2> insetBuffer  = null;
            Buffer <CCVector2> outsetBuffer = null;

            if (outlinePen != null && _strokeType != StrokeType.Fill)
            {
                insetBuffer = Pools <Buffer <CCVector2> > .Obtain();

                outsetBuffer = Pools <Buffer <CCVector2> > .Obtain();

                int vCount = _positionData != null ? _positionData.Length : _pen.MaximumVertexCount(count);

                insetBuffer.EnsureCapacity(vCount);
                outsetBuffer.EnsureCapacity(vCount);
            }

            PenWorkspace ws = Pools <PenWorkspace> .Obtain();

            ws.ResetWorkspace(_pen);
            ws.PathLength = lengths[offset + count - 1];

            int vPrevCount = 0;
            int vNextCount = AddStartPoint(0, points[offset + 0], points[offset + 1], ws, insetBuffer);

            if (insetBuffer != null)
            {
                Array.Reverse(insetBuffer.Data, 0, insetBuffer.Index);
            }

            JoinSample joinSample = new JoinSample(CCVector2.Zero, points[offset + 0], points[offset + 1], 0, lengths[offset + 0], lengths[offset + 1]);

            for (int i = 0; i < count - 2; i++)
            {
                joinSample.Advance(points[offset + i + 2], lengths[offset + i + 2]);

                vPrevCount = vNextCount;
                vNextCount = AddJoint(i + 1, ref joinSample, ws, insetBuffer, outsetBuffer);
                if (_strokeType != StrokeType.Outline)
                {
                    AddSegment(_vertexBufferIndex - vNextCount - vPrevCount, vPrevCount, _jointCCW[i], _vertexBufferIndex - vNextCount, vNextCount, _jointCCW[i + 1]);
                }
            }

            /*for (int i = 0; i < count - 2; i++) {
             *  int i0 = offset + i;
             *  int i1 = i0 + 1;
             *  int i2 = i0 + 2;
             *
             *  vPrevCount = vNextCount;
             *  vNextCount = AddJoint(i + 1, points[i0], points[i1], points[i2], lengths[i0], lengths[i1], lengths[i2], ws, insetBuffer, outsetBuffer);
             *  if (_strokeType != StrokeType.Outline)
             *      AddSegment(_vertexBufferIndex - vNextCount - vPrevCount, vPrevCount, _jointCCW[i], _vertexBufferIndex - vNextCount, vNextCount, _jointCCW[i + 1]);
             * }*/

            vPrevCount = vNextCount;
            vNextCount = AddEndPoint(count - 1, points[offset + count - 2], points[offset + count - 1], ws, insetBuffer);
            if (_strokeType != StrokeType.Outline)
            {
                AddSegment(_vertexBufferIndex - vNextCount - vPrevCount, vPrevCount, _jointCCW[count - 2], _vertexBufferIndex - vNextCount, vNextCount, _jointCCW[count - 1]);
            }

            if (insetBuffer != null)
            {
                Array.Reverse(insetBuffer.Data, 0, insetBuffer.Index);
            }

            Pools <PenWorkspace> .Release(ws);

            if (outlinePen != null && _strokeType != StrokeType.Fill)
            {
                Buffer <CCVector2> mergedBuffer = Pools <Buffer <CCVector2> > .Obtain();

                mergedBuffer.EnsureCapacity(insetBuffer.Index + outsetBuffer.Index);

                Array.Copy(insetBuffer.Data, 0, mergedBuffer.Data, 0, insetBuffer.Index);
                Array.Copy(outsetBuffer.Data, 0, mergedBuffer.Data, insetBuffer.Index, outsetBuffer.Index);

                _outlinePaths = new GraphicsPath[] {
                    new GraphicsPath(outlinePen, mergedBuffer.Data, PathType.Closed, 0, insetBuffer.Index + outsetBuffer.Index),
                };

                Pools <Buffer <CCVector2> > .Release(mergedBuffer);

                Pools <Buffer <CCVector2> > .Release(insetBuffer);

                Pools <Buffer <CCVector2> > .Release(outsetBuffer);
            }
        }
Пример #28
0
        /// <summary>
        /// Erstellt eine Kachel
        /// </summary>
        /// <param name="kachelPoolID">Der Pool in dem die Kachel gespeichert werden soll</param>
        /// <param name="r">Der Rot-Anteil der Kachelfarbe</param>
        /// <param name="g">Der Grün-Anteil der Kachelfarbe</param>
        /// <param name="b">Der Blau-Anteil der Kachelfarbe</param>
        /// <param name="nois">Es kann ein Rauschen der Farbwerte erzeugt werden</param>
        /// <returns>Void</returns>
        public void genKachel(int kachelPoolID, int r, int g, int b, bool nois = false)
        {
            int nr = r;
            int ng = g;
            int nb = b;
            int boul;
            int rand;

            printToConsole("Find pool by Id: " + kachelPoolID, ConsolePrintTypes.INFO);
            Pools kachelPool = db.PoolsSet.Where(p => p.Id == kachelPoolID).First();

            printToConsole("R: " + r + "G: " + g + "B: " + b + "Nois: " + nois, ConsolePrintTypes.INFO);

            printToConsole("Kachelsize " + kachelPool.size + "x" + kachelPool.size, ConsolePrintTypes.INFO);
            int width  = kachelPool.size;
            int height = kachelPool.size;

            Random random = new Random();
            Bitmap bitmap = new Bitmap(width, height);

            try {
                for (int x = 0; x < width; x++)
                {
                    for (int y = 0; y < height; y++)
                    {
                        if (nois)
                        {
                            boul = random.Next(0, 1);
                            rand = random.Next(50, 70);

                            if (boul == 1)
                            {
                                nr = r + rand;
                                ng = g + rand;
                                nb = b + rand;
                            }
                            else
                            {
                                nr = r - rand;
                                ng = g - rand;
                                nb = b - rand;
                            }

                            nr = minMax(nr);
                            ng = minMax(ng);
                            nb = minMax(nb);
                        }
                        bitmap.SetPixel(x, y, Color.FromArgb(nr, ng, nb));
                    }
                }
            }
            catch (Exception e)
            {
                printToConsole(e.ToString(), ConsolePrintTypes.INFO);
            }

            // Generiere eine Einzigartige Bezeichnung
            String UUID = Guid.NewGuid().ToString();

            printToConsole("gen UUID: " + UUID, ConsolePrintTypes.INFO);

            // Speichere das Bild ab
            bitmap.Save(IMAGEPATH + "Kacheln\\" + UUID + ".png");
            printToConsole("Save image to: " + IMAGEPATH + "Kacheln\\" + UUID + ".png", ConsolePrintTypes.INFO);

            var kachel = db.Set <Kacheln>();

            kachel.Add(new Kacheln
            {
                displayname = "Kachel",
                filename    = UUID + ".png",
                path        = "Kacheln\\",
                heigth      = bitmap.Size.Height,
                width       = bitmap.Size.Width,
                hsv         = "000",
                PoolsId     = kachelPoolID,
                avgR        = (int)colorValue(bitmap, ColorType.RED),
                avgG        = (int)colorValue(bitmap, ColorType.GREEN),
                avgB        = (int)colorValue(bitmap, ColorType.BLUE)
            });

            // Speichere die DB
            db.SaveChanges();
            printToConsole("Generation done!", ConsolePrintTypes.INFO);

            bitmap.Dispose();
        }
Пример #29
0
        private void CompileClosedPath(IList <CCVector2> points, IList <float> accumLengths, int offset, int count, Pen outlinePen)
        {
            if (_strokeType != StrokeType.Outline)
            {
                InitializeBuffers(count + 1);
            }

            if (IsClose(points[offset], points[offset + count - 1]))
            {
                count--;
            }

            IList <float> lengths = accumLengths ?? _zeroList;

            Buffer <CCVector2> insetBuffer  = null;
            Buffer <CCVector2> outsetBuffer = null;

            if (outlinePen != null && _strokeType != StrokeType.Fill)
            {
                insetBuffer = Pools <Buffer <CCVector2> > .Obtain();

                outsetBuffer = Pools <Buffer <CCVector2> > .Obtain();

                int vCount = _positionData != null ? _positionData.Length : _pen.MaximumVertexCount(count);

                insetBuffer.EnsureCapacity(vCount);
                outsetBuffer.EnsureCapacity(vCount);
            }

            PenWorkspace ws = Pools <PenWorkspace> .Obtain();

            ws.ResetWorkspace(_pen);

            JoinSample joinSample = new JoinSample(points[offset + count - 1], points[offset + 0], points[offset + 1], 0, lengths[offset + 0], lengths[offset + 1]);

            int vBaseIndex = _vertexBufferIndex;
            int vBaseCount = AddJoint(0, ref joinSample, ws, insetBuffer, outsetBuffer);

            int vPrevCount = 0;
            int vNextCount = vBaseCount;

            for (int i = 0; i < count - 2; i++)
            {
                joinSample.Advance(points[offset + i + 2], lengths[offset + i + 2]);

                vPrevCount = vNextCount;
                vNextCount = AddJoint(i + 1, ref joinSample, ws, insetBuffer, outsetBuffer);
                if (_strokeType != StrokeType.Outline)
                {
                    AddSegment(_vertexBufferIndex - vNextCount - vPrevCount, vPrevCount, _jointCCW[i], _vertexBufferIndex - vNextCount, vNextCount, _jointCCW[i + 1]);
                }
            }

            joinSample.Advance(points[offset + 0], lengths[offset + 0]);

            vPrevCount = vNextCount;
            vNextCount = AddJoint(count - 1, ref joinSample, ws, insetBuffer, outsetBuffer);

            if (_strokeType != StrokeType.Outline)
            {
                AddSegment(_vertexBufferIndex - vNextCount - vPrevCount, vPrevCount, _jointCCW[count - 2], _vertexBufferIndex - vNextCount, vNextCount, _jointCCW[count - 1]);
                AddSegment(_vertexBufferIndex - vNextCount, vNextCount, _jointCCW[count - 1], vBaseIndex, vBaseCount, _jointCCW[0]);
            }

            Pools <PenWorkspace> .Release(ws);

            if (outlinePen != null && _strokeType != StrokeType.Fill)
            {
                Array.Reverse(insetBuffer.Data, 0, insetBuffer.Index);

                _outlinePaths = new GraphicsPath[] {
                    new GraphicsPath(outlinePen, insetBuffer.Data, PathType.Closed, 0, insetBuffer.Index),
                    new GraphicsPath(outlinePen, outsetBuffer.Data, PathType.Closed, 0, outsetBuffer.Index),
                };

                Pools <Buffer <CCVector2> > .Release(insetBuffer);

                Pools <Buffer <CCVector2> > .Release(outsetBuffer);
            }
        }
Пример #30
0
        /// <summary>
        /// A miner program elindítása a megadott paraméterekkel.
        /// </summary>
        private void startMining(int window)
        {
            if (OpenCLDevices != null && !SelectedMinerSettings.ApplicationMode.Equals(ApplicationMode.Silent) &&
                !StartMiningButtonContent.Equals("Stop", StringComparison.InvariantCultureIgnoreCase))
            {
                GpuParameterHandler.WriteParameters(OpenCLDevices);
            }

            if (Devices.Count > 0)
            {
                Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage()
                {
                    OutputText = "The following devices are initialized:"
                });

                foreach (var item in Devices)
                {
                    Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage()
                    {
                        OutputText = $"{item.Name} [w: {item.WorkSize}, i: {item.Intensity}, t: {item.Threads}]", IsError = true
                    });
                }
            }

            if (SelectedMinerSettings.IsCPUMiningEnabled && Utils.CheckInstallation() != CheckDetails.Installed)
            {
                if (Utils.InstallMiners() != InstallDetail.Installed)
                {
                    MessageBoxResult mResult = MessageBox.Show(String.Format("Simple Miner is corrupted, may the antivirus application blocked it. \nIf you already add it as an exception in your antivirus application, please try to download the miner again.\nWould you like to navigate to Simple Miner download page?"), "Miner error", MessageBoxButton.YesNo, MessageBoxImage.Stop);
                    if (mResult == MessageBoxResult.No)
                    {
                        return;
                    }
                    else
                    {
                        Process.Start(Consts.MinerDownload);
                        return;
                    }
                }
            }

            //talán csökkenti a memória fragmentációt
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect();
            if (IsIdle)
            {
                _minerProcesses.Clear();
                MinerOutputString.Clear();
                saveMinerSettings();

                if (OpenCLDevices != null && OpenCLDevices.Any(x => x.IsEnabled)) //videokártya indítása
                {
                    //if (IsAdministrator)
                    //{
                    //    var exeMinerManager = new ExeManager(Consts.ApplicationPath, Consts.ToolExeFileName);
                    //    exeMinerManager.ExecuteResource("disable \"*VEN_1002&DEV_6*\"");
                    //    Thread.Sleep(1000);
                    //    exeMinerManager.ExecuteResource("enable \"*VEN_1002&DEV_6*\"");
                    //}
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        var mp = new MinerProcess()
                        {
                            Algorithm = (int)SupportedAlgos.CryptoNight, Devices = OpenCLDevices, MinerType = MinerType.GPU, Settings = SelectedMinerSettings
                        };
                        if (mp.InitalizeMiner(Pools.Where(x => x.IsGPUPool && (x.IsMain || x.IsFailOver)).ToList()))
                        {
                            mp.StartMiner();
                            _minerProcesses.Add(mp);
                        }
                        else
                        {
                            return;
                        }
                    });
                }

                if (SelectedMinerSettings.IsCPUMiningEnabled) //proci indítása
                {
                    var mp = new MinerProcess()
                    {
                        Algorithm = (int)SupportedAlgos.CryptoNight, Devices = OpenCLDevices, MinerType = MinerType.CPU, Settings = SelectedMinerSettings
                    };

                    if (mp.InitalizeMiner(Pools.Where(x => x.IsCPUPool && (x.IsMain || x.IsFailOver)).ToList()))
                    {
                        mp.StartMiner();
                        _minerProcesses.Add(mp);
                    }
                    else
                    {
                        return;
                    }
                }

                IsIdle = false;
            }
            else
            {
                _minerProcesses.ForEach(x => x.StopMiner());
                IsIdle = true;

                if (!isCountDown)
                {
                    Messenger.Default.Send(new MinerOutputMessage()
                    {
                        OutputText = "Mining finished!"
                    });
                }
            }
            RaisePropertyChanged(nameof(IsIdle));
            RaisePropertyChanged(nameof(StartMiningButtonContent));
            RaisePropertyChanged(nameof(IsEnabledCPUThreadAuto));
        }
Пример #31
0
 public void SetPools(Pools pools)
 {
     _pools        = pools;
     selectedGroup = _pools.core.GetGroup(CoreMatcher.Selected);
 }
Пример #32
0
    IEnumerator<float> _Spawn(Pools.PickUps type)
    {
        // transform.rotation points forward, not up as we want
        // so rotate our spawner's rotation back 90 degrees
        var directionUp = Quaternion.LookRotation(transform.up, -transform.forward);

        // Get random amount
        int amount = Random.Range(m_emitAmount.Min, m_emitAmount.Max);

        // Play spawning effects
        SFX();
        ParticleFX();

        for (int i = 0; i < amount; i++)
        {
            // Make sure Start() is initialized before continuing
            while (!m_startDone)
            {
                yield return 0f;
            }

            // Retrieve the pick up from their pool
            var GO = PooledDB.Instance.Spawn(type, transform.position, true);

            // Get random direction
            var newPoint = Helper.GetPointOnSphere(directionUp, m_emitAngle);
            Debug.DrawLine(transform.position, transform.position + (newPoint * 5), Color.red, 60);

            // Wait for the pickup to initialize Start()
            for (int j = 0; j < m_spawnSpeed; j++)
            {
                yield return 0f;
            }

            var goAtrI = GO.GetComponent<AttractedItem>();
            var goRB = GO.GetComponent<Rigidbody>();

            if (goRB != null)
            {
                goRB.AddForce(newPoint * Random.Range(m_emitSpeed.Min, m_emitSpeed.Max), ForceMode.VelocityChange);
            }
            if (goAtrI != null)
            {
                goAtrI.StartAttract(AttractedItem.AttractMode.explode);
            }
        }

        // Store spawner back into pool
        SelfStore();
    }
 public void SetPools(Pools pools)
 {
     _pools       = pools;
     _moveInputs  = pools.input.GetGroup(InputMatcher.MoveInput);
     _shootInputs = pools.input.GetGroup(InputMatcher.ShootInput);
 }