Exemplo n.º 1
0
 public ItemPopup(string texture, Vector2 position, IResourceCache<Texture2D> textureCache, Vector2 offSet)
 {
     this.texture = texture;
     this.position = position;
     this.textureCache = textureCache;
     OffSet = offSet;
 }
Exemplo n.º 2
0
        public override void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var texture = cache.GetResource(TextureKey);

            Vector2 origin;
            if (SrcRectangle.HasValue)
                origin = new Vector2(SrcRectangle.Value.Width / 2, SrcRectangle.Value.Height / 2);
            else
                origin = new Vector2(texture.Width / 2, texture.Height / 2);

            spriteBatch.Begin(
                SpriteSortMode.BackToFront,
                BlendState.AlphaBlend,
                null,
                null,
                null,
                null,
                globalTransform);

            spriteBatch.Draw(
                texture,
                Position,
                SrcRectangle,
                tintColor,
                Rotation,
                origin,
                Scale,
                SpriteEffects.None,
                0
            );

            spriteBatch.End();
        }
Exemplo n.º 3
0
 public SelectionEditorState(Game game, Camera camera, IResourceCache<Texture2D> cache, bool tilesOnly)
     : base(game, camera, cache)
 {
     selectedEntities = new List<Entity>();
     drillIndex = 0;
     this.tilesOnly = tilesOnly;
 }
Exemplo n.º 4
0
        public bool Contains(Vector2 point, IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var relativeTransform =
                Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0) *
                globalTransform;

            return RenderStack.Any(r => r.Contains(point, cache, relativeTransform));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Opens an existing resource index from the specified page store
        /// </summary>
        /// <param name="pageStore"></param>
        /// <param name="resourceTable">The table used to store long resource strings</param>
        /// <param name="rootNodeId">The ID of the page that contains the root node of the resource index</param>
        public ResourceIndex(IPageStore pageStore, IResourceTable resourceTable, ulong rootNodeId) : base(pageStore, rootNodeId)
        {
            //_resourceCache = new ConcurrentResourceCache();
            //_resourceIdCache = new ConcurrentResourceIdCache();
            _resourceCache= new LruResourceCache();
            _resourceIdCache = new LruResourceIdCache();
            _resourceStore = new ResourceStore(resourceTable);
#if DEBUG_BTREE
            Configuration.DebugId = "ResIx";
            Logging.LogDebug("Opened new {0} BTree with root page {1}", Configuration.DebugId, rootNodeId);
#endif
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates a new empty resource index in the specified page store
        /// </summary>
        /// <param name="txnId"></param>
        /// <param name="pageStore"></param>
        /// <param name="resourceTable"></param>
        public ResourceIndex(ulong txnId, IPageStore pageStore, IResourceTable resourceTable)  : base(txnId, pageStore)
        {
            //_resourceCache = new ConcurrentResourceCache();
            //_resourceIdCache = new ConcurrentResourceIdCache();
            _resourceCache = new LruResourceCache();
            _resourceIdCache = new LruResourceIdCache();
            _resourceStore = new ResourceStore(resourceTable);
#if DEBUG_BTREE
            Configuration.DebugId = "ResIx";
            Logging.LogDebug("Created new {0} BTree with root page {1}", Configuration.DebugId, RootId);
#endif
        }
Exemplo n.º 7
0
        public void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix transform)
        {
            var relativeTransform =
                Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0) *
                transform;

            foreach (var rendering in RenderStack)
            {
                rendering.Draw(spriteBatch, cache, relativeTransform);
            }
        }
Exemplo n.º 8
0
        protected override void LoadContent()
        {
            base.LoadContent();

            textureCache = new InMemoryResourceCache<Texture2D>(
                new ContentManagerProvider<Texture2D>(Content));

            var blank = new Texture2D(GraphicsDevice, 1, 1, false, SurfaceFormat.Color);
            blank.SetData(new[] { Color.White });
            textureCache.AddResource("blank", blank);

            spriteBatch = new SpriteBatch(GraphicsDeviceManager.GraphicsDevice);
        }
Exemplo n.º 9
0
        public static void DrawCircle(this SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Vector2 center, Vector2 size, Color color)
        {
            var texture = cache.GetResource("Textures/circle");
            var textureSize = new Vector2(texture.Width, texture.Height);

            spriteBatch.Draw(
                texture,
                center,
                null,
                color,
                0,
                textureSize / 2,
                size / textureSize,
                SpriteEffects.None,
                0
            );
        }
Exemplo n.º 10
0
 public Particle(Vector2 Position, Vector2 StartDirection, Vector2 EndDirection, float StartingLife, float ScaleBegin, float ScaleEnd, Color StartColor, Color EndColor, string texture, IResourceCache<Texture2D> textureCache, float MaxWidth, float MaxHeight)
 {
     this.Position = Position;
     this.StartingPos = Position;
     this.StartDirection = StartDirection;
     this.EndDirection = EndDirection;
     this.StartingLife = StartingLife;
     this.LifeLeft = StartingLife;
     this.ScaleBegin = ScaleBegin;
     this.ScaleEnd = ScaleEnd;
     this.StartColor = StartColor;
     this.EndColor = EndColor;
     this.texture = texture;
     this.textureCache = textureCache;
     this.MaxWidth = MaxWidth;
     this.MaxHeight = MaxHeight;
 }
Exemplo n.º 11
0
        public virtual void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var relativeTransform =
                Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0) *
                globalTransform;

            spriteBatch.Begin(
                SpriteSortMode.BackToFront,
                BlendState.AlphaBlend,
                null,
                null,
                null,
                null,
                Matrix.Identity);

            spriteBatch.DrawString(EngineGame.Instance.ScreenManager.Font, text, Position, color);
            spriteBatch.End();
        }
