public static void LoadFromXml(this RenderPath command, XElement element, LoadContext lc) { if (element.Attribute("thickness") != null) { command.Thickness = double.Parse(element.Attribute("thickness").Value); } string start; if (element.GetAttribute("start", lc, out start)) { command.Start = new ComponentPoint(start); } var fill = element.Attribute("fill"); if (fill != null && fill.Value.ToLowerInvariant() != "false") { command.Fill = true; } string data; if (element.GetAttribute("data", lc, out data)) { command.Commands = PathHelper.ParseCommands(data); } }
public IEnumerable <Conditional <IRenderCommand> > Flatten(FlattenContext context) { var commands = Commands.Select(x => { if (context.AutoRotate.Mirror) { x = x.Reflect(); } if ((context.AutoRotate.FlipType & Circuit.FlipType.Horizontal) == Circuit.FlipType.Horizontal) { x = x.Flip(true); } if ((context.AutoRotate.FlipType & Circuit.FlipType.Vertical) == Circuit.FlipType.Vertical) { x = x.Flip(false); } return(x); }).ToList(); foreach (var start in Start.Flatten(context)) { var command = new RenderPath( start.Value, Thickness, Fill, commands); yield return(new Conditional <IRenderCommand>(command, start.Conditions)); } }
protected virtual bool ReadPathCommand(XElement element, out RenderPath command) { command = new RenderPath(); if (element.Attribute("thickness") != null) { command.Thickness = double.Parse(element.Attribute("thickness").Value); } if (!componentPointParser.TryParse(element.Attribute("start"), out var start)) { return(false); } command.Start = start; var fill = element.Attribute("fill"); if (fill != null && fill.Value.ToLowerInvariant() != "false") { command.Fill = true; } if (element.GetAttributeValue("data", logger, out var data)) { command.Commands = PathHelper.ParseCommands(data); } return(true); }
private static void SpecifyRenderingMatrix(Camera camera, RenderPath path) { // specify matrixes for stereo rendering if (camera.stereoEnabled) { var stereoRenderType = StereoRendererUtil.GetStereoRenderingType(); if (stereoRenderType != StereoRendererUtil.StereoRenderingTypes.None) { float[] camCenterMat = Utility.Matrix2Array(camera.worldToCameraMatrix); float[] projMatL = Utility.Matrix2Array(GL.GetGPUProjectionMatrix(camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left), false)); float[] projMatR = Utility.Matrix2Array(GL.GetGPUProjectionMatrix(camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right), false)); float[] camMatL = Utility.Matrix2Array(camera.GetStereoViewMatrix(Camera.StereoscopicEye.Left)); float[] camMatR = Utility.Matrix2Array(camera.GetStereoViewMatrix(Camera.StereoscopicEye.Right)); Plugin.EffekseerSetStereoRenderingMatrix(path.renderId, (int)stereoRenderType, camCenterMat, projMatL, projMatR, camMatL, camMatR); } } else { // update view matrixes Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); } }
void SetupViewport() { var renderer = GetSubsystem <Renderer>(); var graphics = GetSubsystem <Graphics>(); renderer.NumViewports = 2; // Set up the front camera viewport Viewport viewport = new Viewport(scene, CameraNode.GetComponent <Camera>()); renderer.SetViewport(0, viewport); // Clone the default render path so that we do not interfere with the other viewport, then add // bloom and FXAA post process effects to the front viewport. Render path commands can be tagged // for example with the effect name to allow easy toggling on and off. We start with the effects // disabled. var cache = GetSubsystem <ResourceCache>(); RenderPath effectRenderPath = viewport.GetRenderPath().Clone(); effectRenderPath.Append(cache.Get <XMLFile>("PostProcess/Bloom.xml")); effectRenderPath.Append(cache.Get <XMLFile>("PostProcess/FXAA2.xml")); // Make the bloom mixing parameter more pronounced effectRenderPath.SetShaderParameter("BloomMix", new Vector2(0.9f, 0.6f)); effectRenderPath.SetEnabled("Bloom", false); effectRenderPath.SetEnabled("FXAA2", false); viewport.SetRenderPath(effectRenderPath); // Set up the rear camera viewport on top of the front view ("rear view mirror") // The viewport index must be greater in that case, otherwise the view would be left behind IntRect rect = new IntRect(graphics.Width * 2 / 3, 32, graphics.Width - 32, graphics.Height / 3); Viewport rearViewport = new Viewport(scene, rearCameraNode.GetComponent <Camera>(), rect); renderer.SetViewport(1, rearViewport); }
void CreateScene() { if (_scene == null) { _scene = new Scene(); } _scene.CreateComponent <Octree>(); var physics = _scene.CreateComponent <PhysicsWorld>(); physics.SetGravity(WorldGravity); var cameraNode = _scene.CreateChild(); cameraNode.Position = CameraPosition; cameraNode.Rotate(CameraRotation); cameraNode.CreateComponent <Camera>(); var Viewport = new Viewport(Context, _scene, cameraNode.GetComponent <Camera>(), null); if (Application.Platform != Platforms.Android && Application.Platform != Platforms.iOS) { RenderPath effectRenderPath = Viewport.RenderPath.Clone(); var fxaaRp = Application.ResourceCache.GetXmlFile(Assets.PostProcess.FXAA3); effectRenderPath.Append(fxaaRp); Viewport.RenderPath = effectRenderPath; } Application.Renderer.SetViewport(0, Viewport); var zoneNode = _scene.CreateChild(); var zone = zoneNode.CreateComponent <Zone>(); zone.SetBoundingBox(new BoundingBox(-1000.0f, 1000.0f)); zone.AmbientColor = new Color(1f, 1f, 1f); _trackNode = _scene.CreateChild(); _trackNode.Scale = TrackSize; _trackNode.Position = TrackPosition; var track = _trackNode.CreateComponent <AnimatedModel>(); track.Model = Application.ResourceCache.GetModel(Assets.Models.Plane); track.Material = Application.ResourceCache.GetMaterial(Assets.Materials.Grass); _lightNode = _scene.CreateChild(); _lightNode.Position = LightPosition; _lightNode.Rotation = LightRotation; _lightNode.AddComponent(new Light { Range = 1200, Brightness = 0.8f }); _scoreLabel = new Text(); _scoreLabel.HorizontalAlignment = HorizontalAlignment.Right; _scoreLabel.VerticalAlignment = VerticalAlignment.Top; _scoreLabel.SetFont(Application.ResourceCache.GetFont(Assets.Fonts.Font), Application.Graphics.Width / 20); _scoreLabel.Value = 0.ToString(); Application.UI.Root.AddChild(_scoreLabel); }
private void SetupViewport(string renderPath = null) { var renderer = Renderer; var rp = new RenderPath(); rp.Load(ResourceCache.GetXmlFile(renderPath ?? "RenderPaths/Forward.xml")); renderer.SetViewport(0, new Viewport(Context, _scene, CameraNode.GetComponent <Camera>(), rp)); }
void OnPreCullEvent(Camera camera) { #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { // シーンビューのカメラはチェック if (this.drawInSceneView == false) { return; } } #endif RenderPath path; // カリングマスクをチェック if ((Camera.current.cullingMask & (1 << gameObject.layer)) == 0) { if (renderPaths.ContainsKey(camera)) { // レンダーパスが存在すればコマンドバッファを解除 path = renderPaths[camera]; path.Dispose(); renderPaths.Remove(camera); } return; } if (renderPaths.ContainsKey(camera)) { // レンダーパスが有れば使う path = renderPaths[camera]; } else { // 無ければレンダーパスを作成 path = new RenderPath(camera, cameraEvent, renderPaths.Count); path.Init(this.enableDistortion); renderPaths.Add(camera, path); } if (!path.IsValid()) { path.Dispose(); path.Init(this.enableDistortion); } // 歪みテクスチャをセット if (path.renderTexture) { Plugin.EffekseerSetBackGroundTexture(path.renderId, path.renderTexture.GetNativeTexturePtr()); } // ビュー関連の行列を更新 Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); }
private async void CreateScene() { scene = new Scene(); scene.CreateComponent <Octree>(); var physics = scene.CreateComponent <PhysicsWorld>(); physics.SetGravity(new Vector3(0, 0, 0)); // Camera var cameraNode = scene.CreateChild(); cameraNode.Position = (new Vector3(0.0f, 0.0f, -10.0f)); cameraNode.CreateComponent <Camera>(); Viewport = new Viewport(Context, scene, cameraNode.GetComponent <Camera>(), null); if (Platform != Platforms.Android && Platform != Platforms.iOS) { RenderPath effectRenderPath = Viewport.RenderPath.Clone(); var fxaaRp = ResourceCache.GetXmlFile(Assets.PostProcess.FXAA3); effectRenderPath.Append(fxaaRp); Viewport.RenderPath = effectRenderPath; } Renderer.SetViewport(0, Viewport); var zoneNode = scene.CreateChild(); var zone = zoneNode.CreateComponent <Zone>(); zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f)); zone.AmbientColor = new Color(1f, 1f, 1f); // UI coinsText = new Text(); coinsText.HorizontalAlignment = HorizontalAlignment.Right; coinsText.SetFont(ResourceCache.GetFont(Assets.Fonts.Font), Graphics.Width / 20); UI.Root.AddChild(coinsText); Input.SetMouseVisible(true, false); // Background var background = new Background(); scene.AddComponent(background); background.Start(); // Luci var lightNode = scene.CreateChild(); lightNode.Position = new Vector3(0, -5, -40); lightNode.AddComponent(new Light { Range = 120, Brightness = 0.8f }); // ciclo della logica di gioco bool firstCycle = true; while (true) { var startMenu = scene.CreateComponent <StartMenu>(); await startMenu.ShowStartMenu(!firstCycle); //wait for "start" startMenu.Remove(); await StartGame(); firstCycle = false; } }
public void CreateScence() { Scene scene = new Scene(); scene.CreateComponent <Octree>(); //camera var cameraNode = scene.CreateChild(); cameraNode.Position = (new Vector3(0.0f, 0.0f, -8.0f)); cameraNode.SetDirection(new Vector3(0.1f, 0f, 900f)); /*string filepath = "D:\\dir.txt"; * var dir = cameraNode.Direction; * if (!File.Exists(filepath)) * { * File.Create(filepath).Dispose(); * File.WriteAllText(filepath, "X:" + dir.X.ToString() + "Y:" + dir.Y.ToString() + "Z:" + dir.Z.ToString() + "\n"); * } * else * { * File.AppendAllText(filepath, "X:" + dir.X.ToString() + "Y:" + dir.Y.ToString() + "Z:" + dir.Z.ToString() + "\n"); * }*/ cameraNode.CreateComponent <Camera>(); Viewport = new Viewport(Context, scene, cameraNode.GetComponent <Camera>(), null); if (Platform != Platforms.Android && Platform != Platforms.iOS) { RenderPath effectRenderPath = Viewport.RenderPath.Clone(); var fxaaRp = ResourceCache.GetXmlFile(Assets.PostProcess.FXAA3); effectRenderPath.Append(fxaaRp); Viewport.RenderPath = effectRenderPath; } Renderer.SetViewport(0, Viewport); //zone construct- 构造分区 var zoneNode = scene.CreateChild(); var zone = zoneNode.CreateComponent <Zone>(); zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f)); zone.AmbientColor = new Color(1, 1, 1); //生成背景 var backgroud = new Backgroud(); scene.AddComponent(backgroud); backgroud.Start(); //生成house var house = new House(); scene.AddComponent(house); house.Start(); //生成Apple var apple = new Apple(); scene.AddComponent(apple); apple.Start(); }
/// <summary> /// Sets starting values to variables /// </summary> private void Start() { rb = GetComponent <Rigidbody>(); colliders = GetComponentsInChildren <BoxCollider>(); if (showTrajectory == true) { rp = GetComponent <RenderPath>(); } }
public void OnPostRender(Camera camera) { if (renderPaths.ContainsKey(camera)) { RenderPath path = renderPaths[camera]; Plugin.EffekseerSetRenderSettings(path.renderId, (camera.activeTexture != null)); } }
void OnRenderObject() { if (renderPaths.ContainsKey(Camera.current)) { RenderPath path = renderPaths[Camera.current]; Plugin.EffekseerSetRenderSettings(path.renderId, (RenderTexture.active != null)); } }
void OnPreCullEvent(Camera camera) { #if UNITY_EDITOR if (Array.IndexOf <Camera>(SceneView.GetAllSceneCameras(), camera) >= 0) { // シーンビューのカメラはチェック if (this.drawInSceneView == false) { return; } } else if (Camera.current.isActiveAndEnabled == false) { // シーンビュー以外のエディタカメラは除外 return; } #endif RenderPath path; // カリングマスクをチェック if ((Camera.current.cullingMask & (1 << gameObject.layer)) == 0) { if (renderPaths.ContainsKey(camera)) { // レンダーパスが存在すればコマンドバッファを解除 path = renderPaths[camera]; camera.RemoveCommandBuffer(path.cameraEvent, path.commandBuffer); renderPaths.Remove(camera); } return; } if (renderPaths.ContainsKey(camera)) { // レンダーパスが有れば使う path = renderPaths[camera]; } else { // 無ければ作成 path = new RenderPath(); path.renderId = renderPaths.Count; path.cameraEvent = cameraEvent; // プラグイン描画するコマンドバッファを作成 path.commandBuffer = new CommandBuffer(); path.commandBuffer.IssuePluginEvent(Plugin.EffekseerGetRenderFunc(), path.renderId); // コマンドバッファをカメラに登録 camera.AddCommandBuffer(path.cameraEvent, path.commandBuffer); renderPaths.Add(camera, path); } // ビュー関連の行列を更新 Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); }
void SetupViewport() { var renderer = GetSubsystem <Renderer>(); var cache = GetSubsystem <ResourceCache>(); renderer.SetNumViewports(2); // use 2 viewports, 1 for 3d and 1 for the 2d hud var viewport2_ = new Viewport(hudScene, hudCamera); // hud orthographic viewport, scene and camera var overlayRenderPath = new RenderPath(); overlayRenderPath.Load(cache.GetResource <XMLFile>("PostProcess/FrontPath.xml")); //special renderpath that does not clear viewport2_.SetRenderPath(overlayRenderPath); // apply to hud viewport, so the background is transparent renderer.SetViewport(0, new Viewport(scene, camera)); // perspective viewport, scene and camera renderer.SetViewport(1, viewport2_); // and add in the HUD viewport }
protected override void OnShow(Node node, Asset asset) { oldRp = App.Viewport.RenderPath.Clone(); RenderPath customRp = oldRp.Clone(); customRp.Append(ResourceCache.GetXmlFile(asset.RelativePathToAsset)); App.Viewport.RenderPath = customRp; var model = node.CreateComponent <StaticModel>(); model.Model = ResourceCache.GetModel("Models/TeaPot.mdl"); model.SetMaterial(ResourceCache.GetMaterial("Materials/DefaulPreviewerMaterial.xml")); node.SetScale(5f); node.Rotation = new Quaternion(20, 150, 20); }
public void CreateMenu() { if (_scene == null) { _scene = new Scene(); } _scene.CreateComponent <Octree>(); var physics = _scene.CreateComponent <PhysicsWorld>(); physics.SetGravity(new Vector3(0, 0, 0)); var cameraNode = _scene.CreateChild(); cameraNode.Position = (new Vector3(0.0f, 0f, -500.0f)); cameraNode.Rotate(new Quaternion(10, 0, 0)); cameraNode.CreateComponent <Camera>(); var Viewport = new Viewport(Context, _scene, cameraNode.GetComponent <Camera>(), null); if (Application.Platform != Platforms.Android && Application.Platform != Platforms.iOS) { RenderPath effectRenderPath = Viewport.RenderPath.Clone(); var fxaaRp = Application.ResourceCache.GetXmlFile(Assets.PostProcess.FXAA3); effectRenderPath.Append(fxaaRp); Viewport.RenderPath = effectRenderPath; } Application.Renderer.SetViewport(0, Viewport); var zoneNode = _scene.CreateChild(); var zone = zoneNode.CreateComponent <Zone>(); zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f)); zone.AmbientColor = new Color(1f, 1f, 1f); var plannerNode = _scene.CreateChild(); plannerNode.Position = new Vector3(0, -50, 0); plannerNode.Scale = new Vector3(10, 10, 10); var planner = plannerNode.CreateComponent <StaticModel>(); planner.Model = Application.ResourceCache.GetModel(Assets.Models.VerBot); planner.Material = Application.ResourceCache.GetMaterial(Assets.Materials.VerBot); planner.SetMaterial(Application.ResourceCache.GetMaterial(Assets.Materials.VerBot)); var movement = new RepeatForever(new RotateBy(1, 0, 5, 0)); plannerNode.RunActionsAsync(movement); // Lights: var _lightNode = _scene.CreateChild(); _lightNode.Position = new Vector3(0.0f, 0f, -5.0f); var light = _lightNode.CreateComponent <Light>(); light.Range = 1200; light.Brightness = 2; if (ResultString != "") { Text ResultText = new Text(); ResultText.HorizontalAlignment = HorizontalAlignment.Center; ResultText.VerticalAlignment = VerticalAlignment.Center; ResultText.Value = ResultString; ResultText.SetFont(Application.ResourceCache.GetFont(Assets.Fonts.Font), Application.Graphics.Width / 20); Application.UI.Root.AddChild(ResultText); } Text WelcomeText = new Text(); WelcomeText.HorizontalAlignment = HorizontalAlignment.Center; WelcomeText.VerticalAlignment = VerticalAlignment.Center; WelcomeText.Position = new IntVector2(WelcomeText.Position.X, 150); WelcomeText.Value = WelcomeString; WelcomeText.SetFont(Application.ResourceCache.GetFont(Assets.Fonts.Font), Application.Graphics.Width / 20); Application.UI.Root.AddChild(WelcomeText); }
private void ReadRenderSection(XElement declaration, LoadContext lc, ComponentDescription description) { List <RenderDescription> parsedRenderDescriptions = new List <RenderDescription>(); var renderDescriptions = declaration.XPathSelectElements("/cd:render/cd:group", lc.NamespaceManager); foreach (var renderNode in renderDescriptions) { IConditionTreeItem conditionCollection = ConditionTree.Empty; List <IRenderCommand> commands = new List <IRenderCommand>(); var conditionsAttribute = renderNode.Attribute("conditions"); if (conditionsAttribute != null) { IXmlLineInfo line = conditionsAttribute as IXmlLineInfo; try { conditionCollection = lc.ConditionParser.Parse(conditionsAttribute.Value, lc.ParseContext); } catch (ConditionFormatException ex) { lc.Errors.Add(new LoadError(lc.FileName, line.LineNumber, line.LinePosition + conditionsAttribute.Name.LocalName.Length + 2 + ex.PositionStart, LoadErrorCategory.Error, ex.Message)); continue; } } foreach (var renderCommandNode in renderNode.Descendants()) { string commandType = renderCommandNode.Name.LocalName; if (commandType == "line") { var command = new Line(); command.LoadFromXml(renderCommandNode, lc); commands.Add(command); } else if (commandType == "rect") { var command = new Rectangle(); command.LoadFromXml(renderCommandNode); commands.Add(command); } else if (commandType == "ellipse") { var command = new Ellipse(); command.LoadFromXml(renderCommandNode, lc); commands.Add(command); } else if (commandType == "text") { var command = new Text(); command.LoadFromXml(renderCommandNode, lc); commands.Add(command); } else if (commandType == "path") { var command = new RenderPath(); command.LoadFromXml(renderCommandNode, lc); commands.Add(command); } } parsedRenderDescriptions.Add(new RenderDescription(conditionCollection, commands.ToArray())); } description.RenderDescriptions = parsedRenderDescriptions.ToArray(); }
public void Render(Camera camera, int?dstID, RenderTargetIdentifier?dstIdentifier) { var settings = EffekseerSettings.Instance; #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { // check a camera in the scene view if (settings.drawInSceneView == false) { return; } } #endif // check a culling mask var mask = Effekseer.Plugin.EffekseerGetCameraCullingMaskToShowAllEffects(); if ((camera.cullingMask & mask) == 0) { if (renderPaths.ContainsKey(camera)) { var path_ = renderPaths[camera]; path_.Dispose(); renderPaths.Remove(camera); } return; } // GC renderpaths bool hasDisposed = false; foreach (var path_ in renderPaths) { path_.Value.LifeTime--; if (path_.Value.LifeTime < 0) { path_.Value.Dispose(); hasDisposed = true; } } // dispose renderpaths if (hasDisposed) { List <Camera> removed = new List <Camera>(); foreach (var path_ in renderPaths) { if (path_.Value.LifeTime >= 0) { continue; } removed.Add(path_.Key); } foreach (var r in removed) { renderPaths.Remove(r); } } RenderPath path; if (renderPaths.ContainsKey(camera)) { path = renderPaths[camera]; } else { // render path doesn't exists, create a render path path = new RenderPath(camera, cameraEvent, renderPaths.Count); var stereoRenderingType = (camera.stereoEnabled)? StereoRendererUtil.GetStereoRenderingType() : StereoRendererUtil.StereoRenderingTypes.None; path.Init(EffekseerRendererUtils.IsDistortionEnabled, dstID, dstIdentifier, stereoRenderingType); renderPaths.Add(camera, path); } if (!path.IsValid()) { path.Dispose(); var stereoRenderingType = (camera.stereoEnabled) ? StereoRendererUtil.GetStereoRenderingType() : StereoRendererUtil.StereoRenderingTypes.None; path.Init(EffekseerRendererUtils.IsDistortionEnabled, dstID, dstIdentifier, stereoRenderingType); } path.LifeTime = 60; Plugin.EffekseerSetRenderingCameraCullingMask(path.renderId, camera.cullingMask); // if LWRP if (dstID.HasValue || dstIdentifier.HasValue) { // flip a rendertaget // Direct11 : OK (2019, LWRP 5.13) // Android(OpenGL) : OK (2019, LWRP 5.13) Plugin.EffekseerSetRenderSettings(path.renderId, true); Plugin.EffekseerSetIsBackgroundTextureFlipped(0); } else { Plugin.EffekseerSetIsBackgroundTextureFlipped(0); } // assign a dinsotrion texture if (path.renderTexture) { Plugin.EffekseerSetBackGroundTexture(path.renderId, path.renderTexture.GetNativeTexturePtr()); } // specify matrixes for stereo rendering if (camera.stereoEnabled) { var stereoRenderType = StereoRendererUtil.GetStereoRenderingType(); if (stereoRenderType != StereoRendererUtil.StereoRenderingTypes.None) { float[] camCenterMat = Utility.Matrix2Array(camera.worldToCameraMatrix); float[] projMatL = Utility.Matrix2Array(GL.GetGPUProjectionMatrix(camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left), false)); float[] projMatR = Utility.Matrix2Array(GL.GetGPUProjectionMatrix(camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right), false)); float[] camMatL = Utility.Matrix2Array(camera.GetStereoViewMatrix(Camera.StereoscopicEye.Left)); float[] camMatR = Utility.Matrix2Array(camera.GetStereoViewMatrix(Camera.StereoscopicEye.Right)); Plugin.EffekseerSetStereoRenderingMatrix(path.renderId, (int)stereoRenderType, camCenterMat, projMatL, projMatR, camMatL, camMatR); } } else { // update view matrixes Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); } }
public void Render(Camera camera, RenderTargetProperty renderTargetProperty, CommandBuffer targetCommandBuffer) { var settings = EffekseerSettings.Instance; #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { // check a camera in the scene view if (settings.drawInSceneView == false) { return; } } #endif // check a culling mask var mask = Effekseer.Plugin.EffekseerGetCameraCullingMaskToShowAllEffects(); // don't need to update because doesn't exists and need not to render if ((camera.cullingMask & mask) == 0 && !renderPaths.ContainsKey(camera)) { return; } // GC renderpaths bool hasDisposed = false; foreach (var path_ in renderPaths) { path_.Value.LifeTime--; if (path_.Value.LifeTime < 0) { path_.Value.Dispose(); hasDisposed = true; } } // dispose renderpaths if (hasDisposed) { List <Camera> removed = new List <Camera>(); foreach (var path_ in renderPaths) { if (path_.Value.LifeTime >= 0) { continue; } removed.Add(path_.Key); Plugin.EffekseerAddRemovingRenderPath(path_.Value.renderId); } foreach (var r in removed) { renderPaths.Remove(r); } } RenderPath path; if (renderPaths.ContainsKey(camera)) { path = renderPaths[camera]; } else { // render path doesn't exists, create a render path while (true) { bool found = false; foreach (var kv in renderPaths) { if (kv.Value.renderId == nextRenderID) { found = true; break; } } if (found) { nextRenderID++; } else { break; } } path = new RenderPath(camera, cameraEvent, nextRenderID, targetCommandBuffer != null); var stereoRenderingType = (camera.stereoEnabled) ? StereoRendererUtil.GetStereoRenderingType() : StereoRendererUtil.StereoRenderingTypes.None; path.Init(EffekseerRendererUtils.IsDistortionEnabled, renderTargetProperty, stereoRenderingType); renderPaths.Add(camera, path); nextRenderID = (nextRenderID + 1) % EffekseerRendererUtils.RenderIDCount; } if (!path.IsValid(renderTargetProperty)) { path.Dispose(); var stereoRenderingType = (camera.stereoEnabled) ? StereoRendererUtil.GetStereoRenderingType() : StereoRendererUtil.StereoRenderingTypes.None; path.Init(EffekseerRendererUtils.IsDistortionEnabled, renderTargetProperty, stereoRenderingType); } path.LifeTime = 60; Plugin.EffekseerSetRenderingCameraCullingMask(path.renderId, camera.cullingMask); // effects shown don't exists if ((camera.cullingMask & mask) == 0) { // Because rendering thread is asynchronous SpecifyRenderingMatrix(camera, path); return; } if (path.isCommandBufferFromExternal) { path.AssignExternalCommandBuffer(targetCommandBuffer, renderTargetProperty); } // if LWRP if (renderTargetProperty != null) { // flip a rendertaget // Direct11 : OK (2019, LWRP 5.13) // Android(OpenGL) : OK (2019, LWRP 5.13) Plugin.EffekseerSetRenderSettings(path.renderId, true); Plugin.EffekseerSetIsBackgroundTextureFlipped(0); } else { #if UNITY_SWITCH && !UNITY_EDITOR Plugin.EffekseerSetIsBackgroundTextureFlipped(1); #else Plugin.EffekseerSetIsBackgroundTextureFlipped(0); #endif } // assign a dinsotrion texture if (path.renderTexture != null) { Plugin.EffekseerSetBackGroundTexture(path.renderId, path.renderTexture.ptr); } SpecifyRenderingMatrix(camera, path); }
public Command() { this.Render = new RenderPath(); }
public override void Deserialize(string key, string value) { switch (key) { case "lgpr": lightPrecision = (LightPrecision)int.Parse(value); break; case "limd": lightMode = (LightMode)int.Parse(value); break; case "uamb": useAmbient = bool.Parse(value); break; case "mssp": maskedSpec = bool.Parse(value); break; case "bkdf": bakedLight = bool.Parse(value); break; case "spmd": specularMode = (SpecularMode)int.Parse(value); break; case "trmd": transparencyMode = (TransparencyMode)int.Parse(value); break; case "grmd": glossRoughMode = (GlossRoughMode)int.Parse(value); break; /*case "shdc": * shadowCast = bool.Parse( value ); * break; * case "shdr": * shadowReceive = bool.Parse( value ); * break;*/ case "lico": lightCount = (LightCount)int.Parse(value); break; case "lmpd": bakedLight |= bool.Parse(value); break; case "lprd": bakedLight |= bool.Parse(value); break; case "hqlp": highQualityLightProbes = bool.Parse(value); break; case "rprd": reflectprobed = bool.Parse(value); break; case "enco": energyConserving = bool.Parse(value); break; case "rmgx": remapGlossExponentially = bool.Parse(value); break; case "imps": includeMetaPass = bool.Parse(value); break; case "rpth": renderPath = (RenderPath)int.Parse(value); break; } }
public override float DrawInner(ref Rect r) { float prevYpos = r.y; r.y = 0; r.xMin += 20; r.y += 20; renderPath = (RenderPath)UndoableContentScaledToolbar(r, "Render Path", (int)renderPath, strRenderPath, "render path"); if (renderPath == RenderPath.Deferred) { if (lightMode != LightMode.PBL) { lightMode = LightMode.PBL; } if (ps.catBlending.autoSort == false) { ps.catBlending.autoSort = true; } if (ps.catBlending.blendModePreset != BlendModePreset.Opaque) { ps.catBlending.blendModePreset = BlendModePreset.Opaque; ps.catBlending.ConformBlendsToPreset(); } } r.y += 20; if (renderPath == RenderPath.Deferred) { GUI.enabled = false; UndoableContentScaledToolbar(r, "Light Mode", (int)LightMode.PBL, strLightMode, "light mode"); GUI.enabled = true; } else { lightMode = (LightMode)UndoableContentScaledToolbar(r, "Light Mode", (int)lightMode, strLightMode, "light mode"); } r.y += 20; if (IsPBL()) { specularMode = (SpecularMode)UndoableContentScaledToolbar(r, "Specular Mode", (int)specularMode, strSpecularMode, "specular mode"); r.y += 20; } GUI.enabled = ps.HasSpecular(); glossRoughMode = (GlossRoughMode)UndoableContentScaledToolbar(r, "Gloss Mode", (int)glossRoughMode, strGlossRoughMode, "gloss mode"); r.y += 20; GUI.enabled = true; GUI.enabled = ps.HasAlpha(); // Has Opacity connected transparencyMode = (TransparencyMode)UndoableContentScaledToolbar(r, "Transparency Mode", (int)transparencyMode, strTransparencyMode, "transparency mode"); r.y += 20; GUI.enabled = true; if (ps.catLighting.IsPBL() == false) { UndoableConditionalToggle(r, ref remapGlossExponentially, usableIf: ps.HasGloss() && renderPath != RenderPath.Deferred, disabledDisplayValue: renderPath == RenderPath.Deferred ? true : false, label: "Remap gloss from [0-1] to " + ((renderPath == RenderPath.Deferred) ? "[0-128]" : "[1-2048]"), undoSuffix: "gloss remap" ); r.y += 20; } if (lightMode == LightMode.Unlit || lightMode == LightMode.PBL) { GUI.enabled = false; } { //bool b = energyConserving; if (lightMode == LightMode.PBL) { GUI.Toggle(r, true, "Energy Conserving"); // Dummy display of a checked energy conserve } else { energyConserving = UndoableToggle(r, energyConserving, "Energy Conserving", "energy conservation", null); } //energyConserving = GUI.Toggle( r, energyConserving, "Energy Conserving" ); r.y += 20; GUI.enabled = true; } GUI.enabled = renderPath == RenderPath.Forward; lightCount = (LightCount)UndoableContentScaledToolbar(r, "Light Count", (int)lightCount, strLightCount, "light count"); GUI.enabled = true; r.y += 20; //lightPrecision = (LightPrecision)ContentScaledToolbar(r, "Light Quality", (int)lightPrecision, strLightPrecision ); // TODO: Too unstable for release //r.y += 20; UndoableConditionalToggle(r, ref bakedLight, usableIf: ps.HasDiffuse() && lightMode != LightMode.Unlit, disabledDisplayValue: false, label: "Lightmap & light probes", undoSuffix: "lightmap & light probes" ); r.y += 20; bool wantsMetaPass = ps.catLighting.bakedLight && (ps.HasDiffuse() || ps.HasEmissive()); UndoableConditionalToggle(r, ref includeMetaPass, usableIf: wantsMetaPass, disabledDisplayValue: false, label: "Write meta pass (light bounce coloring)", undoSuffix: "write meta pass" ); r.y += 20; //includeMetaPass = UndoableToggle( r, includeMetaPass, "Write meta pass (light bounce coloring)", "write meta pass", null ); //r.y += 20; highQualityLightProbes = UndoableToggle(r, highQualityLightProbes, "Per-pixel light probe sampling", "per-pixel light probe sampling", null); r.y += 20; UndoableConditionalToggle(r, ref reflectprobed, usableIf: ps.HasSpecular() && lightMode != LightMode.Unlit, disabledDisplayValue: false, label: "Reflection probe support", undoSuffix: "reflection probe support" ); r.y += 20; /*shadowCast = GUI.Toggle( r, shadowCast, "Cast shadows" ); * r.y += 20; * shadowReceive = GUI.Toggle( r, shadowReceive, "Receive shadows" ); * r.y += 20;*/ //GUI.enabled = IsLit(); /* * UndoableConditionalToggle( r, ref geometricAntiAliasing, * usableIf: ps.HasSpecular() && ps.catLighting.IsPBL(), * disabledDisplayValue: false, * label: "Geometric specular anti-aliasing", * undoSuffix: "geometric specular anti-aliasing" * ); * r.y += 20; */ UndoableConditionalToggle(r, ref useAmbient, usableIf: !bakedLight && ps.catLighting.IsLit(), disabledDisplayValue: bakedLight, label: "Receive Ambient Light", undoSuffix: "receive ambient light" ); r.y += 20; /* * if(lightprobed){ * GUI.enabled = false; * GUI.Toggle( r, true, "Receive Ambient Light" ); * GUI.enabled = true; * }else{ * useAmbient = GUI.Toggle( r, useAmbient, "Receive Ambient Light" ); * }*/ //r.y += 20; /* DISABLED DUE TO CAUSING TOO MANY ARTIFACTS * if(ps.catLighting.HasSpecular() && renderPath == RenderPath.Forward){ * maskedSpec = UndoableToggle( r, maskedSpec, "Mask directional light specular by shadows", "directional light specular shadow masking", null ); * } else { * GUI.enabled = false; * GUI.Toggle( r, false, "Mask directional light specular by shadows" ); * GUI.enabled = true; * } * r.y += 20;*/ r.y += prevYpos; return((int)r.yMax); }
public Viewport(Scene scene, Camera camera, Urho.IntRect rect, RenderPath renderPath) : this(Application.CurrentContext, scene, camera, rect, renderPath) { }
public override void Start() { // We get the variables we are going to use in this example Renderer renderer = GetSubsystem <Renderer>(); graphics = GetSubsystem <Graphics>(); viewport = renderer.GetViewport(0); // We create a new Scene scene = new Scene(); // The Octree should be added to the root scene node (mandatory?) TODO: answer this scene.CreateComponent <Octree>(); // We pass the scene we just created to be displayed in the viewport viewport.Scene = scene; // We create a new camera on the scene, called "Camera". Tip: you can think of a camera as a glorified projection matrix // - Scene.CreateChild(string name) returns a new Node with that name. // - Node.CreateComponent<ComponentType>() returns a component attached to that Node camera = scene.CreateChild("Camera").CreateComponent <Camera>(); // We can access the Node any component is attached to using Component.Node camera.Node.Position = new Vector3(0.5f, 0.5f, 0.0f); // Remember, 'camera' is a Camera component, so we access it directly here camera.Orthographic = true; camera.OrthoSize = 1.5f; // We pass our newly created camera to the viewport so it's used to display our scene viewport.Camera = camera; // We create an XML from string so this code is fully self-contained XMLFile xml = new XMLFile(); xml.FromString("<renderpath><command type=\"sendevent\"/></renderpath>"); // We create a new RenderPath. A Viewport comes by default with some events, and you can use viewport.GetRenderPath().Clone() // to clone the default RenderPath and Append instructions to it instead (see AtomicBlaster for examples on how to do effects) RenderPath renderpath = new RenderPath(); renderpath.Append(xml); // We replace the viewport's default renderpath by the one we just created viewport.SetRenderPath(renderpath); // We subscribe to the RenderPathEvent. Here we pass an anonymous function that just absorbs the argument and calls Render() SubscribeToEvent <RenderPathEvent>(e => { Render(); }); // Here we setup our shaders, we are using the BasicVColUnlitAlpha "technique" and selecting DIFFMAP and VERTEXCOLOR // DIFFMAP is the diffuse texture and VERTEXCOLOR is a color each vertex holds that is used to 'tint' the surface // See this link: github.com/AtomicGameEngine/AtomicGameEngine/tree/master/Resources/CoreData/Techniques ShaderVariation pixelShader = graphics.GetShader(ShaderType.PS, "Basic", "DIFFMAP VERTEXCOLOR"); ShaderVariation vertexShader = graphics.GetShader(ShaderType.VS, "Basic", "DIFFMAP VERTEXCOLOR"); graphics.SetShaders(vertexShader, pixelShader); // This vertex shader parameter just applies no transformation (Identity Matrix means no transformation) so the vertices // display in world coordinates what allow us to use the camera properly. NOTE: Identity Matrix is also called Unit Matrix graphics.SetShaderParameter(ShaderParams.VSP_MODEL, Matrix3x4.IDENTITY); // We set the pixel shader diffuse color to be white. You can change this to 'tint' the texture similar to vertex colors // but this applies to the whole material and in this example vertex colors will also affect it graphics.SetShaderParameter(ShaderParams.PSP_MATDIFFCOLOR, Color.White); // We set cull mode to NONE so our geometry won't be culled (ignored), for this example we don't really need any culling graphics.SetCullMode(CullMode.CULL_NONE); // We create a texture from literal data so this code is fully self-contained, you can safely skip the lines below. // In your real projects you're most likely going to load textures from the disk using Texture.Load Image image = new Image(); image.SetSize(16, 16, 3); Color z = Color.White; Color M = Color.Blue; Color k = Color.Black; Color[] imageData = { k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, z, z, z, z, z, z, z, z, z, z, z, z, z, M, k, k, z, z, z, z, z, z, M, M, z, z, z, z, z, z, k, k, z, z, z, z, z, z, M, M, z, z, z, z, z, z, k, k, z, z, z, z, z, M, z, z, M, z, z, z, z, z, k, k, z, z, z, z, z, M, z, z, M, z, z, z, z, z, k, k, z, z, z, z, M, z, z, z, z, M, z, z, z, z, k, k, z, z, z, z, M, z, z, z, z, M, z, z, z, z, k, k, z, z, z, M, z, z, z, z, z, z, M, z, z, z, k, k, z, z, z, M, z, z, z, z, z, z, M, z, z, z, k, k, z, z, M, M, M, M, M, M, M, M, M, M, z, z, k, k, z, z, M, z, z, z, z, z, z, z, z, M, z, z, k, k, z, M, z, z, z, z, z, z, z, z, z, z, M, z, k, k, z, M, z, z, z, z, z, z, z, z, z, z, M, z, k, k, z, z, z, z, z, z, z, z, z, z, z, z, z, z, k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, k, }; for (int pixel = 0; pixel < imageData.Length; pixel++) { image.SetPixel(pixel % 16, 15 - pixel / 16, imageData[pixel]); } texture = new Texture2D(); texture.SetData(image); // We call this function that creates the quad geometry CreateQuad(); }
public void SetRenderPath(RenderPath renderPath) { csb_Atomic_Viewport_SetRenderPath_RenderPath(nativeInstance, renderPath != null ? renderPath.nativeInstance : IntPtr.Zero); }
private void WriteDescriptions() { BW mainWriter = new BW(m_contentStream); foreach (ComponentDescription description in Descriptions) { using (MemoryStream tempStream = new MemoryStream()) { BW writer = new BW(tempStream); writer.Write(NewResourceID()); // ID writer.Write((uint)(6 + (Settings.WriteExtendedMetadada ? 1 : 0))); // 6 sections #region Metadata // Write METADATA /* Component name (string) * Can resize (bool) * Minimum size (bool) * GUID (byte[16]) * Author (string) * Version (major, minor) (uint, uint) * AdditionalInformation (string) * Implement set (string) * Implement item (string) * IconresourceID (int) * Timestamp (long) */ using (MemoryStream metadatSectionStream = new MemoryStream()) { BW metadataWriter = new BW(metadatSectionStream); metadataWriter.WriteNullString(description.ComponentName); metadataWriter.Write(!description.GetDefaultFlag(FlagOptions.NoResize)); metadataWriter.Write(description.GetDefaultFlag(FlagOptions.FlipPrimary)); metadataWriter.Write(description.MinSize); metadataWriter.Write(description.Metadata.GUID.ToByteArray()); metadataWriter.WriteNullString(description.Metadata.Author); metadataWriter.Write((ushort)description.Metadata.Version.Major); metadataWriter.Write((ushort)description.Metadata.Version.Minor); metadataWriter.WriteNullString(description.Metadata.AdditionalInformation); metadataWriter.WriteNullString(description.Metadata.ImplementSet); metadataWriter.WriteNullString(description.Metadata.ImplementItem); if (description.Metadata.Icon != null) { uint iconResourceID = NewResourceID(); foreach (var icon in description.Metadata.Icon as MultiResolutionImage) { BinaryResource iconResource = new BinaryResource(); iconResource.ID = iconResourceID; // Only PNG images can be written at the moment iconResource.ResourceType = BinaryResourceType.PNGImage; iconResource.Buffer = icon.Data; Resources.Add(iconResource); } metadataWriter.Write((int)iconResourceID); } else { metadataWriter.Write(-1); } metadataWriter.Write(DateTime.Now.ToBinary()); writer.Write((ushort)BinaryConstants.ComponentSectionType.Metadata); writer.Write((uint)metadatSectionStream.Length); writer.Write(metadatSectionStream.ToArray()); } #endregion #region Flags // Write FLAGS using (MemoryStream flagsSectionStream = new MemoryStream()) { BW flagsWriter = new BW(flagsSectionStream); flagsWriter.Write((uint)description.Flags.Count); foreach (Conditional <FlagOptions> flags in description.Flags) { flagsWriter.Write(flags.Conditions); flagsWriter.Write((uint)flags.Value); } writer.Write((ushort)BinaryConstants.ComponentSectionType.Flags); writer.Write((uint)flagsSectionStream.Length); writer.Write(flagsSectionStream.ToArray()); } #endregion #region Properties // Write PROPERTIES using (MemoryStream propertiesSectionStream = new MemoryStream()) { BW propertiesWriter = new BW(propertiesSectionStream); propertiesWriter.Write((uint)description.Properties.Length); foreach (ComponentProperty property in description.Properties) { propertiesWriter.Write(property.Name); propertiesWriter.Write(property.SerializedName.Value); propertiesWriter.Write(property.DisplayName); propertiesWriter.WriteType(property.Default, property.EnumOptions != null); if (property.EnumOptions != null) { propertiesWriter.Write(property.EnumOptions.Length); foreach (string option in property.EnumOptions) { propertiesWriter.Write(option); } } // Format rules propertiesWriter.Write((uint)property.FormatRules.Length); foreach (ComponentPropertyFormat formatRule in property.FormatRules) { propertiesWriter.Write(formatRule.Conditions); propertiesWriter.Write(formatRule.Value); } // Other conditions propertiesWriter.Write((uint)property.OtherConditions.Count); foreach (KeyValuePair <PropertyOtherConditionType, IConditionTreeItem> otherCondition in property.OtherConditions) { propertiesWriter.Write((uint)otherCondition.Key); propertiesWriter.Write(otherCondition.Value); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Properties); writer.Write((uint)propertiesSectionStream.Length); writer.Write(propertiesSectionStream.ToArray()); } #endregion #region Configurations // Write CONFIGURATIONS using (MemoryStream configurationsStream = new MemoryStream()) { BW configurationWriter = new BW(configurationsStream); configurationWriter.Write((uint)description.Metadata.Configurations.Count); foreach (ComponentConfiguration configuration in description.Metadata.Configurations) { configurationWriter.Write(configuration.Name); configurationWriter.Write((configuration.ImplementationName ?? "")); configurationWriter.Write(configuration.Setters.Count); foreach (var setter in configuration.Setters) { foreach (ComponentProperty property in description.Properties) { if (property.SerializedName == setter.Key) { configurationWriter.Write(property.SerializedName.Value); break; } } configurationWriter.WriteType(setter.Value); } if (!Settings.IgnoreIcons && configuration.Icon != null) { uint iconResourceID = NewResourceID(); foreach (var icon in configuration.Icon as MultiResolutionImage) { BinaryResource iconResource = new BinaryResource(); iconResource.ID = iconResourceID; // Only PNG images can be written at the moment iconResource.ResourceType = BinaryResourceType.PNGImage; iconResource.Buffer = icon.Data; Resources.Add(iconResource); } configurationWriter.Write((int)iconResourceID); } else { configurationWriter.Write(-1); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Configurations); writer.Write((uint)configurationsStream.Length); writer.Write(configurationsStream.ToArray()); } #endregion #region Connections // Write CONNECTIONS using (MemoryStream connectionsStream = new MemoryStream()) { BW connectionsWriter = new BW(connectionsStream); connectionsWriter.Write((uint)description.Connections.Length); foreach (ConnectionGroup connectionGroup in description.Connections) { connectionsWriter.Write(connectionGroup.Conditions); connectionsWriter.Write((uint)connectionGroup.Value.Length); foreach (ConnectionDescription connection in connectionGroup.Value) { connectionsWriter.Write(connection.Start); connectionsWriter.Write(connection.End); connectionsWriter.Write((int)connection.Edge); connectionsWriter.Write(connection.Name.Value); } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Connections); writer.Write((uint)connectionsStream.Length); writer.Write(connectionsStream.ToArray()); } #endregion #region Render // Write RENDER using (MemoryStream renderStream = new MemoryStream()) { BW renderWriter = new BW(renderStream); renderWriter.Write(description.RenderDescriptions.Length); foreach (RenderDescription renderDescription in description.RenderDescriptions) { renderWriter.Write(renderDescription.Conditions); renderWriter.Write(renderDescription.Value.Length); // number of render commands foreach (IRenderCommand command in renderDescription.Value) { renderWriter.Write((uint)command.Type); // command type switch (command.Type) { case RenderCommandType.Line: { Line line = command as Line; renderWriter.Write(line.Start); renderWriter.Write(line.End); renderWriter.Write(line.Thickness); } break; case RenderCommandType.Rect: { Rectangle rect = command as Rectangle; renderWriter.Write(rect.Location); renderWriter.Write(rect.Width); renderWriter.Write(rect.Height); renderWriter.Write(rect.StrokeThickness); renderWriter.Write((rect.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled } break; case RenderCommandType.Ellipse: { Ellipse ellipse = command as Ellipse; renderWriter.Write(ellipse.Centre); renderWriter.Write(ellipse.RadiusX); renderWriter.Write(ellipse.RadiusY); renderWriter.Write(ellipse.Thickness); renderWriter.Write((ellipse.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled } break; case RenderCommandType.Path: { RenderPath path = command as RenderPath; renderWriter.Write(path.Start); renderWriter.Write(path.Thickness); renderWriter.Write((path.Fill ? (uint)1 : (uint)0)); // 0 for transparent, 1 for filled renderWriter.Write(path.Commands.Count); foreach (IPathCommand pCommand in path.Commands) { renderWriter.Write((int)pCommand.Type); pCommand.Write(renderWriter); } } break; case RenderCommandType.Text: { var text = command as RenderText; renderWriter.Write(BinaryConstants.FormattedTextVersion); renderWriter.Write(text.Location); renderWriter.Write((byte)text.Alignment); renderWriter.Write((byte)text.Rotation); renderWriter.Write((byte)0); renderWriter.Write((byte)0); renderWriter.Write((uint)text.TextRuns.Count); // Number of text runs foreach (TextRun run in text.TextRuns) { renderWriter.Write((uint)run.Formatting.FormattingType); // Run formatting type renderWriter.Write(run.Formatting.Size); // Run text size renderWriter.Write(run.Text); // Text } } break; } } } writer.Write((ushort)BinaryConstants.ComponentSectionType.Render); writer.Write((uint)renderStream.Length); writer.Write(renderStream.ToArray()); } #endregion #region ExtendedMetadata if (Settings.WriteExtendedMetadada) { using (var extendedMetadataStream = new MemoryStream()) { var extendedMetadataWriter = new BW(extendedMetadataStream); extendedMetadataWriter.Write((byte)BinaryConstants.ExtendedMetadataField.SemanticVersion); extendedMetadataWriter.WriteType(new Circuit.PropertyValue(description.Metadata.Version.ToString())); writer.Write((ushort)BinaryConstants.ComponentSectionType.ExtendedMetadata); writer.Write((uint)extendedMetadataStream.Length); writer.Write(extendedMetadataStream.ToArray()); } } #endregion mainWriter.Write((ushort)BinaryConstants.ContentItemType.Component); mainWriter.Write((uint)tempStream.Length); mainWriter.Write(tempStream.ToArray()); } } }
public Command(RenderPath render) { this.Render = render; }
public void Render(Camera camera, int?dstID, RenderTargetIdentifier?dstIdentifier) { var settings = EffekseerSettings.Instance; #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { // check a camera in the scene view if (settings.drawInSceneView == false) { return; } } #endif // check a culling mask var mask = Effekseer.Plugin.EffekseerGetCameraCullingMaskToShowAllEffects(); if ((camera.cullingMask & mask) == 0) { if (renderPaths.ContainsKey(camera)) { var path_ = renderPaths[camera]; path_.Dispose(); renderPaths.Remove(camera); } return; } // GC renderpaths bool hasDisposed = false; foreach (var path_ in renderPaths) { path_.Value.LifeTime--; if (path_.Value.LifeTime < 0) { path_.Value.Dispose(); hasDisposed = true; } } // dispose renderpaths if (hasDisposed) { List <Camera> removed = new List <Camera>(); foreach (var path_ in renderPaths) { if (path_.Value.LifeTime >= 0) { continue; } removed.Add(path_.Key); } foreach (var r in removed) { renderPaths.Remove(r); } } RenderPath path; if (renderPaths.ContainsKey(camera)) { path = renderPaths[camera]; } else { // render path doesn't exists, create a render path path = new RenderPath(camera, cameraEvent, renderPaths.Count); path.Init(EffekseerRendererUtils.IsDistortionEnabled); renderPaths.Add(camera, path); } if (!path.IsValid()) { path.Dispose(); path.Init(EffekseerRendererUtils.IsDistortionEnabled); } path.Update(); path.LifeTime = 60; Plugin.EffekseerSetRenderingCameraCullingMask(path.renderId, camera.cullingMask); // assign a dinsotrion texture if (path.renderTexture) { Plugin.EffekseerSetBackGroundTexture(path.renderId, path.renderTexture.GetNativeTexturePtr()); } else { Plugin.EffekseerSetBackGroundTexture(path.renderId, IntPtr.Zero); } // update view matrixes Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); // Reset command buffer path.commandBuffer.Clear(); path.materiaProps.Reset(); // generate render events on this thread Plugin.EffekseerRenderBack(path.renderId); // if memory is lacked, reallocate memory while (Plugin.GetUnityRenderParameterCount() > 0 && Plugin.GetUnityRenderVertexBufferCount() > path.computeBufferTemp.Length) { path.ReallocateComputeBuffer(); } RenderInternal(path.commandBuffer, path.computeBufferTemp, path.computeBufferBack, path.materiaProps, path.renderTexture); // Distortion if (EffekseerRendererUtils.IsDistortionEnabled && (path.renderTexture != null || dstID.HasValue || dstIdentifier.HasValue)) { // Add a blit command that copy to the distortion texture if (dstID.HasValue) { path.commandBuffer.Blit(dstID.Value, path.renderTexture); path.commandBuffer.SetRenderTarget(dstID.Value); } else if (dstIdentifier.HasValue) { path.commandBuffer.Blit(dstIdentifier.Value, path.renderTexture); path.commandBuffer.SetRenderTarget(dstIdentifier.Value); } else { path.commandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, path.renderTexture); path.commandBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); } } Plugin.EffekseerRenderFront(path.renderId); // if memory is lacked, reallocate memory while (Plugin.GetUnityRenderParameterCount() > 0 && Plugin.GetUnityRenderVertexBufferCount() > path.computeBufferTemp.Length) { path.ReallocateComputeBuffer(); } RenderInternal(path.commandBuffer, path.computeBufferTemp, path.computeBufferFront, path.materiaProps, path.renderTexture); }
public Viewport(Scene scene, Camera camera, Urho.IntRect rect, RenderPath renderPath) : this(Application.CurrentContext, scene, camera, rect, renderPath) {}
void OnPreCullEvent(Camera camera) { #if UNITY_EDITOR if (Array.IndexOf<Camera>(SceneView.GetAllSceneCameras(), camera) >= 0) { // シーンビューのカメラはチェック if (this.drawInSceneView == false) { return; } } else if (Camera.current.isActiveAndEnabled == false) { // シーンビュー以外のエディタカメラは除外 return; } #endif RenderPath path; if (renderPaths.ContainsKey(camera)) { // レンダーパスが有れば使う path = renderPaths[camera]; } else { // 無ければ作成 path = new RenderPath(); path.renderId = renderPaths.Count; path.cameraEvent = cameraEvent; // プラグイン描画するコマンドバッファを作成 path.commandBuffer = new CommandBuffer(); path.commandBuffer.IssuePluginEvent(Plugin.EffekseerGetRenderFunc(), path.renderId); // コマンドバッファをカメラに登録 camera.AddCommandBuffer(path.cameraEvent, path.commandBuffer); renderPaths.Add(camera, path); } // ビュー関連の行列を更新 Plugin.EffekseerSetProjectionMatrix(path.renderId, Utility.Matrix2Array( GL.GetGPUProjectionMatrix(camera.projectionMatrix, false))); Plugin.EffekseerSetCameraMatrix(path.renderId, Utility.Matrix2Array( camera.worldToCameraMatrix)); }
public unsafe void ProcessARFrame(ARSession session, ARFrame frame) { var arcamera = frame?.Camera; var transform = arcamera.Transform; var prj = arcamera.GetProjectionMatrix(UIInterfaceOrientation.LandscapeRight, new CoreGraphics.CGSize(Graphics.Width, Graphics.Height), 0.01f, 30f); //Urho accepts projection matrix in DirectX format (negative row3 + transpose) var urhoProjection = new Matrix4( prj.M11, prj.M21, -prj.M31, prj.M41, prj.M12, prj.M22, -prj.M32, prj.M42, prj.M13, prj.M23, -prj.M33, prj.M43, prj.M14, prj.M24, -prj.M34, prj.M44); Camera.SetProjection(urhoProjection); ApplyTransform(CameraNode, transform); if (!yuvTexturesInited) { var img = frame.CapturedImage; // texture for Y-plane; cameraYtexture = new Texture2D(); cameraYtexture.SetNumLevels(1); cameraYtexture.FilterMode = TextureFilterMode.Bilinear; cameraYtexture.SetAddressMode(TextureCoordinate.U, TextureAddressMode.Clamp); cameraYtexture.SetAddressMode(TextureCoordinate.V, TextureAddressMode.Clamp); cameraYtexture.SetSize((int)img.Width, (int)img.Height, Graphics.LuminanceFormat, TextureUsage.Dynamic); cameraYtexture.Name = nameof(cameraYtexture); ResourceCache.AddManualResource(cameraYtexture); // texture for UV-plane; cameraUVtexture = new Texture2D(); cameraUVtexture.SetNumLevels(1); cameraUVtexture.SetSize((int)img.GetWidthOfPlane(1), (int)img.GetHeightOfPlane(1), Graphics.LuminanceAlphaFormat, TextureUsage.Dynamic); cameraUVtexture.FilterMode = TextureFilterMode.Bilinear; cameraUVtexture.SetAddressMode(TextureCoordinate.U, TextureAddressMode.Clamp); cameraUVtexture.SetAddressMode(TextureCoordinate.V, TextureAddressMode.Clamp); cameraUVtexture.Name = nameof(cameraUVtexture); ResourceCache.AddManualResource(cameraUVtexture); RenderPath rp = new RenderPath(); rp.Load(ResourceCache.GetXmlFile("ARRenderPath.xml")); var cmd = rp.GetCommand(1); //see ARRenderPath.xml, second command. cmd->SetTextureName(TextureUnit.Diffuse, cameraYtexture.Name); //sDiffMap cmd->SetTextureName(TextureUnit.Normal, cameraUVtexture.Name); //sNormalMap var capturedImage = frame.CapturedImage; var nativeBounds = UIScreen.MainScreen.NativeBounds; float imageAspect = (float)capturedImage.Width / (float)capturedImage.Height; float screenAspect = (float)nativeBounds.Size.Height / (float)nativeBounds.Size.Width; cmd->SetShaderParameter("CameraScale", screenAspect / imageAspect); //rp.Append(CoreAssets.PostProcess.FXAA2); Viewport.RenderPath = rp; yuvTexturesInited = true; } if (ContinuesHitTestAtCenter) { LastHitTest = HitTest(); } // display tracking state (quality) DebugHud.AdditionalText = $"{arcamera.TrackingState}\n"; if (arcamera.TrackingStateReason != ARTrackingStateReason.None) { DebugHud.AdditionalText += arcamera.TrackingStateReason; } // see "Render with Realistic Lighting" // https://developer.apple.com/documentation/arkit/displaying_an_ar_experience_with_metal var ambientIntensity = (float)frame.LightEstimate.AmbientIntensity / 1000f; //Light.Brightness = 0.5f + ambientIntensity / 2; DebugHud.AdditionalText += "\nAmb: " + ambientIntensity.ToString("F1"); //use outside of InvokeOnMain? if (yuvTexturesInited) { UpdateBackground(frame); } // required! frame.Dispose(); }
// public Viewport(Context context) : this(Viewport_Viewport(context.NativeInstance), context) { } public Viewport(Context context, Scene scene, Camera camera, RenderPath renderPath) : this(Viewport_Viewport(context.NativeInstance, scene.NativeInstance, camera.NativeInstance, renderPath.NativeInstance), context) { }