예제 #1
0
파일: FormImage.cs 프로젝트: lvyitian/Alex
        public FormImage(string url)
        {
            Image = url;

            Alex.Instance.ThreadPool.QueueUserWorkItem(() =>
            {
                try
                {
                    byte[] imageData = _cache.GetOrAdd(Image, (path) =>
                    {
                        using (WebClient wc = new WebClient())
                        {
                            var data = wc.DownloadData(path);

                            return(data);
                        }
                    });

                    Background = (TextureSlice2D)TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, SixLabors.ImageSharp.Image.Load <Rgba32>(imageData));
                }
                catch (Exception ex)
                {
                    Log.Error(ex, $"Could not convert image!");
                }
            });
        }
예제 #2
0
        public void CreateOrUpdateProfile(ProfileType type, PlayerProfile profile, bool setActive = false)
        {
            if (profile.Skin.Texture == null)
            {
                if (Alex.Resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture))
                {
                    profile.Skin.Texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, rawTexture);
                    profile.Skin.Slim    = true;
                }
            }
            SavedProfile savedProfile;

            if (Profiles.TryGetValue(profile.Uuid, out savedProfile))
            {
                savedProfile.Profile   = profile;
                Profiles[profile.Uuid] = savedProfile;
            }
            else
            {
                savedProfile         = new SavedProfile();
                savedProfile.Type    = type;
                savedProfile.Profile = profile;
                Profiles.Add(profile.Uuid, savedProfile);
            }

            if (setActive)
            {
                //ActiveProfile = savedProfile;
                Alex.Services.GetService <IPlayerProfileService>()?.Force(profile);
                //_playerProfileService.Force(profile);
            }

            Alex.UIThreadQueue.Enqueue(SaveProfiles);
        }
예제 #3
0
 public ResourcePackEntry(ResourcePackManifest manifest, string path) : this(path, manifest.Name, manifest.Description)
 {
     if (manifest.Icon != null)
     {
         _icon.Texture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, manifest.Icon);
     }
 }
예제 #4
0
        internal void UpdateSkin(PooledTexture2D skinTexture)
        {
            if (skinTexture == null)
            {
                skinTexture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, Alex.PlayerTexture);
            }

            //if (skinSlim)
            {
                var gotModel = ModelFactory.TryGetModel(GeometryName,
                                                        out EntityModel m);

                ValidModel = gotModel;
                if (gotModel || ModelFactory.TryGetModel("geometry.humanoid.customSlim", out m))
                {
                    if (!gotModel)
                    {
                    }
                    _model        = m;
                    ModelRenderer = new EntityModelRenderer(_model, skinTexture);
                    //UpdateModelParts();
                }
            }

            /*else
             * {
             *      if (ModelFactory.TryGetModel("geometry.humanoid.custom",
             *              out EntityModel m))
             *      {
             *              _model = m;
             *              ModelRenderer = new EntityModelRenderer(_model, skinTexture);
             *              UpdateModelParts();
             *      }
             * }*/
        }
예제 #5
0
 private void ApplyModel(Entity entity)
 {
     if (Alex.PlayerModel != null && Alex.PlayerTexture != null)
     {
         var texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, Alex.PlayerTexture);
         entity.ModelRenderer = new EntityModelRenderer(Alex.PlayerModel, texture);
     }
 }
예제 #6
0
        internal void UpdateSkin(PooledTexture2D skinTexture)
        {
            if (skinTexture != null && ModelRenderer != null)
            {
                ModelRenderer.Texture = skinTexture;
                return;
            }

            string geometry = "geometry.humanoid.customSlim";

            if (skinTexture == null)
            {
                string skinVariant = "entity/alex";
                var    uuid        = UUID.GetBytes();

                if ((uuid[3] ^ uuid[7] ^ uuid[11] ^ uuid[15]) % 2 == 0)
                {
                    skinVariant = "entity/steve";
                    geometry    = "geometry.humanoid.custom";
                }

                if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(skinVariant, out var rawTexture))
                {
                    skinTexture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, rawTexture);
                    //skinBitmap = rawTexture;
                }
                else
                {
                    skinTexture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, Alex.PlayerTexture);
                }
            }

            //if (skinSlim)
            {
                //var gotModel = ModelFactory.TryGetModel(GeometryName,
                //	out EntityModel m);

                //ValidModel = gotModel;
                if (ModelFactory.TryGetModel(geometry, out var m))
                {
                    _model        = m;
                    ValidModel    = true;
                    ModelRenderer = new EntityModelRenderer(_model, skinTexture);
                    //UpdateModelParts();
                }
            }

            /*else
             * {
             *      if (ModelFactory.TryGetModel("geometry.humanoid.custom",
             *              out EntityModel m))
             *      {
             *              _model = m;
             *              ModelRenderer = new EntityModelRenderer(_model, skinTexture);
             *              UpdateModelParts();
             *      }
             * }*/
        }
예제 #7
0
        public World(Alex alex, GraphicsDevice graphics, AlexOptions options, Camera camera,
                     INetworkProvider networkProvider)
        {
            Alex     = alex;
            Graphics = graphics;
            Camera   = camera;
            Options  = options;

            PhysicsEngine = new PhysicsManager(alex, this);
            ChunkManager  = new ChunkManager(alex, graphics, options, this);
            EntityManager = new EntityManager(graphics, this, networkProvider);
            Ticker        = new TickManager(this);
            PlayerList    = new PlayerList();

            ChunkManager.Start();
            var    profileService = alex.Services.GetService <IPlayerProfileService>();
            string username       = string.Empty;
            Skin   skin           = profileService?.CurrentProfile?.Skin;

            if (skin == null)
            {
                alex.Resources.ResourcePack.TryGetBitmap("entity/alex", out Bitmap rawTexture);
                var t = TextureUtils.BitmapToTexture2D(graphics, rawTexture);
                skin = new Skin()
                {
                    Texture = t,
                    Slim    = true
                };
            }

            if (!string.IsNullOrWhiteSpace(profileService?.CurrentProfile?.Username))
            {
                username = profileService.CurrentProfile.Username;
            }

            Player = new Player(graphics, alex, username, this, skin, networkProvider, PlayerIndex.One);

            Player.KnownPosition = new PlayerLocation(GetSpawnPoint());
            Camera.MoveTo(Player.KnownPosition, Vector3.Zero);

            Options.FieldOfVision.ValueChanged += FieldOfVisionOnValueChanged;
            Camera.FOV = Options.FieldOfVision.Value;

            PhysicsEngine.AddTickable(Player);

            Player.Inventory.IsPeInventory = true;
            if (ItemFactory.TryGetItem("minecraft:diamond_sword", out var sword))
            {
                Player.Inventory[Player.Inventory.SelectedSlot] = sword;
                Player.Inventory.MainHand = sword;
            }
            else
            {
                Log.Warn($"Could not get diamond sword!");
            }
        }
예제 #8
0
 public static void LoadResources(GraphicsDevice graphicsDevice, McResourcePack resourcePack)
 {
     if (resourcePack.TryGetBitmap("minecraft:entity/chest/normal", out var bmp))
     {
         ChestTexture = TextureUtils.BitmapToTexture2D(graphicsDevice, bmp);
     }
     else
     {
         Log.Warn($"Could not load chest texture.");
     }
 }
