Exemplo n.º 1
0
            protected override Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
            {
                // try to import the font from the original bitmap or ttf file
                Graphics.SpriteFont staticFont;
                try
                {
                    staticFont = OfflineRasterizedFontCompiler.Compile(FontDataFactory, Parameters, colorspace == ColorSpace.Linear);
                }
                catch (FontNotFoundException ex)
                {
                    commandContext.Logger.Error($"Font [{ex.FontName}] was not found on this machine.", ex);
                    return(Task.FromResult(ResultStatus.Failed));
                }

                // check that the font data is valid
                if (staticFont == null || staticFont.Textures.Count == 0)
                {
                    return(Task.FromResult(ResultStatus.Failed));
                }

                // save the data into the database
                var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService);

                assetManager.Save(Url, staticFont);

                // dispose textures allocated by the StaticFontCompiler
                foreach (var texture in staticFont.Textures)
                {
                    texture.Dispose();
                }

                return(Task.FromResult(ResultStatus.Successful));
            }
        protected override Task <bool> Initialize(EditorServiceGame editorGame)
        {
            game = (EntityHierarchyEditorGame)editorGame;

            // create the default font
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 8;
            defaultFont            = OfflineRasterizedFontCompiler.Compile(game.Services.GetService <IFontFactory>(), fontItem, game.GraphicsDevice.ColorSpace == ColorSpace.Linear);

            incrustBatch = new SpriteBatch(game.GraphicsDevice);

            // SpriteEffect will be used to draw camera incrust border
            spriteEffect = new EffectInstance(new Graphics.Effect(game.GraphicsDevice, SpriteEffect.Bytecode));
            spriteEffect.Parameters.Set(TexturingKeys.Texture0, game.GraphicsDevice.GetSharedWhiteTexture());
            spriteEffect.UpdateEffect(game.GraphicsDevice);

            borderPipelineState = new MutablePipelineState(game.GraphicsDevice);
            borderPipelineState.State.RootSignature   = spriteEffect.RootSignature;
            borderPipelineState.State.EffectBytecode  = spriteEffect.Effect.Bytecode;
            borderPipelineState.State.InputElements   = VertexPositionTexture.Layout.CreateInputElements();
            borderPipelineState.State.PrimitiveType   = PrimitiveType.LineStrip;
            borderPipelineState.State.RasterizerState = RasterizerStates.CullNone;

            unsafe
            {
                var borderVertices = new[]
                {
                    new VertexPositionTexture(new Vector3(0.0f, 0.0f, 0.0f), Vector2.Zero),
                    new VertexPositionTexture(new Vector3(0.0f, 1.0f, 0.0f), Vector2.Zero),
                    new VertexPositionTexture(new Vector3(1.0f, 1.0f, 0.0f), Vector2.Zero),
                    new VertexPositionTexture(new Vector3(1.0f, 0.0f, 0.0f), Vector2.Zero),
                    new VertexPositionTexture(new Vector3(0.0f, 0.0f, 0.0f), Vector2.Zero),
                    new VertexPositionTexture(new Vector3(0.0f, 1.0f, 0.0f), Vector2.Zero), // extra vertex so that left-top corner is not missing (likely due to rasterization rule)
                };

                fixed(VertexPositionTexture *borderVerticesPtr = borderVertices)
                borderVertexBuffer = Graphics.Buffer.Vertex.New(game.GraphicsDevice, new DataPointer(borderVerticesPtr, VertexPositionTexture.Size * borderVertices.Length));
            }

            var editorTopLevel = game.EditorSceneSystem.GraphicsCompositor.Game as EditorTopLevelCompositor;

            if (editorTopLevel != null)
            {
                // Display it as incrust
                editorTopLevel.PostGizmoCompositors.Add(renderIncrustRenderer = new RenderIncrustRenderer(this));
            }

            Services.Get <IEditorGameEntitySelectionService>().SelectionUpdated += UpdateModifiedEntitiesList;

            return(Task.FromResult(true));
        }