Exemplo n.º 12
0
        //Todo encapsulate this further down as components -- AnimatedSpriteState, AnimatedSpriteStateDirection
        public void LoadSprites(AnimationCollection collection, IResourceCache resourceCache)
        {
            float x = 0, y = 0, h = 0, w = 0;
            int   t = 0;

            foreach (var info in collection.Animations)
            {
                _sprites.Add(info.Name, new Dictionary <Direction, Sprite[]>());

                //Because we have a shitload of frames, we're going to store the average size as the AABB for each direction and each animation
                _averageAABBs.Add(info.Name, new Dictionary <Direction, Box2>());

                var sprites      = _sprites[info.Name];
                var averageAABBs = _averageAABBs[info.Name];
                AnimationStates.Add(info.Name, new AnimationState(info));
                foreach (var dir in Enum.GetValues(typeof(Direction)).Cast <Direction>())
                {
                    sprites.Add(dir, new Sprite[info.Frames]);
                    var thisDirSprites = sprites[dir];
                    for (var i = 0; i < info.Frames; i++)
                    {
                        var spritename = collection.Name.ToLowerInvariant() + "_" + info.Name.ToLowerInvariant() + "_"
                                         + DirectionToUriComponent(dir) + "_" + i;
                        thisDirSprites[i] = resourceCache.GetSprite(spritename);
                        var bounds = thisDirSprites[i].LocalBounds;
                        x += bounds.Left;
                        y += bounds.Top;
                        w += bounds.Width;
                        h += bounds.Height;
                        t++;
                    }
                    averageAABBs.Add(dir, Box2.FromDimensions(x / t, y / t, w / t, h / t));
                    t = 0;
                    x = 0;
                    y = 0;
                    w = 0;
                    h = 0;
                }
            }
        }
Exemplo n.º 13
0
        private Dictionary <string, List <Image> > GetTileImages(
            ITileDefinitionManager tileDefinitionManager,
            IResourceCache resourceCache,
            int tileSize)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            var images = new Dictionary <string, List <Image> >();

            foreach (var definition in tileDefinitionManager)
            {
                var sprite = definition.SpriteName;
                images[sprite] = new List <Image>(definition.Variants);

                if (string.IsNullOrEmpty(sprite))
                {
                    continue;
                }

                using var stream = resourceCache.ContentFileRead($"{TilesPath}{sprite}.png");
                Image tileSheet = Image.Load <Rgba32>(stream);

                if (tileSheet.Width != tileSize * definition.Variants || tileSheet.Height != tileSize)
                {
                    throw new NotSupportedException($"Unable to use tiles with a dimension other than {tileSize}x{tileSize}.");
                }

                for (var i = 0; i < definition.Variants; i++)
                {
                    var tileImage = tileSheet.Clone(o => o.Crop(new Rectangle(tileSize * i, 0, 32, 32)));
                    images[sprite].Add(tileImage);
                }
            }

            Console.WriteLine($"Indexed all tile images in {(int) stopwatch.Elapsed.TotalMilliseconds} ms");

            return(images);
        }
Exemplo n.º 14
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!cache.ContentFileExists(path))
            {
                throw new FileNotFoundException("Content file does not exist for audio sample.");
            }

            switch (GameController.Mode)
            {
            case GameController.DisplayMode.Headless:
                AudioStream = new AudioStream();
                break;

            case GameController.DisplayMode.Godot:
                using (var fileStream = cache.ContentFileRead(path))
                {
                    var stream = new Godot.AudioStreamOGGVorbis()
                    {
                        Data = fileStream.ToArray(),
                    };
                    if (stream.GetLength() == 0)
                    {
                        throw new InvalidDataException();
                    }
                    AudioStream = new AudioStream(stream);
                }
                break;

            case GameController.DisplayMode.Clyde:
                using (var fileStream = cache.ContentFileRead(path))
                {
                    AudioStream = IoCManager.Resolve <IClyde>().LoadAudioOggVorbis(fileStream);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 15
0
            public Effect(EffectSystemMessage effectcreation, IResourceCache resourceCache, IMapManager mapManager)
            {
                if (effectcreation.RsiState != null)
                {
                    var rsi = resourceCache
                              .GetResource <RSIResource>(new ResourcePath("/Textures/") / effectcreation.EffectSprite)
                              .RSI;
                    RsiState     = rsi[effectcreation.RsiState];
                    EffectSprite = RsiState.Frame0;
                }
                else
                {
                    EffectSprite = resourceCache
                                   .GetResource <TextureResource>(new ResourcePath("/Textures/") / effectcreation.EffectSprite)
                                   .Texture;
                }

                AnimationLoops         = effectcreation.AnimationLoops;
                AttachedEntityUid      = effectcreation.AttachedEntityUid;
                AttachedOffset         = effectcreation.AttachedOffset;
                Coordinates            = effectcreation.Coordinates;
                EmitterCoordinates     = effectcreation.EmitterCoordinates;
                Velocity               = effectcreation.Velocity;
                Acceleration           = effectcreation.Acceleration;
                RadialVelocity         = effectcreation.RadialVelocity;
                RadialAcceleration     = effectcreation.RadialAcceleration;
                TangentialVelocity     = effectcreation.TangentialVelocity;
                TangentialAcceleration = effectcreation.TangentialAcceleration;
                Age          = effectcreation.Born;
                Deathtime    = effectcreation.DeathTime;
                Rotation     = effectcreation.Rotation;
                RotationRate = effectcreation.RotationRate;
                Size         = effectcreation.Size;
                SizeDelta    = effectcreation.SizeDelta;
                Color        = effectcreation.Color;
                ColorDelta   = effectcreation.ColorDelta;
                Shaded       = effectcreation.Shaded;
                _mapManager  = mapManager;
            }
Exemplo n.º 16
0
 public Effect(EffectSystemMessage effectcreation, IResourceCache resourceCache)
 {
     EffectSprite = resourceCache
         .GetResource<TextureResource>(new ResourcePath("/Textures/") / effectcreation.EffectSprite).Texture;
     Coordinates = effectcreation.Coordinates;
     EmitterCoordinates = effectcreation.EmitterCoordinates;
     Velocity = effectcreation.Velocity;
     Acceleration = effectcreation.Acceleration;
     RadialVelocity = effectcreation.RadialVelocity;
     RadialAcceleration = effectcreation.RadialAcceleration;
     TangentialVelocity = effectcreation.TangentialVelocity;
     TangentialAcceleration = effectcreation.TangentialAcceleration;
     Age = effectcreation.Born;
     Deathtime = effectcreation.DeathTime;
     Rotation = effectcreation.Rotation;
     RotationRate = effectcreation.RotationRate;
     Size = effectcreation.Size;
     SizeDelta = effectcreation.SizeDelta;
     Color = effectcreation.Color;
     ColorDelta = effectcreation.ColorDelta;
     Shaded = effectcreation.Shaded;
 }
Exemplo n.º 17
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!cache.ContentFileExists(path))
            {
                throw new FileNotFoundException("Content file does not exist for texture");
            }
            if (!cache.TryGetDiskFilePath(path, out string diskPath))
            {
                throw new InvalidOperationException("Textures can only be loaded from disk.");
            }

            var res = ResourceLoader.Load(diskPath);

            if (!(res is DynamicFontData fontData))
            {
                throw new InvalidDataException("Path does not point to a font.");
            }

            FontData = fontData;
            Font     = new DynamicFont();
            Font.AddFallback(FontData);
        }