예제 #9
0
        public ProfileSelectionState(GuiPanoramaSkyBox skyBox, Alex alex)
        {
            Alex           = alex;
            _skyBox        = skyBox;
            ProfileService = GetService <IPlayerProfileService>();

            Title = "Select Profile";

            Background = new GuiTexture2D(_skyBox, TextureRepeatMode.Stretch);

            base.ListContainer.ChildAnchor = Alignment.MiddleCenter;
            base.ListContainer.Orientation = Orientation.Horizontal;

            Footer.AddRow(row =>
            {
                row.AddChild(_addBtn = new GuiButton("Add", AddClicked)
                {
                });
                row.AddChild(_editBtn = new GuiButton("Edit", EditClicked)
                {
                    Enabled = false
                });
                row.AddChild(_deleteBtn = new GuiButton("Delete", DeleteClicked)
                {
                    Enabled = false
                });
            });

            Footer.AddRow(row =>
            {
                //   row.ChildAnchor = Alignment.CenterX;
                row.AddChild(_selectBtn = new GuiButton("Select Profile", OnProfileSelect)
                {
                    Enabled = false
                });

                row.AddChild(_cancelBtn = new GuiButton("Cancel", OnCancelButtonPressed)
                {
                });
            });

            if (_defaultSkin == null)
            {
                Alex.Instance.Resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture);
                _defaultSkin = new Skin()
                {
                    Slim    = true,
                    Texture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, rawTexture)
                };
            }

            Reload();
        }
예제 #10
0
        public bool TryGetTexture(string textureName, out Texture2D texture)
        {
            //	if (_textureCache.TryGetValue(textureName, out texture))
            //		return true;

            if (TryGetBitmap(textureName, out Bitmap bmp))
            {
                texture = TextureUtils.BitmapToTexture2D(Graphics, bmp);
                return(true);
            }

            texture = null;
            return(false);
        }
예제 #11
0
        public override void HandleMcpePlayerList(McpePlayerList message)
        {
            if (message.records is PlayerAddRecords addRecords)
            {
                foreach (var r in addRecords)
                {
                    var u = new API.Utils.UUID(r.ClientUuid.GetBytes());
                    if (_players.ContainsKey(u))
                    {
                        continue;
                    }

                    Texture2D skinTexture;
                    if (r.Skin.TryGetBitmap(out Bitmap skinBitmap))
                    {
                        skinTexture =
                            TextureUtils.BitmapToTexture2D(BaseClient.WorldProvider.Alex.GraphicsDevice, skinBitmap);
                    }
                    else
                    {
                        BaseClient.WorldProvider.Alex.Resources.ResourcePack.TryGetBitmap("entity/alex", out Bitmap rawTexture);
                        skinTexture = TextureUtils.BitmapToTexture2D(BaseClient.WorldProvider.Alex.GraphicsDevice, rawTexture);
                    }

                    BaseClient.WorldReceiver?.AddPlayerListItem(new PlayerListItem(u, r.DisplayName, Gamemode.Survival, 0));
                    PlayerMob m = new PlayerMob(r.DisplayName, BaseClient.WorldReceiver as World, BaseClient, skinTexture, true);

                    if (!_players.TryAdd(u, m))
                    {
                        Log.Warn($"Duplicate player record! {r.ClientUuid}");
                    }
                }
            }
            else if (message.records is PlayerRemoveRecords removeRecords)
            {
                foreach (var r in removeRecords)
                {
                    var u = new UUID(r.ClientUuid.GetBytes());
                    if (_players.TryRemove(u, out var player))
                    {
                        BaseClient.WorldReceiver?.RemovePlayerListItem(u);
                        if (BaseClient.WorldReceiver is World w)
                        {
                            w.DespawnEntity(player.EntityId);
                        }
                    }
                }
            }
        }
예제 #12
0
        public static bool ResolveItemTexture(string itemName, out Texture2D texture)
        {
            if (ResourcePack.ItemModels.TryGetValue(itemName, out ResourcePackItem item))
            {
                var texture0 = item.Textures.FirstOrDefault();
                if (texture0.Value != null)
                {
                    if (ResourcePack.TryGetBitmap(texture0.Value, out Bitmap bmp))
                    {
                        texture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        return(true);
                    }
                    else
                    {
                        Log.Debug($"Could not find texture for item: {itemName} (Search Term: {texture0.Value})");
                    }
                }
            }
            else
            {
                if (ResourcePack.TryGetBlockModel(itemName, out var b))
                {
                    var texture0 = b.Textures.OrderBy(x => x.Value.Contains("side")).FirstOrDefault();
                    if (texture0.Value != null)
                    {
                        if (ResourcePack.TryGetBitmap(texture0.Value, out Bitmap bmp))
                        {
                            texture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                            return(true);
                        }
                        else
                        {
                            Log.Debug($"Could not find texture for item: {itemName} (Search Term: {texture0.Value})");
                        }
                    }
                }
                else
                {
                    Log.Debug($"Could not find model for item: {itemName}");
                }
            }

            texture = null;
            return(false);
        }
예제 #13
0
        private static void Add(ResourceManager resourceManager, GraphicsDevice graphics, EntityDescription def, EntityModel model, ResourceLocation name)
        {
            _registeredRenderers.AddOrUpdate(name,
                                             (t) =>
            {
                if (t == null)
                {
                    var textures = def.Textures;
                    string texture;
                    if (!textures.TryGetValue("default", out texture) && !textures.TryGetValue(name.Path, out texture))
                    {
                        texture = textures.FirstOrDefault().Value;
                    }

                    if (resourceManager.BedrockResourcePack.Textures.TryGetValue(texture,
                                                                                 out var bmp))
                    {
                        t = TextureUtils.BitmapToTexture2D(graphics, bmp);
                    }
                }

                return(new EntityModelRenderer(model, t));
            },
                                             (s, func) =>
            {
                return((t) =>
                {
                    var textures = def.Textures;
                    string texture;
                    if (!(textures.TryGetValue("default", out texture) || textures.TryGetValue(name.Path, out texture)))
                    {
                        texture = textures.FirstOrDefault().Value;
                    }

                    if (resourceManager.BedrockResourcePack.Textures.TryGetValue(texture,
                                                                                 out var bmp))
                    {
                        t = TextureUtils.BitmapToTexture2D(graphics, bmp);
                    }

                    return new EntityModelRenderer(model, t);
                });
            });
        }
예제 #14
0
        private void Reload()
        {
            ClearItems();

            foreach (var skinPack in Alex.Resources.Packs)
            {
                foreach (var module in skinPack.Modules.Where(x => x is MCSkinPack).Cast <MCSkinPack>())
                {
                    foreach (var skin in module.Skins)
                    {
                        Alex.UIThreadQueue.Enqueue(
                            () =>
                        {
                            var texture     = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, skin.Texture);
                            SkinEntry entry = new SkinEntry(skin, texture, OnDoubleClick);
                            AddItem(entry);
                        });
                    }
                }
            }
        }
예제 #15
0
        protected override void OnShow()
        {
            if (Alex.PlayerModel != null && Alex.PlayerTexture != null)
            {
                Alex.UIThreadQueue.Enqueue(
                    () =>
                {
                    var texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, Alex.PlayerTexture);
                    _playerView.Entity.ModelRenderer = new EntityModelRenderer(Alex.PlayerModel, texture);
                });
            }

            if (Alex.GameStateManager.TryGetState <OptionsState>("options", out _))
            {
                Alex.GameStateManager.RemoveState("options");
            }

            Alex.GameStateManager.AddState("options", new OptionsState(_backgroundSkyBox));

            base.OnShow();
        }
예제 #16
0
        public void CreateOrUpdateProfile(string type, PlayerProfile profile, bool setActive = false)
        {
            IPlayerProfileService profileService = ServiceProvider.GetRequiredService <IPlayerProfileService>();
            var alex = ServiceProvider.GetRequiredService <Alex>();

            if (profile.Skin?.Texture == null)
            {
                profile.Skin = new Skin();

                if (alex.Resources.TryGetBitmap("entity/alex", out var rawTexture))
                {
                    profile.Skin.Texture = TextureUtils.BitmapToTexture2D(alex.GraphicsDevice, rawTexture);
                    profile.Skin.Slim    = true;
                }
            }
            SavedProfile savedProfile;

            if (Profiles.TryGetValue(profile.Uuid, out savedProfile))
            {
                savedProfile.Type      = type;
                savedProfile.Profile   = profile;
                Profiles[profile.Uuid] = savedProfile;
            }
            else
            {
                savedProfile         = new SavedProfile();
                savedProfile.Type    = type;
                savedProfile.Profile = profile;
                Profiles.Add(profile.Uuid, savedProfile);
            }

            if (setActive)
            {
                //ActiveProfile = savedProfile;
                profileService?.Force(profile);
                //_playerProfileService.Force(profile);
            }

            alex.UIThreadQueue.Enqueue(SaveProfiles);
        }