Exemplo n.º 3
0
        /// <inheritdoc />
        protected override async Task LoadContent()
        {
            await base.LoadContent();

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 22;
            DefaultFont            = OfflineRasterizedFontCompiler.Compile(Font, fontItem, GraphicsDevice.ColorSpace == ColorSpace.Linear);

            previewScene = new Scene();

            // create and set the main scene instance
            SceneSystem.SceneInstance = new SceneInstance(Services, previewScene, ExecutionMode.Preview);

            // add thumbnail builder and preview script to scheduler
            Script.AddTask(ProcessPreviewRequestsTask);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Generate a precompiled sprite font from the current sprite font asset.
        /// </summary>
        /// <param name="asset">The sprite font asset</param>
        /// <param name="sourceAsset">The source sprite font asset item</param>
        /// <param name="texturePath">The path of the source texture</param>
        /// <param name="srgb">Indicate if the generated texture should be srgb</param>
        /// <returns>The precompiled sprite font asset</returns>
        public static PrecompiledSpriteFontAsset GeneratePrecompiledSpriteFont(this SpriteFontAsset asset, AssetItem sourceAsset, string texturePath, bool srgb)
        {
            var staticFont = (OfflineRasterizedSpriteFont)OfflineRasterizedFontCompiler.Compile(FontDataFactory, asset, srgb);

            var referenceToSourceFont = new AssetReference(sourceAsset.Id, sourceAsset.Location);
            var glyphs   = new List <Glyph>(staticFont.CharacterToGlyph.Values);
            var textures = staticFont.Textures;

            var imageType       = ImageFileType.Png;
            var textureFileName = new UFile(texturePath).GetFullPathWithoutExtension() + imageType.ToFileExtension();

            if (textures != null && textures.Count > 0)
            {
                // save the texture   TODO support for multi-texture
                using (var stream = File.OpenWrite(textureFileName))
                    staticFont.Textures[0].GetSerializationData().Image.Save(stream, imageType);
            }

            var precompiledAsset = new PrecompiledSpriteFontAsset
            {
                Glyphs             = glyphs,
                Size               = asset.FontType.Size,
                Style              = asset.FontSource.Style,
                OriginalFont       = referenceToSourceFont,
                FontDataFile       = textureFileName,
                BaseOffset         = staticFont.BaseOffsetY,
                DefaultLineSpacing = staticFont.DefaultLineSpacing,
                ExtraSpacing       = staticFont.ExtraSpacing,
                ExtraLineSpacing   = staticFont.ExtraLineSpacing,
                DefaultCharacter   = asset.DefaultCharacter,
                FontName           = asset.FontSource.GetFontName(),
                IsPremultiplied    = asset.FontType.IsPremultiplied,
                IsSrgb             = srgb
            };

            return(precompiledAsset);
        }
Exemplo n.º 5
0
        protected override Entity Create()
        {
            base.Create();

            var entity = new Entity("Space Marker");

            cameraComponent = new CameraComponent
            {
                UseCustomAspectRatio = true,
                AspectRatio          = 1.0f,
                NearClipPlane        = 0.1f,
                FarClipPlane         = 1000.0f,
                UseCustomViewMatrix  = true,
                VerticalFieldOfView  = VerticalFieldOfView
            };
            entity.Add(cameraComponent);

            // Add a renderer on the left bottom size
            var cameraOrientationGizmoRenderStage = new RenderStage("CameraOrientationGizmo", "Main");

            game.EditorSceneSystem.GraphicsCompositor.RenderStages.Add(cameraOrientationGizmoRenderStage);

            var meshRenderFeature = game.EditorSceneSystem.GraphicsCompositor.RenderFeatures.OfType <MeshRenderFeature>().First();

            meshRenderFeature.RenderStageSelectors.Add(new SimpleGroupToRenderStageSelector
            {
                EffectName  = EditorGraphicsCompositorHelper.EditorForwardShadingEffect,
                RenderGroup = SpaceMarkerGroupMask,
                RenderStage = cameraOrientationGizmoRenderStage
            });

            var editorCompositor = (EditorTopLevelCompositor)game.EditorSceneSystem.GraphicsCompositor.Game;

            editorCompositor.PostGizmoCompositors.Add(new ClearRenderer {
                ClearFlags = ClearRendererFlags.DepthOnly
            });
            editorCompositor.PostGizmoCompositors.Add(new GizmoViewportRenderer
            {
                Name             = "Render Spacemarker",
                ViewportSize     = ViewportSize,
                ViewportPosition = new Vector2(0.0f, 1.0f),
                Camera           = cameraComponent,
                Content          = new SceneRendererCollection
                {
                    new SingleStageRenderer {
                        RenderStage = cameraOrientationGizmoRenderStage
                    },
                    new DelegateSceneRenderer(RenderSpaceMarkerAxisNames),
                },
            });

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 8;
            defaultFont            = OfflineRasterizedFontCompiler.Compile(Services.GetService <IFontFactory>(), fontItem, GraphicsDevice.ColorSpace == ColorSpace.Linear);

            // create the sprite batch use to draw text
            spriteBatch = new SpriteBatch(GraphicsDevice)
            {
                DefaultDepth = 1
            };

            var rotations = new[] { Vector3.Zero, new Vector3(0, 0, MathUtil.Pi / 2), new Vector3(0, -MathUtil.Pi / 2f, 0) };
            var coneMesh  = GeometricPrimitive.Cone.New(GraphicsDevice, ConeRadius, ConeHeigth, GizmoTessellation).ToMeshDraw();
            var bodyMesh  = GeometricPrimitive.Cylinder.New(GraphicsDevice, BodyLength, BodyRadius, GizmoTessellation).ToMeshDraw();

            // create the axis arrows
            for (int axis = 0; axis < 3; ++axis)
            {
                var material   = GetAxisDefaultMaterial(axis);
                var coneEntity = new Entity("ArrowCone" + axis)
                {
                    new ModelComponent {
                        Model = new Model {
                            material, new Mesh {
                                Draw = coneMesh
                            }
                        }, RenderGroup = RenderGroup
                    }
                };
                var bodyEntity = new Entity("ArrowBody" + axis)
                {
                    new ModelComponent {
                        Model = new Model {
                            material, new Mesh {
                                Draw = bodyMesh
                            }
                        }, RenderGroup = RenderGroup
                    }
                };

                coneEntity.Transform.Position.X       = BodyLength + ConeHeigth * 0.5f;
                bodyEntity.Transform.Position.X       = BodyLength / 2;
                coneEntity.Transform.Rotation         = Quaternion.RotationZ(-MathUtil.Pi / 2);
                bodyEntity.Transform.RotationEulerXYZ = -MathUtil.Pi / 2 * Vector3.UnitZ;

                // create the arrow entity composed of the cone and bode
                var arrowEntity = new Entity("ArrowEntity" + axis);
                arrowEntity.Transform.Children.Add(coneEntity.Transform);
                arrowEntity.Transform.Children.Add(bodyEntity.Transform);
                arrowEntity.Transform.RotationEulerXYZ = rotations[axis];

                // Add the arrow entity to the gizmo entity
                entity.AddChild(arrowEntity);
            }

            return(entity);
        }
Exemplo n.º 6
0
        public ThumbnailGenerator(EffectCompilerBase effectCompiler)
        {
            // create base services
            Services = new ServiceRegistry();
            Services.AddService(MicrothreadLocalDatabases.ProviderService);
            ContentManager = new ContentManager(Services);
            Services.AddService <IContentManager>(ContentManager);
            Services.AddService(ContentManager);

            GraphicsDevice      = GraphicsDevice.New();
            GraphicsContext     = new GraphicsContext(GraphicsDevice);
            GraphicsCommandList = GraphicsContext.CommandList;
            Services.AddService(GraphicsContext);
            sceneSystem = new SceneSystem(Services);
            Services.AddService(sceneSystem);
            fontSystem = new GameFontSystem(Services);
            Services.AddService(fontSystem.FontSystem);
            Services.AddService <IFontFactory>(fontSystem.FontSystem);

            GraphicsDeviceService = new GraphicsDeviceServiceLocal(Services, GraphicsDevice);
            Services.AddService(GraphicsDeviceService);

            var uiSystem = new UISystem(Services);

            Services.AddService(uiSystem);

            var physicsSystem = new Bullet2PhysicsSystem(Services);

            Services.AddService <IPhysicsSystem>(physicsSystem);

            gameSystems = new GameSystemCollection(Services)
            {
                fontSystem, uiSystem, physicsSystem
            };
            Services.AddService <IGameSystemCollection>(gameSystems);
            Simulation.DisableSimulation = true; //make sure we do not simulate physics within the editor

            // initialize base services
            gameSystems.Initialize();

            // create remaining services
            EffectSystem = new EffectSystem(Services);
            Services.AddService(EffectSystem);

            gameSystems.Add(EffectSystem);
            gameSystems.Add(sceneSystem);
            EffectSystem.Initialize();

            // Mount the same database for the cache
            EffectSystem.Compiler = EffectCompilerFactory.CreateEffectCompiler(effectCompiler.FileProvider, EffectSystem);

            // Deactivate the asynchronous effect compilation
            ((EffectCompilerCache)EffectSystem.Compiler).CompileEffectAsynchronously = false;

            // load game system content
            gameSystems.LoadContent();

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = 22;
            DefaultFont            = OfflineRasterizedFontCompiler.Compile(fontSystem.FontSystem, fontItem, true);

            // create utility members
            nullGameTime = new GameTime();
            SpriteBatch  = new SpriteBatch(GraphicsDevice);
            UIBatch      = new UIBatch(GraphicsDevice);

            // create the pipeline
            SetUpPipeline();
        }
Exemplo n.º 7
0
        protected override Entity Create()
        {
            base.Create();

            DefaultMaterial         = CreateUniformColorMaterial(Color.White);
            ElementSelectedMaterial = CreateUniformColorMaterial(Color.Gold);

            var entity = new Entity("View Gizmo");

            cameraComponent = new CameraComponent
            {
                UseCustomAspectRatio = true,
                AspectRatio          = 1.0f,
                NearClipPlane        = 0.1f,
                FarClipPlane         = 1000.0f,
                UseCustomViewMatrix  = true,
                VerticalFieldOfView  = VerticalFieldOfView
            };
            entity.Add(cameraComponent);

            // create the default fonts
            var fontItem = OfflineRasterizedSpriteFontFactory.Create();

            fontItem.FontType.Size = FontSize;
            defaultFont            = OfflineRasterizedFontCompiler.Compile(Services.GetService <IFontFactory>(), fontItem, GraphicsDevice.ColorSpace == ColorSpace.Linear);

            // create the sprite batch use to draw text
            spriteBatch = new SpriteBatch(GraphicsDevice)
            {
                DefaultDepth = 1
            };

            // Add a renderer on the top right size
            var cameraOrientationGizmoRenderStage = new RenderStage("CameraOrientationGizmo", "Main");

            game.EditorSceneSystem.GraphicsCompositor.RenderStages.Add(cameraOrientationGizmoRenderStage);

            var meshRenderFeature = game.EditorSceneSystem.GraphicsCompositor.RenderFeatures.OfType <MeshRenderFeature>().First();

            meshRenderFeature.RenderStageSelectors.Add(new SimpleGroupToRenderStageSelector
            {
                EffectName  = EditorGraphicsCompositorHelper.EditorForwardShadingEffect,
                RenderGroup = ViewGizmoGroupMask,
                RenderStage = cameraOrientationGizmoRenderStage
            });

            var editorCompositor = (EditorTopLevelCompositor)game.EditorSceneSystem.GraphicsCompositor.Game;

            editorCompositor.PostGizmoCompositors.Add(new ClearRenderer {
                ClearFlags = ClearRendererFlags.DepthOnly
            });
            editorCompositor.PostGizmoCompositors.Add(gizmoViewportRenderer = new GizmoViewportRenderer
            {
                Name             = "Render Camera Orientation",
                ViewportSize     = ViewportSize,
                ViewportPosition = new Vector2(1.0f, 0.0f),
                Camera           = cameraComponent,
                Content          = new SceneRendererCollection
                {
                    new SingleStageRenderer {
                        RenderStage = cameraOrientationGizmoRenderStage
                    },
                    new DelegateSceneRenderer(RenderFaceNames),
                },
            });

            var cubeMesh = GeometricPrimitive.Cube.New(GraphicsDevice).ToMeshDraw();

            int i = 0;

            for (var z = -1; z <= 1; z++)
            {
                for (var y = -1; y <= 1; y++)
                {
                    for (var x = -1; x <= 1; x++)
                    {
                        if (x == 0 && y == 0 && z == 0)
                        {
                            continue;
                        }

                        var cubeEntity = new Entity("CubeEntity" + i++)
                        {
                            new ModelComponent {
                                Model = new Model {
                                    x == 0 ? ElementSelectedMaterial : DefaultMaterial, new Mesh {
                                        Draw = cubeMesh
                                    }
                                }, RenderGroup = RenderGroup
                            }
                        };

                        cubeEntity.Transform.Scale    = new Vector3(x == 0 ? InnerExtent * 2 : Border, y == 0 ? InnerExtent * 2 : Border, z == 0 ? InnerExtent * 2 : Border);
                        cubeEntity.Transform.Position = new Vector3(x, y, z) * (InnerExtent + Border / 2);

                        entity.AddChild(cubeEntity);
                        entities.Add(cubeEntity);
                    }
                }
            }

            return(entity);
        }