void Initialize()
        {
            TalkerName = TextGenerator.GenerateRandom(Datastructures.SelectRandom(Faction.Race.NameTemplates).ToArray());
            Tabs = new Dictionary<string, GUIComponent>();
            GUI = new DwarfGUI(Game, Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Default),
                Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Title),
                Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Small), Input)
            {
                DebugDraw = false
            };
            IsInitialized = true;
            Drawer = new Drawer2D(Game.Content, Game.GraphicsDevice);
            MainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };

            Layout = new GridLayout(GUI, MainWindow, 11, 4);
            Layout.UpdateSizes();

            Talker = new SpeakerComponent(GUI, Layout, new Animation(Faction.Race.TalkAnimation));
            Layout.SetComponentPosition(Talker, 0, 0, 4, 4);

            DialougeSelector = new ListSelector(GUI, Layout)
            {
                Mode = ListItem.SelectionMode.ButtonList,
                DrawPanel = false,
                Label = ""
            };
            DialougeSelector.OnItemSelected += DialougeSelector_OnItemSelected;
            Layout.SetComponentPosition(DialougeSelector, 2, 2, 2, 10);

            Button back = new Button(GUI, Layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow));
            Layout.SetComponentPosition(back, 0, 10, 1, 1);
            back.OnClicked += back_OnClicked;

            DialougeTree = new SpeechNode()
            {
                Text = GetGreeting(),
                Actions = new List<SpeechNode.SpeechAction>()
                {
                    new SpeechNode.SpeechAction()
                    {
                        Text = "Let's trade.",
                        Action = WaitForTrade
                    },
                    new SpeechNode.SpeechAction()
                    {
                        Text = "Goodbye.",
                        Action = () => SpeechNode.Echo(new SpeechNode()
                        {
                            Text = GetFarewell(),
                            Actions = new List<SpeechNode.SpeechAction>()
                        })
                    }
                }
            };

            Transition(DialougeTree);
            Politics.HasMet = true;

            PlayerFation.AddResources(new ResourceAmount(ResourceLibrary.ResourceType.Mana, 64));
        }
