Inheritance: MonoBehaviour
 public BenchmarkToolchainFacade(Benchmark benchmark, IBenchmarkGenerator generator, IBenchmarkBuilder builder, IBenchmarkExecutor executor)
 {
     this.benchmark = benchmark;
     this.generator = generator;
     this.builder = builder;
     this.executor = executor;
 }
 private static BenchmarkGenerateResult CreateProjectDirectory(Benchmark benchmark)
 {
     var directoryPath = Path.Combine(Directory.GetCurrentDirectory(), benchmark.Caption);
     bool exist = Directory.Exists(directoryPath);
     Exception deleteException = null;
     for (int attempt = 0; attempt < 3 && exist; attempt++)
     {
         if (attempt != 0)
             Thread.Sleep(500); // Previous benchmark run didn't release some files
         try
         {
             Directory.Delete(directoryPath, true);
             exist = Directory.Exists(directoryPath);
         }
         catch (Exception e)
         {
             // Can't delete the directory =(
             deleteException = e;
         }
     }
     if (exist)
         return new BenchmarkGenerateResult(directoryPath, false, deleteException);
     if (!Directory.Exists(directoryPath))
         Directory.CreateDirectory(directoryPath);
     return new BenchmarkGenerateResult(directoryPath, true, null);
 }
        internal static string Generate(Benchmark benchmark)
        {
            var provider = GetDeclarationsProvider(benchmark.Target);

            string text = new SmartStringBuilder(ResourceHelper.LoadTemplate("BenchmarkProgram.txt")).
                Replace("$OperationsPerInvoke$", provider.OperationsPerInvoke).
                Replace("$TargetTypeNamespace$", provider.TargetTypeNamespace).
                Replace("$TargetMethodReturnTypeNamespace$", provider.TargetMethodReturnTypeNamespace).
                Replace("$TargetTypeName$", provider.TargetTypeName).
                Replace("$TargetMethodDelegate$", provider.TargetMethodDelegate).
                Replace("$TargetMethodDelegateType$", provider.TargetMethodDelegateType).
                Replace("$IdleMethodDelegateType$", provider.IdleMethodDelegateType).
                Replace("$IdleMethodReturnType$", provider.IdleMethodReturnType).
                Replace("$SetupMethodName$", provider.SetupMethodName).
                Replace("$CleanupMethodName$", provider.CleanupMethodName).
                Replace("$IdleImplementation$", provider.IdleImplementation).
                Replace("$HasReturnValue$", provider.HasReturnValue).
                Replace("$AdditionalLogic$", benchmark.Target.AdditionalLogic).
                Replace("$JobSetDefinition$", GetJobsSetDefinition(benchmark)).
                Replace("$ParamsContent$", GetParamsContent(benchmark)).
                Replace("$ExtraAttribute$", GetExtraAttributes(benchmark.Target)).
                Replace("$EngineFactoryType$", GetEngineFactoryTypeName(benchmark)). 
                ToString();

            text = Unroll(text, benchmark.Job.ResolveValue(RunMode.UnrollFactorCharacteristic, EnvResolver.Instance));

            return text;
        }
示例#4
0
        /// <summary>
        /// generates project.lock.json that tells compiler where to take dlls and source from
        /// and builds executable and copies all required dll's
        /// </summary>
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            if (!ExecuteCommand("restore", generateResult.DirectoryPath, logger))
            {
                return new BuildResult(generateResult, false, new Exception("dotnet restore has failed"), null);
            }

            if (!ExecuteCommand(
                $"build --framework {Framework} --configuration {Configuration} --output {OutputDirectory}", 
                generateResult.DirectoryPath, 
                logger))
            {
                // dotnet cli could have succesfully builded the program, but returned 1 as exit code because it had some warnings
                // so we need to check whether the exe exists or not, if it does then it is OK
                var executablePath = BuildExecutablePath(generateResult, benchmark);
                if (File.Exists(executablePath))
                {
                    return new BuildResult(generateResult, true, null, executablePath);
                }

                return new BuildResult(generateResult, false, new Exception("dotnet build has failed"), null);
            }

            return new BuildResult(generateResult, true, null, BuildExecutablePath(generateResult, benchmark));
        }
 /// <summary>
 /// we need our folder to be on the same level as the project that we want to reference
 /// we are limited by xprojs (by default compiles all .cs files in all subfolders, Program.cs could be doubled and fail the build)
 /// and also by nuget internal implementation like looking for global.json file in parent folders
 /// </summary>
 protected override string GetDirectoryPath(Benchmark benchmark)
 {
     return Path.Combine(
         Directory.GetCurrentDirectory(), 
         @"..\", 
         benchmark.ShortInfo);
 }
示例#6
0
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            lock (buildLock)
            {
                var projectFileName = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".csproj");
                var exeFilePath = Path.Combine(generateResult.DirectoryPath, ClassicGenerator.MainClassName + ".exe");
                var consoleLogger = new MsBuildConsoleLogger(logger);
                var globalProperties = new Dictionary<string, string>();
                var buildRequest = new BuildRequestData(projectFileName, globalProperties, null, new[] { "Build" }, null);
                var buildParameters = new BuildParameters(new ProjectCollection()) { DetailedSummary = false, Loggers = new Microsoft.Build.Framework.ILogger[] { consoleLogger } };
                var buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequest);

                if (buildResult.OverallResult != BuildResultCode.Success && !File.Exists(exeFilePath))
                {
                    logger.WriteLineInfo("BuildManager.DefaultBuildManager can't build this project. =(");
                    logger.WriteLineInfo("Let's try to build it via BuildBenchmark.bat!");
                    var buildProcess = new Process
                    {
                        StartInfo =
                        {
                            FileName = Path.Combine(generateResult.DirectoryPath, "BuildBenchmark.bat"),
                            WorkingDirectory = generateResult.DirectoryPath,
                            UseShellExecute = false,
                            RedirectStandardOutput = false,
                        }
                    };
                    buildProcess.Start();
                    buildProcess.WaitForExit();
                    if (File.Exists(exeFilePath))
                        return new BuildResult(generateResult, true, null, exeFilePath);
                }

                return new BuildResult(generateResult, buildResult.OverallResult == BuildResultCode.Success, buildResult.Exception, exeFilePath);
            }
        }
示例#7
0
        public void Start(Benchmark benchmark)
        {
            if (Directory.Exists(ProfilingFolder) == false)
                Directory.CreateDirectory(ProfilingFolder);

            var filePrefix = GetFileName("GC", benchmark, benchmark.Parameters);

            // Clean-up in case a previous run is still going!! We don't have to print the output here, 
            // because it can fail if things worked okay last time (i.e. nothing to clean-up)
            var output = RunProcess("logman", string.Format("stop {0} -ets", filePrefix));
            DeleteIfFileExists(filePrefix + ".etl");

            // 0x00000001 means collect GC Events only, (JIT Events are 0x00000010),
            // see https://msdn.microsoft.com/en-us/library/ff357720(v=vs.110).aspx for full list
            // 0x5 is the "ETW Event Level" and we set it to "Verbose" (and below)
            // Other flags used:
            // -ets                          Send commands to Event Trace Sessions directly without saving or scheduling.
            // -ct <perf|system|cycle>       Specifies the clock resolution to use when logging the time stamp for each event. 
            //                               You can use query performance counter, system time, or CPU cycle.
            var arguments =
                $"start {filePrefix} -o .\\{ProfilingFolder}\\{filePrefix}.etl -p {CLRRuntimeProvider} 0x00000001 0x5 -ets -ct perf";
            output = RunProcess("logman", arguments);
            if (output.Contains(ExecutedOkayMessage) == false)
                logger.WriteLineError("logman start output:\n" + output);
        }
 public BenchmarkReport(Benchmark benchmark, IList<BenchmarkRunReport> runs, EnvironmentInfo hostInfo, BenchmarkParameters parameters = null)
 {
     Benchmark = benchmark;
     Runs = runs;
     Parameters = parameters;
     HostInfo = hostInfo;
 }
        public async Task<IHttpActionResult> PutBenchmark(int id, Benchmark benchmark)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != benchmark.BenchmarkID)
            {
                return BadRequest();
            }

            db.Entry(benchmark).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BenchmarkExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