예제 #17
0
        public static void LoadResources(GraphicsDevice graphicsDevice, McResourcePack resourcePack)
        {
            if (resourcePack.TryGetBitmap("minecraft:entity/chest/normal", out var bmp))
            {
                ChestTexture = TextureUtils.BitmapToTexture2D(graphicsDevice, bmp);
            }
            else
            {
                Log.Warn($"Could not load chest texture.");
            }

            if (resourcePack.TryGetBitmap("minecraft:entity/chest/ender", out var enderBmp))
            {
                EnderChestTexture = TextureUtils.BitmapToTexture2D(graphicsDevice, enderBmp);
            }
            else
            {
                Log.Warn($"Could not load enderchest texture");
            }

            if (resourcePack.TryGetBitmap("minecraft:entity/steve", out var steveBmp))
            {
                SkullTexture = TextureUtils.BitmapToTexture2D(graphicsDevice, steveBmp);
            }
            else
            {
                Log.Warn($"Could not load skull texture");
            }


            if (resourcePack.TryGetBitmap("minecraft:entity/signs/oak", out var signBmp))
            {
                SignTexture = TextureUtils.BitmapToTexture2D(graphicsDevice, signBmp);
            }
            else
            {
                Log.Warn($"Could not load sign texture");
            }
        }
예제 #18
0
        private void SetVertices()
        {
            var def = _entityDefinitions[_index];

            EntityModelRenderer renderer = null;

            //if (def.Value != null)
            //{
            //	renderer = EntityFactory.GetEntityRenderer(def.Key, null);
            //}

            if (def.Value != null && def.Value.Geometry != null && def.Value.Geometry.ContainsKey("default") &&
                def.Value.Textures != null)
            {
                EntityModel model;
                if (ModelFactory.TryGetModel(def.Value.Geometry["default"],
                                             out model) && model != null)
                {
                    var    textures = def.Value.Textures;
                    string texture;
                    if (!textures.TryGetValue("default", out texture))
                    {
                        texture = textures.FirstOrDefault().Value;
                    }

                    if (Alex.Resources.BedrockResourcePack.Textures.TryGetValue(texture,
                                                                                out var bmp))
                    {
                        PooledTexture2D t = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, bmp.Value);

                        renderer       = new EntityModelRenderer(model, t);
                        renderer.Scale = 1f / 16f;
                    }
                }
            }

            _currentRenderer = renderer;
        }
예제 #19
0
파일: TitleState.cs 프로젝트: lvyitian/Alex
        protected override void OnShow()
        {
            if (Alex.PlayerModel != null && Alex.PlayerTexture != null)
            {
                Alex.UIThreadQueue.Enqueue(
                    () =>
                {
                    var texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, Alex.PlayerTexture);
                    _playerView.Entity.ModelRenderer = new EntityModelRenderer(Alex.PlayerModel, texture);
                });
            }

            if (Alex.GameStateManager.TryGetState <OptionsState>("options", out _))
            {
                Alex.GameStateManager.RemoveState("options");
            }

            Alex.GameStateManager.AddState("options", new OptionsState(_backgroundSkyBox));

            _playerView.Entity.SetInventory(new BedrockInventory(46));

            _playerView.Entity.ShowItemInHand = true;

            if (ItemFactory.TryGetItem("minecraft:grass_block", out var grass))
            {
                _playerView.Entity.Inventory.MainHand = grass;
                _playerView.Entity.Inventory[_playerView.Entity.Inventory.SelectedSlot] = grass;
            }

            if (ItemFactory.TryGetItem("minecraft:diamond_sword", out var sword))
            {
                //_playerView.Entity.Inventory.MainHand = sword;
                //_playerView.Entity.Inventory[_playerView.Entity.Inventory.SelectedSlot] = sword;
            }

            base.OnShow();
        }
예제 #20
0
        internal void UpdateSkin(PooledTexture2D skinTexture)
        {
            if (skinTexture != null && ModelRenderer != null)
            {
                ModelRenderer.Texture = skinTexture;

                return;
            }

            string geometry = "geometry.humanoid.customSlim";

            if (skinTexture == null)
            {
                string skinVariant = "entity/alex";
                skinTexture = _alex;

                var uuid = UUID.GetBytes();

                bool isSteve = (uuid[3] ^ uuid[7] ^ uuid[11] ^ uuid[15]) % 2 == 0;

                if (isSteve)
                {
                    skinVariant = "entity/steve";
                    geometry    = "geometry.humanoid.custom";

                    skinTexture = _steve;
                }

                if (skinTexture == null)
                {
                    if (Alex.Instance.Resources.TryGetBitmap(skinVariant, out var rawTexture))
                    {
                        skinTexture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, rawTexture);

                        if (isSteve)
                        {
                            _steve = skinTexture;
                        }
                        else
                        {
                            _alex = skinTexture;
                        }

                        //skinBitmap = rawTexture;
                    }
                }

                if (skinTexture == null)
                {
                    skinTexture = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, Alex.PlayerTexture);
                }
            }


            if (ModelFactory.TryGetModel(geometry, out var m))
            {
                _model        = m;
                ValidModel    = true;
                ModelRenderer = new EntityModelRenderer(_model, skinTexture);

                _texture = skinTexture;
                //UpdateModelParts();
            }
        }
