/// <summary> /// Renders the specified graph path</summary> /// <param name="graphPath">The graph path</param> /// <param name="renderState">The render state</param> /// <param name="action">The render action</param> /// <param name="camera">The camera</param> protected override void Render(SceneNode[] graphPath, RenderState renderState, IRenderAction action, Camera camera) { // apply xform Gl.glPushMatrix(); Util3D.glMultMatrixf(action.TopMatrix); if (m_displayListId == 0) { RenderStats globalStats = Util3D.RenderStats; RenderStats ourStats = new RenderStats(); Util3D.RenderStats = ourStats; m_displayListId = Gl.glGenLists(1); #if MEMORY_DEBUG lock (s_lock) NumDisplayListIds++; #endif Gl.glNewList(m_displayListId, Gl.GL_COMPILE); Render(action); Gl.glEndList(); m_numPrimitives = ourStats.PrimCount; m_numVertices = ourStats.VertexCount; Util3D.RenderStats = globalStats; } Gl.glCallList(m_displayListId); Gl.glPopMatrix(); Util3D.RenderStats.PrimCount += m_numPrimitives; Util3D.RenderStats.VertexCount += m_numVertices; }
void IGraphicsBackend.EndRendering() { this.currentDevice = null; this.renderOptions = null; this.renderStats = null; DebugCheckOpenGLErrors(); }
private void rt_addRootScene(string filename) { //Once the new scene has been loaded, //Initialize Palettes Palettes.set_palleteColors(); //Clear Systems actionSys.CleanUp(); animationSys.CleanUp(); //Clear Resources resMgr.Cleanup(); resMgr.Init(); RenderState.activeResMgr = resMgr; ModelProcGen.procDecisions.Clear(); RenderState.rootObject = null; RenderState.activeModel = null; //Clear Gizmos RenderState.activeGizmo = null; //Clear RenderStats RenderStats.ClearStats(); //Stop animation if on bool animToggleStatus = RenderState.renderSettings.ToggleAnimations; RenderState.renderSettings.ToggleAnimations = false; //Setup new object Model root = GEOMMBIN.LoadObjects(filename); //Explicitly add default light to the rootObject root.children.Add(resMgr.GLlights[0]); root.updateLODDistances(); root.update(); //Refresh all transforms root.setupSkinMatrixArrays(); //Populate RenderManager renderMgr.populate(root); //Clear Instances renderMgr.clearInstances(); root.updateMeshInfo(); //Update all mesh info root.selected = 1; RenderState.rootObject = root; //RenderState.activeModel = root; //Set the new scene as the new activeModel //Reinitialize gizmos RenderState.activeGizmo = new TranslationGizmo(); //Restart anim worker if it was active RenderState.renderSettings.ToggleAnimations = animToggleStatus; }
void IGraphicsBackend.EndRendering() { GL.BindBuffer(WebGLRenderingContextBase.ARRAY_BUFFER, null); this.currentDevice = null; this.renderOptions = null; this.renderStats = null; DebugCheckOpenGLErrors(); }
void IGraphicsBackend.EndRendering() { GL.BindBuffer(BufferTarget.ArrayBuffer, 0); this.currentDevice = null; this.renderOptions = null; this.renderStats = null; DebugCheckOpenGLErrors(); }
/// <summary> /// Debug GUI constructor /// </summary> public DebugGUI(IServiceProvider services) : base(services) { #if XNA content = new ResourceContentManager(services, MeteorContentResource.ResourceManager); #elif MONOGAME content = new ContentManager(services, "MeteorEngine.Content"); #endif // Set statistic resources renderStats = new RenderStats(); debugString = new StringBuilder(64, 64); }
/// <summary> /// Constructor without a default scene /// </summary> public Core(IServiceProvider services) : base(services) { content = new ContentManager(services, "MeteorEngine.Content"); resxContent = new ResourceContentManager(services, MeteorContentResource.ResourceManager); renderStats = new RenderStats(); currentRenderProfile = null; renderProfiles = new List <RenderProfile>(); debugString = new StringBuilder(64, 64); // Setup rendering components cameras = new List <Camera>(); scenes = new List <Scene>(); }
public void Render(ClearFlag clearFlags, ColorRgba clearColor, float clearDepth) { if (DualityApp.GraphicsBackend == null) { return; } // Process drawcalls this.OptimizeBatches(); RenderOptions options = new RenderOptions { ClearFlags = clearFlags, ClearColor = clearColor, ClearDepth = clearDepth, Viewport = this.viewportRect, RenderMode = this.renderMode, ModelViewMatrix = this.matModelView, ProjectionMatrix = this.matProjection, Target = this.renderTarget.IsAvailable ? this.renderTarget.Res.Native : null }; RenderStats stats = new RenderStats(); DualityApp.GraphicsBackend.BeginRendering(this, options, stats); { if (this.pickingIndex == 0) { Profile.TimeProcessDrawcalls.BeginMeasure(); } // Z-Independent: Sorted as needed by batch optimizer DualityApp.GraphicsBackend.Render(this.drawBuffer); // Z-Sorted: Back to Front DualityApp.GraphicsBackend.Render(this.drawBufferZSort); if (this.pickingIndex == 0) { Profile.TimeProcessDrawcalls.EndMeasure(); } } Profile.StatNumDrawcalls.Add(stats.DrawCalls); DualityApp.GraphicsBackend.EndRendering(); this.drawBuffer.Clear(); this.drawBufferZSort.Clear(); }
void UpdatePostRenderReport(RenderStats stats) { StringBuilder builder = new(); int total = listener.ActiveSources.Count; int dynamic = total - stats.GetSemiStaticCount() - stats.GetSuperStaticCount(); List <ReferenceChannel> channels = stats.GetStaticOrSemiStaticPositions().Select(x => { Vector3 scaled = x / Listener.EnvironmentSize; for (int i = 0; i < Renderer.channelPositions.Length; ++i) { if (scaled == Renderer.channelPositions[i]) { return((ReferenceChannel)i); } } return(ReferenceChannel.Unknown); }).ToList(); bool hasLFE = listener.ActiveSources.Any(source => source.LFE); if (hasLFE) { channels.Add(ReferenceChannel.ScreenLFE); } channels.Sort(); int unused = total - dynamic - channels.Count; if (unused < 0) { if (hasLFE) { channels.Remove(ReferenceChannel.FrontCenter); } unused = 0; } builder.Append("Actually present bed channels: ").Append(channels.Count); if (channels.Count != 0) { builder.Append(" (").Append(string.Join(", ", channels)).Append(')'); } builder.AppendLine().Append("Actually present dynamic objects: ").AppendLine(dynamic.ToString()) .Append("Unused (fake) rendering targets: ").AppendLine(unused.ToString()); report.Dispatcher.Invoke(() => report.Text = builder.ToString()); }
/// <summary> /// Constructor without a default scene /// </summary> public Core(GameServiceContainer services) : base(services) { #if XNA content = new ResourceContentManager(services, MeteorContentResource.ResourceManager); #elif MONOGAME content = new ContentManager(services, "MeteorEngine.Content"); #endif renderStats = new RenderStats(); currentRenderProfile = null; renderProfiles = new List <RenderProfile>(); debugString = new StringBuilder(64, 64); // Setup rendering components cameras = new List <Camera>(); scenes = new Dictionary <String, Scene>(); }
public void Dispose() { if (this.disposed) { return; } this.disposed = true; // Set big object references to null to make // sure they're garbage collected even when keeping // a reference to the disposed DrawDevice around. this.renderOptions = null; this.renderStats = null; this.tempMaterialPool = null; this.drawVertices = null; this.drawBuffer = null; this.sortBufferSolid = null; this.sortBufferBlended = null; this.sortBufferTemp = null; this.batchBufferSolid = null; this.batchBufferBlended = null; this.batchIndexPool = null; }
private void Dispose(bool manually) { if (!this.disposed) { // Release Resources this.disposed = true; // Set big object references to null to make // sure they're garbage collected even when keeping // a reference to the disposed DrawDevice around. this.renderOptions = null; this.renderStats = null; this.tempMaterialPool = null; this.drawVertices = null; this.drawBuffer = null; this.sortBufferSolid = null; this.sortBufferBlended = null; this.sortBufferTemp = null; this.batchBufferSolid = null; this.batchBufferBlended = null; this.drawVertices = null; this.batchIndexPool = null; } }
public static void Run <TGame>(GameInfo info, string[] args) where TGame : IGame, new() { bool sdlInitialised = false; bool sdlImageInitialised = false; bool steamworksInitialised = false; try { // Store info Info = info; // Get commandline arguments Arguments = new ProgramArguments(args); // Determine platform string platformString = SDL.SDL_GetPlatform(); switch (platformString) { case "Windows": { Platform = Platform.Windows; break; } case "Mac OS X": { Platform = Platform.OSX; break; } case "Linux": { Platform = Platform.Linux; break; } default: { Platform = Platform.Unknown; break; } } // Print App Info if (App.Debug && App.Steam) { Log("{0} {1} (Steam Debug build)", Info.Title, Info.Version); } else if (App.Debug) { Log("{0} {1} (Debug build)", Info.Title, Info.Version); } else if (App.Steam) { Log("{0} {1} (Steam build)", Info.Title, Info.Version); } else { Log("{0} {1}", Info.Title, Info.Version); } if (!Arguments.IsEmpty) { Log("Command Line Arguments: {0}", Arguments); } Log("Developed by {0} ({1})", Info.DeveloperName, Info.DeveloperEmail); Log("Platform: {0} ({1})", Platform, platformString); // Setup Steamworks if (App.Steam) { // Relaunch game under Steam if launched externally if (!App.Debug) { if (File.Exists("steam_appid.txt")) { File.Delete("steam_appid.txt"); } AppId_t appID = (Info.SteamAppID > 0) ? new AppId_t(Info.SteamAppID) : AppId_t.Invalid; if (SteamAPI.RestartAppIfNecessary(appID)) { Log("Relaunching game in Steam"); return; } } // Initialise Steamworks if (!SteamAPI.Init()) { throw new SteamworksException("SteamAPI_Init", "If you have just installed " + App.Info.Title + " for the first time, try restarting Steam"); } Log("Steamworks initialised"); steamworksInitialised = true; } // Print SDL version SDL.SDL_version version; SDL.SDL_GetVersion(out version); Log("SDL version: {0}.{1}.{2}", version.major, version.minor, version.patch); // Setup SDL SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "1"); SDL.SDL_SetHint(SDL.SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, "1"); CheckSDLResult("SDL_Init", SDL.SDL_Init( SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO | SDL.SDL_INIT_GAMECONTROLLER | SDL.SDL_INIT_JOYSTICK | SDL.SDL_INIT_HAPTIC )); Log("SDL2 Initialised"); sdlInitialised = true; CheckSDLResult("IMG_Init", SDL_image.IMG_Init( SDL_image.IMG_InitFlags.IMG_INIT_PNG )); sdlImageInitialised = true; Log("SDL2_Image initialised"); // Determine save path InitSavePath(); StartLogging(); // Determine asset directory if (App.Debug) { AssetPath = "../../assets"; } else { if (App.Platform == Platform.OSX) { AssetPath = "assets"; } else { string basePath = SDL.SDL_GetBasePath(); AssetPath = Path.Combine(basePath, "assets"); } } if (!Directory.Exists(AssetPath)) { throw new IOException ( "Could not locate assets directory (" + AssetPath + ")" + Environment.NewLine + "This must be provided from a legal copy of " + App.Info.Title + ". Visit " + App.Info.Website + " for more info." ); } // Register asset types RegisterAssetTypes(); // Load controller database var gameControllerDBPath = Path.Combine(AssetPath, "gamecontrollerdb.txt"); if (File.Exists(gameControllerDBPath)) { try { CheckSDLResult("SDL_GameControllerAddMappingsFromFile", SDL.SDL_GameControllerAddMappingsFromFile(gameControllerDBPath)); App.Log("Loaded gamepad mappings from gamecontrollerdb.txt"); } catch (SDLException) { App.Log("Error: Failed to load gamepad mappings from gamecontrollerdb.txt"); } } else { App.Log("Error: gamecontrollerdb.txt not found"); } // Create game using (var game = new Game.Game.Game()) { App.CheckOpenGLError(); // Main loop uint lastFrameStart = SDL.SDL_GetTicks(); while (!game.Over) { // Get time uint frameStart = SDL.SDL_GetTicks(); uint delta = frameStart - lastFrameStart; FPS = 0.8f * FPS + 0.2f * ((delta > 0) ? (1000.0f / (float)delta) : 1000.0f); float dt = Math.Max((float)delta / 1000.0f, 0.0f); // Handle SDL events SDL.SDL_Event e; while (!game.Over && SDL.SDL_PollEvent(out e) != 0) { // Pass event to game game.HandleEvent(ref e); } // Handle Steamworks events if (!game.Over && App.Steam) { SteamAPI.RunCallbacks(); } // Update game if (!game.Over) { game.Update(dt); } // Render game if (!game.Over) { game.Render(); App.CheckOpenGLError(); RenderStats.EndFrame(); } // Sleep if necessary if (!game.Over) { uint minFrameTime = 1000 / MAX_FPS; uint frameTime = (SDL.SDL_GetTicks() - frameStart); if (frameTime < minFrameTime) { // SDL.SDL_Delay(minFrameTime - frameTime); } } // Update timer for next frame lastFrameStart = frameStart; } } } #if !DEBUG catch (Exception e) { // Log error to console string message = string.Format("Game crashed with {0}: {1}", e.GetType().FullName, e.Message); Log(message); Log(e.StackTrace); while ((e = e.InnerException) != null) { Log("Caused by {0}: {1}", e.GetType().FullName, e.Message); Log(e.StackTrace); } // Open an emergency log file if necessary if (LogFile == null) { try { LogFilePath = "log.txt"; Log("Logging to " + LogFilePath); LogFile = new StreamWriter("log.txt"); for (int i = 0; i < EarlyLogText.Count; ++i) { LogFile.WriteLine(EarlyLogText[i]); } EarlyLogText.Clear(); LogFile.Flush(); } catch (IOException) { Log("Failed to open log file"); LogFilePath = null; } } // Pop up the message box //if( sdlInitialised ) // The docs say SDL doesn't need to be inited to call ShowSimpleMessageBox { try { if (LogFilePath != null) { message += Environment.NewLine; message += Environment.NewLine; message += "Callstack written to " + LogFilePath; } CheckSDLResult("SDL_ShowSimpleMessageBox", SDL.SDL_ShowSimpleMessageBox( SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_ERROR, Info.Title + " " + Info.Version, message, IntPtr.Zero )); } catch (SDLException e2) { Log(e2.Message); } } } #endif finally { // Shutdown SDL if (sdlImageInitialised) { SDL_image.IMG_Quit(); Log("SDL2_Image shut down"); } if (sdlInitialised) { SDL.SDL_Quit(); Log("SDL2 shut down"); } // Shutdown Steamworks if (steamworksInitialised) { SteamAPI.Shutdown(); Log("Steamworks shut down"); } // Close the log file if (LogFile != null) { Log("Closing log file"); LogFile.Dispose(); LogFile = null; Log("Log file closed"); } // Quit Log("Quitting"); } }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { DebugCheckOpenGLErrors(); this.CheckContextCaps(); this.currentDevice = device; this.renderStats = stats; // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); // Determine whether masked blending should use alpha-to-coverage mode if (this.msaaIsDriverDisabled) { this.useAlphaToCoverageBlend = false; } else if (NativeRenderTarget.BoundRT != null) { this.useAlphaToCoverageBlend = NativeRenderTarget.BoundRT.Samples > 0; } else if (this.activeWindow != null) { this.useAlphaToCoverageBlend = this.activeWindow.IsMultisampled; } else { this.useAlphaToCoverageBlend = this.defaultGraphicsMode.Samples > 0; } if (this.primaryVBO == 0) { GL.GenBuffers(1, out this.primaryVBO); } GL.BindBuffer(BufferTarget.ArrayBuffer, this.primaryVBO); // Setup viewport Rect viewportRect = options.Viewport; GL.Viewport((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); GL.Scissor((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth((double)options.ClearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } OpenTK.Matrix4 openTkModelView; Matrix4 modelView = options.ModelViewMatrix; GetOpenTKMatrix(ref modelView, out openTkModelView); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref openTkModelView); OpenTK.Matrix4 openTkProjection; Matrix4 projection = options.ProjectionMatrix; GetOpenTKMatrix(ref projection, out openTkProjection); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref openTkProjection); if (NativeRenderTarget.BoundRT != null) { if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, viewportRect.H * 0.5f, 0.0f); } GL.Scale(1.0f, -1.0f, 1.0f); if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, -viewportRect.H * 0.5f, 0.0f); } } }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { this.currentDevice = device; this.renderStats = stats; // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); if (this.primaryVBO == 0) { GL.GenBuffers(1, out this.primaryVBO); } GL.BindBuffer(BufferTarget.ArrayBuffer, this.primaryVBO); // Setup viewport Rect viewportRect = options.Viewport; GL.Viewport((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); GL.Scissor((int)viewportRect.X, (int)viewportRect.Y, (int)viewportRect.W, (int)viewportRect.H); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth((double)options.ClearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } OpenTK.Matrix4 openTkModelView; Matrix4 modelView = options.ModelViewMatrix; GetOpenTKMatrix(ref modelView, out openTkModelView); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref openTkModelView); OpenTK.Matrix4 openTkProjection; Matrix4 projection = options.ProjectionMatrix; GetOpenTKMatrix(ref projection, out openTkProjection); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref openTkProjection); if (NativeRenderTarget.BoundRT != null) { if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, NativeRenderTarget.BoundRT.Height * 0.5f, 0.0f); } GL.Scale(1.0f, -1.0f, 1.0f); if (options.RenderMode == RenderMatrix.OrthoScreen) { GL.Translate(0.0f, -NativeRenderTarget.BoundRT.Height * 0.5f, 0.0f); } } }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { DebugCheckOpenGLErrors(); this.currentDevice = device; this.renderOptions = options; this.renderStats = stats; // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); // Determine the available size on the active rendering surface //Point2 availableSize; //if (NativeRenderTarget.BoundRT != null) { // availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height); //} else { // availableSize = this.externalBackbufferSize; //} Rect openGLViewport = options.Viewport; // Setup viewport and scissor rects GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth(options.ClearDepth); GL.Clear(glClearMask); // Configure Rendering params GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); if (options.DepthTest) { GL.DepthFunc(DepthFunction.Lequal); } else { GL.DepthFunc(DepthFunction.Always); } Matrix4 view = options.ViewMatrix; Matrix4 projection = options.ProjectionMatrix; if (NativeRenderTarget.BoundRT != null) { Matrix4 flipOutput = Matrix4.CreateScale(1.0f, -1.0f, 1.0f); projection = projection * flipOutput; } // Convert matrices to float arrays GetArrayMatrix(ref view, viewData); GetArrayMatrix(ref projection, projectionData); // All EBOs can be used again lastUsedEBO = 0; }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { }
private void rt_SpecularTestScene() { //Once the new scene has been loaded, //Initialize Palettes Palettes.set_palleteColors(); //Clear Systems actionSys.CleanUp(); animationSys.CleanUp(); //Clear Resources resMgr.Cleanup(); resMgr.Init(); RenderState.activeResMgr = resMgr; ModelProcGen.procDecisions.Clear(); RenderState.rootObject = null; RenderState.activeModel = null; //Clear Gizmos RenderState.activeGizmo = null; //Clear RenderStats RenderStats.ClearStats(); //Stop animation if on bool animToggleStatus = RenderState.renderSettings.ToggleAnimations; RenderState.renderSettings.ToggleAnimations = false; //Setup new object Scene scene = new Scene(); scene.name = "DEFAULT SCENE"; //ADd Lights Light l = new Light(); l.Name = "Light 1"; l.localPosition = new Vector3(0.2f, 0.2f, -2.0f); l.Color = new MVector4(1.0f, 1.0f, 1.0f, 1.0f); l.Intensity = 100.0f; l.falloff = ATTENUATION_TYPE.QUADRATIC; Common.RenderState.activeResMgr.GLlights.Add(l); scene.children.Add(l); Light l1 = new Light(); l1.Name = "Light 2"; l1.localPosition = new Vector3(0.2f, -0.2f, -2.0f); l1.Color = new MVector4(1.0f, 1.0f, 1.0f, 1.0f); l1.Intensity = 100.0f; l1.falloff = ATTENUATION_TYPE.QUADRATIC; Common.RenderState.activeResMgr.GLlights.Add(l1); scene.children.Add(l1); Light l2 = new Light(); l2.Name = "Light 3"; l2.localPosition = new Vector3(-0.2f, 0.2f, -2.0f); l2.Color = new MVector4(1.0f, 1.0f, 1.0f, 1.0f); Common.RenderState.activeResMgr.GLlights.Add(l2); l2.Intensity = 100.0f; l2.falloff = ATTENUATION_TYPE.QUADRATIC; scene.children.Add(l2); Light l3 = new Light(); l3.Name = "Light 4"; l3.localPosition = new Vector3(-0.2f, -0.2f, -2.0f); l3.Color = new MVector4(1.0f, 1.0f, 1.0f, 1.0f); Common.RenderState.activeResMgr.GLlights.Add(l3); l3.Intensity = 100.0f; l3.falloff = ATTENUATION_TYPE.QUADRATIC; scene.children.Add(l3); //Generate a Sphere and center it in the scene Model sphere = new Mesh(); sphere.Name = "Test Sphere"; sphere.parent = scene; sphere.setParentScene(scene); MeshMetaData sphere_metadata = new MeshMetaData(); int bands = 80; sphere_metadata.batchcount = bands * bands * 6; sphere_metadata.batchstart_graphics = 0; sphere_metadata.vertrstart_graphics = 0; sphere_metadata.vertrend_graphics = (bands + 1) * (bands + 1) - 1; sphere_metadata.indicesLength = DrawElementsType.UnsignedInt; sphere.meshVao = new GLMeshVao(sphere_metadata); sphere.meshVao.type = TYPES.MESH; sphere.meshVao.vao = (new GMDL.Primitives.Sphere(new Vector3(), 2.0f, 40)).getVAO(); //Sphere Material Material mat = new Material(); mat.Name = "default_scn"; Uniform uf = new Uniform(); uf.Name = "gMaterialColourVec4"; uf.Values = new libMBIN.NMS.Vector4f(); uf.Values.x = 1.0f; uf.Values.y = 0.0f; uf.Values.z = 0.0f; uf.Values.t = 1.0f; mat.Uniforms.Add(uf); uf = new Uniform(); uf.Name = "gMaterialParamsVec4"; uf.Values = new libMBIN.NMS.Vector4f(); uf.Values.x = 0.15f; //Roughness uf.Values.y = 0.0f; uf.Values.z = 0.2f; //Metallic uf.Values.t = 0.0f; mat.Uniforms.Add(uf); mat.init(); resMgr.GLmaterials["test_mat1"] = mat; sphere.meshVao.material = mat; sphere.instanceId = GLMeshBufferManager.addInstance(ref sphere.meshVao, sphere); //Add instance scene.children.Add(sphere); //Explicitly add default light to the rootObject scene.children.Add(resMgr.GLlights[0]); scene.updateLODDistances(); scene.update(); //Refresh all transforms scene.setupSkinMatrixArrays(); //Save scene path to resourcemanager RenderState.activeResMgr.GLScenes["TEST_SCENE_1"] = scene; //Use input path //Populate RenderManager renderMgr.populate(scene); //Clear Instances renderMgr.clearInstances(); scene.updateMeshInfo(); //Update all mesh info scene.selected = 1; RenderState.rootObject = scene; //RenderState.activeModel = root; //Set the new scene as the new activeModel //Reinitialize gizmos RenderState.activeGizmo = new TranslationGizmo(); //Restart anim worker if it was active RenderState.renderSettings.ToggleAnimations = animToggleStatus; }
void IGraphicsBackend.BeginRendering(IDrawDevice device, VertexBatchStore vertexData, RenderOptions options, RenderStats stats) { DebugCheckOpenGLErrors(); // ToDo: AA is disabled for now //this.CheckContextCaps(); this.currentDevice = device; this.renderOptions = options; this.renderStats = stats; // Upload all vertex data that we'll need during rendering if (vertexData != null) { this.perVertexTypeVBO.Count = Math.Max(this.perVertexTypeVBO.Count, vertexData.Batches.Count); for (int typeIndex = 0; typeIndex < vertexData.Batches.Count; typeIndex++) { // Filter out unused vertex types IVertexBatch vertexBatch = vertexData.Batches[typeIndex]; if (vertexBatch == null) { continue; } if (vertexBatch.Count == 0) { continue; } // Generate a VBO for this vertex type if it didn't exist yet if (this.perVertexTypeVBO[typeIndex] == 0) { GL.GenBuffers(1, out this.perVertexTypeVBO.Data[typeIndex]); } GL.BindBuffer(BufferTarget.ArrayBuffer, this.perVertexTypeVBO[typeIndex]); // Upload all data of this vertex type as a single block int vertexDataLength = vertexBatch.Declaration.Size * vertexBatch.Count; using (PinnedArrayHandle pinned = vertexBatch.Lock()) { GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, IntPtr.Zero, BufferUsage.StreamDraw); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, pinned.Address, BufferUsage.StreamDraw); } } } GL.BindBuffer(BufferTarget.ArrayBuffer, 0); // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); // Determine the available size on the active rendering surface //Point2 availableSize; //if (NativeRenderTarget.BoundRT != null) { // availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height); //} else { // availableSize = this.externalBackbufferSize; //} Rect openGLViewport = options.Viewport; // Setup viewport and scissor rects GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth(options.ClearDepth); GL.Clear(glClearMask); // Configure Rendering params if (options.RenderMode == RenderMatrix.ScreenSpace) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } Matrix4 modelView = options.ModelViewMatrix; Matrix4 projection = options.ProjectionMatrix; if (NativeRenderTarget.BoundRT != null) { modelView = Matrix4.CreateScale(new Vector3(1f, -1f, 1f)) * modelView; if (options.RenderMode == RenderMatrix.ScreenSpace) { modelView = Matrix4.CreateTranslation(new Vector3(0f, -device.TargetSize.Y, 0f)) * modelView; } } // Convert matrices to float arrays GetArrayMatrix(ref modelView, ref modelViewData); GetArrayMatrix(ref projection, ref projectionData); // All EBOs can be used again lastUsedEBO = 0; }
void IGraphicsBackend.BeginRendering(IDrawDevice device, VertexBatchStore vertexData, RenderOptions options, RenderStats stats) { }
void IGraphicsBackend.BeginRendering(IDrawDevice device, RenderOptions options, RenderStats stats) { DebugCheckOpenGLErrors(); this.CheckContextCaps(); this.currentDevice = device; this.renderOptions = options; this.renderStats = stats; // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); // Determine whether masked blending should use alpha-to-coverage mode if (this.msaaIsDriverDisabled) { this.useAlphaToCoverageBlend = false; } else if (NativeRenderTarget.BoundRT != null) { this.useAlphaToCoverageBlend = NativeRenderTarget.BoundRT.Samples > 0; } else if (this.activeWindow != null) { this.useAlphaToCoverageBlend = this.activeWindow.IsMultisampled; } else { this.useAlphaToCoverageBlend = this.defaultGraphicsMode.Samples > 0; } // Determine the available size on the active rendering surface Point2 availableSize; if (NativeRenderTarget.BoundRT != null) { availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height); } else if (this.activeWindow != null) { availableSize = new Point2(this.activeWindow.Width, this.activeWindow.Height); } else { availableSize = this.externalBackbufferSize; } // Translate viewport coordinates to OpenGL screen coordinates (bottom-left, rising), unless rendering // to a texture, which is laid out Duality-like (top-left, descending) Rect openGLViewport = options.Viewport; if (NativeRenderTarget.BoundRT == null) { openGLViewport.Y = (availableSize.Y - openGLViewport.H) - openGLViewport.Y; } // Setup viewport and scissor rects GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth((double)options.ClearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); if (options.DepthTest) { GL.DepthFunc(DepthFunction.Lequal); } else { GL.DepthFunc(DepthFunction.Always); } OpenTK.Matrix4 openTkView; Matrix4 view = options.ViewMatrix; GetOpenTKMatrix(ref view, out openTkView); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref openTkView); Matrix4 projectionMatrix = options.ProjectionMatrix; if (NativeRenderTarget.BoundRT != null) { Matrix4 flipOutput = Matrix4.CreateScale(1.0f, -1.0f, 1.0f); projectionMatrix = projectionMatrix * flipOutput; } OpenTK.Matrix4 openTkProjection; Matrix4 projection = projectionMatrix; GetOpenTKMatrix(ref projection, out openTkProjection); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref openTkProjection); }
void IGraphicsBackend.BeginRendering(IDrawDevice device, VertexBatchStore vertexData, RenderOptions options, RenderStats stats) { DebugCheckOpenGLErrors(); this.CheckContextCaps(); this.currentDevice = device; this.renderOptions = options; this.renderStats = stats; // Upload all vertex data that we'll need during rendering if (vertexData != null) { this.perVertexTypeVBO.Count = Math.Max(this.perVertexTypeVBO.Count, vertexData.Batches.Count); for (int typeIndex = 0; typeIndex < vertexData.Batches.Count; typeIndex++) { // Filter out unused vertex types IVertexBatch vertexBatch = vertexData.Batches[typeIndex]; if (vertexBatch == null) { continue; } if (vertexBatch.Count == 0) { continue; } // Generate a VBO for this vertex type if it didn't exist yet if (this.perVertexTypeVBO[typeIndex] == 0) { GL.GenBuffers(1, out this.perVertexTypeVBO.Data[typeIndex]); } GL.BindBuffer(BufferTarget.ArrayBuffer, this.perVertexTypeVBO[typeIndex]); // Upload all data of this vertex type as a single block int vertexDataLength = vertexBatch.Declaration.Size * vertexBatch.Count; using (PinnedArrayHandle pinned = vertexBatch.Lock()) { GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, IntPtr.Zero, BufferUsageHint.StreamDraw); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)vertexDataLength, pinned.Address, BufferUsageHint.StreamDraw); } } } GL.BindBuffer(BufferTarget.ArrayBuffer, 0); // Prepare the target surface for rendering NativeRenderTarget.Bind(options.Target as NativeRenderTarget); // Determine whether masked blending should use alpha-to-coverage mode if (this.msaaIsDriverDisabled) { this.useAlphaToCoverageBlend = false; } else if (NativeRenderTarget.BoundRT != null) { this.useAlphaToCoverageBlend = NativeRenderTarget.BoundRT.Samples > 0; } else if (this.activeWindow != null) { this.useAlphaToCoverageBlend = this.activeWindow.IsMultisampled; } else { this.useAlphaToCoverageBlend = this.defaultGraphicsMode.Samples > 0; } // Determine the available size on the active rendering surface Point2 availableSize; if (NativeRenderTarget.BoundRT != null) { availableSize = new Point2(NativeRenderTarget.BoundRT.Width, NativeRenderTarget.BoundRT.Height); } else if (this.activeWindow != null) { availableSize = new Point2(this.activeWindow.Width, this.activeWindow.Height); } else { availableSize = this.externalBackbufferSize; } // Translate viewport coordinates to OpenGL screen coordinates (bottom-left, rising), unless rendering // to a texture, which is laid out Duality-like (top-left, descending) Rect openGLViewport = options.Viewport; if (NativeRenderTarget.BoundRT == null) { openGLViewport.Y = (availableSize.Y - openGLViewport.H) - openGLViewport.Y; } // Setup viewport and scissor rects GL.Viewport((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); GL.Scissor((int)openGLViewport.X, (int)openGLViewport.Y, (int)MathF.Ceiling(openGLViewport.W), (int)MathF.Ceiling(openGLViewport.H)); // Clear buffers ClearBufferMask glClearMask = 0; ColorRgba clearColor = options.ClearColor; if ((options.ClearFlags & ClearFlag.Color) != ClearFlag.None) { glClearMask |= ClearBufferMask.ColorBufferBit; } if ((options.ClearFlags & ClearFlag.Depth) != ClearFlag.None) { glClearMask |= ClearBufferMask.DepthBufferBit; } GL.ClearColor(clearColor.R / 255.0f, clearColor.G / 255.0f, clearColor.B / 255.0f, clearColor.A / 255.0f); GL.ClearDepth((double)options.ClearDepth); // The "float version" is from OpenGL 4.1.. GL.Clear(glClearMask); // Configure Rendering params if (options.RenderMode == RenderMatrix.ScreenSpace) { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Always); } else { GL.Enable(EnableCap.ScissorTest); GL.Enable(EnableCap.DepthTest); GL.DepthFunc(DepthFunction.Lequal); } OpenTK.Matrix4 openTkModelView; Matrix4 modelView = options.ModelViewMatrix; GetOpenTKMatrix(ref modelView, out openTkModelView); GL.MatrixMode(MatrixMode.Modelview); GL.LoadMatrix(ref openTkModelView); OpenTK.Matrix4 openTkProjection; Matrix4 projection = options.ProjectionMatrix; GetOpenTKMatrix(ref projection, out openTkProjection); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref openTkProjection); if (NativeRenderTarget.BoundRT != null) { GL.Scale(1.0f, -1.0f, 1.0f); if (options.RenderMode == RenderMatrix.ScreenSpace) { GL.Translate(0.0f, -device.TargetSize.Y, 0.0f); } } }