protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { return Task<HttpResponseMessage>.Factory.StartNew( () => { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized, "unauthorized"); response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=" + "foo")); return response; } ); }
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken) { if (_isAtEof) { return 0; } int returnValue = await base.ReadAsync(buffer, offset, count, cancellationToken); if (returnValue == 0) { ReceivedEof(); } return returnValue; }
/// <summary> /// Starts worker in separate thread. /// After worker finished its work it should call "done" function passed to it. /// After worker called done "callback" function will be called in unity thread. /// Parameter passed to "done" function will be available in "callback" function. /// Note: All Unity function are threade unsave. You are not allowed to use them in the worker. /// Though you can use any Unity functions in "callback" function. /// </summary> /// <param name="worker">Worker.</param> /// <param name="callback">Callback.</param> /// <returns>Thread id</returns> public static int Start(Worker worker, It.Action<object> callback, System.TimeSpan? timeout /*= null*/, It.Action timeoutCallback /*= null*/) { if (_instance == null) { _instance = new GameObject("Threading").AddComponent<Threading>(); } var id = _instance._id++; var info = new Info(); info.id = id; info.callback = callback; info.worker = worker; info.thread = new System.Threading.Thread(info.Run); if (timeout.HasValue) { info.timeout = System.DateTime.Now + timeout.Value; info.timeoutCallback = timeoutCallback; } _instance._threads[id] = info; info.thread.Start(); return id; }
protected void SetDataInternal <T>(int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride, SetDataOptions options) where T : struct { if (data == null) { throw new ArgumentNullException("data is null"); } if (data.Length < (startIndex + elementCount)) { throw new InvalidOperationException("The array specified in the data parameter is not the correct size for the amount of data requested."); } var bufferSize = VertexCount * VertexDeclaration.VertexStride; if ((vertexStride > bufferSize) || (vertexStride < VertexDeclaration.VertexStride)) { throw new ArgumentOutOfRangeException("One of the following conditions is true:\nThe vertex stride is larger than the vertex buffer.\nThe vertex stride is too small for the type of data requested."); } #if !PSM var elementSizeInBytes = Marshal.SizeOf(typeof(T)); #endif #if DIRECTX GenerateIfRequired(); if (_isDynamic) { // We assume discard by default. var mode = SharpDX.Direct3D11.MapMode.WriteDiscard; if ((options & SetDataOptions.NoOverwrite) == SetDataOptions.NoOverwrite) { mode = SharpDX.Direct3D11.MapMode.WriteNoOverwrite; } var d3dContext = GraphicsDevice._d3dContext; lock (d3dContext) { var dataBox = d3dContext.MapSubresource(_buffer, 0, mode, SharpDX.Direct3D11.MapFlags.None); SharpDX.Utilities.Write(IntPtr.Add(dataBox.DataPointer, offsetInBytes), data, startIndex, elementCount); d3dContext.UnmapSubresource(_buffer, 0); } } else { var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); var startBytes = startIndex * elementSizeInBytes; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); var box = new SharpDX.DataBox(dataPtr, 1, 0); var region = new SharpDX.Direct3D11.ResourceRegion(); region.Top = 0; region.Front = 0; region.Back = 1; region.Bottom = 1; region.Left = offsetInBytes; region.Right = offsetInBytes + (elementCount * elementSizeInBytes); lock (GraphicsDevice._d3dContext) GraphicsDevice._d3dContext.UpdateSubresource(box, _buffer, 0, region); dataHandle.Free(); } #elif PSM if (_vertexArray == null) { _vertexArray = new T[VertexCount]; } Array.Copy(data, offsetInBytes / vertexStride, _vertexArray, startIndex, elementCount); #else if (Threading.IsOnUIThread()) { SetBufferData(bufferSize, elementSizeInBytes, offsetInBytes, data, startIndex, elementCount, vertexStride, options); } else { Threading.BlockOnUIThread(() => SetBufferData(bufferSize, elementSizeInBytes, offsetInBytes, data, startIndex, elementCount, vertexStride, options)); } #endif }
public void Present() { Threading.EnsureUIThread(); Game.Instance.Platform.Present(); }
public IVertexBuffer <Vertex> CreateVertexBuffer(int size) { Threading.EnsureUIThread(); return(new VertexBuffer <Vertex>(size)); }
private void PlatformSetData <T>(int level, Rectangle?rect, T[] data, int startIndex, int elementCount) where T : struct { Threading.BlockOnUIThread(() => { var elementSizeInByte = Marshal.SizeOf(typeof(T)); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); // Use try..finally to make sure dataHandle is freed in case of an error try { var startBytes = startIndex * elementSizeInByte; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); int x, y, w, h; if (rect.HasValue) { x = rect.Value.X; y = rect.Value.Y; w = rect.Value.Width; h = rect.Value.Height; } else { x = 0; y = 0; w = Math.Max(width >> level, 1); h = Math.Max(height >> level, 1); // For DXT textures the width and height of each level is a multiple of 4. // OpenGL only: The last two mip levels require the width and height to be // passed as 2x2 and 1x1, but there needs to be enough data passed to occupy // a 4x4 block. // Ref: http://www.mentby.com/Group/mac-opengl/issue-with-dxt-mipmapped-textures.html if (_format == SurfaceFormat.Dxt1 || _format == SurfaceFormat.Dxt1a || _format == SurfaceFormat.Dxt3 || _format == SurfaceFormat.Dxt5) { if (w > 4) { w = (w + 3) & ~3; } if (h > 4) { h = (h + 3) & ~3; } } } // Store the current bound texture. var prevTexture = GraphicsExtensions.GetBoundTexture2D(); GenerateGLTextureIfRequired(); GL.BindTexture(TextureTarget.Texture2D, this.glTexture); GraphicsExtensions.CheckGLError(); if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) { if (rect.HasValue) { GL.CompressedTexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, glFormat, data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.CompressedTexImage2D(TextureTarget.Texture2D, level, glInternalFormat, w, h, 0, data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } } else { // Set pixel alignment to match texel size in bytes GL.PixelStore(PixelStoreParameter.UnpackAlignment, GraphicsExtensions.GetSize(this.Format)); if (rect.HasValue) { GL.TexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.TexImage2D(TextureTarget.Texture2D, level, glInternalFormat, w, h, 0, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } // Return to default pixel alignment GL.PixelStore(PixelStoreParameter.UnpackAlignment, 4); } #if !ANDROID GL.Finish(); GraphicsExtensions.CheckGLError(); #endif // Restore the bound texture. GL.BindTexture(TextureTarget.Texture2D, prevTexture); GraphicsExtensions.CheckGLError(); } finally { dataHandle.Free(); } #if !ANDROID // Required to make sure that any texture uploads on a thread are completed // before the main thread tries to use the texture. GL.Finish(); #endif }); }
public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { var stream = new MemoryStream(); await request.Content.CopyToAsync(stream); stream.Position = 0; return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream), }; }
protected virtual void OnDestroy() { foreach(var thread in _threads) { Stop(thread.Key); } _instance = null; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { Task<HttpResponseMessage> t = base.SendAsync(request, cancellationToken); if (!ReturnNull) { return t; } TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetResult(null); return tcs.Task; }
/// <summary> /// Primary method for refreshing the locations of points in the current zone /// </summary> /// <param name="state"></param> private void RefreshLocations(object state = null) { lock (locationsRefreshTimerLock) { if (this.isStopped) { return; // Immediately return if we are supposed to be stopped } API.Data.Entities.Point playerPos = null; API.Data.Entities.Point cameraDir = null; try { playerPos = this.playerService.PlayerPosition; cameraDir = this.playerService.CameraDirection; } catch (ObjectDisposedException) { // The player service is disposed! return; } if (playerPos != null && cameraDir != null) { var playerMapPosition = CalcUtil.ConvertToMapPosition(playerPos); var cameraDirectionMapPosition = CalcUtil.ConvertToMapPosition(cameraDir); Threading.BeginInvokeOnUI(() => { if (playerMapPosition.X != this.CharacterPosition.X && playerMapPosition.Y != this.CharacterPosition.Y) { this.CharacterPosition = playerMapPosition; } if (cameraDirectionMapPosition.X != this.CameraDirection.X && cameraDirectionMapPosition.Y != this.CameraDirection.Y) { this.CameraDirection = cameraDirectionMapPosition; } }); lock (this.zoneItemsLock) { foreach (var item in this.ZoneItems) { var newDistance = Math.Round(CalcUtil.CalculateDistance(playerMapPosition, item.ItemModel.Location, this.UserData.DistanceUnits)); var newAngle = CalcUtil.CalculateAngle(CalcUtil.Vector.CreateVector(playerMapPosition, item.ItemModel.Location), CalcUtil.Vector.CreateVector(new API.Data.Entities.Point(0, 0), cameraDirectionMapPosition)); if (item.DistanceFromPlayer != newDistance) { Threading.BeginInvokeOnUI(() => item.DistanceFromPlayer = newDistance); } if (item.DirectionFromPlayer != newAngle) { Threading.BeginInvokeOnUI(() => item.DirectionFromPlayer = newAngle); } if (!item.IsUnlocked) { // If the zone item isn't already unlocked, check to see if it should be automatically unlocked // based on the item's distance from the player and based on how long the player has been near the item var ftDistance = Math.Round(CalcUtil.CalculateDistance(playerMapPosition, item.ItemModel.Location, API.Data.Enums.Units.Feet)); switch (item.ItemType) { case API.Data.Enums.ZoneItemType.Waypoint: if (this.UserData.AutoUnlockWaypoints && ftDistance >= 0 && ftDistance < 75) { Threading.InvokeOnUI(() => item.IsUnlocked = true); } break; case API.Data.Enums.ZoneItemType.PointOfInterest: if (this.UserData.AutoUnlockPois && ftDistance >= 0 && ftDistance < 75) { Threading.InvokeOnUI(() => item.IsUnlocked = true); } break; case API.Data.Enums.ZoneItemType.Vista: if (this.UserData.AutoUnlockVistas && ftDistance >= 0 && ftDistance < 8) { if (this.playerInProximityCounters[item.ItemId] > 4) { this.playerInProximityCounters[item.ItemId] = 0; Threading.InvokeOnUI(() => item.IsUnlocked = true); } else { this.playerInProximityCounters[item.ItemId] += 1; } } else { this.playerInProximityCounters[item.ItemId] = 0; } break; case API.Data.Enums.ZoneItemType.HeartQuest: if (this.UserData.AutoUnlockHeartQuests && ftDistance >= 0 && ftDistance < 400) { if (this.playerInProximityCounters[item.ItemId] > 90) { this.playerInProximityCounters[item.ItemId] = 0; Threading.InvokeOnUI(() => item.IsUnlocked = true); } else { this.playerInProximityCounters[item.ItemId] += 1; } } else { this.playerInProximityCounters[item.ItemId] = 0; } break; case API.Data.Enums.ZoneItemType.HeroPoint: if (this.UserData.AutoUnlockSkillChallenges && ftDistance >= 0 && ftDistance < 25) { if (this.playerInProximityCounters[item.ItemId] > 15) { this.playerInProximityCounters[item.ItemId] = 0; Threading.InvokeOnUI(() => item.IsUnlocked = true); } else { this.playerInProximityCounters[item.ItemId] += 1; } } else { this.playerInProximityCounters[item.ItemId] = 0; } break; default: break; } } } } } this.itemLocationsRefreshTimer.Change(this.LocationsRefreshInterval, Timeout.Infinite); } }
private void CleanupTrayIcon() { Threading.InvokeOnUI(() => this.TrayIcon.Dispose()); }
private void Timer_OnProgress(object sender, int e) { Threading.ComponentInvoke(progressBar1, (x) => x.Value = e); TaskbarHelper.SetProgress(SaiHelper.AppProcess, e, progressBar1.Maximum); }
/// <summary> /// Shuts down all controllers, views, and viewmodels /// </summary> public void Shutdown() { logger.Info("Shutting down application controller"); logger.Debug("Closing views"); if (this.eventTrackerView != null) { Properties.Settings.Default.IsEventTrackerOpen = this.eventTrackerView.IsVisible; Threading.InvokeOnUI(() => this.eventTrackerView.Close()); } if (this.zoneCompletionView != null) { Properties.Settings.Default.IsZoneAssistantOpen = this.zoneCompletionView.IsVisible; Threading.InvokeOnUI(() => this.zoneCompletionView.Close()); } if (this.eventNotificationsView != null) { Threading.InvokeOnUI(() => this.eventNotificationsView.Close()); } if (this.dungeonTrackerView != null) { Properties.Settings.Default.IsDungeonTrackerOpen = this.dungeonTrackerView.IsVisible; Threading.InvokeOnUI(() => this.dungeonTrackerView.Close()); } if (this.wvwTrackerView != null) { Properties.Settings.Default.IsWvWTrackerOpen = this.wvwTrackerView.IsVisible; Threading.InvokeOnUI(() => this.wvwTrackerView.Close()); } if (this.wvwNotificationsView != null) { Threading.InvokeOnUI(() => this.wvwNotificationsView.Close()); } if (this.tpCalculatorView != null) { Properties.Settings.Default.IsTPCalculatorOpen = this.tpCalculatorView.IsVisible; Threading.InvokeOnUI(() => this.tpCalculatorView.Close()); } if (this.teamspeakView != null) { Properties.Settings.Default.IsTeamspeakOpen = this.teamspeakView.IsVisible; Threading.InvokeOnUI(() => this.teamspeakView.Close()); } Threading.InvokeOnUI(() => this.BrowserController.CloseBrowser()); Properties.Settings.Default.Save(); logger.Debug("Stopping controllers"); this.EventsController.Stop(); this.ZoneCompletionController.Stop(); this.DungeonsController.Stop(); this.WvWController.Stop(); }
public void RouteNoteOn(NoteOnMessage noteOnMessage) { if (FilterSingleChannel && noteOnMessage.Channel != FilterChannel) { return; } if (LogNoteOns) { Debug.Log(noteOnMessage.Channel + "." + noteOnMessage.Pitch); } Threading.RunOnMain((Action)(() => { switch (noteOnMessage.Channel) { case Channel.Channel1: { RouteCueMidi(noteOnMessage.Pitch); break; } case Channel.Channel9: { RouteOneFiveNine(noteOnMessage.Pitch); break; } case Channel.Channel14: { CircleParticleController.Instance.BangRotation = true; break; } case Channel.Channel2: { RouteComputerRain(noteOnMessage.Pitch); break; } case Channel.Channel3: { RouteDesmondMidi(noteOnMessage.Pitch); break; } case Channel.Channel4: { RouteHyphenMidi(noteOnMessage.Pitch); break; } case Channel.Channel5: { RouteUmbeantsMidi(noteOnMessage.Pitch); break; } case Channel.Channel6: { RouteJordanMidi(noteOnMessage.Pitch); break; } case Channel.Channel7: { RouteTunnelMidi(noteOnMessage.Pitch); break; } case Channel.Channel16: { UpdateAbletonState(noteOnMessage.Pitch); break; } } })); }
public void Code(string outDir, Blacklist[] blacklist, Threading[] threading) { m_blacklist = blacklist; m_threading = threading; m_fastCalls = 0; m_slowCalls = 0; foreach (NativeFile file in m_objects.Files) { string hfile = Path.GetFileNameWithoutExtension(file.Path); if (hfile != "NSObjCRuntime" && hfile != "NSObject" && hfile != "NSProxy" && hfile != "NSDistantObject" && hfile != "NSProtocolChecker") { m_inPath = file.Path; StringBuilder buffer = new StringBuilder(); m_buffer = buffer; DoWrite("// machine generated on {0} using {1}", DateTime.Now, Path.GetFullPath(m_inPath)); DoWrite(); DoWrite("using MObjc;"); DoWrite("using MObjc.Helpers;"); DoWrite("using System;"); DoWrite("using System.Runtime.InteropServices;"); DoWrite(); DoWrite("namespace MCocoa"); DoWrite("{"); DoEnums(buffer, file); DoInterfaces(buffer, file); m_buffer = buffer; DoWrite("}"); string outPath = Path.Combine(outDir, hfile + ".cs"); File.WriteAllText(outPath, buffer.ToString()); // These files should not normally be hand edited so we'll lock them. File.SetAttributes(outPath, FileAttributes.ReadOnly); } } string[] components = outDir.Split('/'); Console.WriteLine("{0:0.0}% of {1} {2} methods are fast path", 100.0*m_fastCalls/(m_fastCalls+m_slowCalls), m_fastCalls+m_slowCalls, components[components.Length - 2]); }
protected override HttpResponseMessage Send(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { throw new NotImplementedException(); }
/// <summary>Initializes the MPI environment.</summary> /// <param name="args"> /// Arguments passed to the <c>Main</c> function in your program. MPI /// may use some of these arguments for its initialization, and will remove /// them from this argument before returning. /// </param> /// <param name="threading"> /// The level of threading support requested of the MPI implementation. The /// implementation will attempt to provide this level of threading support. /// However, the actual level of threading support provided will be published /// via the <see cref="MPI.Environment.Threading"/> property. /// </param> /// <remarks> /// This routine must be invoked before using any other MPI facilities. /// Be sure to call <c>Dispose()</c> to finalize the MPI environment before exiting! /// </remarks> /// <example>This simple program initializes MPI and writes out the rank of each processor: /// <code> /// using MPI; /// /// public class Hello /// { /// static void Main(string[] args) /// { /// using (MPI.Environment env = new MPI.Environment(ref args)) /// { /// System.Console.WriteLine("Hello, from process number " /// + MPI.Communicator.world.Rank.ToString() + " of " /// + MPI.Communicator.world.Size.ToString()); /// } /// } /// } /// </code> /// </example> public Environment(ref string[] args, Threading threading) { if (!Initialized) { int requiredThreadLevel = 0; int providedThreadLevel; switch (threading) { case Threading.Single: requiredThreadLevel = Unsafe.MPI_THREAD_SINGLE; break; case Threading.Funneled: requiredThreadLevel = Unsafe.MPI_THREAD_FUNNELED; break; case Threading.Serialized: requiredThreadLevel = Unsafe.MPI_THREAD_SERIALIZED; break; case Threading.Multiple: requiredThreadLevel = Unsafe.MPI_THREAD_MULTIPLE; break; } if (args == null) { unsafe { int argc = 0; byte** argv = null; Unsafe.MPI_Init_thread(ref argc, ref argv, requiredThreadLevel, out providedThreadLevel); } } else { ASCIIEncoding ascii = new ASCIIEncoding(); unsafe { // Copy args into C-style argc/argv int my_argc = args.Length; byte** my_argv = stackalloc byte*[my_argc]; for (int argidx = 0; argidx < my_argc; ++argidx) { // Copy argument into a byte array (C-style characters) char[] arg = args[argidx].ToCharArray(); fixed (char* argp = arg) { int length = ascii.GetByteCount(arg); byte* c_arg = stackalloc byte[length]; if (length > 0) { ascii.GetBytes(argp, arg.Length, c_arg, length); } my_argv[argidx] = c_arg; } } // Initialize MPI int mpi_argc = my_argc; byte** mpi_argv = my_argv; Unsafe.MPI_Init_thread(ref mpi_argc, ref mpi_argv, requiredThreadLevel, out providedThreadLevel); // \todo Copy c-style argc/argv back into args if (mpi_argc != my_argc || mpi_argv != my_argv) { args = new string[mpi_argc]; for (int argidx = 0; argidx < args.Length; ++argidx) { // Find the end of the string int byteCount = 0; while (mpi_argv[argidx][byteCount] != 0) ++byteCount; // Determine how many Unicode characters we need int charCount = ascii.GetCharCount(mpi_argv[argidx], byteCount); // Convert ASCII characters into unicode characters char[] chars = new char[charCount]; fixed (char* argp = chars) { ascii.GetChars(mpi_argv[argidx], byteCount, argp, charCount); } // Create the resulting string args[argidx] = new string(chars); } } } } switch (providedThreadLevel) { case Unsafe.MPI_THREAD_SINGLE: Environment.providedThreadLevel = Threading.Single; break; case Unsafe.MPI_THREAD_FUNNELED: Environment.providedThreadLevel = Threading.Funneled; break; case Unsafe.MPI_THREAD_SERIALIZED: Environment.providedThreadLevel = Threading.Serialized; break; case Unsafe.MPI_THREAD_MULTIPLE: Environment.providedThreadLevel = Threading.Multiple; break; default: throw new ApplicationException("MPI.NET: Underlying MPI library returned incorrect value for thread level"); } // Setup communicators Communicator.world = Intracommunicator.Adopt(Unsafe.MPI_COMM_WORLD); Communicator.self = Intracommunicator.Adopt(Unsafe.MPI_COMM_SELF); } }
/// <summary> /// Default constructor /// </summary> public OverlayWindow() { this.Loaded += OverlayWindowBase_Loaded; this.ResizeHelper = new ResizeSnapHelper(this); this.IsClosed = false; this.Closed += (o, e) => this.IsClosed = true; OverlayWindow.EventAggregator.GetEvent <GW2ProcessFocused>().Subscribe(o => Threading.BeginInvokeOnUI(() => User32.SetTopMost(this, true))); }
public void Download(CancellationToken cancellationToken) { Assert.MethodCalledOnlyOnce(ref _downloadHasBeenCalled, "Download"); DebugLogger.Log("Downloading."); var validUrls = new List <string>(_mirrorUrls); // getting through urls list backwards, because urls may be removed during the process, // and it's easier to iterate that way validUrls.Reverse(); int retry = RetriesAmount; while (validUrls.Count > 0 && retry > 0) { for (int i = validUrls.Count - 1; i >= 0 && retry-- > 0; --i) { string url = validUrls[i]; try { OpenFileStream(); Download(url, cancellationToken); CloseFileStream(); if (_resource.HasValue) { var validator = new DownloadedResourceValidator(); validator.Validate(_destinationFilePath, _resource.Value); } return; } catch (DownloadedResourceValidationException validationException) { DebugLogger.LogException(validationException); validUrls.Remove(url); } catch (DownloaderException downloaderException) { DebugLogger.LogException(downloaderException); switch (downloaderException.Status) { case DownloaderExceptionStatus.EmptyStream: // try another one break; case DownloaderExceptionStatus.CorruptData: // try another one break; case DownloaderExceptionStatus.NotFound: // remove url and try another one validUrls.Remove(url); break; case DownloaderExceptionStatus.Other: // try another one break; default: throw new ArgumentOutOfRangeException(); } } finally { CloseFileStream(); } } DebugLogger.Log("Waiting 10 seconds before trying again..."); Threading.CancelableSleep(10000, cancellationToken); } if (retry <= 0) { throw new DownloaderException("Too many retries, aborting.", DownloaderExceptionStatus.Other); } throw new DownloaderException("Cannot download resource.", DownloaderExceptionStatus.Other); }
/// <summary> /// Increments the Progress member /// </summary> private void HandleIncrementProgress() { logger.Debug("Incrementing progress - progress={0}", this.progress); Threading.BeginInvokeOnUI(() => this.Progress++); }
Task<Net.Http.HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(Controllers.HttpActionContext actionContext, Threading.CancellationToken cancellationToken, Func<Threading.Tasks.Task<Net.Http.HttpResponseMessage>> continuation) { throw new NotImplementedException(); }
public void ClearDepthBuffer() { Threading.EnsureUIThread(); GL.Clear(ClearBufferMask.DepthBufferBit); GraphicsExtensions.CheckGLError(); }
private void GameGridScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { try { if (SmoothScrolling == SmoothScrollingMode.Default) { return; } e.Handled = true; var gameGrid = Helpers.UIHelper.FindChild <Grid>(GameGridScrollViewer, "GameGrid"); var realScrollableHeight = ((gameGrid.RowDefinitions.Count - 1) / 2) * (Const.GameControlSize.Height + Const.GridBorder) - GameGridScrollViewer.ViewportHeight; // TODO scrolling with pgUp/pgDown or ctrl+pgUp/pgDown should be checked against realScrollableHeight // "smooth" scrolling Threading.ThreadAndForget(() => { var direction = e.Delta < 0 ? -1.0 : 1.0; if (SmoothScrolling == SmoothScrollingMode.Linear) { int scrollStep = 4; for (var i = 0; i < Math.Abs(e.Delta) / scrollStep; i++) { var newScroll = Math.Min(GameGridScrollViewer.VerticalOffset - (scrollStep * direction), realScrollableHeight); GameGridScrollViewer.Dispatcher.Invoke(() => { GameGridScrollViewer.ScrollToVerticalOffset(newScroll); }); if (newScroll == realScrollableHeight) { break; } System.Threading.Thread.Sleep(10); } } else if (SmoothScrolling == SmoothScrollingMode.Exponential) { for (var scrollStep = Math.Abs((double)e.Delta); scrollStep > 1; scrollStep = scrollStep / 2) { var newScroll = Math.Min(GameGridScrollViewer.VerticalOffset - (scrollStep * direction), realScrollableHeight); GameGridScrollViewer.Dispatcher.Invoke(() => { GameGridScrollViewer.ScrollToVerticalOffset(newScroll); }); if (newScroll == realScrollableHeight) { break; } System.Threading.Thread.Sleep(32); } } }); } catch (Exception ex) { Log.WriteLine(ex.ToString()); } }
internal void PlatformApplyState(bool applyShaders) { Threading.EnsureUIThread(); if (_scissorRectangleDirty) { var scissorRect = _scissorRectangle; if (!IsRenderTargetBound) { scissorRect.Y = _viewport.Height - scissorRect.Y - scissorRect.Height; } GL.Scissor(scissorRect.X, scissorRect.Y, scissorRect.Width, scissorRect.Height); GraphicsExtensions.CheckGLError(); _scissorRectangleDirty = false; } if (_blendStateDirty) { _blendState.PlatformApplyState(this); _blendStateDirty = false; } if (_depthStencilStateDirty) { _depthStencilState.PlatformApplyState(this); _depthStencilStateDirty = false; } if (_rasterizerStateDirty) { _rasterizerState.PlatformApplyState(this); _rasterizerStateDirty = false; } // If we're not applying shaders then early out now. if (!applyShaders) { return; } if (_indexBufferDirty) { if (_indexBuffer != null) { GL.BindBuffer(BufferTarget.ElementArrayBuffer, _indexBuffer.ibo); GraphicsExtensions.CheckGLError(); } _indexBufferDirty = false; } if (_vertexBufferDirty) { if (_vertexBuffer != null) { GL.BindBuffer(BufferTarget.ArrayBuffer, _vertexBuffer.vbo); GraphicsExtensions.CheckGLError(); } } if (_vertexShader == null) { throw new InvalidOperationException("A vertex shader must be set!"); } if (_pixelShader == null) { throw new InvalidOperationException("A pixel shader must be set!"); } if (_vertexShaderDirty || _pixelShaderDirty) { ActivateShaderProgram(); _vertexShaderDirty = _pixelShaderDirty = false; } _vertexConstantBuffers.SetConstantBuffers(this, _shaderProgram); _pixelConstantBuffers.SetConstantBuffers(this, _shaderProgram); Textures.SetTextures(this); SamplerStates.PlatformSetSamplers(this); }
public void DisableDepthBuffer() { Threading.EnsureUIThread(); GL.Disable(EnableCap.DepthTest); GraphicsExtensions.CheckGLError(); }
/// <summary> /// Performs actions to handle a match change (either the match ended or the user switched matches) /// </summary> /// <param name="newMatchID">The new match ID</param> private void HandleMatchChange(string newMatchID) { logger.Info("Match change detected: new matchID = {0}", newMatchID); this.MatchID = newMatchID; if (MatchID == null) { // Unable to retrieve the current match ID, which means a reset is probably occuring // When this happens, clear out the state of everything Threading.InvokeOnUI(() => { foreach (var objective in this.AllObjectives) { objective.PrevWorldOwner = WorldColor.None; objective.WorldOwner = WorldColor.None; objective.FlipTime = DateTime.UtcNow; objective.DistanceFromPlayer = 0; objective.TimerValue = TimeSpan.Zero; objective.IsRIActive = false; objective.GuildClaimer.ID = null; objective.GuildClaimer.Name = string.Empty; objective.GuildClaimer.Tag = string.Empty; } }); } else { // Refresh all team colors var teamColors = this.wvwService.GetTeamColors(); Threading.InvokeOnUI(() => { foreach (var team in this.Worlds) { if (teamColors.ContainsKey(team.WorldId)) { team.Color = teamColors[team.WorldId]; } } }); // Refresh state of all objectives var latestObjectivesData = this.wvwService.GetAllObjectives(MatchID); while (latestObjectivesData.Count() != this.AllObjectives.Count && !this.isStopped) { // We were unable to pull data for all objectives - this can happen if we are // in the middle of a reset. As such, loop until we actually get a full set logger.Warn("Unable to retrieve data for all objectives! Trying again..."); latestObjectivesData = this.wvwService.GetAllObjectives(MatchID); } ConcurrentDictionary <Guid, API.Data.Entities.Guild> guildDict = new ConcurrentDictionary <Guid, API.Data.Entities.Guild>(); Parallel.ForEach(latestObjectivesData.Where(o => o.GuildOwner.HasValue), (objective) => { var guildInfo = this.guildService.GetGuild(objective.GuildOwner.Value); guildDict.TryAdd(guildInfo.ID, guildInfo); }); if (latestObjectivesData.Count() >= this.AllObjectives.Count) { Threading.InvokeOnUI(() => { foreach (var objective in this.AllObjectives) { objective.RefreshForMatchReset(this.Worlds); var latestData = latestObjectivesData.First(obj => obj.ID == objective.ID); objective.ModelData.MatchId = this.MatchID; objective.PrevWorldOwner = latestData.WorldOwner; objective.WorldOwner = latestData.WorldOwner; objective.FlipTime = DateTime.UtcNow; objective.DistanceFromPlayer = 0; objective.TimerValue = TimeSpan.Zero; objective.IsRIActive = false; if (latestData.GuildOwner.HasValue) { objective.GuildClaimer.ID = latestData.GuildOwner.Value; API.Data.Entities.Guild guildInfo; if (guildDict.TryGetValue(objective.GuildClaimer.ID.Value, out guildInfo) && guildInfo != null) { objective.GuildClaimer.Name = guildInfo.Name; objective.GuildClaimer.Tag = string.Format("[{0}]", guildInfo.Tag); } } } }); } } }
public void DisableScissor() { Threading.EnsureUIThread(); GL.Disable(EnableCap.ScissorTest); GraphicsExtensions.CheckGLError(); }
/// <summary> /// Refreshes various state information for all objectives /// </summary> private void RefreshObjectives() { var latestObjectivesData = this.wvwService.GetAllObjectives(MatchID); if (latestObjectivesData.Count() > 0) { foreach (var objective in this.AllObjectives) { var latestData = latestObjectivesData.FirstOrDefault(obj => obj.ID == objective.ID); if (latestData != null) { // Refresh owner information if (objective.WorldOwner != latestData.WorldOwner) { Threading.InvokeOnUI(() => { objective.PrevWorldOwner = objective.WorldOwner; objective.WorldOwner = latestData.WorldOwner; logger.Info("{0} - {1}: {2} -> {3}", objective.Map, objective.Name, objective.PrevWorldOwnerName, objective.WorldOwnerName); // Bloodlust objectives don't get RI, so don't bother with a flip time or RI flag if (objective.Type != ObjectiveType.TempleofLostPrayers && objective.Type != ObjectiveType.BattlesHollow && objective.Type != ObjectiveType.BauersEstate && objective.Type != ObjectiveType.OrchardOverlook && objective.Type != ObjectiveType.CarversAscent) { objective.FlipTime = DateTime.UtcNow; objective.IsRIActive = true; } }); if (objective.WorldOwner != WorldColor.None) // Don't show a notification if the new owner is "none" { // Owner just changed, raise a notification! this.DisplayNotification(objective); } } // Refresh guild information if (latestData.GuildOwner.HasValue) { if (!objective.GuildClaimer.ID.HasValue || objective.GuildClaimer.ID.Value != latestData.GuildOwner.Value) { // Guild claimer has changed Threading.InvokeOnUI(() => objective.GuildClaimer.ID = latestData.GuildOwner.Value); var guildInfo = this.guildService.GetGuild(latestData.GuildOwner.Value); if (guildInfo != null) { Threading.InvokeOnUI(() => { objective.GuildClaimer.Name = guildInfo.Name; objective.GuildClaimer.Tag = string.Format("[{0}]", guildInfo.Tag); }); } } } else { Threading.InvokeOnUI(() => { objective.GuildClaimer.ID = null; objective.GuildClaimer.Name = string.Empty; objective.GuildClaimer.Tag = string.Empty; }); } } else { logger.Warn("Unable to retrieve latest data for {0} ({1})", objective.ID, objective.Name); } } } }
public IFrameBuffer CreateFrameBuffer(Size s) { Threading.EnsureUIThread(); return(new FrameBuffer(s)); }
protected internal override Texture2D Read(ContentReader reader, Texture2D existingInstance) { Texture2D texture = null; var surfaceFormat = (SurfaceFormat)reader.ReadInt32(); int width = reader.ReadInt32(); int height = reader.ReadInt32(); int levelCount = reader.ReadInt32(); int levelCountOutput = levelCount; // If the system does not fully support Power of Two textures, // skip any mip maps supplied with any non PoT textures. if (levelCount > 1 && !reader.GraphicsDevice.GraphicsCapabilities.SupportsNonPowerOfTwo && (!MathHelper.IsPowerOfTwo(width) || !MathHelper.IsPowerOfTwo(height))) { levelCountOutput = 1; System.Diagnostics.Debug.WriteLine( "Device does not support non Power of Two textures. Skipping mipmaps."); } SurfaceFormat convertedFormat = surfaceFormat; switch (surfaceFormat) { case SurfaceFormat.Dxt1: case SurfaceFormat.Dxt1a: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1) convertedFormat = SurfaceFormat.Color; break; case SurfaceFormat.Dxt1SRgb: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1) convertedFormat = SurfaceFormat.ColorSRgb; break; case SurfaceFormat.Dxt3: case SurfaceFormat.Dxt5: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc) convertedFormat = SurfaceFormat.Color; break; case SurfaceFormat.Dxt3SRgb: case SurfaceFormat.Dxt5SRgb: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc) convertedFormat = SurfaceFormat.ColorSRgb; break; case SurfaceFormat.NormalizedByte4: convertedFormat = SurfaceFormat.Color; break; } texture = existingInstance ?? new Texture2D(reader.GraphicsDevice, width, height, levelCountOutput > 1, convertedFormat); #if OPENGL Threading.BlockOnUIThread(() => { #endif for (int level = 0; level < levelCount; level++) { var levelDataSizeInBytes = reader.ReadInt32(); var levelData = reader.ContentManager.GetScratchBuffer(levelDataSizeInBytes); reader.Read(levelData, 0, levelDataSizeInBytes); int levelWidth = Math.Max(width >> level, 1); int levelHeight = Math.Max(height >> level, 1); if (level >= levelCountOutput) continue; //Convert the image data if required switch (surfaceFormat) { case SurfaceFormat.Dxt1: case SurfaceFormat.Dxt1SRgb: case SurfaceFormat.Dxt1a: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsDxt1 && convertedFormat == SurfaceFormat.Color) { levelData = DxtUtil.DecompressDxt1(levelData, levelWidth, levelHeight); levelDataSizeInBytes = levelData.Length; } break; case SurfaceFormat.Dxt3: case SurfaceFormat.Dxt3SRgb: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc) if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc && convertedFormat == SurfaceFormat.Color) { levelData = DxtUtil.DecompressDxt3(levelData, levelWidth, levelHeight); levelDataSizeInBytes = levelData.Length; } break; case SurfaceFormat.Dxt5: case SurfaceFormat.Dxt5SRgb: if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc) if (!reader.GraphicsDevice.GraphicsCapabilities.SupportsS3tc && convertedFormat == SurfaceFormat.Color) { levelData = DxtUtil.DecompressDxt5(levelData, levelWidth, levelHeight); levelDataSizeInBytes = levelData.Length; } break; case SurfaceFormat.Bgra5551: { #if OPENGL // Shift the channels to suit OpenGL int offset = 0; for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { ushort pixel = BitConverter.ToUInt16(levelData, offset); pixel = (ushort)(((pixel & 0x7FFF) << 1) | ((pixel & 0x8000) >> 15)); levelData[offset] = (byte)(pixel); levelData[offset + 1] = (byte)(pixel >> 8); offset += 2; } } #endif } break; case SurfaceFormat.Bgra4444: { #if OPENGL // Shift the channels to suit OpenGL int offset = 0; for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { ushort pixel = BitConverter.ToUInt16(levelData, offset); pixel = (ushort)(((pixel & 0x0FFF) << 4) | ((pixel & 0xF000) >> 12)); levelData[offset] = (byte)(pixel); levelData[offset + 1] = (byte)(pixel >> 8); offset += 2; } } #endif } break; case SurfaceFormat.NormalizedByte4: { int bytesPerPixel = surfaceFormat.GetSize(); int pitch = levelWidth * bytesPerPixel; for (int y = 0; y < levelHeight; y++) { for (int x = 0; x < levelWidth; x++) { int color = BitConverter.ToInt32(levelData, y * pitch + x * bytesPerPixel); levelData[y * pitch + x * 4] = (byte)(((color >> 16) & 0xff)); //R:=W levelData[y * pitch + x * 4 + 1] = (byte)(((color >> 8) & 0xff)); //G:=V levelData[y * pitch + x * 4 + 2] = (byte)(((color) & 0xff)); //B:=U levelData[y * pitch + x * 4 + 3] = (byte)(((color >> 24) & 0xff)); //A:=Q } } } break; } texture.SetData(level, null, levelData, 0, levelDataSizeInBytes); } #if OPENGL }); #endif return texture; }
public void GetData <T> (int offsetInBytes, T[] data, int startIndex, int elementCount, int vertexStride) where T : struct { #if GLES // Buffers are write-only on OpenGL ES 1.1 and 2.0. See the GL_OES_mapbuffer extension for more information. // http://www.khronos.org/registry/gles/extensions/OES/OES_mapbuffer.txt throw new NotSupportedException("Vertex buffers are write-only on OpenGL ES platforms"); #else if (data == null) { throw new ArgumentNullException("data", "This method does not accept null for this parameter."); } if (data.Length < (startIndex + elementCount)) { throw new ArgumentOutOfRangeException("elementCount", "This parameter must be a valid index within the array."); } if (BufferUsage == BufferUsage.WriteOnly) { throw new NotSupportedException("Calling GetData on a resource that was created with BufferUsage.WriteOnly is not supported."); } if ((elementCount * vertexStride) > (VertexCount * VertexDeclaration.VertexStride)) { throw new InvalidOperationException("The array is not the correct size for the amount of data requested."); } #if DIRECTX GenerateIfRequired(); if (_isDynamic) { throw new NotImplementedException(); } else { var deviceContext = GraphicsDevice._d3dContext; // Copy the buffer to a staging resource var stagingDesc = _buffer.Description; stagingDesc.BindFlags = SharpDX.Direct3D11.BindFlags.None; stagingDesc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.Read | SharpDX.Direct3D11.CpuAccessFlags.Write; stagingDesc.Usage = SharpDX.Direct3D11.ResourceUsage.Staging; stagingDesc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; var stagingBuffer = new SharpDX.Direct3D11.Buffer(GraphicsDevice._d3dDevice, stagingDesc); lock (GraphicsDevice._d3dContext) deviceContext.CopyResource(_buffer, stagingBuffer); int TsizeInBytes = SharpDX.Utilities.SizeOf <T>(); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); var startBytes = startIndex * vertexStride; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); SharpDX.DataPointer DataPointer = new SharpDX.DataPointer(dataPtr, data.Length * TsizeInBytes); lock (GraphicsDevice._d3dContext) { // Map the staging resource to a CPU accessible memory var box = deviceContext.MapSubresource(stagingBuffer, 0, SharpDX.Direct3D11.MapMode.Read, SharpDX.Direct3D11.MapFlags.None); if (vertexStride == TsizeInBytes) { SharpDX.Utilities.CopyMemory(dataPtr, box.DataPointer + offsetInBytes, vertexStride * elementCount); } else { for (int i = 0; i < data.Length; i++) { SharpDX.Utilities.CopyMemory(dataPtr + i * TsizeInBytes, box.DataPointer + i * vertexStride + offsetInBytes, TsizeInBytes); } } // Make sure that we unmap the resource in case of an exception deviceContext.UnmapSubresource(stagingBuffer, 0); } stagingBuffer.Dispose(); } #elif PSM throw new NotImplementedException(); #else if (Threading.IsOnUIThread()) { GetBufferData(offsetInBytes, data, startIndex, elementCount, vertexStride); } else { Threading.BlockOnUIThread(() => GetBufferData(offsetInBytes, data, startIndex, elementCount, vertexStride)); } #endif #endif }
internal Texture2D(GraphicsDevice graphicsDevice, int width, int height, bool mipmap, SurfaceFormat format, bool renderTarget) { if (graphicsDevice == null) throw new ArgumentNullException("Graphics Device Cannot Be Null"); this.GraphicsDevice = graphicsDevice; this.width = width; this.height = height; this.format = format; this.levelCount = 1; if (mipmap) { int size = Math.Max(this.width, this.height); while (size > 1) { size = size / 2; this.levelCount++; } } #if DIRECTX // TODO: Move this to SetData() if we want to make Immutable textures! var desc = new SharpDX.Direct3D11.Texture2DDescription(); desc.Width = width; desc.Height = height; desc.MipLevels = levelCount; desc.ArraySize = 1; desc.Format = SharpDXHelper.ToFormat(format); desc.BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource; desc.CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None; desc.SampleDescription.Count = 1; desc.SampleDescription.Quality = 0; desc.Usage = SharpDX.Direct3D11.ResourceUsage.Default; desc.OptionFlags = SharpDX.Direct3D11.ResourceOptionFlags.None; if (renderTarget) desc.BindFlags |= SharpDX.Direct3D11.BindFlags.RenderTarget; _texture = new SharpDX.Direct3D11.Texture2D(graphicsDevice._d3dDevice, desc); #elif PSM _texture2D = new Sce.PlayStation.Core.Graphics.Texture2D(width, height, mipmap, PSSHelper.ToFormat(format)); #else this.glTarget = TextureTarget.Texture2D; Threading.BlockOnUIThread(() => { // Store the current bound texture. var prevTexture = GraphicsExtensions.GetBoundTexture2D(); GenerateGLTextureIfRequired(); format.GetGLFormat(out glInternalFormat, out glFormat, out glType); if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) { var imageSize = 0; switch (format) { case SurfaceFormat.RgbPvrtc2Bpp: case SurfaceFormat.RgbaPvrtc2Bpp: imageSize = (Math.Max(this.width, 8) * Math.Max(this.height, 8) * 2 + 7) / 8; break; case SurfaceFormat.RgbPvrtc4Bpp: case SurfaceFormat.RgbaPvrtc4Bpp: imageSize = (Math.Max(this.width, 16) * Math.Max(this.height, 8) * 4 + 7) / 8; break; case SurfaceFormat.Dxt1: imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * 8 * 1; break; case SurfaceFormat.Dxt3: case SurfaceFormat.Dxt5: imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * 16 * 1; break; default: throw new NotImplementedException(); } GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, glInternalFormat, this.width, this.height, 0, imageSize, IntPtr.Zero); GraphicsExtensions.CheckGLError(); } else { GL.TexImage2D(TextureTarget.Texture2D, 0, #if IOS || ANDROID (int)glInternalFormat, #else glInternalFormat, #endif this.width, this.height, 0, glFormat, glType, IntPtr.Zero); GraphicsExtensions.CheckGLError(); } // Restore the bound texture. GL.BindTexture(TextureTarget.Texture2D, prevTexture); GraphicsExtensions.CheckGLError(); }); #endif }
public override Task ExecuteBindingAsync(Metadata.ModelMetadataProvider metadataProvider, HttpActionContext actionContext, Threading.CancellationToken cancellationToken) { throw new NotImplementedException(); }
public void SetData<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct { if (data == null) throw new ArgumentNullException("data"); #if OPENGL Threading.BlockOnUIThread(() => { #endif #if !PSM var elementSizeInByte = Marshal.SizeOf(typeof(T)); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); var startBytes = startIndex * elementSizeInByte; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); #endif int x, y, w, h; if (rect.HasValue) { x = rect.Value.X; y = rect.Value.Y; w = rect.Value.Width; h = rect.Value.Height; } else { x = 0; y = 0; w = Math.Max(width >> level, 1); h = Math.Max(height >> level, 1); } #if DIRECTX var box = new SharpDX.DataBox(dataPtr, GetPitch(w), 0); var region = new SharpDX.Direct3D11.ResourceRegion(); region.Top = y; region.Front = 0; region.Back = 1; region.Bottom = y + h; region.Left = x; region.Right = x + w; // TODO: We need to deal with threaded contexts here! var d3dContext = GraphicsDevice._d3dContext; lock (d3dContext) d3dContext.UpdateSubresource(box, _texture, level, region); #elif PSM _texture2D.SetPixels(level, data, _texture2D.Format, startIndex, 0, x, y, w, h); #elif OPENGL // Store the current bound texture. var prevTexture = GraphicsExtensions.GetBoundTexture2D(); GenerateGLTextureIfRequired(); GL.BindTexture(TextureTarget.Texture2D, this.glTexture); GraphicsExtensions.CheckGLError(); if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) { if (rect.HasValue) { GL.CompressedTexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, #if GLES glInternalFormat, #else glFormat, #endif data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.CompressedTexImage2D(TextureTarget.Texture2D, level, glInternalFormat, w, h, 0, data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } } else { // Set pixel alignment to match texel size in bytes GL.PixelStore(PixelStoreParameter.UnpackAlignment, GraphicsExtensions.Size(this.Format)); if (rect.HasValue) { GL.TexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.TexImage2D(TextureTarget.Texture2D, level, #if GLES (int)glInternalFormat, #else glInternalFormat, #endif w, h, 0, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } // Return to default pixel alignment GL.PixelStore(PixelStoreParameter.UnpackAlignment, 4); } #if !ANDROID GL.Finish(); GraphicsExtensions.CheckGLError(); #endif // Restore the bound texture. GL.BindTexture(TextureTarget.Texture2D, prevTexture); GraphicsExtensions.CheckGLError(); #endif // OPENGL #if !PSM dataHandle.Free(); #endif #if OPENGL #if !ANDROID // Required to make sure that any texture uploads on a thread are completed // before the main thread tries to use the texture. GL.Finish(); #endif }); #endif }
protected override Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { throw new NotImplementedException(); }
private void PlatformGetData <T>(int level, int arraySlice, Rectangle rect, T[] data, int startIndex, int elementCount) where T : struct { Threading.EnsureUIThread(); #if GLES // TODO: check for for non renderable formats (formats that can't be attached to FBO) var framebufferId = 0; GL.GenFramebuffers(1, out framebufferId); GraphicsExtensions.CheckGLError(); GL.BindFramebuffer(FramebufferTarget.Framebuffer, framebufferId); GraphicsExtensions.CheckGLError(); GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, this.glTexture, 0); GraphicsExtensions.CheckGLError(); GL.ReadPixels(rect.X, rect.Y, rect.Width, rect.Height, this.glFormat, this.glType, data); GraphicsExtensions.CheckGLError(); GL.DeleteFramebuffers(1, ref framebufferId); #else var tSizeInByte = ReflectionHelpers.SizeOf <T> .Get(); GL.BindTexture(TextureTarget.Texture2D, this.glTexture); GL.PixelStore(PixelStoreParameter.PackAlignment, Math.Min(tSizeInByte, 8)); if (glFormat == (PixelFormat)GLPixelFormat.CompressedTextureFormats) { // Note: for compressed format Format.GetSize() returns the size of a 4x4 block var pixelToT = Format.GetSize() / tSizeInByte; var tFullWidth = Math.Max(this.width >> level, 1) / 4 * pixelToT; var temp = new T[Math.Max(this.height >> level, 1) / 4 * tFullWidth]; GL.GetCompressedTexImage(TextureTarget.Texture2D, level, temp); GraphicsExtensions.CheckGLError(); var rowCount = rect.Height / 4; var tRectWidth = rect.Width / 4 * Format.GetSize() / tSizeInByte; for (var r = 0; r < rowCount; r++) { var tempStart = rect.X / 4 * pixelToT + (rect.Top / 4 + r) * tFullWidth; var dataStart = startIndex + r * tRectWidth; Array.Copy(temp, tempStart, data, dataStart, tRectWidth); } } else { // we need to convert from our format size to the size of T here var tFullWidth = Math.Max(this.width >> level, 1) * Format.GetSize() / tSizeInByte; var temp = new T[Math.Max(this.height >> level, 1) * tFullWidth]; GL.GetTexImage(TextureTarget.Texture2D, level, glFormat, glType, temp); GraphicsExtensions.CheckGLError(); var pixelToT = Format.GetSize() / tSizeInByte; var rowCount = rect.Height; var tRectWidth = rect.Width * pixelToT; for (var r = 0; r < rowCount; r++) { var tempStart = rect.X * pixelToT + (r + rect.Top) * tFullWidth; var dataStart = startIndex + r * tRectWidth; Array.Copy(temp, tempStart, data, dataStart, tRectWidth); } } #endif }
public static GenTensor <T, TWrapper> CreateTensor(TensorShape shape, Func <int[], T> operation, Threading threading) { var res = new GenTensor <T, TWrapper>(shape); if (threading == Threading.Multi || threading == Threading.Auto && shape.shape[0] > 5) { var inds = res.IterateOverCopy(0).ToArray(); Parallel.For(0, inds.Length, id => { var ind = inds[id]; res.SetValueNoCheck(operation(ind), ind); }); } else { foreach (var ind in res.IterateOverElements()) { res.SetValueNoCheck(operation(ind), ind); } } return(res); }
protected Texture2D(GraphicsDevice graphicsDevice, int width, int height, bool mipmap, SurfaceFormat format, SurfaceType type, bool shared) { if (graphicsDevice == null) throw new ArgumentNullException("Graphics Device Cannot Be Null"); this.GraphicsDevice = graphicsDevice; this.width = width; this.height = height; this._format = format; this._levelCount = mipmap ? CalculateMipLevels(width, height) : 1; // Texture will be assigned by the swap chain. if (type == SurfaceType.SwapChainRenderTarget) return; #if DIRECTX _shared = shared; _renderTarget = (type == SurfaceType.RenderTarget); _mipmap = mipmap; // Create texture GetTexture(); #elif PSM PixelBufferOption option = PixelBufferOption.None; if (type == SurfaceType.RenderTarget) option = PixelBufferOption.Renderable; _texture2D = new Sce.PlayStation.Core.Graphics.Texture2D(width, height, mipmap, PSSHelper.ToFormat(format),option); #else this.glTarget = TextureTarget.Texture2D; Threading.BlockOnUIThread(() => { // Store the current bound texture. var prevTexture = GraphicsExtensions.GetBoundTexture2D(); GenerateGLTextureIfRequired(); format.GetGLFormat(out glInternalFormat, out glFormat, out glType); if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) { var imageSize = 0; switch (format) { case SurfaceFormat.RgbPvrtc2Bpp: case SurfaceFormat.RgbaPvrtc2Bpp: imageSize = (Math.Max(this.width, 16) * Math.Max(this.height, 8) * 2 + 7) / 8; break; case SurfaceFormat.RgbPvrtc4Bpp: case SurfaceFormat.RgbaPvrtc4Bpp: imageSize = (Math.Max(this.width, 8) * Math.Max(this.height, 8) * 4 + 7) / 8; break; case SurfaceFormat.RgbEtc1: case SurfaceFormat.Dxt1: case SurfaceFormat.Dxt1a: case SurfaceFormat.Dxt3: case SurfaceFormat.Dxt5: imageSize = ((this.width + 3) / 4) * ((this.height + 3) / 4) * format.Size(); break; default: throw new NotSupportedException(); } GL.CompressedTexImage2D(TextureTarget.Texture2D, 0, glInternalFormat, this.width, this.height, 0, imageSize, IntPtr.Zero); GraphicsExtensions.CheckGLError(); } else { GL.TexImage2D(TextureTarget.Texture2D, 0, #if IOS || ANDROID (int)glInternalFormat, #else glInternalFormat, #endif this.width, this.height, 0, glFormat, glType, IntPtr.Zero); GraphicsExtensions.CheckGLError(); } // Restore the bound texture. GL.BindTexture(TextureTarget.Texture2D, prevTexture); GraphicsExtensions.CheckGLError(); }); #endif }
public override Task WriteAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken) { throw new NotSupportedException(SR.net_http_content_readonly_stream); }
public void SetData<T>(int level, Rectangle? rect, T[] data, int startIndex, int elementCount) where T : struct { if (data == null) throw new ArgumentNullException("data"); #if OPENGL Threading.BlockOnUIThread(() => { #endif #if !PSM var elementSizeInByte = Marshal.SizeOf(typeof(T)); var dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); // Use try..finally to make sure dataHandle is freed in case of an error try { var startBytes = startIndex * elementSizeInByte; var dataPtr = (IntPtr)(dataHandle.AddrOfPinnedObject().ToInt64() + startBytes); #endif int x, y, w, h; if (rect.HasValue) { x = rect.Value.X; y = rect.Value.Y; w = rect.Value.Width; h = rect.Value.Height; } else { x = 0; y = 0; w = Math.Max(width >> level, 1); h = Math.Max(height >> level, 1); // For DXT textures the width and height of each level is a multiple of 4. // OpenGL only: The last two mip levels require the width and height to be // passed as 2x2 and 1x1, but there needs to be enough data passed to occupy // a 4x4 block. // Ref: http://www.mentby.com/Group/mac-opengl/issue-with-dxt-mipmapped-textures.html if (_format == SurfaceFormat.Dxt1 || _format == SurfaceFormat.Dxt1a || _format == SurfaceFormat.Dxt3 || _format == SurfaceFormat.Dxt5) { #if DIRECTX w = (w + 3) & ~3; h = (h + 3) & ~3; #else if (w > 4) w = (w + 3) & ~3; if (h > 4) h = (h + 3) & ~3; #endif } } #if DIRECTX var box = new SharpDX.DataBox(dataPtr, GetPitch(w), 0); var region = new SharpDX.Direct3D11.ResourceRegion(); region.Top = y; region.Front = 0; region.Back = 1; region.Bottom = y + h; region.Left = x; region.Right = x + w; // TODO: We need to deal with threaded contexts here! var d3dContext = GraphicsDevice._d3dContext; lock (d3dContext) d3dContext.UpdateSubresource(box, GetTexture(), level, region); #elif PSM _texture2D.SetPixels(level, data, _texture2D.Format, startIndex, 0, x, y, w, h); #elif OPENGL // Store the current bound texture. var prevTexture = GraphicsExtensions.GetBoundTexture2D(); GenerateGLTextureIfRequired(); GL.BindTexture(TextureTarget.Texture2D, this.glTexture); GraphicsExtensions.CheckGLError(); if (glFormat == (GLPixelFormat)All.CompressedTextureFormats) { if (rect.HasValue) { GL.CompressedTexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, #if GLES glInternalFormat, #else glFormat, #endif data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.CompressedTexImage2D(TextureTarget.Texture2D, level, glInternalFormat, w, h, 0, data.Length - startBytes, dataPtr); GraphicsExtensions.CheckGLError(); } } else { // Set pixel alignment to match texel size in bytes GL.PixelStore(PixelStoreParameter.UnpackAlignment, GraphicsExtensions.Size(this.Format)); if (rect.HasValue) { GL.TexSubImage2D(TextureTarget.Texture2D, level, x, y, w, h, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } else { GL.TexImage2D(TextureTarget.Texture2D, level, #if GLES (int)glInternalFormat, #else glInternalFormat, #endif w, h, 0, glFormat, glType, dataPtr); GraphicsExtensions.CheckGLError(); } // Return to default pixel alignment GL.PixelStore(PixelStoreParameter.UnpackAlignment, 4); } #if !ANDROID GL.Finish(); GraphicsExtensions.CheckGLError(); #endif // Restore the bound texture. GL.BindTexture(TextureTarget.Texture2D, prevTexture); GraphicsExtensions.CheckGLError(); #endif // OPENGL #if !PSM } finally { dataHandle.Free(); } #endif #if OPENGL #if !ANDROID // Required to make sure that any texture uploads on a thread are completed // before the main thread tries to use the texture. GL.Finish(); #endif }); #endif }
protected virtual void Awake() { _instance = this; }
public static Texture2D FromStream(GraphicsDevice graphicsDevice, Stream stream) { //todo: partial classes would be cleaner #if IOS || MONOMAC #if IOS using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream))) #elif MONOMAC using (var nsImage = NSImage.FromStream (stream)) #endif { #if IOS var cgImage = uiImage.CGImage; #elif MONOMAC var rectangle = RectangleF.Empty; var cgImage = nsImage.AsCGImage (ref rectangle, null, null); #endif var width = cgImage.Width; var height = cgImage.Height; var data = new byte[width * height * 4]; var colorSpace = CGColorSpace.CreateDeviceRGB(); var bitmapContext = new CGBitmapContext(data, width, height, 8, width * 4, colorSpace, CGBitmapFlags.PremultipliedLast); bitmapContext.DrawImage(new RectangleF(0, 0, width, height), cgImage); bitmapContext.Dispose(); colorSpace.Dispose(); Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData(data); }); return texture; } #elif ANDROID using (Bitmap image = BitmapFactory.DecodeStream(stream, null, new BitmapFactory.Options { InScaled = false, InDither = false, InJustDecodeBounds = false, InPurgeable = true, InInputShareable = true, })) { var width = image.Width; var height = image.Height; int[] pixels = new int[width * height]; if ((width != image.Width) || (height != image.Height)) { using (Bitmap imagePadded = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888)) { Canvas canvas = new Canvas(imagePadded); canvas.DrawARGB(0, 0, 0, 0); canvas.DrawBitmap(image, 0, 0, null); imagePadded.GetPixels(pixels, 0, width, 0, 0, width, height); imagePadded.Recycle(); } } else { image.GetPixels(pixels, 0, width, 0, 0, width, height); } image.Recycle(); // Convert from ARGB to ABGR for (int i = 0; i < width * height; ++i) { uint pixel = (uint)pixels[i]; pixels[i] = (int)((pixel & 0xFF00FF00) | ((pixel & 0x00FF0000) >> 16) | ((pixel & 0x000000FF) << 16)); } Texture2D texture = null; Threading.BlockOnUIThread(() => { texture = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); texture.SetData<int>(pixels); }); return texture; } #elif WINDOWS_PHONE throw new NotImplementedException(); #elif WINDOWS_STOREAPP || DIRECTX // For reference this implementation was ultimately found through this post: // http://stackoverflow.com/questions/9602102/loading-textures-with-sharpdx-in-metro Texture2D toReturn = null; SharpDX.WIC.BitmapDecoder decoder; using(var bitmap = LoadBitmap(stream, out decoder)) using (decoder) { SharpDX.Direct3D11.Texture2D sharpDxTexture = CreateTex2DFromBitmap(bitmap, graphicsDevice); toReturn = new Texture2D(graphicsDevice, bitmap.Size.Width, bitmap.Size.Height); toReturn._texture = sharpDxTexture; } return toReturn; #elif PSM return new Texture2D(graphicsDevice, stream); #else using (Bitmap image = (Bitmap)Bitmap.FromStream(stream)) { // Fix up the Image to match the expected format image.RGBToBGR(); var data = new byte[image.Width * image.Height * 4]; BitmapData bitmapData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); if (bitmapData.Stride != image.Width * 4) throw new NotImplementedException(); Marshal.Copy(bitmapData.Scan0, data, 0, data.Length); image.UnlockBits(bitmapData); Texture2D texture = null; texture = new Texture2D(graphicsDevice, image.Width, image.Height); texture.SetData(data); return texture; } #endif }
protected override Task<HttpResponseMessage> SendAsync (HttpRequestMessage request, Threading.CancellationToken cancellationToken) { throw new PlatformNotSupportedException (); }
internal void SetTextures(GraphicsDevice device) { #if !DIRECTX Threading.EnsureUIThread(); #endif // Skip out if nothing has changed. if (_dirty == 0) { return; } #if DIRECTX // NOTE: We make the assumption here that the caller has // locked the d3dContext for us to use. var pixelShaderStage = device._d3dContext.PixelShader; #endif for (var i = 0; i < _textures.Length; i++) { var mask = 1 << i; if ((_dirty & mask) == 0) { continue; } var tex = _textures[i]; #if OPENGL GL.ActiveTexture(TextureUnit.Texture0 + i); GraphicsExtensions.CheckGLError(); // Clear the previous binding if the // target is different from the new one. if (_targets[i] != 0 && (tex == null || _targets[i] != tex.glTarget)) { GL.BindTexture(_targets[i], 0); GraphicsExtensions.CheckGLError(); } if (tex != null) { _targets[i] = tex.glTarget; GL.BindTexture(tex.glTarget, tex.glTexture); GraphicsExtensions.CheckGLError(); } #elif DIRECTX if (_textures[i] == null) { pixelShaderStage.SetShaderResource(i, null); } else { pixelShaderStage.SetShaderResource(i, _textures[i].GetShaderResourceView()); } #endif _dirty &= ~mask; if (_dirty == 0) { break; } } _dirty = 0; }
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, Threading.CancellationToken cancellationToken) { return _fs.ReadAsync(buffer, offset, count, cancellationToken); }
/// <summary> /// Sends the async. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, Threading.CancellationToken cancellationToken) { TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); } else { HttpWebRequest webRequest = null; if (this.AutomaticDecompression == DecompressionMethods.GZip) webRequest = new GZipHttpWebRequest(request.RequestUri); else webRequest = WebRequest.CreateHttp(request.RequestUri); webRequest.Method = request.Method.Method; if (webRequest.SupportsCookieContainer) webRequest.CookieContainer = this.CookieContainer; webRequest.AllowAutoRedirect = this.AllowAutoRedirect; webRequest.Credentials = this.Credentials; webRequest.UseDefaultCredentials = this.UseDefaultCredentials; Action<IEnumerable<KeyValuePair<string,string>>> addHeaders = (headers) => { if (headers == null) return; foreach (var header in headers) { switch (header.Key) { case "Accept": webRequest.Accept = header.Value; break; case "Content-Type": webRequest.ContentType = header.Value; break; case "UserAgent": webRequest.UserAgent = header.Value; break; default: webRequest.Headers[header.Key] = header.Value; break; } } }; addHeaders(request.Headers.InternalHeaders); addHeaders(request.Content.Headers.InternalHeaders); var beginGetResponseDelegate = new AsyncCallback(delegate(IAsyncResult asynchronousResult2) { HttpWebRequest req2 = (HttpWebRequest)asynchronousResult2.AsyncState; if (req2.HaveResponse) { try { WebResponse response = req2.EndGetResponse(asynchronousResult2); tcs.SetResult(new HttpResponseMessage(response, request)); } catch (Exception exception) { tcs.SetException(exception); } } }); if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Head) { webRequest.BeginGetResponse(beginGetResponseDelegate, webRequest); } else { #if !WP7 long length = -1; if (request.Content.TryComputeLength(out length)) webRequest.ContentLength = length; #endif webRequest.BeginGetRequestStream(new AsyncCallback(async delegate(IAsyncResult asynchronousResult) { HttpWebRequest req = (HttpWebRequest)asynchronousResult.AsyncState; if (cancellationToken.IsCancellationRequested) tcs.SetCanceled(); else { if (request.Content != null) { Stream postStream = null; try { postStream = req.EndGetRequestStream(asynchronousResult); } catch (Exception ex) { tcs.SetException(ex); return; } await request.Content.CopyToAsync(postStream); if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled(); return; } postStream.Close(); } req.BeginGetResponse(beginGetResponseDelegate, req); } }), webRequest); } } return tcs.Task; }