예제 #21
0
        private void GenerateAtlas(GraphicsDevice device,
                                   IDictionary <ResourceLocation, ImageEntry> blockTextures,
                                   IProgressReceiver progressReceiver)
        {
            Stopwatch sw = Stopwatch.StartNew();

            Log.Info($"Generating texture atlas out of {(blockTextures.Count)} bitmaps...");

            long totalSize = 0;

            Image <Rgba32> no;

            using (MemoryStream ms = new MemoryStream(ResourceManager.ReadResource("Alex.Resources.no.png")))
            {
                no = Image.Load <Rgba32>(ms);
            }

            Dictionary <ResourceLocation, TextureInfo> stillFrameInfo = new Dictionary <ResourceLocation, TextureInfo>();

            GenerateAtlasInternal(
                new[] { new KeyValuePair <ResourceLocation, Image <Rgba32> >("no_texture", no), }.Concat(
                    blockTextures
                    .Where(x => x.Value.Image.Height == TextureHeight && x.Value.Image.Width == TextureWidth).Select(
                        x => new KeyValuePair <ResourceLocation, Image <Rgba32> >(x.Key, x.Value.Image))).ToArray(),
                progressReceiver, stillFrameInfo, false, out var stillAtlas);

            AtlasSize = new Vector2(stillAtlas.Width, stillAtlas.Height);

            //  totalSize += size;

            _atlasLocations = stillFrameInfo;


            Dictionary <ResourceLocation, Image <Rgba32>[]> blockFrames =
                new Dictionary <ResourceLocation, Image <Rgba32>[]>();

            foreach (var other in blockTextures.Where(
                         x => x.Value.Image.Height != x.Value.Image.Width))
            {
                if (!blockFrames.TryGetValue(other.Key, out _))
                {
                    blockFrames.Add(other.Key, GetFrames(other.Value.Image, TextureWidth, TextureHeight));
                }
            }

            var animatedFrameInfo = new Dictionary <ResourceLocation, TextureInfo>();

            GenerateAtlasInternal(
                blockFrames.Select(x => new KeyValuePair <ResourceLocation, Image <Rgba32> >(x.Key, x.Value[0])).ToArray(),
                progressReceiver, animatedFrameInfo, true, out Image <Rgba32> animatedFrame);

            AnimatedAtlasSize       = new Vector2(animatedFrame.Width, animatedFrame.Height);
            _animatedAtlasLocations = animatedFrameInfo;


            var frameCount = blockFrames.Max(x => x.Value.Length);

            while (frameCount % 2 != 0)
            {
                frameCount++;
            }

            var frames = new Image <Rgba32> [frameCount];

            frames[0] = animatedFrame;

            for (int i = 1; i < frames.Length; i++)
            {
                double percentage = 100D * ((double)i / (double)frames.Length);
                progressReceiver.UpdateProgress((int)percentage, $"Animating frame {i + 1} / {frames.Length}...");

                var target = (i > 0 ? frames[i - 1] : animatedFrame).CloneAs <Rgba32>();            //new Bitmap(animatedFrame);

                // System.Drawing.Rectangle destination;

                foreach (var animated in blockFrames)
                {
                    progressReceiver.UpdateProgress((int)percentage, null, animated.Key.ToString());

                    if (animatedFrameInfo.TryGetValue(animated.Key, out var textureInfo))
                    {
                        //((i % 3 == 0 ? i - 1 : i) / 6)

                        var destination = new System.Drawing.Rectangle(
                            (int)textureInfo.Position.X, (int)textureInfo.Position.Y, textureInfo.Width,
                            textureInfo.Height);

                        var sourceRegion = new System.Drawing.Rectangle(0, 0, textureInfo.Width, textureInfo.Height);

                        var index = i % animated.Value.Length;

                        var   indexOffset        = 0;
                        bool  shouldInterpolate  = false;
                        float interpolationValue = 0.5f;
                        if (blockTextures.TryGetValue(animated.Key, out var imageEntry) && imageEntry.Meta != null)
                        {
                            var meta = imageEntry.Meta;

                            if (meta.Animation != null)
                            {
                                if (meta.Animation.Interpolate)
                                {
                                    int extraFrames = (frames.Length - animated.Value.Length);

                                    var interpolationFrames = (int)Math.Floor(((double)extraFrames / (double)animated.Value.Length));

                                    var remainder = i % interpolationFrames;

                                    if (remainder != 0)
                                    {
                                        shouldInterpolate  = true;
                                        interpolationValue = (1f / interpolationFrames) * remainder;

                                        indexOffset = -remainder;
                                        //   index -= remainder;
                                    }
                                }

                                if (meta.Animation.Frames != null)
                                {
                                    var entry = meta.Animation.Frames[(i + indexOffset) % meta.Animation.Frames.Length];

                                    if (entry.Integer.HasValue)
                                    {
                                        index = (int)entry.Integer.Value;
                                    }
                                    else if (entry.FrameClass != null)
                                    {
                                        index = (int)entry.FrameClass.Index;
                                    }
                                }
                                else
                                {
                                    index = (i + indexOffset) % animated.Value.Length;
                                }
                            }
                        }

                        //TextureUtils.ClearRegion(ref target, destination);

                        if (shouldInterpolate)
                        {
                            TextureUtils.CopyRegionIntoImage(
                                ((i + indexOffset >= 0) ? frames[(i + indexOffset) % frames.Length] : animatedFrame), destination, ref target,
                                destination, clear: true);
                        }

                        var texture = animated.Value[index];

                        TextureUtils.CopyRegionIntoImage(texture,
                                                         sourceRegion, ref target,
                                                         destination, shouldInterpolate, interpolationValue, clear: !shouldInterpolate);
                    }
                }

                frames[i] = target;
            }

            _frames = frames.Select(
                x =>
            {
                var a      = TextureUtils.BitmapToTexture2D(device, x, out var s);
                totalSize += s;

                return(a);
            }).ToArray();

            _stillFrame = TextureUtils.BitmapToTexture2D(device, stillAtlas, out var size);
            totalSize  += size;

            sw.Stop();

            Log.Info(
                $"TextureAtlas's generated in {sw.ElapsedMilliseconds}ms! ({PlayingState.GetBytesReadable(totalSize, 2)})");

            /*
             * PngEncoder encoder = new PngEncoder();
             *
             * stillAtlas.Save("atlas.png", encoder);
             *
             * if (!Directory.Exists("frames"))
             *      Directory.CreateDirectory("frames");
             *
             * for (var index = 0; index < frames.Length; index++)
             * {
             *      var frame = frames[index];
             *
             *      frame.Save(Path.Combine("frames", $"frame-{index}.png"), encoder);
             * }*/
        }
예제 #22
0
        protected override void OnLoad(IRenderArgs args)
        {
            Skin skin = _playerProfileService?.CurrentProfile?.Skin;

            if (skin == null)
            {
                Alex.Resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture);
                skin = new Skin()
                {
                    Slim    = true,
                    Texture = TextureUtils.BitmapToTexture2D(Alex.GraphicsDevice, rawTexture)
                };
            }

            var entity = new RemotePlayer("", null, null, skin.Texture);

            AddChild(_playerView =
                         new GuiEntityModelView(
                             entity /*new PlayerMob("", null, null, skin.Texture, skin.Slim)*/)                    /*"geometry.humanoid.customSlim"*/
            {
                BackgroundOverlay = new Color(Color.Black, 0.15f),

                Margin = new Thickness(15, 15, 5, 40),

                Width  = 92,
                Height = 128,

                Anchor = Alignment.BottomRight,
            });

            AddChild(new GuiButton("Change Skin", ChangeSKinBtnPressed)
            {
                Anchor         = Alignment.BottomRight,
                Modern         = false,
                TranslationKey = "",
                Margin         = new Thickness(15, 15, 6, 15),
                Width          = 90,
                //Enabled = false
            });

            AutoResetEvent reset = new AutoResetEvent(false);

            Alex.UIThreadQueue.Enqueue(() =>
            {
                using (MemoryStream ms =
                           new MemoryStream(ResourceManager.ReadResource("Alex.Resources.GradientBlur.png")))
                {
                    BackgroundOverlay = (TextureSlice2D)GpuResourceManager.GetTexture2D(this, args.GraphicsDevice, ms);
                }

                BackgroundOverlay.RepeatMode = TextureRepeatMode.Stretch;
                reset.Set();
            });
            reset.WaitOne();
            reset.Dispose();

            BackgroundOverlay.Mask = new Color(Color.White, 0.5f);

            _splashText.Text    = SplashTexts.GetSplashText();
            Alex.IsMouseVisible = true;

            Alex.GameStateManager.AddState("serverlist", new MultiplayerServerSelectionState(_backgroundSkyBox));
            //Alex.GameStateManager.AddState("profileSelection", new ProfileSelectionState(_backgroundSkyBox));
        }
