/// <summary> /// Display an avatar /// </summary> /// <param name="avatar"></param> public void DisplayAvatar(AvatarData avatar) { this.Avatar = avatar; var isUsed = avatar != null; SetSlotAvailable(!isUsed); if (avatar == null) { return; } PersonNameText.Caption = avatar.Name; //PersonDescriptionText.CurrentText = avatar.Description; AvatarButton.Texture = Screen.SimSelectButtonImage; var shard = Screen.LoginRegulator.Shards.All.First(x => x.Name == avatar.ShardName); CityNameText.Caption = shard.Name; if (avatar.LotId.HasValue && avatar.LotName != null) { HouseNameText.Caption = avatar.LotName; Screen.AsyncAPILotThumbnail((uint)shard.Id, avatar.LotLocation.Value, (tex) => { HouseThumb.Texture = tex; HouseThumb.Y += HouseThumb.Size.Y / 2; HouseThumb.SetSize(HouseThumb.Size.X, (int)(HouseThumb.Size.X * ((double)HouseThumb.Texture.Height / HouseThumb.Texture.Width))); HouseThumb.Y -= HouseThumb.Size.Y / 2; }); /* * HouseThumb.Texture = Screen.GetLotThumbnail(avatar.ShardName, avatar.LotLocation.Value); * HouseThumb.Y += HouseThumb.Size.Y / 2; * HouseThumb.SetSize(HouseThumb.Size.X, (int)(HouseThumb.Size.X * ((double)HouseThumb.Texture.Height / HouseThumb.Texture.Width))); * HouseThumb.Y -= HouseThumb.Size.Y / 2; */ } var cityThumb = (int.Parse(shard.Map) >= 100)? Path.Combine(FSOEnvironment.ContentDir, "Cities/city_" + shard.Map + "/thumbnail.png") : GameFacade.GameFilePath("cities/city_" + shard.Map + "/thumbnail.bmp"); Texture2D cityThumbTex = TextureUtils.Resize( GameFacade.GraphicsDevice, TextureUtils.TextureFromFile(GameFacade.GraphicsDevice, cityThumb), 78, 58); TextureUtils.CopyAlpha(ref cityThumbTex, Screen.CityHouseButtonAlpha); CityThumb.Texture = cityThumbTex; SetTab(PersonSlotTab.EnterTab); Sim.Avatar.Appearance = (AppearanceType)Enum.Parse(typeof(AppearanceType), avatar.AppearanceType.ToString()); Sim.Avatar.BodyOutfitId = avatar.BodyOutfitID; Sim.Avatar.HeadOutfitId = avatar.HeadOutfitID; Sim.Visible = true; PersonDescriptionText.CurrentText = avatar.Description; }
void addSingleTile(Texture2D[] array, int index, Sprite sprite) { array[index] = TextureUtils.textureFromSprite(sprite); }
Texture CreateTexture(Info info, Device device) { FLogger.Log(LogType.Debug, "Creating new texture at slice: " + info.Slice); return(TextureUtils.CreateTexture(device, info.Width, info.Height)); }
public UILotPage() { var script = RenderScript("housepage.uis"); BackgroundNumOccupantsImage = script.Create <UIImage>("BackgroundNumOccupantsImage"); AddAt(0, BackgroundNumOccupantsImage); BackgroundHouseCategoryThumbImage = script.Create <UIImage>("BackgroundHouseCategoryThumbImage"); AddAt(0, BackgroundHouseCategoryThumbImage); BackgroundHouseLeaderThumbImage = script.Create <UIImage>("BackgroundHouseLeaderThumbImage"); AddAt(0, BackgroundHouseLeaderThumbImage); BackgroundDescriptionEditImage = script.Create <UIImage>("BackgroundDescriptionEditImage"); AddAt(0, BackgroundDescriptionEditImage); BackgroundDescriptionImage = script.Create <UIImage>("BackgroundDescriptionImage"); AddAt(0, BackgroundDescriptionImage); BackgroundContractedImage = new UIImage(); BackgroundContractedImage.Texture = ContractedBackgroundImage; this.AddAt(0, BackgroundContractedImage); BackgroundExpandedImage = new UIImage(); BackgroundExpandedImage.Texture = ExpandedBackgroundImage; this.AddAt(0, BackgroundExpandedImage); ContractButton.OnButtonClick += (x) => Open = false; ExpandButton.OnButtonClick += (x) => Open = true; ExpandedCloseButton.OnButtonClick += Close; ContractedCloseButton.OnButtonClick += Close; LotThumbnail = script.Create <UILotThumbButton>("HouseThumbSetup"); LotThumbnail.Init(RoommateThumbButtonImage, VisitorThumbButtonImage); DefaultThumb = TextureUtils.TextureFromFile(GameFacade.GraphicsDevice, GameFacade.GameFilePath("userdata/houses/defaulthouse.bmp")); TextureUtils.ManualTextureMask(ref DefaultThumb, new uint[] { 0xFF000000 }); LotThumbnail.SetThumbnail(DefaultThumb, 0); Add(LotThumbnail); RoommateList = script.Create <UIRoommateList>("RoommateList"); Add(RoommateList); SkillGameplayLabel = new UIClickableLabel(); SkillGameplayLabel.Position = RoommateList.Position + new Vector2(-1, 24); SkillGameplayLabel.Size = new Vector2(180, 18); SkillGameplayLabel.Alignment = TextAlignment.Center; SkillGameplayLabel.OnButtonClick += SkillGameplayLabel_OnButtonClick; SkillGameplayLabel.CaptionStyle = SkillGameplayLabel.CaptionStyle.Clone(); SkillGameplayLabel.CaptionStyle.Size = 9; Add(SkillGameplayLabel); OwnerButton = script.Create <UIPersonButton>("HouseLeaderThumbSetup"); OwnerButton.FrameSize = UIPersonButtonSize.LARGE; Add(OwnerButton); /** Drag **/ UIUtils.MakeDraggable(BackgroundContractedImage, this, true); UIUtils.MakeDraggable(BackgroundExpandedImage, this, true); /** Description scroll **/ HouseDescriptionSlider.AttachButtons(HouseDescriptionScrollUpButton, HouseDescriptionScrollDownButton, 1); HouseDescriptionTextEdit.AttachSlider(HouseDescriptionSlider); HouseLinkButton.OnButtonClick += JoinLot; HouseCategoryButton.OnButtonClick += ChangeCategory; HouseNameButton.OnButtonClick += ChangeName; LotThumbnail.OnLotClick += JoinLot; CurrentLot = new Binding <Lot>() .WithBinding(HouseNameButton, "Caption", "Lot_Name") .WithBinding(HouseValueLabel, "Caption", "Lot_Price", x => MoneyFormatter.Format((uint)x)) .WithBinding(OccupantsNumberLabel, "Caption", "Lot_NumOccupants", x => x.ToString()) .WithBinding(OwnerButton, "AvatarId", "Lot_LeaderID") .WithBinding(HouseCategoryButton, "Texture", "Lot_Category", x => { var category = (LotCategory)Enum.Parse(typeof(LotCategory), x.ToString()); switch (category) { case LotCategory.none: return(HouseCategory_NoCategoryButtonImage); case LotCategory.welcome: return(HouseCategory_WelcomeButtonImage); case LotCategory.money: return(HouseCategory_MoneyButtonImage); case LotCategory.entertainment: return(HouseCategory_EntertainmentButtonImage); case LotCategory.games: return(HouseCategory_GamesButtonImage); case LotCategory.offbeat: return(HouseCategory_OffbeatButtonImage); case LotCategory.residence: return(HouseCategory_ResidenceButtonImage); case LotCategory.romance: return(HouseCategory_RomanceButtonImage); case LotCategory.services: return(HouseCategory_ServicesButtonImage); case LotCategory.shopping: return(HouseCategory_ShoppingButtonImage); case LotCategory.skills: return(HouseCategory_SkillsButtonImage); default: return(null); } }).WithBinding(HouseCategoryButton, "Position", "Lot_Category", x => { return(new Vector2(69 + 11 - HouseCategoryButton.Texture.Width / 8, 164 + 11 - HouseCategoryButton.Texture.Height / 2)); }) .WithMultiBinding(x => RefreshUI(), "Lot_LeaderID", "Lot_IsOnline", "Lot_Thumbnail", "Lot_Description", "Lot_RoommateVec"); RefreshUI(); NeighborhoodNameButton.Visible = false; Size = BackgroundExpandedImage.Size.ToVector2(); SendToFront(ExpandButton, ContractButton); }
public UIMotiveDisplay() { MotiveValues = new short[8]; Filler = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, Color.White); }
//this method gets called, when Update() was called in evaluate, //or a graphics device asks for its texture, here you fill the texture with the actual data //this is called for each renderer, careful here with multiscreen setups, in that case //calculate the pixels in evaluate and just copy the data to the device texture here unsafe protected override void UpdateTexture(int Slice, Texture texture) { FCurrentSlice = Slice; TextureUtils.CopyBitmapToTexture(FBitmaps[Slice], texture); }
public void Initialize(_3DLayer layer) { CenterPixel = TextureUtils.TextureFromColor(layer.Device, Color.Purple, 4, 4); }
/// <summary> /// Extracts a DDS file's texture format and pixel data. /// </summary> private static void ExtractDDSTextureFormatAndData(DDSHeader header, UnityBinaryReader reader, out bool hasMipmaps, out uint DDSMipmapLevelCount, out TextureFormat textureFormat, out int bytesPerPixel, out byte[] textureData) { hasMipmaps = Utils.ContainsBitFlags(header.dwCaps, (uint)DDSCaps.Mipmap); // Non-mipmapped textures still have one mipmap level: the texture itself. DDSMipmapLevelCount = hasMipmaps ? header.dwMipMapCount : 1; // If the DDS file contains uncompressed data. if (Utils.ContainsBitFlags(header.pixelFormat.flags, (uint)DDSPixelFormatFlags.RGB)) { // some permutation of RGB if (!Utils.ContainsBitFlags(header.pixelFormat.flags, (uint)DDSPixelFormatFlags.AlphaPixels)) { throw new NotImplementedException("Unsupported DDS file pixel format."); } // some permutation of RGBA else { // There should be 32 bits per pixel. if (header.pixelFormat.RGBBitCount != 32) { throw new FileFormatException("Invalid DDS file pixel format."); } // BGRA32 if ((header.pixelFormat.BBitMask == 0x000000FF) && (header.pixelFormat.GBitMask == 0x0000FF00) && (header.pixelFormat.RBitMask == 0x00FF0000) && (header.pixelFormat.ABitMask == 0xFF000000)) { textureFormat = TextureFormat.BGRA32; bytesPerPixel = 4; } // ARGB32 else if ((header.pixelFormat.ABitMask == 0x000000FF) && (header.pixelFormat.RBitMask == 0x0000FF00) && (header.pixelFormat.GBitMask == 0x00FF0000) && (header.pixelFormat.BBitMask == 0xFF000000)) { textureFormat = TextureFormat.ARGB32; bytesPerPixel = 4; } else { throw new NotImplementedException("Unsupported DDS file pixel format."); } if (!hasMipmaps) { textureData = new byte[header.dwPitchOrLinearSize * header.dwHeight]; } else { // Create a data buffer to hold all mipmap levels down to 1x1. textureData = new byte[TextureUtils.CalculateMipMappedTextureDataSize((int)header.dwWidth, (int)header.dwHeight, bytesPerPixel)]; } reader.ReadRestOfBytes(textureData, 0); } } else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT1")) { textureFormat = TextureFormat.ARGB32; bytesPerPixel = 4; var compressedTextureData = reader.ReadRestOfBytes(); textureData = DecodeDXT1ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount); } else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT3")) { textureFormat = TextureFormat.ARGB32; bytesPerPixel = 4; var compressedTextureData = reader.ReadRestOfBytes(); textureData = DecodeDXT3ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount); } else if (StringUtils.Equals(header.pixelFormat.fourCC, "DXT5")) { textureFormat = TextureFormat.ARGB32; bytesPerPixel = 4; var compressedTextureData = reader.ReadRestOfBytes(); textureData = DecodeDXT5ToARGB(compressedTextureData, header.dwWidth, header.dwHeight, header.pixelFormat, DDSMipmapLevelCount); } else { throw new NotImplementedException("Unsupported DDS file pixel format."); } }
public override void Init() { base.Init(); gradient = TextureUtils.CreateFromGradient(Game, new Color(0xBD, 0xBD, 0xBD), new Color(0xAD, 0xAD, 0xAD), Bounds.Width, Bounds.Height); }
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); System.Drawing.Rectangle destination; if (waterLocation != null) { 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); } } if (waterFlowLocation != null) { 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); } } if (lavaLocation != null) { 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); } } if (lavaFlowLocation != null) { 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); } } if (fireLocation != null) { 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); } } if (fireLocation2 != null) { 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); } } if (portalLocation != null) { 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); } } if (seagrassLocation != null) { 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)})"); }
/// <summary> /// Gets an object group's thumbnail provided an array of objects. /// </summary> /// <param name="objects">The object components to draw.</param> /// <param name="gd">GraphicsDevice instance.</param> /// <param name="state">WorldState instance.</param> /// <returns>Object's ID if the object was found at the given position.</returns> public Texture2D GetObjectThumb(ObjectComponent[] objects, Vector3[] positions, GraphicsDevice gd, WorldState state) { var oldZoom = state.Zoom; var oldRotation = state.Rotation; var oldPreciseZoom = state.PreciseZoom; /** Center average position **/ Vector3 average = new Vector3(); for (int i = 0; i < positions.Length; i++) { average += positions[i]; } average /= positions.Length; state.SilentZoom = WorldZoom.Near; state.SilentRotation = WorldRotation.BottomRight; state.SilentPreciseZoom = 1; state.WorldSpace.Invalidate(); state.InvalidateCamera(); state.DrawOOB = true; state.TempDraw = true; var pxOffset = new Vector2(442, 275) - state.WorldSpace.GetScreenFromTile(average); var _2d = state._2D; Promise <Texture2D> bufferTexture = null; Promise <Texture2D> depthTexture = null; state._2D.OBJIDMode = false; Rectangle bounds = new Rectangle(); state.ClearLighting(true); using (var buffer = state._2D.WithBuffer(BUFFER_THUMB, ref bufferTexture, BUFFER_THUMB_DEPTH, ref depthTexture)) { _2d.SetScroll(new Vector2()); while (buffer.NextPass()) { for (int i = 0; i < objects.Length; i++) { var obj = objects[i]; var tilePosition = positions[i]; //we need to trick the object into believing it is in a set world state. var oldObjRot = obj.Direction; var oldRoom = obj.Room; obj.Direction = Direction.NORTH; obj.Room = 65535; state.SilentZoom = WorldZoom.Near; state.SilentRotation = WorldRotation.BottomRight; obj.OnRotationChanged(state); obj.OnZoomChanged(state); _2d.OffsetPixel(state.WorldSpace.GetScreenFromTile(tilePosition) + pxOffset); _2d.OffsetTile(tilePosition); _2d.SetObjID(obj.ObjectID); obj.Draw(gd, state); //return everything to normal obj.Direction = oldObjRot; obj.Room = oldRoom; state.SilentZoom = oldZoom; state.SilentRotation = oldRotation; obj.OnRotationChanged(state); obj.OnZoomChanged(state); } bounds = _2d.GetSpriteListBounds(); } } bounds.X = Math.Max(0, Math.Min(1023, bounds.X)); bounds.Y = Math.Max(0, Math.Min(1023, bounds.Y)); if (bounds.Width + bounds.X > 1024) { bounds.Width = 1024 - bounds.X; } if (bounds.Height + bounds.Y > 1024) { bounds.Height = 1024 - bounds.Y; } //return things to normal state.DrawOOB = false; state.SilentPreciseZoom = oldPreciseZoom; state.WorldSpace.Invalidate(); state.InvalidateCamera(); state.TempDraw = false; var tex = bufferTexture.Get(); return(TextureUtils.Clip(gd, tex, bounds)); }
public Texture2D GetObjectThumb(ObjectComponent[] objects, Vector3[] positions, GraphicsDevice gd, WorldState state) { var cam = new WorldCamera3D(gd, Vector3.Zero, Vector3.Zero, Vector3.Up);// WorldCamera3D)state.Camera; var oldVp = state.ViewProjection; /** Center average position **/ Vector3 average = new Vector3(); for (int i = 0; i < positions.Length; i++) { average += positions[i]; } average /= positions.Length; cam.ProjectionOrigin = new Vector2(512, 512); cam.Target = average + new Vector3(0.5f, 0.5f, 0) * 3f; cam.Position = cam.Target + new Vector3(-9, 6, -9); state.DrawOOB = true; var _2d = state._2D; if (ObjThumbTarget == null) { ObjThumbTarget = new RenderTarget2D(gd, 1024, 1024, true, SurfaceFormat.Color, DepthFormat.Depth24); } gd.SetRenderTarget(ObjThumbTarget); var cpoints = new List <Vector3>(); var view = state.View; var vp = view * state.Projection; gd.BlendState = BlendState.NonPremultiplied; gd.RasterizerState = RasterizerState.CullNone; gd.DepthStencilState = DepthStencilState.Default; var effect = WorldContent.RCObject; effect.ViewProjection = vp; state.ViewProjection = vp; effect.SetTechnique(RCObjectTechniques.Draw); state.ClearLighting(false); Blueprint.SetLightColor(WorldContent.RCObject, Color.White, Color.White); var objs = objects.OrderBy(x => { x.UpdateDrawOrder(state); return(x.DrawOrder); }).ToList(); gd.Clear(Color.Transparent); for (int i = 0; i < objs.Count; i++) { var obj = objs[i]; var tilePosition = positions[Array.IndexOf(objects, obj)]; //we need to trick the object into believing it is in a set world state. var oldObjRot = obj.Direction; var oldObjPos = obj.UnmoddedPosition; var oldRoom = obj.Room; obj.Direction = Direction.NORTH; obj.Room = 65535; obj.OnRotationChanged(state); obj.OnZoomChanged(state); obj.Position = tilePosition; obj.Draw(gd, state); var mat = obj.World * vp; cpoints.AddRange(obj.GetBounds().GetCorners().Select(x => { var proj = Vector3.Transform(x, vp); proj.X /= proj.Z; proj.Y /= -proj.Z; proj.X += 1f; proj.X *= 512; proj.Y += 1f; proj.Y *= 512; return(proj); })); //return everything to normal obj.Direction = oldObjRot; obj.Room = oldRoom; obj.UnmoddedPosition = oldObjPos; obj.OnRotationChanged(state); obj.OnZoomChanged(state); } gd.SetRenderTarget(null); var bounds3d = (cpoints.Count > 0) ? BoundingBox.CreateFromPoints(cpoints) : new BoundingBox(); var bounds = new Rectangle((int)bounds3d.Min.X, (int)bounds3d.Min.Y, (int)(bounds3d.Max.X - bounds3d.Min.X), (int)(bounds3d.Max.Y - bounds3d.Min.Y)); bounds.Inflate(1, 1); bounds.X = Math.Max(0, Math.Min(1023, bounds.X)); bounds.Y = Math.Max(0, Math.Min(1023, bounds.Y)); if (bounds.Width + bounds.X > 1024) { bounds.Width = 1024 - bounds.X; } if (bounds.Height + bounds.Y > 1024) { bounds.Height = 1024 - bounds.Y; } bp.Changes.SetFlag(BlueprintGlobalChanges.LIGHTING_CHANGED); //return things to normal state.DrawOOB = false; state.ViewProjection = oldVp; gd.DepthStencilState = DepthStencilState.None; var clip = TextureUtils.Clip(gd, ObjThumbTarget, bounds); var dec = TextureUtils.Decimate(clip, gd, 3, true); return(dec); }
public DebugTypeFaceScreen() { var msg = "The quick brown fox jumps over the lazy dog"; var sizes = new int[] { 10, 12, 14, 16, 20 }; Add(new UILabel() { X = 10.0f, Y = 30.0f, Caption = "Metric calculation test: Green bar is Y 0, Red bar is calculated baseline" }); var greenTexture = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, Color.Green); var redTexture = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, Color.Red); var grayTexture = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, Color.Gray); var yPosition = 100.0f; for (var i = 0; i < sizes.Length; i++) { var pxSize = sizes[i]; var label = new UILabel { Caption = msg, CaptionStyle = TextStyle.DefaultLabel.Clone() }; label.CaptionStyle.Size = pxSize; label.X = 10; label.Y = yPosition; /** Origin line **/ var origLine = new UIImage(greenTexture); origLine.SetSize(800.0f, 1.0f); origLine.X = 10; origLine.Y = yPosition; Add(origLine); var baseLine = new UIImage(redTexture); baseLine.SetSize(800.0f, 1.0f); baseLine.X = 10; baseLine.Y = yPosition + label.CaptionStyle.BaselineOffset; Add(baseLine); yPosition += (float)Math.Round(label.CaptionStyle.MeasureString(msg).Y); yPosition += 20.0f; Add(label); } Add(new UILabel() { X = 10.0f, Y = yPosition + 30.0f, Caption = "Alignment calculation test" }); var alignments = new TextAlignment[] { TextAlignment.Center, TextAlignment.Right, TextAlignment.Middle, TextAlignment.Middle | TextAlignment.Center, TextAlignment.Middle | TextAlignment.Right }; yPosition += 60.0f; sizes = new int[] { 10 }; for (var i = 0; i < sizes.Length; i++) { var pxSize = sizes[i]; foreach (var align in alignments) { var label = new UILabel { Caption = msg, CaptionStyle = TextStyle.DefaultLabel.Clone() }; label.CaptionStyle.Size = pxSize; label.Size = new Vector2(800.0f, 50.0f); label.Alignment = align; label.X = 10; label.Y = yPosition; var area = new UIImage(grayTexture); area.SetSize(800.0f, 50.0f); area.X = 10; area.Y = yPosition; Add(area); ///** Origin line **/ //var origLine = new UIImage(greenTexture); //origLine.SetSize(800.0f, 1.0f); //origLine.X = 10; //origLine.Y = yPosition; //this.Add(origLine); //var baseLine = new UIImage(redTexture); //baseLine.SetSize(800.0f, 1.0f); //baseLine.X = 10; //baseLine.Y = yPosition + label.CaptionStyle.BaselineOffset; //this.Add(baseLine); yPosition += 50.0f;//(float)Math.Round(label.CaptionStyle.MeasureString(msg).Y); yPosition += 20.0f; Add(label); } } }
private void OnGUI() { var rect = new Rect(0, 0, position.width, position.height); GUICustomUtils.DrawTitle("Dash AOT Scanner/Generator"); var titleStyle = new GUIStyle(); titleStyle.alignment = TextAnchor.MiddleLeft; titleStyle.padding.left = 5; titleStyle.normal.textColor = new Color(1, .5f, 0); titleStyle.fontStyle = FontStyle.Bold; titleStyle.fontSize = 16; var infoStyle = new GUIStyle(); infoStyle.normal.textColor = Color.gray; infoStyle.alignment = TextAnchor.MiddleLeft; infoStyle.padding.left = 5; var scrollViewStyle = new GUIStyle(); scrollViewStyle.normal.background = TextureUtils.GetColorTexture(new Color(.1f, .1f, .1f)); GUILayout.Space(4); GUILayout.Label("Scanned types", titleStyle, GUILayout.ExpandWidth(true)); GUILayout.Label( "Last scan found " + (DashEditorCore.EditorConfig.scannedAOTTypes == null ? 0 : DashEditorCore.EditorConfig.scannedAOTTypes.Count) + " types", infoStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(2); _scrollPositionScanned = GUILayout.BeginScrollView(_scrollPositionScanned, scrollViewStyle, GUILayout.ExpandWidth(true), GUILayout.Height(rect.height / 2 - 100)); GUILayout.BeginVertical(); if (DashEditorCore.EditorConfig.scannedAOTTypes != null) { foreach (Type type in DashEditorCore.EditorConfig.scannedAOTTypes) { GUILayout.BeginHorizontal(); GUILayout.Label((string.IsNullOrEmpty(type.Namespace) ? "" : type.Namespace + ".") + type.GetReadableTypeName()); if (GUILayout.Button("Remove", GUILayout.Width(120))) { DashAOTScanner.RemoveScannedAOTType(type); break; } GUILayout.EndHorizontal(); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.Label("Explicit Types", titleStyle, GUILayout.ExpandWidth(true)); GUILayout.Label( "You have " + (DashEditorCore.EditorConfig.explicitAOTTypes == null ? 0 : DashEditorCore.EditorConfig.explicitAOTTypes.Count) + " explicitly defined types.", infoStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(2); _scrollPositionExplicit = GUILayout.BeginScrollView(_scrollPositionExplicit, scrollViewStyle, GUILayout.ExpandWidth(true), GUILayout.Height(rect.height / 2 - 100)); GUILayout.BeginVertical(); if (DashEditorCore.EditorConfig.explicitAOTTypes != null) { int index = 0; foreach (Type type in DashEditorCore.EditorConfig.explicitAOTTypes) { GUILayout.BeginHorizontal(); GUILayout.Label((string.IsNullOrEmpty(type.Namespace) ? "" : type.Namespace + ".") + type.GetReadableTypeName()); if (type.IsGenericType && type.GetGenericArguments()[0].FullName == null) { if (GUILayout.Button("Inflate", GUILayout.Width(120))) { AddTypeContextMenu.ShowAsPopup((p) => InflateType(p, type, index)); } } if (GUILayout.Button("Remove", GUILayout.Width(120))) { DashAOTScanner.RemoveExplicitAOTType(type); break; } GUILayout.EndHorizontal(); index++; } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.Space(4); GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); _generateLinkXml = GUILayout.Toggle(_generateLinkXml, new GUIContent("Generate Link Xml"), GUILayout.Width(140)); _includeOdin = GUILayout.Toggle(_includeOdin, new GUIContent("Include Odin Assembly")); GUILayout.EndHorizontal(); GUILayout.Space(2); GUILayout.BeginHorizontal(); bool generate = GUILayout.Button("Generate AOT DLL", GUILayout.Height(40)); bool scan = GUILayout.Button("Scan Types", GUILayout.Height(40)); if (GUILayout.Button("Add Explicit Type", GUILayout.Height(40))) { AddTypeContextMenu.ShowAsPopup(AddType); } GUILayout.EndHorizontal(); var dll = PluginImporter.GetAtPath(DashEditorCore.EditorConfig.AOTAssemblyPath + "/" + DashEditorCore.EditorConfig.AOTAssemblyName + ".dll"); if (dll != null) { GUILayout.Label("Assembly generated in " + DashEditorCore.EditorConfig.AOTAssemblyPath + "/" + DashEditorCore.EditorConfig.AOTAssemblyName + ".dll" + " last generated on " + DashEditorCore.EditorConfig.AOTAssemblyGeneratedTime); } else { GUILayout.Label("No generated Dash AOT Assembly found."); } GUILayout.EndVertical(); if (scan) { DashAOTScanner.Scan(); } else if (generate) { DashAOTScanner.GenerateDLL(_generateLinkXml, _includeOdin); } }
public World(IServiceProvider serviceProvider, GraphicsDevice graphics, AlexOptions options, Camera camera, NetworkProvider 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 alex = serviceProvider.GetRequiredService<Alex>(); 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)); } else { Player.SetInventory(new Utils.Inventory(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); var guiManager = serviceProvider.GetRequiredService <GuiManager>(); FormManager = new BedrockFormManager(networkProvider, guiManager, serviceProvider.GetService <Alex>().InputManager); InventoryManager = new InventoryManager(guiManager); 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; }
public ColorSwatch(Color c) { swatchColor = c; assigned = true; swatchTexture = TextureUtils.GenerateColorTexture(60, 60, swatchColor); }
//this method gets called, when Reinitialize() was called in evaluate, //or a graphics device asks for its data protected override Texture CreateTexture(int Slice, Device device) { FLogger.Log(LogType.Debug, "Creating new texture at slice: " + Slice); return(TextureUtils.CreateTexture(device, Math.Max(FSizes[Slice].Width, 1), Math.Max(FSizes[Slice].Height, 1))); }
private void OnGUI() { var rect = new Rect(0, 0, position.width, position.height); GUICustomUtils.DrawTitle("Dash Prefab Editor"); var scrollViewStyle = new GUIStyle(); scrollViewStyle.normal.background = TextureUtils.GetColorTexture(new Color(.1f, .1f, .1f)); GUILayout.BeginArea(new Rect(5, 35, rect.width - 400, rect.height - 40)); _scrollPositionPrefabs = GUILayout.BeginScrollView(_scrollPositionProperties, scrollViewStyle, GUILayout.ExpandWidth(true)); GUILayout.BeginVertical(); if (DashEditorCore.RuntimeConfig.prefabs != null) { foreach (var pair in DashEditorCore.RuntimeConfig.prefabs) { GUILayout.BeginHorizontal(); GUILayout.Label(pair.Key.name, GUILayout.Width(120)); EditorGUI.BeginChangeCheck(); var newValue = EditorGUILayout.ObjectField(pair.Value, typeof(GameObject), false); if (EditorGUI.EndChangeCheck()) { if (newValue != null) { DashEditorCore.RuntimeConfig.prefabs[pair.Key] = (GameObject)newValue; break; } } if (GUILayout.Button("Remove", GUILayout.Width(100))) { DashEditorCore.RuntimeConfig.prefabs.Remove(pair.Key); break; } if (GUILayout.Button("Edit", GUILayout.Width(100))) { _selectedPrefabInfo = pair.Key; break; } GUILayout.EndHorizontal(); } } GUILayout.EndVertical(); GUILayout.EndScrollView(); if (GUILayout.Button("Add Prefab", GUILayout.Height(40))) { if (DashEditorCore.RuntimeConfig.prefabs == null) { DashEditorCore.RuntimeConfig.prefabs = new Dictionary <PrefabInfo, GameObject>(); } DashEditorCore.RuntimeConfig.prefabs.Add(PrefabInfo.GetDefault(), null); } GUILayout.EndArea(); var propertyRect = new Rect(rect.width - 390, 35, 385, rect.height - 45); DrawBoxGUI(propertyRect, "Properties", TextAnchor.UpperRight, Color.white); GUILayout.BeginArea(new Rect(propertyRect.x + 5, propertyRect.y + 30, propertyRect.width - 10, propertyRect.height - 35)); _scrollPositionProperties = GUILayout.BeginScrollView(_scrollPositionProperties, false, false); if (_selectedPrefabInfo != null && DashEditorCore.RuntimeConfig.prefabs != null && DashEditorCore.RuntimeConfig.prefabs.ContainsKey(_selectedPrefabInfo)) { GUILayout.BeginHorizontal(); GUILayout.Label("Name", GUILayout.Width(100)); _selectedPrefabInfo.name = GUILayout.TextField(_selectedPrefabInfo.name); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Enable Pooling", GUILayout.Width(100)); _selectedPrefabInfo.enablePooling = EditorGUILayout.Toggle(_selectedPrefabInfo.enablePooling); GUILayout.EndHorizontal(); GUI.enabled = _selectedPrefabInfo.enablePooling; GUILayout.BeginHorizontal(); GUILayout.Label("Count", GUILayout.Width(100)); _selectedPrefabInfo.count = EditorGUILayout.IntField(_selectedPrefabInfo.count); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Prewarm", GUILayout.Width(100)); _selectedPrefabInfo.prewarm = EditorGUILayout.Toggle(_selectedPrefabInfo.prewarm); GUILayout.EndHorizontal(); GUI.enabled = true; var asset = DashEditorCore.RuntimeConfig.prefabs[_selectedPrefabInfo]; if (asset != null) { var style = new GUIStyle(); style.alignment = TextAnchor.MiddleCenter; style.normal.textColor = Color.white; style.fontStyle = FontStyle.Bold; GUI.backgroundColor = new Color(0.1f, 0.1f, 0.1f); style.normal.background = Texture2D.whiteTexture; GUI.Label(new Rect(0, propertyRect.height - 400, propertyRect.width, 20), asset.name, style); GUI.DrawTexture(new Rect(10, propertyRect.height - 380, 360, 360), AssetPreview.GetMiniThumbnail(asset)); GUI.backgroundColor = Color.white; } } GUILayout.EndScrollView(); GUILayout.EndArea(); }
private PooledTexture2D[] ProcessFrames(GraphicsDevice device, IProgressReceiver progressReceiver, IDictionary <ResourceLocation, ImageEntry> blockTextures) { 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 var 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; } return(frames.Select( (x, index) => { var a = GetMipMappedTexture2D(device, x); //totalSize += a.MemoryUsage; return a; }).ToArray()); }
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); * }*/ }
/// <summary> /// When the text / scroll / highlight changes we need to /// re-compute how we are going to draw this text field /// </summary> public void ComputeDrawingCommands() { m_DrawCmds.Clear(); m_DrawDirty = false; /** * Split the text into lines using manual lines * breaks and word wrap */ var txt = m_SBuilder.ToString(); var lineWidth = m_Width - (TextMargin.Left + TextMargin.Height); m_LineHeight = TextStyle.MeasureString("W").Y; m_Lines.Clear(); var words = txt.Split(' ').ToList(); var spaceWidth = TextStyle.MeasureString(" ").X; /** * Modify the array to make manual line breaks their own segment * in the array */ var newWordsArray = TextRenderer.ExtractLineBreaks(words); TextRenderer.CalculateLines(m_Lines, newWordsArray, TextStyle, lineWidth, spaceWidth, new Vector2(), m_LineHeight); var topLeft = new Vector2(TextMargin.Left, TextMargin.Top); var position = topLeft; var txtScale = TextStyle.Scale * _Scale; m_NumVisibleLines = (int)Math.Floor(m_Height / m_LineHeight); /** Make sure the current vscroll is valid **/ VerticalScrollPosition = m_VScroll; if (m_Slider != null) { m_Slider.MaxValue = Math.Max(0, m_Lines.Count - m_NumVisibleLines); m_Slider.Value = VerticalScrollPosition; } var yPosition = topLeft.Y; var numLinesAdded = 0; for (var i = 0; i < m_Lines.Count - m_VScroll; i++) { var line = m_Lines[m_VScroll + i]; var segments = CalculateSegments(line); var xPosition = topLeft.X; segments.ForEach(x => x.Size = TextStyle.MeasureString(x.Text)); var thisLineWidth = segments.Sum(x => x.Size.X); /** Alignment **/ if (Alignment == TextAlignment.Center) { xPosition += (int)Math.Round((lineWidth - thisLineWidth) / 2); } line.LineStartX = (int)xPosition; foreach (var segment in segments) { var segmentSize = segment.Size; var segmentPosition = LocalPoint(new Vector2(xPosition, yPosition)); if (segment.Selected) { m_DrawCmds.Add(new TextDrawCmd_SelectionBox { BlendColor = new Color(0xFF, 0xFF, 0xFF, 200), Texture = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, TextStyle.SelectionBoxColor), Position = segmentPosition, Scale = new Vector2(segmentSize.X, m_LineHeight) * _Scale }); } m_DrawCmds.Add(new TextDrawCmd_Text { Selected = segment.Selected, Text = segment.Text, Style = TextStyle, Position = segmentPosition, Scale = txtScale }); xPosition += segmentSize.X; } yPosition += m_LineHeight; position.Y += m_LineHeight; numLinesAdded++; if (numLinesAdded >= m_NumVisibleLines) { break; } } /** No cursor in read only mode **/ if (m_IsReadOnly) { m_DrawCmds.ForEach(x => x.Init()); return; } var start = Control_GetSelectionStart(); var cursorLine = GetLineForIndex(start); if (cursorLine != null && cursorLine.LineNumber >= m_VScroll && cursorLine.LineNumber < m_VScroll + m_NumVisibleLines) { var prefix = start - cursorLine.StartIndex; var cursorPosition = new Vector2(cursorLine.LineStartX, topLeft.Y + ((cursorLine.LineNumber - m_VScroll) * m_LineHeight)); if (prefix > 0) { if (prefix > cursorLine.Text.Length - 1) { cursorPosition.X += cursorLine.LineWidth; } else { cursorPosition.X += TextStyle.MeasureString(cursorLine.Text.Substring(0, prefix)).X; } } m_DrawCmds.Add(new TextDrawCmd_Cursor { Scale = new Vector2(_Scale.X, m_LineHeight * _Scale.Y), Position = LocalPoint(cursorPosition), Texture = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, TextStyle.CursorColor) }); } m_DrawCmds.ForEach(x => x.Init()); }
public NeighbourhoodEditPlugin(Terrain city) : base(city) { PxBlack = TextureUtils.TextureFromColor(GameFacade.GraphicsDevice, Color.Black); EditTarget = city.NeighGeom.Data; }
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); }
private void LoadSkin(Skin skin) { try { if (skin == null) { return; } 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; } } EntityModel model = null; if (!skin.IsPersonaSkin) { if (!string.IsNullOrWhiteSpace(skin.GeometryData) && !skin.GeometryData.Equals( "null", StringComparison.OrdinalIgnoreCase)) { 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); //if (!Directory.Exists("skins")) // Directory.CreateDirectory("skins"); //File.WriteAllText(Path.Combine("skins", $"{Environment.TickCount64}.json"), skin.GeometryData); 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 {Name} !!"); 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 { 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)) { 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."); } }
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)); }
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.ResourcePack.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(); } }
/// <summary> /// 以下参数分别为 精灵名,取材文件,最大分解桢数,坐标x,坐标y,每行取材宽度,每列取材长度,平均每桢显示时间 /// </summary> /// /// <param name="spriteName_0"></param> /// <param name="fileName"></param> /// <param name="maxFrame"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="row"></param> /// <param name="col"></param> /// <param name="timer"></param> public Sprite(string spriteName_0, string fileName, int maxFrame, float x, float y, int row, int col, long timer) : this(spriteName_0, TextureUtils.GetSplitTextures(fileName, row, col), maxFrame, x, y, timer) { }
public static void Setup() { greyTex = TextureUtils.PlainTexture(2, 2, new Color(.7f, .7f, .7f, 1f)); bckgTex = TextureUtils.PlainTexture(2, 2, new Color(1f, 1f, 1f, 0.46f)); }
unsafe void UpdateTexture(Info info, Texture texture) { TextureUtils.CopyBitmapToTexture(FBmpBuffer[info.Slice], texture); }
public TMXTileSet(TMXTiledMap map, XMLElement element, bool loadImage) { this.map = map; this.name = element.GetAttribute("name", null); this.firstGID = element.GetIntAttribute("firstgid", 0); string source = element.GetAttribute("source", ""); if (!"".Equals(source)) { try { Stream ins0 = Resources.OpenStream(map.GetTilesLocation() + "/" + source); XMLDocument doc = XMLParser.Parse(ins0); XMLElement docElement = doc.GetRoot(); element = docElement; } catch (Exception e) { Loon.Utils.Debug.Log.Exception(e); throw new Exception(this.map.tilesLocation + "/" + source); } } string tileWidthString = element.GetAttribute("tilewidth", ""); string tileHeightString = element.GetAttribute("tileheight", ""); if (tileWidthString.Length == 0 || tileHeightString.Length == 0) { throw new Exception( "tileWidthString.length == 0 || tileHeightString.length == 0"); } tileWidth = Int32.Parse(tileWidthString); tileHeight = Int32.Parse(tileHeightString); string sv = element.GetAttribute("spacing", ""); if ((sv != null) && (!"".Equals(sv))) { tileSpacing = Int32.Parse(sv); } string mv = element.GetAttribute("margin", ""); if ((mv != null) && (!"".Equals(mv))) { tileMargin = Int32.Parse(mv); } List <XMLElement> list = element.List("image"); XMLElement imageNode = list[0]; string fileName = imageNode.GetAttribute("source", null); LColor trans = null; string t = imageNode.GetAttribute("trans", null); if ((t != null) && (t.Length > 0)) { trans = new LColor(((uint)Convert.ToInt32(t, 16))); } if (loadImage) { string path = map.GetTilesLocation() + "/" + fileName; LTexture image; if (trans != null) { image = TextureUtils.FilterColor(path, trans); } else { image = LTextures.LoadTexture(path); } SetTileSetImage(image); } List <XMLElement> elements = element.List("tile"); for (int i = 0; i < elements.Count; i++) { XMLElement tileElement = elements[i]; int id = tileElement.GetIntAttribute("id", 0); id += firstGID; TMXProperty tileProps = new TMXProperty(); XMLElement propsElement = tileElement .GetChildrenByName("properties"); List <XMLElement> properties = propsElement.List("property"); for (int p = 0; p < properties.Count; p++) { XMLElement propElement = properties[p]; string name_1 = propElement.GetAttribute("name", null); string value_ren = propElement.GetAttribute("value", null); tileProps.SetProperty(name_1, value_ren); } CollectionUtils.Put(props, id, tileProps); } }