Exemplo n.º 18
0
        public ViewVariablesPropertyControl(IViewVariablesManagerInternal viewVars, IResourceCache resourceCache)
        {
            MouseFilter = MouseFilterMode.Pass;

            _viewVariablesManager = viewVars;
            _resourceCache        = resourceCache;

            MouseFilter       = MouseFilterMode.Pass;
            ToolTip           = "Click to expand";
            CustomMinimumSize = new Vector2(0, 25);

            VBox = new VBoxContainer {
                SeparationOverride = 0
            };
            AddChild(VBox);

            TopContainer = new HBoxContainer {
                SizeFlagsVertical = SizeFlags.FillExpand
            };
            VBox.AddChild(TopContainer);

            BottomContainer = new HBoxContainer
            {
                Visible = false
            };
            VBox.AddChild(BottomContainer);

            //var smallFont = new VectorFont(_resourceCache.GetResource<FontResource>("/Fonts/CALIBRI.TTF"), 10);

            _bottomLabel = new Label
            {
                //    FontOverride = smallFont,
                FontColorOverride = Color.DarkGray
            };
            BottomContainer.AddChild(_bottomLabel);

            NameLabel = new Label();
            TopContainer.AddChild(NameLabel);
        }
Exemplo n.º 19
0
        public TileSpawnWindow(ITileDefinitionManager tileDefinitionManager, IPlacementManager placementManager,
                               IResourceCache resourceCache)
        {
            __tileDefinitionManager = tileDefinitionManager;
            _placementManager       = placementManager;
            _resourceCache          = resourceCache;

            var vBox = new VBoxContainer();

            Contents.AddChild(vBox);
            var hBox = new HBoxContainer();

            vBox.AddChild(hBox);
            SearchBar = new LineEdit {
                PlaceHolder = "Search", SizeFlagsHorizontal = SizeFlags.FillExpand
            };
            SearchBar.OnTextChanged += OnSearchBarTextChanged;
            hBox.AddChild(SearchBar);

            ClearButton = new Button {
                Text = "Clear"
            };
            ClearButton.OnPressed += OnClearButtonPressed;
            hBox.AddChild(ClearButton);

            TileList = new ItemList {
                SizeFlagsVertical = SizeFlags.FillExpand
            };
            TileList.OnItemSelected   += TileListOnOnItemSelected;
            TileList.OnItemDeselected += TileListOnOnItemDeselected;
            vBox.AddChild(TileList);

            BuildTileList();

            _placementManager.PlacementChanged += OnPlacementCanceled;

            Title = "Place Tiles";
            SearchBar.GrabKeyboardFocus();
        }
Exemplo n.º 20
0
    public IRsiStateLike GetPrototypeIcon(EntityPrototype prototype, IResourceCache resourceCache)
    {
        var icon = IconComponent.GetPrototypeIcon(prototype, _resourceCache);

        if (icon != null)
        {
            return(icon);
        }

        if (!prototype.Components.ContainsKey("Sprite"))
        {
            return(SpriteComponent.GetFallbackState(resourceCache));
        }

        var dummy           = Spawn(prototype.ID, MapCoordinates.Nullspace);
        var spriteComponent = EnsureComp <SpriteComponent>(dummy);
        var result          = spriteComponent.Icon ?? SpriteComponent.GetFallbackState(resourceCache);

        Del(dummy);

        return(result);
    }
