void Start() { string levelToPlay = SelectLevel(); clock.Start(); StartCoroutine(LoadGameLevelWithProgress(levelToPlay)); }
private Dictionary <string, ParameterMetadata> RetriveParameterMetadata( AzFunctionInfo functionInfo, out string moduleName) { moduleName = null; string scriptPath = functionInfo.ScriptPath; string entryPoint = functionInfo.EntryPoint; using (ExecutionTimer.Start(_logger, "Parameter metadata retrieved.")) { if (String.IsNullOrEmpty(entryPoint)) { return(_pwsh.AddCommand("Microsoft.PowerShell.Core\\Get-Command").AddParameter("Name", scriptPath) .InvokeAndClearCommands <ExternalScriptInfo>()[0].Parameters); } else { moduleName = Path.GetFileNameWithoutExtension(scriptPath); return(_pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameter("Name", scriptPath) .AddStatement() .AddCommand("Microsoft.PowerShell.Core\\Get-Command").AddParameter("Name", entryPoint) .InvokeAndClearCommands <FunctionInfo>()[0].Parameters); } } }
internal void AuthenticateToAzure() { // Try to authenticate to Azure // TODO: The Azure Functions Host might supply these differently. This might change but works for the demo string applicationId = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_APP_ID"); string applicationSecret = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_APP_PASSWORD"); string tenantId = Environment.GetEnvironmentVariable("SERVICE_PRINCIPAL_TENANT_ID"); if (string.IsNullOrEmpty(applicationId) || string.IsNullOrEmpty(applicationSecret) || string.IsNullOrEmpty(tenantId)) { _logger.Log(LogLevel.Warning, "Required environment variables to authenticate to Azure were not present"); return; } // Build SecureString var secureString = new SecureString(); foreach (char item in applicationSecret) { secureString.AppendChar(item); } using (ExecutionTimer.Start(_logger, "Authentication to Azure completed.")) { _pwsh.AddCommand("Az.Profile\\Connect-AzAccount") .AddParameter("Credential", new PSCredential(applicationId, secureString)) .AddParameter("ServicePrincipal") .AddParameter("TenantId", tenantId) .InvokeAndClearCommands(); } }
void IAggregator.Begin() { _timer.Start(); ResetStats(); TestStartedDisableButtons(); // Invoke forces this command to be executed on UI thread // This will allow BW ProcessChange to work properly. Invoke(new InvokeDelegate(() => _backgroundWorker1.RunWorkerAsync())); }
public ITestState Start() { _threadPoolCounter = new ThreadPoolCounter(); PipeFactory <IResult> pipeFactory = new PipeFactory <IResult>(); _aggregator = new PipelineDataAggregator(_settings.Aggregators, pipeFactory); _aggregator.Start(); _globalCounters = GlobalCounters.CreateDefault(); _errorHandler = new ErrorHandler(); _limit = new LimitsHandler(_settings.Limits); _threading = _settings.Threading; _state = new TestState(_timer, _globalCounters, _threadPoolCounter); _speed = PriorityStrategyFactory.Create(_settings.Speeds, _timer); _speed.Setup(_state); IIterationContextFactory iterationContextFactory = CreateIterationContextFactory(); IScenarioHandlerFactory scenarioHandlerFactory = CreateScenarioHandlerFactory(); ISchedulerFactory schedulerFactory = CreateSchedulerFactory(); IDataCollectorFactory dataCollectorFactory = CreateDataCollectorFactory(pipeFactory, _threadPoolCounter); IScenarioThreadFactory scenarioThreadFactory = CreateScenarioThreadFactory(); IThreadFactory threadFactory = new ScenarioThreadFactory( iterationContextFactory, scenarioHandlerFactory, schedulerFactory, dataCollectorFactory, scenarioThreadFactory ); _pool = new ThreadPool(threadFactory, _threadPoolCounter); InitialThreadingSetup(); _timer.Start(); // This line also releases Worker-Threads from wait in IPrewait return(_state); }
void Update() { if (Input.GetButtonDown("Fire1")) { LoggerTool.Post("Start generating island from a click"); bool prevRandSet = islandGenerator.useRandomSeed; islandGenerator.useRandomSeed = useRandomSeed; startedRecording = true; clock.Start(); islandGenerator.GenerateIsland(); islandGenerator.useRandomSeed = prevRandSet; } if (startedRecording && islandGenerator.IsDone()) { startedRecording = false; LoggerTool.Post("Generated with " + clock.Elapsed() + " seconds."); LoggerTool.Post(" ----------------------- "); } }
public virtual ITestState Start() { _threadPoolCounter = new ThreadPoolCounter(); _globalCounters = GlobalCounters.CreateDefault(); ITestState testState = new TestState(_timer, _globalCounters, _threadPoolCounter); PipeFactory <IResult> pipeFactory = new PipeFactory <IResult>(); _aggregator = new PipelineDataAggregator(_settings.Aggregators, pipeFactory); _aggregator.Start(); _errorHandler = new ErrorHandler(); _dataReader = _settings.DataReader; _dataReader.Begin(testState); IIterationContextFactory iterationContextFactory = CreateIterationContextFactory(); IReplayScenarioHandlerFactory scenarioHandlerFactory = CreateScenarioHandlerFactory(); IReplaySchedulerFactory schedulerFactory = CreateSchedulerFactory(); IDataCollectorFactory dataCollectorFactory = CreateDataCollectorFactory(pipeFactory, _threadPoolCounter); IScenarioThreadFactory scenarioThreadFactory = CreateScenarioThreadFactory(); IThreadFactory threadFactory = new ReplayScenarioThreadFactory( iterationContextFactory, scenarioHandlerFactory, schedulerFactory, dataCollectorFactory, scenarioThreadFactory ); _pool = new ThreadPool(threadFactory, _threadPoolCounter); _pool.StartWorkersAsync(_settings.ThreadCount); while (_threadPoolCounter.CreatedThreadCount != _threadPoolCounter.InitializedThreadCount) { Thread.Sleep(100); _errorHandler.Assert(); } _timer.Start(); // This line also releases Worker-Threads from wait in IPrewait return(testState); }
// TODO: Redesign validator so it uses actual handlers. /// <summary> /// Validates ILoadTest scenario correctness by executing single test iteration /// from ScenarioSetup to ScenarioTearDown on the same thread. /// Exceptions are not handled on purpose to ease problem identification while developing. /// </summary> /// <param name="scenario">ILoadTestScenario object</param> /// <param name="threadId">TheardId to set in TestContext</param> /// <param name="threadIterationId">ThreadIterationId to set in TestContext</param> /// <param name="globalIterationId">GlobalIterationId to set in TestContext</param> /// <returns>Raw result from single iteration</returns> public static IterationResult Validate(this IScenario scenario, int threadId = 0, int threadIterationId = 0, int globalIterationId = 0) { ExecutionTimer timer = new ExecutionTimer(); ThreadSafeCounter errorsCounter = new ThreadSafeCounter(); GlobalCounters globalCounters = new GlobalCounters(errorsCounter, new MockedIdGenerator(globalIterationId)); IIterationControl context = new IterationContext(threadId, timer); ScenarioHandler handler = new ScenarioHandler(globalCounters, new MockedIdGenerator(threadIterationId), scenario, context); timer.Start(); handler.Init(); handler.PrepareNext(); handler.Execute(); IterationResult result = new IterationResult(context, new WorkerThreadStats()); handler.Cleanup(); timer.Stop(); return(result); }
public static IterationResult Validate <TData>(this IReplayScenario <TData> scenario, DataItem data, int threadId = 0, int threadIterationId = 0, int globalIterationId = 0) { ExecutionTimer timer = new ExecutionTimer(); ThreadSafeCounter errorsCounter = new ThreadSafeCounter(); GlobalCounters globalCounters = new GlobalCounters(errorsCounter, new MockedIdGenerator(globalIterationId)); IIterationControl context = new IterationContext(threadId, timer); ReplayScenarioHandler <TData> handler = new ReplayScenarioHandler <TData>(globalCounters, new MockedIdGenerator(threadIterationId), scenario, context); timer.Start(); handler.Init(); handler.PrepareNext(); handler.SetData(data.Value, data.TimeStamp); handler.Execute(); IterationResult result = new IterationResult(context, new WorkerThreadStats()); handler.Cleanup(); timer.Stop(); return(result); }
void Start() { SetLevelSeed(); clock.Start(); generator.GenerateIsland(); }
/// <summary> /// Execution a function fired by a trigger or an activity function scheduled by an orchestration. /// </summary> internal Hashtable InvokeFunction( AzFunctionInfo functionInfo, Hashtable triggerMetadata, IList <ParameterBinding> inputData) { string scriptPath = functionInfo.ScriptPath; string entryPoint = functionInfo.EntryPoint; string moduleName = null; try { // If an entry point is defined, we load the script as a module and invoke the function with that name. // We also need to fetch the ParameterMetadata to know what to pass in as arguments. var parameterMetadata = RetriveParameterMetadata(functionInfo, out moduleName); _pwsh.AddCommand(String.IsNullOrEmpty(entryPoint) ? scriptPath : entryPoint); // Set arguments for each input binding parameter foreach (ParameterBinding binding in inputData) { if (parameterMetadata.ContainsKey(binding.Name)) { _pwsh.AddParameter(binding.Name, binding.Data.ToObject()); } } // Gives access to additional Trigger Metadata if the user specifies TriggerMetadata if (parameterMetadata.ContainsKey(AzFunctionInfo.TriggerMetadata)) { _logger.Log(LogLevel.Debug, "Parameter '-TriggerMetadata' found."); _pwsh.AddParameter(AzFunctionInfo.TriggerMetadata, triggerMetadata); } Collection <object> pipelineItems = null; using (ExecutionTimer.Start(_logger, "Execution of the user's function completed.")) { pipelineItems = _pwsh.InvokeAndClearCommands <object>(); } var result = _pwsh.AddCommand("Microsoft.Azure.Functions.PowerShellWorker\\Get-OutputBinding") .AddParameter("Purge") .InvokeAndClearCommands <Hashtable>()[0]; if (pipelineItems != null && pipelineItems.Count > 0) { // Log everything we received from the pipeline foreach (var item in pipelineItems) { _logger.Log(LogLevel.Information, $"OUTPUT: {_pwsh.FormatObjectToString(item)}", isUserLog: true); } // TODO: See GitHub issue #82. We are not settled on how to handle the Azure Functions concept of the $returns Output Binding // If we would like to support Option 1 from #82, uncomment the following code: // object[] items = new object[pipelineItems.Count]; // pipelineItems.CopyTo(items, 0); // result.Add(AzFunctionInfo.DollarReturn, items); // If we would like to support Option 2 from #82, uncomment this line: // result.Add(AzFunctionInfo.DollarReturn, pipelineItems[pipelineItems.Count - 1]); } return(result); } finally { ResetRunspace(moduleName); } }
public int ClusterLocationsKMedoidsVoronoi(MapPoint[,] points) { // K-medoids cluster algorithm to separate locations in the regions int regionId = 0; foreach (MapRegion region in regions) { int k = InitializeNumOfK(region.turf.Count); Debug.Log(k + " medoid(s)"); Coord[] medoids = new Coord[k]; for (int i = 0; i < k; i++) { // Assign medoid to first k data points medoids[i] = region.turf[i * (region.turf.Count / k)]; } List <List <Coord> > clustering = new List <List <Coord> > (); for (int i = 0; i < k; i++) { clustering.Add(new List <Coord> ()); } // Loop until converged int changes = -1; int iter = 0; float cost; while (changes != 0) { clock.Start(); changes = 0; cost = 0; for (int i = 0; i < k; i++) { clustering[i].Clear(); } foreach (Coord tile in region.turf) { float distanceToMedoid = float.MaxValue; for (int i = 0; i < k; i++) { //float currDistToMedoid = tile.ManhattanDist (medoids[i]); float currDistToMedoid = tile.Dist(medoids[i]); if (currDistToMedoid < distanceToMedoid) { distanceToMedoid = currDistToMedoid; points[tile.x, tile.y].areaValue = regionId + i; } } clustering[points[tile.x, tile.y].areaValue - regionId].Add(tile); cost += distanceToMedoid; } for (int i = 0; i < k; i++) { List <Coord> cluster = clustering[i]; float minDist = cluster.Sum(til => til.ManhattanDist(medoids[i])); for (int t = 0; t < cluster.Count; t++) { float newDist = cluster.Sum(til => til.ManhattanDist(cluster[t])); if (newDist < minDist) { medoids[i] = cluster[t]; minDist = newDist; changes++; } } } //Debug.Log ("Medoid " + medoidIndex + " takes " + (clock.Elapsed () - tt) + " seconds. Sum cost calc time = " + tSum); iter++; //Debug.Log ("Iteration run with " + clock.Elapsed () + " seconds."); } Debug.Log("Iteration: " + iter); regionId += k; } return(regionId); }
// Called by LandMap.GetZones (), returns number of subregions public int ClusterLocationsKMedoidsPAM(MapPoint[,] points) { // K-medoids cluster algorithm to separate locations in the regions ExecutionTimer clock = new ExecutionTimer(); int regionId = 0; foreach (MapRegion region in regions) { int k = InitializeNumOfK(region.turf.Count); Debug.Log(k + " medoid(s)"); Coord[] medoids = new Coord[k]; bool[] isMedoid = new bool[region.turf.Count]; for (int i = 0; i < k; i++) { // Assign medoid to first k data points medoids[i] = region.turf[i * (region.turf.Count / k)]; isMedoid[i * (region.turf.Count / k)] = true; } // Loop until converged int changes = -1; int iter = 0; float cost; while (changes != 0 && iter < 10) { clock.Start(); changes = 0; cost = 0; foreach (Coord tile in region.turf) { float distanceToMedoid = float.MaxValue; for (int i = 0; i < k; i++) { float currDistToMedoid = tile.ManhattanDist(medoids[i]); if (currDistToMedoid < distanceToMedoid) { distanceToMedoid = currDistToMedoid; points[tile.x, tile.y].areaValue = regionId + i; } } cost += distanceToMedoid; } for (int medoidIndex = 0; medoidIndex < k; medoidIndex++) { //float tt = clock.Elapsed (); float tSum = 0; Coord oldMedoid = medoids[medoidIndex]; for (int i = 0; i < region.turf.Count; i++) { Coord tile = region.turf[i]; if (tile != oldMedoid) { float newCost = 0; medoids[medoidIndex] = tile; float tCost = clock.Elapsed(); region.turf.Sum(til => til.ManhattanDist(medoids[points[til.x, til.y].areaValue - regionId])); /*foreach (Coord t in region.turf) { * newCost += t.ManhattanDist (medoids[points[t.x, t.y].areaValue - regionId]); * }*/ tSum += clock.Elapsed() - tCost; if (newCost < cost) { cost = newCost; changes++; } else { medoids[medoidIndex] = oldMedoid; } } } //Debug.Log ("Medoid " + medoidIndex + " takes " + (clock.Elapsed () - tt) + " seconds. Sum cost calc time = " + tSum); } iter++; //Debug.Log ("Iteration run with " + clock.Elapsed () + " seconds."); } Debug.Log("Iteration: " + iter); regionId += k; } return(regionId); }
/// <summary> /// Execute a select statement and return the results /// @TODO: Clean up console writelines /// </summary> /// <param name="query"></param> /// <param name="bindings"></param> /// <returns></returns> public ResultSet Select(string query, BindingsDict bindings) { IDbCommand cmd = PrepareCommand(query, bindings); ResultSet results = new ResultSet(); try { if (_useTimer) { _execTimer.Start(); } IDataReader dataReader = cmd.ExecuteReader(); Console.WriteLine("\nReading dataresult\n----------------------------"); while (dataReader.Read()) { Row row = new Row(); for (int i = 0; i < dataReader.FieldCount; i++) { // Add this column to the current result row Column newCol = new Column(dataReader.GetName(i), dataReader[i], dataReader[i].GetSqlValueType()); row.Add(newCol); Console.WriteLine("[{0}]: '{1}'", dataReader.GetName(i), dataReader[i].ToString()); } // Add the row to our final result set results.Add(row); } #region Debug - Write out command text // Print out all the parameters we added to the Command object Console.WriteLine("\nUsing:\n[CommandText]: '{0}'", cmd.CommandText); foreach (IDbDataParameter param in cmd.Parameters) { Console.WriteLine("[" + param.DbType.ToString() + "] Name: '" + param.ParameterName + "', Value: " + param.Value.ToString()); } Console.WriteLine("-"); #endregion dataReader.Close(); if (_useTimer) { _execTimer.Stop(); } } catch (Exception ex) { if (_useTimer) { _execTimer.Stop(); } Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); throw new DBException("Failed to execute reader on Select query!", ex); } return(results); }
public async void DoesNotThrowExceptionWhenDisposedOnAnotherThread() { var timer = ExecutionTimer.Start(Logging.CreateLogger().Build(), "Message"); await Task.Run(() => timer.Dispose()); }
private void RunInner() { if (_threadCoordinator != null) { throw new InvalidOperationException("Async instance is already running"); } try { _threadCoordinator = new ThreadCoordinator( _iTestScenarioObjectType, _timer, _parameters.ThreadingStrategy.InitialThreadCount ) { InitialUserData = _parameters.InitialUserData }; _threadCoordinator.ScenarioIterationFinished += _threadCoordinator_ScenarioIterationFinished; int testIterationCount = 0; TimeSpan executionEnqueueThreshold = TimeSpan.Zero; _timer.Start(); _resultsAggregator.Begin(); while (_timer.CurrentValue < _parameters.Limits.MaxDuration && testIterationCount < _parameters.Limits.MaxIterationsCount) { WorkerThreadStats threadStats = _threadCoordinator.BuildWorkerThreadStats(); int allowedWorkingthreadCount = _parameters.ThreadingStrategy.GetAllowedMaxWorkingThreadCount(_timer.CurrentValue, threadStats); _threadCoordinator.AssertThreadErrors(); TryAdjustCreatedThreadCount(threadStats); if (allowedWorkingthreadCount > threadStats.WorkingThreadCount && _timer.CurrentValue >= executionEnqueueThreshold) { if (_threadCoordinator.TryEnqueueSingleIteration()) { executionEnqueueThreshold = CalculateNextExecutionTime(executionEnqueueThreshold); testIterationCount++; } else { Thread.Sleep(1); } } else { Thread.Sleep(1); } //_timer.UpdateCurrent(); } } finally { _threadCoordinator?.StopAndDispose((int)_parameters.Limits.FinishTimeout.TotalMilliseconds); _resultsAggregator.End(); _threadCoordinator?.AssertThreadErrors(); _threadCoordinator = null; _timer.Stop(); } }
internal Hashtable InvokeFunction( string scriptPath, string entryPoint, Hashtable triggerMetadata, IList <ParameterBinding> inputData) { try { Dictionary <string, ParameterMetadata> parameterMetadata; // We need to take into account if the user has an entry point. // If it does, we invoke the command of that name. We also need to fetch // the ParameterMetadata so that we can tell whether or not the user is asking // for the $TriggerMetadata using (ExecutionTimer.Start(_logger, "Parameter metadata retrieved.")) { if (entryPoint != "") { parameterMetadata = _pwsh .AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameter("Name", scriptPath) .AddStatement() .AddCommand("Microsoft.PowerShell.Core\\Get-Command").AddParameter("Name", entryPoint) .InvokeAndClearCommands <FunctionInfo>()[0].Parameters; _pwsh.AddCommand(entryPoint); } else { parameterMetadata = _pwsh.AddCommand("Microsoft.PowerShell.Core\\Get-Command").AddParameter("Name", scriptPath) .InvokeAndClearCommands <ExternalScriptInfo>()[0].Parameters; _pwsh.AddCommand(scriptPath); } } // Sets the variables for each input binding foreach (ParameterBinding binding in inputData) { _pwsh.AddParameter(binding.Name, binding.Data.ToObject()); } // Gives access to additional Trigger Metadata if the user specifies TriggerMetadata if (parameterMetadata.ContainsKey(_TriggerMetadataParameterName)) { _pwsh.AddParameter(_TriggerMetadataParameterName, triggerMetadata); _logger.Log(LogLevel.Debug, $"TriggerMetadata found. Value:{Environment.NewLine}{triggerMetadata.ToString()}"); } PSObject returnObject = null; using (ExecutionTimer.Start(_logger, "Execution of the user's function completed.")) { // Log everything we received from the pipeline and set the last one to be the ReturnObject Collection <PSObject> pipelineItems = _pwsh.InvokeAndClearCommands <PSObject>(); if (pipelineItems.Count > 0) { foreach (var psobject in pipelineItems) { _logger.Log(LogLevel.Information, $"OUTPUT: {psobject.ToString()}"); } returnObject = pipelineItems[pipelineItems.Count - 1]; } } var result = _pwsh.AddCommand("Microsoft.Azure.Functions.PowerShellWorker\\Get-OutputBinding") .AddParameter("Purge") .InvokeAndClearCommands <Hashtable>()[0]; if (returnObject != null) { result.Add("$return", returnObject); } return(result); } finally { ResetRunspace(scriptPath); } }
/// <summary> /// Execution a function fired by a trigger or an activity function scheduled by an orchestration. /// </summary> internal Hashtable InvokeFunction( AzFunctionInfo functionInfo, Hashtable triggerMetadata, IList <ParameterBinding> inputData) { string scriptPath = functionInfo.ScriptPath; string entryPoint = functionInfo.EntryPoint; string moduleName = null; try { if (string.IsNullOrEmpty(entryPoint)) { _pwsh.AddCommand(scriptPath); } else { // If an entry point is defined, we import the script module. moduleName = Path.GetFileNameWithoutExtension(scriptPath); _pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module") .AddParameter("Name", scriptPath) .InvokeAndClearCommands(); _pwsh.AddCommand(entryPoint); } // Set arguments for each input binding parameter foreach (ParameterBinding binding in inputData) { if (functionInfo.FuncParameters.Contains(binding.Name)) { _pwsh.AddParameter(binding.Name, binding.Data.ToObject()); } } // Gives access to additional Trigger Metadata if the user specifies TriggerMetadata if (functionInfo.FuncParameters.Contains(AzFunctionInfo.TriggerMetadata)) { _logger.Log(LogLevel.Debug, "Parameter '-TriggerMetadata' found."); _pwsh.AddParameter(AzFunctionInfo.TriggerMetadata, triggerMetadata); } Collection <object> pipelineItems = null; using (ExecutionTimer.Start(_logger, "Execution of the user's function completed.")) { pipelineItems = _pwsh.AddCommand("Microsoft.Azure.Functions.PowerShellWorker\\Trace-PipelineObject") .InvokeAndClearCommands <object>(); } var result = _pwsh.AddCommand("Microsoft.Azure.Functions.PowerShellWorker\\Get-OutputBinding") .AddParameter("Purge", true) .InvokeAndClearCommands <Hashtable>()[0]; /* * TODO: See GitHub issue #82. We are not settled on how to handle the Azure Functions concept of the $returns Output Binding * if (pipelineItems != null && pipelineItems.Count > 0) * { * // If we would like to support Option 1 from #82, use the following 3 lines of code: * object[] items = new object[pipelineItems.Count]; * pipelineItems.CopyTo(items, 0); * result.Add(AzFunctionInfo.DollarReturn, items); * * // If we would like to support Option 2 from #82, use this line: * result.Add(AzFunctionInfo.DollarReturn, pipelineItems[pipelineItems.Count - 1]); * } */ return(result); } finally { ResetRunspace(moduleName); } }
void GenerateInEditor() { if (!Application.isPlaying) { finished = false; if (useRandomSeed) { seed = DateTime.Now.ToString(); } Random.State oldState = Random.state; int seedHash = seed.GetHashCode(); Random.InitState(seedHash); for (int i = 0; i < randCol.Length; i++) { randCol[i] = Random.ColorHSV(0, 1, 0, 1, 0.5f, 1); } map = new LandMap(islandData.maxWidth, islandData.maxHeight); // Fill the map randomly with 0s and 1s based on percentage fill map.RandomFillMap(islandData.randomFillPercent); // Mold to the base shape if (islandData.baseShape) { map.makeBaseShape(islandData.baseShape); } // Smooth the map 5 times map.SmoothMap(5); meshGen = GetComponent <IslandMeshGenerator> (); vertDatabase.Clear(); vertDatabase.tileSize = islandData.tileSize; // Find separated regions to form an island List <MapRegion> regions = map.GetRegions(); // Create separate islands SeparateIslands(regions); clk.Start(); vertDatabase.SetCoordDB(); Debug.Log("Indexing takes " + clk.Elapsed() + " seconds."); if (shouldElevate) { int highestPeak = 0; foreach (IsleInfo island in islands) { int peak = island.surfaceMeshDetail.localPeak; highestPeak = peak > highestPeak ? peak : highestPeak; } foreach (IsleInfo island in islands) { island.surfaceMeshDetail.NormalizeGradientMap(highestPeak); } vertDatabase.SetVerticesInlandPos(islands, islandData.mountainCurve); ElevationGenerator elevGen = GetComponent <ElevationGenerator> (); elevGen.elevateSurface(islands, islandData.altitude, islandData.mountainCurve, surfaceNoiseData, seedHash, 0, vertDatabase); // elevate hills on the surface elevGen.elevateSurface(islands, -islandData.stalactite, islandData.bellyCurve, undersideNoiseData, seedHash, 2, vertDatabase); // extend stakes at surface below } clk.Start(); int zoneNum = DoClustering(regions, map.spots, vertDatabase, clusterAnalysis, seedHash); Debug.Log("Clustering takes " + clk.Elapsed() + " seconds."); // Find strategic locations in each region List <MapRegion> zones = map.GetZones(zoneNum); SpliceTerritory(zones); SetColliders(); PlacementGenerator placement = GetComponent <PlacementGenerator> (); if (placement && decorateTerrain) { placement.GenerateTrees(islands); placement.GenerateSectorsContent(sectors, vertDatabase); } else if (placement) { //placement.GeneratePlacements (islands); placement.GenerateSectorsContent(sectors, vertDatabase); } if (flatShading) { foreach (IsleInfo island in islands) { for (int surfaceIndex = 0; surfaceIndex < 3; surfaceIndex++) { MeshFilter mf = island.GetSurfaceMesh(surfaceIndex); float oldVertCount = mf.sharedMesh.vertexCount; mf.sharedMesh = FlatShade.DuplicateSharedVertex(mf.sharedMesh); float newVertCount = mf.sharedMesh.vertexCount; //Debug.Log (mf.transform.parent.name + "." + mf.transform.name + " new vertices are at " + (newVertCount / oldVertCount * 100) + "% with " + newVertCount + " verts."); } } } Random.state = oldState; } }