Exemple #2
0
        private void Draw(GraphicsDevice graphics, DwarfTime time)
        {
            if (DwarfGame.SpriteBatch.IsDisposed)
            {
                return;
            }

            if (Tiles.IsDisposed)
            {
                CreateAssets();
            }

            Bloom.BeginDraw();
            try
            {
                graphics.Clear(Color.SkyBlue);
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               DepthStencilState.Default, RasterizerState.CullNone, null, Matrix.Identity);


                Rectangle screenRect = graphics.Viewport.Bounds;

                int maxX = screenRect.Width / TileSize + 2;
                int maxY = screenRect.Width / TileSize;


                float t = (float)time.TotalRealTime.TotalSeconds;

                float offsetX = t * 2.0f;
                float offsetY = 0.0f;

                float st = (float)Math.Abs(Math.Sin(t));

                float lava     = LavaHeight;
                int   backSize = 2;

                for (int ix = 0; ix < maxX * backSize; ix++)
                {
                    float x = ix + (int)(offsetX * 0.6f);

                    float height = Noise.Noise(x * HeightScale * 3, 0, 100) * 0.5f + 0.6f;
                    for (int iy = 0; iy < maxY * backSize; iy++)
                    {
                        float y           = iy + (int)offsetY;
                        float normalizedY = (1.0f) - (float)y / (float)(maxY * backSize);

                        if (normalizedY < height)
                        {
                            float tileX = ix * (TileSize / backSize) - ((offsetX * 0.6f) * (TileSize / backSize)) % (TileSize / backSize);
                            float tileY = iy * (TileSize / backSize);

                            Drawer2D.FillRect(DwarfGame.SpriteBatch, new Rectangle((int)tileX, (int)tileY, TileSize / backSize, TileSize / backSize),
                                              new Color((int)(Color.SkyBlue.R * normalizedY * 0.8f), (int)(Color.SkyBlue.G * normalizedY * 0.8f),
                                                        (int)(Color.SkyBlue.B * normalizedY)));
                        }
                    }
                }


                for (int ix = 0; ix < maxX; ix++)
                {
                    float x      = ix + (int)offsetX;
                    float height = Noise.Noise(x * HeightScale, 0, 0) * 0.8f + MinHeight;
                    for (int iy = 0; iy < maxY; iy++)
                    {
                        float y           = iy + (int)offsetY;
                        float normalizedY = (1.0f) - (float)y / (float)maxY;

                        if (Math.Abs(normalizedY - height) < 0.01f)
                        {
                            Color tint = new Color(normalizedY, normalizedY, normalizedY);

                            RenderTile(Grass, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                        }
                        else if (normalizedY > height - 0.1f && normalizedY < height)
                        {
                            Color tint = new Color((float)Math.Pow(normalizedY, 1.5f), (float)Math.Pow(normalizedY, 1.6f),
                                                   normalizedY);

                            RenderTile(Soil, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                        }
                        else if (normalizedY < height)
                        {
                            float caviness = Noise.Noise(x * CaveScale, y * CaveScale, 0);

                            if (caviness < CaveThreshold)
                            {
                                TerrainElement?oreFound = null;

                                int i = 0;
                                foreach (TerrainElement ore in Ores)
                                {
                                    i++;
                                    float oreNess = Noise.Noise(x * ore.SpawnScale, y * ore.SpawnScale, i);

                                    if (oreNess > ore.SpawnThreshold)
                                    {
                                        oreFound = ore;
                                    }
                                }

                                Color tint = new Color((float)Math.Pow(normalizedY, 1.5f) * 0.5f,
                                                       (float)Math.Pow(normalizedY, 1.6f) * 0.5f, normalizedY * 0.5f);

                                if (oreFound == null)
                                {
                                    RenderTile(Substrate, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                                }
                                else
                                {
                                    RenderTile(oreFound.Value, DwarfGame.SpriteBatch, ix, iy, offsetX, t, tint);
                                }
                            }
                            else
                            {
                                if (normalizedY < lava)
                                {
                                    float glowiness = Noise.Noise(x * CaveScale * 2, y * CaveScale * 2, t);
                                    RenderTile(Lava, DwarfGame.SpriteBatch, ix, iy, offsetX, t,
                                               new Color(0.5f * glowiness + 0.5f, 0.7f * glowiness + 0.3f * st, glowiness));
                                }
                                else
                                {
                                    RenderTile(Cave, DwarfGame.SpriteBatch, ix, iy, offsetX, t,
                                               new Color((float)Math.Pow(normalizedY, 1.5f) * (1.0f - caviness) * 0.8f,
                                                         (float)Math.Pow(normalizedY, 1.6f) * (1.0f - caviness) * 0.8f,
                                                         normalizedY * (1.0f - caviness)));
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                DwarfGame.SpriteBatch.End();
            }

            Bloom.Draw(time.ToRealTime());
        }
Exemple #3
0
 public override void Render()
 {
     Drawer2D.DrawText(Text, Position, Tint, Color.Transparent);
 }
Exemple #4
0
 public override void Render(SpriteBatch batch, Camera camera, Viewport viewport)
 {
     Drawer2D.FillRect(batch, Bounds, FillColor);
     Drawer2D.DrawRect(batch, Bounds, StrokeColor, StrokeWeight);
 }
        public override IEnumerable <Act.Status> Run()
        {
            if (Spell.IsResearched)
            {
                Creature.CurrentCharacterMode  = CharacterMode.Idle;
                Creature.OverrideCharacterMode = false;
                yield return(Status.Success);

                yield break;
            }
            Timer   starParitcle  = new Timer(0.5f, false);
            float   totalResearch = 0.0f;
            Sound3D sound         = null;

            while (!Spell.IsResearched)
            {
                Creature.CurrentCharacterMode  = CharacterMode.Attacking;
                Creature.OverrideCharacterMode = true;
                Creature.Sprite.ReloopAnimations(CharacterMode.Attacking);
                float research = Creature.Stats.BuffedInt * 0.25f * DwarfTime.Dt;
                Spell.ResearchProgress    += research;
                totalResearch             += research;
                Creature.Physics.Velocity *= 0;
                Drawer2D.DrawLoadBar(Creature.World.Camera, Creature.Physics.Position, Color.Cyan, Color.Black, 64, 4, Spell.ResearchProgress / Spell.ResearchTime);
                if ((int)totalResearch > 0)
                {
                    if (sound == null || sound.EffectInstance.IsDisposed || sound.EffectInstance.State == SoundState.Stopped)
                    {
                        sound = SoundManager.PlaySound(ContentPaths.Audio.Oscar.sfx_ic_dwarf_magic_research,
                                                       Creature.AI.Position,
                                                       true);
                    }
                    //SoundManager.PlaySound(ContentPaths.Audio.tinkle, Creature.AI.Position, true);
                    Creature.AI.AddXP((int)(totalResearch));
                    totalResearch = 0.0f;
                }

                if (Spell.ResearchProgress >= Spell.ResearchTime)
                {
                    Creature.Manager.World.MakeAnnouncement(
                        new Gui.Widgets.QueuedAnnouncement
                    {
                        Text = String.Format("{0} ({1}) discovered the {2} spell!",
                                             Creature.Stats.FullName,
                                             Creature.Stats.CurrentLevel.Name, Spell.Spell.Name),
                        ClickAction = (gui, sender) => Agent.ZoomToMe()
                    });

                    SoundManager.PlaySound(ContentPaths.Audio.Oscar.sfx_gui_positive_generic, 0.15f);
                }

                starParitcle.Update(DwarfTime.LastTime);
                if (starParitcle.HasTriggered)
                {
                    Creature.Manager.World.ParticleManager.Trigger("star_particle", Creature.AI.Position, Color.White, 3);
                }
                yield return(Status.Running);
            }

            if (sound != null)
            {
                sound.Stop();
            }
            Creature.AI.AddThought(Thought.ThoughtType.Researched);
            Creature.OverrideCharacterMode = false;
            Creature.CurrentCharacterMode  = CharacterMode.Idle;
            yield return(Status.Success);

            yield break;
        }
Exemple #6
0
        private void GenerateData(GraphicsDevice device, float sizeX, float sizeY, float resolution)
        {
            if (banners.ContainsKey(Logo))
            {
                return;
            }

            int        numCellsX   = (int)(sizeX / resolution);
            int        numCellsY   = (int)(sizeY / resolution);
            int        numVerts    = (numCellsX + 1) * (numCellsY + 1);
            int        numIndices  = numCellsX * numCellsY * 6;
            float      aspectRatio = sizeX / sizeY;
            const int  height      = 36;
            int        width       = (int)(aspectRatio * height);
            BannerData data        = new BannerData()
            {
                Mesh    = new VertexBuffer(device, ExtendedVertex.VertexDeclaration, numVerts, BufferUsage.None),
                Indices = new IndexBuffer(device, typeof(short), numIndices, BufferUsage.None),
                Texture = new RenderTarget2D(device, width, height),
                Verts   = new ExtendedVertex[numVerts],
                SizeX   = sizeX,
                SizeY   = sizeY,
                Idx     = new ushort[numIndices]
            };

            banners[Logo] = data;
            for (int i = 0, y = 0; y <= numCellsY; y++)
            {
                for (int x = 0; x <= numCellsX; x++, i++)
                {
                    data.Verts[i] = new ExtendedVertex(new Vector3(0, y * resolution - sizeY * 0.5f, 0), Color.White, Color.White,
                                                       new Vector2((float)x / (float)numCellsX, 1.0f - (float)y / (float)numCellsY), new Vector4(0, 0, 1, 1));
                }
            }

            for (ushort ti = 0, vi = 0, y = 0; y < numCellsY; y++, vi++)
            {
                for (int x = 0; x < numCellsX; x++, ti += 6, vi++)
                {
                    data.Idx[ti]     = vi;
                    data.Idx[ti + 3] = data.Idx[ti + 2] = (ushort)(vi + 1);
                    data.Idx[ti + 4] = data.Idx[ti + 1] = (ushort)(vi + numCellsX + 1);
                    data.Idx[ti + 5] = (ushort)(vi + numCellsX + 2);
                }
            }
            var oldView = device.Viewport;

            data.Mesh.SetData(data.Verts);
            data.Indices.SetData(data.Idx);
            device.SetRenderTarget(data.Texture);
            device.Viewport = new Viewport(0, 0, width, height); // Must set viewport after target bound.
            device.Clear(new Color(Logo.LogoBackgroundColor * 0.5f + Logo.LogoSymbolColor * 0.5f));
            Texture2D logoBg = TextureManager.GetTexture("newgui/logo-bg");
            Texture2D logoFg = TextureManager.GetTexture("newgui/logo-fg");
            int       bgIdx  = Logo.LogoBackground.Tile;
            int       bgX    = (bgIdx % (logoBg.Width / 32)) * 32;
            int       bgY    = (bgIdx / (logoBg.Width / 32)) * 32;
            int       fgIdx  = Logo.LogoSymbol.Tile;
            int       fgX    = (fgIdx % (logoFg.Width / 32)) * 32;
            int       fgY    = (fgIdx / (logoFg.Width / 32)) * 32;

            DwarfGame.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                        DepthStencilState.None, RasterizerState.CullNone);
            Drawer2D.DrawRect(DwarfGame.SpriteBatch, new Rectangle(1, 1, width - 1, height - 2), Color.Black, 2);
            DwarfGame.SpriteBatch.Draw(logoBg, new Rectangle(width / 2 - 16, height / 2 - 16, 32, 32), new Rectangle(bgX, bgY, 32, 32), new Color(Logo.LogoBackgroundColor));
            DwarfGame.SpriteBatch.Draw(logoFg, new Rectangle(width / 2 - 16, height / 2 - 16, 32, 32), new Rectangle(fgX, fgY, 32, 32), new Color(Logo.LogoSymbolColor));
            DwarfGame.SpriteBatch.End();
            device.SetRenderTarget(null);
            device.Indices = null;
            device.SetVertexBuffer(null);
            device.Viewport = oldView;
        }
Exemple #7
0
        /// <summary>
        /// Called when a frame is to be drawn to the screen
        /// </summary>
        /// <param name="gameTime">The current time</param>
        public void Render(DwarfTime gameTime)
        {
            if (!ShowingWorld)
            {
                return;
            }

#if RENDER_VOXEL_ICONS
            var voxels = VoxelLibrary.RenderIcons(GraphicsDevice, DefaultShader, ChunkManager, -1, -1, 32);
            using (var stream = new FileStream("voxels.png", FileMode.OpenOrCreate))
            {
                GraphicsDevice.SetRenderTarget(null);
                voxels.SaveAsPng(stream, voxels.Width, voxels.Height);
            }
#endif
            GamePerformance.Instance.StartTrackPerformance("Render - RENDER");
            GamePerformance.Instance.StartTrackPerformance("Render - Prep");

            var renderables = ComponentRenderer.EnumerateVisibleRenderables(ComponentManager.GetRenderables(),
                                                                            ChunkManager,
                                                                            Camera);

            // Controls the sky fog
            float x = (1.0f - Sky.TimeOfDay);
            x = x * x;
            DefaultShader.FogColor       = new Color(0.32f * x, 0.58f * x, 0.9f * x);
            DefaultShader.LightPositions = LightPositions;

            CompositeLibrary.Render(GraphicsDevice);
            CompositeLibrary.Update();
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            if (GameSettings.Default.UseDynamicShadows)
            {
                ChunkRenderer.RenderShadowmap(DefaultShader, GraphicsDevice, Shadows, Matrix.Identity, Tilesheet);
            }

            if (GameSettings.Default.UseLightmaps)
            {
                ChunkRenderer.RenderLightmaps(Camera, gameTime, GraphicsDevice, DefaultShader, Matrix.Identity);
            }

            // Computes the water height.
            float wHeight = WaterRenderer.GetVisibleWaterHeight(ChunkManager, Camera, GraphicsDevice.Viewport,
                                                                lastWaterHeight);
            lastWaterHeight = wHeight;

            // Draw reflection/refraction images
            WaterRenderer.DrawReflectionMap(renderables, gameTime, this, wHeight - 0.1f,
                                            GetReflectedCameraMatrix(wHeight),
                                            DefaultShader, GraphicsDevice);

            GamePerformance.Instance.StopTrackPerformance("Render - Prep");
            GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer");

            #region Draw Selection Buffer.

            if (SelectionBuffer == null)
            {
                SelectionBuffer = new SelectionBuffer(8, GraphicsDevice);
            }

            GraphicsDevice.RasterizerState   = RasterizerState.CullNone;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            Plane slicePlane = WaterRenderer.CreatePlane(SlicePlane, new Vector3(0, -1, 0), Camera.ViewMatrix, false);

            if (SelectionBuffer.Begin(GraphicsDevice))
            {
                // Draw the whole world, and make sure to handle slicing
                DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
                DefaultShader.ClippingEnabled = true;
                DefaultShader.View            = Camera.ViewMatrix;
                DefaultShader.Projection      = Camera.ProjectionMatrix;
                DefaultShader.World           = Matrix.Identity;

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Chunks");
                ChunkRenderer.RenderSelectionBuffer(DefaultShader, GraphicsDevice, Camera.ViewMatrix);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Chunks");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Components");
                ComponentRenderer.RenderSelectionBuffer(renderables, gameTime, ChunkManager, Camera,
                                                        DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Components");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Instances");
                NewInstanceManager.RenderInstances(GraphicsDevice, DefaultShader, Camera,
                                                   InstanceRenderer.RenderMode.SelectionBuffer);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Instances");

                SelectionBuffer.End(GraphicsDevice);

                GamePerformance.Instance.TrackValueType("SBUFFER RENDERED", true);
            }
            else
            {
                GamePerformance.Instance.TrackValueType("SBUFFER RENDERED", false);
            }


            #endregion

            GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer");
            GamePerformance.Instance.StartTrackPerformance("Render - BG Stuff");


            // Start drawing the bloom effect
            if (GameSettings.Default.EnableGlow)
            {
                bloom.BeginDraw();
            }

            // Draw the sky
            GraphicsDevice.Clear(DefaultShader.FogColor);
            DrawSky(gameTime, Camera.ViewMatrix, 1.0f, DefaultShader.FogColor);

            // Defines the current slice for the GPU
            float level = ChunkManager.ChunkData.MaxViewingLevel + 0.25f;
            if (level > VoxelConstants.ChunkSizeY)
            {
                level = 1000;
            }

            GamePerformance.Instance.StopTrackPerformance("Render - BG Stuff");
            GamePerformance.Instance.StartTrackPerformance("Render - Chunks");

            SlicePlane = level;

            DefaultShader.WindDirection = Weather.CurrentWind;
            DefaultShader.WindForce     = 0.0005f * (1.0f + (float)Math.Sin(Time.GetTotalSeconds() * 0.001f));
            // Draw the whole world, and make sure to handle slicing
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;
            //Blue ghost effect above the current slice.
            DefaultShader.GhostClippingEnabled = true;
            Draw3DThings(gameTime, DefaultShader, Camera.ViewMatrix);

            GamePerformance.Instance.StopTrackPerformance("Render - Chunks");


            // Now we want to draw the water on top of everything else
            DefaultShader.ClippingEnabled      = true;
            DefaultShader.GhostClippingEnabled = false;

            //ComponentManager.CollisionManager.DebugDraw();

            DefaultShader.View                 = Camera.ViewMatrix;
            DefaultShader.Projection           = Camera.ProjectionMatrix;
            DefaultShader.GhostClippingEnabled = true;
            // Now draw all of the entities in the game
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;

            GamePerformance.Instance.StartTrackPerformance("Render - Drawer3D");
            // Render simple geometry (boxes, etc.)
            Drawer3D.Render(GraphicsDevice, DefaultShader, Camera, DesignationDrawer, PlayerFaction.Designations, this);
            GamePerformance.Instance.StopTrackPerformance("Render - Drawer3D");

            GamePerformance.Instance.StartTrackPerformance("Render - Instances");

            DefaultShader.EnableShadows = GameSettings.Default.UseDynamicShadows;

            if (GameSettings.Default.UseDynamicShadows)
            {
                Shadows.BindShadowmapEffect(DefaultShader);
            }

            DefaultShader.View = Camera.ViewMatrix;
            NewInstanceManager.RenderInstances(GraphicsDevice, DefaultShader, Camera, InstanceRenderer.RenderMode.Normal);
            GamePerformance.Instance.StopTrackPerformance("Render - Instances");
            GamePerformance.Instance.StartTrackPerformance("Render - Components");

            ComponentRenderer.Render(renderables, gameTime, ChunkManager,
                                     Camera,
                                     DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader,
                                     ComponentRenderer.WaterRenderType.None, lastWaterHeight);

            GamePerformance.Instance.StopTrackPerformance("Render - Components");
            GamePerformance.Instance.StartTrackPerformance("Render - Tools");



            if (Master.CurrentToolMode == GameMaster.ToolMode.BuildZone ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildWall ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildObject)
            {
                DefaultShader.View       = Camera.ViewMatrix;
                DefaultShader.Projection = Camera.ProjectionMatrix;
                DefaultShader.SetTexturedTechnique();
                GraphicsDevice.BlendState = BlendState.NonPremultiplied;
                Master.Faction.CraftBuilder.Render(gameTime, GraphicsDevice, DefaultShader);
            }

            GamePerformance.Instance.StopTrackPerformance("Render - Tools");
            GamePerformance.Instance.StartTrackPerformance("Render - Water");


            WaterRenderer.DrawWater(
                GraphicsDevice,
                (float)gameTime.TotalGameTime.TotalSeconds,
                DefaultShader,
                Camera.ViewMatrix,
                GetReflectedCameraMatrix(wHeight),
                Camera.ProjectionMatrix,
                new Vector3(0.1f, 0.0f, 0.1f),
                Camera,
                ChunkManager);

            GamePerformance.Instance.StopTrackPerformance("Render - Water");
            GamePerformance.Instance.StartTrackPerformance("Render - Misc");


            DefaultShader.ClippingEnabled = false;

            if (GameSettings.Default.EnableGlow)
            {
                bloom.DrawTarget = UseFXAA ? fxaa.RenderTarget : null;

                if (UseFXAA)
                {
                    fxaa.Begin(DwarfTime.LastTime, fxaa.RenderTarget);
                }
                bloom.Draw(gameTime.ToGameTime());
                if (UseFXAA)
                {
                    fxaa.End(DwarfTime.LastTime, fxaa.RenderTarget);
                }
            }
            else if (UseFXAA)
            {
                fxaa.End(DwarfTime.LastTime, fxaa.RenderTarget);
            }

            RasterizerState rasterizerState = new RasterizerState()
            {
                ScissorTestEnable = true
            };


            //if (CompositeLibrary.Composites.ContainsKey("resources"))
            //    CompositeLibrary.Composites["resources"].DebugDraw(DwarfGame.SpriteBatch, 0, 0);
            //SelectionBuffer.DebugDraw(GraphicsDevice.Viewport.Bounds);
            try
            {
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               null, rasterizerState, null, Matrix.Identity);
                //DwarfGame.SpriteBatch.Draw(Shadows.ShadowTexture, Vector2.Zero, Color.White);
                if (IsCameraUnderwater())
                {
                    Drawer2D.FillRect(DwarfGame.SpriteBatch, GraphicsDevice.Viewport.Bounds, new Color(10, 40, 60, 200));
                }

                Drawer2D.Render(DwarfGame.SpriteBatch, Camera, GraphicsDevice.Viewport);

                IndicatorManager.Render(gameTime);
            }
            finally
            {
                DwarfGame.SpriteBatch.End();
            }

            Master.Render(Game, gameTime, GraphicsDevice);

            DwarfGame.SpriteBatch.GraphicsDevice.ScissorRectangle =
                DwarfGame.SpriteBatch.GraphicsDevice.Viewport.Bounds;


            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            GamePerformance.Instance.StopTrackPerformance("Render - Misc");
            GamePerformance.Instance.StopTrackPerformance("Render - RENDER");

            lock (ScreenshotLock)
            {
                foreach (Screenshot shot in Screenshots)
                {
                    TakeScreenshot(shot.FileName, shot.Resolution);
                }

                Screenshots.Clear();
            }
        }
Exemple #8
0
        protected override void LoadContent()
        {
            LogSentryBreadcrumb("Loading", "LoadContent was called.", BreadcrumbLevel.Info);
            AssetManager.Initialize(Content, GraphicsDevice, GameSettings.Current);


            //DwarfSprites.LayerLibrary.ConvertTestPSD();


            // Prepare GemGui
            if (GumInputMapper == null)
            {
                GumInputMapper = new Gui.Input.GumInputMapper(Window.Handle);
                GumInput       = new Gui.Input.Input(GumInputMapper);
            }

            GuiSkin = new RenderData(GraphicsDevice, Content);

            // Create console.
            ConsoleGui            = new Gui.Root(GuiSkin);
            ConsoleGui.SetMetrics = false;
            ConsoleGui.RootItem.AddChild(new Gui.Widgets.AutoGridPanel
            {
                Rows       = 2,
                Columns    = 4,
                AutoLayout = AutoLayout.DockFill
            });

            ConsoleGui.RootItem.Layout();
            if (_logwriter != null)
            {
                _logwriter.SetConsole(GetConsoleTile("LOG"));
            }

            Console.Out.WriteLine("Console created.");

            if (SoundManager.Content == null)
            {
                SoundManager.Content = Content;
                SoundManager.LoadDefaultSounds();
            }

            if (GameStateManager.StateStackIsEmpty)
            {
                LogSentryBreadcrumb("GameState", "There was nothing in the state stack. Starting over.");
                if (GameSettings.Current.DisplayIntro)
                {
                    GameStateManager.PushState(new IntroState(this));
                }
                else
                {
                    GameStateManager.PushState(new MainMenuState(this));
                }
            }

            ControlSettings.Load();
            Drawer2D.Initialize(Content, GraphicsDevice);
            ScreenSaver = new Terrain2D(this);

            base.LoadContent();
        }
        public void DrawHilites(
            DesignationSet Set,
            Action <Vector3, Vector3, Color, float, bool> DrawBoxCallback,
            Action <Vector3, VoxelType> DrawPhantomCallback)
        {
            var colorModulation = Math.Abs(Math.Sin(DwarfTime.LastTime.TotalGameTime.TotalSeconds * 2.0f));

            foreach (var properties in DesignationProperties)
            {
                properties.Value.ModulatedColor = new Color(
                    (byte)(MathFunctions.Clamp((float)(properties.Value.Color.R * colorModulation + 50), 0.0f, 255.0f)),
                    (byte)(MathFunctions.Clamp((float)(properties.Value.Color.G * colorModulation + 50), 0.0f, 255.0f)),
                    (byte)(MathFunctions.Clamp((float)(properties.Value.Color.B * colorModulation + 50), 0.0f, 255.0f)),
                    255);
            }

            foreach (var voxel in Set.EnumerateDesignations())
            {
                if ((voxel.Type & VisibleTypes) == voxel.Type)
                {
                    var props = DefaultProperties;
                    if (DesignationProperties.ContainsKey(voxel.Type))
                    {
                        props = DesignationProperties[voxel.Type];
                    }

                    var v = voxel.Voxel.Coordinate.ToVector3();
                    if (props.Icon != null)
                    {
                        Drawer2D.DrawSprite(props.Icon, v + Vector3.One * 0.5f, Vector2.One * 0.5f, Vector2.Zero, new Color(255, 255, 255, 100));
                    }

                    if (voxel.Type == DesignationType.Put) // Hate this.
                    {
                        DrawPhantomCallback(v, VoxelLibrary.GetVoxelType((voxel.Tag as short?).Value));
                    }
                    else
                    {
                        DrawBoxCallback(v, Vector3.One, props.ModulatedColor, props.LineWidth, true);
                    }
                }
            }

            foreach (var entity in Set.EnumerateEntityDesignations())
            {
                if ((entity.Type & VisibleTypes) == entity.Type)
                {
                    var props = DefaultProperties;
                    if (DesignationProperties.ContainsKey(entity.Type))
                    {
                        props = DesignationProperties[entity.Type];
                    }

                    entity.Body.SetTintRecursive(props.ModulatedColor);

                    // Todo: More consistent drawing?
                    if (entity.Type == DesignationType.Craft)
                    {
                        entity.Body.SetFlagRecursive(GameComponent.Flag.Visible, true);
                    }
                    else
                    {
                        var box = entity.Body.GetBoundingBox();
                        DrawBoxCallback(box.Min, box.Max - box.Min, props.ModulatedColor, props.LineWidth, false);
                    }

                    if (props.Icon != null)
                    {
                        Drawer2D.DrawSprite(props.Icon, entity.Body.Position + Vector3.One * 0.5f, Vector2.One * 0.5f, Vector2.Zero, new Color(255, 255, 255, 100));
                    }
                }
                else if (entity.Type == DesignationType.Craft) // Make the ghost object invisible if these designations are turned off.
                {
                    entity.Body.SetFlagRecursive(GameComponent.Flag.Visible, false);
                }
            }
        }
        void Initialize()
        {
            Envoy.TradeMoney = Faction.TradeMoney + MathFunctions.Rand(-100.0f, 100.0f);
            Envoy.TradeMoney = Math.Max(Envoy.TradeMoney, 0.0f);
            TalkerName       = TextGenerator.GenerateRandom(Datastructures.SelectRandom(Faction.Race.NameTemplates).ToArray());
            Tabs             = new Dictionary <string, GUIComponent>();
            GUI = new DwarfGUI(Game, Game.Content.Load <SpriteFont>(ContentPaths.Fonts.Default),
                               Game.Content.Load <SpriteFont>(ContentPaths.Fonts.Title),
                               Game.Content.Load <SpriteFont>(ContentPaths.Fonts.Small), Input)
            {
                DebugDraw = false
            };
            IsInitialized = true;
            Drawer        = new Drawer2D(Game.Content, Game.GraphicsDevice);
            MainWindow    = new GUIComponent(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };

            Layout = new GridLayout(GUI, MainWindow, 11, 4);
            Layout.UpdateSizes();

            Talker = new SpeakerComponent(GUI, Layout, new Animation(Faction.Race.TalkAnimation));
            Layout.SetComponentPosition(Talker, 0, 0, 4, 4);

            DialougeSelector = new ListSelector(GUI, Layout)
            {
                Mode        = ListItem.SelectionMode.ButtonList,
                DrawButtons = true,
                DrawPanel   = false,
                Label       = "",
                ItemHeight  = 35,
                Padding     = 5
            };
            DialougeSelector.OnItemSelected += DialougeSelector_OnItemSelected;
            Layout.SetComponentPosition(DialougeSelector, 2, 3, 1, 8);

            BackButton = new Button(GUI, Layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow));
            Layout.SetComponentPosition(BackButton, 2, 10, 1, 1);
            BackButton.OnClicked += back_OnClicked;
            BackButton.IsVisible  = false;
            DialougeTree          = new SpeechNode()
            {
                Text    = GetGreeting(),
                Actions = new List <SpeechNode.SpeechAction>()
                {
                    new SpeechNode.SpeechAction()
                    {
                        Text   = "Trade...",
                        Action = WaitForTrade
                    },
                    new SpeechNode.SpeechAction()
                    {
                        Text   = "Ask a question...",
                        Action = AskAQuestion
                    },
                    new SpeechNode.SpeechAction()
                    {
                        Text   = "Declare war!",
                        Action = DeclareWar
                    },
                    new SpeechNode.SpeechAction()
                    {
                        Text   = "Leave",
                        Action = () =>
                        {
                            BackButton.IsVisible = true;
                            if (Envoy != null)
                            {
                                Diplomacy.RecallEnvoy(Envoy);
                            }
                            return(SpeechNode.Echo(new SpeechNode()
                            {
                                Text = GetFarewell(),
                                Actions = new List <SpeechNode.SpeechAction>()
                            }));
                        }
                    }
                }
            };


            if (Politics.WasAtWar)
            {
                PreeTree = new SpeechNode()
                {
                    Text    = Datastructures.SelectRandom(Faction.Race.Speech.PeaceDeclarations),
                    Actions = new List <SpeechNode.SpeechAction>()
                    {
                        new SpeechNode.SpeechAction()
                        {
                            Text   = "Make peace with " + Faction.Name,
                            Action = () =>
                            {
                                if (!Politics.HasEvent("you made peace with us"))
                                {
                                    Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent()
                                    {
                                        Change      = 0.4f,
                                        Description = "you made peace with us",
                                        Duration    = new TimeSpan(4, 0, 0, 0),
                                        Time        = PlayState.Time.CurrentDate
                                    });
                                }
                                return(SpeechNode.Echo(DialougeTree));
                            }
                        },
                        new SpeechNode.SpeechAction()
                        {
                            Text   = "Continue the war with " + Faction.Name,
                            Action = DeclareWar
                        }
                    }
                };
                Transition(PreeTree);
                Politics.WasAtWar = false;
            }
            else
            {
                Transition(DialougeTree);
            }


            if (!Politics.HasMet)
            {
                Politics.HasMet = true;

                Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent()
                {
                    Change      = 0.0f,
                    Description = "we just met",
                    Duration    = new TimeSpan(1, 0, 0, 0),
                    Time        = PlayState.Time.CurrentDate
                });
            }

            Layout.UpdateSizes();
            Talker.TweenIn(Drawer2D.Alignment.Top, 0.25f);
            DialougeSelector.TweenIn(Drawer2D.Alignment.Right, 0.25f);
        }
Exemple #11
0
        /// <summary>
        /// Called when a frame is to be drawn to the screen
        /// </summary>
        /// <param name="gameTime">The current time</param>
        public void Render(DwarfTime gameTime)
        {
            if (!World.ShowingWorld)
            {
                return;
            }
            ValidateShader();
            var frustum     = Camera.GetDrawFrustum();
            var renderables = World.EnumerateIntersectingObjects(frustum,
                                                                 r => (Debugger.Switches.DrawInvisible || r.IsVisible) && !World.ChunkManager.IsAboveCullPlane(r.GetBoundingBox()));

            // Controls the sky fog
            float x = (1.0f - Sky.TimeOfDay);

            x = x * x;
            DefaultShader.FogColor       = new Color(0.32f * x, 0.58f * x, 0.9f * x);
            DefaultShader.LightPositions = LightPositions;

            CompositeLibrary.Render(GraphicsDevice);
            CompositeLibrary.Update();

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            if (lastWaterHeight < 0) // Todo: Seriously, every single frame??
            {
                lastWaterHeight = 0;
                foreach (var chunk in World.ChunkManager.ChunkMap)
                {
                    for (int y = 0; y < VoxelConstants.ChunkSizeY; y++)
                    {
                        if (chunk.Data.LiquidPresent[y] > 0)
                        {
                            lastWaterHeight = Math.Max(y + chunk.Origin.Y, lastWaterHeight);
                        }
                    }
                }
            }

            // Computes the water height.
            float wHeight = WaterRenderer.GetVisibleWaterHeight(World.ChunkManager, Camera, GraphicsDevice.Viewport,
                                                                lastWaterHeight);

            lastWaterHeight = wHeight;

            // Draw reflection/refraction images
            WaterRenderer.DrawReflectionMap(renderables, gameTime, World, wHeight - 0.1f,
                                            GetReflectedCameraMatrix(wHeight),
                                            DefaultShader, GraphicsDevice);


            #region Draw Selection Buffer.

            if (SelectionBuffer == null)
            {
                SelectionBuffer = new SelectionBuffer(8, GraphicsDevice);
            }

            GraphicsDevice.RasterizerState   = RasterizerState.CullNone;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            // Defines the current slice for the GPU
            var   level      = PersistentSettings.MaxViewingLevel >= World.WorldSizeInVoxels.Y ? 1000.0f : PersistentSettings.MaxViewingLevel + 0.25f;
            Plane slicePlane = WaterRenderer.CreatePlane(level, new Vector3(0, -1, 0), Camera.ViewMatrix, false);

            if (SelectionBuffer.Begin(GraphicsDevice))
            {
                // Draw the whole world, and make sure to handle slicing
                DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
                DefaultShader.ClippingEnabled = true;
                DefaultShader.View            = Camera.ViewMatrix;
                DefaultShader.Projection      = Camera.ProjectionMatrix;
                DefaultShader.World           = Matrix.Identity;

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Chunks");
                ChunkRenderer.RenderSelectionBuffer(DefaultShader, GraphicsDevice, Camera.ViewMatrix);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Chunks");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Components");
                ComponentRenderer.RenderSelectionBuffer(renderables, gameTime, World.ChunkManager, Camera,
                                                        DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Components");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Instances");
                InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera,
                                       InstanceRenderMode.SelectionBuffer);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Instances");

                SelectionBuffer.End(GraphicsDevice);
            }


            #endregion



            // Start drawing the bloom effect
            if (GameSettings.Current.EnableGlow)
            {
                bloom.BeginDraw();
            }

            // Draw the sky
            GraphicsDevice.Clear(DefaultShader.FogColor);
            DrawSky(gameTime, Camera.ViewMatrix, 1.0f, DefaultShader.FogColor);



            DefaultShader.FogEnd   = GameSettings.Current.ChunkDrawDistance;
            DefaultShader.FogStart = GameSettings.Current.ChunkDrawDistance * 0.8f;

            CaveView = CaveView * 0.9f + TargetCaveView * 0.1f;
            DefaultShader.WindDirection = World.Weather.CurrentWind;
            DefaultShader.WindForce     = 0.0005f * (1.0f + (float)Math.Sin(World.Time.GetTotalSeconds() * 0.001f));
            // Draw the whole world, and make sure to handle slicing
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;
            //Blue ghost effect above the current slice.
            DefaultShader.GhostClippingEnabled = true;
            Draw3DThings(gameTime, DefaultShader, Camera.ViewMatrix);


            // Now we want to draw the water on top of everything else
            DefaultShader.ClippingEnabled      = true;
            DefaultShader.GhostClippingEnabled = false;

            //ComponentManager.CollisionManager.DebugDraw();

            DefaultShader.View                 = Camera.ViewMatrix;
            DefaultShader.Projection           = Camera.ProjectionMatrix;
            DefaultShader.GhostClippingEnabled = true;
            // Now draw all of the entities in the game
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;

            // Render simple geometry (boxes, etc.)
            Drawer3D.Render(GraphicsDevice, DefaultShader, Camera, World.PersistentData.Designations, World);

            DefaultShader.EnableShadows = false;

            DefaultShader.View = Camera.ViewMatrix;

            ComponentRenderer.Render(renderables, gameTime, World.ChunkManager,
                                     Camera,
                                     DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader,
                                     ComponentRenderer.WaterRenderType.None, lastWaterHeight);
            InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera, InstanceRenderMode.Normal);

            WaterRenderer.DrawWater(
                GraphicsDevice,
                (float)gameTime.TotalGameTime.TotalSeconds,
                DefaultShader,
                Camera.ViewMatrix,
                GetReflectedCameraMatrix(wHeight),
                Camera.ProjectionMatrix,
                new Vector3(0.1f, 0.0f, 0.1f),
                Camera,
                World.ChunkManager);
            World.ParticleManager.Render(World, GraphicsDevice);
            DefaultShader.ClippingEnabled = false;

            if (UseFXAA && fxaa == null)
            {
                fxaa = new FXAA();
                fxaa.Initialize();
            }

            if (GameSettings.Current.EnableGlow)
            {
                if (UseFXAA)
                {
                    fxaa.Begin(DwarfTime.LastTime);
                }
                bloom.DrawTarget = UseFXAA ? fxaa.RenderTarget : null;

                bloom.Draw(gameTime.ToRealTime());
                if (UseFXAA)
                {
                    fxaa.End(DwarfTime.LastTime);
                }
            }
            else if (UseFXAA)
            {
                fxaa.End(DwarfTime.LastTime);
            }

            RasterizerState rasterizerState = new RasterizerState()
            {
                ScissorTestEnable = true
            };


            if (Debugger.Switches.DrawSelectionBuffer)
            {
                SelectionBuffer.DebugDraw(GraphicsDevice.Viewport.Bounds);
            }

            try
            {
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               null, rasterizerState, null, Matrix.Identity);
                //DwarfGame.SpriteBatch.Draw(Shadows.ShadowTexture, Vector2.Zero, Color.White);
                if (IsCameraUnderwater())
                {
                    Drawer2D.FillRect(DwarfGame.SpriteBatch, GraphicsDevice.Viewport.Bounds, new Color(10, 40, 60, 200));
                }

                Drawer2D.Render(DwarfGame.SpriteBatch, Camera, GraphicsDevice.Viewport);

                IndicatorManager.Render(gameTime);
            }
            finally
            {
                try
                {
                    DwarfGame.SpriteBatch.End();
                }
                catch (Exception exception)
                {
                    DwarfGame.SpriteBatch = new SpriteBatch(GraphicsDevice);
                }
            }

            if (Debugger.Switches.DrawComposites)
            {
                Vector2 offset = Vector2.Zero;
                foreach (var composite in CompositeLibrary.Composites)
                {
                    offset = composite.Value.DebugDraw(DwarfGame.SpriteBatch, (int)offset.X, (int)offset.Y);
                }
            }

            if (Debugger.Switches.DrawTiledInstanceAtlas)
            {
                var tiledInstanceGroup = InstanceRenderer.GetCombinedTiledInstance();
                var tex = tiledInstanceGroup.GetAtlasTexture();
                if (tex != null)
                {
                    this.World.UserInterface.Gui.DrawQuad(tex.Bounds, tex);
                }
            }

            DwarfGame.SpriteBatch.GraphicsDevice.ScissorRectangle =
                DwarfGame.SpriteBatch.GraphicsDevice.Viewport.Bounds;

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            foreach (var module in World.UpdateSystems)
            {
                module.Render(gameTime, World.ChunkManager, Camera, DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader);
            }

            lock (ScreenshotLock)
            {
                foreach (Screenshot shot in Screenshots)
                {
                    TakeScreenshot(shot.FileName, shot.Resolution);
                }

                Screenshots.Clear();
            }
        }