예제 #23
0
        private void LoadSkin(Skin skin)
        {
            try
            {
                if (skin == null)
                {
                    return;
                }

                EntityModel model = null;

                if (!skin.IsPersonaSkin)
                {
                    if (!string.IsNullOrWhiteSpace(skin.GeometryData) && !skin.GeometryData.Equals(
                            "null", StringComparison.InvariantCultureIgnoreCase))
                    {
                        try
                        {
                            if (string.IsNullOrWhiteSpace(skin.ResourcePatch) || skin.ResourcePatch == "null")
                            {
                                Log.Debug($"Resourcepatch null for player {Name}");
                            }
                            else
                            {
                                var resourcePatch = JsonConvert.DeserializeObject <SkinResourcePatch>(
                                    skin.ResourcePatch, GeometrySerializationSettings);

                                Dictionary <string, EntityModel> models = new Dictionary <string, EntityModel>();
                                BedrockResourcePack.LoadEntityModel(skin.GeometryData, models);

                                var processedModels = BedrockResourcePack.ProcessEntityModels(models);

                                if (processedModels == null || processedModels.Count == 0)
                                {
                                    Log.Warn($"!! Model count was 0 for player {NameTag} !!");

                                    if (!Directory.Exists("failed"))
                                    {
                                        Directory.CreateDirectory("failed");
                                    }

                                    File.WriteAllText(
                                        Path.Combine(
                                            "failed",
                                            $"{Environment.TickCount64}-{resourcePatch.Geometry.Default}.json"),
                                        skin.GeometryData);
                                }
                                else
                                {
                                    if (resourcePatch?.Geometry != null)
                                    {
                                        if (!processedModels.TryGetValue(resourcePatch.Geometry.Default, out model))
                                        {
                                            Log.Debug(
                                                $"Invalid geometry: {resourcePatch.Geometry.Default} for player {Name}");
                                        }
                                        else
                                        {
                                        }
                                    }
                                    else
                                    {
                                        Log.Debug($"Resourcepatch geometry was null for player {Name}");
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            string name = "N/A";
                            Log.Debug(ex, $"Could not create geometry ({name}): {ex.ToString()} for player {Name}");
                        }
                    }
                    else
                    {
                        //Log.Debug($"Geometry data null for player {Name}");
                    }
                }

                if (model == null)
                {
                    ModelFactory.TryGetModel(
                        skin.Slim ? "geometry.humanoid.custom" : "geometry.humanoid.customSlim", out model);

                    /*model = skin.Slim ? (EntityModel) new Models.HumanoidCustomslimModel() :
                     *      (EntityModel) new HumanoidModel();*/// new Models.HumanoidCustomGeometryHumanoidModel();
                }

                if (model != null && ValidateModel(model, Name))
                {
                    Image <Rgba32> skinBitmap = null;

                    if (!skin.TryGetBitmap(model, out skinBitmap))
                    {
                        Log.Warn($"No custom skin data for player {Name}");

                        if (Alex.Instance.Resources.TryGetBitmap("entity/alex", out var rawTexture))
                        {
                            skinBitmap = rawTexture;
                        }
                    }

                    //if (!Directory.Exists("skins"))
                    //	Directory.CreateDirectory("skins");

                    //var path = Path.Combine("skins", $"{model.Description.Identifier}-{Environment.TickCount64}");
                    //File.WriteAllText($"{path}.json", skin.GeometryData);
                    //skinBitmap.SaveAsPng($"{path}.png");

                    var modelTextureSize = new Point(
                        (int)model.Description.TextureWidth, (int)model.Description.TextureHeight);

                    var textureSize = new Point(skinBitmap.Width, skinBitmap.Height);

                    if (modelTextureSize != textureSize)
                    {
                        if (modelTextureSize.Y > textureSize.Y)
                        {
                            skinBitmap = SkinUtils.ConvertSkin(skinBitmap, modelTextureSize.X, modelTextureSize.Y);
                        }

                        /*var bitmap = skinBitmap;
                         * bitmap.Mutate<Rgba32>(xx =>
                         * {
                         *      xx.Resize(modelTextureSize.X, modelTextureSize.Y);
                         * //	xx.Flip(FlipMode.Horizontal);
                         * });
                         *
                         * skinBitmap = bitmap;*/
                    }

                    GeometryName = model.Description.Identifier;

                    var modelRenderer = new EntityModelRenderer(
                        model, TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, skinBitmap));

                    if (modelRenderer.Valid)
                    {
                        ModelRenderer = modelRenderer;
                    }
                    else
                    {
                        modelRenderer.Dispose();
                        Log.Debug($"Invalid model: for player {Name} (Disposing)");
                    }
                }
                else
                {
                    Log.Debug($"Invalid model for player {Name}");
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, $"Error while handling player skin.");
            }
        }
예제 #24
0
        public World(IServiceProvider serviceProvider, GraphicsDevice graphics, AlexOptions options, Camera camera,
                     INetworkProvider networkProvider)
        {
            Graphics = graphics;
            Camera   = camera;
            Options  = options;

            PhysicsEngine = new PhysicsManager(this);
            ChunkManager  = new ChunkManager(serviceProvider, graphics, this);
            EntityManager = new EntityManager(graphics, this, networkProvider);
            Ticker        = new TickManager();
            PlayerList    = new PlayerList();

            ChunkManager.Start();
            var settings       = serviceProvider.GetRequiredService <IOptionsProvider>();
            var profileService = serviceProvider.GetRequiredService <IPlayerProfileService>();
            var resources      = serviceProvider.GetRequiredService <ResourceManager>();

            EventDispatcher = serviceProvider.GetRequiredService <IEventDispatcher>();

            string username = string.Empty;
            Skin   skin     = profileService?.CurrentProfile?.Skin;

            if (skin == null)
            {
                resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture);
                var t = TextureUtils.BitmapToTexture2D(graphics, rawTexture);
                skin = new Skin()
                {
                    Texture = t,
                    Slim    = true
                };
            }

            if (!string.IsNullOrWhiteSpace(profileService?.CurrentProfile?.Username))
            {
                username = profileService.CurrentProfile.Username;
            }

            Player = new Player(graphics, serviceProvider.GetRequiredService <Alex>().InputManager, username, this, skin, networkProvider, PlayerIndex.One, camera);

            Player.KnownPosition = new PlayerLocation(GetSpawnPoint());
            Camera.MoveTo(Player.KnownPosition, Vector3.Zero);

            Options.FieldOfVision.ValueChanged += FieldOfVisionOnValueChanged;
            Camera.FOV = Options.FieldOfVision.Value;

            PhysicsEngine.AddTickable(Player);

            if (networkProvider is BedrockClient)
            {
                Player.SetInventory(new BedrockInventory(46));
            }
            //	Player.Inventory.IsPeInventory = true;

            /*if (ItemFactory.TryGetItem("minecraft:diamond_sword", out var sword))
             * {
             *      Player.Inventory[Player.Inventory.SelectedSlot] = sword;
             *      Player.Inventory.MainHand = sword;
             * }
             * else
             * {
             *      Log.Warn($"Could not get diamond sword!");
             * }*/

            EventDispatcher.RegisterEvents(this);

            FormManager = new BedrockFormManager(networkProvider, serviceProvider.GetRequiredService <GuiManager>(), serviceProvider.GetService <Alex>().InputManager);

            SkyRenderer = new SkyBox(serviceProvider, graphics, this);
            //SkyLightCalculations = new SkyLightCalculations();

            UseDepthMap = options.VideoOptions.Depthmap;
            options.VideoOptions.Depthmap.Bind((old, newValue) => { UseDepthMap = newValue; });

            ServerType = (networkProvider is BedrockClient) ? ServerType.Bedrock : ServerType.Java;
        }
예제 #25
0
        public void GenerateAtlas(GraphicsDevice device, KeyValuePair <string, Image <Rgba32> >[] bitmaps, IReadOnlyDictionary <string, TextureMeta> meta, IProgressReceiver progressReceiver)
        {
            Stopwatch sw = Stopwatch.StartNew();

            Log.Info($"Generating texture atlas out of {bitmaps.Length} bitmaps...");

            long totalSize = 0;

            Image <Rgba32> no;

            using (MemoryStream ms = new MemoryStream(ResourceManager.ReadResource("Alex.Resources.no.png")))
            {
                no = Image.Load <Rgba32>(ms);
            }

            //  Dictionary<string, Bitmap[]> animatedFrames = new Dictionary<string, Bitmap[]>();
            foreach (var bmp in bitmaps)
            {
                if (meta.TryGetValue(bmp.Key, out var textureMeta))
                {
                    if (textureMeta.Animation == null || textureMeta.Animation == default)
                    {
                        continue;
                    }

                    // Bitmap[] bmpFrames = GetFrames(bmp.Value);
                    //   animatedFrames.Add(bmp.Key, bmpFrames);
                }
            }

            var regular = new[]
            {
                new KeyValuePair <string, Image <Rgba32> >("no_texture", no),
            }.Concat(bitmaps.Where(x => x.Value.Height == TextureHeight && x.Value.Width == TextureWidth)).ToArray();

            var others = bitmaps.Where(x => x.Value.Height != TextureHeight || x.Value.Width != TextureWidth).ToList();

            Image <Rgba32>[] waterFrames     = new Image <Rgba32> [0];
            Image <Rgba32>[] lavaFrames      = new Image <Rgba32> [0];
            Image <Rgba32>[] waterFlowFrames = new Image <Rgba32> [0];
            Image <Rgba32>[] lavaFlowFrames  = new Image <Rgba32> [0];
            Image <Rgba32>[] fireFrames      = new Image <Rgba32> [0];
            Image <Rgba32>[] fireFrames2     = new Image <Rgba32> [0];
            Image <Rgba32>[] portalFrames    = new Image <Rgba32> [0];
            Image <Rgba32>[] seagrassFrames  = new Image <Rgba32> [0];

            foreach (var other in others.ToArray())
            {
                if (other.Key.Contains("water") && other.Key.Contains("still"))
                {
                    waterFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("water") && other.Key.Contains("flow"))
                {
                    waterFlowFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("lava") && other.Key.Contains("still"))
                {
                    lavaFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("lava") && other.Key.Contains("flow"))
                {
                    lavaFlowFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("fire_0"))
                {
                    fireFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("fire_1"))
                {
                    fireFrames2 = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("nether_portal"))
                {
                    portalFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                else if (other.Key.Contains("seagrass"))
                {
                    seagrassFrames = GetFrames(other.Value);
                    others.Remove(other);
                }
                //seagrass
            }

            Dictionary <string, TextureInfo> stillFrameInfo = new Dictionary <string, TextureInfo>();

            GenerateAtlasInternal(regular, others.ToArray(), progressReceiver, stillFrameInfo, out var stillAtlas);
            _stillFrame = TextureUtils.BitmapToTexture2D(device, stillAtlas, out var size);

            //stillAtlas.Save(Path.Combine(DebugPath, "atlas.png"));

            totalSize += size;

            _atlasLocations = stillFrameInfo;

            Dictionary <string, Image <Rgba32> > animated = new Dictionary <string, Image <Rgba32> >();

            if (waterFrames.Length > 0)
            {
                animated.Add("block/water_still", waterFrames[0]);
            }


            if (waterFlowFrames.Length > 0)
            {
                animated.Add("block/water_flow", waterFlowFrames[0]);
            }


            if (lavaFrames.Length > 0)
            {
                animated.Add("block/lava_still", lavaFrames[0]);
            }


            if (lavaFlowFrames.Length > 0)
            {
                animated.Add("block/lava_flow", lavaFlowFrames[0]);
            }

            if (fireFrames.Length > 0)
            {
                animated.Add("block/fire_0", fireFrames[0]);
            }

            if (fireFrames2.Length > 0)
            {
                animated.Add("block/fire_1", fireFrames2[0]);
            }

            if (portalFrames.Length > 0)
            {
                animated.Add("block/nether_portal", portalFrames[0]);
            }

            if (seagrassFrames.Length > 0)
            {
                animated.Add("block/seagrass", seagrassFrames[0]);
            }

            var animatedFrameInfo = new Dictionary <string, TextureInfo>();

            GenerateAtlasInternal(animated.ToArray(), new KeyValuePair <string, Image <Rgba32> > [0], progressReceiver,
                                  animatedFrameInfo, out Image <Rgba32> animatedFrame);

            AnimatedAtlasSize = new Vector2(animatedFrame.Width, animatedFrame.Height);

            TextureInfo waterLocation, waterFlowLocation, lavaLocation, lavaFlowLocation, fireLocation, fireLocation2, portalLocation, seagrassLocation;

            animatedFrameInfo.TryGetValue("block/water_still", out waterLocation);
            animatedFrameInfo.TryGetValue("block/water_flow", out waterFlowLocation);
            animatedFrameInfo.TryGetValue("block/lava_still", out lavaLocation);
            animatedFrameInfo.TryGetValue("block/lava_flow", out lavaFlowLocation);
            animatedFrameInfo.TryGetValue("block/fire_0", out fireLocation);
            animatedFrameInfo.TryGetValue("block/fire_1", out fireLocation2);
            animatedFrameInfo.TryGetValue("block/nether_portal", out portalLocation);
            animatedFrameInfo.TryGetValue("block/seagrass", out seagrassLocation);

            //var waterLocation = new Vector3();

            // var baseBitmap = new Bitmap(stillAtlas.Width, stillAtlas.Height);
            var frameCount = Math.Max(Math.Max(Math.Max(waterFrames.Length,
                                                        Math.Max(waterFlowFrames.Length,
                                                                 Math.Max(lavaFrames.Length, Math.Max(lavaFlowFrames.Length, fireFrames.Length)))), portalFrames.Length), seagrassFrames.Length);

            while (frameCount % 2 != 0)
            {
                frameCount++;
            }

            var frames = new Texture2D[frameCount];

            for (int i = 0; i < frames.Length; i++)
            {
                var target      = animatedFrame.CloneAs <Rgba32>();       //new Bitmap(animatedFrame);
                var r           = new System.Drawing.Rectangle(0, 0, TextureWidth, TextureHeight);
                var destination = new System.Drawing.Rectangle((int)waterLocation.Position.X, (int)waterLocation.Position.Y, TextureWidth, TextureHeight);

                if (waterFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(waterFrames[((i % 3 == 0 ? i - 1 : i) / 6) % waterFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)waterFlowLocation.Position.X, (int)waterFlowLocation.Position.Y, TextureWidth, TextureHeight);
                if (waterFlowFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(waterFlowFrames[i % waterFlowFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)lavaLocation.Position.X, (int)lavaLocation.Position.Y, TextureWidth, TextureHeight);
                if (lavaFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(lavaFrames[i % lavaFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)lavaFlowLocation.Position.X, (int)lavaFlowLocation.Position.Y, TextureWidth, TextureHeight);
                if (lavaFlowFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(lavaFlowFrames[i % lavaFlowFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)fireLocation.Position.X, (int)fireLocation.Position.Y, TextureWidth, TextureHeight);
                if (fireFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(fireFrames[i % fireFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)fireLocation2.Position.X, (int)fireLocation2.Position.Y, TextureWidth, TextureHeight);
                if (fireFrames2.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(fireFrames2[i % fireFrames2.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)portalLocation.Position.X, (int)portalLocation.Position.Y, TextureWidth, TextureHeight);
                if (portalFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(portalFrames[i % portalFrames.Length], r, ref target, destination);
                }

                destination = new System.Drawing.Rectangle((int)seagrassLocation.Position.X, (int)seagrassLocation.Position.Y, TextureWidth, TextureHeight);
                if (seagrassFrames.Length > 0)
                {
                    TextureUtils.CopyRegionIntoImage(seagrassFrames[i % seagrassFrames.Length], r, ref target, destination);
                }

                frames[i]  = TextureUtils.BitmapToTexture2D(device, target, out var s);
                totalSize += s;

                //   target.Save(Path.Combine(DebugFramePath, $"frame{i}.png"));
            }

            _animatedAtlasLocations = animatedFrameInfo;

            AtlasSize = new Vector2(stillAtlas.Width, stillAtlas.Height);
            _frames   = frames;

            sw.Stop();

            Log.Info($"TextureAtlas generated in {sw.ElapsedMilliseconds}ms! ({PlayingState.GetBytesReadable(totalSize, 2)})");
        }
예제 #26
0
        /// <inheritdoc />
        protected override void BlockChanged(Block oldBlock, Block newBlock)
        {
            if (newBlock is Skull s)
            {
                switch (s.SkullType)
                {
                case SkullType.Player:
                    break;

                case SkullType.Skeleton:
                    if (_skeleton == null)
                    {
                        if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(
                                "minecraft:entity/skeleton/skeleton", out var bmp))
                        {
                            _skeleton = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        }
                    }

                    if (_skeleton != null)
                    {
                        ModelRenderer = new EntityModelRenderer(new SkullBlockEntityModel(), _skeleton);
                        //ModelRenderer.Texture = _skeleton;
                    }
                    break;

                case SkullType.WitherSkeleton:
                    if (_witherSkeleton == null)
                    {
                        if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(
                                "minecraft:entity/skeleton/wither_skeleton", out var bmp))
                        {
                            _witherSkeleton = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        }
                    }

                    if (_witherSkeleton != null)
                    {
                        ModelRenderer = new EntityModelRenderer(new SkullBlockEntityModel(), _witherSkeleton);
                    }
                    break;

                case SkullType.Zombie:
                    if (_zombie == null)
                    {
                        if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(
                                "minecraft:entity/zombie/zombie", out var bmp))
                        {
                            _zombie = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        }
                    }

                    if (_zombie != null)
                    {
                        ModelRenderer = new EntityModelRenderer(new SkullBlockEntityModel(), _zombie);
                    }
                    break;

                case SkullType.Creeper:
                    if (_creeper == null)
                    {
                        if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(
                                "minecraft:entity/creeper/creeper", out var bmp))
                        {
                            _creeper = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        }
                    }

                    if (_creeper != null)
                    {
                        ModelRenderer = new EntityModelRenderer(new SkullBlockEntityModel(), _creeper);
                    }
                    break;

                case SkullType.Dragon:
                    if (_dragon == null)
                    {
                        if (Alex.Instance.Resources.ResourcePack.TryGetBitmap(
                                "minecraft:entity/enderdragon/dragon", out var bmp))
                        {
                            _dragon = TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, bmp);
                        }
                    }

                    if (_dragon != null)
                    {
                        if (ModelFactory.TryGetModel("geometry.dragon_head", out var dragonHead))
                        {
                            ModelRenderer = new EntityModelRenderer(dragonHead, _dragon);
                        }

                        //ModelRenderer.Texture = _dragon;
                    }
                    break;
                }
            }

            if (newBlock is WallSkull)
            {
                if (newBlock.BlockState.TryGetValue("facing", out var facing))
                {
                    if (Enum.TryParse <BlockFace>(facing, true, out var face))
                    {
                        Offset = (face.Opposite().GetVector3() * 0.5f);
                    }
                }
            }
            else if (newBlock is Skull)
            {
                if (newBlock.BlockState.TryGetValue("rotation", out var r))
                {
                    if (byte.TryParse(r, out var rot))
                    {
                        Rotation = rot;
                    }
                }
            }
        }
예제 #27
0
 public BitmapFont(GraphicsDevice graphics, Image <Rgba32> bitmap, int gridWidth, int gridHeight, List <char> characters) :
     this(TextureUtils.BitmapToTexture2D(graphics, bitmap), gridWidth, gridHeight, characters)
 {
     Scale = new Vector2(128f / bitmap.Width, 128f / bitmap.Height);
     LoadGlyphs(bitmap, characters);
 }
예제 #28
0
        public void LoadSkin(Skin skin)
        {
            //PooledTexture2D skinTexture = null;
            Image <Rgba32> skinBitmap = null;

            if (!skin.TryGetBitmap(out skinBitmap))
            {
                Log.Warn($"No custom skin data for player {Name}");

                if (Alex.Instance.Resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture))
                {
                    skinBitmap = rawTexture;
                    //skinTexture = TextureUtils.BitmapToTexture2D(AlexInstance.GraphicsDevice, rawTexture);
                }
            }

            EntityModel model = null;

            if (!skin.IsPersonaSkin)
            {
                if (!string.IsNullOrWhiteSpace(skin.GeometryData) && skin.GeometryData != "null")
                {
                    try
                    {
                        if (string.IsNullOrWhiteSpace(skin.ResourcePatch) || skin.ResourcePatch == "null")
                        {
                            Log.Warn($"Resourcepatch null for player {Name}");
                        }
                        else
                        {
                            var resourcePatch = JsonConvert.DeserializeObject <SkinResourcePatch>(
                                skin.ResourcePatch, GeometrySerializationSettings);

                            GeometryModel geometryModel = null;
                            //	Dictionary<string, EntityModel> models = new Dictionary<string, EntityModel>();

                            if (!GeometryModel.TryParse(skin.GeometryData, resourcePatch, out geometryModel))
                            {
                                Log.Warn($"Failed to parse geometry for player {Name}");
                            }

                            /*try
                             * {
                             *      geometryModel = MCJsonConvert.DeserializeObject<GeometryModel>(skin.GeometryData);
                             * }
                             * catch (Exception ex)
                             * {
                             *      Log.Warn($"Failed to parse geometry for player {Name}: {ex.ToString()}");
                             * }*/

                            if (geometryModel == null || geometryModel.Geometry.Count == 0)
                            {
                                Log.Warn($"!! Model count was 0 for player {Name} !!");
                                //EntityModel.GetEntries(r.Skin.GeometryData, models);
                            }
                            else
                            {
                                if (resourcePatch?.Geometry != null)
                                {
                                    model = geometryModel.FindGeometry(resourcePatch.Geometry.Default);

                                    if (model == null)
                                    {
                                        Log.Warn(
                                            $"Invalid geometry: {resourcePatch.Geometry.Default} for player {Name}");
                                    }
                                    else
                                    {
                                        var modelTextureSize = model.Description != null ?
                                                               new Point((int)model.Description.TextureWidth, (int)model.Description.TextureHeight) :
                                                               new Point((int)model.Texturewidth, (int)model.Textureheight);

                                        var textureSize = new Point(skinBitmap.Width, skinBitmap.Height);

                                        if (modelTextureSize != textureSize)
                                        {
                                            int newHeight = modelTextureSize.Y > textureSize.Y ? textureSize.Y : modelTextureSize.Y;
                                            int newWidth  = modelTextureSize.X > textureSize.X ? textureSize.X: modelTextureSize.X;

                                            var bitmap = skinBitmap;
                                            //	bitmap.Mutate<Rgba32>(xx => xx.Resize(newWidth, newHeight));

                                            Image <Rgba32> skinTexture = new Image <Rgba32>(modelTextureSize.X, modelTextureSize.Y);

                                            skinTexture.Mutate <Rgba32>(
                                                c =>
                                            {
                                                c.DrawImage(bitmap, new SixLabors.ImageSharp.Point(0, 0), 1f);
                                            });

                                            skinBitmap = skinTexture;
                                        }
                                    }
                                }
                                else
                                {
                                    Log.Warn($"Resourcepatch geometry was null for player {Name}");
                                }
                            }

                            /*foreach (var mm in models.ToArray())
                             * {
                             *      if (ProcessEntityModel(models, mm.Value, false))
                             *      {
                             *              models.Remove(mm.Key);
                             *      }
                             * }
                             *
                             * foreach (var mm in models.ToArray())
                             * {
                             *      if (ProcessEntityModel(models, mm.Value, true))
                             *      {
                             *              models.Remove(mm.Key);
                             *      }
                             * }*/
                        }
                    }
                    catch (Exception ex)
                    {
                        string name = "N/A";

                        /*if (r.Skin.SkinResourcePatch != null)
                         * {
                         *      name = r.Skin.SkinResourcePatch.Geometry.Default;
                         * }*/
                        Log.Warn(ex, $"Could not create geometry ({name}): {ex.ToString()} for player {Name}");

                        //	File.WriteAllBytes(Path.Combine("/home/kenny/.config/Alex/skinDebug/failed", $"failed-{Environment.TickCount}.json"), Encoding.UTF8.GetBytes(skin.GeometryData));
                    }
                }
                else
                {
                    Log.Warn($"Geometry data null for player {Name}");
                }
            }

            if (model == null)
            {
                model = skin.Slim ? (EntityModel) new Models.HumanoidCustomslimModel() : (EntityModel) new Models.HumanoidCustomGeometryHumanoidModel();
            }

            if (model != null && ValidateModel(model, Name))
            {
                var modelRenderer = new EntityModelRenderer(model, TextureUtils.BitmapToTexture2D(Alex.Instance.GraphicsDevice, skinBitmap));

                if (modelRenderer.Valid)
                {
                    ModelRenderer = modelRenderer;
                }
                else
                {
                    modelRenderer.Dispose();
                    Log.Warn($"Invalid model: for player {Name} (Disposing)");
                }
            }
            else
            {
                Log.Warn($"Invalid model for player {Name}");
            }
        }
예제 #29
0
        public SkyBox(IServiceProvider serviceProvider, GraphicsDevice device, World world)
        {
            World = world;
            //Game = alex;
            var alex = serviceProvider.GetRequiredService <Alex>();

            OptionsProvider = serviceProvider.GetRequiredService <IOptionsProvider>();

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/sun", out var sun))
            {
                SunTexture = TextureUtils.BitmapToTexture2D(device, sun);
            }
            else
            {
                CanRender = false;
                return;
            }

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/moon_phases", out var moonPhases))
            {
                MoonTexture = TextureUtils.BitmapToTexture2D(device, moonPhases);
            }
            else
            {
                CanRender = false;
                return;
            }

            if (alex.Resources.ResourcePack.TryGetBitmap("environment/clouds", out var cloudTexture))
            {
                CloudTexture = TextureUtils.BitmapToTexture2D(device, cloudTexture);
                EnableClouds = false;
            }
            else
            {
                EnableClouds = false;
            }

            //var d = 144;

            CelestialPlaneEffect = new BasicEffect(device);
            CelestialPlaneEffect.VertexColorEnabled = false;
            CelestialPlaneEffect.LightingEnabled    = false;
            CelestialPlaneEffect.TextureEnabled     = true;

            SkyPlaneEffect = new BasicEffect(device);
            SkyPlaneEffect.VertexColorEnabled = false;
            SkyPlaneEffect.FogEnabled         = true;
            SkyPlaneEffect.FogStart           = 0;
            SkyPlaneEffect.FogEnd             = 64 * 0.8f;
            SkyPlaneEffect.LightingEnabled    = true;

            var planeDistance = 64;
            var plane         = new[]
            {
                new VertexPositionColor(new Vector3(-planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(-planeDistance, 0, planeDistance), Color.White),

                new VertexPositionColor(new Vector3(planeDistance, 0, -planeDistance), Color.White),
                new VertexPositionColor(new Vector3(planeDistance, 0, planeDistance), Color.White),
                new VertexPositionColor(new Vector3(-planeDistance, 0, planeDistance), Color.White)
            };

            SkyPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionColor.VertexDeclaration,
                                                    plane.Length, BufferUsage.WriteOnly);
            SkyPlane.SetData <VertexPositionColor>(plane);

            planeDistance = 60;
            var celestialPlane = new[]
            {
                new VertexPositionTexture(new Vector3(-planeDistance, 0, -planeDistance), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1)),

                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(1, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, planeDistance), new Vector2(1, 1)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, 1))
            };

            CelestialPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionTexture.VertexDeclaration,
                                                          celestialPlane.Length, BufferUsage.WriteOnly);
            CelestialPlane.SetData <VertexPositionTexture>(celestialPlane);

            _moonPlaneVertices = new[]
            {
                new VertexPositionTexture(new Vector3(-planeDistance, 0, -planeDistance), new Vector2(0, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(MoonX, 0)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, MoonY)),

                new VertexPositionTexture(new Vector3(planeDistance, 0, -planeDistance), new Vector2(MoonX, 0)),
                new VertexPositionTexture(new Vector3(planeDistance, 0, planeDistance), new Vector2(MoonX, MoonY)),
                new VertexPositionTexture(new Vector3(-planeDistance, 0, planeDistance), new Vector2(0, MoonY)),
            };
            MoonPlane = GpuResourceManager.GetBuffer(this, device, VertexPositionTexture.VertexDeclaration,
                                                     _moonPlaneVertices.Length, BufferUsage.WriteOnly);
            MoonPlane.SetData <VertexPositionTexture>(_moonPlaneVertices);

            if (EnableClouds)
            {
                SetupClouds(device, planeDistance);
            }

            RenderSkybox = Options.VideoOptions.Skybox.Value;
            Options.VideoOptions.Skybox.Bind(SkyboxSettingUpdated);
        }