示例#10
0
 private ProcessStartInfo CreateStartInfo(Benchmark benchmark, string exeName, string args, string workingDirectory, IResolver resolver)
 {
     var start = new ProcessStartInfo
     {
         UseShellExecute = false,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         CreateNoWindow = true,
         WorkingDirectory = workingDirectory
     };
     var runtime = benchmark.Job.Env.HasValue(EnvMode.RuntimeCharacteristic)
         ? benchmark.Job.Env.Runtime
         : RuntimeInformation.GetCurrentRuntime();
         // TODO: use resolver
     switch (runtime)
     {
         case Runtime.Clr:
         case Runtime.Core:
             start.FileName = exeName;
             start.Arguments = args;
             break;
         case Runtime.Mono:
             start.FileName = "mono";
             start.Arguments = GetMonoArguments(benchmark.Job, exeName, args, resolver);
             break;
         default:
             throw new NotSupportedException("Runtime = " + runtime);
     }
     return start;
 }
 internal static IEnumerable<Assembly> GetAllReferences(Benchmark benchmark)
 {
     return benchmark.Target.Type.GetTypeInfo().Assembly
         .GetReferencedAssemblies()
         .Select(Assembly.Load)
         .Concat(new[] { benchmark.Target.Type.GetTypeInfo().Assembly });
 }
        static void Main(string[] args)
        {
            var comparer = new PrimeComparer();
            var writer = new PrimeNumberWriter();

            MyConsole.WriteLine("Hello World");

            const int maxNumberToFind = (int)1e8;
            const int threadCount = 4;

            //do
            //{
            //    var workers = new BaseBenchmarkStrategy<List<int>>[]
            //    {
            //        // sieve
            //        new SieveOfEratosthenesStrategy(maxNumberToFind),
            //        new ParallelSieveNumberStrategy(maxNumberToFind, threadCount),
            //        // basic
            //        new BasicPrimeNumberStrategy(maxNumberToFind),
            //        new ParallelPrimeNumberStrategy(maxNumberToFind, threadCount),
            //        new FullyParrallelPrimeNumberStrategy(maxNumberToFind, threadCount),
            //    };

            //    var benchmark = new Benchmark<List<int>>(workers, comparer, writer);
            //    if (!benchmark.StartBenchmark().IsBechmarkSuccessful)
            //    {
            //        break;
            //    }

            //    MyConsole.WriteLine();

            //} while (true);

            //MyConsole.WriteLine("Tests finished!! Press enter");

            var averageBenchmark = new AverageBenchmark();
            averageBenchmark.StartBenchmark(5, () =>
            {
                var workers = new BaseBenchmarkStrategy<List<int>>[]
                {
                    // basic
                    new BasicPrimeNumberStrategy(maxNumberToFind),
                    new ParallelPrimeNumberStrategy(maxNumberToFind, threadCount),
                    //new FullyParrallelPrimeNumberStrategy(maxNumberToFind, threadCount),
                    // sieve
                    //new SieveOfEratosthenesStrategy(maxNumberToFind),
                    //new ParallelSieveNumberStrategy(maxNumberToFind, threadCount),
                };

                var benchmark = new Benchmark<List<int>>(workers, comparer, writer);

                return benchmark;
            }, result =>
            {
                MyConsole.Write("AVG Time {0}/{1}: ", "Basic", "Parrallel");
                MyConsole.WriteLine(result.GetAVGTimeComparing(0, 1).ToString());
            });

            MyConsole.ReadLine();
        }
        // PUT api/benchmark/5
        public HttpResponseMessage Put(int id, Benchmark viewModel)
        {
            viewModel.User = this.User.Identity.Name;

            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != viewModel.BenchmarkID)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(viewModel).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        static void Main(string[] args)
        {
            MyConsole.WriteLine("Hello World");

            const int threadCount = 4;
            const int width = 1000;
            const int height = 1000;
            const int moleculaCount = 10000;
            var time = TimeSpan.FromSeconds(0.01);

            var random = new Random();
            var forceCalculatingService = new ForceCalculatingService();
            var moleculasUpdatingService = new MoleculasUpdatingService();
            var factory = new ForceStategyFactory();

            var moleculasA = new Molecula[moleculaCount];
            var moleculasB = new Molecula[moleculaCount];
            for (int i = 0; i < moleculaCount; i++)
            {
                int x = random.Next(width);
                int y = random.Next(height);

                var moleculaA = new Molecula(null);
                var moleculaB = new Molecula(null);
                moleculaA.Position = new Vector2(x, y);
                moleculaB.Position = new Vector2(x, y);
                moleculasA[i] = moleculaA;
                moleculasB[i] = moleculaB;
            }

            var strategies = new BaseForceStrategy[]
            {
                factory.GetBasicForceStrategy(moleculasA, forceCalculatingService, moleculasUpdatingService),
                factory.GetParallelForceStratagy(moleculasB, forceCalculatingService, moleculasUpdatingService,
                    threadCount)
            };

            foreach (var strategy in strategies)
            {
                strategy.Time = time;
                strategy.Height = height;
                strategy.Width = width;
            }

            do
            {
                var benchmark = new Benchmark<object>(strategies);
                if (!benchmark.StartBenchmark().IsBechmarkSuccessful)
                {
                    break;
                }

                MyConsole.WriteLine();

            } while (true);

            MyConsole.WriteLine("Tests finished!! Press enter");

            MyConsole.ReadLine();
        }
        /// <summary>
        /// generates project.lock.json that tells compiler where to take dlls and source from
        /// and builds executable and copies all required dll's
        /// </summary>
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark, IResolver resolver)
        {
            if (!DotNetCliCommandExecutor.ExecuteCommand(
                RestoreCommand, 
                generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath, 
                logger, 
                DefaultTimeout))
            {
                return BuildResult.Failure(generateResult, new Exception("dotnet restore has failed"));
            }

            if (!DotNetCliCommandExecutor.ExecuteCommand(
                GetBuildCommand(TargetFrameworkMoniker),
                generateResult.ArtifactsPaths.BuildArtifactsDirectoryPath, 
                logger,
                DefaultTimeout))
            {
                // dotnet cli could have succesfully builded the program, but returned 1 as exit code because it had some warnings
                // so we need to check whether the exe exists or not, if it does then it is OK
                if (File.Exists(generateResult.ArtifactsPaths.ExecutablePath))
                {
                    return BuildResult.Success(generateResult);
                }

                return BuildResult.Failure(generateResult);
            }

            return BuildResult.Success(generateResult);
        }
 public string GetValue(Summary summary, Benchmark benchmark)
 {
     var ranks = RankHelper.GetRanks(summary.Reports.Select(r => r.ResultStatistics).ToArray());
     int index = Array.IndexOf(summary.Reports.Select(r => r.Benchmark).ToArray(), benchmark);
     int rank = ranks[index];
     return system.ToPresentation(rank);
 }
示例#17
0
 public void Stop(Benchmark benchmark, BenchmarkReport report)
 {
     var filePrefix = GetFileName("GC", report.Benchmark, benchmark.Parameters);
     var output = RunProcess("logman", string.Format("stop {0} -ets", filePrefix));
     if (output.Contains(ExecutedOkayMessage) == false)
         logger.WriteLineError("logman stop output\n" + output);
 }
示例#18
0
        /// <summary>
        /// generates project.lock.json that tells compiler where to take dlls and source from
        /// and builds executable and copies all required dll's
        /// </summary>
        public BuildResult Build(GenerateResult generateResult, ILogger logger, Benchmark benchmark)
        {
            if (!DotNetCliCommandExecutor.ExecuteCommand(
                RestoreCommand,
                generateResult.DirectoryPath,
                logger,
                DefaultTimeout))
            {
                return new BuildResult(generateResult, false, new Exception("dotnet restore has failed"), null);
            }

            if (!DotNetCliCommandExecutor.ExecuteCommand(
                GetBuildCommand(TargetFrameworkMonikerProvider(benchmark.Job.Framework)),
                generateResult.DirectoryPath,
                logger,
                DefaultTimeout))
            {
                // dotnet cli could have succesfully builded the program, but returned 1 as exit code because it had some warnings
                // so we need to check whether the exe exists or not, if it does then it is OK
                var executablePath = BuildExecutablePath(generateResult, benchmark);
                if (File.Exists(executablePath))
                {
                    return new BuildResult(generateResult, true, null, executablePath);
                }

                return new BuildResult(generateResult, false, new Exception("dotnet build has failed"), null);
            }

            return new BuildResult(generateResult, true, null, BuildExecutablePath(generateResult, benchmark));
        }
示例#19
0
 private Summary(string title, HostEnvironmentInfo hostEnvironmentInfo, IConfig config, string resultsDirectoryPath, TimeSpan totalTime, ValidationError[] validationErrors, Benchmark[] benchmarks, BenchmarkReport[] reports)
     : this(title, hostEnvironmentInfo, config, resultsDirectoryPath, totalTime, validationErrors)
 {
     Benchmarks = benchmarks;
     Table = new SummaryTable(this);
     Reports = reports ?? new BenchmarkReport[0];
 }
 private GenerateResult CreateProjectDirectory(Benchmark benchmark, string rootArtifactsFolderPath, IConfig config)
 {
     var directoryPath = GetBinariesDirectoryPath(benchmark, rootArtifactsFolderPath, config);
     bool exist = Directory.Exists(directoryPath);
     Exception deleteException = null;
     for (int attempt = 0; attempt < 3 && exist; attempt++)
     {
         if (attempt != 0)
             Thread.Sleep(500); // Previous benchmark run didn't release some files
         try
         {
             Directory.Delete(directoryPath, true);
             exist = Directory.Exists(directoryPath);
         }
         catch (DirectoryNotFoundException)
         {
             exist = false;
             break;
         }
         catch (Exception e)
         {
             // Can't delete the directory =(
             deleteException = e;
         }
     }
     if (exist)
         return new GenerateResult(directoryPath, false, deleteException);
     if (!Directory.Exists(directoryPath))
         Directory.CreateDirectory(directoryPath);
     return new GenerateResult(directoryPath, true, null);
 }
 public BenchmarkClassicFlow(Benchmark benchmark, IBenchmarkLogger logger)
 {
     this.benchmark = benchmark;
     generator = new BenchmarkClassicGenerator(logger);
     builder = new BenchmarkClassicBuilder(logger);
     executor = new BenchmarkClassicExecutor(benchmark, logger);
 }
        public string GetValue(Summary summary, Benchmark benchmark)
        {
            var baselineBenchmark = summary.Benchmarks.
                Where(b => b.Job.GetFullInfo() == benchmark.Job.GetFullInfo()).
                Where(b => b.Parameters.FullInfo == benchmark.Parameters.FullInfo).
                FirstOrDefault(b => b.Target.Baseline);
            if (baselineBenchmark == null)
                return "?";

            var baselineMedian = summary.Reports[baselineBenchmark].ResultStatistics.Median;
            var currentMedian = summary.Reports[benchmark].ResultStatistics.Median;

            switch (Kind)
            {
                case DiffKind.Delta:
                    if (benchmark.Target.Baseline)
                        return "Baseline";
                    var diff = (currentMedian - baselineMedian)/baselineMedian*100.0;
                    return diff.ToStr("0.0") + "%";
                case DiffKind.Scaled:
                    var scale = currentMedian/baselineMedian;
                    return scale.ToStr("0.00");
                default:
                    return "?";
            }
        }