Exemple #12
0
        public override void Render(DwarfTime time, SpriteBatch batch)
        {
            if (!IsVisible)
            {
                return;
            }

            Rectangle globalBounds = GlobalBounds;
            Color     imageColor   = Color.White;
            Color     textColor    = TextColor;
            Color     strokeColor  = GUI.DefaultStrokeColor;

            if (IsLeftPressed)
            {
                imageColor = PressedTint;
                textColor  = PressedTextColor;
            }
            else if (IsMouseOver)
            {
                imageColor = HoverTint;
                textColor  = HoverTextColor;
            }

            if (CanToggle && IsToggled)
            {
                imageColor = ToggleTint;
            }

            imageColor.A = Transparency;

            Rectangle imageBounds = GetImageBounds();

            switch (Mode)
            {
            case ButtonMode.ImageButton:
                if (DrawFrame)
                {
                    GUI.Skin.RenderButtonFrame(imageBounds, batch);
                }
                Rectangle bounds = imageBounds;
                if (Image != null && Image.Image != null)
                {
                    batch.Draw(Image.Image, bounds, Image.SourceRect, imageColor);
                }

                Drawer2D.DrawAlignedText(batch, Text, TextFont, textColor, Drawer2D.Alignment.Under | Drawer2D.Alignment.Center, new Rectangle(bounds.X + 2, bounds.Y + 4, bounds.Width, bounds.Height), true);
                if (IsToggled)
                {
                    Drawer2D.DrawRect(batch, GetImageBounds(), Color.White, 2);
                }
                break;

            case ButtonMode.PushButton:
                GUI.Skin.RenderButton(GlobalBounds, batch);
                Drawer2D.DrawAlignedStrokedText(batch, Text,
                                                TextFont,
                                                textColor, strokeColor, Drawer2D.Alignment.Center, GlobalBounds, true);
                break;

            case ButtonMode.ToolButton:
                GUI.Skin.RenderButton(GlobalBounds, batch);
                if (Image != null && Image.Image != null)
                {
                    Rectangle imageRect   = GetImageBounds();
                    Rectangle alignedRect = Drawer2D.Align(GlobalBounds, imageRect.Width, imageRect.Height, Drawer2D.Alignment.Left);
                    alignedRect.X += 5;
                    batch.Draw(Image.Image, alignedRect, Image.SourceRect, imageColor);
                }
                Drawer2D.DrawAlignedStrokedText(batch, Text, TextFont, textColor, strokeColor, Drawer2D.Alignment.Center, GlobalBounds, true);

                if (IsToggled)
                {
                    Drawer2D.DrawRect(batch, GetImageBounds(), Color.White, 2);
                }

                break;

            case ButtonMode.TabButton:
                GUI.Skin.RenderTab(GlobalBounds, batch, IsToggled ? Color.White : Color.LightGray);
                Drawer2D.DrawAlignedStrokedText(batch, Text,
                                                TextFont,
                                                textColor, strokeColor, Drawer2D.Alignment.Top, new Rectangle(GlobalBounds.X, GlobalBounds.Y + 2, GlobalBounds.Width, GlobalBounds.Height), true);
                break;
            }

            base.Render(time, batch);
        }
