/// <summary> /// Create a new session using the given SessionParameters and Scene /// </summary> /// <param name="sessionParams">Previously created SessionParameters to create Session with</param> /// <param name="scene">Previously created Scene to create Session with</param> public Session(Client client, SessionParameters sessionParams, Scene scene) { Client = client; SessionParams = sessionParams; Scene = scene; Id = CSycles.session_create(Client.Id, sessionParams.Id, scene.Id); }
public Form1() { InitializeComponent(); // Turn on key preview this.KeyPreview = true; // Allocate Kinect data structure for speed data = new KinectData(); // Allocate bitmaps for speed //!! Should use System.Windows.Media.Imaging.WriteableBitmap colorBitmap = new Bitmap(640, 480, PixelFormat.Format24bppRgb); depthBitmap = new Bitmap(640, 480, PixelFormat.Format24bppRgb); testBitmap = new Bitmap(640, 480, PixelFormat.Format24bppRgb); demoBitmap = new Bitmap(640, 480, PixelFormat.Format24bppRgb); // Set up session parameters SessionParameters sessionParams = new SessionParameters(KinectDataParams.EnableType.All); sessionParams.DataParams.validityImageEnable = false; sessionParams.DataParams.testImageEnable = false; // Connect to a local Kinect and hook up to the data event client = KinectTableNet.KinectTable.ConnectLocal(sessionParams); client.DataReady += new Client.DataReadyHandler(client_DataReady); return; }
void Start() { spawnedObjects = new List <GameObject>(); SessionParameters parameters = FindObjectOfType <SessionParameters>(); count = defaultValue; if (parameters != null) { count = parameters.GetInt(CountParameterName, defaultValue, true); } StartCoroutine(CheckLoop()); }
// Use this for initialization void Start() { SessionParameters parameters = FindObjectOfType <SessionParameters>(); var lengthIndex = defaultValue; if (parameters != null) { lengthIndex = parameters.GetChoice(parameterName, defaultValue).Index; } if (lengths.Count > lengthIndex) { GetComponent <Grabber>().MaxLength = lengths[lengthIndex]; } }
public AsyncDtlsSessionImpl(byte[] sessionID, SessionParameters sessionParameters) { if (sessionID == null) { throw new ArgumentException("'sessionID' cannot be null"); } if (sessionID.Length < 1 || sessionID.Length > 32) { throw new ArgumentException("'sessionID' must have length between 1 and 32 bytes, inclusive"); } this.sessionID = new byte[sessionID.Length]; Array.Copy(sessionID, 0, this.sessionID, 0, sessionID.Length); this.sessionParameters = sessionParameters; }
void Start() { SessionParameters parameters = FindObjectOfType <SessionParameters>(); var speedIndex = defaultValue; if (parameters != null) { reaction = (ReactionType)parameters.GetChoice(reactionParameterName, (int)defaultValue).Index; } else { reaction = defaultValue; } UpdateAll(); }
/// <summary> /// Start experiment and checks errors. /// </summary> /// <remarks> /// The part with the logsessionparameters is from the old implementation and is not suited for everchanging sensors /// </remarks> public void StartExperiment() { _participantId = MenuManager.ParticipantId; if (string.IsNullOrEmpty(_participantId)) { MenuManager.DisplayErrorMessage("The Subject ID is invalid!", "Experiment Menu", "Launcher"); } else { SynchroniseScenesWithDatabase(); var sceneList = ExperimentSettings.SceneSettings.Scenes; Console.Write(sceneList.Count); var nParameters = MenuManager.ExperimentParameterList.Count; if (sceneList.Count <= 0) { MenuManager.DisplayErrorMessage("No scenes selected!", "Scene Configuration", "Launcher"); } else { if (SessionParameters.Count != nParameters) { MenuManager.DisplayErrorMessage("Session parameters are not set.", "Session Parameters Menu", "Launcher"); } else { LoggingManager.LogSession(ExperimentSettings.Name, _participantId); if (SessionParameters.ContainsKey("Labchart File Name")) { LoggingManager.SetLabChartFilePath(SessionParameters["Labchart File Name"]); } if (LoggingManager.GetSensors().Contains("HL7Server")) { this.gameObject.GetComponent <HL7ServerStarter>().enabled = true; } StoreSessionParameters(); MenuManager.InstantiateAndShowMenu("Start Menu", "Launcher"); //var startBaseMenu = GameObject.Find("Start Menu").GetComponent<BaseMenu>(); //MenuManager.ShowMenu(startBaseMenu); } } } }
public void SessionCreateCorrectQuestionsInExamMode() { ISession session; var parameters = new SessionParameters() { Mode = QuestionsGenerationMode.ExamTicket }; var creationResult = SessionFactory.CreateSession(parameters, out session); Assert.IsNotNull(session); Assert.AreEqual(ParametersValidationResult.Valid, creationResult); var ticket = session.Tickets.Single(); Assert.IsNotNull(ticket); var questions = session.Tickets.SelectMany(t => t.Questions).Count(); Assert.AreEqual(questions, AppLogic.Constants.GlobalConstants.questionsCount); }
void Start() { SessionParameters parameters = FindObjectOfType <SessionParameters>(); var sizeIndex = defaultValue; if (parameters != null) { sizeIndex = parameters.GetChoice(sizeParameterName, defaultValue).Index; } if (sizes.Count > sizeIndex) { size = sizes[sizeIndex]; UpdateAll(); } }
protected virtual void Start() { // The event processor is used to execute action on the main thread eventProcessor = GetComponent <EventProcessor>(); if (eventProcessor == null) { eventProcessor = gameObject.AddComponent <EventProcessor>(); } // Init parser and corresponding events parser = new CommandParser(); parser.playReceived += delegate() { eventProcessor.QueueEvent(new Action(Play)); }; parser.pauseReceived += delegate() { eventProcessor.QueueEvent(new Action(Pause)); }; parser.resetReceived += delegate() { eventProcessor.QueueEvent(new Action(Reset)); }; parser.loadScenarioReceived += delegate() { eventProcessor.QueueEvent(new Action(LoadScenario)); }; parser.loadSafezoneReceived += delegate() { eventProcessor.QueueEvent(new Action(LoadPatientSafezone)); }; parameters = FindObjectOfType <SessionParameters>(); if (parameters != null) { session = parameters.Session; // Init the note processor noteProcessor = new NoteProcessor(Application.persistentDataPath, session); parser.noteReceived += noteProcessor.Process; // Init the video recorder videoRecorder = GetComponent <VideoRecorder>(); videoRecorder.session = session; videoRecorder.StartRecord(); } // Transmit every command received directly to the parser CommunicationManager.Instance.commandReceived += parser.Parse; CommunicationManager.Instance.Start(); if (StartPaused) { Pause(); } }
public static Boolean SendNoticeOfExecution(SessionParameters SessionParams, UserSession Session, String Subject, String Body, String CardID, String FolderId) { logger.Info(String.Format("SendNoticeOfExecution: '{0}' on '{1}'", SessionParams.UserAccount, SessionParams.UserComputer)); var folderCard = (FolderCard)Session.CardManager.GetDictionary(FoldersCard.ID); var folder = folderCard.GetFolder(new Guid(FolderId)); CardData tt = Session.CardManager.GetCardData(new Guid("8F26CB44-BCDC-4040-AE74-3D3F6F6E6425")); var pt = tt.Copy(); pt.IsTemplate = false; folder.Shortcuts.AddNew(pt.Id, true); var rc = new CardResolution(pt); rc.Info.Name = Subject; rc.Info.Comments = Body; rc.Info.RegisteredBy = SessionParams.EmployeeId; var perf = rc.Performers.CreatePerformer(); var pg = new Guid("A6640FFB-8583-4F73-BBE4-E2FF7F30E119"); perf.EmployeeId = pg; perf.PerformerId = pg; perf.RoutingType = PerformerRoutingType.Default; perf.Order = 1; foreach (var row in pt.Sections[DocsVision.TakeOffice.Cards.Constants.CardResolution.Performers.ID].Rows) { row.SetInt32("PerformerType", 0); } var cg = new Guid(CardID); Reference rfr = rc.References.CreateReference(cg); rfr.Comment = "Ссылка на запрос"; rfr.RefCardId = cg; rfr.RefType = ReferenceRefType.DVDocument; rc.Info.ResolutionState = MainInfoResolutionState.ToPerform; logger.Info(String.Format("SendNoticeOfExecution - выполнено")); return(true); }
public ActionResult CreateSession(StartSettingsViewModel vm) { if (!ModelState.IsValid) { return(View(vm)); } try { SessionParameters parameters = new SessionParameters(vm.Public, vm.PersistHistory, vm.ConnectionExpiryInHours); _service.StartNewSession(vm.SessionName, vm.SessionPassword, parameters); } catch (Exception e) { return(View(vm)); } return(RedirectToAction("Index")); }
public void SessionCannotBeCreatedWithInvalidParameters() { ISession session; var parameters = new SessionParameters() { Mode = QuestionsGenerationMode.SelectedTickets }; var creationResult = SessionFactory.CreateSession(parameters, out session); Assert.IsNull(session); Assert.AreEqual(ParametersValidationResult.NoTickets, creationResult); parameters = new SessionParameters() { Mode = QuestionsGenerationMode.SelectedTickets, TicketNums = new int[] { 1, 1 } }; creationResult = SessionFactory.CreateSession(parameters, out session); Assert.IsNull(session); Assert.AreEqual(ParametersValidationResult.DuplicateTickets, creationResult); }
public async Task QuestionContentFitsToTextBlock() { ISession session; var sessionParameters = new SessionParameters(); var creationResult = SessionFactory.CreateSession(sessionParameters, out session); Assert.AreEqual(AppLogic.Enums.ParametersValidationResult.Valid, creationResult); var left = session.Tickets.SelectMany(ticket => ticket.Questions).Count(); Size?foundSize = null; Size allowedSize; await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var frame = new Frame(); frame.Navigate(typeof(QuestionPage), session); var questionPage = frame.Content as QuestionPage; var questionPageFields = questionPage.GetType().GetRuntimeFields(); var pagedCanvas = questionPageFields.Single(f => f.FieldType == typeof(PagedCanvas)).GetValue(questionPage) as PagedCanvas; FrameworkElement element = pagedCanvas.ItemTemplate.LoadContent() as FrameworkElement; var questionTextBlock = (element as Canvas).Children.OfType <TextBlock>().Single(); allowedSize = new Size(questionTextBlock.Width, questionTextBlock.Height); foreach (var question in session.Tickets.SelectMany(ticket => ticket.Questions)) { questionTextBlock.DataContext = question; questionTextBlock.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); if (questionTextBlock.ActualHeight > questionTextBlock.Height || questionTextBlock.ActualWidth > questionTextBlock.Width) { foundSize = new Size(questionTextBlock.ActualHeight, questionTextBlock.ActualWidth); break; } } }); Assert.IsNull(foundSize, "Question TextBlock does not fix: at least one text block's (width,height) is: ({0},{1}){2}Max allowed (width,height) is: ({3},{4})", (foundSize ?? new Size()).Width, (foundSize ?? new Size()).Height, Environment.NewLine, allowedSize.Width, allowedSize.Height); }
public override bool start(SessionParameters _params) { bool flag = base.start(_params); this.product = _params.connectionParameters[0]; this.version = _params.connectionParameters[1]; this.login = _params.connectionParameters[2]; this.password = _params.connectionParameters[3]; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("-product {0} ", (object)this.product); stringBuilder.AppendFormat("-version {0} ", (object)this.version); stringBuilder.AppendFormat("-login {0} ", (object)this.login); stringBuilder.AppendFormat("-password {0} ", (object)this.password); stringBuilder.Append("-savelogininfo "); stringBuilder.Append("-autoconnect"); Process.Start("IQConnect.exe", stringBuilder.ToString()); Thread.Sleep(8000); this.m_sockAdmin = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.m_sockLevel1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { this.m_sockAdmin.Connect((EndPoint)this.getConnection("Admin")); this.m_sockLevel1.Connect((EndPoint)this.getConnection("Level1")); this.WaitForData("Level1"); this.SendRequestToIQFeed(string.Format("S,SET PROTOCOL,{0}\r\n", (object)this.version)); foreach (InstrumentInfo instrument in this.Instruments) { this.SendRequestToIQFeed(string.Format("w{0}\r\n", (object)instrument.ID)); } } catch (Exception ex) { if (this.DataWriter != null) { this.DataWriter.writeException(ex); } } return(flag); }
public ActionResult Index(FormCollection collection) { if (!IsOAuthSignatureValid()) { ViewBag.ErrorMessage = "Invalid OAuth signature."; return(View("BookError")); } var parameters = new SessionParameters { ClassOrgId = collection["context_id"] }; if (parameters.ClassOrgId == null) { ViewBag.ErrorMessage = "Invalid class org ID."; return(View("BookError")); } parameters.CanEdit = CanEdit(collection["roles"]); Uri redirectUri; try { Uri requestUrl = new Uri(collection["lis_outcome_service_url"]); parameters.LtiUri = new UriBuilder( requestUrl.Scheme, requestUrl.Host, requestUrl.Port ).Uri; Session[SESSION_KEY] = parameters; redirectUri = GenerateAuthRedirect(parameters.LtiUri, Request.Url); } catch (ArgumentNullException e) { ViewBag.ErrorMessage = "Invalid request URL. " + e.Message; return(View("BookError")); } return(Redirect(redirectUri.ToString( ))); }
public Session(SessionParameters sessionParameter) { m_sessionParameter = sessionParameter; m_SyllableChoiceArray = new ICryptoSyllable[sessionParameter.SyllableChoiceAmount]; m_SyllableSearchArray = new ICryptoSyllable[sessionParameter.SyllableSearchedAmount]; // Create transmission flow from parameter SessionParameters sp = m_sessionParameter; m_TransmissionSetup = TransmissionManager.BuildTransmissionSetup(sp.Seed, sp.RoundCount, sp.SyllableSearchedAmount, sp.SyllableChoiceAmount); m_TransmissionWord = new TransmissionWord(m_TransmissionSetup.StartWord); Debug.Assert(m_TransmissionSetup.Transmissions.Length == sp.RoundCount, "Transmission setup creation returned tansmission array with wrong length"); // Set the active round index to the first entry ActiveRoundIndex = 0; // Start the first round SetRound(ActiveRoundIndex); }
public void SessionSelectsRightQuestions() { var ticketNums = new int[] { 1 }; ISession session; var parameters = new SessionParameters() { Mode = QuestionsGenerationMode.SelectedTickets, TicketNums = ticketNums }; var creationResult = SessionFactory.CreateSession(parameters, out session); IEnumerable <string> questions; using (var accessor = new SQLiteShared.SQLiteDataAccessor()) { var ticketIds = accessor.CreateQuery <SQLiteShared.Models.Tickets>().Where(ticket => ticketNums.Contains(ticket.num)).Select(ticket => ticket.id); questions = accessor.CreateQuery <SQLiteShared.Models.Questions>().Where(question => ticketIds.Contains(question.ticket_id)).Select(question => question.question).ToArray(); } Assert.IsNotNull(session); Assert.AreEqual(ParametersValidationResult.Valid, creationResult); Assert.IsTrue(session.Tickets.Any()); Assert.IsTrue(questions.All(question => session.Tickets.SelectMany(ticket => ticket.Questions).Any(q => q.Text == question))); }
public void SessionCreatesWithCorrectHierarchy() { ISession session; var parameters = new SessionParameters() { Mode = QuestionsGenerationMode.RandomTicket }; var creationResult = SessionFactory.CreateSession(parameters, out session); Assert.IsNotNull(session); Assert.AreEqual(ParametersValidationResult.Valid, creationResult); var ticket = session.Tickets.SingleOrDefault(); Assert.IsNotNull(ticket); var question = ticket.Questions.FirstOrDefault(); Assert.IsNotNull(question); Assert.AreEqual(question.Ticket, ticket); var answer = question.Answers.FirstOrDefault(); Assert.IsNotNull(answer); Assert.AreEqual(answer.Question, question); }
/// <summary> /// Entry point for viewport interactive rendering /// </summary> public void Renderer() { var cyclesEngine = this; Locked = false; var vi = new ViewInfo(RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport); var vpi = vi.Viewport; var client = cyclesEngine.Client; var rw = cyclesEngine.RenderWindow; if (rw == null) { return; } _throttle = RcCore.It.EngineSettings.ThrottleMs; _samples = RcCore.It.EngineSettings.Samples; #region pick a render device #if YES var rd0 = Device.GetDevice(0); var rd1 = Device.GetDevice(1); var rd2 = Device.GetDevice(2); var rd3 = Device.GetDevice(3); var rd4 = Device.GetDevice(4); var rdlist = new List <Device>(); //rdlist.Add(rd0); rdlist.Add(rd1); rdlist.Add(rd2); //rdlist.Add(rd3); //rdlist.Add(rd4); var renderDevice = Device.CreateMultiDevice(rdlist); #else TriggerCurrentViewportSettingsRequested(); var renderDevice = RenderDevice; // RcCore.It.EngineSettings.RenderDevice; #endif #endregion var scene = CreateScene(client, renderDevice, cyclesEngine); #region set up session parameters var sessionParams = new SessionParameters(client, renderDevice) { Experimental = false, Samples = (int)_samples, TileSize = renderDevice.IsCpu ? new Size(32, 32) : new Size(RcCore.It.EngineSettings.TileX, RcCore.It.EngineSettings.TileY), TileOrder = TileOrder.Center, Threads = (uint)(renderDevice.IsCpu ? RcCore.It.EngineSettings.Threads : 0), ShadingSystem = ShadingSystem.SVM, SkipLinearToSrgbConversion = true, DisplayBufferLinear = true, Background = !RcCore.It.CanUseDrawOpenGl(), ProgressiveRefine = true, Progressive = true, }; if (RcCore.It.CanUseDrawOpenGl()) { sessionParams.StartResolution = RcCore.It.EngineSettings.StartResolution; } #endregion if (cyclesEngine.CancelRender) { return; } #region create session for scene cyclesEngine.Session = new Session(client, sessionParams, scene); #endregion TriggerCurrentViewportSettingsRequested(); // register callbacks before starting any rendering cyclesEngine.SetCallbacks(); // main render loop, including restarts #region start the rendering thread, wait for it to complete, we're rendering now! cyclesEngine.CheckFlushQueue(); if (!cyclesEngine.CancelRender) { cyclesEngine.Synchronize(); } if (!cyclesEngine.CancelRender) { cyclesEngine.Session.PrepareRun(); } #endregion // We've got Cycles rendering now, notify anyone who cares cyclesEngine.RenderStarted?.Invoke(cyclesEngine, new RenderStartedEventArgs(!cyclesEngine.CancelRender)); while (!IsStopped) { if (_needReset) { _needReset = false; var size = RenderDimension; Session.Scene.Integrator.NoShadows = RcCore.It.EngineSettings.NoShadows; Session.Scene.Integrator.TagForUpdate(); // lets first reset session Session.Reset(size.Width, size.Height, _samples); // then reset scene Session.Scene.Reset(); } if (cyclesEngine.IsRendering && cyclesEngine.Session.Sample()) { cyclesEngine.PassRendered?.Invoke(cyclesEngine, new PassRenderedEventArgs(-1, View)); } Thread.Sleep(_throttle); if (!Locked && !CancelRender && !IsStopped && Flush) { TriggerChangesReady(); } } cyclesEngine.Session.EndRun(); cyclesEngine.Session.Destroy(); }
public void RenderScene(string scenename) { var dev = Device.FirstGpu; Console.WriteLine("Using device {0} {1}", dev.Name, dev.Description); var scene_params = new SceneParameters(Client, ShadingSystem.SVM, BvhType.Static, false, false, false); var scene = new Scene(Client, scene_params, dev); var xml = new CSyclesXmlReader(Client, scenename); xml.Parse(false); var width = (uint)scene.Camera.Size.Width; var height = (uint)scene.Camera.Size.Height; var session_params = new SessionParameters(Client, dev) { Experimental = false, Samples = (int)samples, TileSize = new Size(64, 64), StartResolution = 64, Threads = (uint)(dev.IsCpu ? 0 : 0), ShadingSystem = ShadingSystem.SVM, Background = true, ProgressiveRefine = false, Progressive = false, TileOrder = TileOrder.HilbertSpiral }; var Session = new Session(Client, session_params, scene); Session.Reset(width, height, samples); g_write_render_tile_callback = WriteRenderTileCallback; Session.WriteTileCallback = g_write_render_tile_callback; /*if (!silent) * { * Session.UpdateCallback = g_update_callback; * Session.UpdateTileCallback = g_update_render_tile_callback; * Session.WriteTileCallback = g_write_render_tile_callback; * } * CSycles.set_logger(Client.Id, g_logger_callback); */ Session.Start(); Session.Wait(); uint bufsize; uint bufstride; CSycles.session_get_buffer_info(Client.Id, Session.Id, out bufsize, out bufstride); var pixels = CSycles.session_copy_buffer(Client.Id, Session.Id, bufsize); var bmp = new ed.Bitmap((int)width, (int)height, Eto.Drawing.PixelFormat.Format32bppRgba); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var i = y * (int)width * 4 + x * 4; bmp.SetPixel(x, y, new ed.Color(Math.Min(pixels[i], 1.0f), Math.Min(pixels[i + 1], 1.0f), Math.Min(pixels[i + 2], 1.0f), Math.Min(pixels[i + 3], 1.0f))); } } bmp.Save("test.png", Eto.Drawing.ImageFormat.Png); Result = bmp; Session.Destroy(); Console.WriteLine("Cleaning up :)"); }
static void Main(string[] args) { var file = ""; if (args.Length < 1 || args.Length > 2) { Console.WriteLine("Wrong count parameter: csycles_tester [--quiet] file.xml"); return; } var s = args[args.Length - 1]; if (!File.Exists(s)) { Console.WriteLine("File {0} doesn't exist.", s); return; } var silent = args.Length == 2 && "--quiet".Equals(args[0]); file = Path.GetFullPath(s); Console.WriteLine("We get file path: {0}", file); var path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) ?? ""; var userpath = Path.Combine(path, "userpath"); CSycles.path_init(path, userpath); CSycles.initialise(); const uint samples = 50; g_update_callback = StatusUpdateCallback; g_update_render_tile_callback = UpdateRenderTileCallback; g_write_render_tile_callback = WriteRenderTileCallback; g_logger_callback = LoggerCallback; var client = new Client(); Client = client; /*if (!silent) * { * CSycles.set_logger(client.Id, g_logger_callback); * }*/ foreach (var adev in Device.Devices) { Console.WriteLine("{0}", adev); } Console.WriteLine("All device capabilities: {0}", Device.Capabilities); var dev = Device.FirstCuda; Console.WriteLine("Using device {0} {1}", dev.Name, dev.Description); var scene_params = new SceneParameters(client, ShadingSystem.SVM, BvhType.Static, false, false, false); var scene = new Scene(client, scene_params, dev); Console.WriteLine("Default surface shader {0}", scene.DefaultSurface.Name); #region background shader var background_shader = new Shader(client, Shader.ShaderType.World) { Name = "Background shader" }; var bgnode = new BackgroundNode(); bgnode.ins.Color.Value = new float4(0.7f); bgnode.ins.Strength.Value = 1.0f; background_shader.AddNode(bgnode); bgnode.outs.Background.Connect(background_shader.Output.ins.Surface); background_shader.FinalizeGraph(); scene.AddShader(background_shader); scene.Background.Shader = background_shader; scene.Background.AoDistance = 0.0f; scene.Background.AoFactor = 0.0f; scene.Background.Visibility = PathRay.AllVisibility; #endregion #region diffuse shader var diffuse_shader = create_some_setup_shader(); scene.AddShader(diffuse_shader); scene.DefaultSurface = diffuse_shader; #endregion #region point light shader var light_shader = new Shader(client, Shader.ShaderType.Material) { Name = "Tester light shader" }; var emission_node = new EmissionNode(); emission_node.ins.Color.Value = new float4(0.8f); emission_node.ins.Strength.Value = 10.0f; light_shader.AddNode(emission_node); emission_node.outs.Emission.Connect(light_shader.Output.ins.Surface); light_shader.FinalizeGraph(); scene.AddShader(light_shader); #endregion var xml = new XmlReader(client, file); xml.Parse(silent); var width = (uint)scene.Camera.Size.Width; var height = (uint)scene.Camera.Size.Height; var session_params = new SessionParameters(client, dev) { Experimental = false, Samples = (int)samples, TileSize = new Size(64, 64), StartResolution = 64, Threads = (uint)(dev.IsCpu ? 0 : 0), ShadingSystem = ShadingSystem.SVM, Background = true, ProgressiveRefine = false }; Session = new Session(client, session_params, scene); Session.Reset(width, height, samples); if (!silent) { Session.UpdateCallback = g_update_callback; Session.UpdateTileCallback = g_update_render_tile_callback; Session.WriteTileCallback = g_write_render_tile_callback; } CSycles.set_logger(client.Id, g_logger_callback); Session.Start(); Session.Wait(); uint bufsize; uint bufstride; CSycles.session_get_buffer_info(client.Id, Session.Id, out bufsize, out bufstride); var pixels = CSycles.session_copy_buffer(client.Id, Session.Id, bufsize); var bmp = new Bitmap((int)width, (int)height); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var i = y * (int)width * 4 + x * 4; var r = ColorClamp((int)(pixels[i] * 255.0f)); var g = ColorClamp((int)(pixels[i + 1] * 255.0f)); var b = ColorClamp((int)(pixels[i + 2] * 255.0f)); var a = ColorClamp((int)(pixels[i + 3] * 255.0f)); bmp.SetPixel(x, y, Color.FromArgb(a, r, g, b)); } } bmp.Save("test.png", ImageFormat.Png); Console.WriteLine("Cleaning up :)"); CSycles.shutdown(); Console.WriteLine("Done"); }
/// <summary> /// Creates a session for a node /// </summary> /// <param name='resourceGroupName'> /// The resource group name uniquely identifies the resource group within the /// user subscriptionId. /// </param> /// <param name='nodeName'> /// The node name (256 characters maximum). /// </param> /// <param name='session'> /// The sessionId from the user /// </param> /// <param name='userName'> /// encrypted User name to be used to connect to node /// </param> /// <param name='password'> /// encrypted Password associated with user name /// </param> /// <param name='retentionPeriod'> /// session retention period. Possible values include: 'Session', 'Persistent' /// </param> /// <param name='credentialDataFormat'> /// credential data format. Possible values include: 'RsaEncrypted' /// </param> /// <param name='encryptionCertificateThumbprint'> /// encryption certificate thumbprint /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task <Microsoft.Rest.Azure.AzureOperationResponse <SessionResource> > BeginCreateWithHttpMessagesAsync(string resourceGroupName, string nodeName, string session, string userName = default(string), string password = default(string), RetentionPeriod?retentionPeriod = default(RetentionPeriod?), CredentialDataFormat?credentialDataFormat = default(CredentialDataFormat?), string encryptionCertificateThumbprint = default(string), System.Collections.Generic.Dictionary <string, System.Collections.Generic.List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length < 3) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+"); } } if (nodeName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nodeName"); } if (nodeName != null) { if (nodeName.Length > 256) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "nodeName", 256); } if (nodeName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "nodeName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(nodeName, "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "nodeName", "^[a-zA-Z0-9][a-zA-Z0-9_.-]*$"); } } if (session == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "session"); } SessionParameters sessionParameters = new SessionParameters(); if (userName != null || password != null || encryptionCertificateThumbprint != null) { sessionParameters.UserName = userName; sessionParameters.Password = password; sessionParameters.RetentionPeriod = retentionPeriod; sessionParameters.CredentialDataFormat = credentialDataFormat; sessionParameters.EncryptionCertificateThumbprint = encryptionCertificateThumbprint; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary <string, object> tracingParameters = new System.Collections.Generic.Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("nodeName", nodeName); tracingParameters.Add("session", session); tracingParameters.Add("sessionParameters", sessionParameters); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServerManagement/nodes/{nodeName}/sessions/{session}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{nodeName}", System.Uri.EscapeDataString(nodeName)); _url = _url.Replace("{session}", System.Uri.EscapeDataString(session)); System.Collections.Generic.List <string> _queryParameters = new System.Collections.Generic.List <string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (sessionParameters != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(sessionParameters, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201 && (int)_statusCode != 202) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse <SessionResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SessionResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <SessionResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void SetParameter(SessionParameters parameter) { m_usedParameters = parameter; }
/// <summary> /// Renderer entry point for preview rendering /// </summary> /// <param name="oPipe"></param> public static void Renderer(object oPipe) { var cyclesEngine = (PreviewRenderEngine)oPipe; var client = cyclesEngine.Client; var size = cyclesEngine.RenderDimension; var samples = 500; #region pick a render device var renderDevice = RcCore.It.EngineSettings.RenderDevice; if (RcCore.It.EngineSettings.Verbose) { sdd.WriteLine( $"Using device {renderDevice.Name + " " + renderDevice.Description}"); } #endregion if (cyclesEngine.CancelRender) { return; } var scene = CreateScene(client, renderDevice, cyclesEngine); #region set up session parameters var sessionParams = new SessionParameters(client, renderDevice) { Experimental = false, Samples = samples, TileSize = new Size(RcCore.It.EngineSettings.TileX, RcCore.It.EngineSettings.TileY), TileOrder = TileOrder.Center, Threads = 1, ShadingSystem = ShadingSystem.SVM, Background = true, DisplayBufferLinear = true, ProgressiveRefine = true, Progressive = true, }; #endregion if (cyclesEngine.CancelRender) { return; } #region create session for scene cyclesEngine.Session = new Session(client, sessionParams, scene); #endregion // register callbacks before starting any rendering cyclesEngine.SetCallbacks(); // main render loop cyclesEngine.Database.Flush(); cyclesEngine.UploadData(); cyclesEngine.Session.PrepareRun(); // lets first reset session cyclesEngine.Session.Reset(size.Width, size.Height, samples); // then reset scene cyclesEngine.Session.Scene.Reset(); // and actually start bool stillrendering = true; var throttle = Math.Max(0, RcCore.It.EngineSettings.ThrottleMs); while (stillrendering) { if (cyclesEngine.IsRendering) { stillrendering = cyclesEngine.Session.Sample(); Thread.Sleep(throttle); } else { break; } if (cyclesEngine.IsStopped) { break; } if (cyclesEngine.CancelRender) { break; } } cyclesEngine.Session.EndRun(); // we're done now, so lets clean up our session. cyclesEngine.Session.Destroy(); cyclesEngine.Database?.Dispose(); }
/// <summary> /// Entry point for a new render process. This is to be done in a separate thread. /// </summary> public void Renderer() { var cyclesEngine = this; var rw = cyclesEngine.RenderWindow; if (rw == null) { return; // we don't have a window to write to... } var client = cyclesEngine.Client; var size = cyclesEngine.RenderDimension; _samples = RcCore.It.EngineSettings.Samples; maxSamples = _samples; cyclesEngine.TriggerCurrentViewportSettingsRequested(); #region pick a render device var renderDevice = RcCore.It.EngineSettings.RenderDevice; if (RcCore.It.EngineSettings.Verbose) { sdd.WriteLine( $"Using device {renderDevice.Name + " " + renderDevice.Description}"); } #endregion var scene = CreateScene(client, renderDevice, cyclesEngine); cyclesEngine.TriggerCurrentViewportSettingsRequested(); maxSamples = _samples; #region set up session parameters var sessionParams = new SessionParameters(client, renderDevice) { Experimental = false, Samples = _samples, TileSize = renderDevice.IsCpu ? new Size(32, 32) : new Size(RcCore.It.EngineSettings.TileX, RcCore.It.EngineSettings.TileY), TileOrder = TileOrder.Center, Threads = (uint)(renderDevice.IsGpu ? 0 : RcCore.It.EngineSettings.Threads), ShadingSystem = ShadingSystem.SVM, Background = true, DisplayBufferLinear = true, ProgressiveRefine = true, Progressive = true, }; #endregion if (cyclesEngine.CancelRender) { return; } #region create session for scene cyclesEngine.Session = new Session(client, sessionParams, scene); #endregion // register callbacks before starting any rendering cyclesEngine.SetCallbacks(); // main render loop, including restarts #region start the rendering loop, wait for it to complete, we're rendering now! if (cyclesEngine.CancelRender) { return; } cyclesEngine.Database?.Flush(); var rc = cyclesEngine.UploadData(); cyclesEngine.Database?.Dispose(); cyclesEngine.Database = null; if (rc) { cyclesEngine.Session.PrepareRun(); // lets first reset session cyclesEngine.Session.Reset(size.Width, size.Height, _samples); // then reset scene cyclesEngine.Session.Scene.Reset(); // and actually start bool stillrendering = true; var throttle = Math.Max(0, RcCore.It.EngineSettings.ThrottleMs); while (stillrendering) { if (cyclesEngine.IsRendering) { stillrendering = cyclesEngine.Session.Sample(); Thread.Sleep(throttle); } else { Thread.Sleep(100); } if (cyclesEngine.IsStopped) { break; } } cyclesEngine.Session.EndRun(); } cyclesEngine.CancelRender = true; #endregion if (RcCore.It.EngineSettings.SaveDebugImages) { var tmpf = $"{Environment.GetEnvironmentVariable("TEMP")}\\RC_modal_renderer.png"; cyclesEngine.RenderWindow.SaveRenderImageAs(tmpf, true); } // we're done now, so lets clean up our session. cyclesEngine.Session.Destroy(); // set final status string and progress to 1.0f to signal completed render cyclesEngine.SetProgress(rw, $"Render ready {cyclesEngine.RenderedSamples + 1} samples, duration {cyclesEngine.TimeString}", 1.0f); cyclesEngine.CancelRender = true; // signal the render window we're done. rw.EndAsyncRender(RenderWindow.RenderSuccessCode.Completed); }
public override void OnEnterState() { base.OnEnterState(); m_InputIndex = 0; m_Session = GameManager.instance.ActiveSession; SessionParameters sessionParams = m_Session.SessionParams; var transmission = m_Session.TransmissionSetup.Transmissions[m_Session.ActiveRoundIndex]; // Resize array m_DisplayedSyllables = new SyllableViewModel[sessionParams.SyllableSearchedAmount]; m_InputSyllables = new SyllableViewModel[sessionParams.SyllableChoiceAmount]; m_InTableSyllables = new SyllableViewModel[sessionParams.SyllableChoiceAmount]; m_OutTableSyllables = new SyllableViewModel[sessionParams.SyllableChoiceAmount]; m_ShuffledInLanguageIndexes = new byte[sessionParams.SyllableChoiceAmount]; var tmpList = new List <byte>(sessionParams.SyllableChoiceAmount); for (byte i = 0; i < sessionParams.SyllableChoiceAmount; i++) { tmpList.Add(i); } for (int i = 0; i < sessionParams.SyllableChoiceAmount; i++) { var index = UnityEngine.Random.Range(0, tmpList.Count); m_ShuffledInLanguageIndexes[i] = tmpList[index]; tmpList.RemoveAt(index); } var inSyllables = transmission.InLanguage.GetSyllables(); var outSyllables = transmission.OutLanguage.GetSyllables(); for (int i = 0; i < sessionParams.SyllableChoiceAmount; i++) { m_InputSyllables[i] = new SyllableViewModel(); m_InTableSyllables[i] = new SyllableViewModel(); m_OutTableSyllables[i] = new SyllableViewModel(); } for (int i = 0; i < sessionParams.SyllableSearchedAmount; i++) { m_DisplayedSyllables[i] = new SyllableViewModel(); } OnSyllablesChanged?.Invoke(); for (int i = 0; i < sessionParams.SyllableChoiceAmount; i++) { m_InputSyllables[i].SetFromSyllable(outSyllables[transmission.Conversion[m_ShuffledInLanguageIndexes[i]]]); m_InTableSyllables[i].SetFromSyllable(inSyllables[m_ShuffledInLanguageIndexes[i]]); m_OutTableSyllables[i].SetFromSyllable(outSyllables[transmission.Conversion[m_ShuffledInLanguageIndexes[i]]]); } CanTransmit = false; }
// ----------------------------------------- // During one Playthrough //------------------------------------------ /// <summary> /// This method is called whenever unity finished loading a scene or we manually move onto a new /// scene to update the state of the experiment. /// </summary> /// <param name="scene">Upcoming scene</param> /// <param name="mode">Unity parameter needed to mach listener.</param> private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (!_initialized) { _initialized = true; return; } var isReplay = FirstPersonController.GetComponentInChildren <ReplayRoute>().isActivated(); var sceneList = ExperimentSettings.SceneSettings.Scenes; _activeSceneName = SceneManager.GetActiveScene().name; var subSceneName = sceneList[_currentScene].Name; Debug.Log("Scene " + _currentScene + ":" + subSceneName + " in " + _activeSceneName); if (!isReplay) { LoggingManager.InsertLiveSystemEvent("SceneFlow", "switch", null, "Scene " + _currentScene + ":" + subSceneName.Substring(0, Math.Min(subSceneName.Length, 25)) + " in " + _activeSceneName.Substring(0, Math.Min(_activeSceneName.Length, 25))); } FirstPersonController.transform.position = Vector3.zero; FirstPersonController.transform.rotation = Quaternion.identity; FirstPersonController.SetActive(false); if (_activeSceneName == "Launcher" && !_inQuestionnaire && !_configureLabchart) { //coming back from a scene Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (isReplay) { MenuManager.InstantiateAndShowMenu("Participant Menu", "Launcher"); } else { LoggingManager.LogSceneEnd(subSceneName); if (_currentScene < sceneList.Count - 1) { _currentScene++; LoadCurrentScene(); return; } else { MenuManager.InstantiateAndShowMenu("Finish Menu", "Launcher"); SessionParameters.Clear(); return; } } } //Reset state machine flags for a clean load _inQuestionnaire = false; _configureLabchart = false; //A new scene started that is not the if (!isReplay) { LoggingManager.LogSceneStart(subSceneName); } }
public Form1(PolhemusController newPolhemusController, PhidgetController newPhidgetController, string host, string port) { this.host = host; this.port = port; InitializeComponent(); this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true); polhemusController = newPolhemusController; phidgetController = newPhidgetController; this.BackColor = Color.Black; this.Size = new Size(Program.tableWidth, Program.tableHeight); studyController = new HaikuStudyController(HaikuStudyPosition.SideBySide);//, HaikuStudyType.RealArmsPictureArms); wordBoxController = new WordBoxController(studyController); if (studyController.isActuatePenalty == true) { //phidgetController.setUpServos(); } //to snap words back to their original locations when dropped outside of a user's paper, set this to true. wordBoxController.boxesShouldSnapBack = true; studyController.wordBoxController = wordBoxController; studyController.currentCondition = HaikuStudyCondition.Cursors; studyController.isInSetUpMode = false; setMouseProperties(); setUpEmbodiments(); if (Program.kinectEnabled) { // Set up KinectTable kinectData = new KinectData(); // Set up session parameters SessionParameters sessionParams = new SessionParameters(KinectDataParams.EnableType.All); sessionParams.DataParams.validityImageEnable = false; sessionParams.DataParams.testImageEnable = false; // Connect to a local Kinect and hook up to the data event kinectClient = KinectTableNet.KinectTable.ConnectLocal(sessionParams); kinectClient.DataReady += kinectClient_DataReady; // Set up Kinect calibration kinectCalibration = new KinectCalibrationController(); // Read the saved table depth tweak value ReadTableDepthTweak(); } Cursor.Hide(); Load += Form1_Load; FormClosed += Form1_FormClosed; playerID = 0; updateTimer = new Timer(); updateTimer.Interval = 25; updateTimer.Tick += new EventHandler(updateTimer_Tick); updateTimer.Start(); }