示例#23
0
        private ExecuteResult Execute(Process process, Benchmark benchmark, SynchronousProcessOutputLoggerWithDiagnoser loggerWithDiagnoser, IDiagnoser compositeDiagnoser, ILogger logger)
        {
            consoleHandler.SetProcess(process);

            process.Start();

            compositeDiagnoser?.ProcessStarted(process);

            process.EnsureHighPriority(logger);
            if (!benchmark.Job.Affinity.IsAuto)
            {
                process.EnsureProcessorAffinity(benchmark.Job.Affinity.Value);
            }

            loggerWithDiagnoser.ProcessInput();

            process.WaitForExit(); // should we add timeout here?

            compositeDiagnoser?.ProcessStopped(process);

            if (process.ExitCode == 0)
            {
                return new ExecuteResult(true, loggerWithDiagnoser.Lines);
            }

            return new ExecuteResult(true, new string[0]);
        }
示例#24
0
 private ProcessStartInfo CreateStartInfo(Benchmark benchmark, string exeName, string args, string workingDirectory)
 {
     var start = new ProcessStartInfo
     {
         UseShellExecute = false,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         CreateNoWindow = true,
         WorkingDirectory = workingDirectory
     };
     var runtime = benchmark.Job.Runtime == Runtime.Host ? EnvironmentHelper.GetCurrentRuntime() : benchmark.Job.Runtime;
     switch (runtime)
     {
         case Runtime.Clr:
         case Runtime.Dnx:
         case Runtime.Core:
             start.FileName = exeName;
             start.Arguments = args;
             break;
         case Runtime.Mono:
             start.FileName = "mono";
             start.Arguments = exeName + " " + args;
             break;
         default:
             throw new NotSupportedException("Runtime = " + benchmark.Job.Runtime);
     }
     return start;
 }
        protected override string GetBinariesDirectoryPath(Benchmark benchmark, string rootArtifactsFolderPath, IConfig config)
        {
            if (config.KeepBenchmarkFiles)
            {
                return Path.Combine(rootArtifactsFolderPath, "bin", benchmark.ShortInfo);
            }

            return Path.Combine(rootArtifactsFolderPath, "bin", ShortFolderName);
        }
示例#26
0
 public GenerateResult GenerateProject(Benchmark benchmark, ILogger logger)
 {
     var result = CreateProjectDirectory(benchmark);
     GenerateProgramFile(result.DirectoryPath, benchmark);
     GenerateProjectFile(logger, result.DirectoryPath, benchmark);
     GenerateProjectBuildFile(result.DirectoryPath);
     GenerateAppConfigFile(result.DirectoryPath, benchmark.Job);
     return result;
 }
 public BenchmarkGenerateResult GenerateProject(Benchmark benchmark)
 {
     var result = CreateProjectDirectory(benchmark);
     GenerateProgramFile(result.DirectoryPath, benchmark);
     GenerateProjectFile(result.DirectoryPath, benchmark);
     GenerateProjectBuildFile(result.DirectoryPath);
     GenerateAppConfigFile(result.DirectoryPath, benchmark.Task.Configuration);
     return result;
 }
 public static IBenchmarkToolchainFacade CreateToolchain(Benchmark benchmark, IBenchmarkLogger logger)
 {
     switch (benchmark.Task.Configuration.Toolchain)
     {
         case BenchmarkToolchain.Classic:
             return new BenchmarkToolchainFacade(benchmark, new BenchmarkClassicGenerator(logger), new BenchmarkClassicBuilder(logger), new BenchmarkClassicExecutor(benchmark, logger));
         default:
             throw new NotSupportedException();
     }
 }
        public void Stop(Benchmark benchmark, BenchmarkReport report)
        {
            // ETW real-time sessions receive events with a slight delay. Typically it
            // shouldn't be more than a few seconds. This increases the likelihood that
            // all relevant events are processed by the collection thread by the time we
            // are done with the benchmark.
            Thread.Sleep(TimeSpan.FromSeconds(3));

            session.Dispose();
        }
        private IEnumerable<string> GetAllKnownTargetFrameworkVersions(Benchmark benchmark)
        {
            yield return benchmark.Target.Type.Assembly().GetTargetFrameworkVersion(); // the dll that defines benchmark
            yield return Assembly.GetExecutingAssembly().GetTargetFrameworkVersion(); // the executing program

            foreach (var assemblyName in benchmark.Target.Type.Assembly.GetReferencedAssemblies())
            {
                yield return Assembly.Load(assemblyName).GetTargetFrameworkVersion();
            }
        }