Exemple #13
0
        public bool IsValid(CraftDesignation designation)
        {
            if (IsDesignation(designation.Location))
            {
                PlayState.GUI.ToolTipManager.Popup(Drawer2D.WrapColor("Something is already being built there!", Color.Red));
                return(false);
            }

            if (Faction.GetNearestRoomOfType(WorkshopRoom.WorkshopName, designation.Location.Position) == null)
            {
                PlayState.GUI.ToolTipManager.Popup(Drawer2D.WrapColor("Can't build, no workshops!", Color.Red));
                return(false);
            }

            if (!Faction.HasResources(designation.ItemType.RequiredResources))
            {
                string neededResources = "";

                foreach (Quantitiy <Resource.ResourceTags> amount in designation.ItemType.RequiredResources)
                {
                    neededResources += "" + amount.NumResources + " " + amount.ResourceType.ToString() + " ";
                }

                PlayState.GUI.ToolTipManager.Popup(Drawer2D.WrapColor("Not enough resources! Need " + neededResources + ".", Color.Red));
                return(false);
            }

            Voxel[] neighbors = new Voxel[4];
            foreach (CraftItem.CraftPrereq req in designation.ItemType.Prerequisites)
            {
                switch (req)
                {
                case CraftItem.CraftPrereq.NearWall:
                {
                    designation.Location.Chunk.Get2DManhattanNeighbors(neighbors, (int)designation.Location.GridPosition.X,
                                                                       (int)designation.Location.GridPosition.Y, (int)designation.Location.GridPosition.Z);

                    bool neighborFound = neighbors.Any(voxel => voxel != null && !voxel.IsEmpty);

                    if (!neighborFound)
                    {
                        PlayState.GUI.ToolTipManager.Popup(Drawer2D.WrapColor("Must be built next to wall!", Color.Red));
                        return(false);
                    }

                    break;
                }

                case CraftItem.CraftPrereq.OnGround:
                {
                    Voxel below = new Voxel();
                    designation.Location.GetNeighbor(Vector3.Down, ref below);

                    if (below.IsEmpty)
                    {
                        PlayState.GUI.ToolTipManager.Popup(Drawer2D.WrapColor("Must be built on solid ground!", Color.Red));
                        return(false);
                    }
                    break;
                }
                }
            }

            return(true);
        }