예제 #30
0
파일: World.cs 프로젝트: PocketGold-MP/Alex
        public World(IServiceProvider serviceProvider, GraphicsDevice graphics, AlexOptions options,
                     NetworkProvider networkProvider)
        {
            Graphics = graphics;
            Options  = options;

            PhysicsEngine = new PhysicsManager(this);
            ChunkManager  = new ChunkManager(serviceProvider, graphics, this);
            EntityManager = new EntityManager(graphics, this, networkProvider);
            Ticker        = new TickManager();
            PlayerList    = new PlayerList();

            Ticker.RegisterTicked(this);
            Ticker.RegisterTicked(EntityManager);
            //Ticker.RegisterTicked(PhysicsEngine);
            Ticker.RegisterTicked(ChunkManager);

            ChunkManager.Start();
            var profileService = serviceProvider.GetRequiredService <IPlayerProfileService>();
            var resources      = serviceProvider.GetRequiredService <ResourceManager>();

            EventDispatcher = serviceProvider.GetRequiredService <IEventDispatcher>();

            string          username = string.Empty;
            PooledTexture2D texture;

            if (Alex.PlayerTexture != null)
            {
                texture = TextureUtils.BitmapToTexture2D(graphics, Alex.PlayerTexture);
            }
            else
            {
                resources.ResourcePack.TryGetBitmap("entity/alex", out var rawTexture);
                texture = TextureUtils.BitmapToTexture2D(graphics, rawTexture);
            }

            Skin skin = profileService?.CurrentProfile?.Skin;

            if (skin == null)
            {
                skin = new Skin()
                {
                    Texture = texture,
                    Slim    = true
                };
            }

            if (!string.IsNullOrWhiteSpace(profileService?.CurrentProfile?.Username))
            {
                username = profileService.CurrentProfile.Username;
            }

            Player = new Player(graphics, serviceProvider.GetRequiredService <Alex>().InputManager, username, this, skin, networkProvider, PlayerIndex.One);
            Camera = new EntityCamera(Player);

            if (Alex.PlayerModel != null)
            {
                EntityModelRenderer modelRenderer = new EntityModelRenderer(Alex.PlayerModel, texture);

                if (modelRenderer.Valid)
                {
                    Player.ModelRenderer = modelRenderer;
                }
            }

            Player.KnownPosition = new PlayerLocation(GetSpawnPoint());

            Options.FieldOfVision.ValueChanged += FieldOfVisionOnValueChanged;
            Camera.FOV = Options.FieldOfVision.Value;

            PhysicsEngine.AddTickable(Player);

            EventDispatcher.RegisterEvents(this);

            var guiManager = serviceProvider.GetRequiredService <GuiManager>();

            InventoryManager = new InventoryManager(guiManager);

            SkyRenderer = new SkyBox(serviceProvider, graphics, this);

            options.VideoOptions.RenderDistance.Bind(
                (old, newValue) =>
            {
                Camera.SetRenderDistance(newValue);
            });
            Camera.SetRenderDistance(options.VideoOptions.RenderDistance);
        }