示例#31
0
        protected void CustomUpdatePathTargetPositions(ushort vehicleID, ref Vehicle vehicleData, Vector3 refPos, ref int targetPosIndex, int maxTargetPosIndex, float minSqrDistanceA, float minSqrDistanceB)
        {
            PathManager pathMan    = Singleton <PathManager> .instance;
            NetManager  netManager = Singleton <NetManager> .instance;

            Vector4 targetPos = vehicleData.m_targetPos0;

            targetPos.w = 1000f;
            float minSqrDistA      = minSqrDistanceA;
            uint  pathId           = vehicleData.m_path;
            byte  finePathPosIndex = vehicleData.m_pathPositionIndex;
            byte  lastPathOffset   = vehicleData.m_lastPathOffset;

            // initial position
            if (finePathPosIndex == 255)
            {
                finePathPosIndex = 0;
                if (targetPosIndex <= 0)
                {
                    vehicleData.m_pathPositionIndex = 0;
                }

                if (!Singleton <PathManager> .instance.m_pathUnits.m_buffer[pathId].CalculatePathPositionOffset(finePathPosIndex >> 1, targetPos, out lastPathOffset))
                {
                    this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                    return;
                }
            }

            // get current path position, check for errors
            PathUnit.Position currentPosition;
            if (!pathMan.m_pathUnits.m_buffer[pathId].GetPosition(finePathPosIndex >> 1, out currentPosition))
            {
                this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                return;
            }

            // get current segment info, check for errors
            NetInfo curSegmentInfo = netManager.m_segments.m_buffer[(int)currentPosition.m_segment].Info;

            if (curSegmentInfo.m_lanes.Length <= (int)currentPosition.m_lane)
            {
                this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                return;
            }

            // main loop
            uint curLaneId = PathManager.GetLaneID(currentPosition);

            NetInfo.Lane laneInfo = curSegmentInfo.m_lanes[(int)currentPosition.m_lane];
            Bezier3      bezier;
            bool         firstIter = true;     // NON-STOCK CODE

            while (true)
            {
                if ((finePathPosIndex & 1) == 0)
                {
                    // vehicle is not in transition
                    if (laneInfo.m_laneType != NetInfo.LaneType.CargoVehicle)
                    {
                        bool first = true;
                        while (lastPathOffset != currentPosition.m_offset)
                        {
                            // catch up and update target position until we get to the current segment offset
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                float distDiff = Mathf.Sqrt(minSqrDistA) - Vector3.Distance(targetPos, refPos);
                                int   pathOffsetDelta;
                                if (distDiff < 0f)
                                {
                                    pathOffsetDelta = 4;
                                }
                                else
                                {
                                    pathOffsetDelta = 4 + Mathf.Max(0, Mathf.CeilToInt(distDiff * 256f / (netManager.m_lanes.m_buffer[curLaneId].m_length + 1f)));
                                }
                                if (lastPathOffset > currentPosition.m_offset)
                                {
                                    lastPathOffset = (byte)Mathf.Max((int)lastPathOffset - pathOffsetDelta, (int)currentPosition.m_offset);
                                }
                                else if (lastPathOffset < currentPosition.m_offset)
                                {
                                    lastPathOffset = (byte)Mathf.Min((int)lastPathOffset + pathOffsetDelta, (int)currentPosition.m_offset);
                                }
                            }

                            Vector3 curSegPos;
                            Vector3 curSegDir;
                            float   curSegOffset;
                            this.CalculateSegmentPosition(vehicleID, ref vehicleData, currentPosition, curLaneId, lastPathOffset, out curSegPos, out curSegDir, out curSegOffset);
                            targetPos.Set(curSegPos.x, curSegPos.y, curSegPos.z, Mathf.Min(targetPos.w, curSegOffset));
                            float refPosSqrDist = (curSegPos - refPos).sqrMagnitude;
                            if (refPosSqrDist >= minSqrDistA)
                            {
                                if (targetPosIndex <= 0)
                                {
                                    vehicleData.m_lastPathOffset = lastPathOffset;
                                }
                                vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                                minSqrDistA = minSqrDistanceB;
                                refPos      = targetPos;
                                targetPos.w = 1000f;
                                if (targetPosIndex == maxTargetPosIndex)
                                {
                                    // maximum target position index reached
                                    return;
                                }
                            }
                        }
                    }

                    // set vehicle in transition
                    finePathPosIndex += 1;
                    lastPathOffset    = 0;
                    if (targetPosIndex <= 0)
                    {
                        vehicleData.m_pathPositionIndex = finePathPosIndex;
                        vehicleData.m_lastPathOffset    = lastPathOffset;
                    }
                }

                if ((vehicleData.m_flags2 & Vehicle.Flags2.EndStop) != 0)
                {
                    if (targetPosIndex <= 0)
                    {
                        targetPos.w = 0f;
                        if (VectorUtils.LengthSqrXZ(vehicleData.GetLastFrameVelocity()) < 0.01f)
                        {
                            vehicleData.m_flags2 &= ~Vehicle.Flags2.EndStop;
                        }
                    }
                    else
                    {
                        targetPos.w = 1f;
                    }
                    while (targetPosIndex < maxTargetPosIndex)
                    {
                        vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                    }
                    return;
                }

                // vehicle is in transition now

                /*
                 * coarse path position format: 0..11 (always equals 'fine path position' / 2 == 'fine path position' >> 1)
                 * fine path position format: 0..23
                 */

                // find next path unit (or abort if at path end)
                int  nextCoarsePathPosIndex = (finePathPosIndex >> 1) + 1;
                uint nextPathId             = pathId;
                if (nextCoarsePathPosIndex >= (int)pathMan.m_pathUnits.m_buffer[pathId].m_positionCount)
                {
                    nextCoarsePathPosIndex = 0;
                    nextPathId             = pathMan.m_pathUnits.m_buffer[pathId].m_nextPathUnit;
                    if (nextPathId == 0u)
                    {
                        if (targetPosIndex <= 0)
                        {
                            Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                            vehicleData.m_path = 0u;
                        }
                        targetPos.w = 1f;
                        vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                        return;
                    }
                }

                // check for errors
                PathUnit.Position nextPathPos;
                if (!pathMan.m_pathUnits.m_buffer[nextPathId].GetPosition(nextCoarsePathPosIndex, out nextPathPos))
                {
                    this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                    return;
                }

                // check for errors
                NetInfo nextSegmentInfo = netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].Info;
                if (nextSegmentInfo.m_lanes.Length <= (int)nextPathPos.m_lane)
                {
                    this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                    return;
                }

                // find next lane (emergency vehicles / dynamic lane selection)
                int bestLaneIndex = nextPathPos.m_lane;
                if ((vehicleData.m_flags & Vehicle.Flags.Emergency2) != (Vehicle.Flags) 0)
                {
                    bestLaneIndex = FindBestLane(vehicleID, ref vehicleData, nextPathPos);
                }
                else
                {
                    // NON-STOCK CODE START
                    if (firstIter &&
                        this.m_info.m_vehicleType == VehicleInfo.VehicleType.Car &&
                        !this.m_info.m_isLargeVehicle
                        )
                    {
                        bool mayFindBestLane = false;
#if BENCHMARK
                        using (var bm = new Benchmark(null, "MayFindBestLane")) {
#endif
                        mayFindBestLane = VehicleBehaviorManager.Instance.MayFindBestLane(vehicleID, ref vehicleData, ref VehicleStateManager.Instance.VehicleStates[vehicleID]);
#if BENCHMARK
                    }
#endif

                        if (mayFindBestLane)
                        {
                            uint next2PathId       = nextPathId;
                            int  next2PathPosIndex = nextCoarsePathPosIndex;
                            bool next2Invalid;
                            PathUnit.Position next2PathPos;
                            NetInfo           next2SegmentInfo = null;
                            PathUnit.Position next3PathPos;
                            NetInfo           next3SegmentInfo = null;
                            PathUnit.Position next4PathPos;
                            if (PathUnit.GetNextPosition(ref next2PathId, ref next2PathPosIndex, out next2PathPos, out next2Invalid))
                            {
                                next2SegmentInfo = netManager.m_segments.m_buffer[(int)next2PathPos.m_segment].Info;

                                uint next3PathId       = next2PathId;
                                int  next3PathPosIndex = next2PathPosIndex;
                                bool next3Invalid;
                                if (PathUnit.GetNextPosition(ref next3PathId, ref next3PathPosIndex, out next3PathPos, out next3Invalid))
                                {
                                    next3SegmentInfo = netManager.m_segments.m_buffer[(int)next3PathPos.m_segment].Info;

                                    uint next4PathId       = next3PathId;
                                    int  next4PathPosIndex = next3PathPosIndex;
                                    bool next4Invalid;
                                    if (!PathUnit.GetNextPosition(ref next4PathId, ref next4PathPosIndex, out next4PathPos, out next4Invalid))
                                    {
                                        next4PathPos = default(PathUnit.Position);
                                    }
                                }
                                else
                                {
                                    next3PathPos = default(PathUnit.Position);
                                    next4PathPos = default(PathUnit.Position);
                                }
                            }
                            else
                            {
                                next2PathPos = default(PathUnit.Position);
                                next3PathPos = default(PathUnit.Position);
                                next4PathPos = default(PathUnit.Position);
                            }

#if BENCHMARK
                            using (var bm = new Benchmark(null, "FindBestLane")) {
#endif
                            bestLaneIndex = VehicleBehaviorManager.Instance.FindBestLane(vehicleID, ref vehicleData, ref VehicleStateManager.Instance.VehicleStates[vehicleID], curLaneId, currentPosition, curSegmentInfo, nextPathPos, nextSegmentInfo, next2PathPos, next2SegmentInfo, next3PathPos, next3SegmentInfo, next4PathPos);
#if BENCHMARK
                        }
#endif
                        }
                        // NON-STOCK CODE END
                    }
                }

                // update lane index
                if (bestLaneIndex != (int)nextPathPos.m_lane)
                {
                    nextPathPos.m_lane = (byte)bestLaneIndex;
                    pathMan.m_pathUnits.m_buffer[nextPathId].SetPosition(nextCoarsePathPosIndex, nextPathPos);
#if BENCHMARK
                    using (var bm = new Benchmark(null, "AddTraffic")) {
#endif
                    // prevent multiple lane changes to the same lane from happening at the same time
                    TrafficMeasurementManager.Instance.AddTraffic(nextPathPos.m_segment, nextPathPos.m_lane
#if MEASUREDENSITY
                                                                  , VehicleStateManager.Instance.VehicleStates[vehicleID].totalLength
#endif
                                                                  , 0); // NON-STOCK CODE
#if BENCHMARK
                }
#endif
                }

                // check for errors
                uint nextLaneId           = PathManager.GetLaneID(nextPathPos);
                NetInfo.Lane nextLaneInfo = nextSegmentInfo.m_lanes[(int)nextPathPos.m_lane];
                ushort curSegStartNodeId  = netManager.m_segments.m_buffer[(int)currentPosition.m_segment].m_startNode;
                ushort curSegEndNodeId    = netManager.m_segments.m_buffer[(int)currentPosition.m_segment].m_endNode;
                ushort nextSegStartNodeId = netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].m_startNode;
                ushort nextSegEndNodeId   = netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].m_endNode;
                if (nextSegStartNodeId != curSegStartNodeId &&
                    nextSegStartNodeId != curSegEndNodeId &&
                    nextSegEndNodeId != curSegStartNodeId &&
                    nextSegEndNodeId != curSegEndNodeId &&
                    ((netManager.m_nodes.m_buffer[(int)curSegStartNodeId].m_flags | netManager.m_nodes.m_buffer[(int)curSegEndNodeId].m_flags) & NetNode.Flags.Disabled) == NetNode.Flags.None &&
                    ((netManager.m_nodes.m_buffer[(int)nextSegStartNodeId].m_flags | netManager.m_nodes.m_buffer[(int)nextSegEndNodeId].m_flags) & NetNode.Flags.Disabled) != NetNode.Flags.None)
                {
                    this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                    return;
                }

                // park vehicle
                if (nextLaneInfo.m_laneType == NetInfo.LaneType.Pedestrian)
                {
                    if (vehicleID != 0 && (vehicleData.m_flags & Vehicle.Flags.Parking) == (Vehicle.Flags) 0)
                    {
                        byte inOffset  = currentPosition.m_offset;
                        byte outOffset = currentPosition.m_offset;
                        if (this.ParkVehicle(vehicleID, ref vehicleData, currentPosition, nextPathId, nextCoarsePathPosIndex << 1, out outOffset))
                        {
                            if (outOffset != inOffset)
                            {
                                if (targetPosIndex <= 0)
                                {
                                    vehicleData.m_pathPositionIndex = (byte)((int)vehicleData.m_pathPositionIndex & -2);
                                    vehicleData.m_lastPathOffset    = inOffset;
                                }
                                currentPosition.m_offset = outOffset;
                                pathMan.m_pathUnits.m_buffer[(int)((UIntPtr)pathId)].SetPosition(finePathPosIndex >> 1, currentPosition);
                            }
                            vehicleData.m_flags |= Vehicle.Flags.Parking;
                        }
                        else
                        {
                            this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                        }
                    }
                    return;
                }

                // check for errors
                if ((byte)(nextLaneInfo.m_laneType & (NetInfo.LaneType.Vehicle | NetInfo.LaneType.CargoVehicle | NetInfo.LaneType.TransportVehicle)) == 0)
                {
                    this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                    return;
                }

                // change vehicle
                if (nextLaneInfo.m_vehicleType != this.m_info.m_vehicleType &&
                    this.NeedChangeVehicleType(vehicleID, ref vehicleData, nextPathPos, nextLaneId, nextLaneInfo.m_vehicleType, ref targetPos)
                    )
                {
                    float targetPos0ToRefPosSqrDist = ((Vector3)targetPos - refPos).sqrMagnitude;
                    if (targetPos0ToRefPosSqrDist >= minSqrDistA)
                    {
                        vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                    }
                    if (targetPosIndex <= 0)
                    {
                        while (targetPosIndex < maxTargetPosIndex)
                        {
                            vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                        }
                        if (nextPathId != vehicleData.m_path)
                        {
                            Singleton <PathManager> .instance.ReleaseFirstUnit(ref vehicleData.m_path);
                        }
                        vehicleData.m_pathPositionIndex = (byte)(nextCoarsePathPosIndex << 1);
                        PathUnit.CalculatePathPositionOffset(nextLaneId, targetPos, out vehicleData.m_lastPathOffset);
                        if (vehicleID != 0 && !this.ChangeVehicleType(vehicleID, ref vehicleData, nextPathPos, nextLaneId))
                        {
                            this.InvalidPath(vehicleID, ref vehicleData, vehicleID, ref vehicleData);
                        }
                    }
                    else
                    {
                        while (targetPosIndex < maxTargetPosIndex)
                        {
                            vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                        }
                    }
                    return;
                }

                // unset leaving flag
                if (nextPathPos.m_segment != currentPosition.m_segment && vehicleID != 0)
                {
                    vehicleData.m_flags &= ~Vehicle.Flags.Leaving;
                }

                // calculate next segment offset
                byte nextSegOffset = 0;
                if ((vehicleData.m_flags & Vehicle.Flags.Flying) != (Vehicle.Flags) 0)
                {
                    nextSegOffset = (byte)((nextPathPos.m_offset < 128) ? 255 : 0);
                }
                else if (curLaneId != nextLaneId && laneInfo.m_laneType != NetInfo.LaneType.CargoVehicle)
                {
                    PathUnit.CalculatePathPositionOffset(nextLaneId, targetPos, out nextSegOffset);
                    bezier = default(Bezier3);
                    Vector3 curSegDir;
                    float   maxSpeed;
                    this.CalculateSegmentPosition(vehicleID, ref vehicleData, currentPosition, curLaneId, currentPosition.m_offset, out bezier.a, out curSegDir, out maxSpeed);
                    bool calculateNextNextPos = lastPathOffset == 0;
                    if (calculateNextNextPos)
                    {
                        if ((vehicleData.m_flags & Vehicle.Flags.Reversed) != (Vehicle.Flags) 0)
                        {
                            calculateNextNextPos = (vehicleData.m_trailingVehicle == 0);
                        }
                        else
                        {
                            calculateNextNextPos = (vehicleData.m_leadingVehicle == 0);
                        }
                    }
                    Vector3 nextSegDir;
                    float   nextMaxSpeed;
                    if (calculateNextNextPos)
                    {
                        PathUnit.Position nextNextPathPos;
                        if (!pathMan.m_pathUnits.m_buffer[nextPathId].GetNextPosition(nextCoarsePathPosIndex, out nextNextPathPos))
                        {
                            nextNextPathPos = default(PathUnit.Position);
                        }
                        this.CalculateSegmentPosition(vehicleID, ref vehicleData, nextNextPathPos, nextPathPos, nextLaneId, nextSegOffset, currentPosition, curLaneId, currentPosition.m_offset, targetPosIndex, out bezier.d, out nextSegDir, out nextMaxSpeed);
                    }
                    else
                    {
                        this.CalculateSegmentPosition(vehicleID, ref vehicleData, nextPathPos, nextLaneId, nextSegOffset, out bezier.d, out nextSegDir, out nextMaxSpeed);
                    }
                    if (nextMaxSpeed < 0.01f || (netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].m_flags & (NetSegment.Flags.Collapsed | NetSegment.Flags.Flooded)) != NetSegment.Flags.None)
                    {
                        if (targetPosIndex <= 0)
                        {
                            vehicleData.m_lastPathOffset = lastPathOffset;
                        }
                        targetPos   = bezier.a;
                        targetPos.w = 0f;
                        while (targetPosIndex < maxTargetPosIndex)
                        {
                            vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                        }
                        return;
                    }
                    if (currentPosition.m_offset == 0)
                    {
                        curSegDir = -curSegDir;
                    }
                    if (nextSegOffset < nextPathPos.m_offset)
                    {
                        nextSegDir = -nextSegDir;
                    }
                    curSegDir.Normalize();
                    nextSegDir.Normalize();
                    float dist;
                    NetSegment.CalculateMiddlePoints(bezier.a, curSegDir, bezier.d, nextSegDir, true, true, out bezier.b, out bezier.c, out dist);
                    if (dist > 1f)
                    {
                        ushort nextNodeId;
                        if (nextSegOffset == 0)
                        {
                            nextNodeId = netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].m_startNode;
                        }
                        else if (nextSegOffset == 255)
                        {
                            nextNodeId = netManager.m_segments.m_buffer[(int)nextPathPos.m_segment].m_endNode;
                        }
                        else
                        {
                            nextNodeId = 0;
                        }
                        float curve = 1.57079637f * (1f + Vector3.Dot(curSegDir, nextSegDir));
                        if (dist > 1f)
                        {
                            curve /= dist;
                        }
                        nextMaxSpeed = Mathf.Min(nextMaxSpeed, this.CalculateTargetSpeed(vehicleID, ref vehicleData, 1000f, curve));
                        while (lastPathOffset < 255)
                        {
                            float distDiff = Mathf.Sqrt(minSqrDistA) - Vector3.Distance(targetPos, refPos);
                            int   pathOffsetDelta;
                            if (distDiff < 0f)
                            {
                                pathOffsetDelta = 8;
                            }
                            else
                            {
                                pathOffsetDelta = 8 + Mathf.Max(0, Mathf.CeilToInt(distDiff * 256f / (dist + 1f)));
                            }
                            lastPathOffset = (byte)Mathf.Min((int)lastPathOffset + pathOffsetDelta, 255);
                            Vector3 bezierPos = bezier.Position((float)lastPathOffset * 0.003921569f);
                            targetPos.Set(bezierPos.x, bezierPos.y, bezierPos.z, Mathf.Min(targetPos.w, nextMaxSpeed));
                            float sqrMagnitude2 = (bezierPos - refPos).sqrMagnitude;
                            if (sqrMagnitude2 >= minSqrDistA)
                            {
                                if (targetPosIndex <= 0)
                                {
                                    vehicleData.m_lastPathOffset = lastPathOffset;
                                }
                                if (nextNodeId != 0)
                                {
                                    this.UpdateNodeTargetPos(vehicleID, ref vehicleData, nextNodeId, ref netManager.m_nodes.m_buffer[(int)nextNodeId], ref targetPos, targetPosIndex);
                                }
                                vehicleData.SetTargetPos(targetPosIndex++, targetPos);
                                minSqrDistA = minSqrDistanceB;
                                refPos      = targetPos;
                                targetPos.w = 1000f;
                                if (targetPosIndex == maxTargetPosIndex)
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
                else
                {
                    PathUnit.CalculatePathPositionOffset(nextLaneId, targetPos, out nextSegOffset);
                }

                // check for arrival
                if (targetPosIndex <= 0)
                {
                    if ((netManager.m_segments.m_buffer[nextPathPos.m_segment].m_flags & NetSegment.Flags.Untouchable) != 0 && (netManager.m_segments.m_buffer[currentPosition.m_segment].m_flags & NetSegment.Flags.Untouchable) == NetSegment.Flags.None)
                    {
                        ushort ownerBuildingId = NetSegment.FindOwnerBuilding(nextPathPos.m_segment, 363f);
                        if (ownerBuildingId != 0)
                        {
                            BuildingManager buildingMan       = Singleton <BuildingManager> .instance;
                            BuildingInfo    ownerBuildingInfo = buildingMan.m_buildings.m_buffer[ownerBuildingId].Info;
                            InstanceID      itemID            = default(InstanceID);
                            itemID.Vehicle = vehicleID;
                            ownerBuildingInfo.m_buildingAI.EnterBuildingSegment(ownerBuildingId, ref buildingMan.m_buildings.m_buffer[ownerBuildingId], nextPathPos.m_segment, nextPathPos.m_offset, itemID);
                        }
                    }

                    if (nextCoarsePathPosIndex == 0)
                    {
                        Singleton <PathManager> .instance.ReleaseFirstUnit(ref vehicleData.m_path);
                    }
                    if (nextCoarsePathPosIndex >= (int)(pathMan.m_pathUnits.m_buffer[(int)((UIntPtr)nextPathId)].m_positionCount - 1) && pathMan.m_pathUnits.m_buffer[(int)((UIntPtr)nextPathId)].m_nextPathUnit == 0u && vehicleID != 0)
                    {
                        this.ArrivingToDestination(vehicleID, ref vehicleData);
                    }
                }

                // prepare next loop iteration: go to next path position
                pathId           = nextPathId;
                finePathPosIndex = (byte)(nextCoarsePathPosIndex << 1);
                lastPathOffset   = nextSegOffset;
                if (targetPosIndex <= 0)
                {
                    vehicleData.m_pathPositionIndex = finePathPosIndex;
                    vehicleData.m_lastPathOffset    = lastPathOffset;
                    vehicleData.m_flags             = ((vehicleData.m_flags & ~(Vehicle.Flags.OnGravel | Vehicle.Flags.Underground | Vehicle.Flags.Transition)) | nextSegmentInfo.m_setVehicleFlags);
                    if (this.LeftHandDrive(nextLaneInfo))
                    {
                        vehicleData.m_flags |= Vehicle.Flags.LeftHandDrive;
                    }
                    else
                    {
                        vehicleData.m_flags &= (Vehicle.Flags.Created | Vehicle.Flags.Deleted | Vehicle.Flags.Spawned | Vehicle.Flags.Inverted | Vehicle.Flags.TransferToTarget | Vehicle.Flags.TransferToSource | Vehicle.Flags.Emergency1 | Vehicle.Flags.Emergency2 | Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped | Vehicle.Flags.Leaving | Vehicle.Flags.Arriving | Vehicle.Flags.Reversed | Vehicle.Flags.TakingOff | Vehicle.Flags.Flying | Vehicle.Flags.Landing | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo | Vehicle.Flags.GoingBack | Vehicle.Flags.WaitingTarget | Vehicle.Flags.Importing | Vehicle.Flags.Exporting | Vehicle.Flags.Parking | Vehicle.Flags.CustomName | Vehicle.Flags.OnGravel | Vehicle.Flags.WaitingLoading | Vehicle.Flags.Congestion | Vehicle.Flags.DummyTraffic | Vehicle.Flags.Underground | Vehicle.Flags.Transition | Vehicle.Flags.InsideBuilding);
                    }
                }
                currentPosition = nextPathPos;
                curLaneId       = nextLaneId;
                laneInfo        = nextLaneInfo;
                firstIter       = false;           // NON-STOCK CODE
            }
        }
 //
 // Summary:
 //     Value in this column formatted using the specified style.
 public string GetValue(Summary summary, Benchmark benchmark, ISummaryStyle style) => (JemStatFunction.Invoke());