Exemple #14
0
        public IEnumerable <Act.Status> PerformOnVoxel(Creature performer, Vector3 pos, KillVoxelTask DigAct, DwarfTime time, float bonus, string faction)
        {
            while (true)
            {
                if (!DigAct.Voxel.IsValid)
                {
                    yield return(Act.Status.Fail);

                    yield break;
                }

                Drawer2D.DrawLoadBar(performer.World.Camera, DigAct.Voxel.WorldPosition + Vector3.One * 0.5f, Color.White, Color.Black, 32, 1, (float)DigAct.VoxelHealth / DigAct.Voxel.Type.StartingHealth);

                switch (TriggerMode)
                {
                case AttackTrigger.Timer:
                    RechargeTimer.Update(time);
                    if (!RechargeTimer.HasTriggered)
                    {
                        yield return(Act.Status.Running);

                        continue;
                    }
                    break;

                case AttackTrigger.Animation:
                    if (!performer.Sprite.AnimPlayer.HasValidAnimation() ||
                        performer.Sprite.AnimPlayer.CurrentFrame < TriggerFrame)
                    {
                        if (performer.Sprite.AnimPlayer.HasValidAnimation())
                        {
                            performer.Sprite.AnimPlayer.Play();
                        }
                        yield return(Act.Status.Running);

                        continue;
                    }
                    break;
                }

                switch (Mode)
                {
                case AttackMode.Melee:
                {
                    DigAct.VoxelHealth -= (DamageAmount + bonus);

                    DigAct.Voxel.Type.HitSound.Play(DigAct.Voxel.WorldPosition);
                    if (HitParticles != "")
                    {
                        performer.Manager.World.ParticleManager.Trigger(HitParticles, DigAct.Voxel.WorldPosition, Color.White, 5);
                    }

                    if (HitAnimation != null)
                    {
                        IndicatorManager.DrawIndicator(HitAnimation, DigAct.Voxel.WorldPosition + Vector3.One * 0.5f,
                                                       10.0f, 1.0f, MathFunctions.RandVector2Circle() * 10, HitColor, MathFunctions.Rand() > 0.5f);
                    }

                    break;
                }

                case AttackMode.Ranged:
                {
                    throw new InvalidOperationException("Ranged attacks should never be used for digging.");
                    //LaunchProjectile(pos, DigAct.GetTargetVoxel().WorldPosition, null);
                    //break;
                }
                }
                yield return(Act.Status.Success);

                yield break;
            }
        }
Exemple #15
0
        public IEnumerable <Status> FarmATile()
        {
            FarmTool.FarmTile tile = FarmToWork;
            if (tile == null)
            {
                yield return(Status.Fail);

                yield break;
            }
            if (tile.IsCanceled)
            {
                yield return(Status.Fail);

                yield break;
            }
            else if (tile.PlantExists())
            {
                tile.Farmer = null;
                yield return(Status.Success);
            }
            else
            {
                if (tile.Plant != null && tile.Plant.IsDead)
                {
                    tile.Plant = null;
                }
                Creature.CurrentCharacterMode = Creature.CharacterMode.Attacking;
                Creature.Sprite.ResetAnimations(Creature.CharacterMode.Attacking);
                Creature.Sprite.PlayAnimations(Creature.CharacterMode.Attacking);
                while (tile.Progress < 100.0f && !Satisfied())
                {
                    if (tile.IsCanceled)
                    {
                        yield return(Status.Fail);

                        yield break;
                    }
                    Creature.Physics.Velocity *= 0.1f;
                    tile.Progress             += Creature.Stats.BaseFarmSpeed * DwarfTime.Dt;

                    Drawer2D.DrawLoadBar(Agent.Manager.World.Camera, Agent.Position + Vector3.Up, Color.White, Color.Black, 100, 16,
                                         tile.Progress / 100.0f);

                    if (tile.Progress >= 100.0f && !Satisfied())
                    {
                        tile.Progress = 0.0f;
                        if (Mode == FarmAct.FarmMode.Plant)
                        {
                            FarmToWork.CreatePlant(PlantToCreate, Creature.Manager.World);
                            DestroyResources();
                        }
                        else
                        {
                            FarmToWork.Vox.Type = VoxelLibrary.GetVoxelType("TilledSoil");
                            FarmToWork.Vox.Chunk.NotifyTotalRebuild(true);
                        }
                    }
                    if (MathFunctions.RandEvent(0.01f))
                    {
                        Creature.Manager.World.ParticleManager.Trigger("dirt_particle", Creature.AI.Position, Color.White, 1);
                    }
                    yield return(Status.Running);

                    Creature.Sprite.ReloopAnimations(Creature.CharacterMode.Attacking);
                }
                Creature.CurrentCharacterMode = Creature.CharacterMode.Idle;
                Creature.AI.AddThought(Thought.ThoughtType.Farmed);
                Creature.AI.AddXP(1);
                tile.Farmer = null;
                Creature.Sprite.PauseAnimations(Creature.CharacterMode.Attacking);
                yield return(Status.Success);
            }
        }