Exemplo n.º 21
0
        public static void DrawTiles(IResourceCache resCache, IEnumerable <TileRef> tileRefs, SpriteBatch floorBatch, SpriteBatch gasBatch)
        {
            Sprite          sprite  = null;
            ITileDefinition lastDef = null;
            var             ppm     = CluwneLib.Camera.PixelsPerMeter;

            foreach (var tileReference in tileRefs)
            {
                if (tileReference.TileDef != lastDef)
                {
                    lastDef = tileReference.TileDef;
                    sprite  = resCache.GetSprite(lastDef.SpriteName);
                }

                if (sprite == null)
                {
                    continue;
                }

                sprite.Position = new Vector2(tileReference.X, tileReference.Y) * ppm;
                floorBatch.Draw(sprite);
            }
        }
Exemplo n.º 22
0
        public MainMenuControl(IResourceCache resCache, IConfigurationManager configMan)
        {
            RobustXamlLoader.Load(this);

            LayoutContainer.SetAnchorPreset(this, LayoutContainer.LayoutPreset.Wide);

            LayoutContainer.SetAnchorPreset(VBox, LayoutContainer.LayoutPreset.TopRight);
            LayoutContainer.SetMarginRight(VBox, -25);
            LayoutContainer.SetMarginTop(VBox, 30);
            LayoutContainer.SetGrowHorizontal(VBox, LayoutContainer.GrowDirection.Begin);

            var logoTexture = resCache.GetResource <TextureResource>("/Textures/Logo/logo.png");

            Logo.Texture = logoTexture;

            var currentUserName = configMan.GetCVar(CVars.PlayerName);

            UsernameBox.Text = currentUserName;

            LayoutContainer.SetAnchorPreset(VersionLabel, LayoutContainer.LayoutPreset.BottomRight);
            LayoutContainer.SetGrowHorizontal(VersionLabel, LayoutContainer.GrowDirection.Begin);
            LayoutContainer.SetGrowVertical(VersionLabel, LayoutContainer.GrowDirection.Begin);
        }
Exemplo n.º 23
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!GameController.OnGodot)
            {
                return;
            }
            using (var stream = cache.ContentFileRead(path))
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    var code = reader.ReadToEnd();
                    GodotShader = new Godot.Shader
                    {
                        Code = code,
                    };
                }

            var properties = Godot.VisualServer.ShaderGetParamList(GodotShader.GetRid());

            foreach (var dict in properties.Cast <IDictionary <object, object> >())
            {
                Parameters.Add((string)dict["name"], DetectParamType(dict));
            }
        }
Exemplo n.º 24
0
        public MainMenuControl(IResourceCache resCache, IConfigurationManager configMan)
        {
            RobustXamlLoader.Load(this);

            Panel.PanelOverride   = new StyleBoxFlat(Color.Black);
            WIPLabel.FontOverride = new VectorFont(resCache.GetResource <FontResource>("/Fonts/NotoSans-Bold.ttf"), 32);

            LayoutContainer.SetAnchorPreset(this, LayoutContainer.LayoutPreset.Wide);

            LayoutContainer.SetAnchorPreset(VBox, LayoutContainer.LayoutPreset.Center);
            LayoutContainer.SetGrowHorizontal(VBox, LayoutContainer.GrowDirection.Both);
            LayoutContainer.SetGrowVertical(VBox, LayoutContainer.GrowDirection.Both);

            var logoTexture = resCache.GetResource <TextureResource>("/OpenDream/Logo/logo.png");

            Logo.Texture = logoTexture;

            var currentUserName = configMan.GetCVar(CVars.PlayerName);

            UserNameBox.Text = currentUserName;

            AddressBoxProtected.Text = "127.0.0.1:25566";
        }
Exemplo n.º 25
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!cache.TryContentFileRead(path, out var stream))
            {
                throw new FileNotFoundException("Content file does not exist for texture");
            }

            // Primarily for tracking down iCCP sRGB errors in the image files.
            Logger.DebugS("res.tex", $"Loading texture {path}.");

            var loadParameters = _tryLoadTextureParameters(cache, path) ?? TextureLoadParameters.Default;

            var manager = IoCManager.Resolve <IClyde>();

            using var image = Image.Load <Rgba32>(stream);

            Texture = manager.LoadTextureFromImage(image, path.ToString(), loadParameters);

            if (cache is IResourceCacheInternal cacheInternal)
            {
                cacheInternal.TextureLoaded(new TextureLoadedEventArgs(path, image, this));
            }
        }
Exemplo n.º 26
0
 public override void Load(IResourceCache cache, ResourcePath path)
 {
     if (!cache.ContentFileExists(path))
     {
         throw new FileNotFoundException("Content file does not exist for texture");
     }
     if (!cache.TryGetDiskFilePath(path, out string diskPath))
     {
         throw new InvalidOperationException("Textures can only be loaded from disk.");
     }
     godotTexture = new Godot.ImageTexture();
     godotTexture.Load(diskPath);
     // If it fails to load it won't change the texture dimensions, so they'll still be at zero.
     if (godotTexture.GetWidth() == 0)
     {
         throw new InvalidDataException();
     }
     // Disable filter by default because pixel art.
     godotTexture.SetFlags(godotTexture.GetFlags() & ~(int)Godot.Texture.FlagsEnum.Filter);
     Texture = new GodotTextureSource(godotTexture);
     // Primarily for tracking down iCCP sRGB errors in the image files.
     Logger.Debug($"Loaded texture {Path.GetFullPath(diskPath)}.");
 }