示例#33
0
 public void Initialize(Benchmark benchmark)
 {
     _greeter = XRPCHandler.Single.Greeter;
 }
        public bool CustomStartPathFind(ushort vehicleID, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget)
        {
#if DEBUG
            //Log._Debug($"CustomCargoTruckAI.CustomStartPathFind called for vehicle {vehicleID}");
#endif

#if BENCHMARK
            using (var bm = new Benchmark(null, "OnStartPathFind")) {
#endif
            ExtVehicleType vehicleType = VehicleStateManager.Instance.OnStartPathFind(vehicleID, ref vehicleData, null);
            if (vehicleType == ExtVehicleType.None)
            {
#if DEBUG
                Log.Warning($"CustomCargoTruck.CustomStartPathFind: Vehicle {vehicleID} does not have a valid vehicle type!");
#endif
            }
#if BENCHMARK
        }
#endif

            if ((vehicleData.m_flags & (Vehicle.Flags.TransferToSource | Vehicle.Flags.GoingBack)) != 0)
            {
                return(base.StartPathFind(vehicleID, ref vehicleData, startPos, endPos, startBothWays, endBothWays, undergroundTarget));
            }

            bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != 0;
            PathUnit.Position startPosA;
            PathUnit.Position startPosB;
            float startDistSqrA;
            float startDistSqrB;
            bool startPosFound = CustomPathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, allowUnderground, false, 32f, out startPosA, out startPosB, out startDistSqrA, out startDistSqrB);
            PathUnit.Position startAltPosA;
            PathUnit.Position startAltPosB;
            float startAltDistSqrA;
            float startAltDistSqrB;
            if (CustomPathManager.FindPathPosition(startPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship | VehicleInfo.VehicleType.Plane, allowUnderground, false, 32f, out startAltPosA, out startAltPosB, out startAltDistSqrA, out startAltDistSqrB))
            {
                if (!startPosFound || (startAltDistSqrA < startDistSqrA && (Mathf.Abs(endPos.x) > 8000f || Mathf.Abs(endPos.z) > 8000f)))
                {
                    startPosA     = startAltPosA;
                    startPosB     = startAltPosB;
                    startDistSqrA = startAltDistSqrA;
                    startDistSqrB = startAltDistSqrB;
                }
                startPosFound = true;
            }
            PathUnit.Position endPosA;
            PathUnit.Position endPosB;
            float endDistSqrA;
            float endDistSqrB;
            bool endPosFound = CustomPathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, VehicleInfo.VehicleType.Car, undergroundTarget, false, 32f, out endPosA, out endPosB, out endDistSqrA, out endDistSqrB);
            PathUnit.Position endAltPosA;
            PathUnit.Position endAltPosB;
            float endAltDistSqrA;
            float endAltDistSqrB;
            if (CustomPathManager.FindPathPosition(endPos, ItemClass.Service.PublicTransport, NetInfo.LaneType.Vehicle, VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship | VehicleInfo.VehicleType.Plane, undergroundTarget, false, 32f, out endAltPosA, out endAltPosB, out endAltDistSqrA, out endAltDistSqrB))
            {
                if (!endPosFound || (endAltDistSqrA < endDistSqrA && (Mathf.Abs(endPos.x) > 8000f || Mathf.Abs(endPos.z) > 8000f)))
                {
                    endPosA     = endAltPosA;
                    endPosB     = endAltPosB;
                    endDistSqrA = endAltDistSqrA;
                    endDistSqrB = endAltDistSqrB;
                }
                endPosFound = true;
            }
            if (startPosFound && endPosFound)
            {
                CustomPathManager pathMan = CustomPathManager._instance;
                if (!startBothWays || startDistSqrA < 10f)
                {
                    startPosB = default(PathUnit.Position);
                }
                if (!endBothWays || endDistSqrA < 10f)
                {
                    endPosB = default(PathUnit.Position);
                }
                NetInfo.LaneType        laneTypes    = NetInfo.LaneType.Vehicle | NetInfo.LaneType.CargoVehicle;
                VehicleInfo.VehicleType vehicleTypes = VehicleInfo.VehicleType.Car | VehicleInfo.VehicleType.Train | VehicleInfo.VehicleType.Ship | VehicleInfo.VehicleType.Plane;
                uint path;
                // NON-STOCK CODE START
                PathCreationArgs args;
                args.extPathType         = ExtCitizenInstance.ExtPathType.None;
                args.extVehicleType      = ExtVehicleType.CargoVehicle;
                args.vehicleId           = vehicleID;
                args.spawned             = (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0;
                args.buildIndex          = Singleton <SimulationManager> .instance.m_currentBuildIndex;
                args.startPosA           = startPosA;
                args.startPosB           = startPosB;
                args.endPosA             = endPosA;
                args.endPosB             = endPosB;
                args.vehiclePosition     = default(PathUnit.Position);
                args.laneTypes           = laneTypes;
                args.vehicleTypes        = vehicleTypes;
                args.maxLength           = 20000f;
                args.isHeavyVehicle      = this.IsHeavyVehicle();
                args.hasCombustionEngine = this.CombustionEngine();
                args.ignoreBlocked       = this.IgnoreBlocked(vehicleID, ref vehicleData);
                args.ignoreFlooded       = false;
                args.ignoreCosts         = false;
                args.randomParking       = false;
                args.stablePath          = false;
                args.skipQueue           = (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0;

                if (pathMan.CreatePath(out path, ref Singleton <SimulationManager> .instance.m_randomizer, args))
                {
                    // NON-STOCK CODE END
                    if (vehicleData.m_path != 0u)
                    {
                        pathMan.ReleasePath(vehicleData.m_path);
                    }
                    vehicleData.m_path   = path;
                    vehicleData.m_flags |= Vehicle.Flags.WaitingPath;
                    return(true);
                }
            }
            return(false);
        }
示例#35
0
 public static IDiagnoser GetCompositeDiagnoser(this IConfig config, Benchmark benchmark, RunMode runMode)
 => config.GetDiagnosers().Any(d => d.GetRunMode(benchmark) == runMode)
         ? new CompositeDiagnoser(config.GetDiagnosers().Where(d => d.GetRunMode(benchmark) == runMode).ToArray())
         : null;
 public AStarComparer(Benchmark <string> benchmark = null)
 {
     Benchmark = benchmark;
 }
示例#37
0
 protected override string GetBuildArtifactsDirectoryPath(Benchmark benchmark, string programName)
 => Path.GetDirectoryName(benchmark.Target.Type.GetTypeInfo().Assembly.Location);
示例#38
0
 public string GetValue(Summary summary, Benchmark benchmark, ISummaryStyle style) => benchmark.Target.Method.DeclaringType.Name.Replace("Benchmarks", string.Empty);
示例#39
0
 public bool IsDefault(Summary summary, Benchmark benchmark) => false;
示例#40
0
文件: Game.cs 项目: dnqbob/OpenRA
 public static void BenchmarkMode(string prefix)
 {
     benchmark = new Benchmark(prefix);
 }
示例#41
0
        public bool CustomStartPathFind(ushort vehicleID, ref Vehicle vehicleData, Vector3 startPos, Vector3 endPos, bool startBothWays, bool endBothWays, bool undergroundTarget)
        {
#if DEBUG
            //Log._Debug($"CustomFireTruckAI.CustomStartPathFind called for vehicle {vehicleID}");
#endif
            ExtVehicleType vehicleType = ExtVehicleType.None;
#if BENCHMARK
            using (var bm = new Benchmark(null, "OnStartPathFind")) {
#endif
            vehicleType = VehicleStateManager.Instance.OnStartPathFind(vehicleID, ref vehicleData, (vehicleData.m_flags & Vehicle.Flags.Emergency2) != 0 ? ExtVehicleType.Emergency : ExtVehicleType.Service);
#if BENCHMARK
        }
#endif
            VehicleInfo info      = this.m_info;
            bool allowUnderground = (vehicleData.m_flags & (Vehicle.Flags.Underground | Vehicle.Flags.Transition)) != 0;
            PathUnit.Position startPosA;
            PathUnit.Position startPosB;
            float startDistSqrA;
            float startDistSqrB;
            PathUnit.Position endPosA;
            PathUnit.Position endPosB;
            float endDistSqrA;
            float endDistSqrB;
            if (CustomPathManager.FindPathPosition(startPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, allowUnderground, false, 32f, out startPosA, out startPosB, out startDistSqrA, out startDistSqrB) &&
                CustomPathManager.FindPathPosition(endPos, ItemClass.Service.Road, NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle, info.m_vehicleType, undergroundTarget, false, 32f, out endPosA, out endPosB, out endDistSqrA, out endDistSqrB))
            {
                if (!startBothWays || startDistSqrA < 10f)
                {
                    startPosB = default(PathUnit.Position);
                }
                if (!endBothWays || endDistSqrA < 10f)
                {
                    endPosB = default(PathUnit.Position);
                }
                uint path;
                // NON-STOCK CODE START
                PathCreationArgs args;
                args.extPathType         = ExtCitizenInstance.ExtPathType.None;
                args.extVehicleType      = vehicleType;
                args.vehicleId           = vehicleID;
                args.buildIndex          = Singleton <SimulationManager> .instance.m_currentBuildIndex;
                args.startPosA           = startPosA;
                args.startPosB           = startPosB;
                args.endPosA             = endPosA;
                args.endPosB             = endPosB;
                args.vehiclePosition     = default(PathUnit.Position);
                args.laneTypes           = NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle;
                args.vehicleTypes        = info.m_vehicleType;
                args.maxLength           = 20000f;
                args.isHeavyVehicle      = this.IsHeavyVehicle();
                args.hasCombustionEngine = this.CombustionEngine();
                args.ignoreBlocked       = this.IgnoreBlocked(vehicleID, ref vehicleData);
                args.ignoreFlooded       = false;
                args.randomParking       = false;
                args.stablePath          = false;
                args.skipQueue           = (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0;

                if (CustomPathManager._instance.CreatePath(out path, ref Singleton <SimulationManager> .instance.m_randomizer, args))
                {
                    // NON-STOCK CODE END
                    if (vehicleData.m_path != 0u)
                    {
                        Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);
                    }
                    vehicleData.m_path   = path;
                    vehicleData.m_flags |= Vehicle.Flags.WaitingPath;
                    return(true);
                }
            }
            else
            {
                PathfindFailure(vehicleID, ref vehicleData);
            }
            return(false);
        }
示例#42
0
 public void Initialize(Benchmark benchmark)
 {
     Greeter = GRPCHandler.GetClient();
 }
示例#43
0
 public void BeforeAnythingElse(Process process, Benchmark benchmark) => Start(process, benchmark);
示例#44
0
 public void AfterSetup(Process process, Benchmark benchmark)
 {
 }
示例#45
0
        public bool CustomCheckTrafficLights(ushort nodeId, ushort segmentId)
        {
#if DEBUGTTL
            bool debug = GlobalConfig.Instance.Debug.Switches[7] && GlobalConfig.Instance.Debug.NodeId == nodeId;
#endif

            var netManager = Singleton <NetManager> .instance;

            var currentFrameIndex = Singleton <SimulationManager> .instance.m_currentFrameIndex;
            var num          = (uint)(((int)nodeId << 8) / 32768);
            var stepWaitTime = currentFrameIndex - num & 255u;

            // NON-STOCK CODE START //

            bool customSim = false;
#if BENCHMARK
            using (var bm = new Benchmark(null, "GetNodeSimulation")) {
#endif
            customSim = Options.timedLightsEnabled && TrafficLightSimulationManager.Instance.HasActiveSimulation(nodeId);
#if BENCHMARK
        }
#endif
            RoadBaseAI.TrafficLightState pedestrianLightState;
            bool startNode = netManager.m_segments.m_buffer[segmentId].m_startNode == nodeId;

            ICustomSegmentLights lights = null;
#if BENCHMARK
            using (var bm = new Benchmark(null, "GetSegmentLights")) {
#endif
            if (customSim)
            {
                lights = CustomSegmentLightsManager.Instance.GetSegmentLights(segmentId, startNode, false);
            }
#if BENCHMARK
        }
#endif

            if (lights == null)
            {
                // NON-STOCK CODE END //
                RoadBaseAI.TrafficLightState vehicleLightState;
                bool vehicles;
                bool pedestrians;

#if DEBUGTTL
                if (debug)
                {
                    Log._Debug($"CustomHumanAI.CustomCheckTrafficLights({nodeId}, {segmentId}): No custom simulation!");
                }
#endif

                RoadBaseAI.GetTrafficLightState(nodeId, ref netManager.m_segments.m_buffer[segmentId], currentFrameIndex - num, out vehicleLightState, out pedestrianLightState, out vehicles, out pedestrians);
                if (pedestrianLightState == RoadBaseAI.TrafficLightState.GreenToRed || pedestrianLightState == RoadBaseAI.TrafficLightState.Red)
                {
                    if (!pedestrians && stepWaitTime >= 196u)
                    {
                        RoadBaseAI.SetTrafficLightState(nodeId, ref netManager.m_segments.m_buffer[segmentId], currentFrameIndex - num, vehicleLightState, pedestrianLightState, vehicles, true);
                    }
                    return(false);
                }
                // NON-STOCK CODE START //
            }
            else
            {
                if (lights.InvalidPedestrianLight)
                {
                    pedestrianLightState = RoadBaseAI.TrafficLightState.Green;
                }
                else
                {
                    pedestrianLightState = (RoadBaseAI.TrafficLightState)lights.PedestrianLightState;
                }

#if DEBUGTTL
                if (debug)
                {
                    Log._Debug($"CustomHumanAI.CustomCheckTrafficLights({nodeId}, {segmentId}): Custom simulation! pedestrianLightState={pedestrianLightState}, lights.InvalidPedestrianLight={lights.InvalidPedestrianLight}");
                }
#endif
            }
            // NON-STOCK CODE END //

            switch (pedestrianLightState)
            {
            case RoadBaseAI.TrafficLightState.RedToGreen:
                if (stepWaitTime < 60u)
                {
                    return(false);
                }
                break;

            case RoadBaseAI.TrafficLightState.Red:
            case RoadBaseAI.TrafficLightState.GreenToRed:
                return(false);
            }
            return(true);
        }
示例#46
0
 protected abstract void AttachToEvents(TraceEventSession traceEventSession, Benchmark benchmark);
示例#47
0
        public void CustomSimulationStep(ushort instanceID, ref CitizenInstance instanceData, Vector3 physicsLodRefPos)
        {
            uint citizenId = instanceData.m_citizen;

            if ((instanceData.m_flags & (CitizenInstance.Flags.Blown | CitizenInstance.Flags.Floating)) != CitizenInstance.Flags.None && (instanceData.m_flags & CitizenInstance.Flags.Character) == CitizenInstance.Flags.None)
            {
                Singleton <CitizenManager> .instance.ReleaseCitizenInstance(instanceID);

                if (citizenId != 0u)
                {
                    Singleton <CitizenManager> .instance.ReleaseCitizen(citizenId);
                }
                return;
            }

            if ((instanceData.m_flags & CitizenInstance.Flags.WaitingPath) != CitizenInstance.Flags.None)
            {
                PathManager pathManager   = Singleton <PathManager> .instance;
                byte        pathFindFlags = pathManager.m_pathUnits.m_buffer[instanceData.m_path].m_pathFindFlags;

                // NON-STOCK CODE START
                ExtPathState mainPathState = ExtPathState.Calculating;
                if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || instanceData.m_path == 0)
                {
                    mainPathState = ExtPathState.Failed;
                }
                else if ((pathFindFlags & PathUnit.FLAG_READY) != 0)
                {
                    mainPathState = ExtPathState.Ready;
                }

#if DEBUG
                if (GlobalConfig.Instance.Debug.Switches[2])
                {
                    Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): Path={instanceData.m_path}, mainPathState={mainPathState}");
                }
#endif

                ExtSoftPathState finalPathState = ExtSoftPathState.None;
#if BENCHMARK
                using (var bm = new Benchmark(null, "ConvertPathStateToSoftPathState+UpdateCitizenPathState")) {
#endif
                finalPathState = ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
                if (Options.prohibitPocketCars)
                {
                    finalPathState = AdvancedParkingManager.Instance.UpdateCitizenPathState(instanceID, ref instanceData, ref ExtCitizenInstanceManager.Instance.ExtInstances[instanceID], ref Singleton <CitizenManager> .instance.m_citizens.m_buffer[instanceData.m_citizen], mainPathState);
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): Applied Parking AI logic. Path={instanceData.m_path}, mainPathState={mainPathState}, finalPathState={finalPathState}, extCitizenInstance={ExtCitizenInstanceManager.Instance.ExtInstances[instanceID]}");
                    }
#endif
                }
