void GraphicsCore_Loaded(object sender, RoutedEventArgs e) { GraphicsCore.SetKinectDevice(DeviceManager); SetKinect(); SetPreprocessing(); SetView(); SetCameras(); SetShading(); SetLighting(); SetPerformance(); SetSave(); if (TurntableActivated) { InitRotatingScanner(); } }
/// <summary> /// Sets the content to all lines in the given polygon. /// </summary> /// <param name="center">The center of the ellipse.</param> /// <param name="radiusX">The radius in x direction.</param> /// <param name="radiusY">The radius in y direction.</param> public unsafe void SetContent(Vector2 center, float radiusX, float radiusY) { GraphicsCore.EnsureGraphicsSupportLoaded(); radiusX.EnsurePositiveOrZero(nameof(radiusX)); radiusY.EnsurePositiveOrZero(nameof(radiusY)); _center = center; _radiusX = radiusX; _radiusY = radiusY; SeeingSharpUtil.SafeDispose(ref _geometry); _geometry = GraphicsCore.Current.FactoryD2D !.CreateEllipseGeometry( new D2D.Ellipse( *(PointF *)¢er, radiusX, radiusY)); }
/// <summary> /// Initializes a new instance of the <see cref="MemoryRenderTarget" /> class. /// </summary> /// <param name="pixelHeight">Height of the offline render target in pixels.</param> /// <param name="pixelWidth">Width of the offline render target in pixels.</param> /// <param name="syncContext">Sets the SynchronizationContext which should be used by default.</param> public MemoryRenderTarget(int pixelWidth, int pixelHeight, SynchronizationContext syncContext = null) { //Set confiugration m_pixelWidth = pixelWidth; m_pixelHeight = pixelHeight; m_renderAwaitors = new ThreadSaveQueue <TaskCompletionSource <object> >(); if (syncContext == null) { syncContext = new SynchronizationContext(); } //Create the RenderLoop object GraphicsCore.Touch(); m_renderLoop = new RenderLoop(syncContext, this); m_renderLoop.Camera.SetScreenSize(pixelWidth, pixelHeight); m_renderLoop.RegisterRenderLoop(); }
public void Initialize(CoreApplicationView applicationView) { SeeingSharpApplication.InitializeAsync( this.GetType().GetTypeInfo().Assembly, new Assembly[] { typeof(SeeingSharpApplication).GetTypeInfo().Assembly, typeof(GraphicsCore).GetTypeInfo().Assembly }, new string[] { }).Wait(); GraphicsCore.Initialize(enableDebug: true); applicationView.Activated += this.OnViewActivated; // Register event handlers for app lifecycle. CoreApplication.Suspending += this.OnSuspending; CoreApplication.Resuming += this.OnResuming; }
/// <summary> /// Initializes a new instance of the <see cref="FullscreenRenderTarget" /> class. /// </summary> /// <param name="outputInfo">The target output monitor.</param> /// <param name="initialMode">The initial view mode.</param> public FullscreenRenderTarget(EngineOutputInfo outputInfo, EngineOutputModeInfo initialMode = default(EngineOutputModeInfo)) { outputInfo.EnsureNotNull(nameof(outputInfo)); // Check whether we are inside a win.forms application System.Windows.Forms.WindowsFormsSynchronizationContext syncContext = SynchronizationContext.Current as System.Windows.Forms.WindowsFormsSynchronizationContext; if (syncContext == null) { throw new SeeingSharpException($"{nameof(FullscreenRenderTarget)} muss be created inside a Windows.Forms application context!"); } m_syncContext = syncContext; //Set confiugration m_targetOutput = outputInfo; m_targetOutputMode = initialMode; if (m_targetOutputMode.HostOutput != outputInfo) { m_targetOutputMode = m_targetOutput.DefaultMode; } m_renderAwaitors = new ThreadSaveQueue <TaskCompletionSource <object> >(); // Ensure that graphics is initialized GraphicsCore.Touch(); // Create the dummy form m_dummyForm = new DummyForm(); m_dummyForm.SetStyleCustom(ControlStyles.AllPaintingInWmPaint, true); m_dummyForm.SetStyleCustom(ControlStyles.ResizeRedraw, true); m_dummyForm.SetStyleCustom(ControlStyles.OptimizedDoubleBuffer, false); m_dummyForm.SetStyleCustom(ControlStyles.Opaque, true); m_dummyForm.SetStyleCustom(ControlStyles.Selectable, true); m_dummyForm.SetDoubleBuffered(false); m_dummyForm.MouseEnter += (sender, eArgs) => Cursor.Hide(); m_dummyForm.MouseLeave += (sender, eArgs) => Cursor.Show(); m_dummyForm.HandleDestroyed += OnDummyForm_HandleDestroyed; m_dummyForm.GotFocus += OnDummyForm_GotFocus; m_dummyForm.CreateControl(); // Create and start the renderloop m_renderLoop = new RenderLoop(syncContext, this); m_renderLoop.Camera.SetScreenSize(m_targetOutputMode.PixelWidth, m_targetOutputMode.PixelHeight); m_renderLoop.RegisterRenderLoop(); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Default initializations SeeingSharpApplication.InitializeAsync( Assembly.GetExecutingAssembly(), new Assembly[] { typeof(GraphicsCore).Assembly }, new string[0]).Wait(); GraphicsCore.Initialize(); // Run the application MainWindow mainWindow = new MainWindow(); SeeingSharpApplication.Current.InitializeUIEnvironment(); Application.Run(mainWindow); }
public static async Task InitializeWithGrahicsAsync() { // Initialize main application singleton if (!SeeingSharpApplication.IsInitialized) { await SeeingSharpApplication.InitializeAsync( Assembly.GetExecutingAssembly(), new Assembly[] { typeof(GraphicsCore).Assembly }, new string[0]); } // Initialize the graphics engine if (!GraphicsCore.IsInitialized) { GraphicsCore.Initialize(); GraphicsCore.Current.SetDefaultDeviceToSoftware(); GraphicsCore.Current.DefaultDevice.ForceDetailLevel(DetailLevel.High); } Assert.True(GraphicsCore.IsInitialized, "GraphicsCore could not be initialized!"); }
protected async override void OnStartup(StartupEventArgs e) { base.OnStartup(e); // Default initializations await SeeingSharpApplication.InitializeAsync( Assembly.GetExecutingAssembly(), new Assembly[] { typeof(GraphicsCore).Assembly }, new string[0]); // Initialize UI and Graphics SeeingSharpApplication.Current.InitializeUIEnvironment(); GraphicsCore.Initialize(); // Load the main window MainWindow mainWindow = new SeeingSharpModelViewer.MainWindow(); SeeingSharpApplication.Current.InitializeAutoErrorReporting_Wpf(this, mainWindow); mainWindow.Show(); }
public async Task MemoryRenderTarget_GraphicsInitError() { await UnitTestHelper.InitializeWithGrahicsAsync(); bool isRenderTargetOperational = true; bool isGraphicsCoreInitialized = true; int registeredRenderLoopCount = 1; using (GraphicsCore.AutomatedTest_NewTestEnviornment()) using (GraphicsCore.AutomatedTest_ForceDeviceInitError()) { using (MemoryRenderTarget memRenderTarget = new MemoryRenderTarget(1024, 1024)) { isRenderTargetOperational = memRenderTarget.IsOperational; isGraphicsCoreInitialized = GraphicsCore.IsInitialized; registeredRenderLoopCount = GraphicsCore.Current.RegisteredRenderLoopCount; } } Assert.False(isRenderTargetOperational); Assert.False(isGraphicsCoreInitialized); Assert.True(registeredRenderLoopCount == 0); }
private void SaveRawImage() { SaveDialog(GraphicsCore.SaveRawImage(GenerateFilename(".png"))); }
/// <summary> /// 描画 /// </summary> public void Draw() { var context = GraphicsCore.ImmediateContext; UpdateDraw(); { // シャドウマップ using (new MyGpuProfilePoint(context, "Create ShadowMap")) { shadowMap_.BeginRender(context); { SceneDraw(context); } shadowMap_.EndRender(context); } // キューブマップ if (cubeMapRenderEnable_ && !cubeMapRendered_) { RenderCubeMap(); cubeMapRendered_ = true; } // ディファードパス using (new MyGpuProfilePoint(context, "Deferred Path")) { // GBuffer using (new MyGpuProfilePoint(context, "Render GBuffer")) { GraphicsCore.CurrentDrawCamera = GraphicsCore.Camera3D; RenderGBuffer(); } context.SetRenderTargets(new Texture[4], null); // unbind // ライティングCS using (new MyGpuProfilePoint(context, "Lighting")) { csMgr_.Bind(); int x = Lib.ComputeShader.CalcThreadGroups(gbuffers_[0].Width, 32); int y = Lib.ComputeShader.CalcThreadGroups(gbuffers_[0].Height, 32); csMgr_.Dispatch(gbuffers_[0].Width, gbuffers_[0].Height); csMgr_.UnBind(); } } // フォワードパス using (new MyGpuProfilePoint(context, "Forward Path")) { context.SetRenderTargets(forwardBuffer_.color_buffer_, forwardBuffer_.depth_stencil_); { // キューブマップデバッグ if (cubeMapRenderEnable_) { //globalCapture_.DebugDraw(); //foreach (var c in localCapture_) { // c.DebugDraw(); //} } //// ライトのデバッグ描画 //if (ViewModel.IsDrawLights // && ViewModel.ViewIndex == (int)ViewItems.Type.Result // && ViewModel.TiledRenderView != (int)TiledRenderItems.Type.LightCount // ) { // lightMgr_.DebugDraw(); //} } } // トーンマップ using (new MyGpuProfilePoint(context, "HDR Resolve")) { if (viewModel_.IsEnableToneMap) { toneMap_.CalcLuminance(context, uav_); context.SetRenderTargets(hdrResultBuffer_.color_buffer_, null); toneMap_.KeyValue = viewModel_.ToneMapKeyValue; toneMap_.ResolveHDR(context, uav_); } else { context.SetRenderTargets(hdrResultBuffer_.color_buffer_, null); toneMap_.ResolveGamma(context, uav_); } } // 最終レンダリング GraphicsCore.BeginRender(); { context.ClearDepthStencil(GraphicsCore.DefaultDepthBuffer, 1.0f); // ライティング結果 if (ViewModel.IsEnableFXAA && ViewModel.ViewIndex == (int)ViewItems.Type.Result) { using (new MyGpuProfilePoint(context, "FXAA")) { fxaaPrim_.Draw(context); } } else { prim_.Draw(context); } } } }
void SetPerformance() { GraphicsCore.SetPerformance( Settings.TriangleGridResolution.Width, Settings.TriangleGridResolution.Height); }
internal GraphicsCoreInternals(GraphicsCore parent) { _parent = parent; }
/// <summary> /// Wird aufgerufen, wenn die Anwendung durch den Endbenutzer normal gestartet wird. Weitere Einstiegspunkte /// werden z. B. verwendet, wenn die Anwendung gestartet wird, um eine bestimmte Datei zu öffnen. /// </summary> /// <param name="e">Details über Startanforderung und -prozess.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { // Initialize application and graphics if (!SeeingSharpApplication.IsInitialized) { await SeeingSharpApplication.InitializeAsync( this.GetType().GetTypeInfo().Assembly, new Assembly[] { typeof(SeeingSharpApplication).GetTypeInfo().Assembly, typeof(GraphicsCore).GetTypeInfo().Assembly }, new string[] { e.Arguments }); GraphicsCore.Initialize(); // Force high texture quality on tablet devices foreach (EngineDevice actDevice in GraphicsCore.Current.LoadedDevices) { if (actDevice.IsSoftware) { continue; } actDevice.Configuration.TextureQuality = TextureQuality.Hight; } // Initialize the UI environment SeeingSharpApplication.Current.InitializeUIEnvironment(); } Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// キューブマップにレンダリング /// </summary> void RenderCubeMap() { var context = GraphicsCore.ImmediateContext; // コンスタントバッファ更新定義 bool isInit = false; Shader.SetConstantBufferUpdateFunc("CB_LightParam", (s, i) => { if (!isInit) { dynamic cb = i; cb.g_directionalLightDir = lightMgr_.DirectionalLightDir; cb.g_directionalLightIntensity = lightMgr_.DirectionalLightIntensity; cb.g_shadowMatrix = Matrix.Transpose(shadowMap_.Camera.ViewProjectionMatrix); isInit = true; return(true); } return(false); }); // モデルのシェーダ差し換え Func <Shader, Shader> overrideFunc = (o) => { return(ShaderManager.FindShader("ForwardRender", (uint)(Shader.VertexAttr.NORMAL | Shader.VertexAttr.TEXCOORD0) & o.NeedVertexAttr)); }; // 描画アクション Action func = () => { // TODO:要クリア //context.ClearRenderTarget(new Color4(1, 0, 0, 0)); //context.ClearDepthStencil(); int shadowMapBindingPoint = 4; context.SetShaderResourcePS(shadowMapBindingPoint, shadowMap_.Map); GraphicsCore.SetSamplerStatePS(shadowMapBindingPoint, shadowMap_.Map.AddressingModeU, shadowMap_.Map.AddressingModeV); ShaderManager.UserShaderBindHandler += overrideFunc; SceneDraw(context); ShaderManager.UserShaderBindHandler -= overrideFunc; }; //globalCapture_.Capture(func, 3); if (localCapture_.Count > 0) { foreach (var c in localCapture_) { c.Capture(context, func, 2); } int size = cubeMapInfo_.numZ * cubeMapInfo_.numY * cubeMapInfo_.numX * 4 * 2; DataStream data_r = new DataStream(size, true, true); DataStream data_g = new DataStream(size, true, true); DataStream data_b = new DataStream(size, true, true); for (int z = 0; z < cubeMapInfo_.numZ; z++) { for (int y = 0; y < cubeMapInfo_.numY; y++) { for (int x = 0; x < cubeMapInfo_.numX; x++) { int index = (z * cubeMapInfo_.numY * cubeMapInfo_.numX) + (y * cubeMapInfo_.numX) + x; var coef = localCapture_[index].SHCoef; for (int i = 0; i < 4; i++) { data_r.Write(Lib.Math.CPf32Tof16(coef[i].X)); data_g.Write(Lib.Math.CPf32Tof16(coef[i].Y)); data_b.Write(Lib.Math.CPf32Tof16(coef[i].Z)); //data_r.Write(coef[i].X); //data_g.Write(coef[i].Y); //data_b.Write(coef[i].Z); } } } } var giTexDesc = new Texture.InitDesc() { bindFlag = TextureBuffer.BindFlag.IsRenderTarget, width = cubeMapInfo_.numX, height = cubeMapInfo_.numY, depth = cubeMapInfo_.numZ, format = SlimDX.DXGI.Format.R16G16B16A16_Float, //format = SlimDX.DXGI.Format.R32G32B32A32_Float, }; giTexDesc.initStream = data_r; giTextures_[0] = new Texture(giTexDesc); giTextures_[0].SaveFile("asset/gitex_r.dds"); giTexDesc.initStream = data_g; giTextures_[1] = new Texture(giTexDesc); giTextures_[1].SaveFile("asset/gitex_g.dds"); giTexDesc.initStream = data_b; giTextures_[2] = new Texture(giTexDesc); giTextures_[2].SaveFile("asset/gitex_b.dds"); csMgr_.SetResources(6, giTextures_[0]); csMgr_.SetResources(7, giTextures_[1]); csMgr_.SetResources(8, giTextures_[2]); } }
/// <summary> /// Initializes a new instance of the <see cref="SeeingSharpRendererElement"/> class. /// </summary> public SeeingSharpRendererElement() { this.Loaded += OnLoaded; this.Unloaded += OnUnloaded; // Basic configuration this.Focusable = true; this.IsHitTestVisible = true; this.Stretch = System.Windows.Media.Stretch.Fill; this.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; this.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; // Load ummy bitmap using (System.Drawing.Bitmap dummyOrig = Properties.Resources.GfxNotInitialized) { m_dummyBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dummyOrig.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(500, 500)); } this.Source = m_dummyBitmap; //Create the RenderLoop object GraphicsCore.Touch(); m_renderLoop = new RenderLoop( SynchronizationContext.Current, this, isDesignMode: this.IsInDesignMode()); // Break here if we are in design mode if (this.IsInDesignMode()) { return; } m_renderLoop.ClearColor = Color4.Transparent; m_renderLoop.CallPresentInUIThread = true; // Create new scene and camera object if (SeeingSharpApplication.IsInitialized) { this.Scene = new Core.Scene(); this.Camera = new PerspectiveCamera3D(); } //Attach to SizeChanged event (refresh view resources only after a specific time) if (SeeingSharpApplication.IsInitialized) { // Observe events and trigger rendreing as long as the control lives this.Loaded += (sender, eArgs) => { if (m_controlObserver == null) { m_controlObserver = CommonTools.DisposeObject(m_controlObserver); m_controlObserver = Observable.FromEventPattern <EventArgs>(this, "SizeChanged") .Merge(Observable.FromEventPattern <EventArgs>(m_renderLoop.ViewConfiguration, "ConfigurationChanged")) .Throttle(TimeSpan.FromSeconds(0.5)) .ObserveOn(SynchronizationContext.Current) .Subscribe((innerEArgs) => OnThrottledSizeChanged()); SystemEvents.SessionSwitch += OnSystemEvents_SessionSwitch; } }; this.Unloaded += (sender, eArgs) => { if (m_controlObserver != null) { SystemEvents.SessionSwitch -= OnSystemEvents_SessionSwitch; m_controlObserver = CommonTools.DisposeObject(m_controlObserver); } }; } }
/// <summary> /// IDWriteTextLayout::Draw calls this function to instruct the client to render a run of glyphs. /// </summary> /// <param name="clientDrawingContext">The application-defined drawing context passed to <see cref="M:Vortice.DirectWrite.TextLayout.Draw_(System.IntPtr,System.IntPtr,System.Single,System.Single)" />.</param> /// <param name="baselineOriginX">The pixel location (X-coordinate) at the baseline origin of the glyph run.</param> /// <param name="baselineOriginY">The pixel location (Y-coordinate) at the baseline origin of the glyph run.</param> /// <param name="measuringMode">The measuring method for glyphs in the run, used with the other properties to determine the rendering mode.</param> /// <param name="glyphRun">Pointer to the glyph run instance to render.</param> /// <param name="glyphRunDescription">A pointer to the optional glyph run description instance which contains properties of the characters associated with this run.</param> /// <param name="clientDrawingEffect">Application-defined drawing effects for the glyphs to render. Usually this argument represents effects such as the foreground brush filling the interior of text.</param> /// <returns> /// If the method succeeds, it returns S_OK. Otherwise, it returns an HRESULT error code. /// </returns> /// <unmanaged>HRESULT DrawGlyphRun([None] void* clientDrawingContext,[None] FLOAT baselineOriginX,[None] FLOAT baselineOriginY,[None] DWRITE_MEASURING_MODE measuringMode,[In] const DWRITE_GLYPH_RUN* glyphRun,[In] const DWRITE_GLYPH_RUN_DESCRIPTION* glyphRunDescription,[None] IUnknown* clientDrawingEffect)</unmanaged> /// <remarks> /// The <see cref="M:Vortice.DirectWrite.TextLayout.Draw_(System.IntPtr,System.IntPtr,System.Single,System.Single)" /> function calls this callback function with all the information about glyphs to render. The application implements this callback by mostly delegating the call to the underlying platform's graphics API such as {{Direct2D}} to draw glyphs on the drawing context. An application that uses GDI can implement this callback in terms of the <see cref="M:Vortice.DirectWrite.BitmapRenderTarget.DrawGlyphRun(System.Single,System.Single,SharpDX.Direct2D1.MeasuringMode,Vortice.DirectWrite.GlyphRun,Vortice.DirectWrite.RenderingParams,SharpDX.Color4)" /> method. /// </remarks> public override void DrawGlyphRun( IntPtr clientDrawingContext, float baselineOriginX, float baselineOriginY, MeasuringMode measuringMode, DWrite.GlyphRun glyphRun, DWrite.GlyphRunDescription glyphRunDescription, IUnknown clientDrawingEffect) { if (glyphRun.Indices == null || glyphRun.Indices.Length == 0) { return; } GraphicsCore.EnsureGraphicsSupportLoaded(); var d2DFactory = GraphicsCore.Current.FactoryD2D !; // Extrude geometry data out of given glyph run var geometryExtruder = new SimplePolygon2DGeometrySink(new Vector2(baselineOriginX, baselineOriginY)); using (var pathGeometry = d2DFactory.CreatePathGeometry()) { // Write all geometry data into a standard PathGeometry object using (var geoSink = pathGeometry.Open()) { glyphRun.FontFace !.GetGlyphRunOutline( glyphRun.FontSize, glyphRun.Indices, glyphRun.Advances, glyphRun.Offsets, glyphRun.IsSideways, glyphRun.BidiLevel % 2 == 1, geoSink); geoSink.Close(); } // Simplify written geometry and write it into own structure pathGeometry.Simplify(D2D.GeometrySimplificationOption.Lines, _geometryOptions.SimplificationFlatternTolerance, geometryExtruder); } // Geometry for caching the result var tempGeometry = new Geometry(); var tempSurface = tempGeometry.CreateSurface(); // Create the text surface if (_geometryOptions.MakeSurface) { // Separate polygons by clock direction // Order polygons as needed for further hole finding algorithm IEnumerable <Polygon2D> fillingPolygons = geometryExtruder.GeneratedPolygons .Where(actPolygon => actPolygon.EdgeOrder == EdgeOrder.CounterClockwise) .OrderBy(actPolygon => actPolygon.BoundingBox.Size.X * actPolygon.BoundingBox.Size.Y); var holePolygons = geometryExtruder.GeneratedPolygons .Where(actPolygon => actPolygon.EdgeOrder == EdgeOrder.Clockwise) .OrderByDescending(actPolygon => actPolygon.BoundingBox.Size.X * actPolygon.BoundingBox.Size.Y) .ToList(); // Build geometry for all polygons foreach (var actFillingPolygon in fillingPolygons) { // Find all corresponding holes var actFillingPolygonBounds = actFillingPolygon.BoundingBox; IEnumerable <Polygon2D> correspondingHoles = holePolygons .Where(actHolePolygon => actHolePolygon.BoundingBox.IsContainedBy(actFillingPolygonBounds)) .ToList(); // Two steps here: // - Merge current filling polygon and all its holes. // - RemoveObject found holes from current hole list var polygonForRendering = actFillingPolygon; var polygonForTriangulation = actFillingPolygon.Clone(); var cutPoints = new List <Vector2>(); foreach (var actHole in correspondingHoles) { holePolygons.Remove(actHole); polygonForRendering = polygonForRendering.MergeWithHole(actHole, Polygon2DMergeOptions.DEFAULT, cutPoints); polygonForTriangulation = polygonForTriangulation.MergeWithHole(actHole, new Polygon2DMergeOptions { MakeMergepointSpaceForTriangulation = true }); } var actBaseIndex = tempGeometry.CountVertices; // Append all vertices to temporary Geometry for (var loop = 0; loop < polygonForRendering.Vertices.Count; loop++) { // Calculate 3d location and texture coordinate var actVertexLocation = new Vector3( polygonForRendering.Vertices[loop].X, 0f, polygonForRendering.Vertices[loop].Y); var actTexCoord = new Vector2( (polygonForRendering.Vertices[loop].X - polygonForRendering.BoundingBox.Location.X) / polygonForRendering.BoundingBox.Size.X, (polygonForRendering.Vertices[loop].Y - polygonForRendering.BoundingBox.Location.Y) / polygonForRendering.BoundingBox.Size.Y); if (float.IsInfinity(actTexCoord.X) || float.IsNaN(actTexCoord.X)) { actTexCoord.X = 0f; } if (float.IsInfinity(actTexCoord.Y) || float.IsNaN(actTexCoord.Y)) { actTexCoord.Y = 0f; } // Append the vertex to the result tempGeometry.AddVertex( new VertexBasic( actVertexLocation, _geometryOptions.SurfaceVertexColor, actTexCoord, new Vector3(0f, 1f, 0f))); } // Generate cubes on each vertex if requested if (_geometryOptions.GenerateCubesOnVertices) { for (var loop = 0; loop < polygonForRendering.Vertices.Count; loop++) { var colorToUse = Color4.GreenColor; var pointRenderSize = 0.1f; if (cutPoints.Contains(polygonForRendering.Vertices[loop])) { colorToUse = Color4.RedColor; pointRenderSize = 0.15f; } var actVertexLocation = new Vector3( polygonForRendering.Vertices[loop].X, 0f, polygonForRendering.Vertices[loop].Y); tempSurface.BuildCube(actVertexLocation, pointRenderSize).SetVertexColor(colorToUse); } } // Triangulate the polygon var triangleIndices = polygonForTriangulation.TriangulateUsingCuttingEars(); if (triangleIndices == null) { continue; } // Append all triangles to the temporary geometry using (var indexEnumerator = triangleIndices.GetEnumerator()) { while (indexEnumerator.MoveNext()) { var index1 = indexEnumerator.Current; var index2 = 0; var index3 = 0; if (indexEnumerator.MoveNext()) { index2 = indexEnumerator.Current; } else { break; } if (indexEnumerator.MoveNext()) { index3 = indexEnumerator.Current; } else { break; } tempSurface.AddTriangle( actBaseIndex + index3, actBaseIndex + index2, actBaseIndex + index1); } } } } // Make volumetric outlines var triangleCountWithoutSide = tempSurface.CountTriangles; if (_geometryOptions.MakeVolumetricText) { var volumetricTextDepth = _geometryOptions.VolumetricTextDepth; if (_geometryOptions.VerticesScaleFactor > 0f) { volumetricTextDepth = volumetricTextDepth / _geometryOptions.VerticesScaleFactor; } // AddObject all side surfaces foreach (var actPolygon in geometryExtruder.GeneratedPolygons) { foreach (var actLine in actPolygon.Lines) { tempSurface.BuildRect( new Vector3(actLine.StartPosition.X, -volumetricTextDepth, actLine.StartPosition.Y), new Vector3(actLine.EndPosition.X, -volumetricTextDepth, actLine.EndPosition.Y), new Vector3(actLine.EndPosition.X, 0f, actLine.EndPosition.Y), new Vector3(actLine.StartPosition.X, 0f, actLine.StartPosition.Y)) .SetVertexColor(_geometryOptions.VolumetricSideSurfaceVertexColor); } } } // Do also make back surface? if (_geometryOptions.MakeBackSurface) { for (var loop = 0; loop < triangleCountWithoutSide; loop++) { var triangle = tempSurface.Triangles[loop]; var vertex0 = tempGeometry.Vertices[triangle.Index1]; var vertex1 = tempGeometry.Vertices[triangle.Index2]; var vertex2 = tempGeometry.Vertices[triangle.Index3]; var changeVector = new Vector3(0f, -_geometryOptions.VolumetricTextDepth, 0f); tempSurface.AddTriangle( vertex2.Copy(vertex2.Position - changeVector, Vector3.Negate(vertex2.Normal)), vertex1.Copy(vertex1.Position - changeVector, Vector3.Negate(vertex1.Normal)), vertex0.Copy(vertex0.Position - changeVector, Vector3.Negate(vertex0.Normal))); } } // Toggle coordinate system becomes text input comes in opposite direction tempGeometry.ToggleCoordinateSystem(); // Scale the text using given scale factor if (_geometryOptions.VerticesScaleFactor > 0f) { var scaleMatrix = Matrix4x4.CreateScale( _geometryOptions.VerticesScaleFactor, _geometryOptions.VerticesScaleFactor, _geometryOptions.VerticesScaleFactor); var transformMatrix = new Matrix4Stack(scaleMatrix); transformMatrix.TransformLocal(_geometryOptions.VertexTransform); tempGeometry.UpdateVerticesUsingTranslation(actVector => Vector3.Transform(actVector, transformMatrix.Top)); } // Calculate all normals before adding to target geometry if (_geometryOptions.CalculateNormals) { tempGeometry.CalculateNormalsFlat(); } // Merge temporary geometry to target geometry _targetSurface.AddGeometry(tempGeometry); }
/// <summary> /// Initializes a new instance of the <see cref="SeeingSharpRendererControl"/> class. /// </summary> public SeeingSharpRendererControl() { //Set style parameters for this control base.SetStyle(ControlStyles.AllPaintingInWmPaint, true); base.SetStyle(ControlStyles.ResizeRedraw, true); base.SetStyle(ControlStyles.OptimizedDoubleBuffer, false); base.SetStyle(ControlStyles.Opaque, true); base.SetStyle(ControlStyles.Selectable, true); base.DoubleBuffered = false; //Create the render loop GraphicsCore.Touch(); m_renderLoop = new RenderLoop(SynchronizationContext.Current, this, this.DesignMode); m_renderLoop.ManipulateFilterList += OnRenderLoopManipulateFilterList; m_renderLoop.ClearColor = new Color4(this.BackColor); m_renderLoop.DiscardRendering = true; this.Disposed += (sender, eArgs) => { m_renderLoop.Dispose(); }; // Perform default initialization logic (if not called before) if (SeeingSharpApplication.IsInitialized) { m_renderLoop.SetScene(new Scene()); m_renderLoop.Camera = new PerspectiveCamera3D(); //Observe resize event and throttle them this.HandleCreateDisposeOnControl( () => Observable.FromEventPattern(this, "Resize") .Merge(Observable.FromEventPattern(m_renderLoop.ViewConfiguration, "ConfigurationChanged")) .Throttle(TimeSpan.FromSeconds(0.5)) .ObserveOn(SynchronizationContext.Current) .Subscribe((eArgs) => OnThrottledViewRecreation())); //Initialize background brush UpdateDrawingResourcesForFailoverRendering(); // Observe mouse click event this.HandleCreateDisposeOnControl(() => { var mouseDownEvent = Observable.FromEventPattern <MouseEventArgs>(this, "MouseDown"); var mouseUpEvent = Observable.FromEventPattern <MouseEventArgs>(this, "MouseUp"); var mouseClick = from down in mouseDownEvent let timeStampDown = DateTime.UtcNow from up in mouseUpEvent where up.EventArgs.Button == down.EventArgs.Button let timeStampUp = DateTime.UtcNow where timeStampUp - timeStampDown < TimeSpan.FromMilliseconds(200.0) select new { Down = down, Up = up }; return(mouseClick.Subscribe((givenItem) => { MouseClickEx.Raise(this, givenItem.Up.EventArgs); })); }); } this.Disposed += OnDisposed; UpdateDrawingResourcesForFailoverRendering(); }
public async Task MemoryRenderTarget_2DInitError() { await TestUtilities.InitializeWithGraphicsAsync(); // Ensure that any async disposal is done before we create a new GraphicsCore await GraphicsCore.Current.MainLoop !.WaitForNextPassedLoopAsync(); await GraphicsCore.Current.MainLoop !.WaitForNextPassedLoopAsync(); GDI.Bitmap?screenshot = null; using (TestUtilities.FailTestOnInternalExceptions()) using (GraphicsCore.AutomatedTest_NewTestEnvironment()) { await GraphicsCore.Loader .ConfigureLoading(settings => settings.ThrowD2DInitDeviceError = true) .LoadAsync(); Assert.IsTrue(GraphicsCore.IsLoaded); Assert.IsFalse(GraphicsCore.Current.DefaultDevice !.Supports2D); using (var solidBrush = new SolidBrushResource(Color4.Gray)) using (var textFormat = new TextFormatResource("Arial", 36)) using (var textBrush = new SolidBrushResource(Color4.RedColor)) using (var memRenderTarget = new MemoryRenderTarget(1024, 1024)) { memRenderTarget.ClearColor = Color4.CornflowerBlue; // Get and configure the camera var camera = (PerspectiveCamera3D)memRenderTarget.Camera; camera.Position = new Vector3(0f, 5f, -7f); camera.Target = new Vector3(0f, 0f, 0f); camera.UpdateCamera(); // 2D rendering is made here var d2dDrawingLayer = new Custom2DDrawingLayer(graphics => { var d2dRectangle = new GDI.RectangleF(10, 10, 236, 236); graphics.Clear(Color4.LightBlue); graphics.FillRoundedRectangle( d2dRectangle, 30, 30, solidBrush); d2dRectangle.Inflate(-10, -10); graphics.DrawText("Hello Direct2D!", textFormat, d2dRectangle, textBrush); }); // Define scene await memRenderTarget.Scene.ManipulateSceneAsync(manipulator => { var resD2DTexture = manipulator.AddResource( _ => new Direct2DTextureResource(d2dDrawingLayer, 256, 256)); var resD2DMaterial = manipulator.AddStandardMaterialResource(resD2DTexture); var resGeometry = manipulator.AddResource( _ => new GeometryResource(new CubeGeometryFactory())); var newMesh = manipulator.AddMeshObject(resGeometry, resD2DMaterial); newMesh.RotationEuler = new Vector3(0f, EngineMath.RAD_90DEG / 2f, 0f); newMesh.Scaling = new Vector3(2f, 2f, 2f); }); // Take screenshot await memRenderTarget.AwaitRenderAsync(); screenshot = await memRenderTarget.RenderLoop.GetScreenshotGdiAsync(); // TestUtilities.DumpToDesktop(screenshot, "Blub.png"); } } // Calculate and check difference Assert.IsNotNull(screenshot); var isNearEqual = BitmapComparison.IsNearEqual( screenshot, TestUtilities.LoadBitmapFromResource("ErrorHandling", "SimpleObject.png")); Assert.IsTrue(isNearEqual, "Difference to reference image is to big!"); }
/// <summary> /// Initializes a new instance of the <see cref="PolygonGeometryResource"/> class. /// </summary> public PolygonGeometryResource() { GraphicsCore.EnsureGraphicsSupportLoaded(); _d2dGeometry = GraphicsCore.Current.FactoryD2D !.CreatePathGeometry(); }
public async Task MemoryRenderTarget_2DInitError() { await UnitTestHelper.InitializeWithGrahicsAsync(); GDI.Bitmap screenshot = null; using (UnitTestHelper.FailTestOnInternalExceptions()) using (GraphicsCore.AutomatedTest_NewTestEnviornment()) using (GraphicsCore.AutomatedTest_ForceD2DInitError()) { GraphicsCore.Initialize(); Assert.True(GraphicsCore.IsInitialized); Assert.False(GraphicsCore.Current.DefaultDevice.Supports2D); using (SolidBrushResource solidBrush = new SolidBrushResource(Color4.Gray)) using (TextFormatResource textFormat = new TextFormatResource("Arial", 36)) using (SolidBrushResource textBrush = new SolidBrushResource(Color4.RedColor)) using (MemoryRenderTarget memRenderTarget = new MemoryRenderTarget(1024, 1024)) { memRenderTarget.ClearColor = Color4.CornflowerBlue; // Get and configure the camera PerspectiveCamera3D camera = memRenderTarget.Camera as PerspectiveCamera3D; camera.Position = new Vector3(0f, 5f, -7f); camera.Target = new Vector3(0f, 0f, 0f); camera.UpdateCamera(); // 2D rendering is made here Custom2DDrawingLayer d2dDrawingLayer = new Custom2DDrawingLayer((graphics) => { RectangleF d2dRectangle = new RectangleF(10, 10, 236, 236); graphics.Clear(Color4.LightBlue); graphics.FillRoundedRectangle( d2dRectangle, 30, 30, solidBrush); d2dRectangle.Inflate(-10, -10); graphics.DrawText("Hello Direct2D!", textFormat, d2dRectangle, textBrush); }); // Define scene await memRenderTarget.Scene.ManipulateSceneAsync((manipulator) => { var resD2DTexture = manipulator.AddResource <Direct2DTextureResource>( () => new Direct2DTextureResource(d2dDrawingLayer, 256, 256)); var resD2DMaterial = manipulator.AddSimpleColoredMaterial(resD2DTexture); var geoResource = manipulator.AddResource <GeometryResource>( () => new GeometryResource(new PalletType( palletMaterial: NamedOrGenericKey.Empty, contentMaterial: resD2DMaterial))); GenericObject newObject = manipulator.AddGeneric(geoResource); newObject.RotationEuler = new Vector3(0f, EngineMath.RAD_90DEG / 2f, 0f); newObject.Scaling = new Vector3(2f, 2f, 2f); }); // Take screenshot await memRenderTarget.AwaitRenderAsync(); screenshot = await memRenderTarget.RenderLoop.GetScreenshotGdiAsync(); //screenshot.DumpToDesktop("Blub.png"); } } // Calculate and check difference Assert.NotNull(screenshot); bool isNearEqual = BitmapComparison.IsNearEqual( screenshot, Properties.Resources.ReferenceImage_SimpleObject); Assert.True(isNearEqual, "Difference to reference image is to big!"); }