Exemplo n.º 27
0
        private static TextureLoadParameters?_tryLoadTextureParameters(IResourceCache cache, ResourcePath path)
        {
            var metaPath = path.WithName(path.Filename + ".yml");

            if (cache.TryContentFileRead(metaPath, out var stream))
            {
                YamlDocument yamlData;
                using (var reader = new StreamReader(stream, EncodingHelpers.UTF8))
                {
                    var yamlStream = new YamlStream();
                    yamlStream.Load(reader);
                    if (yamlStream.Documents.Count == 0)
                    {
                        return(null);
                    }

                    yamlData = yamlStream.Documents[0];
                }

                return(TextureLoadParameters.FromYaml((YamlMappingNode)yamlData.RootNode));
            }
            return(null);
        }
Exemplo n.º 28
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            var    manifestPath = path / "meta.json";
            string manifestContents;

            using (var manifestFile = cache.ContentFileRead(manifestPath))
                using (var reader = new StreamReader(manifestFile))
                {
                    manifestContents = reader.ReadToEnd();
                }

#if DEBUG
            if (RSISchema != null)
            {
                var errors = RSISchema.Validate(manifestContents);
                if (errors.Count != 0)
                {
                    Logger.Error($"Unable to load RSI from '{path}', {errors.Count} errors:");

                    foreach (var error in errors)
                    {
                        Logger.Error("{0}", error.ToString());
                    }

                    throw new RSILoadException($"{errors.Count} errors while loading RSI. See console.");
                }
            }
#endif

            // Ok schema validated just fine.
            var manifestJson = JObject.Parse(manifestContents);
            var size         = manifestJson["size"].ToObject <Vector2u>();

            var rsi = new RSI(size);

            var images = new List <(Image <Rgba32> src, Vector2i offset)>();
            var directionFramesList = new List <(Texture, float)[]>();
        public EntitySpawnSelectButton(EntityPrototype entityTemplate, string templateName,
                                       IResourceCache resourceCache)
        {
            _resourceCache = resourceCache;

            var    spriteNameParam = entityTemplate.GetBaseSpriteParamaters().FirstOrDefault();
            string SpriteName      = "";

            if (spriteNameParam != null)
            {
                SpriteName = spriteNameParam.GetValue <string>();
            }
            string ObjectName = entityTemplate.Name;

            associatedTemplate     = entityTemplate;
            associatedTemplateName = templateName;

            objectSprite = _resourceCache.GetSprite(SpriteName);

            font       = _resourceCache.GetResource <FontResource>(@"Fonts/CALIBRI.TTF").Font;
            name       = new TextSprite("Label" + SpriteName, "Name", font);
            name.Color = Color4.Black;
            name.Text  = ObjectName;
        }
        public MagicMirrorWindow(MagicMirrorBoundUserInterface owner, IResourceCache resourceCache, ILocalizationManager localization)
        {
            Title = "Magic Mirror";

            _hairPickerWindow = new HairPickerWindow(resourceCache, localization);
            _hairPickerWindow.Populate();
            _hairPickerWindow.OnHairStylePicked += newStyle => owner.HairSelected(newStyle, false);
            _hairPickerWindow.OnHairColorPicked += newColor => owner.HairColorSelected(newColor, false);

            _facialHairPickerWindow = new FacialHairPickerWindow(resourceCache, localization);
            _facialHairPickerWindow.Populate();
            _facialHairPickerWindow.OnHairStylePicked += newStyle => owner.HairSelected(newStyle, true);
            _facialHairPickerWindow.OnHairColorPicked += newColor => owner.HairColorSelected(newColor, true);

            var vBox = new VBoxContainer();

            Contents.AddChild(vBox);

            var hairButton = new Button
            {
                Text = localization.GetString("Customize hair")
            };

            hairButton.OnPressed += args => _hairPickerWindow.Open();
            vBox.AddChild(hairButton);

            var facialHairButton = new Button
            {
                Text = localization.GetString("Customize facial hair")
            };

            facialHairButton.OnPressed += args => _facialHairPickerWindow.Open();
            vBox.AddChild(facialHairButton);

            Size = CombinedMinimumSize;
        }
        public EscapeMenu(IClientConsole console,
                          ITileDefinitionManager tileDefinitionManager,
                          IPlacementManager placementManager,
                          IPrototypeManager prototypeManager,
                          IResourceCache resourceCache,
                          IConfigurationManager configSystem, ILocalizationManager localizationManager)
        {
            _configSystem           = configSystem;
            _localizationManager    = localizationManager;
            _console                = console;
            __tileDefinitionManager = tileDefinitionManager;
            _placementManager       = placementManager;
            _prototypeManager       = prototypeManager;
            _resourceCache          = resourceCache;

            IoCManager.InjectDependencies(this);

            _sandboxManager.AllowedChanged      += AllowedChanged;
            _conGroupController.ConGroupUpdated += UpdateSpawnButtonStates;

            PerformLayout();

            UpdateSpawnButtonStates();
        }
Exemplo n.º 32
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!cache.ContentFileExists(path))
            {
                throw new FileNotFoundException("Content file does not exist for audio sample.");
            }

            using (var fileStream = cache.ContentFileRead(path))
            {
                var clyde = IoCManager.Resolve <IClydeAudio>();
                if (path.Extension == "ogg")
                {
                    AudioStream = clyde.LoadAudioOggVorbis(fileStream, path.ToString());
                }
                else if (path.Extension == "wav")
                {
                    AudioStream = clyde.LoadAudioWav(fileStream, path.ToString());
                }
                else
                {
                    throw new NotSupportedException("Unable to load audio files outside of ogg Vorbis or PCM wav");
                }
            }
        }