Exemple #16
0
        public override IEnumerable <Status> Run()
        {
            Creature.IsCloaked = false;

            if (CurrentAttack == null)
            {
                yield return(Status.Fail);

                yield break;
            }

            Timeout.Reset();
            FailTimer.Reset();
            if (Target == null && TargetName != null)
            {
                Target = Agent.Blackboard.GetData <GameComponent>(TargetName);

                if (Target == null)
                {
                    yield return(Status.Fail);

                    yield break;
                }
            }

            if (Agent.Faction.Race.IsIntelligent)
            {
                var targetInventory = Target.GetRoot().GetComponent <Inventory>();
                if (targetInventory != null)
                {
                    targetInventory.SetLastAttacker(Agent);
                }
            }

            CharacterMode defaultCharachterMode = Creature.AI.Movement.CanFly
                ? CharacterMode.Flying
                : CharacterMode.Walking;

            bool avoided = false;

            while (true)
            {
                Timeout.Update(DwarfTime.LastTime);
                FailTimer.Update(DwarfTime.LastTime);
                if (FailTimer.HasTriggered)
                {
                    Creature.Physics.Orientation   = Physics.OrientMode.RotateY;
                    Creature.OverrideCharacterMode = false;
                    Creature.CurrentCharacterMode  = defaultCharachterMode;
                    yield return(Status.Fail);

                    yield break;
                }

                if (Timeout.HasTriggered)
                {
                    if (Training)
                    {
                        Agent.AddXP(1);
                        Creature.Physics.Orientation   = Physics.OrientMode.RotateY;
                        Creature.OverrideCharacterMode = false;
                        Creature.CurrentCharacterMode  = defaultCharachterMode;
                        yield return(Status.Success);

                        yield break;
                    }
                    else
                    {
                        Creature.Physics.Orientation   = Physics.OrientMode.RotateY;
                        Creature.OverrideCharacterMode = false;
                        Creature.CurrentCharacterMode  = defaultCharachterMode;
                        yield return(Status.Fail);

                        yield break;
                    }
                }

                if (Target == null || Target.IsDead)
                {
                    Creature.CurrentCharacterMode = defaultCharachterMode;
                    Creature.Physics.Orientation  = Physics.OrientMode.RotateY;
                    yield return(Status.Success);
                }

                // Find the location of the melee target
                Vector3 targetPos = new Vector3(Target.GlobalTransform.Translation.X,
                                                Target.GetBoundingBox().Min.Y,
                                                Target.GlobalTransform.Translation.Z);

                Vector2 diff = new Vector2(targetPos.X, targetPos.Z) - new Vector2(Creature.AI.Position.X, Creature.AI.Position.Z);

                Creature.Physics.Face(targetPos);

                bool  intersectsbounds = Creature.Physics.BoundingBox.Intersects(Target.BoundingBox);
                float dist             = diff.Length();
                // If we are really far from the target, something must have gone wrong.
                if (DefensiveStructure == null && !intersectsbounds && dist > CurrentAttack.Weapon.Range * 4)
                {
                    Creature.Physics.Orientation   = Physics.OrientMode.RotateY;
                    Creature.OverrideCharacterMode = false;
                    Creature.CurrentCharacterMode  = defaultCharachterMode;
                    yield return(Status.Fail);

                    yield break;
                }

                if (DefensiveStructure != null)
                {
                    if (Creature.Hp < LastHp)
                    {
                        float damage = LastHp - Creature.Hp;
                        Creature.Heal(Math.Min(5.0f, damage));
                        var health = DefensiveStructure.GetRoot().GetComponent <Health>();
                        if (health != null)
                        {
                            health.Damage(damage);
                            Drawer2D.DrawLoadBar(health.World.Renderer.Camera, DefensiveStructure.Position, Color.White, Color.Black, 32, 1, health.Hp / health.MaxHealth, 0.1f);
                        }
                        LastHp = Creature.Hp;
                    }

                    if (dist > CurrentAttack.Weapon.Range)
                    {
                        float sqrDist = dist * dist;
                        foreach (var threat in Creature.AI.Faction.Threats)
                        {
                            float threatDist = (threat.AI.Position - Creature.AI.Position).LengthSquared();
                            if (threatDist < sqrDist)
                            {
                                sqrDist = threatDist;
                                Target  = threat.Physics;
                                break;
                            }
                        }
                        dist = (float)Math.Sqrt(sqrDist);
                    }

                    if (dist > CurrentAttack.Weapon.Range * 4)
                    {
                        yield return(Status.Fail);

                        yield break;
                    }

                    if (DefensiveStructure.IsDead)
                    {
                        DefensiveStructure = null;
                    }
                }

                LastHp = Creature.Hp;


                // If we're out of attack range, run toward the target.
                if (DefensiveStructure == null && !Creature.AI.Movement.IsSessile && !intersectsbounds && diff.Length() > CurrentAttack.Weapon.Range)
                {
                    Creature.CurrentCharacterMode = defaultCharachterMode;
                    var greedyPath = new GreedyPathAct(Creature.AI, Target, CurrentAttack.Weapon.Range * 0.75f)
                    {
                        PathLength = 5
                    };
                    greedyPath.Initialize();

                    foreach (Act.Status stat in greedyPath.Run())
                    {
                        if (stat == Act.Status.Running)
                        {
                            yield return(Status.Running);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                // If we have a ranged weapon, try avoiding the target for a few seconds to get within range.
                else if (DefensiveStructure == null && !Creature.AI.Movement.IsSessile && !intersectsbounds && !avoided && (CurrentAttack.Weapon.Mode == Weapon.AttackMode.Ranged &&
                                                                                                                            dist < CurrentAttack.Weapon.Range * 0.15f))
                {
                    FailTimer.Reset();
                    foreach (Act.Status stat in AvoidTarget(CurrentAttack.Weapon.Range, 3.0f))
                    {
                        yield return(Status.Running);
                    }
                    avoided = true;
                }
                // Else, stop and attack
                else if ((DefensiveStructure == null && dist < CurrentAttack.Weapon.Range) ||
                         (DefensiveStructure != null && dist < CurrentAttack.Weapon.Range * 2.0))
                {
                    if (CurrentAttack.Weapon.Mode == Weapon.AttackMode.Ranged &&
                        VoxelHelpers.DoesRayHitSolidVoxel(Creature.World.ChunkManager, Creature.AI.Position, Target.Position))
                    {
                        yield return(Status.Fail);

                        yield break;
                    }

                    FailTimer.Reset();
                    avoided = false;
                    Creature.Physics.Orientation = Physics.OrientMode.Fixed;
                    Creature.Physics.Velocity    = new Vector3(Creature.Physics.Velocity.X * 0.9f, Creature.Physics.Velocity.Y, Creature.Physics.Velocity.Z * 0.9f);
                    CurrentAttack.RechargeTimer.Reset(CurrentAttack.Weapon.RechargeRate);

                    Creature.Sprite.ResetAnimations(Creature.Stats.CurrentClass.AttackMode);
                    Creature.Sprite.PlayAnimations(Creature.Stats.CurrentClass.AttackMode);
                    Creature.CurrentCharacterMode  = Creature.Stats.CurrentClass.AttackMode;
                    Creature.OverrideCharacterMode = true;
                    Timer timeout = new Timer(10.0f, true);
                    while (!CurrentAttack.Perform(Creature, Target, DwarfTime.LastTime, Creature.Stats.Strength + Creature.Stats.Size,
                                                  Creature.AI.Position, Creature.Faction.ParentFaction.Name))
                    {
                        timeout.Update(DwarfTime.LastTime);
                        if (timeout.HasTriggered)
                        {
                            break;
                        }

                        Creature.Physics.Velocity = new Vector3(Creature.Physics.Velocity.X * 0.9f, Creature.Physics.Velocity.Y, Creature.Physics.Velocity.Z * 0.9f);
                        if (Creature.AI.Movement.CanFly)
                        {
                            Creature.Physics.ApplyForce(-Creature.Physics.Gravity * 0.1f, DwarfTime.Dt);
                        }
                        yield return(Status.Running);
                    }

                    timeout.Reset();
                    while (!Agent.Creature.Sprite.AnimPlayer.IsDone())
                    {
                        timeout.Update(DwarfTime.LastTime);
                        if (timeout.HasTriggered)
                        {
                            break;
                        }
                        if (Creature.AI.Movement.CanFly)
                        {
                            Creature.Physics.ApplyForce(-Creature.Physics.Gravity * 0.1f, DwarfTime.Dt);
                        }
                        yield return(Status.Running);
                    }

                    var targetCreature = Target.GetRoot().GetComponent <CreatureAI>();
                    if (targetCreature != null && Creature.AI.FightOrFlight(targetCreature) == CreatureAI.FightOrFlightResponse.Flee)
                    {
                        yield return(Act.Status.Fail);

                        yield break;
                    }
                    Creature.CurrentCharacterMode = CharacterMode.Attacking;

                    Vector3 dogfightTarget = Vector3.Zero;
                    while (!CurrentAttack.RechargeTimer.HasTriggered && !Target.IsDead)
                    {
                        CurrentAttack.RechargeTimer.Update(DwarfTime.LastTime);
                        if (CurrentAttack.Weapon.Mode == Weapon.AttackMode.Dogfight)
                        {
                            dogfightTarget += MathFunctions.RandVector3Cube() * 0.1f;
                            Vector3 output = Creature.Controller.GetOutput(DwarfTime.Dt, dogfightTarget + Target.Position, Creature.Physics.GlobalTransform.Translation) * 0.9f;
                            Creature.Physics.ApplyForce(output - Creature.Physics.Gravity, DwarfTime.Dt);
                        }
                        else
                        {
                            Creature.Physics.Velocity = Vector3.Zero;
                            if (Creature.AI.Movement.CanFly)
                            {
                                Creature.Physics.ApplyForce(-Creature.Physics.Gravity, DwarfTime.Dt);
                            }
                        }
                        yield return(Status.Running);
                    }

                    Creature.CurrentCharacterMode = defaultCharachterMode;
                    Creature.Physics.Orientation  = Physics.OrientMode.RotateY;

                    if (Target.IsDead)
                    {
                        Target = null;
                        Agent.AddXP(10);
                        Creature.Physics.Face(Creature.Physics.Velocity + Creature.Physics.GlobalTransform.Translation);
                        Creature.Stats.NumThingsKilled++;
                        Creature.AddThought("I killed somehing!", new TimeSpan(0, 8, 0, 0), 1.0f);
                        Creature.Physics.Orientation   = Physics.OrientMode.RotateY;
                        Creature.OverrideCharacterMode = false;
                        Creature.CurrentCharacterMode  = defaultCharachterMode;
                        yield return(Status.Success);

                        break;
                    }
                }

                yield return(Status.Running);
            }
        }
Exemple #17
0
        public void RenderSliderVertical(SpriteFont font, Rectangle boundingRect, float value, float minvalue, float maxValue, Slider.SliderMode mode, bool drawLabel, bool invert, SpriteBatch spriteBatch)
        {
            const int padding = 5;

            if (invert)
            {
                value = maxValue - value;
            }


            int       fieldSize = Math.Max(Math.Min((int)(0.2f * boundingRect.Width), 150), 64);
            Rectangle rect      = new Rectangle(boundingRect.X + boundingRect.Width / 2 - TileWidth / 2, boundingRect.Y + padding, boundingRect.Width, boundingRect.Height - TileHeight - padding * 2);
            Rectangle fieldRect = new Rectangle(boundingRect.Right - fieldSize, boundingRect.Y + boundingRect.Height - TileHeight / 2, fieldSize, TileHeight);

            int maxY   = rect.Y + rect.Height;
            int diffY  = rect.Height % TileHeight;
            int bottom = maxY;
            int left   = rect.X;
            int top    = rect.Y;


            for (int y = top; y <= bottom; y += TileHeight)
            {
                spriteBatch.Draw(Texture, new Rectangle(rect.X, y, TileWidth, TileHeight), GetSourceRect(Tile.TrackVert), Color.White);
            }

            spriteBatch.Draw(Texture, new Rectangle(rect.X, maxY - diffY, TileWidth, diffY), GetSourceRect(Tile.TrackVert), Color.White);

            float d = (value - minvalue) / (maxValue - minvalue);

            int sliderY = (int)((d) * rect.Height + rect.Y);

            spriteBatch.Draw(Texture, new Rectangle(rect.X, sliderY - TileHeight / 2, TileWidth, TileHeight), GetSourceRect(Tile.SliderVertical), Color.White);

            if (!drawLabel)
            {
                return;
            }

            RenderField(fieldRect, spriteBatch);

            if (invert)
            {
                value = -(value - maxValue);
            }

            float v = 0.0f;

            if (mode == Slider.SliderMode.Float)
            {
                v = (float)Math.Round(value, 2);
            }
            else
            {
                v = (int)value;
            }

            string toDraw = "" + v;

            Vector2 origin = Datastructures.SafeMeasure(font, toDraw) * 0.5f;

            Drawer2D.SafeDraw(spriteBatch, toDraw, font, Color.Black, new Vector2(fieldRect.X + fieldRect.Width / 2, fieldRect.Y + 16), origin);
        }
Exemple #18
0
        protected override void LoadContent()
        {
#if SHARP_RAVEN && !DEBUG
            try
            {
#endif
            LogSentryBreadcrumb("Loading", "LoadContent was called.", BreadcrumbLevel.Info);
            AssetManager.Initialize(Content, GraphicsDevice, GameSettings.Default);

            // Prepare GemGui
            if (GumInputMapper == null)
            {
                GumInputMapper = new Gui.Input.GumInputMapper(Window.Handle);
                GumInput       = new Gui.Input.Input(GumInputMapper);
            }

            GuiSkin = new RenderData(GraphicsDevice, Content);

            // Create console.
            ConsoleGui = new Gui.Root(GuiSkin);
            ConsoleGui.RootItem.AddChild(new Gui.Widgets.AutoGridPanel
            {
                Rows       = 2,
                Columns    = 4,
                AutoLayout = AutoLayout.DockFill
            });

            ConsoleGui.RootItem.Layout();
            if (_logwriter != null)
            {
                _logwriter.SetConsole(GetConsoleTile("LOG"));
            }

            Console.Out.WriteLine("Console created.");

            if (SoundManager.Content == null)
            {
                SoundManager.Content = Content;
                SoundManager.LoadDefaultSounds();
            }

            if (GameStateManager.StateStackIsEmpty)
            {
                LogSentryBreadcrumb("GameState", "There was nothing in the state stack. Starting over.");
                if (GameSettings.Default.DisplayIntro)
                {
                    GameStateManager.PushState(new IntroState(this));
                }
                else
                {
                    GameStateManager.PushState(new MainMenuState(this));
                }
            }

            ControlSettings.Load();
            Drawer2D.Initialize(Content, GraphicsDevice);
            ScreenSaver = new Terrain2D(this);

            base.LoadContent();

#if SHARP_RAVEN && !DEBUG
        }

        catch (Exception exception)
        {
            if (ravenClient != null)
            {
                ravenClient.Capture(new SentryEvent(exception));
            }
            throw;
        }
#endif
        }
Exemple #19
0
        /// <summary> Updates the creature </summary>
        public virtual void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            if (FirstUpdate)
            {
                FirstUpdate = false;
                Faction.Minions.Add(AI);
                Physics.AllowPhysicsSleep = false;

                addToSpeciesCount();
            }

            if (!Active)
            {
                return;
            }
            DrawLifeTimer.Update(gameTime);

            if (!DrawLifeTimer.HasTriggered)
            {
                float val   = Hp / MaxHealth;
                Color color = val < 0.75f ? (val < 0.5f ? Color.Red : Color.Orange) : Color.LightGreen;
                Drawer2D.DrawLoadBar(Manager.World.Camera, AI.Position - Vector3.Up * 0.5f, color, Color.Black, 32, 2, Hp / MaxHealth);
            }

            CheckNeighborhood(chunks, (float)gameTime.ElapsedGameTime.TotalSeconds);
            UpdateAnimation(gameTime, chunks, camera);
            Status.Update(this, gameTime, chunks, camera);
            JumpTimer.Update(gameTime);
            HandleBuffs(gameTime);

            if (Stats.IsMigratory && !AI.IsPositionConstrained())
            {
                if (MigrationTimer == null)
                {
                    MigrationTimer = new Timer(3600f + MathFunctions.Rand(-120, 120), false);
                }
                MigrationTimer.Update(gameTime);
                if (MigrationTimer.HasTriggered)
                {
                    AI.LeaveWorld();
                }
            }

            if (Stats.LaysEggs)
            {
                if (EggTimer == null)
                {
                    EggTimer = new Timer(3600f + MathFunctions.Rand(-120, 120), false);
                }
                EggTimer.Update(gameTime);

                if (EggTimer.HasTriggered)
                {
                    if (!_speciesCounts.ContainsKey(Species) || _speciesCounts[Species] < _maxPerSpecies)
                    {
                        LayEgg();
                        EggTimer = new Timer(1200f + MathFunctions.Rand(-30, 30), false);
                    }
                }
            }

            if (IsPregnant && World.Time.CurrentDate > CurrentPregnancy.EndDate)
            {
                if (!_speciesCounts.ContainsKey(Species) || _speciesCounts[Species] < _maxPerSpecies)
                {
                    var baby = EntityFactory.CreateEntity <GameComponent>(BabyType, Physics.Position);
                    baby.GetRoot().GetComponent <CreatureAI>().PositionConstraint = AI.PositionConstraint;
                }
                CurrentPregnancy = null;
            }

            if (MathFunctions.RandEvent(0.0001f))
            {
                NoiseMaker.MakeNoise("Chirp", AI.Position, true, 0.25f);
            }
        }
Exemple #20
0
 public static void DrawLoadBar(Vector3 worldPos, Color backgroundColor, Color strokeColor, int width, int height, float progress)
 {
     Drawer2D.DrawRect(worldPos, new Rectangle(0, 0, width + 1, height + 1), Color.Transparent, strokeColor, 1);
     Drawer2D.DrawRect(worldPos, new Rectangle((int)(width * (progress)) / 2 - width / 2, 0, (int)(width * (progress)), height), backgroundColor, Color.Transparent, 1);
 }
Exemple #21
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            if (!IsActive) return;

            IdleTimer.Update(gameTime);
            SpeakTimer.Update(gameTime);

            OrderEnemyAttack();
            DeleteBadTasks();
            PreEmptTasks();

            if (Status.Energy.IsUnhappy() && PlayState.Time.IsNight())
            {
                Task toReturn = new SatisfyTirednessTask();
                toReturn.SetupScript(Creature);
                if (!Tasks.Contains(toReturn))
                    Tasks.Add(toReturn);
            }

            if (Status.Hunger.IsUnhappy() &&  Faction.CountResourcesWithTag(Resource.ResourceTags.Edible) > 0)
            {
                Task toReturn = new SatisfyHungerTask();
                toReturn.SetupScript(Creature);
                if (!Tasks.Contains(toReturn))
                    Tasks.Add(toReturn);
            }


            if(CurrentTask != null && CurrentAct != null)
            {
                Act.Status status = CurrentAct.Tick();


                bool retried = false;
                if(status == Act.Status.Fail)
                {
                    if(CurrentTask.ShouldRetry(Creature))
                    {
                        if (!Tasks.Contains(CurrentTask))
                        {
                            CurrentTask.Priority = Task.PriorityType.Eventually;
                            Tasks.Add(CurrentTask);
                            CurrentTask.SetupScript(Creature);
                            retried = true;
                        }
                    }
                }

                if(status != Act.Status.Running && !retried)
                {
                    CurrentTask = null;
                }
            }
            else
            {
                bool tantrum = false;
                if (Status.Happiness.IsUnhappy())
                {
                    tantrum = MathFunctions.Rand(0, 1) < 0.25f;
                }

                Task goal = GetEasiestTask(Tasks);
                if (goal != null)
                {
                    if (tantrum)
                    {
                        Creature.DrawIndicator(IndicatorManager.StandardIndicators.Sad);
                        if (Creature.Allies == "Dwarf")
                        {
                            PlayState.AnnouncementManager.Announce(Stats.FullName +  " (" + Stats.CurrentLevel.Name + ")" + Drawer2D.WrapColor(" refuses to work!", Color.DarkRed), 
                                "Our employee is unhappy, and would rather not work!", ZoomToMe);
                        }
                        CurrentTask = null;
                    }
                    else
                    {
                        IdleTimer.Reset(IdleTimer.TargetTimeSeconds);
                        goal.SetupScript(Creature);
                        CurrentTask = goal;
                        Tasks.Remove(goal);
                    }
                }
                else
                {
                    CurrentTask = ActOnIdle();
                }   
                
            }


            PlannerTimer.Update(gameTime);
            UpdateThoughts();
            UpdateXP();

            base.Update(gameTime, chunks, camera);
        }
Exemple #22
0
 public virtual void Render()
 {
     Drawer2D.DrawSprite(Image, Position, new Vector2(Scale, Scale), Offset, Tint, Flip);
 }
Exemple #23
0
        protected override void LoadContent()
        {
#if SHARP_RAVEN && !DEBUG
            try
            {
#endif
            AssetManager.Initialize(Content, GraphicsDevice, GameSettings.Default);

            //var palette = TextureTool.ExtractPaletteFromDirectoryRecursive("Entities/Dwarf");
            //var paletteTexture = TextureTool.Texture2DFromMemoryTexture(GraphicsDevice, TextureTool.MemoryTextureFromPalette(palette));
            //paletteTexture.SaveAsPng(System.IO.File.OpenWrite("palette.png"), paletteTexture.Width, paletteTexture.Height);

            // Prepare GemGui
            GumInputMapper = new Gui.Input.GumInputMapper(Window.Handle);
            GumInput       = new Gui.Input.Input(GumInputMapper);

            // Register all bindable actions with the input system.
            //GumInput.AddAction("TEST", Gui.Input.KeyBindingType.Pressed);

            GuiSkin = new RenderData(GraphicsDevice, Content);

            // Create console.
            ConsoleGui = new Gui.Root(GuiSkin);
            ConsoleGui.RootItem.AddChild(new Gui.Widgets.AutoGridPanel
            {
                Rows       = 2,
                Columns    = 4,
                AutoLayout = AutoLayout.DockFill
            });

            ConsoleGui.RootItem.Layout();
            if (_logwriter != null)
            {
                _logwriter.SetConsole(GetConsoleTile("LOG"));
            }

            Console.Out.WriteLine("Console created.");

            if (SoundManager.Content == null)
            {
                SoundManager.Content = Content;
                SoundManager.LoadDefaultSounds();
#if XNA_BUILD
                //SoundManager.SetActiveSongs(ContentPaths.Music.dwarfcorp, ContentPaths.Music.dwarfcorp_2,
                //    ContentPaths.Music.dwarfcorp_3, ContentPaths.Music.dwarfcorp_4, ContentPaths.Music.dwarfcorp_5);
#endif
            }

            if (StateManager.StateStack.Count == 0)
            {
                if (GameSettings.Default.DisplayIntro)
                {
                    StateManager.PushState(new IntroState(this, StateManager));
                }
                else
                {
                    StateManager.PushState(new MainMenuState(this, StateManager));
                }
            }
            BiomeLibrary.InitializeStatics();
            EmbarkmentLibrary.InitializeDefaultLibrary();
            VoxelChunk.InitializeStatics();
            ControlSettings.Load();
            Drawer2D.Initialize(Content, GraphicsDevice);
            ResourceLibrary.Initialize();
            base.LoadContent();
#if SHARP_RAVEN && !DEBUG
        }

        catch (Exception exception)
        {
            if (ravenClient != null)
            {
                ravenClient.Capture(new SentryEvent(exception));
            }
            throw;
        }
#endif
        }
Exemple #24
0
        public IEnumerable <Status> FarmATile()
        {
            if (Farm == null)
            {
                yield return(Status.Fail);

                yield break;
            }
            else if (Farm.Finished)
            {
                yield return(Status.Success);
            }
            else
            {
                Creature.CurrentCharacterMode = Creature.Stats.CurrentClass.AttackMode;
                Creature.Sprite.ResetAnimations(Creature.Stats.CurrentClass.AttackMode);
                Creature.Sprite.PlayAnimations(Creature.Stats.CurrentClass.AttackMode);
                while (Farm.Progress < Farm.TargetProgress && !Farm.Finished)
                {
                    Creature.Physics.Velocity *= 0.1f;
                    Farm.Progress             += 3 * Creature.Stats.BaseFarmSpeed * DwarfTime.Dt;

                    Drawer2D.DrawLoadBar(Agent.Manager.World.Renderer.Camera, Agent.Position + Vector3.Up, Color.LightGreen, Color.Black, 64, 4,
                                         Farm.Progress / Farm.TargetProgress);

                    if (Farm.Progress >= (Farm.TargetProgress * 0.5f) && Farm.Voxel.Type.Name != "TilledSoil" &&
                        Library.GetVoxelType("TilledSoil").HasValue(out VoxelType tilledSoil))
                    {
                        Farm.Voxel.Type = tilledSoil;
                    }

                    if (Farm.Progress >= Farm.TargetProgress && !Farm.Finished)
                    {
                        if (Library.GetResourceType(Farm.SeedType).HasValue(out var seedType))
                        {
                            var plant = EntityFactory.CreateEntity <Plant>(
                                seedType.PlantToGenerate,
                                Farm.Voxel.WorldPosition + new Vector3(0.5f, 1.0f, 0.5f));

                            plant.Farm = Farm;

                            Matrix original = plant.LocalTransform;
                            original.Translation += Vector3.Down;
                            plant.AnimationQueue.Add(new EaseMotion(0.5f, original, plant.LocalTransform.Translation));


                            Creature.Manager.World.ParticleManager.Trigger("puff", original.Translation, Color.White, 20);

                            SoundManager.PlaySound(ContentPaths.Audio.Oscar.sfx_env_plant_grow, Farm.Voxel.WorldPosition, true);
                        }

                        Farm.Finished = true;
                        DestroyResources();
                    }

                    if (MathFunctions.RandEvent(0.01f))
                    {
                        Creature.Manager.World.ParticleManager.Trigger("dirt_particle", Creature.AI.Position, Color.White, 1);
                    }
                    yield return(Status.Running);

                    Creature.Sprite.ReloopAnimations(Creature.Stats.CurrentClass.AttackMode);
                }

                Creature.CurrentCharacterMode = CharacterMode.Idle;
                Creature.AddThought("I farmed something!", new TimeSpan(0, 4, 0, 0), 1.0f);
                Creature.AI.AddXP(1);
                Creature.Sprite.PauseAnimations(Creature.Stats.CurrentClass.AttackMode);
                yield return(Status.Success);
            }
        }
        /// <summary>
        /// Called when a frame is to be drawn to the screen
        /// </summary>
        /// <param name="gameTime">The current time</param>
        public void Render(DwarfTime gameTime)
        {
            if (!ShowingWorld)
            {
                return;
            }
            ValidateShader();
            var frustum     = Camera.GetDrawFrustum();
            var renderables = EnumerateIntersectingObjects(frustum,
                                                           r => r.IsVisible && !ChunkManager.IsAboveCullPlane(r.GetBoundingBox()));

            // Controls the sky fog
            float x = (1.0f - Sky.TimeOfDay);

            x = x * x;
            DefaultShader.FogColor       = new Color(0.32f * x, 0.58f * x, 0.9f * x);
            DefaultShader.LightPositions = LightPositions;

            CompositeLibrary.Render(GraphicsDevice);
            CompositeLibrary.Update();

            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            // Computes the water height.
            float wHeight = WaterRenderer.GetVisibleWaterHeight(ChunkManager, Camera, GraphicsDevice.Viewport,
                                                                lastWaterHeight);

            lastWaterHeight = wHeight;

            // Draw reflection/refraction images
            WaterRenderer.DrawReflectionMap(renderables, gameTime, this, wHeight - 0.1f,
                                            GetReflectedCameraMatrix(wHeight),
                                            DefaultShader, GraphicsDevice);


            #region Draw Selection Buffer.

            if (SelectionBuffer == null)
            {
                SelectionBuffer = new SelectionBuffer(8, GraphicsDevice);
            }

            GraphicsDevice.RasterizerState   = RasterizerState.CullNone;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            Plane slicePlane = WaterRenderer.CreatePlane(SlicePlane, new Vector3(0, -1, 0), Camera.ViewMatrix, false);

            if (SelectionBuffer.Begin(GraphicsDevice))
            {
                // Draw the whole world, and make sure to handle slicing
                DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
                DefaultShader.ClippingEnabled = true;
                DefaultShader.View            = Camera.ViewMatrix;
                DefaultShader.Projection      = Camera.ProjectionMatrix;
                DefaultShader.World           = Matrix.Identity;

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Chunks");
                ChunkRenderer.RenderSelectionBuffer(DefaultShader, GraphicsDevice, Camera.ViewMatrix);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Chunks");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Components");
                ComponentRenderer.RenderSelectionBuffer(renderables, gameTime, ChunkManager, Camera,
                                                        DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Components");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Instances");
                InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera,
                                       InstanceRenderMode.SelectionBuffer);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Instances");

                SelectionBuffer.End(GraphicsDevice);
            }


            #endregion



            // Start drawing the bloom effect
            if (GameSettings.Default.EnableGlow)
            {
                bloom.BeginDraw();
            }

            // Draw the sky
            GraphicsDevice.Clear(DefaultShader.FogColor);
            DrawSky(gameTime, Camera.ViewMatrix, 1.0f, DefaultShader.FogColor);

            // Defines the current slice for the GPU
            float level = ChunkManager.World.Master.MaxViewingLevel + 0.25f;
            if (level > VoxelConstants.ChunkSizeY)
            {
                level = 1000;
            }

            SlicePlane = level;
            CaveView   = CaveView * 0.9f + TargetCaveView * 0.1f;
            DefaultShader.WindDirection = Weather.CurrentWind;
            DefaultShader.WindForce     = 0.0005f * (1.0f + (float)Math.Sin(Time.GetTotalSeconds() * 0.001f));
            // Draw the whole world, and make sure to handle slicing
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;
            //Blue ghost effect above the current slice.
            DefaultShader.GhostClippingEnabled = true;
            Draw3DThings(gameTime, DefaultShader, Camera.ViewMatrix);

            // Now we want to draw the water on top of everything else
            DefaultShader.ClippingEnabled      = true;
            DefaultShader.GhostClippingEnabled = false;

            //ComponentManager.CollisionManager.DebugDraw();

            DefaultShader.View                 = Camera.ViewMatrix;
            DefaultShader.Projection           = Camera.ProjectionMatrix;
            DefaultShader.GhostClippingEnabled = true;
            // Now draw all of the entities in the game
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;

            if (Debugger.Switches.DrawOcttree)
            {
                foreach (var box in OctTree.EnumerateBounds(frustum))
                {
                    Drawer3D.DrawBox(box.Item2, Color.Yellow, 1.0f / (float)(box.Item1 + 1), false);
                }
            }

            // Render simple geometry (boxes, etc.)
            Drawer3D.Render(GraphicsDevice, DefaultShader, Camera, DesignationDrawer, PlayerFaction.Designations, this);

            DefaultShader.EnableShadows = false;

            DefaultShader.View = Camera.ViewMatrix;

            ComponentRenderer.Render(renderables, gameTime, ChunkManager,
                                     Camera,
                                     DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader,
                                     ComponentRenderer.WaterRenderType.None, lastWaterHeight);
            InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera, InstanceRenderMode.Normal);

            if (Master.CurrentToolMode == GameMaster.ToolMode.BuildZone ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildWall ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildObject)
            {
                DefaultShader.View       = Camera.ViewMatrix;
                DefaultShader.Projection = Camera.ProjectionMatrix;
                DefaultShader.SetTexturedTechnique();
                GraphicsDevice.BlendState = BlendState.NonPremultiplied;
            }

            WaterRenderer.DrawWater(
                GraphicsDevice,
                (float)gameTime.TotalGameTime.TotalSeconds,
                DefaultShader,
                Camera.ViewMatrix,
                GetReflectedCameraMatrix(wHeight),
                Camera.ProjectionMatrix,
                new Vector3(0.1f, 0.0f, 0.1f),
                Camera,
                ChunkManager);
            ParticleManager.Render(this, GraphicsDevice);
            DefaultShader.ClippingEnabled = false;

            if (GameSettings.Default.EnableGlow)
            {
                bloom.DrawTarget = UseFXAA ? fxaa.RenderTarget : null;

                if (UseFXAA)
                {
                    fxaa.Begin(DwarfTime.LastTime);
                }
                bloom.Draw(gameTime.ToRealTime());
                if (UseFXAA)
                {
                    fxaa.End(DwarfTime.LastTime);
                }
            }
            else if (UseFXAA)
            {
                fxaa.End(DwarfTime.LastTime);
            }

            RasterizerState rasterizerState = new RasterizerState()
            {
                ScissorTestEnable = true
            };


            if (Debugger.Switches.DrawSelectionBuffer)
            {
                SelectionBuffer.DebugDraw(GraphicsDevice.Viewport.Bounds);
            }

            try
            {
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               null, rasterizerState, null, Matrix.Identity);
                //DwarfGame.SpriteBatch.Draw(Shadows.ShadowTexture, Vector2.Zero, Color.White);
                if (IsCameraUnderwater())
                {
                    Drawer2D.FillRect(DwarfGame.SpriteBatch, GraphicsDevice.Viewport.Bounds, new Color(10, 40, 60, 200));
                }

                Drawer2D.Render(DwarfGame.SpriteBatch, Camera, GraphicsDevice.Viewport);

                IndicatorManager.Render(gameTime);
            }
            finally
            {
                DwarfGame.SpriteBatch.End();
            }

            if (Debugger.Switches.DrawComposites)
            {
                Vector2 offset = Vector2.Zero;
                foreach (var composite in CompositeLibrary.Composites)
                {
                    offset = composite.Value.DebugDraw(DwarfGame.SpriteBatch, (int)offset.X, (int)offset.Y);
                }
            }


            Master.Render(Game, gameTime);

            DwarfGame.SpriteBatch.GraphicsDevice.ScissorRectangle =
                DwarfGame.SpriteBatch.GraphicsDevice.Viewport.Bounds;


            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            lock (ScreenshotLock)
            {
                foreach (Screenshot shot in Screenshots)
                {
                    TakeScreenshot(shot.FileName, shot.Resolution);
                }

                Screenshots.Clear();
            }
        }