#if BENCHMARK
            }
#endif

                switch (finalPathState)
                {
                case ExtSoftPathState.Ready:
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): Path-finding succeeded for citizen instance {instanceID} (finalPathState={finalPathState}). Path: {instanceData.m_path} -- calling HumanAI.PathfindSuccess");
                    }
#endif
                    this.Spawn(instanceID, ref instanceData);
                    instanceData.m_pathPositionIndex = 255;
                    instanceData.m_flags            &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags            &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering);
                    // NON-STOCK CODE START (transferred from ResidentAI.PathfindSuccess)
                    if (citizenId != 0 && (Singleton <CitizenManager> .instance.m_citizens.m_buffer[citizenId].m_flags & (Citizen.Flags.Tourist | Citizen.Flags.MovingIn | Citizen.Flags.DummyTraffic)) == Citizen.Flags.MovingIn)
                    {
                        StatisticBase statisticBase = Singleton <StatisticsManager> .instance.Acquire <StatisticInt32>(StatisticType.MoveRate);

                        statisticBase.Add(1);
                    }
                    // NON-STOCK CODE END
                    this.PathfindSuccess(instanceID, ref instanceData);
                    break;

                case ExtSoftPathState.Ignore:
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): Path-finding result shall be ignored for citizen instance {instanceID} (finalPathState={finalPathState}). Path: {instanceData.m_path} -- ignoring");
                    }