Exemplo n.º 33
0
        public override void Load(IResourceCache cache, ResourcePath path)
        {
            if (!GameController.OnGodot)
            {
                return;
            }
            if (!cache.ContentFileExists(path))
            {
                throw new FileNotFoundException("Content file does not exist for audio sample.");
            }

            using (var fileStream = cache.ContentFileRead(path))
            {
                var stream = new Godot.AudioStreamOGGVorbis()
                {
                    Data = fileStream.ToArray(),
                };
                if (stream.GetLength() == 0)
                {
                    throw new InvalidDataException();
                }
                AudioStream = new GodotAudioStreamSource(stream);
            }
        }
Exemplo n.º 34
0
 public Dart(World world, IResourceCache<Texture2D> texCache)
     : base(world)
 {
     textureCache = texCache;
 }
Exemplo n.º 35
0
        public LobbyGui(IEntityManager entityManager,
                        IResourceCache resourceCache,
                        IClientPreferencesManager preferencesManager)
        {
            var margin = new MarginContainer
            {
                MarginBottomOverride = 20,
                MarginLeftOverride   = 20,
                MarginRightOverride  = 20,
                MarginTopOverride    = 20,
            };

            AddChild(margin);

            var panelTex = resourceCache.GetTexture("/Textures/Interface/Nano/button.svg.96dpi.png");
            var back     = new StyleBoxTexture
            {
                Texture  = panelTex,
                Modulate = new Color(37, 37, 42),
            };

            back.SetPatchMargin(StyleBox.Margin.All, 10);

            var panel = new PanelContainer
            {
                PanelOverride = back
            };

            margin.AddChild(panel);

            var vBox = new VBoxContainer {
                SeparationOverride = 0
            };

            margin.AddChild(vBox);

            var topHBox = new HBoxContainer
            {
                CustomMinimumSize = (0, 40),
                Children          =
                {
                    new MarginContainer
                    {
                        MarginLeftOverride = 8,
                        Children           =
                        {
                            new Label
                            {
                                Text         = Loc.GetString("Lobby"),
                                StyleClasses ={ StyleNano.StyleClassLabelHeadingBigger                    },

                                /*MarginBottom = 40,
                                 * MarginLeft = 8,*/
                                VAlign = Label.VAlignMode.Center
                            }
                        }
                    },
                    (ServerName = new Label
                    {
                        StyleClasses ={ StyleNano.StyleClassLabelHeadingBigger                    },

                        /*MarginBottom = 40,
                         * GrowHorizontal = GrowDirection.Both,*/
                        VAlign = Label.VAlignMode.Center,
                        SizeFlagsHorizontal = SizeFlags.Expand | SizeFlags.ShrinkCenter
                    }),
                    (CreditsButton = new Button
                    {
                        SizeFlagsHorizontal = SizeFlags.ShrinkEnd,
                        Text = Loc.GetString("Credits"),
                        StyleClasses ={ StyleNano.StyleClassButtonBig                             },
                        //GrowHorizontal = GrowDirection.Begin
                    }),
                    (LeaveButton = new Button
                    {
                        SizeFlagsHorizontal = SizeFlags.ShrinkEnd,
                        Text = Loc.GetString("Leave"),
                        StyleClasses ={ StyleNano.StyleClassButtonBig                             },
                        //GrowHorizontal = GrowDirection.Begin
                    })
                }
            };

            vBox.AddChild(topHBox);

            vBox.AddChild(new PanelContainer
            {
                PanelOverride = new StyleBoxFlat
                {
                    BackgroundColor          = StyleNano.NanoGold,
                    ContentMarginTopOverride = 2
                },
            });

            var hBox = new HBoxContainer
            {
                SizeFlagsVertical  = SizeFlags.FillExpand,
                SeparationOverride = 0
            };

            vBox.AddChild(hBox);

            CharacterPreview = new LobbyCharacterPreviewPanel(
                entityManager,
                preferencesManager)
            {
                SizeFlagsHorizontal = SizeFlags.None
            };
            hBox.AddChild(new VBoxContainer
            {
                SizeFlagsHorizontal = SizeFlags.FillExpand,
                SeparationOverride  = 0,
                Children            =
                {
                    CharacterPreview,

                    new StripeBack
                    {
                        Children =
                        {
                            new MarginContainer
                            {
                                MarginRightOverride  = 3,
                                MarginLeftOverride   = 3,
                                MarginTopOverride    = 3,
                                MarginBottomOverride = 3,
                                Children             =
                                {
                                    new HBoxContainer
                                    {
                                        SeparationOverride = 6,
                                        Children           =
                                        {
                                            (ObserveButton          = new Button
                                            {
                                                Text                = Loc.GetString("Observe"),
                                                StyleClasses        = { StyleNano.StyleClassButtonBig }
                                            }),
                                            (StartTime              = new Label
                                            {
                                                SizeFlagsHorizontal = SizeFlags.FillExpand,
                                                Align               = Label.AlignMode.Right,
                                                FontColorOverride   = Color.DarkGray,
                                                StyleClasses        = { StyleNano.StyleClassLabelBig  }
                                            }),
                                            (ReadyButton            = new Button
                                            {
                                                ToggleMode          = true,
                                                Text                = Loc.GetString("Ready Up"),
                                                StyleClasses        = { StyleNano.StyleClassButtonBig }
                                            }),
                                        }
                                    }
                                }
                            }
                        }
                    },

                    new MarginContainer
                    {
                        MarginRightOverride  = 3,
                        MarginLeftOverride   = 3,
                        MarginTopOverride    = 3,
                        MarginBottomOverride = 3,
                        SizeFlagsVertical    = SizeFlags.FillExpand,
                        Children             =
                        {
                            (Chat     = new ChatBox
                            {
                                Input = { PlaceHolder = Loc.GetString("Say something!") }
                            })
                        }
                    },
                }
            });

            hBox.AddChild(new PanelContainer
            {
                PanelOverride = new StyleBoxFlat {
                    BackgroundColor = StyleNano.NanoGold
                }, CustomMinimumSize = (2, 0)
            });
Exemplo n.º 36
0
 public NonAxisAlignedBoundingBox GetNonAxisAlignedBoundingBox(IResourceCache<Texture2D> cache, Matrix globalTransform)
 {
     throw new NotImplementedException(); //don't use parented rendering for previews
 }
 public AdminNameOverlay(AdminSystem system, IEntityManager entityManager, IEyeManager eyeManager, IResourceCache resourceCache, EntityLookupSystem entityLookup)
 {
     _system        = system;
     _entityManager = entityManager;
     _eyeManager    = eyeManager;
     _entityLookup  = entityLookup;
     ZIndex         = 200;
     _font          = new VectorFont(resourceCache.GetResource <FontResource>("/Fonts/NotoSans/NotoSans-Regular.ttf"), 10);
 }
Exemplo n.º 38
0
        public Vector2 GetCenter(IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var relativeTransform =
                Matrix.CreateScale(new Vector3(Scale.X, Scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(Position.X, Position.Y, 0) *
                globalTransform;

            var centerAcc = Vector2.Zero;
            RenderStack.ForEach(r => centerAcc += r.GetCenter(cache, relativeTransform));

            return centerAcc / RenderStack.Count;
        }
Exemplo n.º 39
0
 public Vector2 GetCenter(IResourceCache<Texture2D> cache, Matrix transform)
 {
     return Vector2.One;
 }
Exemplo n.º 40
0
        public void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix transform)
        {
            var relativeTransform =
                Matrix.CreateScale(new Vector3(Scale, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(new Vector3(Position, 0)) *
                transform;

            frames[CurrentFrame].Draw(spriteBatch, cache, relativeTransform);
        }
Exemplo n.º 41
0
 public NonAxisAlignedBoundingBox GetNonAxisAlignedBoundingBox(IResourceCache<Texture2D> cache, Matrix globalTransform)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 42
0
 public void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix transform)
 {
 }
Exemplo n.º 43
0
 public CameraZoomState(Game game, Camera camera, IResourceCache<Texture2D> cache)
     : base(game, camera, cache)
 {
 }
Exemplo n.º 44
0
 public CachingResourceFinder(IResourceCache cache, IResourceFinder inner)
 {
     _cache = cache;
     _inner = inner;
 }
Exemplo n.º 45
0
        public void Expand(IResourceCache<Texture2D> cache, Vector2 dragOffset, Vector2 origScale, Matrix transform)
        {
            var tex = cache.GetResource(Texture);

            var size = origScale * new Vector2(tex.Width / 2, tex.Height / 2) * 2;

            var relativeTransform =
                Matrix.CreateRotationZ(Rotation) *
                transform;

            var offsetInMeshFrame = Vector2.Transform(dragOffset, relativeTransform);

            Scale += (2 * offsetInMeshFrame) / size;
        }
Exemplo n.º 46
0
        public void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix transform)
        {
            Parent.Draw(spriteBatch, cache, transform);

            var relativeTransform =
                Matrix.CreateScale(new Vector3(Parent.Scale, 1)) *
                Matrix.CreateRotationZ(Parent.Rotation) *
                Matrix.CreateTranslation(new Vector3(Parent.Position, 0)) *
                transform;

            Children.ForEach(x => x.Draw(spriteBatch, cache, relativeTransform));
        }
Exemplo n.º 47
0
 public Vector2 GetCenter(IResourceCache<Texture2D> cache, Matrix globalTransform)
 {
     throw new NotImplementedException(); //don't use parented rendering for previews
 }
Exemplo n.º 48
0
 public TilePainter(ClientIntegrationInstance client, ServerIntegrationInstance server)
 {
     _sTileDefinitionManager = server.ResolveDependency <ITileDefinitionManager>();
     _cResourceCache         = client.ResolveDependency <IResourceCache>();
 }
Exemplo n.º 49
0
 public bool Contains(Vector2 point, IResourceCache<Texture2D> cache, Matrix globalTransform)
 {
     throw new NotImplementedException(); //don't use parented rendering for previews
 }
 public void InitializeResources(IResourceCache resourceCache)
 {
     tileSprite = resourceCache.GetSprite("space_texture");
 }
Exemplo n.º 51
0
 /// <inheritdoc />
 public override void Load(IResourceCache cache, string path, Stream stream)
 {
     Font = new Font(stream);
 }
 public StaticMeshPlacementEditorState(Game game, Camera camera, IResourceCache<Texture2D> cache, string textureKey)
     : base(game, camera, cache)
 {
     this.textureKey = textureKey;
 }
Exemplo n.º 53
0
 protected override Texture2D GetTexture(IResourceCache<Texture2D> textureCache)
 {
     return textureCache.GetResource(CENTIPEDE_TEXTURE);
 }
Exemplo n.º 54
0
        public bool Contains(Vector2 point, IResourceCache<Texture2D> cache, Matrix transform)
        {
            var texture = cache.GetResource(textureKey);

            var relativeTransform =
                Matrix.CreateScale(new Vector3(scale.X, scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0)) *
                transform;

            var pointInRenderCoordinates =
                Vector2.Transform(point, Matrix.Invert(relativeTransform));

            return (pointInRenderCoordinates.X >= -texture.Width / 2) &&
                   (pointInRenderCoordinates.X <= texture.Width / 2) &&
                   (pointInRenderCoordinates.Y >= -texture.Height / 2) &&
                   (pointInRenderCoordinates.Y <= texture.Height / 2);
        }
Exemplo n.º 55
0
        internal static void LoadPreTexture(IResourceCache cache, LoadStepData data)
        {
            var metadata = LoadRsiMetadata(cache, data.Path);

            var stateCount = metadata.States.Length;
            var toAtlas    = new StateReg[stateCount];

            var frameSize = metadata.Size;
            var rsi       = new RSI(frameSize, data.Path, metadata.States.Length);

            var callbackOffsets = new Dictionary <RSI.StateId, Vector2i[][]>(stateCount);

            // Check for duplicate states
            for (var i = 0; i < metadata.States.Length; i++)
            {
                var stateId = metadata.States[i].StateId;

                for (int j = i + 1; j < metadata.States.Length; j++)
                {
                    if (stateId == metadata.States[j].StateId)
                    {
                        throw new RSILoadException($"RSI '{data.Path}' has a duplicate stateId '{stateId}'.");
                    }
                }
            }

            // Do every state.
            for (var index = 0; index < metadata.States.Length; index++)
            {
                ref var reg = ref toAtlas[index];

                var stateObject = metadata.States[index];
                // Load image from disk.
                var texPath = data.Path / (stateObject.StateId + ".png");
                using (var stream = cache.ContentFileRead(texPath))
                {
                    reg.Src = Image.Load <Rgba32>(stream);
                }

                if (reg.Src.Width % frameSize.X != 0 || reg.Src.Height % frameSize.Y != 0)
                {
                    var regDims  = $"{reg.Src.Width}x{reg.Src.Height}";
                    var iconDims = $"{frameSize.X}x{frameSize.Y}";
                    throw new RSILoadException($"State '{stateObject.StateId}' image size ({regDims}) is not a multiple of the icon size ({iconDims}).");
                }

                // Load all frames into a list so we can operate on it more sanely.
                reg.TotalFrameCount = stateObject.Delays.Sum(delayList => delayList.Length);

                var(foldedDelays, foldedIndices) = FoldDelays(stateObject.Delays);

                var textures       = new Texture[foldedIndices.Length][];
                var callbackOffset = new Vector2i[foldedIndices.Length][];

                for (var i = 0; i < textures.Length; i++)
                {
                    textures[i]       = new Texture[foldedIndices[0].Length];
                    callbackOffset[i] = new Vector2i[foldedIndices[0].Length];
                }

                reg.Output  = textures;
                reg.Indices = foldedIndices;
                reg.Offsets = callbackOffset;

                var state = new RSI.State(frameSize, rsi, stateObject.StateId, stateObject.DirType, foldedDelays,
                                          textures);
                rsi.AddState(state);

                callbackOffsets[stateObject.StateId] = callbackOffset;
            }
Exemplo n.º 56
0
        public virtual void Draw(SpriteBatch spriteBatch, IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var texture = cache.GetResource(textureKey);

            Vector2 origin;
            if (srcRectangle.HasValue)
                origin = new Vector2(srcRectangle.Value.Width / 2, srcRectangle.Value.Height / 2);
            else
                origin = new Vector2(texture.Width / 2, 0);
                //origin = new Vector2(texture.Width / 2, texture.Height / 2);

            if (InputManager.Instance.Pressed(Keys.B))
            {
                //Debugger.Break();
            }

            spriteBatch.Begin(
                SpriteSortMode.BackToFront,
                BlendState.AlphaBlend,
                null,
                null,
                null,
                null,
                globalTransform);

            spriteBatch.Draw(
                texture,
                Position - new Vector2(0, texture.Height / 4),
                srcRectangle,
                Color.White,
                (float)Rotation,
                origin,
                scale,
                SpriteEffects.None,
                0
            );

            spriteBatch.End();
        }
 protected StyleBase(IResourceCache resCache)
 {
     FontLib = new FontLibrary(
         new FontClass(Id: "notosans", Style: (FontStyle) default, Size: (FontSize)12)
Exemplo n.º 58
0
        public Vector2 GetCenter(IResourceCache<Texture2D> cache, Matrix transform)
        {
            var texture = cache.GetResource(textureKey);

            return Vector2.Transform(Position, transform);
        }
 public override void InitializeResources(IResourceCache resourceCache)
 {
     tileSprite = resourceCache.GetSprite("floor_texture");
 }
Exemplo n.º 60
0
        public NonAxisAlignedBoundingBox GetNonAxisAlignedBoundingBox(IResourceCache<Texture2D> cache, Matrix globalTransform)
        {
            var texture = cache.GetResource(textureKey);

            var relativeTransform =
                Matrix.CreateScale(new Vector3(scale.X, scale.Y, 1)) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(new Vector3(Position.X, Position.Y, 0)) *
                globalTransform;

            var topLeft = Vector2.Transform(
                new Vector2(-texture.Width / 2, -texture.Height / 2),
                relativeTransform);
            var topRight = Vector2.Transform(
                new Vector2(texture.Width / 2, -texture.Height / 2),
                relativeTransform);
            var botLeft = Vector2.Transform(
                new Vector2(-texture.Width / 2, texture.Height / 2),
                relativeTransform);
            var botRight = Vector2.Transform(
                new Vector2(texture.Width / 2, texture.Height / 2),
                relativeTransform);

            if (InputManager.Instance.Pressed(Keys.N))
            {
                Debugger.Break();
            }

            return new NonAxisAlignedBoundingBox(topLeft, topRight, botLeft, botRight);
        }