Exemple #26
0
 public void TweenOut(Drawer2D.Alignment alignment, float time = 0.5f, Func<float, float, float, float, float> tweenFn = null)
 {
     Point end = new Point(0, 0);
     switch (alignment)
     {
         case Drawer2D.Alignment.Bottom:
             end = new Point(LocalBounds.X, Parent.LocalBounds.Height);
             break;
         case Drawer2D.Alignment.Top:
             end = new Point(LocalBounds.X, -LocalBounds.Height);
             break;
         case Drawer2D.Alignment.Left:
             end = new Point(-LocalBounds.Width, LocalBounds.Y);
             break;
         case Drawer2D.Alignment.Right:
             end = new Point(Parent.LocalBounds.Width, LocalBounds.Y);
             break;
     }
     TweenOut(end, time, tweenFn);
 }
Exemple #27
0
        private void DeleteVoxels(IEnumerable <Voxel> refs)
        {
            foreach (Voxel v in refs.Select(r => r).Where(v => !v.IsEmpty))
            {
                if (IsBuildDesignation(v))
                {
                    BuildVoxelOrder vox = GetBuildDesignation(v);
                    vox.ToBuild.Destroy();
                    BuildDesignations.Remove(vox.Order);
                }
                else if (IsInRoom(v))
                {
                    Room existingRoom = GetMostLikelyRoom(v);

                    if (existingRoom == null)
                    {
                        continue;
                    }

                    Dialog destroyDialog = Dialog.Popup(PlayState.GUI, "Destroy room?",
                                                        "Do you want to destroy this " + Drawer2D.WrapColor(existingRoom.RoomData.Name, Color.DarkRed) + "?", Dialog.ButtonType.OkAndCancel);
                    destroyDialog.OnClosed += (status) => destroyDialog_OnClosed(status, existingRoom);
                    break;
                }
            }
        }