public IntRect Intersection(IntRect r2) { var left = ArrayPoint.Max(offset, r2.offset); var right = ArrayPoint.Min(RightEnd, r2.RightEnd); return new IntRect(left, right - left).IncDimensions(new ArrayPoint(15, 15)); }
public Glyph(Vector2f location, float scale, GlyphConfig settings) { _config = settings; _sprite = new Sprite(_texture) { Scale = new Vector2f(scale, scale), Position = location, }; _spriteOutline = new Sprite(_textureOutline) { Scale = new Vector2f(scale, scale), Position = location, }; var glyphAreaX = (GLYPH_WIDTH*scale); _glyphArea = new IntRect( (int) (location.X - 0.5f*glyphAreaX), (int) location.Y, (int) glyphAreaX, (int) (GLYPH_HEIGHT*scale)); Index = GetRandom.Int(MAX_INDEX); _twitch = new TwitchCalculator(); }
public Person(string name, SpritesetInstance spriteset, bool destroy) { #if(DEBUG) if (_debug1 == null) _debug1 = new ColorInstance(Program._engine, Color.Magenta); if (_debug2 == null) _debug2 = new ColorInstance(Program._engine, Color.Red); #endif Name = name; DestroyOnMap = destroy; Speed = new Vector2f(1, 1); _innerSS = spriteset; Data = Program.CreateObject(); _base = _innerSS.GetBase(); _sprite = new Sprite(_innerSS.TextureAtlas.Texture); Mask = new Color(255, 255, 255); Scripts = new FunctionScript[5]; string d = GetDirectionAt(0); if (!String.IsNullOrEmpty(d)) Direction = d; }
public Chatbox(IResourceManager resourceManager, IUserInterfaceManager userInterfaceManager, IKeyBindingManager keyBindingManager) { _resourceManager = resourceManager; _userInterfaceManager = userInterfaceManager; _keyBindingManager = keyBindingManager; Position = new Vector2i((int)CluwneLib.CurrentClippingViewport.Width - (int)Size.X - 10, 10); ClientArea = new IntRect(Position.X, Position.Y, (int) Size.X, (int) Size.Y); _textInputLabel = new Label("", "CALIBRI", _resourceManager) { Text = { Size = new Vector2i(ClientArea.Width - 10, 12), Color = new SFML.Graphics.Color(0, 128, 0) } }; _chatColors = new Dictionary<ChatChannel, SFML.Graphics.Color> { [ChatChannel.Default] = new SFML.Graphics.Color(128, 128, 128), [ChatChannel.Damage ] = Color.Red, [ChatChannel.Radio ] = new SFML.Graphics.Color(0, 100, 0), [ChatChannel.Server ] = Color.Blue, [ChatChannel.Player ] = new SFML.Graphics.Color(0, 128, 0), [ChatChannel.Lobby ] = Color.White, [ChatChannel.Ingame ] = new SFML.Graphics.Color(0, 128, 0), [ChatChannel.OOC ] = Color.White, [ChatChannel.Emote ] = Color.Cyan, [ChatChannel.Visual ] = Color.Yellow, }; }
public Teleporter(Teleporter copy) : base(copy) { MapName = copy.MapName; WarpPointName = copy.WarpPointName; Area = copy.Area == null ? null : new IntRect(copy.Area); }
public Frame(int id, int nextFrameId, IntRect frame) { this.id = id; this.nextFrameId = nextFrameId; this.frame = frame; }
public static Vector2D GetCenter(IntRect hitbox) { int x = hitbox.Left + hitbox.Width / 2; int y = hitbox.Top + hitbox.Height / 2; return new Vector2D(x, y); }
public TriggerGiveItem(int left, int top, int width, int height, int inAmount, string inDraw, string inItem) { name = "triggerGiveItem"; position = new Vector2f(left, top); boundingbox = new IntRect(left, top, width, height); visible = false; solid = false; trigger = true; _amount = inAmount; _item = inItem; visible = Convert.ToBoolean(inDraw); active = true; /*switch (_item) { case "ItemGoldKey": item = new Items.GoldKey(); break; case "ItemSpectecBlaster": item = new Items.SpectecBlaster(); break; case "ItemSpectecChargeSabre": item = new Items.SpectecChargeSabre(); break; case "ItemInterCoin": item = new Items.InterCoin(); break; } sprite = new Sprite(new Texture("./assets/" + item.tileName));*/ }
/// <summary> /// Creates a new CluwneSprite with a specified portion of the Texture /// </summary> /// <param name="texture"> Texture to draw </param> /// <param name="rectangle"> What part of the Texture to use </param> public CluwneSprite(string key, Texture texture, IntRect rectangle) : base(texture,rectangle) { Key = key; Position = new Vector2(X, Y); Size = new Vector2(Width, Height); }
public void Draw(RenderManager renderMgr) { IntRect subImageRect = new IntRect(0, 0, (int) texture.Size.X, (int) texture.Size.Y); Vector2f centerPos = new Vector2f(box.Left + box.Width * 0.5f, box.Top + box.Height * 0.5f); renderMgr.DrawSprite(texture, subImageRect, centerPos, box.Width, box.Height, false, false, new Color(255, 255, 255, 255), 10000); }
public IntRect Intersection(IntRect otherRect) { var left = ArrayPoint.Max(offset, otherRect.offset); var right = ArrayPoint.Min(RightEnd, otherRect.RightEnd); return new IntRect(left, right - left); }
public IntRect Union(IntRect r2) { var left = ArrayPoint.Min(offset, r2.offset); var right = ArrayPoint.Max(RightEnd, r2.RightEnd); return new IntRect(left, right - left); }
public Door(Door copy) : base(copy) { Area = new IntRect(copy.Area); OnStateChange += new StateEventHandler(Door_OnStateChange); }
public void SetSetting(string mapName, string warpPointName, IntRect rect = null) { MapName = mapName; WarpPointName = warpPointName; SetArea(rect != null ? rect : new IntRect(0, 0, (int)Dimension.X, (int)Dimension.Y)); }
//////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <param name="overlap">Rectangle to be filled with overlapping rect</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(IntRect rect, out IntRect overlap) { // Compute the intersection boundaries int left = Math.Max(Left, rect.Left); int top = Math.Max(Top, rect.Top); int right = Math.Min(Left + Width, rect.Left + rect.Width); int bottom = Math.Min(Top + Height, rect.Top + rect.Height); // If the intersection is valid (positive non zero area), then there is an intersection if ((left < right) && (top < bottom)) { overlap.Left = left; overlap.Top = top; overlap.Width = right - left; overlap.Height = bottom - top; return true; } else { overlap.Left = 0; overlap.Top = 0; overlap.Width = 0; overlap.Height = 0; return false; } }
public TextureAtlas(TextureAtlas copy) { Size = copy.Size; _canvas = new Image(copy._canvas); Texture = new Texture(_canvas); Sources = new IntRect[copy.Sources.Length]; copy.Sources.CopyTo(Sources, 0); }
/// <summary> /// Set position and size of a GUI element using resolution-independant coordinates. Size of the screen in these coordinates is always 1280x720. /// There are a lot of overloads of this method that allow you to use <see cref="Vector2i"/>/<see cref="Vector2u"/> for position and/or size. /// </summary> /// <param name="ctrl">Gui element to resize</param> /// <param name="x">Distance from left of the window to left of ctrl</param> /// <param name="y">Distance from top of the window to top of ctrl</param> /// <param name="w">Width of ctrl</param> /// <param name="h">Height of ctrl</param> /// <param name="screenrect">Actual screen resolusion</param> /// <seealso cref="LayoutSprite"/> public static void LayoutControl(UI.Control ctrl, int x, int y, int w, int h, IntRect screenrect) { // x,y,w,h are relative to 1280x720 ctrl.X = (int)((x / 1280.0f) * screenrect.Width); ctrl.Y = (int)((y / 720.0f) * screenrect.Height); ctrl.Width = (int)((w / 1280.0f) * screenrect.Width); ctrl.Height = (int)((h / 720.0f) * screenrect.Height); }
internal static new void LoadContent() { meleeProjectileTexture = GameBox.loadTexture("images/blue_dot"); meleeProjectileRect = new IntRect(0, 0, 5, 5); volleyProjectileTexture = GameBox.loadTexture("images/atk_boss"); volleyProjectileRect = new IntRect(0, 0, 20, 10); bossCircleTexture = GameBox.loadTexture("images/avatars/bosses/busey"); }
/// <summary> /// This will clip the image, replacing the atlas graphic. /// In order to change the physical bounds, see <see cref="update(image[])"/>. /// </summary> public void SetImageAt(uint index, Image img) { IntRect dest = Sources[index]; int width = Math.Min(dest.Width, (int)img.Size.X); int height = Math.Min(dest.Height, (int)img.Size.Y); IntRect sourceRect = new IntRect(0, 0, width, height); _canvas.Copy(img, (uint)dest.Left, (uint)dest.Top, sourceRect); _modified = true; }
public Texture(Texture copy, IntRect imageSubRect) : this(copy) { ImageSubRect = new IntRect( copy.ImageSubRect.Left + imageSubRect.Left, copy.ImageSubRect.Top + imageSubRect.Top, copy.ImageSubRect.Left + imageSubRect.Right, copy.ImageSubRect.Top + imageSubRect.Bottom); }
public InGameLog(IntRect _res, RenderWindow rw) { Log = new List<InGameLogMessage>(); _screen = rw; Restriction = _res; MinMsg = 0; Program.Log = this; }
public static IntRect getRect(this View view) { IntRect bounds = new IntRect(); bounds.Left = (int)view.Center.X - (int)view.Size.X / 2; bounds.Top = (int)view.Center.Y - (int)view.Size.Y / 2; bounds.Height = (int)view.Size.Y; bounds.Width = (int)view.Size.X; return bounds; }
internal Button(IntRect size, Texture text) : this(size) { texture = text; if (text == null) throw new Exception("null texture?"); sprite = new Sprite(text); sprite.Position = new Vector2f((float)size.Left, (float)size.Top); }
internal static new void LoadContent() { meleeProjectileTexture = GameBox.loadTexture("images/abilitys/tomhanksmelee_proj"); meleeProjectileRect = new IntRect(0, 0, 20, 10); volleyProjectileTexture = GameBox.loadTexture("images/abilitys/tomhanksvolley_proj"); volleyProjectileRect = new IntRect(0, 0, 10, 5); bossCircleTexture = GameBox.loadTexture("images/avatars/circle_edward"); leashTexture = GameBox.loadTexture("images/abilitys/fraizer/leash"); biteTexture = GameBox.loadTexture("images/abilitys/fraizer/bite_big"); }
public TriggerHeal(int left, int top, int width, int height, int healPerTick) { name = "triggerHeal"; position = new Vector2f(left, top); boundingbox = new IntRect(left, top, width, height); visible = false; solid = false; trigger = true; _healPerTick = healPerTick; }
public TriggerMapChange(int left, int top, int width, int height, string map) { name = "triggerMapChange"; position = new Vector2f(left, top); boundingbox = new IntRect(left, top, width, height); visible = false; solid = false; trigger = true; _map = map; }
//////////////////////////////////////////////////////////// /// <summary> /// Check intersection between two rectangles /// </summary> /// <param name="rect"> Rectangle to test</param> /// <returns>True if rectangles overlap</returns> //////////////////////////////////////////////////////////// public bool Intersects(IntRect rect) { // Compute the intersection boundaries int left = Math.Max(Left, rect.Left); int top = Math.Max(Top, rect.Top); int right = Math.Min(Left + Width, rect.Left + rect.Width); int bottom = Math.Min(Top + Height, rect.Top + rect.Height); return (left < right) && (top < bottom); }
void SetArea(IntRect rect) { Area = rect; TeleportationBB = new EBoundingBox(this, EBoundingBoxType.Event, Area.Left, Area.Top, Area.Right, Area.Bottom); TeleportationEvent = new ObjectEvent(ObjectEventType.In); TeleportationEvent.AddAction(new WarpAction(MapName, WarpPointName)); TeleportationBB.AddEvent(TeleportationEvent); AddEventBoundingBox(TeleportationBB, EventBoundingBoxType.Internal); }
//////////////////////////////////////////////////////////// /// <summary> /// Construct the texture from a file in a stream /// </summary> /// <param name="stream">Stream containing the file contents</param> /// <param name="area">Area of the image to load</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public Texture(Stream stream, IntRect area) : base(IntPtr.Zero) { using (StreamAdaptor adaptor = new StreamAdaptor(stream)) { SetThis(sfTexture_createFromStream(adaptor.InputStreamPtr, ref area)); } if (CPointer == IntPtr.Zero) throw new LoadingFailedException("texture"); }
public ContextMenu(Entity entity, Vector2f creationPos, IResourceManager resourceManager, IUserInterfaceManager userInterfaceManager, bool showExamine = true) { _owningEntity = entity; _resourceManager = resourceManager; _userInterfaceManager = userInterfaceManager; var entries = new List<ContextMenuEntry>(); var replies = new List<ComponentReplyMessage>(); entity.SendMessage(this, ComponentMessageType.ContextGetEntries, replies); if (replies.Any()) entries = (List<ContextMenuEntry>) replies.First(x => x.MessageType == ComponentMessageType.ContextGetEntries).ParamsList[0]; if (showExamine) { var examineButton = new ContextMenuButton( new ContextMenuEntry {ComponentMessage = "examine", EntryName = "Examine", IconName = "context_eye"}, _buttonSize, _resourceManager); examineButton.Selected += ContextSelected; _buttons.Add(examineButton); examineButton.Update(0); } var sVarButton = new ContextMenuButton( new ContextMenuEntry {ComponentMessage = "svars", EntryName = "SVars", IconName = "context_eye"}, _buttonSize, _resourceManager); sVarButton.Selected += ContextSelected; _buttons.Add(sVarButton); sVarButton.Update(0); foreach (ContextMenuEntry entry in entries) { var newButton = new ContextMenuButton(entry, _buttonSize, _resourceManager); newButton.Selected += ContextSelected; _buttons.Add(newButton); newButton.Update(0); } float currY = creationPos.Y; foreach (ContextMenuButton button in _buttons) { button.Position = new Vector2i((int) creationPos.X, (int) currY); currY += _buttonSize.Y; } ClientArea = new IntRect((int) creationPos.X, (int) creationPos.Y, (int) _buttonSize.X, _buttons.Count()*(int) _buttonSize.Y); }
//Documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms632667(v=vs.85).aspx private static extern bool AdjustWindowRect( ref IntRect rect, WindowStyles style, bool menu, ExtendedWindowStyles extendedStyle);
public LandChunkContainer(IntRect area) { this.Area = area; this.LandChunk = null; }
public void Draw(Texture texture, Vector2f position, IntRect rec, Color color, Vector2f scale, Vector2f origin, float rotation) { if (currentRenderState.Texture == null || !ReferenceEquals(currentRenderState.Texture, texture)) { SwitchTextures(texture); } if (spriteBatchArray.VertexCount > maxVertexCount) { //spriteBatch.Draw(spriteBatchArray, currentRenderState); //spriteBatchArray.Clear(); } /* Could implement a capacity before restarting drawing * if (count*4 >= capacity) * { * display(false); * if(capacity<MaxCapacity) * { * delete[] vertices; * capacity *= 2; * if(capacity > MaxCapacity) capacity = MaxCapacity; * vertices = new Vertex[capacity]; * } * } */ /* * int rot = (int)(rotation / 360 * LookupSize) & (LookupSize - 1); * float _sin = getSin[rot]; * float _cos = getCos[rot];*/ float _sin = 0, _cos = 1; if (rotation != 0) { rotation = rotation * (float)Math.PI / 180.0f; _sin = (float)Math.Sin(rotation); _cos = (float)Math.Cos(rotation); } origin.X *= scale.X; origin.Y *= scale.Y; scale.X *= rec.Width; scale.Y *= rec.Height; float pX = -origin.X; float pY = -origin.Y; float pCT = 0.6f; //Top left spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + pCT, rec.Top + pCT))); pX += scale.X; //Top right spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + rec.Width - pCT, rec.Top + pCT))); pX -= scale.X; pY += scale.Y; //Bottom left spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + pCT, rec.Top + rec.Height - pCT))); pX += scale.X; pY -= scale.Y; //Top right spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + rec.Width - pCT, rec.Top + pCT))); pY += scale.Y; //Bottom right spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + rec.Width - pCT, rec.Top + rec.Height - pCT))); pX -= scale.X; spriteBatchArray.Append(new Vertex(new Vector2f(pX * _cos - pY * _sin + position.X, pX * _sin + pY * _cos + position.Y), color, new Vector2f(rec.Left + pCT, rec.Top + rec.Height - pCT))); }
public void Center() { var r1 = IntRect.FromExtents(0, 0, 10, 10); Assert.AreEqual(new int2(5, 5), r1.Center); }
public TextureInfo(Texture texture, IntRect subrect) { this.texture = texture; this.subrect = subrect; }
private void Update() { if (!craft.GetIsDead()) { // find target Entity target = getNearestEntity <Entity>(craft, true); craft.GetTargetingSystem().SetTarget(target ? target.transform : null); foreach (Ability a in craft.GetAbilities()) { if (a) { a.Tick(); } } // shouldn't tick if dead or in cutscene, give control to the cutscene if (aggression != AIAggression.KeepMoving && aggroSearchTimer < Time.time && !DialogueSystem.isInCutscene) { // stop or follow target, give up if it's outside range if (target && (target.transform.position - craft.transform.position).sqrMagnitude < 800f) { aggroTarget = target; //Debug.Log("AggroTarget: " + aggroTarget.name + " Factions: " + aggroTarget.faction + " - " + craft.faction); } aggroSearchTimer = Time.time + 1f; } // shouldn't tick if dead or in cutscene, give control to the cutscene if (aggroTarget && !FactionManager.IsAllied(aggroTarget.faction, craft.faction) && !DialogueSystem.isInCutscene) { if (aggroTarget.GetIsDead() || aggroTarget.IsInvisible) { aggroTarget = null; aggroSearchTimer = 0f; } else { // if(craft as Drone && Input.GetKey(KeyCode.D)) Debug.Log(aggroTarget); switch (aggression) { case AIAggression.FollowInRange: var aggroPos = aggroTarget.transform.position; if (timer >= 0.3F) { timer = 0; movement.SetMoveTarget(aggroPos + new Vector3(Random.Range(-1F, 1F), Random.Range(-1F, 1F)), 9); } else { timer += Time.deltaTime; } float dist = movement.DistanceToTarget; if (dist > 1000f) { aggroTarget = null; } if (module is FollowAI && (module as FollowAI).followTarget) { if (((module as FollowAI).followTarget.position - craft.transform.position).sqrMagnitude > 150f) { aggroTarget = null; } } //// Stealth if module is not BattleAI to not interfere with it //if (!(module is BattleAI) && craft.GetHealth()[0] < craft.GetMaxHealth()[0] * 0.25f) //{ // var abilities = craft.GetAbilities(); // if(abilities != null) // { // var stealths = abilities.Where((x) => { return (x != null) && x.GetID() == 24; }); // foreach (var stealth in stealths) // { // stealth.Tick("activate"); // if (stealth.GetActiveTimeRemaining() > 0) // break; // } // } //} break; case AIAggression.StopToAttack: movement.SetMoveTarget(craft.transform.position); break; case AIAggression.KeepMoving: // Back to module's movement aggroTarget = null; break; default: break; } } } else { aggroTarget = null; aggroSearchTimer = 0f; } if (module != null) { if (state == AIState.Active) { module.StateTick(); if (aggroTarget == null) { module.ActionTick(); } if (allowRetreat) { // check if retreat necessary if (craft.GetHealth()[0] < retreatTreshold * craft.GetMaxHealth()[0]) { state = AIState.Retreating; //Debug.Log(craft.name + "[ " + craft.faction + " ] retreating!"); } } } else if (state == AIState.Retreating) { if ((!retreatTargetFound && retreatSearchTimer < Time.time) || retreatSearchTimer < Time.time) { Entity enemy = getNearestEntity <Entity>(craft, true); if (enemy && (enemy.transform.position - craft.transform.position).sqrMagnitude < 1600f) { retreatTarget = craft.transform.position + (craft.transform.position - enemy.transform.position).normalized * 20f; //Debug.Log(craft.name + "[ " + craft.faction + " ] Initial retreat target : " + retreatTarget); IntRect bounds = SectorManager.instance.current.bounds; if (!bounds.contains(retreatTarget)) { retreatTarget = craft.spawnPoint; //Debug.Log(craft.name + "[ " + craft.faction + " ] Updated to Spawn point : " + retreatTarget); } // stay inside sector (just in case the spawn point is outside) if (retreatTarget.x > bounds.x + bounds.w) { retreatTarget = new Vector2(bounds.x + bounds.w, retreatTarget.y); } if (retreatTarget.x < bounds.x) { retreatTarget = new Vector2(bounds.x, retreatTarget.y); } if (retreatTarget.y < bounds.y - bounds.h) { retreatTarget = new Vector2(retreatTarget.x, bounds.y - bounds.h); } if (retreatTarget.y > bounds.y) { retreatTarget = new Vector2(retreatTarget.x, bounds.y); } retreatTargetFound = true; //Debug.Log(craft.name + "[ " + craft.faction + " ] Sector bounds: " + bounds.x + ", " + bounds.y + ", " + bounds.w + ", " + bounds.h); //Debug.Log(craft.name + "[ " + craft.faction + " ] Found a retreat target! : " + retreatTarget); } else { retreatTarget = craft.spawnPoint; retreatTargetFound = true; } retreatSearchTimer = Time.time + 3.0f; } else if (retreatTargetFound) { movement.SetMoveTarget(retreatTarget); if (movement.targetIsInRange() && retreatTarget != (Vector2)craft.spawnPoint) { retreatSearchTimer = 0f; } } else { movement.SetMoveTarget(craft.spawnPoint); } // check if retreating is still necessary if (craft.GetHealth()[0] > retreatTreshold * craft.GetMaxHealth()[0]) { state = AIState.Active; //Debug.Log(craft.name + "[ " + craft.faction + " ] stopped retreating!"); } } else { if (state == AIState.Inactive) { module.Init(); state = AIState.Active; } } } //else //{ // state = AIState.Inactive; //} movement.Update(); abilityControl.Update(); } }
public void SetCanevas(IntRect newCanevas) { // Nothing to do }
public static extern void fc_push_intrect(ref IntRect v);
public static extern void fc_get_value_intrect(long ptr, ref IntRect v);
public static extern void fc_get_intrect(long L, int i, ref IntRect v);
/// <summary>Move an object to occupy a new set of cells</summary> public void Move(T item, IntRect bounds) { Root root; if (!rootLookup.TryGetValue(item, out root)) { throw new System.ArgumentException("The item has not been added to this object"); } var prev = root.previousBounds; if (prev == bounds) { return; } // Remove all for (int i = 0; i < root.items.Count; i++) { Item ob = root.items[i]; ob.prev.next = ob.next; if (ob.next != null) { ob.next.prev = ob.prev; } } root.previousBounds = bounds; int reusedItems = 0; for (int z = bounds.ymin; z <= bounds.ymax; z++) { for (int x = bounds.xmin; x <= bounds.xmax; x++) { Item ob; if (reusedItems < root.items.Count) { ob = root.items[reusedItems]; } else { ob = itemPool.Count > 0 ? itemPool.Pop() : new Item(); ob.root = root; root.items.Add(ob); } reusedItems++; ob.prev = cells[x + z * size.x]; ob.next = ob.prev.next; ob.prev.next = ob; if (ob.next != null) { ob.next.prev = ob; } } } for (int i = root.items.Count - 1; i >= reusedItems; i--) { Item ob = root.items[i]; ob.root = null; ob.next = null; ob.prev = null; root.items.RemoveAt(i); itemPool.Push(ob); } }
public ContextMenu(IEntity entity, Vector2f creationPos, IResourceManager resourceManager, IUserInterfaceManager userInterfaceManager, bool showExamine = true) { _owningEntity = entity; _resourceManager = resourceManager; _userInterfaceManager = userInterfaceManager; var entries = new List <ContextMenuEntry>(); var replies = new List <ComponentReplyMessage>(); entity.SendMessage(this, ComponentMessageType.ContextGetEntries, replies); if (replies.Any()) { entries = (List <ContextMenuEntry>) replies.First(x => x.MessageType == ComponentMessageType.ContextGetEntries).ParamsList[0]; } if (showExamine) { var examineButton = new ContextMenuButton( new ContextMenuEntry { ComponentMessage = "examine", EntryName = "Examine", IconName = "context_eye" }, _buttonSize, _resourceManager); examineButton.Selected += ContextSelected; _buttons.Add(examineButton); examineButton.Update(0); } var sVarButton = new ContextMenuButton( new ContextMenuEntry { ComponentMessage = "svars", EntryName = "SVars", IconName = "context_eye" }, _buttonSize, _resourceManager); sVarButton.Selected += ContextSelected; _buttons.Add(sVarButton); sVarButton.Update(0); foreach (ContextMenuEntry entry in entries) { var newButton = new ContextMenuButton(entry, _buttonSize, _resourceManager); newButton.Selected += ContextSelected; _buttons.Add(newButton); newButton.Update(0); } float currY = creationPos.Y; foreach (ContextMenuButton button in _buttons) { button.Position = new Vector2i((int)creationPos.X, (int)currY); currY += _buttonSize.Y; } ClientArea = new IntRect((int)creationPos.X, (int)creationPos.Y, (int)_buttonSize.X, _buttons.Count() * (int)_buttonSize.Y); }
private void CutPoly(ListView <NavmeshCut> InNavmeshCuts, VInt3[] verts, int[] tris, ref VInt3[] outVertsArr, ref int[] outTrisArr, out int outVCount, out int outTCount, VInt3[] extraShape, VInt3 cuttingOffset, Bounds realBounds, SGameTileHandler.CutMode mode = (SGameTileHandler.CutMode) 3, int perturbate = 0) { if (verts.Length == 0 || tris.Length == 0) { outVCount = 0; outTCount = 0; outTrisArr = new int[0]; outVertsArr = new VInt3[0]; return; } List <IntPoint> list = null; if (extraShape == null && (mode & SGameTileHandler.CutMode.CutExtra) != (SGameTileHandler.CutMode) 0) { throw new Exception("extraShape is null and the CutMode specifies that it should be used. Cannot use null shape."); } if ((mode & SGameTileHandler.CutMode.CutExtra) != (SGameTileHandler.CutMode) 0) { list = new List <IntPoint>(extraShape.Length); for (int i = 0; i < extraShape.Length; i++) { list.Add(new IntPoint((long)(extraShape[i].x + cuttingOffset.x), (long)(extraShape[i].z + cuttingOffset.z))); } } List <IntPoint> list2 = new List <IntPoint>(5); Dictionary <TriangulationPoint, int> dictionary = new Dictionary <TriangulationPoint, int>(); List <PolygonPoint> list3 = new List <PolygonPoint>(); IntRect b = new IntRect(verts[0].x, verts[0].z, verts[0].x, verts[0].z); for (int j = 0; j < verts.Length; j++) { b = b.ExpandToContain(verts[j].x, verts[j].z); } List <VInt3> list4 = ListPool <VInt3> .Claim(verts.Length * 2); List <int> list5 = ListPool <int> .Claim(tris.Length); PolyTree polyTree = new PolyTree(); List <List <IntPoint> > list6 = new List <List <IntPoint> >(); Stack <Polygon> stack = new Stack <Polygon>(); if (this.clipper == null) { this.clipper = new Clipper(0); } this.clipper.set_ReverseSolution(true); this.clipper.set_StrictlySimple(true); ListView <NavmeshCut> listView; if (mode == SGameTileHandler.CutMode.CutExtra) { listView = new ListView <NavmeshCut>(); } else { listView = new ListView <NavmeshCut>(InNavmeshCuts); } List <int> list7 = ListPool <int> .Claim(); List <IntRect> list8 = ListPool <IntRect> .Claim(); List <VInt2> list9 = ListPool <VInt2> .Claim(); List <List <IntPoint> > list10 = new List <List <IntPoint> >(); List <bool> list11 = ListPool <bool> .Claim(); List <bool> list12 = ListPool <bool> .Claim(); if (perturbate > 10) { Debug.LogError("Too many perturbations aborting : " + mode); Debug.Break(); outVCount = verts.Length; outTCount = tris.Length; outTrisArr = tris; outVertsArr = verts; return; } Random random = null; if (perturbate > 0) { random = new Random(); } for (int k = 0; k < listView.Count; k++) { Bounds bounds = listView[k].GetBounds(); VInt3 vInt = (VInt3)bounds.min + cuttingOffset; VInt3 vInt2 = (VInt3)bounds.max + cuttingOffset; IntRect a = new IntRect(vInt.x, vInt.z, vInt2.x, vInt2.z); if (IntRect.Intersects(a, b)) { VInt2 vInt3 = new VInt2(0, 0); if (perturbate > 0) { vInt3.x = random.Next() % 6 * perturbate - 3 * perturbate; if (vInt3.x >= 0) { vInt3.x++; } vInt3.y = random.Next() % 6 * perturbate - 3 * perturbate; if (vInt3.y >= 0) { vInt3.y++; } } int count = list10.get_Count(); listView[k].GetContour(list10); for (int l = count; l < list10.get_Count(); l++) { List <IntPoint> list13 = list10.get_Item(l); if (list13.get_Count() == 0) { Debug.LogError("Zero Length Contour"); list8.Add(default(IntRect)); list9.Add(new VInt2(0, 0)); } else { IntRect intRect = new IntRect((int)list13.get_Item(0).X + cuttingOffset.x, (int)list13.get_Item(0).Y + cuttingOffset.y, (int)list13.get_Item(0).X + cuttingOffset.x, (int)list13.get_Item(0).Y + cuttingOffset.y); for (int m = 0; m < list13.get_Count(); m++) { IntPoint intPoint = list13.get_Item(m); intPoint.X += (long)cuttingOffset.x; intPoint.Y += (long)cuttingOffset.z; if (perturbate > 0) { intPoint.X += (long)vInt3.x; intPoint.Y += (long)vInt3.y; } list13.set_Item(m, intPoint); intRect = intRect.ExpandToContain((int)intPoint.X, (int)intPoint.Y); } list9.Add(new VInt2(vInt.y, vInt2.y)); list8.Add(intRect); list11.Add(listView[k].isDual); list12.Add(listView[k].cutsAddedGeom); } } } } ListView <NavmeshAdd> listView2 = new ListView <NavmeshAdd>(); VInt3[] array = verts; int[] array2 = tris; int num = -1; int n = -3; VInt3[] array3 = null; VInt3[] array4 = null; VInt3 vInt4 = VInt3.zero; if (listView2.Count > 0) { array3 = new VInt3[7]; array4 = new VInt3[7]; vInt4 = (VInt3)realBounds.extents; } while (true) { n += 3; while (n >= array2.Length) { num++; n = 0; if (num >= listView2.Count) { array = null; break; } if (array == verts) { array = null; } listView2[num].GetMesh(cuttingOffset, ref array, out array2); } if (array == null) { break; } VInt3 vInt5 = array[array2[n]]; VInt3 vInt6 = array[array2[n + 1]]; VInt3 vInt7 = array[array2[n + 2]]; IntRect a2 = new IntRect(vInt5.x, vInt5.z, vInt5.x, vInt5.z); a2 = a2.ExpandToContain(vInt6.x, vInt6.z); a2 = a2.ExpandToContain(vInt7.x, vInt7.z); int num2 = Math.Min(vInt5.y, Math.Min(vInt6.y, vInt7.y)); int num3 = Math.Max(vInt5.y, Math.Max(vInt6.y, vInt7.y)); list7.Clear(); bool flag = false; for (int num4 = 0; num4 < list10.get_Count(); num4++) { int x = list9.get_Item(num4).x; int y = list9.get_Item(num4).y; if (IntRect.Intersects(a2, list8.get_Item(num4)) && y >= num2 && x <= num3 && (list12.get_Item(num4) || num == -1)) { VInt3 vInt8 = vInt5; vInt8.y = x; VInt3 vInt9 = vInt5; vInt9.y = y; list7.Add(num4); flag |= list11.get_Item(num4); } } if (list7.get_Count() == 0 && (mode & SGameTileHandler.CutMode.CutExtra) == (SGameTileHandler.CutMode) 0 && (mode & SGameTileHandler.CutMode.CutAll) != (SGameTileHandler.CutMode) 0 && num == -1) { list5.Add(list4.get_Count()); list5.Add(list4.get_Count() + 1); list5.Add(list4.get_Count() + 2); list4.Add(vInt5); list4.Add(vInt6); list4.Add(vInt7); } else { list2.Clear(); if (num == -1) { list2.Add(new IntPoint((long)vInt5.x, (long)vInt5.z)); list2.Add(new IntPoint((long)vInt6.x, (long)vInt6.z)); list2.Add(new IntPoint((long)vInt7.x, (long)vInt7.z)); } else { array3[0] = vInt5; array3[1] = vInt6; array3[2] = vInt7; int num5 = Utility.ClipPolygon(array3, 3, array4, 1, 0, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * vInt4.x, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array3, num5, array4, 1, 0, 2); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * vInt4.z, 2); if (num5 == 0) { continue; } for (int num6 = 0; num6 < num5; num6++) { list2.Add(new IntPoint((long)array3[num6].x, (long)array3[num6].z)); } } dictionary.Clear(); VInt3 vInt10 = vInt6 - vInt5; VInt3 vInt11 = vInt7 - vInt5; VInt3 vInt12 = vInt10; VInt3 vInt13 = vInt11; vInt12.y = 0; vInt13.y = 0; for (int num7 = 0; num7 < 16; num7++) { if ((mode >> (num7 & 31) & SGameTileHandler.CutMode.CutAll) != (SGameTileHandler.CutMode) 0) { if (1 << num7 == 1) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num8 = 0; num8 < list7.get_Count(); num8++) { this.clipper.AddPolygon(list10.get_Item(list7.get_Item(num8)), 1); } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 2) { if (!flag) { goto IL_1173; } this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num9 = 0; num9 < list7.get_Count(); num9++) { if (list11.get_Item(list7.get_Item(num9))) { this.clipper.AddPolygon(list10.get_Item(list7.get_Item(num9)), 1); } } list6.Clear(); this.clipper.Execute(0, list6, 0, 1); this.clipper.Clear(); for (int num10 = 0; num10 < list6.get_Count(); num10++) { this.clipper.AddPolygon(list6.get_Item(num10), (!Clipper.Orientation(list6.get_Item(num10))) ? 0 : 1); } for (int num11 = 0; num11 < list7.get_Count(); num11++) { if (!list11.get_Item(list7.get_Item(num11))) { this.clipper.AddPolygon(list10.get_Item(list7.get_Item(num11)), 1); } } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 4) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); this.clipper.AddPolygon(list, 1); polyTree.Clear(); this.clipper.Execute(0, polyTree, 0, 1); } for (int num12 = 0; num12 < polyTree.get_ChildCount(); num12++) { PolyNode polyNode = polyTree.get_Childs().get_Item(num12); List <IntPoint> contour = polyNode.get_Contour(); List <PolyNode> childs = polyNode.get_Childs(); if (childs.get_Count() == 0 && contour.get_Count() == 3 && num == -1) { for (int num13 = 0; num13 < contour.get_Count(); num13++) { VInt3 vInt14 = new VInt3((int)contour.get_Item(num13).X, 0, (int)contour.get_Item(num13).Y); double num14 = (double)(vInt6.z - vInt7.z) * (double)(vInt5.x - vInt7.x) + (double)(vInt7.x - vInt6.x) * (double)(vInt5.z - vInt7.z); if (num14 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num15 = ((double)(vInt6.z - vInt7.z) * (double)(vInt14.x - vInt7.x) + (double)(vInt7.x - vInt6.x) * (double)(vInt14.z - vInt7.z)) / num14; double num16 = ((double)(vInt7.z - vInt5.z) * (double)(vInt14.x - vInt7.x) + (double)(vInt5.x - vInt7.x) * (double)(vInt14.z - vInt7.z)) / num14; vInt14.y = (int)Math.Round(num15 * (double)vInt5.y + num16 * (double)vInt6.y + (1.0 - num15 - num16) * (double)vInt7.y); list5.Add(list4.get_Count()); list4.Add(vInt14); } } } else { Polygon polygon = null; int num17 = -1; for (List <IntPoint> list14 = contour; list14 != null; list14 = ((num17 >= childs.get_Count()) ? null : childs.get_Item(num17).get_Contour())) { list3.Clear(); for (int num18 = 0; num18 < list14.get_Count(); num18++) { PolygonPoint polygonPoint = new PolygonPoint((double)list14.get_Item(num18).X, (double)list14.get_Item(num18).Y); list3.Add(polygonPoint); VInt3 vInt15 = new VInt3((int)list14.get_Item(num18).X, 0, (int)list14.get_Item(num18).Y); double num19 = (double)(vInt6.z - vInt7.z) * (double)(vInt5.x - vInt7.x) + (double)(vInt7.x - vInt6.x) * (double)(vInt5.z - vInt7.z); if (num19 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num20 = ((double)(vInt6.z - vInt7.z) * (double)(vInt15.x - vInt7.x) + (double)(vInt7.x - vInt6.x) * (double)(vInt15.z - vInt7.z)) / num19; double num21 = ((double)(vInt7.z - vInt5.z) * (double)(vInt15.x - vInt7.x) + (double)(vInt5.x - vInt7.x) * (double)(vInt15.z - vInt7.z)) / num19; vInt15.y = (int)Math.Round(num20 * (double)vInt5.y + num21 * (double)vInt6.y + (1.0 - num20 - num21) * (double)vInt7.y); dictionary.set_Item(polygonPoint, list4.get_Count()); list4.Add(vInt15); } } Polygon polygon2; if (stack.get_Count() > 0) { polygon2 = stack.Pop(); polygon2.AddPoints(list3); } else { polygon2 = new Polygon(list3); } if (polygon == null) { polygon = polygon2; } else { polygon.AddHole(polygon2); } num17++; } try { P2T.Triangulate(polygon); } catch (PointOnEdgeException) { Debug.LogWarning(string.Concat(new object[] { "PointOnEdgeException, perturbating vertices slightly ( at ", num7, " in ", mode, ")" })); this.CutPoly(InNavmeshCuts, verts, tris, ref outVertsArr, ref outTrisArr, out outVCount, out outTCount, extraShape, cuttingOffset, realBounds, mode, perturbate + 1); return; } for (int num22 = 0; num22 < polygon.get_Triangles().get_Count(); num22++) { DelaunayTriangle delaunayTriangle = polygon.get_Triangles().get_Item(num22); list5.Add(dictionary.get_Item(delaunayTriangle.Points._0)); list5.Add(dictionary.get_Item(delaunayTriangle.Points._1)); list5.Add(dictionary.get_Item(delaunayTriangle.Points._2)); } if (polygon.get_Holes() != null) { for (int num23 = 0; num23 < polygon.get_Holes().get_Count(); num23++) { polygon.get_Holes().get_Item(num23).get_Points().Clear(); polygon.get_Holes().get_Item(num23).ClearTriangles(); if (polygon.get_Holes().get_Item(num23).get_Holes() != null) { polygon.get_Holes().get_Item(num23).get_Holes().Clear(); } stack.Push(polygon.get_Holes().get_Item(num23)); } } polygon.ClearTriangles(); if (polygon.get_Holes() != null) { polygon.get_Holes().Clear(); } polygon.get_Points().Clear(); stack.Push(polygon); } } } IL_1173 :; } } } Dictionary <VInt3, int> dictionary2 = this.cached_Int3_int_dict; dictionary2.Clear(); if (this.cached_int_array.Length < list4.get_Count()) { this.cached_int_array = new int[Math.Max(this.cached_int_array.Length * 2, list4.get_Count())]; } int[] array5 = this.cached_int_array; int num24 = 0; for (int num25 = 0; num25 < list4.get_Count(); num25++) { int num26; if (!dictionary2.TryGetValue(list4.get_Item(num25), ref num26)) { dictionary2.Add(list4.get_Item(num25), num24); array5[num25] = num24; list4.set_Item(num24, list4.get_Item(num25)); num24++; } else { array5[num25] = num26; } } outTCount = list5.get_Count(); if (outTrisArr == null || outTrisArr.Length < outTCount) { outTrisArr = new int[outTCount]; } for (int num27 = 0; num27 < outTCount; num27++) { outTrisArr[num27] = array5[list5.get_Item(num27)]; } outVCount = num24; if (outVertsArr == null || outVertsArr.Length < outVCount) { outVertsArr = new VInt3[outVCount]; } for (int num28 = 0; num28 < outVCount; num28++) { outVertsArr[num28] = list4.get_Item(num28); } for (int num29 = 0; num29 < listView.Count; num29++) { listView[num29].UsedForCut(); } ListPool <VInt3> .Release(list4); ListPool <int> .Release(list5); ListPool <int> .Release(list7); ListPool <VInt2> .Release(list9); ListPool <bool> .Release(list11); ListPool <bool> .Release(list12); ListPool <IntRect> .Release(list8); }
public static Vector2u GetSize(this IntRect rect) { return(new Vector2u((uint)rect.Width, (uint)rect.Height)); }
public static void SetTransformToRect(this SFML.Graphics.Sprite sprite, IntRect rect) { sprite.Scale = new SFML.System.Vector2f((float)rect.Width / (float)sprite.TextureRect.Width, (float)rect.Height / (float)sprite.TextureRect.Height); sprite.Position = new Vector2f(rect.Left, rect.Top); }
public override void Update(float frameTime) { if (disposing || !IsVisible()) { return; } ClientArea = new IntRect(Position, new Vector2i((int)clippingRI.Width, (int)clippingRI.Height)); if (inner_focus != null && !components.Contains((GuiComponent)inner_focus)) { ClearFocus(); } scrollbarH.Position = new Vector2i(ClientArea.Left, ClientArea.Bottom() - scrollbarH.ClientArea.Height); scrollbarV.Position = new Vector2i(ClientArea.Right() - scrollbarV.ClientArea.Width, ClientArea.Top); if (scrollbarV.IsVisible()) { scrollbarH.size = Size.X - scrollbarV.ClientArea.Width; } else { scrollbarH.size = Size.X; } if (scrollbarH.IsVisible()) { scrollbarV.size = Size.Y - scrollbarH.ClientArea.Height; } else { scrollbarV.size = Size.Y; } max_x = 0; max_y = 0; foreach (GuiComponent component in components) { if (component.Position.X + component.ClientArea.Width > max_x) { max_x = component.Position.X + component.ClientArea.Width; } if (component.Position.Y + component.ClientArea.Height > max_y) { max_y = component.Position.Y + component.ClientArea.Height; } } scrollbarH.max = (int)max_x - ClientArea.Width + (max_y > clippingRI.Height ? scrollbarV.ClientArea.Width : 0); if (max_x > clippingRI.Width) { scrollbarH.SetVisible(true); } else { scrollbarH.SetVisible(false); } scrollbarV.max = (int)max_y - ClientArea.Height + (max_x > clippingRI.Height ? scrollbarH.ClientArea.Height : 0); if (max_y > clippingRI.Height) { scrollbarV.SetVisible(true); } else { scrollbarV.SetVisible(false); } scrollbarH.Update(frameTime); scrollbarV.Update(frameTime); }
public static void thickenAndOffset(ref AXParameter sp, AXParameter src) { if (sp == null || src == null) { return; } //sp.polyTree = null; float thickness = sp.thickness; float roundness = sp.roundness; float offset = sp.offset; bool flipX = sp.flipX; //Debug.Log(sp.parametricObject.Name + "." + sp.Name +"."+ sp.offset); //bool srcIsCC = src.isCCW(); Paths subjPaths = src.getClonePaths(); if (subjPaths == null) { return; } // FLIP_X if (flipX) { //Debug.Log(subjPaths.Count); //AXGeometryTools.Utilities.printPaths(subjPaths); subjPaths = AXGeometryTools.Utilities.transformPaths(subjPaths, Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(-1, 1, 1))); sp.transformedControlPaths = AXGeometryTools.Utilities.transformPaths(sp.transformedControlPaths, Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(-1, 1, 1))); } // SYMMETRY if (sp.symmetry) { if (subjPaths != null && subjPaths.Count > 0) { for (int i = 0; i < subjPaths.Count; i++) { Path orig = subjPaths[i]; Path sym = new Path(); float seperation = sp.symSeperation * AXGeometryTools.Utilities.IntPointPrecision; float apex = .1f * seperation; for (int j = 0; j < orig.Count; j++) { sym.Add(new IntPoint(orig[j].X + seperation / 2, orig[j].Y)); } // midpoint. slightly raised sym.Add(new IntPoint(0, orig[orig.Count - 1].Y + apex)); for (int j = orig.Count - 1; j >= 0; j--) { sym.Add(new IntPoint(-orig[j].X - seperation / 2, orig[j].Y)); } subjPaths[i] = sym; } } } AX.Generators.Generator2D gener2D = sp.parametricObject.generator as AX.Generators.Generator2D; if (subjPaths != null && gener2D != null && (gener2D.scaleX != 1 || gener2D.scaleY != 1)) { sp.transformedButUnscaledOutputPaths = AX.Generators.Generator2D.transformPaths(subjPaths, gener2D.localUnscaledMatrix); } else { sp.transformedButUnscaledOutputPaths = null; } //cleanPolygonPrecision IntRect brect = Clipper.GetBounds(subjPaths); if ((brect.right - brect.left) < 100000) { cleanPolygonPrecision = 2; } else { cleanPolygonPrecision = 30; } //Debug.Log("cleanPolygonPrecision="+cleanPolygonPrecision); /* * if (offset_p.FloatVal == 0 && wallthick_p.FloatVal == 0) * { * sp.polyTree = src.polyTree; * sp.paths = src.paths; * return; * } * */ //sp.polyTree = null; //Debug.Log("new count a = " + subjPaths[0].Count); bool hasOffset = false; sp.hasThickness = false; Paths resPaths = new Paths(); AXClipperLib.PolyTree resPolytree = null; // OFFSETTER ClipperOffset co = new ClipperOffset(); //co.ArcTolerance = sp.arcTolerance; float smooth = (float)(120 / (sp.arcTolerance * sp.arcTolerance)); float smoothLOD = ((smooth - .048f) * sp.parametricObject.model.segmentReductionFactor) + .048f; co.ArcTolerance = (float)(Mathf.Sqrt(120 / smoothLOD)); co.MiterLimit = 2.0f; //if (offset != 0) // 1. Offset? Can't offset an open shape if (sp.shapeState == ShapeState.Closed && (sp.endType == AXClipperLib.EndType.etClosedLine || sp.endType == AXClipperLib.EndType.etClosedPolygon)) { //AXClipperLib.JoinType jt = (sp.endType == AXClipperLib.EndType.etClosedLine) ? JoinType.jtMiter : sp.joinType;//output.joinType; AXClipperLib.JoinType jt = (sp.parametricObject.model.segmentReductionFactor < .15f) ? AXClipperLib.JoinType.jtSquare : sp.joinType; //output.joinType; //Debug.Log ("sp.endType="+sp.endType+", jt="+jt); if (roundness != 0) { // reduce co.Clear(); if (subjPaths != null) { co.AddPaths(AXGeometryTools.Utilities.cleanPaths(subjPaths, cleanPolygonPrecision), jt, AXClipperLib.EndType.etClosedPolygon); //JoinType.jtSquare, AXClipperLib.EndType.etClosedPolygon); } co.Execute(ref subjPaths, (double)(-roundness * AXGeometryTools.Utilities.IntPointPrecision)); } offset += roundness; if (subjPaths != null) { subjPaths = Clipper.SimplifyPolygons(subjPaths, PolyFillType.pftNonZero); } co.Clear(); hasOffset = true; // if (offset != 0 || thickness == 0) { // --! PUC ** Removed because the pass thru was causing a problem with Instance2D of a ShapeMerger // Do Offset // = true; if (subjPaths != null) { // After changes made mid April to allow for FlipX, this started doubling the localMatrix and thus became redundent, though not sure why. //if (gener2D != null) // sp.transformedAndScaledButNotOffsetdOutputPaths = AX.Generators.Generator2D.transformPaths(subjPaths, gener2D.localMatrix); co.AddPaths(AXGeometryTools.Utilities.cleanPaths(subjPaths, cleanPolygonPrecision), jt, AXClipperLib.EndType.etClosedPolygon); //JoinType.jtSquare, AXClipperLib.EndType.etClosedPolygon); // this resPolytree has transformed curves in it resPolytree = new AXClipperLib.PolyTree(); co.Execute(ref resPolytree, (double)(offset * AXGeometryTools.Utilities.IntPointPrecision)); } // } if (thickness > 0) { // No offset, but is closed sp.transformedAndScaledButNotOffsetdOutputPaths = null; if (src.polyTree != null) { if (thickness > 0) { resPaths = subjPaths; // Clipper.PolyTreeToPaths(src.polyTree); } else { resPolytree = src.polyTree; } } else { resPaths = subjPaths; } } } else { //resPolytree = src.polyTree; if (src.polyTree != null) { if (thickness > 0) { resPaths = subjPaths; // Clipper.PolyTreeToPaths(src.polyTree); } else { resPolytree = src.polyTree; } } else { resPaths = subjPaths; } } // 2. Thickness? //subjPaths = sp.getPaths(); if ((sp.endType != AXClipperLib.EndType.etClosedPolygon) && thickness > 0) //input.endType != AXClipperLib.EndType.etClosedPolygon) { { // this is a wall if (resPaths != null && gener2D != null) { sp.transformedFullyAndOffsetdButNotThickenedOutputPaths = AX.Generators.Generator2D.transformPaths(resPaths, gener2D.localMatrix); } sp.hasThickness = true; co.Clear(); if (resPolytree != null) // closed block has happened { co.AddPaths(AXGeometryTools.Utilities.cleanPaths(Clipper.PolyTreeToPaths(resPolytree), cleanPolygonPrecision), sp.joinType, sp.endType); //input.endType); } else if (resPaths != null) { co.AddPaths(AXGeometryTools.Utilities.cleanPaths(resPaths, cleanPolygonPrecision), sp.joinType, sp.endType); //input.endType); } resPolytree = new AXClipperLib.PolyTree(); co.Execute(ref resPolytree, (double)(thickness * AXGeometryTools.Utilities.IntPointPrecision)); } else { sp.transformedFullyAndOffsetdButNotThickenedOutputPaths = null; } // 3. Update input data //Debug.Log(sp.parametricObject.Name + "." + sp.Name + " here ["+hasOffset+"] " + (! sp.symmetry) + " " + (! flipX) + " " + (! hasOffset) + " " + (! hasThicken) + " " + (roundness == 0)); // SIMPLE PASSTHRU? if (!sp.symmetry && !flipX && !hasOffset && !sp.hasThickness && roundness == 0) { // SIMPLE PASS THROUGH sp.polyTree = src.polyTree; sp.paths = src.paths; } else { if (resPolytree == null) { //sp.paths = resPaths; //Generator2D.transformPaths(resPaths, gener2D.localMatrix); //if (Clipper.Orientation(resPaths[0]) != srcIsCC) // AXGeometryTools.Utilities.reversePaths(ref resPaths); sp.paths = AXGeometryTools.Utilities.cleanPaths(resPaths, cleanPolygonPrecision); } else { //Generator2D.transformPolyTree(resPolytree, gener2D.localMatrix); //if (resPolytree != null && resPolytree.Childs.Count > 0 && Clipper.Orientation(resPolytree.Childs[0].Contour) != srcIsCC) // AXGeometryTools.Utilities.reversePolyTree(resPolytree); sp.polyTree = resPolytree; } } // REVERSE if (sp.reverse) { if (sp.polyTree != null) { AXGeometryTools.Utilities.reversePolyTree(sp.polyTree); } else if (sp.paths != null && sp.paths.Count > 0) { for (int i = 0; i < sp.paths.Count; i++) { sp.paths[i].Reverse(); } } } // if (sp.paths != null && sp.paths.Count > 0) // { // // SUBDIVISION // Debug.Log("sp.paths.Count="+sp.paths.Count); // // for(int i=0; i<sp.paths.Count; i++) // { // // // Path path = sp.paths[i]; // Path subdivPath = new Path(); // // for (int j=0; j<path.Count-1; j++) // { // subdivPath.Add(path[j]); // Vector2 v0 = new Vector2(path[j].X, path[j].Y); // Vector2 v1 = new Vector2(path[j+1].X, path[j+1].Y); // // Debug.Log("["+i+"]["+j+"] " + Vector2.Distance(v0, v1)/10000); // Vector2 newp = Vector2.Lerp(v0, v1, .5f); // // subdivPath.Add(new IntPoint(newp.x, newp.y)); // } // subdivPath.Add(path[path.Count-1]); // // // sp.paths[i] = subdivPath; // // Debug.Log("------------"); // AXGeometryTools.Utilities.printPath(sp.paths[i]); // } // // SUBDIVISION --- // } // }
/** Async method for moving the graph */ IEnumerator UpdateGraphCoroutine() { // Find the direction // that we want to move the graph in. // Calcuculate this in graph space (where a distance of one is the size of one node) Vector3 dir = PointToGraphSpace(target.position) - PointToGraphSpace(graph.center); // Snap to a whole number of nodes dir.x = Mathf.Round(dir.x); dir.z = Mathf.Round(dir.z); dir.y = 0; // Nothing do to if (dir == Vector3.zero) { yield break; } // Number of nodes to offset in each direction Int2 offset = new Int2(-Mathf.RoundToInt(dir.x), -Mathf.RoundToInt(dir.z)); // Move the center (this is in world units, so we need to convert it back from graph space) graph.center += graph.matrix.MultiplyVector(dir); graph.GenerateMatrix(); // Create a temporary buffer // required for the calculations if (tmp == null || tmp.Length != graph.nodes.Length) { tmp = new GridNode[graph.nodes.Length]; } // Cache some variables for easier access int width = graph.width; int depth = graph.depth; GridNode[] nodes = graph.nodes; // Check if we have moved // less than a whole graph // width in any direction if (Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth) { // Offset each node by the #offset variable // nodes which would end up outside the graph // will wrap around to the other side of it for (int z = 0; z < depth; z++) { int pz = z * width; int tz = ((z + offset.y + depth) % depth) * width; for (int x = 0; x < width; x++) { tmp[tz + ((x + offset.x + width) % width)] = nodes[pz + x]; } } yield return(null); // Copy the nodes back to the graph // and set the correct indices for (int z = 0; z < depth; z++) { int pz = z * width; for (int x = 0; x < width; x++) { GridNode node = tmp[pz + x]; node.NodeInGridIndex = pz + x; nodes[pz + x] = node; } } IntRect r = new IntRect(0, 0, offset.x, offset.y); int minz = r.ymax; int maxz = depth; // If offset.x < 0, adjust the rect if (r.xmin > r.xmax) { int tmp2 = r.xmax; r.xmax = width + r.xmin; r.xmin = width + tmp2; } // If offset.y < 0, adjust the rect if (r.ymin > r.ymax) { int tmp2 = r.ymax; r.ymax = depth + r.ymin; r.ymin = depth + tmp2; minz = 0; maxz = r.ymin; } // Make sure erosion is taken into account // Otherwise we would end up with ugly artifacts r = r.Expand(graph.erodeIterations + 1); // Makes sure the rect stays inside the grid r = IntRect.Intersection(r, new IntRect(0, 0, width, depth)); yield return(null); // Update all nodes along one edge of the graph // With the same width as the rect for (int z = r.ymin; z < r.ymax; z++) { for (int x = 0; x < width; x++) { graph.UpdateNodePositionCollision(nodes[z * width + x], x, z, false); } } yield return(null); // Update all nodes along the other edge of the graph // With the same width as the rect for (int z = minz; z < maxz; z++) { for (int x = r.xmin; x < r.xmax; x++) { graph.UpdateNodePositionCollision(nodes[z * width + x], x, z, false); } } yield return(null); // Calculate all connections for the nodes // that might have changed for (int z = r.ymin; z < r.ymax; z++) { for (int x = 0; x < width; x++) { graph.CalculateConnections(x, z, nodes[z * width + x]); } } yield return(null); // Calculate all connections for the nodes // that might have changed for (int z = minz; z < maxz; z++) { for (int x = r.xmin; x < r.xmax; x++) { graph.CalculateConnections(x, z, nodes[z * width + x]); } } yield return(null); // Calculate all connections for the nodes along the boundary // of the graph, these always need to be updated /** \todo Optimize to not traverse all nodes in the graph, only those at the edges */ for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { if (x == 0 || z == 0 || x >= width - 1 || z >= depth - 1) { graph.CalculateConnections(x, z, nodes[z * width + x]); } } } } else { // Just update all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.UpdateNodePositionCollision(nodes[z * width + x], x, z, false); } } // Recalculate the connections of all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.CalculateConnections(x, z, nodes[z * width + x]); } } } if (floodFill) { yield return(null); // Make sure the areas for the graph // have been recalculated // not doing this can cause pathfinding to fail AstarPath.active.QueueWorkItemFloodFill(); } }
public BatchedSprite(Texture texture, IntRect textureRect) { Texture = texture; TextureRect = textureRect; }
/// <summary> /// Tries to pack the subdirectory alone into textureatlases. Can be configured to throw if it needs more than one atlas. /// Can also mark the atlas as full even if it isn't upon finishing. /// </summary> /// <param name="directoryPath"></param> /// <param name="markAsFull"></param> /// <param name="throwIfOverflow"></param> private void PackSubdirectoryAlone(string directoryPath, bool markAsFull, bool throwIfOverflow) { //First get the images List <KeyValuePair <String, Image> > textureSet = new List <KeyValuePair <string, Image> >(); List <string> textureFileNames = new List <string>(Directory.EnumerateFiles(directoryPath, "*.png", SearchOption.AllDirectories)); foreach (string textureFileName in textureFileNames) { textureSet.Add(new KeyValuePair <string, Image>(Path.GetFileNameWithoutExtension(textureFileName), new Image(textureFileName))); Console.WriteLine("\tLoaded image" + Path.GetFileNameWithoutExtension(textureFileName)); } //Sort the images by area textureSet.Sort(delegate(KeyValuePair <string, Image> kvp1, KeyValuePair <string, Image> kvp2) { uint a1 = kvp1.Value.Size.X * kvp1.Value.Size.Y; uint a2 = kvp2.Value.Size.X * kvp2.Value.Size.Y; return((int)(a2 - a1)); }); //Write the sorted sizes to console foreach (KeyValuePair <string, Image> kvp in textureSet) { Console.WriteLine("Size: " + (kvp.Value.Size.X * kvp.Value.Size.Y) + " : " + kvp.Key); } //Next, render the images into textures starting with the largest using scanline algo int firstIndex = textureAtlases.Count; foreach (KeyValuePair <string, Image> kvp in textureSet) { //Calculate the bounding box for the image IntRect place = new IntRect(0, 0, (int)kvp.Value.Size.X, (int)kvp.Value.Size.Y); int curIndex = firstIndex; //Create a new textureAtlas to pack into if (curIndex >= textureAtlases.Count) { textureAtlases.Add(new TextureAtlas(Props.textureAtlasSize, Props.textureAtlasSize)); } bool placed = false; //Try to keep placing the texture while (placed == false) { if (textureAtlases[curIndex].textures.Count == 0) //If there is no other present textures, pack the texture immediately { textureAtlases[curIndex].atlas.Update(kvp.Value, 0, 0); textureAtlases[curIndex].textures.Add(kvp.Key, place); textureAtlasIndex.Add(kvp.Key, curIndex); placed = true; if (place.Left + place.Width > Props.textureAtlasSize - Props.textureAtlasFullMargin && place.Top + place.Height > Props.textureAtlasSize - Props.textureAtlasFullMargin) { textureAtlases[curIndex].full = true; } } else { for (uint curX = 0; curX < Props.textureAtlasSize - place.Width; curX++) { for (uint curY = 0; curY < Props.textureAtlasSize - place.Height; curY++) { place.Left = (int)curX; place.Top = (int)curY; bool collided = false; foreach (KeyValuePair <string, IntRect> rect in textureAtlases[curIndex].textures) { if (place.Intersects(rect.Value)) { collided = true; } } if (collided == false) { textureAtlases[curIndex].atlas.Update(kvp.Value, curX, curY); textureAtlases[curIndex].textures.Add(kvp.Key, place); textureAtlasIndex.Add(kvp.Key, curIndex); curY = Props.textureAtlasSize; curX = Props.textureAtlasSize; placed = true; if (place.Left + place.Width > Props.textureAtlasSize - Props.textureAtlasFullMargin && place.Top + place.Height > Props.textureAtlasSize - Props.textureAtlasFullMargin) { textureAtlases[curIndex].full = true; } } } } } if (placed == false) { if (throwIfOverflow) { throw new InvalidOperationException("The texture packing failed unexpectedly (or expectedly)! :( \n\tFailure Cause Directory:" + directoryPath); } else { if (markAsFull) { textureAtlases[curIndex].full = true; } curIndex++; if (curIndex >= textureAtlases.Count) { textureAtlases.Add(new TextureAtlas(4096, 4096)); } while (textureAtlases[curIndex].full == true) { curIndex++; if (curIndex >= textureAtlases.Count) { textureAtlases.Add(new TextureAtlas(Props.textureAtlasSize, Props.textureAtlasSize)); } } } } } } textureAtlases[firstIndex].full = true; }
static extern void sfShape_setTextureRect(IntPtr CPointer, IntRect Rect);
public virtual void changeSizePreview(Element element, IntRect newRect, ResizeType resizeType, IntSize2 bounds) { }
/** Async method for moving the graph */ IEnumerator UpdateGraphCoroutine() { // Find the direction that we want to move the graph in. // Calcuculate this in graph space (where a distance of one is the size of one node) Vector3 dir = PointToGraphSpace(target.position) - PointToGraphSpace(graph.center); // Snap to a whole number of nodes dir.x = Mathf.Round(dir.x); dir.z = Mathf.Round(dir.z); dir.y = 0; // Nothing do to if (dir == Vector3.zero) { yield break; } // Number of nodes to offset in each direction Int2 offset = new Int2(-Mathf.RoundToInt(dir.x), -Mathf.RoundToInt(dir.z)); // Move the center (this is in world units, so we need to convert it back from graph space) graph.center += graph.transform.TransformVector(dir); graph.UpdateTransform(); // Cache some variables for easier access int width = graph.width; int depth = graph.depth; GridNodeBase[] nodes; // Layers are required when handling LayeredGridGraphs int layers = graph.LayerCount; nodes = graph.nodes; // Create a temporary buffer required for the calculations if (buffer == null || buffer.Length != width * depth) { buffer = new GridNodeBase[width * depth]; } // Check if we have moved less than a whole graph width all directions // If we have moved more than this we can just as well recalculate the whole graph if (Mathf.Abs(offset.x) <= width && Mathf.Abs(offset.y) <= depth) { IntRect recalculateRect = new IntRect(0, 0, offset.x, offset.y); // If offset.x < 0, adjust the rect if (recalculateRect.xmin > recalculateRect.xmax) { int tmp2 = recalculateRect.xmax; recalculateRect.xmax = width + recalculateRect.xmin; recalculateRect.xmin = width + tmp2; } // If offset.y < 0, adjust the rect if (recalculateRect.ymin > recalculateRect.ymax) { int tmp2 = recalculateRect.ymax; recalculateRect.ymax = depth + recalculateRect.ymin; recalculateRect.ymin = depth + tmp2; } // Connections need to be recalculated for the neighbours as well, so we need to expand the rect by 1 var connectionRect = recalculateRect.Expand(1); // Makes sure the rect stays inside the grid connectionRect = IntRect.Intersection(connectionRect, new IntRect(0, 0, width, depth)); // Offset each node by the #offset variable // nodes which would end up outside the graph // will wrap around to the other side of it for (int l = 0; l < layers; l++) { int layerOffset = l * width * depth; for (int z = 0; z < depth; z++) { int pz = z * width; int tz = ((z + offset.y + depth) % depth) * width; for (int x = 0; x < width; x++) { buffer[tz + ((x + offset.x + width) % width)] = nodes[layerOffset + pz + x]; } } yield return(null); // Copy the nodes back to the graph // and set the correct indices for (int z = 0; z < depth; z++) { int pz = z * width; for (int x = 0; x < width; x++) { int newIndex = pz + x; var node = buffer[newIndex]; if (node != null) { node.NodeInGridIndex = newIndex; } nodes[layerOffset + newIndex] = node; } // Calculate the limits for the region that has been wrapped // to the other side of the graph int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = depth; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { var node = buffer[pz + x]; if (node != null) { // Clear connections on all nodes that are wrapped and placed on the other side of the graph. // This is both to clear any custom connections (which do not really make sense after moving the node) // and to prevent possible exceptions when the node will later (possibly) be destroyed because it was // not needed anymore (only for layered grid graphs). node.ClearConnections(false); } } } yield return(null); } // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = 1000; // To avoid the update taking too long, make yieldEvery somewhat proportional to the number of nodes that we are going to update int approxNumNodesToUpdate = Mathf.Max(Mathf.Abs(offset.x), Mathf.Abs(offset.y)) * Mathf.Max(width, depth); yieldEvery = Mathf.Max(yieldEvery, approxNumNodesToUpdate / 10); int counter = 0; // Recalculate the nodes // Take a look at the image in the docs for the UpdateGraph method // to see which nodes are being recalculated. for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= recalculateRect.ymin && z < recalculateRect.ymax) { xmin = 0; xmax = width; } else { xmin = recalculateRect.xmin; xmax = recalculateRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.RecalculateCell(x, z, false, false); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return(null); } } for (int z = 0; z < depth; z++) { int xmin, xmax; if (z >= connectionRect.ymin && z < connectionRect.ymax) { xmin = 0; xmax = width; } else { xmin = connectionRect.xmin; xmax = connectionRect.xmax; } for (int x = xmin; x < xmax; x++) { graph.CalculateConnections(x, z); } counter += (xmax - xmin); if (counter > yieldEvery) { counter = 0; yield return(null); } } yield return(null); // Calculate all connections for the nodes along the boundary // of the graph, these always need to be updated /** \todo Optimize to not traverse all nodes in the graph, only those at the edges */ for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { if (x == 0 || z == 0 || x == width - 1 || z == depth - 1) { graph.CalculateConnections(x, z); } } } // We need to clear the Area if we are not using flood filling. // This will make pathfinding always work, but it may be slow // to figure out that no path exists if none does. // (of course, if there are regions between which no valid // paths exist, then the #floodFill field should not // be set to false anyway). if (!floodFill) { graph.GetNodes(node => node.Area = 1); } } else { // The calculation will only update approximately this number of // nodes per frame. This is used to keep CPU load per frame low int yieldEvery = Mathf.Max(depth * width / 20, 1000); int counter = 0; // Just update all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.RecalculateCell(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return(null); } } // Recalculate the connections of all nodes for (int z = 0; z < depth; z++) { for (int x = 0; x < width; x++) { graph.CalculateConnections(x, z); } counter += width; if (counter > yieldEvery) { counter = 0; yield return(null); } } } }
public void ToJSON() { if (string.IsNullOrEmpty(sctName)) { Debug.Log("Name your damn sector!"); return; } Sector sct = ScriptableObject.CreateInstance <Sector>(); sct.sectorName = sctName; sct.type = type; sct.backgroundColor = currentColor; LandPlatform platform = ScriptableObject.CreateInstance <LandPlatform>(); Vector3 firstTilePos = new Vector3 { x = center.x, y = center.y }; Vector3 lastTilePos = new Vector3 { x = center.x, y = center.y }; foreach (PlaceableObject ojs in objects) { if (ojs.type == ObjectTypes.Platform) { Vector3 tilePos = ojs.obj.transform.position; if (tilePos.x < firstTilePos.x) { firstTilePos.x = tilePos.x; } if (tilePos.y > firstTilePos.y) { firstTilePos.y = tilePos.y; } if (tilePos.x > lastTilePos.x) { lastTilePos.x = tilePos.x; } if (tilePos.y < lastTilePos.y) { lastTilePos.y = tilePos.y; } } } int columns = Mathf.CeilToInt(Mathf.Max(Mathf.Abs(firstTilePos.x - center.x) + 1, Mathf.Abs(lastTilePos.x - center.x) + 1) / tileSize) * 2; int rows = Mathf.CeilToInt(Mathf.Max(Mathf.Abs(firstTilePos.y - center.y) + 1, Mathf.Abs(lastTilePos.y - center.y) + 1) / tileSize) * 2; if (Mathf.RoundToInt(center.x - cursorOffset.x) % Mathf.RoundToInt(tileSize) == 0) { columns++; } if (Mathf.RoundToInt(center.y - cursorOffset.y) % Mathf.RoundToInt(tileSize) == 0) { rows++; } Vector2 offset = new Vector2 { x = center.x + -(columns - 1) * tileSize / 2, y = center.y + (rows - 1) * tileSize / 2 }; platform.rows = rows; platform.columns = columns; platform.tilemap = new int[rows * columns]; platform.rotations = new int[rows * columns]; platform.prefabs = new string[] { "4 Entry", "3 Entry", "2 Entry", "1 Entry", "0 Entry", "Junction" }; for (int i = 0; i < platform.tilemap.Length; i++) { platform.tilemap[i] = -1; } IntRect rect = new IntRect(); List <string> targetIDS = new List <string>(); List <Sector.LevelEntity> ents = new List <Sector.LevelEntity>(); rect.x = x; rect.y = y; rect.w = width; rect.h = height; sct.bounds = rect; int ID = 0; foreach (PlaceableObject oj in objects) { if (oj.type != ObjectTypes.Platform) { Sector.LevelEntity ent = new Sector.LevelEntity(); ent.ID = (ID++).ToString(); ent.faction = oj.faction; ent.position = oj.obj.transform.position; ent.assetID = oj.assetID; ent.vendingID = oj.vendingID; if (oj.isTarget) { targetIDS.Add(ent.ID); } ent.name = oj.obj.name; if (ent.assetID == "shellcore_blueprint") { targetIDS.Add(ent.ID); ent.blueprintJSON = oj.shellcoreJSON; } ents.Add(ent); } else if (oj.type == ObjectTypes.Platform) { int[] coordinates = new int[2]; coordinates[1] = Mathf.RoundToInt((oj.obj.transform.position.x - offset.x) / tileSize); coordinates[0] = -Mathf.RoundToInt((oj.obj.transform.position.y - offset.y) / tileSize); platform.tilemap[coordinates[1] + platform.columns * coordinates[0]] = oj.placeablesIndex; platform.rotations[coordinates[1] + platform.columns * coordinates[0]] = oj.rotation; } } sct.entities = ents.ToArray(); sct.targets = targetIDS.ToArray(); sct.backgroundColor = currentColor; SectorData data = new SectorData(); data.sectorjson = JsonUtility.ToJson(sct); data.platformjson = JsonUtility.ToJson(platform); string output = JsonUtility.ToJson(data); var sectorsDir = System.IO.Path.Combine(Application.streamingAssetsPath, "Sectors"); if (!System.IO.Directory.Exists(sectorsDir)) { System.IO.Directory.CreateDirectory(sectorsDir); } string path = System.IO.Path.Combine(sectorsDir, sct.sectorName); System.IO.File.WriteAllText(path, output); System.IO.Path.ChangeExtension(path, ".json"); mainMenu.ToggleActive(); successBox.ToggleActive(); Debug.Log("JSON written to location: " + path); }
public override int GenerateLandLayer(WorldGenerator worldGenerator, ILandChunk landChunk, IntRect area, int seed, int minAltitude, int maxAltitude) { return(seed); }
public override void Update(float frameTime) { if (_inventory == null && _playerManager != null) { //Gotta do this here because the vars are null in the constructor. if (_playerManager.ControlledEntity != null) { if (_playerManager.ControlledEntity.HasComponent(ComponentFamily.Inventory)) { var invComp = (InventoryComponent)_playerManager.ControlledEntity.GetComponent(ComponentFamily.Inventory); _inventory = new InventoryViewer(invComp, _userInterfaceManager, _resourceManager); } } } _comboBg.Position = new Vector2f(Position.X, Position.Y); var bounds = _comboBg.GetLocalBounds(); var equipBgPos = Position; _equipBg.Position = new Vector2f(Position.X, Position.Y); equipBgPos += new Vector2i((int)(bounds.Width / 2f - _equipBg.GetLocalBounds().Width / 2f), 40); _equipBg.Position = new Vector2f(equipBgPos.X, equipBgPos.Y); var comboClosePos = Position; comboClosePos += new Vector2i(264, 11); //Magic photoshop ruler numbers. _comboClose.Position = comboClosePos; _comboClose.Update(frameTime); var tabEquipPos = Position; tabEquipPos += new Vector2i(-26, 76); //Magic photoshop ruler numbers. _tabEquip.Position = tabEquipPos; _tabEquip.Color = _currentTab == 1 ? Color.White :_inactiveColor; _tabEquip.Update(frameTime); var tabHealthPos = tabEquipPos; tabHealthPos += new Vector2i(0, 3 + _tabEquip.ClientArea.Height); _tabHealth.Position = tabHealthPos; _tabHealth.Color = _currentTab == 2 ? Color.White : _inactiveColor; _tabHealth.Update(frameTime); ClientArea = new IntRect(Position.X, Position.Y, (int)bounds.Width, (int)bounds.Height); switch (_currentTab) { case (1): //Equip tab { #region Equip //Only set position for topmost 2 slots directly. Rest uses these to position themselves. var slotLeftStart = Position; slotLeftStart += new Vector2i(28, 40); _slotHead.Position = slotLeftStart; _slotHead.Update(frameTime); var slotRightStart = Position; slotRightStart += new Vector2i((int)(bounds.Width - _slotMask.ClientArea.Width - 28), 40); _slotMask.Position = slotRightStart; _slotMask.Update(frameTime); int vertSpacing = 6 + _slotHead.ClientArea.Height; //Left Side - head, eyes, outer, hands, feet slotLeftStart.Y += vertSpacing; _slotEyes.Position = slotLeftStart; _slotEyes.Update(frameTime); slotLeftStart.Y += vertSpacing; _slotOuter.Position = slotLeftStart; _slotOuter.Update(frameTime); slotLeftStart.Y += vertSpacing; _slotHands.Position = slotLeftStart; _slotHands.Update(frameTime); slotLeftStart.Y += vertSpacing; _slotFeet.Position = slotLeftStart; _slotFeet.Update(frameTime); //Right Side - mask, ears, inner, belt, back slotRightStart.Y += vertSpacing; _slotEars.Position = slotRightStart; _slotEars.Update(frameTime); slotRightStart.Y += vertSpacing; _slotInner.Position = slotRightStart; _slotInner.Update(frameTime); slotRightStart.Y += vertSpacing; _slotBelt.Position = slotRightStart; _slotBelt.Update(frameTime); slotRightStart.Y += vertSpacing; _slotBack.Position = slotRightStart; _slotBack.Update(frameTime); if (_inventory != null) { _inventory.Position = new Vector2i(Position.X + 12, Position.Y + 315); _inventory.Update(frameTime); } break; #endregion } case (2): //Health tab { #region Status var resLinePos = new Vector2i(Position.X + 35, Position.Y + 70); const int spacing = 8; _ResBlunt.Position = resLinePos; resLinePos.Y += _ResBlunt.ClientArea.Height + spacing; _ResBlunt.Update(frameTime); _ResPierce.Position = resLinePos; resLinePos.Y += _ResPierce.ClientArea.Height + spacing; _ResPierce.Update(frameTime); _ResSlash.Position = resLinePos; resLinePos.Y += _ResSlash.ClientArea.Height + spacing; _ResSlash.Update(frameTime); _ResBurn.Position = resLinePos; resLinePos.Y += _ResBurn.ClientArea.Height + spacing; _ResBurn.Update(frameTime); _ResFreeze.Position = resLinePos; resLinePos.Y += _ResFreeze.ClientArea.Height + spacing; _ResFreeze.Update(frameTime); _ResShock.Position = resLinePos; resLinePos.Y += _ResShock.ClientArea.Height + spacing; _ResShock.Update(frameTime); _ResTox.Position = resLinePos; _ResTox.Update(frameTime); break; #endregion } } //Needs to update even when its not on the crafting tab so it continues to count. }
public static bool Matches(this SadRogueRectangle self, IntRect other) => self.X == other.Left && self.Y == other.Top && self.Width == other.Width && self.Height == other.Height;
private void CutPoly(Int3[] verts, int[] tris, ref Int3[] outVertsArr, ref int[] outTrisArr, out int outVCount, out int outTCount, Int3[] extraShape, Int3 cuttingOffset, Bounds realBounds, TileHandler.CutMode mode = (TileHandler.CutMode) 3, int perturbate = 0) { if (verts.Length == 0 || tris.Length == 0) { outVCount = 0; outTCount = 0; outTrisArr = new int[0]; outVertsArr = new Int3[0]; return; } List <IntPoint> list = null; if (extraShape == null && (mode & TileHandler.CutMode.CutExtra) != (TileHandler.CutMode) 0) { throw new Exception("extraShape is null and the CutMode specifies that it should be used. Cannot use null shape."); } if ((mode & TileHandler.CutMode.CutExtra) != (TileHandler.CutMode) 0) { list = new List <IntPoint>(extraShape.Length); for (int i = 0; i < extraShape.Length; i++) { list.Add(new IntPoint((long)(extraShape[i].x + cuttingOffset.x), (long)(extraShape[i].z + cuttingOffset.z))); } } List <IntPoint> list2 = new List <IntPoint>(5); Dictionary <TriangulationPoint, int> dictionary = new Dictionary <TriangulationPoint, int>(); List <PolygonPoint> list3 = new List <PolygonPoint>(); IntRect b = new IntRect(verts[0].x, verts[0].z, verts[0].x, verts[0].z); for (int j = 0; j < verts.Length; j++) { b = b.ExpandToContain(verts[j].x, verts[j].z); } List <Int3> list4 = ListPool <Int3> .Claim(verts.Length * 2); List <int> list5 = ListPool <int> .Claim(tris.Length); PolyTree polyTree = new PolyTree(); List <List <IntPoint> > list6 = new List <List <IntPoint> >(); Stack <Polygon> stack = new Stack <Polygon>(); if (this.clipper == null) { this.clipper = new Clipper(0); } this.clipper.ReverseSolution = true; List <NavmeshCut> list7; if (mode == TileHandler.CutMode.CutExtra) { list7 = ListPool <NavmeshCut> .Claim(); } else { list7 = NavmeshCut.GetAllInRange(realBounds); } List <int> list8 = ListPool <int> .Claim(); List <IntRect> list9 = ListPool <IntRect> .Claim(); List <Int2> list10 = ListPool <Int2> .Claim(); List <List <IntPoint> > list11 = new List <List <IntPoint> >(); List <bool> list12 = ListPool <bool> .Claim(); List <bool> list13 = ListPool <bool> .Claim(); if (perturbate > 10) { Debug.LogError("Too many perturbations aborting : " + mode); Debug.Break(); outVCount = verts.Length; outTCount = tris.Length; outTrisArr = tris; outVertsArr = verts; return; } Random random = null; if (perturbate > 0) { random = new Random(); } for (int k = 0; k < list7.Count; k++) { Bounds bounds = list7[k].GetBounds(); Int3 @int = (Int3)bounds.min + cuttingOffset; Int3 int2 = (Int3)bounds.max + cuttingOffset; IntRect a = new IntRect(@int.x, @int.z, int2.x, int2.z); if (IntRect.Intersects(a, b)) { Int2 int3 = new Int2(0, 0); if (perturbate > 0) { int3.x = random.Next() % 6 * perturbate - 3 * perturbate; if (int3.x >= 0) { int3.x++; } int3.y = random.Next() % 6 * perturbate - 3 * perturbate; if (int3.y >= 0) { int3.y++; } } int count = list11.Count; list7[k].GetContour(list11); for (int l = count; l < list11.Count; l++) { List <IntPoint> list14 = list11[l]; if (list14.Count == 0) { Debug.LogError("Zero Length Contour"); list9.Add(default(IntRect)); list10.Add(new Int2(0, 0)); } else { IntRect item = new IntRect((int)list14[0].X + cuttingOffset.x, (int)list14[0].Y + cuttingOffset.y, (int)list14[0].X + cuttingOffset.x, (int)list14[0].Y + cuttingOffset.y); for (int m = 0; m < list14.Count; m++) { IntPoint value = list14[m]; value.X += (long)cuttingOffset.x; value.Y += (long)cuttingOffset.z; if (perturbate > 0) { value.X += (long)int3.x; value.Y += (long)int3.y; } list14[m] = value; item = item.ExpandToContain((int)value.X, (int)value.Y); } list10.Add(new Int2(@int.y, int2.y)); list9.Add(item); list12.Add(list7[k].isDual); list13.Add(list7[k].cutsAddedGeom); } } } } List <NavmeshAdd> allInRange = NavmeshAdd.GetAllInRange(realBounds); Int3[] array = verts; int[] array2 = tris; int num = -1; int n = -3; Int3[] array3 = null; Int3[] array4 = null; Int3 int4 = Int3.zero; if (allInRange.Count > 0) { array3 = new Int3[7]; array4 = new Int3[7]; int4 = (Int3)realBounds.extents; } for (;;) { n += 3; while (n >= array2.Length) { num++; n = 0; if (num >= allInRange.Count) { array = null; break; } if (array == verts) { array = null; } allInRange[num].GetMesh(cuttingOffset, ref array, out array2); } if (array == null) { break; } Int3 int5 = array[array2[n]]; Int3 int6 = array[array2[n + 1]]; Int3 int7 = array[array2[n + 2]]; IntRect a2 = new IntRect(int5.x, int5.z, int5.x, int5.z); a2 = a2.ExpandToContain(int6.x, int6.z); a2 = a2.ExpandToContain(int7.x, int7.z); int num2 = Math.Min(int5.y, Math.Min(int6.y, int7.y)); int num3 = Math.Max(int5.y, Math.Max(int6.y, int7.y)); list8.Clear(); bool flag = false; for (int num4 = 0; num4 < list11.Count; num4++) { int x = list10[num4].x; int y = list10[num4].y; if (IntRect.Intersects(a2, list9[num4]) && y >= num2 && x <= num3 && (list13[num4] || num == -1)) { Int3 int8 = int5; int8.y = x; Int3 int9 = int5; int9.y = y; list8.Add(num4); flag |= list12[num4]; } } if (list8.Count == 0 && (mode & TileHandler.CutMode.CutExtra) == (TileHandler.CutMode) 0 && (mode & TileHandler.CutMode.CutAll) != (TileHandler.CutMode) 0 && num == -1) { list5.Add(list4.Count); list5.Add(list4.Count + 1); list5.Add(list4.Count + 2); list4.Add(int5); list4.Add(int6); list4.Add(int7); } else { list2.Clear(); if (num == -1) { list2.Add(new IntPoint((long)int5.x, (long)int5.z)); list2.Add(new IntPoint((long)int6.x, (long)int6.z)); list2.Add(new IntPoint((long)int7.x, (long)int7.z)); } else { array3[0] = int5; array3[1] = int6; array3[2] = int7; int num5 = Utility.ClipPolygon(array3, 3, array4, 1, 0, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * int4.x, 0); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array3, num5, array4, 1, 0, 2); if (num5 == 0) { continue; } num5 = Utility.ClipPolygon(array4, num5, array3, -1, 2 * int4.z, 2); if (num5 == 0) { continue; } for (int num6 = 0; num6 < num5; num6++) { list2.Add(new IntPoint((long)array3[num6].x, (long)array3[num6].z)); } } dictionary.Clear(); Int3 int10 = int6 - int5; Int3 int11 = int7 - int5; Int3 int12 = int10; Int3 int13 = int11; int12.y = 0; int13.y = 0; for (int num7 = 0; num7 < 16; num7++) { if ((mode >> (num7 & 31) & TileHandler.CutMode.CutAll) != (TileHandler.CutMode) 0) { if (1 << num7 == 1) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num8 = 0; num8 < list8.Count; num8++) { this.clipper.AddPolygon(list11[list8[num8]], 1); } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 2) { if (!flag) { goto IL_1161; } this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); for (int num9 = 0; num9 < list8.Count; num9++) { if (list12[list8[num9]]) { this.clipper.AddPolygon(list11[list8[num9]], 1); } } list6.Clear(); this.clipper.Execute(0, list6, 0, 1); this.clipper.Clear(); for (int num10 = 0; num10 < list6.Count; num10++) { this.clipper.AddPolygon(list6[num10], (!Clipper.Orientation(list6[num10])) ? 0 : 1); } for (int num11 = 0; num11 < list8.Count; num11++) { if (!list12[list8[num11]]) { this.clipper.AddPolygon(list11[list8[num11]], 1); } } polyTree.Clear(); this.clipper.Execute(2, polyTree, 0, 1); } else if (1 << num7 == 4) { this.clipper.Clear(); this.clipper.AddPolygon(list2, 0); this.clipper.AddPolygon(list, 1); polyTree.Clear(); this.clipper.Execute(0, polyTree, 0, 1); } for (int num12 = 0; num12 < polyTree.ChildCount; num12++) { PolyNode polyNode = polyTree.Childs[num12]; List <IntPoint> contour = polyNode.Contour; List <PolyNode> childs = polyNode.Childs; if (childs.Count == 0 && contour.Count == 3 && num == -1) { for (int num13 = 0; num13 < contour.Count; num13++) { Int3 item2 = new Int3((int)contour[num13].X, 0, (int)contour[num13].Y); double num14 = (double)(int6.z - int7.z) * (double)(int5.x - int7.x) + (double)(int7.x - int6.x) * (double)(int5.z - int7.z); if (num14 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num15 = ((double)(int6.z - int7.z) * (double)(item2.x - int7.x) + (double)(int7.x - int6.x) * (double)(item2.z - int7.z)) / num14; double num16 = ((double)(int7.z - int5.z) * (double)(item2.x - int7.x) + (double)(int5.x - int7.x) * (double)(item2.z - int7.z)) / num14; item2.y = (int)Math.Round(num15 * (double)int5.y + num16 * (double)int6.y + (1.0 - num15 - num16) * (double)int7.y); list5.Add(list4.Count); list4.Add(item2); } } } else { Polygon polygon = null; int num17 = -1; for (List <IntPoint> list15 = contour; list15 != null; list15 = ((num17 >= childs.Count) ? null : childs[num17].Contour)) { list3.Clear(); for (int num18 = 0; num18 < list15.Count; num18++) { PolygonPoint polygonPoint = new PolygonPoint((double)list15[num18].X, (double)list15[num18].Y); list3.Add(polygonPoint); Int3 item3 = new Int3((int)list15[num18].X, 0, (int)list15[num18].Y); double num19 = (double)(int6.z - int7.z) * (double)(int5.x - int7.x) + (double)(int7.x - int6.x) * (double)(int5.z - int7.z); if (num19 == 0.0) { Debug.LogWarning("Degenerate triangle"); } else { double num20 = ((double)(int6.z - int7.z) * (double)(item3.x - int7.x) + (double)(int7.x - int6.x) * (double)(item3.z - int7.z)) / num19; double num21 = ((double)(int7.z - int5.z) * (double)(item3.x - int7.x) + (double)(int5.x - int7.x) * (double)(item3.z - int7.z)) / num19; item3.y = (int)Math.Round(num20 * (double)int5.y + num21 * (double)int6.y + (1.0 - num20 - num21) * (double)int7.y); dictionary[polygonPoint] = list4.Count; list4.Add(item3); } } Polygon polygon2; if (stack.Count > 0) { polygon2 = stack.Pop(); polygon2.AddPoints(list3); } else { polygon2 = new Polygon(list3); } if (polygon == null) { polygon = polygon2; } else { polygon.AddHole(polygon2); } num17++; } try { P2T.Triangulate(polygon); } catch (PointOnEdgeException) { Debug.LogWarning(string.Concat(new object[] { "PointOnEdgeException, perturbating vertices slightly ( at ", num7, " in ", mode, ")" })); this.CutPoly(verts, tris, ref outVertsArr, ref outTrisArr, out outVCount, out outTCount, extraShape, cuttingOffset, realBounds, mode, perturbate + 1); return; } for (int num22 = 0; num22 < polygon.Triangles.Count; num22++) { DelaunayTriangle delaunayTriangle = polygon.Triangles[num22]; list5.Add(dictionary[delaunayTriangle.Points._0]); list5.Add(dictionary[delaunayTriangle.Points._1]); list5.Add(dictionary[delaunayTriangle.Points._2]); } if (polygon.Holes != null) { for (int num23 = 0; num23 < polygon.Holes.Count; num23++) { polygon.Holes[num23].Points.Clear(); polygon.Holes[num23].ClearTriangles(); if (polygon.Holes[num23].Holes != null) { polygon.Holes[num23].Holes.Clear(); } stack.Push(polygon.Holes[num23]); } } polygon.ClearTriangles(); if (polygon.Holes != null) { polygon.Holes.Clear(); } polygon.Points.Clear(); stack.Push(polygon); } } } IL_1161 :; } } } Dictionary <Int3, int> dictionary2 = this.cached_Int3_int_dict; dictionary2.Clear(); if (this.cached_int_array.Length < list4.Count) { this.cached_int_array = new int[Math.Max(this.cached_int_array.Length * 2, list4.Count)]; } int[] array5 = this.cached_int_array; int num24 = 0; for (int num25 = 0; num25 < list4.Count; num25++) { int num26; if (!dictionary2.TryGetValue(list4[num25], out num26)) { dictionary2.Add(list4[num25], num24); array5[num25] = num24; list4[num24] = list4[num25]; num24++; } else { array5[num25] = num26; } } outTCount = list5.Count; if (outTrisArr == null || outTrisArr.Length < outTCount) { outTrisArr = new int[outTCount]; } for (int num27 = 0; num27 < outTCount; num27++) { outTrisArr[num27] = array5[list5[num27]]; } outVCount = num24; if (outVertsArr == null || outVertsArr.Length < outVCount) { outVertsArr = new Int3[outVCount]; } for (int num28 = 0; num28 < outVCount; num28++) { outVertsArr[num28] = list4[num28]; } for (int num29 = 0; num29 < list7.Count; num29++) { list7[num29].UsedForCut(); } ListPool <Int3> .Release(list4); ListPool <int> .Release(list5); ListPool <int> .Release(list8); ListPool <Int2> .Release(list10); ListPool <bool> .Release(list12); ListPool <bool> .Release(list13); ListPool <IntRect> .Release(list9); ListPool <NavmeshCut> .Release(list7); }
private void RenderCell(IFastGridCell cell, IntRect rect, Color?selectedTextColor, Color bgColor, FastGridCellAddress cellAddr) { bool isHoverCell = !cellAddr.IsEmpty && cellAddr == _mouseOverCell; if (isHoverCell) { _mouseOverCellIsTrimmed = false; CurrentCellActiveRegions.Clear(); CurrentHoverRegion = null; } if (cell == null) { return; } var rectContent = GetContentRect(rect); _drawBuffer.DrawRectangle(rect, GridLineColor); _drawBuffer.FillRectangle(rect.GrowSymmetrical(-1, -1), bgColor); int count = cell.BlockCount; int rightCount = cell.RightAlignBlockCount; int leftCount = count - rightCount; int leftPos = rectContent.Left; int rightPos = rectContent.Right; for (int i = count - 1; i >= count - rightCount; i--) { var block = cell.GetBlock(i); if (block == null) { continue; } if (i < count - 1) { rightPos -= BlockPadding; } int blockWi = RenderBlock(leftPos, rightPos, selectedTextColor, bgColor, rectContent, block, cellAddr, false, isHoverCell); rightPos -= blockWi; } for (int i = 0; i < leftCount && leftPos < rightPos; i++) { var block = cell.GetBlock(i); if (block == null) { continue; } if (i > 0) { leftPos += BlockPadding; } int blockWi = RenderBlock(leftPos, rightPos, selectedTextColor, bgColor, rectContent, block, cellAddr, true, isHoverCell); leftPos += blockWi; } switch (cell.Decoration) { case CellDecoration.StrikeOutHorizontal: _drawBuffer.DrawLine(rect.Left, rect.Top + rect.Height / 2, rect.Right, rect.Top + rect.Height / 2, cell.DecorationColor ?? Colors.Black); break; } if (isHoverCell) { _mouseOverCellIsTrimmed = leftPos > rightPos; } }
private int RenderBlock(int leftPos, int rightPos, Color?selectedTextColor, Color bgColor, IntRect rectContent, IFastGridCellBlock block, FastGridCellAddress cellAddr, bool leftAlign, bool isHoverCell) { bool renderBlock = true; if (block.MouseHoverBehaviour == MouseHoverBehaviours.HideWhenMouseOut && !isHoverCell) { renderBlock = false; } int width = 0, top = 0, height = 0; switch (block.BlockType) { case FastGridBlockType.Text: var font = GetFont(block.IsBold, block.IsItalic); int textHeight = font.GetTextHeight(block.TextData); width = font.GetTextWidth(block.TextData, _columnSizes.MaxSize); height = textHeight; top = rectContent.Top + (int)Math.Round(rectContent.Height / 2.0 - textHeight / 2.0); break; case FastGridBlockType.Image: top = rectContent.Top + (int)Math.Round(rectContent.Height / 2.0 - block.ImageHeight / 2.0); height = block.ImageHeight; width = block.ImageWidth; break; } if (renderBlock && block.CommandParameter != null) { var activeRect = new IntRect(new IntPoint(leftAlign ? leftPos : rightPos - width, top), new IntSize(width, height)).GrowSymmetrical(1, 1); var region = new ActiveRegion { CommandParameter = block.CommandParameter, Rect = activeRect, Tooltip = block.ToolTip, }; CurrentCellActiveRegions.Add(region); if (_mouseCursorPoint.HasValue && activeRect.Contains(_mouseCursorPoint.Value)) { _drawBuffer.FillRectangle(activeRect, ActiveRegionHoverFillColor); CurrentHoverRegion = region; } bool renderRectangle = true; if (block.MouseHoverBehaviour == MouseHoverBehaviours.HideButtonWhenMouseOut && !isHoverCell) { renderRectangle = false; } if (renderRectangle) { _drawBuffer.DrawRectangle(activeRect, ActiveRegionFrameColor); } } switch (block.BlockType) { case FastGridBlockType.Text: if (renderBlock) { var textOrigin = new IntPoint(leftAlign ? leftPos : rightPos - width, top); var font = GetFont(block.IsBold, block.IsItalic); _drawBuffer.DrawString(textOrigin.X, textOrigin.Y, rectContent, selectedTextColor ?? block.FontColor ?? CellFontColor, UseClearType ? bgColor : (Color?)null, font, block.TextData); } break; case FastGridBlockType.Image: if (renderBlock) { var imgOrigin = new IntPoint(leftAlign ? leftPos : rightPos - block.ImageWidth, top); var image = GetImage(block.ImageSource); _drawBuffer.Blit(new Point(imgOrigin.X, imgOrigin.Y), image.Bitmap, new Rect(0, 0, block.ImageWidth, block.ImageHeight), image.KeyColor, image.BlendMode); } break; } return(width); }