#endif
                    return;

                case ExtSoftPathState.Calculating:
                default:
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): Path-finding result undetermined for citizen instance {instanceID} (finalPathState={finalPathState}). Path: {instanceData.m_path} -- continue");
                    }
#endif
                    break;

                case ExtSoftPathState.FailedHard:
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): HARD path-finding failure for citizen instance {instanceID} (finalPathState={finalPathState}). Path: {instanceData.m_path} -- calling HumanAI.PathfindFailure");
                    }
#endif
                    instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering);
                    Singleton <PathManager> .instance.ReleasePath(instanceData.m_path);

                    instanceData.m_path = 0u;
                    this.PathfindFailure(instanceID, ref instanceData);
                    return;

                case ExtSoftPathState.FailedSoft:
#if DEBUG
                    if (GlobalConfig.Instance.Debug.Switches[2])
                    {
                        Log._Debug($"CustomHumanAI.CustomSimulationStep({instanceID}): SOFT path-finding failure for citizen instance {instanceID} (finalPathState={finalPathState}). Path: {instanceData.m_path} -- calling HumanAI.InvalidPath");
                    }
#endif
                    // path mode has been updated, repeat path-finding
                    instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown | CitizenInstance.Flags.Cheering);
                    this.InvalidPath(instanceID, ref instanceData);
                    return;
                }
                // NON-STOCK CODE END
            }

            // NON-STOCK CODE START
#if BENCHMARK
            using (var bm = new Benchmark(null, "ExtSimulationStep")) {
#endif
            if (Options.prohibitPocketCars)
            {
                if (ExtSimulationStep(instanceID, ref instanceData, ref ExtCitizenInstanceManager.Instance.ExtInstances[instanceID], physicsLodRefPos))
                {
                    return;
                }
            }
#if BENCHMARK
        }
#endif
            // NON-STOCK CODE END

            base.SimulationStep(instanceID, ref instanceData, physicsLodRefPos);

            CitizenManager citizenManager = Singleton <CitizenManager> .instance;
            VehicleManager vehicleManager = Singleton <VehicleManager> .instance;
            ushort vehicleId = 0;
            if (instanceData.m_citizen != 0u)
            {
                vehicleId = citizenManager.m_citizens.m_buffer[instanceData.m_citizen].m_vehicle;
            }
            if (vehicleId != 0)
            {
                VehicleInfo vehicleInfo = vehicleManager.m_vehicles.m_buffer[(int)vehicleId].Info;
                if (vehicleInfo.m_vehicleType == VehicleInfo.VehicleType.Bicycle)
                {
                    vehicleInfo.m_vehicleAI.SimulationStep(vehicleId, ref vehicleManager.m_vehicles.m_buffer[(int)vehicleId], vehicleId, ref vehicleManager.m_vehicles.m_buffer[(int)vehicleId], 0);
                    vehicleId = 0;
                }
            }
            if (vehicleId == 0 && (instanceData.m_flags & (CitizenInstance.Flags.Character | CitizenInstance.Flags.WaitingPath | CitizenInstance.Flags.Blown | CitizenInstance.Flags.Floating)) == CitizenInstance.Flags.None)
            {
                instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround | CitizenInstance.Flags.Panicking | CitizenInstance.Flags.SittingDown);
                this.ArriveAtDestination(instanceID, ref instanceData, false);
                citizenManager.ReleaseCitizenInstance(instanceID);
            }
        }
示例#48
0
 protected virtual TraceEventSession CreateSession(Benchmark benchmark)
 => new TraceEventSession(GetSessionName(SessionNamePrefix, benchmark, benchmark.Parameters));
 public void ProcessResults(Benchmark benchmark, BenchmarkReport report)
 => diagnosers.ForEach(diagnoser => diagnoser.ProcessResults(benchmark, report));
示例#50
0
 public virtual void ProcessResults(Benchmark benchmark, BenchmarkReport report)
 {
 }
示例#51
0
 public void Initialize(Benchmark benchmark)
 {
 }
示例#52
0
        public void CouldAppendSeriesBench()
        {
            if (AdditionalCorrectnessChecks.Enabled)
            {
                Console.WriteLine("AdditionalCorrectnessChecks.Enabled");
            }

            int count  = 10_000_000;
            int rounds = 100;

            var sa = new AppendSeries <int, int>(DataBlock.Create());
            var sm = new SortedMap <int, int>();

            //for (int r = 0; r < rounds; r++)
            //{
            //    using (Benchmark.Run("SM.TryAddLast", count))
            //    {
            //        for (int i = r * count; i < (r + 1) * count; i++)
            //        {
            //            if (i == r * count + 3)
            //            {
            //                continue;
            //            }
            //            if (!sm.TryAddLast(i, i).Result)
            //            {
            //                Assert.Fail("Cannot add " + i);
            //            }
            //        }
            //    }
            //    Console.WriteLine($"Added {((r + 1) * count / 1000000).ToString("N")}");
            //}

            for (int r = 0; r < rounds; r++)
            {
                using (Benchmark.Run("Append", count))
                {
                    for (int i = r * count; i < (r + 1) * count; i++)
                    {
                        if (i == r * count + 3)
                        {
                            continue;
                        }
                        if (!sa.TryAddLast(i, i).Result)
                        {
                            Console.WriteLine("Cannot add " + i);
                            return;
                        }
                    }
                }

                Console.WriteLine($"Added {((r + 1) * count / 1000000).ToString("N")}");
            }



            Benchmark.Dump();

            Console.WriteLine("Finished, press enter");
            Console.ReadLine();

            sa.Dispose();
        }
示例#53
0
 public virtual RunMode GetRunMode(Benchmark benchmark) => RunMode.ExtraRun;
示例#54
0
        public void CreateDatabase()
        {
            var unsorted = 0;

            _creationBench = new Benchmark();

            _prevSaCreator = null;

            // loading ref sequence
            var saCreator = GetNextSupplementaryAnnotation();

            while (saCreator != null)
            {
                if (!_currentRefName.Equals(saCreator.RefSeqName)) //sanity check
                {
                    throw new Exception("Error: currentRef != sa ref");
                }

                if (_saWriter == null) //check for empty writer
                {
                    Console.WriteLine("Supplementary annotationa writer was not initialized");
                    return;
                }


                // this SA is not the first one in current contig
                if (_prevSaCreator != null)
                {
                    if (saCreator.ReferencePosition == _prevSaCreator.ReferencePosition)
                    {
                        _prevSaCreator.MergeSaCreator(saCreator);
                    }
                    else
                    {
                        if (_prevSaCreator.RefSeqName == saCreator.RefSeqName && _prevSaCreator.ReferencePosition > saCreator.ReferencePosition)
                        {
                            Console.WriteLine("Unsorted records:{0}, {1}, {2}, {3}", _prevSaCreator.RefSeqName,
                                              _prevSaCreator.ReferencePosition, saCreator.RefSeqName, saCreator.ReferencePosition);
                            unsorted++;
                        }

                        if (!_prevSaCreator.IsEmpty())
                        {
                            _saWriter.Write(_prevSaCreator, _prevSaCreator.ReferencePosition);
                            _numSaWritten++;
                        }
                        _prevSaCreator = saCreator;
                    }
                }
                else
                {
                    _prevSaCreator = saCreator;
                }


                saCreator = GetNextSupplementaryAnnotation();
            }


            // do not forgot to write the last item
            CloseCurrentSaWriter();

            Console.WriteLine("");
            Console.WriteLine("unsorted records: {0}", unsorted);
        }
示例#55
0
        public SynchronousProcessOutputLoggerWithDiagnoser(ILogger logger, Process process, IDiagnoser diagnoser, Benchmark benchmark)
        {
            if (!process.StartInfo.RedirectStandardOutput)
            {
                throw new NotSupportedException("set RedirectStandardOutput to true first");
            }

            this.logger    = logger;
            this.process   = process;
            this.diagnoser = diagnoser;
            this.benchmark = benchmark;

            LinesWithResults     = new List <string>();
            LinesWithExtraOutput = new List <string>();
        }
示例#56
0
 public static void RunBench()
 {
     Benchmark.Iterate(() => Bench(16, false));
 }
 public string GetGroupKey(Benchmark benchmark, Summary summary) =>
 summaryOrderPolicy == SummaryOrderPolicy.Default
     ? benchmark.Parameters.DisplayInfo
     : null;
 /// <summary>Generates the project for benchmark.</summary>
 /// <param name="benchmark">The benchmark.</param>
 /// <param name="logger">The logger.</param>
 /// <param name="rootArtifactsFolderPath">The root artifacts folder path.</param>
 /// <param name="config">The config for benchmark.</param>
 /// <returns>Generation result.</returns>
 public GenerateResult GenerateProject(
     Benchmark benchmark, ILogger logger,
     string rootArtifactsFolderPath, IConfig config) =>
 new GenerateResult(null, true, null);
示例#59
0
        private static void Main(string[] args)
        {
            bool success;
            WINUSB_PIPE_INFORMATION pipeInfo;
            UsbK usb;
            USB_INTERFACE_DESCRIPTOR interfaceDescriptor;

            // Find and configure the device.
            if (!Test.ConfigureDevice(out pipeInfo, out usb, out interfaceDescriptor))
            {
                return;
            }

#if BMFW
            // TODO FOR USER: Remove this block if not using benchmark firmware.
            // This configures devices running benchmark firmware for streaming DeviceToHost transfers.
            Console.WriteLine("Configuring for benchmark device..");
            BM_TEST_TYPE testType = BM_TEST_TYPE.READ;
            success = Benchmark.Configure(usb, BM_COMMAND.SET_TEST, interfaceDescriptor.bInterfaceNumber, ref testType);
            if (!success)
            {
                Console.WriteLine("Bench_Configure failed.");
            }
#endif
            // Create the ISO transfer queue.  This class manages the pending and outstanding transfer lists.
            ReadIsoTransferQueue readXfers = new ReadIsoTransferQueue(usb, ref pipeInfo, Test.MaxOutstandingTransfers, Test.IsoPacketsPerTransfer);

            if (!Test.ShowTestReady())
            {
                goto Done;
            }

            // Always issue a reset pipe prior to re/starting an ISO stream.
            usb.ResetPipe(pipeInfo.PipeId);

            // This example will not manage the start frame manually, but this is
            // how I might caculate the starting point.
            usb.GetCurrentFrameNumber(out readXfers.FrameNumber);
            unchecked
            {
                // Add some start latency
                readXfers.FrameNumber += 32;

                // Start FrameNumber at an interval of 8.
                readXfers.FrameNumber -= ((readXfers.FrameNumber) % 8);
            }

            // This is a counter/timer used only for statistics gathering.
            Thread.Sleep(0);
            Test.Dcs.Start();

            // Transfer processing loop
            do
            {
                IsoTransferItem isoTransferItem;
                int             transferred;
                int             errorCode;
                // While buffers exist in the completed list, submit them.
                while (readXfers.Completed.Count > 0 && readXfers.TotalSubmittedCount < Test.MaxTransfersTotal)
                {
                    errorCode = readXfers.SubmitNextRead();
                    if (errorCode != 0)
                    {
                        Console.WriteLine("IsoReadPipe failed. ErrorCode: {0:X8}h", errorCode);
                        goto Done;
                    }
                }

                if (readXfers.Outstanding.Count == 0)
                {
                    // The MAX_TRANSFERS_TOTAL test limit hit.
                    Console.WriteLine("Done!");
                    goto Done;
                }

                // Wait for the oldest transfer to complete.
                errorCode = readXfers.WaitRead(out isoTransferItem, 1000, out transferred);
                if (errorCode != 0)
                {
                    Console.WriteLine("OvlPool.Wait failed. ErrorCode: {0:X8}h", errorCode);
                    goto Done;
                }

                // Report iso status.
                IsoXferReport(readXfers, isoTransferItem, transferred);

                if (readXfers.CompletedCount == 1)
                {
                    Test.Dcs.Start();
                }
            } while (true);

Done:
            readXfers.Destroy();
            Test.Free();

            usb.Free();
        }
示例#60
0
 public void PerformanceTests(Benchmark benchmark)
 {
     Benchmark.PrepareForRun();
     benchmark.Run();
     benchmark.Finish();
 }