public void Load(string Filename) { List levelLisp = Util.Load(Filename, "supertux-level"); Properties props = new Properties(levelLisp); int version = 1; props.Get("version", ref version); if(version == 1) throw new Exception("Old Level format not supported"); if(version > 2) Console.WriteLine("Warning: Level Format newer than application"); props.Get("name", ref Name); props.Get("author", ref Author); LispIterator iter = new LispIterator(levelLisp); while(iter.MoveNext()) { switch(iter.Key) { case "sector": Sector sector = new Sector(); sector.Parse(this, iter.List); break; default: Console.WriteLine("Ignoring unknown tag '" + iter.Key + "' in level"); break; } } }
public static void CheckIds(Application application, Sector sector, bool AlertGood) { System.Text.StringBuilder sb = new System.Text.StringBuilder("These tilemaps have bad ids in sector " + sector.Name + ":"); List<int> invalidtiles; // Any bad found yet? bool bad = false; foreach (Tilemap tilemap in sector.GetObjects(typeof(Tilemap))) { invalidtiles = CheckIds(tilemap, application.CurrentLevel.Tileset); if (invalidtiles.Count != 0) { bad = true; if (String.IsNullOrEmpty(tilemap.Name)) sb.Append(Environment.NewLine + "Tilemap (" + tilemap.Layer + ")"); else sb.Append(Environment.NewLine + tilemap.Name + " (" + tilemap.Layer + ")"); } } MessageType msgtype; string message; if (! bad) { if (! AlertGood) return; msgtype = MessageType.Info; message = "No invalid tile ids in any tilemap in sector " + sector.Name + "."; } else { msgtype = MessageType.Warning; message = sb.ToString(); } MessageDialog md = new MessageDialog(null, DialogFlags.DestroyWithParent, msgtype, ButtonsType.Close, message); md.Run(); md.Destroy(); }
public Sector Create(Block blockArg, uint sector) { uint block = blockArg.BlockIndex; long totalSectors = blockArg.SectorCount; if (sector > totalSectors) { string message = String.Format("TotalSectors: {0}, Requested Sector:{1}", totalSectors, sector); throw new ArgumentOutOfRangeException("sector", message); } if (!blockFactory.HasData(block)) { return CreateEmptySector(block, sector); } long currentAddress = blockFactory.GetBlockAddress(block); vhdFile.DataReader.SetPosition(currentAddress + (int)VhdConstants.VHD_SECTOR_LENGTH * sector); var result = new Sector { BlockIndex = block, SectorIndex = sector, GlobalSectorIndex = this.blockFactory.GetBlockSize() * block + sector, Data = vhdFile.DataReader.ReadBytes((int)VhdConstants.VHD_SECTOR_LENGTH) }; return result; }
private void ObjectsChanged(Sector sector, IGameObject Object) { if((Object is IObject) || (Object is Tilemap)) return; UpdateList(); }
public ResizeDialog(Sector sector, Tilemap tilemap) { this.sector = sector; this.tilemap = tilemap; Glade.XML gxml = new Glade.XML("editor.glade", "resizeDialog"); gxml.Autoconnect(this); if (resizeDialog == null || XOffsetEntry == null || YOffsetEntry == null || WidthEntry == null || HeightEntry == null) { throw new Exception("Couldn't load resize Dialog"); } if (tilemap == null) { XOffsetEntry.Text = "0"; YOffsetEntry.Text = "0"; WidthEntry.Text = sector.Width.ToString(); HeightEntry.Text = sector.Height.ToString(); undoTitleBase = "Sector \"" + sector.Name + "\""; } else { XOffsetEntry.Text = "0"; YOffsetEntry.Text = "0"; WidthEntry.Text = tilemap.Width.ToString(); HeightEntry.Text = tilemap.Height.ToString(); undoTitleBase = "Tilemap \"" + tilemap.Name + "\""; } resizeDialog.Title += " " + undoTitleBase; resizeDialog.Icon = EditorStock.WindowIcon; resizeDialog.ShowAll(); }
public void SpawnPeople(Sector sector) { int numPeopleOptions = mPeoplePrefabs.Length; if(numPeopleOptions <= 0) { return; } int numSlots = mSpawnPositions.Length; int forceSpawnIndex = Random.Range(0, numSlots); // ensure that at least one person is on this boat for(int i = 0; i < numSlots; ++i) { if(i != forceSpawnIndex && Random.value > 0.6f) { continue; } int leftOrRight = (Random.value > 0.5f)?1:-1; float range = mBuoyancy.mEndsOffset; Vector3 personPos = mSpawnPositions[i].position; GameObject prefab = mPeoplePrefabs[Random.Range(0, numPeopleOptions)]; sector.SpawnEntity(prefab, personPos, transform.up, Vector3.forward*leftOrRight); } }
public override Sector Parse(TextReader reader) { Sector sector = new Sector(); StringBuilder accum = new StringBuilder(); while (true) { string line = reader.ReadLine(); if (line == null) break; if (Regex.IsMatch(line, @"^\s*$")) continue; if (Regex.IsMatch(line, @"^\s*#")) continue; if (Char.IsWhiteSpace(line[0])) { accum.Append(" "); accum.Append(Regex.Replace(line, @"^\s+", "")); continue; } if (accum.Length > 0) Apply(accum.ToString(), sector); accum.Clear(); accum.Append(line); } if (accum.Length > 0) { Apply(accum.ToString(), sector); } return sector; }
//Check if a spot has access to the exit of a track. public bool CanBeExited(Sector sec) { Track strck = null; int idx=-1; foreach(Track trck in Tracks) { idx = trck.Sectors.FindIndex(p => p.Id == sec.Id); if(idx != -1) { strck = trck; break; } } if (strck == null || idx == -1) //Invalid sector (track could not be found) return false; if (idx == strck.Sectors.Count) return true; for(int i=idx+1; i<strck.Sectors.Count; i++) //Check if any of the above laying sectors are occupied { if (strck.Sectors[i].Blocked) return false; } return true; }
public ObjectCreationTool(Application application, Sector sector, Type objectType, Sprite Icon) { this.application = application; this.sector = sector; this.objectType = objectType; this.Icon = Icon; }
public Ship(string name, Ships ships, Sector sector, SectorPosition sectorPosition, Vector3 angle, Tile tile) { this.name = name; this.ships = ships; this.sector = sector; this.sectorPosition = sectorPosition; this.angle = angle; this.tilesList.Add(tile); }
internal void Add( Sector sector ) { sector.PhysicsSpace = world; lock ( active_sectors ) { active_sectors.Add( sector ); } world.Add( sector.grid ); }
/// <summary> /// Initializes a new instance of the <see cref="Tram"/> class. /// </summary> /// <param name="id">The database ID of the tram.</param> /// <param name="number">The identification number (string) of the tram.</param> /// <param name="state">The current status of the tram.</param> /// <param name="tramType">The tram type of the tram.</param> /// <param name="usedForEducationalPurposes">Whether the tram is used for lessons or not.</param> /// <param name="sector">The sector on which the tram is standing.</param> public Tram(int id, string number, State state, TramType tramType, bool usedForEducationalPurposes, Sector sector) : this(id) { this.Number = number; this.State = state; this.TramType = tramType; this.UsedForEducationalPurposes = usedForEducationalPurposes; this.Sector = sector; }
public static Sector Parse(SqlDataReader dr) { Sector Sector = new Sector(); Sector.Id = Convert.ToInt32(dr["Id"]); Sector.Name = Convert.ToString(dr["Name"]); return Sector; }
//acceleration or power/weight //turn rates //any other parts that aren't in cubes public Ship() { name = null; ships = null; sector = new Sector(); sectorPosition = new SectorPosition(); ObjectVelocity velocity = new ObjectVelocity(); List<Tile> tiles = new List<Tile>(); }
public Player(GameObject playerObject) { this.playerObject = playerObject; sector = new Sector(); sectorPosition = new SectorPosition(); Vector3 angle = new Vector3(0,0,0); ObjectVelocity velocity = new ObjectVelocity(); Vector3 angularVelocity = new Vector3(0,0,0); updateScriptRef(); }
public DetalleDiagramacion(Deporte deporte, int item, string dia_semana, Sector sector, Horario hora_desde, Horario hora_hasta, Personal profesor) { Deporte = deporte; Item = item; Dia_semana = dia_semana; Sector = sector; Hora_desde = hora_desde; Hora_hasta = hora_hasta; Profesor = profesor; }
private void CreateTabList() { foreach(Sector sector in level.Sectors) { SectorRenderer Renderer = new SectorRenderer(level, sector); Renderer.ShowAll(); AppendPage(Renderer, new Label(sector.Name)); } if(this.sector == null && level.Sectors.Count > 0) this.sector = level.Sectors[0]; }
public static void Edit(Sector pSector) { SqlCommand SQLCmd = new SqlCommand(); SQLCmd.CommandType = CommandType.StoredProcedure; SQLCmd.CommandText = "UpdateSector"; SQLCmd.Parameters.Add("Id", SqlDbType.Int).Value = pSector.Id; SQLCmd.Parameters.Add("ClientId", SqlDbType.Int).Value = pSector.ClientId; SQLCmd.Parameters.Add("Name", SqlDbType.NVarChar, 255).Value = pSector.Name; BaseDataAccess.OpenConnection(SQLCmd); BaseDataAccess.ExecuteNonSelect(SQLCmd); BaseDataAccess.CloseConnection(); }
public SectorRenderer(Application application, Level level, Sector sector) { this.application = application; this.level = level; this.sector = sector; Layer layer = new Layer(); foreach(IDrawableLayer IDrawableLayer in sector.GetObjects(typeof(IDrawableLayer))) { Node node = IDrawableLayer.GetSceneGraphNode(); if (IDrawableLayer is Tilemap) //Special handling for tilemaps node = new TilemapNode((Tilemap) IDrawableLayer, level.Tileset); ColorNode colorNode = new ColorNode(node, new Color(1f, 1f, 1f, 1f), true); layer.Add(IDrawableLayer.Layer, colorNode); colors[IDrawableLayer] = colorNode; } objectsNode = new NodeWithChilds(); objectsColorNode = new ColorNode(objectsNode, new Color(1f, 1f, 1f, 1f)); layer.Add(1, objectsColorNode); foreach(IObject Object in sector.GetObjects(typeof(IObject))) { Node node = Object.GetSceneGraphNode(); if(node != null) objectsNode.AddChild(node); } // fill remaining place with one color sectorFill = new SceneGraph.Rectangle(); sectorFill.Fill = true; ColorNode color = new ColorNode(sectorFill, new Drawing.Color(0.4f, 0.3f, 0.4f)); layer.Add(-10000, color); // draw border around sector... sectorBBox = new SceneGraph.Rectangle(); sectorBBox.Fill = false; color = new ColorNode(sectorBBox, new Drawing.Color(1, 0.3f, 1)); layer.Add(1000, color); // draw border around selected layer... color = new ColorNode(new TilemapBorder(application), new Drawing.Color(1, 1, 0)); layer.Add(1001, color); OnSizeChanged(sector); this.SceneGraphRoot = layer; sector.ObjectAdded += OnObjectAdded; sector.ObjectRemoved += OnObjectRemoved; sector.SizeChanged += OnSizeChanged; application.TilemapChanged += OnTilemapChanged; //TODO: It should be possible to iterate over all (currently present?) types that implements ILayer.. How? FieldOrProperty.AnyFieldChanged += OnFieldChanged; }
public SectorRenderer(Level level, Sector sector) { this.level = level; Layer layer = new Layer(); backgroundNode = new NodeWithChilds(); backgroundColorNode = new ColorNode(backgroundNode, new Color(1f, 1f, 1f, 1f)); layer.Add(-900, backgroundColorNode); foreach(Background background in sector.GetObjects(typeof(Background))) { Node node = background.GetSceneGraphNode(); if(node == null) continue; backgroundNode.AddChild(node); } foreach(Tilemap tilemap in sector.GetObjects(typeof(Tilemap))) { Node node = new TilemapNode(tilemap, level.Tileset); ColorNode colorNode = new ColorNode(node, new Color(1f, 1f, 1f, 1f)); layer.Add(tilemap.ZPos, colorNode); colors[tilemap] = colorNode; } objectsNode = new NodeWithChilds(); objectsColorNode = new ColorNode(objectsNode, new Color(1f, 1f, 1f, 1f)); layer.Add(1, objectsColorNode); foreach(IObject Object in sector.GetObjects(typeof(IObject))) { Node node = Object.GetSceneGraphNode(); if(node != null) objectsNode.AddChild(node); } // draw border around sector... sectorFill = new SceneGraph.Rectangle(); sectorFill.Fill = true; ColorNode color = new ColorNode(sectorFill, new Drawing.Color(0.4f, 0.3f, 0.4f)); layer.Add(-10000, color); sectorBBox = new SceneGraph.Rectangle(); sectorBBox.Fill = false; color = new ColorNode(sectorBBox, new Drawing.Color(1, 0.3f, 1)); layer.Add(1000, color); OnSizeChanged(sector); this.SceneGraphRoot = layer; sector.ObjectAdded += OnObjectAdded; sector.ObjectRemoved += OnObjectRemoved; sector.SizeChanged += OnSizeChanged; Drag.DestSet(this, DestDefaults.All, ObjectListWidget.DragTargetEntries, Gdk.DragAction.Default); DragMotion += OnDragMotion; }
public Ship(string name, Ships ships, Sector sector, SectorPosition sectorPosition, Vector3 angle, List<Tile> tileList) { this.name = name; this.ships = ships; this.sector = sector; this.sectorPosition = sectorPosition; this.angle = angle; foreach (Tile tile in tileList) { this.tilesList.Add(tile); tile.ship = this; } }
public static Block GetBlockAt(Vector3 position, Sector sector = null) { Block result = null; // Get the chunk. Chunk chunk = GetChunkAt(position, sector); if (chunk != null) { // Modulo the player's position by the measure of blocks in a chunk to get their position within their chunk. result = chunk.blocks[(int)position.x % Chunk.WIDTH, (int)position.y % Chunk.HEIGHT, (int)position.z % Chunk.DEPTH]; } return result; }
public Sector CreateEmptySector(uint block, uint sector) { var buffer = new byte[((int)VhdConstants.VHD_SECTOR_LENGTH)]; Array.Clear(buffer, 0, buffer.Length); var emptySector = new Sector { BlockIndex = block, SectorIndex = sector, GlobalSectorIndex = this.blockFactory.GetBlockSize() * block + sector, Data = buffer }; return emptySector; }
public void Awake() { sInstance = this; mSectorSize = (Mathf.PI*2.0f)/mNumSectors; mSectors = new Sector[mNumSectors]; for(int i = 0; i < mNumSectors; ++i) { mSectors[i] = new Sector(this, i); } mWaveManager = FindObjectOfType<WaveManager>(); }
public void PopulateSector(Sector SpecifiedSector) { CurrentSector = SpecifiedSector; for (int i = 0; i < CurrentSector.Planets.Count; i++) { GameObject NewPlanet = new GameObject("Planet " + i.ToString() + ":" + CurrentSector.Planets[i].Name); PlanetBehaviour PBehaviour = NewPlanet.AddComponent<PlanetBehaviour>(); PBehaviour.Initialize(CurrentSector.Planets[i]); NewPlanet.transform.position = new Vector3(CurrentSector.Planets[i].Coordinates.x, 0f, CurrentSector.Planets[i].Coordinates.y); NewPlanet.transform.parent = gameObject.transform; } }
void Start() { Instance = this; star = GameObject.Instantiate(starPrefab) as GameObject; Transform starBody = star.transform.Find("Body"); starBody.renderer.sharedMaterial = starMaterials[UnityEngine.Random.Range(0, starMaterials.Length)]; List<int> unusedPlanetMaterialIds = new List<int>(); for (int i = 0; i < planetMaterials.Length; i++) unusedPlanetMaterialIds.Add(i); planets = new List<Planet>(); int numPlanets = 8; numPlanets = Mathf.Min (numPlanets, planetMaterials.Length); for (int i = 0; i < numPlanets; i++) { bool hasRing = (UnityEngine.Random.Range(0, 4) == 0); GameObject planet = GameObject.Instantiate(hasRing ? ringPlanetPrefab : planetPrefab) as GameObject; float radius = UnityEngine.Random.Range(i + 1.0f, i + 1.5f) * 2000.0f; float angle = UnityEngine.Random.Range(0.0f, Mathf.PI * 2.0f); Vector3 scale = planet.transform.localScale; planet.transform.localScale = scale * (UnityEngine.Random.Range(0.5f, 2.0f)); planet.transform.parent = star.transform; Transform planetBody = planet.transform.Find("Body"); int pos = UnityEngine.Random.Range(0, unusedPlanetMaterialIds.Count); planetBody.renderer.sharedMaterial = planetMaterials[unusedPlanetMaterialIds[pos]]; unusedPlanetMaterialIds.RemoveAt(pos); if (hasRing) { Transform planetRing = planetBody.Find("Ring"); planetRing.renderer.sharedMaterial = planetRingMaterials[UnityEngine.Random.Range(0, planetRingMaterials.Length)]; } planetBody.localPosition = new Vector3(Mathf.Cos(angle) * radius, 0.0f, Mathf.Sin(angle) * radius); Planet p = planet.GetComponent<Planet>(); //p.orbitSpeed = 360.0f * UnityEngine.Random.Range(1.0f / (i * 4.0f + 2.5f), 1.0f / (i * 4.0f + 5.0f)) * (UnityEngine.Random.Range(0, 2) == 0 ? 1.0f : -1.0f) / 100.0f; //p.rotationSpeed = UnityEngine.Random.Range(-180.0f, 180.0f) / 50.0f; planets.Add(p); } }
public static int Create(Sector pSector) { SqlCommand SQLCmd = new SqlCommand(); SQLCmd.CommandType = CommandType.StoredProcedure; SQLCmd.CommandText = "CreateSector"; SQLCmd.Parameters.Add("ClientId", SqlDbType.Int).Value = pSector.ClientId; SQLCmd.Parameters.Add("Name", SqlDbType.NVarChar, 255).Value = pSector.Name; SQLCmd.Parameters.Add("Id", SqlDbType.Int).Direction = ParameterDirection.Output; BaseDataAccess.OpenConnection(SQLCmd); BaseDataAccess.ExecuteNonSelect(SQLCmd); BaseDataAccess.CloseConnection(); return Convert.ToInt32(SQLCmd.Parameters["Id"].Value); }
/// <summary> /// This function save sthe sector /// </summary> private void SaveSector() { var sector = new Sector { SectorText = txtSector.Text, Published = rbtnActiveYes.Checked }; var sectorId = new Sectors().AddEditSector(sector); //clear text box and load sectors txtSector.Text = ""; rbtnActiveYes.Checked = true; rbtnActiveNo.Checked = false; //load sectros LoadSectors(); }
// Use this for initialization void Start () { sector = Sector.Instance; state = State.TRAVELLING; targetPlanetId = UnityEngine.Random.Range(0, 8); forward = Vector3.right; speed = 0.0f; foreach (Thruster thruster in thrusters) { thruster.StartThruster(); } }
public DetalleDiagramacion(Diagramacion diagramacion, int item, Dia dia_semana, Sector sector, Horario hora_desde, Horario hora_hasta, Personal profesor, bool lugar_confirmado, bool horario_confirmado, bool profesor_confirmado) { Diagramacion = diagramacion; Item = item; Dia_semana = dia_semana; Sector = sector; Hora_desde = hora_desde; Hora_hasta = hora_hasta; Profesor = profesor; Lugar_confirmado = lugar_confirmado; Horario_confirmado = horario_confirmado; Profesor_confirmado = profesor_confirmado; }
//mxd. Auto-align texture offsets public virtual void OnTextureAlign(bool alignx, bool aligny) { if (!General.Map.UDMF) { return; } //create undo string rest; if (alignx && aligny) { rest = "(X and Y)"; } else if (alignx) { rest = "(X)"; } else { rest = "(Y)"; } mode.CreateUndo("Auto-align textures " + rest); mode.SetActionResult("Auto-aligned textures " + rest + "."); //get selection List <VisualGeometry> selection = mode.GetSelectedSurfaces(); //align textures on slopes foreach (VisualGeometry vg in selection) { if (vg.GeometryType == VisualGeometryType.FLOOR || vg.GeometryType == VisualGeometryType.CEILING) { // Might be a 3D floor, so we might need another VisualGeometry VisualGeometry realvg; if (vg.GeometryType == VisualGeometryType.FLOOR) { if (((VisualFloor)vg).ExtraFloor == null) { realvg = vg; } else { Sector s = ((VisualFloor)vg).GetControlSector(); BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(s); realvg = vs.Floor; } } else { if (((VisualCeiling)vg).ExtraFloor == null) { realvg = vg; } else { Sector s = ((VisualCeiling)vg).GetControlSector(); BaseVisualSector vs = (BaseVisualSector)mode.GetVisualSector(s); realvg = vs.Ceiling; } } if (realvg.GeometryType == VisualGeometryType.FLOOR) { ((VisualFloor)realvg).AlignTexture(alignx, aligny); } else { ((VisualCeiling)realvg).AlignTexture(alignx, aligny); } realvg.Sector.Sector.UpdateNeeded = true; realvg.Sector.Sector.UpdateCache(); } } // Map is changed General.Map.Map.Update(); General.Map.IsChanged = true; General.Interface.RefreshInfo(); }
public SectorItemViewModel(Sector sector) { this.model = sector; }
//mxd protected void AlignTextureToClosestLine(bool alignx, bool aligny) { if (!(mode.HighlightedObject is BaseVisualSector)) { return; } // Do we need to align this? (and also grab texture scale while we are at it) double scaleX, scaleY; bool isFloor = (geometrytype == VisualGeometryType.FLOOR); if (mode.HighlightedTarget is VisualFloor) { Sector target; VisualFloor vf = (VisualFloor)mode.HighlightedTarget; // Use the control sector if the floor belongs to a 3D floor if (vf.ExtraFloor == null) { target = vf.Sector.Sector; } else { target = vf.GetControlSector(); } // Check texture if (target.FloorTexture != (isFloor ? Sector.Sector.FloorTexture : Sector.Sector.CeilTexture)) { return; } scaleX = target.Fields.GetValue("xscalefloor", 1.0); scaleY = target.Fields.GetValue("yscalefloor", 1.0); } else { Sector target; VisualCeiling vc = (VisualCeiling)mode.HighlightedTarget; // Use the control sector if the ceiling belongs to a 3D floor if (vc.ExtraFloor == null) { target = vc.Sector.Sector; } else { target = vc.GetControlSector(); } // Check texture if (target.CeilTexture != (isFloor ? Sector.Sector.FloorTexture : Sector.Sector.CeilTexture)) { return; } scaleX = target.Fields.GetValue("xscaleceiling", 1.0); scaleY = target.Fields.GetValue("yscaleceiling", 1.0); } //find a linedef to align to Vector2D hitpos = mode.GetHitPosition(); if (!hitpos.IsFinite()) { return; } //align to line of highlighted sector, which is closest to hitpos Sector highlightedSector = ((BaseVisualSector)mode.HighlightedObject).Sector; List <Linedef> lines = new List <Linedef>(); foreach (Sidedef side in highlightedSector.Sidedefs) { lines.Add(side.Line); } Linedef targetLine = MapSet.NearestLinedef(lines, hitpos); if (targetLine == null) { return; } bool isFront = targetLine.SideOfLine(hitpos) > 0; Sector.Sector.Fields.BeforeFieldsChange(); //find an angle to rotate texture double sourceAngle = Math.Round(General.ClampAngle(isFront ? -Angle2D.RadToDeg(targetLine.Angle) + 90 : -Angle2D.RadToDeg(targetLine.Angle) - 90), 1); if (!isFront) { sourceAngle = General.ClampAngle(sourceAngle + 180); } //update angle UniFields.SetFloat(Sector.Sector.Fields, (isFloor ? "rotationfloor" : "rotationceiling"), sourceAngle, 0.0); // Scale texture if it's a slope and the appropriate option is set if (level.plane.Normal.z != 1.0 && BuilderPlug.Me.ScaleTexturesOnSlopes != 2) { Vector2D basescale = new Vector2D(1.0, 1.0); // User wants to use the current scale as a base? if (BuilderPlug.Me.ScaleTexturesOnSlopes == 1) { basescale.x = scaleX; basescale.y = scaleY; } // Create a unit vector of the direction of the target line in 3D space Vector3D targetlinevector = new Line3D(new Vector3D(targetLine.Start.Position, level.plane.GetZ(targetLine.Start.Position)), new Vector3D(targetLine.End.Position, level.plane.GetZ(targetLine.End.Position))).GetDelta().GetNormal(); // Get a perpendicular vector of the target line in 3D space. This is used to get the slope angle relative to the target line Vector3D targetlineperpendicular = Vector3D.CrossProduct(targetlinevector, level.plane.Normal); if (alignx) { scaleX = Math.Abs(basescale.x * (1.0 / Math.Cos(targetlinevector.GetAngleZ()))); } if (aligny) { scaleY = Math.Abs(basescale.y * (1.0 / Math.Cos(targetlineperpendicular.GetAngleZ()))); } } //set scale UniFields.SetFloat(Sector.Sector.Fields, (isFloor ? "xscalefloor" : "xscaleceiling"), scaleX, 1.0); UniFields.SetFloat(Sector.Sector.Fields, (isFloor ? "yscalefloor" : "yscaleceiling"), scaleY, 1.0); //update offset double distToStart = Vector2D.Distance(hitpos, targetLine.Start.Position); double distToEnd = Vector2D.Distance(hitpos, targetLine.End.Position); Vector2D offset = (distToStart < distToEnd ? targetLine.Start.Position : targetLine.End.Position).GetRotated(Angle2D.DegToRad(sourceAngle)); if (alignx) { if (Texture != null && Texture.IsImageLoaded) { offset.x %= Texture.Width / scaleX; } UniFields.SetFloat(Sector.Sector.Fields, (isFloor ? "xpanningfloor" : "xpanningceiling"), Math.Round(-offset.x, 6), 0.0); } if (aligny) { if (Texture != null && Texture.IsImageLoaded) { offset.y %= Texture.Height / scaleY; } UniFields.SetFloat(Sector.Sector.Fields, (isFloor ? "ypanningfloor" : "ypanningceiling"), Math.Round(offset.y, 6), 0.0); } //update geometry Sector.UpdateSectorGeometry(false); }
/// <summary> /// Navigation for space objects. /// </summary> /// <param name="me"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="avoidEnemies"></param> /// <returns></returns> public static IEnumerable <Sector> Pathfind(IMobileSpaceObject me, Sector start, Sector end, bool avoidEnemies, bool avoidDamagingSectors, IDictionary <PathfinderNode <Sector>, ISet <PathfinderNode <Sector> > > map) { bool cacheEnabled = Galaxy.Current.IsAbilityCacheEnabled; if (!cacheEnabled) { Galaxy.Current.EnableAbilityCache(); } if (end == null || end.StarSystem == null || start == end) { return(Enumerable.Empty <Sector>()); } if (me != null && me.StrategicSpeed < 1) { return(Enumerable.Empty <Sector>()); } if (map == null) { map = CreateDijkstraMap(me, start, end, avoidEnemies, avoidDamagingSectors); } if (!map.Any()) { return(Enumerable.Empty <Sector>()); // nowhere to go! } var nodes = new List <PathfinderNode <Sector> >(); PathfinderNode <Sector> node; if (map.Keys.Any(n => n.Location == end)) { // can reach it node = map.Keys.Where(n => n.Location == end).OrderBy(n => n.Cost).First(); } else { // can't reach it; get as close as possible var dist = map.Keys.Min(n => n.MinimumCostRemaining); node = map.Keys.First(n => n.MinimumCostRemaining == dist); } while (node != null) { nodes.Add(node); node = node.PreviousNode; } if (!cacheEnabled) { Galaxy.Current.DisableAbilityCache(); } return(nodes.Select(n => n.Location).Where(s => s != start).Reverse()); }
private static void Apply(string line, Sector sector) { string[] kv = line.Split(null, 2); string key = kv[0].Trim().ToUpperInvariant(); string value = kv[1].Trim(); if (Regex.IsMatch(key, @"^\d{4}$")) { // Value is full name for world in hex return; } if (Regex.IsMatch(key, @"^[A-P]$")) { sector.Subsectors.Add(new Subsector() { Index = key, Name = value }); return; } switch (key) { case "DOMAIN": sector.Domain = value; return; case "SECTOR": { // TODO: Add sector name sector.Names.Add(new Name(value)); return; } case "ALPHA": sector.AlphaQuadrant = value; return; case "BETA": sector.BetaQuadrant = value; return; case "GAMMA": sector.GammaQuadrant = value; return; case "DELTA": sector.DeltaQuadrant = value; return; case "ALLY": { Match match = Regex.Match(value, @"^(..)\s+(.*)$"); if (match.Success) { var code = match.Groups[1].Value; var name = match.Groups[2].Value; sector.Allegiances.Add(new Allegiance(code, name)); return; } break; } case "BASE": { Match match = Regex.Match(value, @"^(.)\s+(..)$/"); // Base decodes to two bases if (match.Success) { //var code = match.Groups[1].Value; //var bases = match.Groups[2].Value; // TODO: Base decodes return; } match = Regex.Match(value, @"^(.)\s+(\S+)\s(\S+)\s+(.*)$"); if (match.Success) { //var code = match.Groups[1].Value; //var zapf = match.Groups[2].Value; //var color = match.Groups[3].Value; //var name = match.Groups[4].Value; // TODO: Base symbols return; } break; } case "REGION": { string[] tokens = value.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (!Regex.IsMatch(tokens.Last(), @"^\d{4}$")) { sector.Regions.Add(new Region(string.Join(" ", tokens.Take(tokens.Count() - 1)), tokens.Last())); } else { sector.Regions.Add(new Region(string.Join(" ", tokens))); } return; } case "BORDER": { string[] tokens = value.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (!Regex.IsMatch(tokens.Last(), @"^\d{4}$")) { sector.Borders.Add(new Border(string.Join(" ", tokens.Take(tokens.Count() - 1)), tokens.Last())); } else { sector.Borders.Add(new Border(string.Join(" ", tokens))); } return; } case "ROUTE": { var tokens = value.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); int cur = 0; Route route = new Route(); if (Regex.IsMatch(tokens[cur], @"^[-+]?[01]$")) { route.StartOffsetX = sbyte.Parse(tokens[cur++], NumberStyles.Integer, CultureInfo.InvariantCulture); } if (Regex.IsMatch(tokens[cur], @"^[-+]?[01]$")) { route.StartOffsetY = sbyte.Parse(tokens[cur++], NumberStyles.Integer, CultureInfo.InvariantCulture); } route.Start = new Hex(tokens[cur++]); if (Regex.IsMatch(tokens[cur], @"^[-+]?[01]$")) { route.EndOffsetX = sbyte.Parse(tokens[cur++], NumberStyles.Integer, CultureInfo.InvariantCulture); } if (Regex.IsMatch(tokens[cur], @"^[-+]?[01]$")) { route.EndOffsetY = sbyte.Parse(tokens[cur++], NumberStyles.Integer, CultureInfo.InvariantCulture); } route.End = new Hex(tokens[cur++]); if (cur < tokens.Length) { route.ColorHtml = tokens[cur++]; } sector.Routes.Add(route); return; } case "LABEL": { Match match = Regex.Match(value, @"^(..)(..)[,\/]?([\S]+)?\s+(.*)$"); if (match.Success) { var c = match.Groups[1].Value; var r = match.Groups[2].Value; var options = match.Groups[3].Value; var text = match.Groups[4].Value; Label label = new Label(int.Parse(c + r), text); foreach (var option in options.ToLowerInvariant().Split(',')) { if (option == "low") { label.OffsetY = 0.85f; continue; } if (Regex.IsMatch(option, @"[-+](\d+)$")) { if (int.TryParse(option, out int offset)) { label.OffsetY = offset / 100f; } continue; } if (option == "right" || option == "left") { // TODO: Implement continue; } if (option == "large" || option == "small") { label.Size = option; continue; } if (option.StartsWith("subsec")) { label.RenderType = "Subsector"; continue; } if (option.StartsWith("quad")) { label.RenderType = "Quadrant"; continue; } if (option.StartsWith("sect")) { label.RenderType = "Sector"; continue; } if (option.StartsWith("custom")) { label.RenderType = "Custom"; continue; } if (option.Length > 0) { label.ColorHtml = option; } } sector.Labels.Add(label); return; } break; } } }
public void Insert(Sector sector) { sectorRepository.Insert(sector); unitOfWork.SaveChanges(); }
public bool CheckMovement(IPoint3D p, Map map, Point3D loc, Direction d, out int newZ) { if (!Enabled && _Successor != null) { return(_Successor.CheckMovement(p, map, loc, d, out newZ)); } if (map == null || map == Map.Internal) { newZ = 0; return(false); } int xStart = loc.X; int yStart = loc.Y; int xForward = xStart, yForward = yStart; int xRight = xStart, yRight = yStart; int xLeft = xStart, yLeft = yStart; bool checkDiagonals = ((int)d & 0x1) == 0x1; Offset(d, ref xForward, ref yForward); Offset((Direction)(((int)d - 1) & 0x7), ref xLeft, ref yLeft); Offset((Direction)(((int)d + 1) & 0x7), ref xRight, ref yRight); if (xForward < 0 || yForward < 0 || xForward >= map.Width || yForward >= map.Height) { newZ = 0; return(false); } int startZ, startTop; IEnumerable <Item> itemsStart, itemsForward, itemsLeft, itemsRight; bool ignoreMovableImpassables = MovementImpl.IgnoresMovableImpassables(p); TileFlag reqFlags = ImpassableSurface; if (p is Mobile mobile && mobile.CanSwim) { reqFlags |= TileFlag.Wet; } if (checkDiagonals) { Sector sStart = map.GetSector(xStart, yStart); Sector sForward = map.GetSector(xForward, yForward); Sector sLeft = map.GetSector(xLeft, yLeft); Sector sRight = map.GetSector(xRight, yRight); itemsStart = sStart.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xStart, yStart)); itemsForward = sForward.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xForward, yForward)); itemsLeft = sLeft.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xLeft, yLeft)); itemsRight = sRight.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xRight, yRight)); } else { Sector sStart = map.GetSector(xStart, yStart); Sector sForward = map.GetSector(xForward, yForward); itemsStart = sStart.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xStart, yStart)); itemsForward = sForward.Items.Where(i => Verify(i, reqFlags, ignoreMovableImpassables, xForward, yForward)); itemsLeft = Enumerable.Empty <Item>(); itemsRight = Enumerable.Empty <Item>(); } GetStartZ(p, map, loc, itemsStart, out startZ, out startTop); List <Item> list = null; MovementPool.AcquireMoveCache(ref list, itemsForward); Mobile m = p as Mobile; bool moveIsOk = Check(map, p, list, xForward, yForward, startTop, startZ, m != null && m.CanSwim, m != null && m.CantWalk, out newZ); if (m != null && moveIsOk && checkDiagonals) { int hold; if (m.Player && m.AccessLevel < AccessLevel.GameMaster) { MovementPool.AcquireMoveCache(ref list, itemsLeft); if (!Check(map, m, list, xLeft, yLeft, startTop, startZ, m.CanSwim, m.CantWalk, out hold)) { moveIsOk = false; } else { MovementPool.AcquireMoveCache(ref list, itemsRight); if (!Check(map, m, list, xRight, yRight, startTop, startZ, m.CanSwim, m.CantWalk, out hold)) { moveIsOk = false; } } } else { MovementPool.AcquireMoveCache(ref list, itemsLeft); if (!Check(map, m, list, xLeft, yLeft, startTop, startZ, m.CanSwim, m.CantWalk, out hold)) { MovementPool.AcquireMoveCache(ref list, itemsRight); if (!Check(map, m, list, xRight, yRight, startTop, startZ, m.CanSwim, m.CantWalk, out hold)) { moveIsOk = false; } } } } MovementPool.ClearMoveCache(ref list, true); if (!moveIsOk) { newZ = startZ; } return(moveIsOk); }
public Serializer(Sector sector, TextWriter writer) { this.sector = sector; this.writer = writer; }
//mxd public override bool OnMapTestBegin(bool testFromCurrentPosition) { if (testFromCurrentPosition) { if (!mouseinside) { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: mouse is outside editing window!"); return(false); } //now check if cursor is located inside a sector Sector s = General.Map.Map.GetSectorByCoordinates(mousemappos); if (s == null) { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: mouse cursor must be inside a sector!"); return(false); } //41 = player's height in Doom. Is that so in all other games as well? if (s.CeilHeight - s.FloorHeight < 41) { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: sector is too low!"); return(false); } //find Single Player Start. Should be type 1 in all games Thing start = null; foreach (Thing t in General.Map.Map.Things) { if (t.Type == 1) { // biwa. In Hexen format and UDMF a map can have multiple valid player starts because of // hubs. The player by default stats at the player start withe arg0 set to 0 if ((General.Map.HEXEN || General.Map.UDMF) && t.Args[0] != 0) { continue; } //store thing and position if (start == null) { start = t; } else if (t.Index > start.Index) { //if there are several Player Start 1 things, GZDoom uses one with the biggest index. start = t; } } } if (start == null) { // biwa. If there's no existing valid player start create one playerStartIsTempThing = true; start = General.Map.Map.CreateThing(); if (start != null) { General.Settings.ApplyDefaultThingSettings(start); start.Type = 1; } else { General.MainWindow.DisplayStatus(StatusType.Warning, "Can't test from current position: couldn't create player start!"); return(false); } } else { playerStartIsTempThing = false; } //store initial position playerStart = start; playerStartPosition = start.Position; //everything should be valid, let's move player start here start.Move(new Vector3D(mousemappos.x, mousemappos.y, s.FloorHeight)); } return(true); }
/// <summary> /// This returns the VisualSector for the given Sector. /// </summary> public VisualSector GetVisualSector(Sector s) { return(allsectors[s]); }
// This creates a visual sector protected override VisualSector CreateVisualSector(Sector s) { BaseVisualSector vs = new BaseVisualSector(this, s); return(vs); }
/// <summary> /// Implement this to create an instance of your VisualSector implementation. /// </summary> protected abstract VisualSector CreateVisualSector(Sector s);
// This builds the geometry. Returns false when no geometry created. public override bool Setup() { Vector2D vl, vr; //mxd. Apply sky hack? UpdateSkyRenderFlag(); //mxd. lightfog flag support int lightvalue; bool lightabsolute; GetLightValue(out lightvalue, out lightabsolute); Vector2D tscale = new Vector2D(Sidedef.Fields.GetValue("scalex_top", 1.0f), Sidedef.Fields.GetValue("scaley_top", 1.0f)); Vector2D toffset = new Vector2D(Sidedef.Fields.GetValue("offsetx_top", 0.0f), Sidedef.Fields.GetValue("offsety_top", 0.0f)); // Left and right vertices for this sidedef if (Sidedef.IsFront) { vl = new Vector2D(Sidedef.Line.Start.Position.x, Sidedef.Line.Start.Position.y); vr = new Vector2D(Sidedef.Line.End.Position.x, Sidedef.Line.End.Position.y); } else { vl = new Vector2D(Sidedef.Line.End.Position.x, Sidedef.Line.End.Position.y); vr = new Vector2D(Sidedef.Line.Start.Position.x, Sidedef.Line.Start.Position.y); } // Load sector data SectorData sd = Sector.GetSectorData(); SectorData osd = mode.GetSectorData(Sidedef.Other.Sector); if (!osd.Updated) { osd.Update(); } // Texture given? if ((Sidedef.LongHighTexture != MapSet.EmptyLongName)) { // Load texture base.Texture = General.Map.Data.GetTextureImage(Sidedef.LongHighTexture); if (base.Texture == null || base.Texture is UnknownImage) { base.Texture = General.Map.Data.UnknownTexture3D; setuponloadedtexture = Sidedef.LongHighTexture; } else { if (!base.Texture.IsImageLoaded) { setuponloadedtexture = Sidedef.LongHighTexture; } } } else { // Use missing texture base.Texture = General.Map.Data.MissingTexture3D; setuponloadedtexture = 0; } // Get texture scaled size Vector2D tsz = new Vector2D(base.Texture.ScaledWidth, base.Texture.ScaledHeight); tsz = tsz / tscale; // Get texture offsets Vector2D tof = new Vector2D(Sidedef.OffsetX, Sidedef.OffsetY); tof = tof + toffset; tof = tof / tscale; if (General.Map.Config.ScaledTextureOffsets && !base.Texture.WorldPanning) { tof = tof * base.Texture.Scale; } // Determine texture coordinates plane as they would be in normal circumstances. // We can then use this plane to find any texture coordinate we need. // The logic here is the same as in the original VisualMiddleSingle (except that // the values are stored in a TexturePlane) // NOTE: I use a small bias for the floor height, because if the difference in // height is 0 then the TexturePlane doesn't work! TexturePlane tp = new TexturePlane(); float ceilbias = (Sidedef.Other.Sector.CeilHeight == Sidedef.Sector.CeilHeight) ? 1.0f : 0.0f; if (!Sidedef.Line.IsFlagSet(General.Map.Config.UpperUnpeggedFlag)) { // When lower unpegged is set, the lower texture is bound to the bottom tp.tlt.y = tsz.y - ((float)Sidedef.Sector.CeilHeight - Sidedef.Other.Sector.CeilHeight); } tp.trb.x = tp.tlt.x + (float)Math.Round(Sidedef.Line.Length); //mxd. (G)ZDoom snaps texture coordinates to integral linedef length tp.trb.y = tp.tlt.y + (Sidedef.Sector.CeilHeight - (Sidedef.Other.Sector.CeilHeight + ceilbias)); // Apply texture offset tp.tlt += tof; tp.trb += tof; // Transform pixel coordinates to texture coordinates tp.tlt /= tsz; tp.trb /= tsz; // Left top and right bottom of the geometry that tp.vlt = new Vector3D(vl.x, vl.y, Sidedef.Sector.CeilHeight); tp.vrb = new Vector3D(vr.x, vr.y, Sidedef.Other.Sector.CeilHeight + ceilbias); // Make the right-top coordinates tp.trt = new Vector2D(tp.trb.x, tp.tlt.y); tp.vrt = new Vector3D(tp.vrb.x, tp.vrb.y, tp.vlt.z); // Create initial polygon, which is just a quad between floor and ceiling WallPolygon poly = new WallPolygon(); poly.Add(new Vector3D(vl.x, vl.y, sd.Floor.plane.GetZ(vl))); poly.Add(new Vector3D(vl.x, vl.y, sd.Ceiling.plane.GetZ(vl))); poly.Add(new Vector3D(vr.x, vr.y, sd.Ceiling.plane.GetZ(vr))); poly.Add(new Vector3D(vr.x, vr.y, sd.Floor.plane.GetZ(vr))); // Determine initial color int lightlevel = lightabsolute ? lightvalue : sd.Ceiling.brightnessbelow + lightvalue; //mxd. This calculates light with doom-style wall shading PixelColor wallbrightness = PixelColor.FromInt(mode.CalculateBrightness(lightlevel, Sidedef)); PixelColor wallcolor = PixelColor.Modulate(sd.Ceiling.colorbelow, wallbrightness); fogfactor = CalculateFogFactor(lightlevel); poly.color = wallcolor.WithAlpha(255).ToInt(); // Cut off the part below the other ceiling CropPoly(ref poly, osd.Ceiling.plane, false); // Cut out pieces that overlap 3D floors in this sector List <WallPolygon> polygons = new List <WallPolygon> { poly }; ClipExtraFloors(polygons, sd.ExtraFloors, false); //mxd if (polygons.Count > 0) { // Keep top and bottom planes for intersection testing Vector2D linecenter = Sidedef.Line.GetCenterPoint(); //mxd. Our sector's floor can be higher than the other sector's ceiling! top = sd.Ceiling.plane; bottom = (osd.Ceiling.plane.GetZ(linecenter) > sd.Floor.plane.GetZ(linecenter) ? osd.Ceiling.plane : sd.Floor.plane); // Process the polygon and create vertices List <WorldVertex> verts = CreatePolygonVertices(polygons, tp, sd, lightvalue, lightabsolute); if (verts.Count > 2) { base.SetVertices(verts); return(true); } } base.SetVertices(null); //mxd return(false); }
// This shows the info public void ShowInfo(Sector s, bool highlightceiling, bool highlightfloor) { int sheight = s.CeilHeight - s.FloorHeight; // Lookup effect description in config string effectinfo = s.Effect + " - " + General.Map.Config.GetSectorEffectInfo(s.Effect).Title; //mxd // Sector info sectorinfo.Text = " Sector " + s.Index + " (" + (s.Sidedefs == null ? "no" : s.Sidedefs.Count.ToString()) + " sidedefs)"; //mxd effect.Text = effectinfo; ceiling.Text = s.CeilHeight.ToString(); floor.Text = s.FloorHeight.ToString(); height.Text = sheight.ToString(); brightness.Text = s.Brightness.ToString(); floorname.Text = (s.FloorTexture.Length > DataManager.CLASIC_IMAGE_NAME_LENGTH ? s.FloorTexture : s.FloorTexture.ToUpperInvariant()); ceilingname.Text = (s.CeilTexture.Length > DataManager.CLASIC_IMAGE_NAME_LENGTH ? s.CeilTexture : s.CeilTexture.ToUpperInvariant()); //mxd. Set tags if (s.Tags.Count > 1) { string[] tags = new string[s.Tags.Count]; for (int i = 0; i < s.Tags.Count; i++) { tags[i] = s.Tags[i].ToString(); } tag.Text = string.Join(", ", tags); tag.Enabled = true; taglabel.Enabled = true; taglabel.Text = "Tags:"; } else { tag.Text = s.Tag + (General.Map.Options.TagLabels.ContainsKey(s.Tag) ? " - " + General.Map.Options.TagLabels[s.Tag] : string.Empty); tag.Enabled = (s.Tag != 0); taglabel.Enabled = (s.Tag != 0); taglabel.Text = "Tag:"; } //mxd effect.Enabled = (s.Effect != 0); effectlabel.Enabled = (s.Effect != 0); //mxd. Texture size if (s.LongFloorTexture == MapSet.EmptyLongName) { labelFloorTextureSize.Visible = false; General.DisplayZoomedImage(floortex, Properties.Resources.MissingTexture); } else { ImageData image = General.Map.Data.GetFlatImage(s.FloorTexture); DisplayTextureSize(labelFloorTextureSize, image); General.DisplayZoomedImage(floortex, image.GetPreview()); } if (s.LongCeilTexture == MapSet.EmptyLongName) { labelCeilTextureSize.Visible = false; General.DisplayZoomedImage(ceilingtex, Properties.Resources.MissingTexture); } else { ImageData image = General.Map.Data.GetFlatImage(s.CeilTexture); DisplayTextureSize(labelCeilTextureSize, image); //mxd General.DisplayZoomedImage(ceilingtex, image.GetPreview()); } //mxd bool showExtededFloorInfo = false; bool showExtededCeilingInfo = false; if (General.Map.UDMF) { if (s.Fields != null) { //sector colors labelLight.Visible = true; labelFade.Visible = true; panelLightColor.Visible = true; panelFadeColor.Visible = true; if (s.Fields.ContainsKey("lightcolor")) { panelLightColor.BackColor = PixelColor.FromInt(s.Fields.GetValue("lightcolor", 0xFFFFFF)).WithAlpha(255).ToColor(); labelLight.Enabled = true; } else { panelLightColor.BackColor = SystemColors.Control; labelLight.Enabled = false; } if (s.Fields.ContainsKey("fadecolor")) { panelFadeColor.BackColor = PixelColor.FromInt(s.Fields.GetValue("fadecolor", 0)).WithAlpha(255).ToColor(); labelFade.Enabled = true; } else { panelFadeColor.BackColor = SystemColors.Control; labelFade.Enabled = false; } //light if (s.Fields.ContainsKey("lightceiling") || s.Fields.ContainsKey("lightceilingabsolute")) { showExtededCeilingInfo = true; ceilingLight.Enabled = true; ceilingLightLabel.Enabled = true; int cl = s.Fields.GetValue("lightceiling", 0); if (s.Fields.GetValue("lightceilingabsolute", false)) { ceilingLight.Text = cl + " (abs.)"; } else { ceilingLight.Text = cl + " (" + Math.Min(255, Math.Max(0, (cl + s.Brightness))) + ")"; } } else { ceilingLight.Text = "--"; ceilingLight.Enabled = false; ceilingLightLabel.Enabled = false; } if (s.Fields.ContainsKey("lightfloor") || s.Fields.ContainsKey("lightfloorabsolute")) { showExtededFloorInfo = true; floorLight.Enabled = true; floorLightLabel.Enabled = true; int fl = s.Fields.GetValue("lightfloor", 0); if (s.Fields.GetValue("lightfloorabsolute", false)) { floorLight.Text = fl + " (abs.)"; } else { floorLight.Text = fl + " (" + Math.Min(255, Math.Max(0, (fl + s.Brightness))) + ")"; } } else { floorLight.Text = "--"; floorLight.Enabled = false; floorLightLabel.Enabled = false; } //ceiling offsets double panX = s.Fields.GetValue("xpanningceiling", 0.0); double panY = s.Fields.GetValue("ypanningceiling", 0.0); if (panX != 0 || panY != 0) { showExtededCeilingInfo = true; ceilingOffset.Enabled = true; ceilingOffsetLabel.Enabled = true; ceilingOffset.Text = panX.ToString(CultureInfo.InvariantCulture) + ", " + panY.ToString(CultureInfo.InvariantCulture); } else { ceilingOffset.Text = "--, --"; ceilingOffset.Enabled = false; ceilingOffsetLabel.Enabled = false; } //floor offsets panX = s.Fields.GetValue("xpanningfloor", 0.0); panY = s.Fields.GetValue("ypanningfloor", 0.0); if (panX != 0 || panY != 0) { showExtededFloorInfo = true; floorOffset.Enabled = true; floorOffsetLabel.Enabled = true; floorOffset.Text = panX.ToString(CultureInfo.InvariantCulture) + ", " + panY.ToString(CultureInfo.InvariantCulture); } else { floorOffset.Text = "--, --"; floorOffset.Enabled = false; floorOffsetLabel.Enabled = false; } //ceiling scale double scaleX = s.Fields.GetValue("xscaleceiling", 1.0); double scaleY = s.Fields.GetValue("yscaleceiling", 1.0); if (scaleX != 1.0f || scaleY != 1.0f) { showExtededCeilingInfo = true; ceilingScale.Enabled = true; ceilingScaleLabel.Enabled = true; ceilingScale.Text = scaleX.ToString(CultureInfo.InvariantCulture) + ", " + scaleY.ToString(CultureInfo.InvariantCulture); } else { ceilingScale.Text = "--, --"; ceilingScale.Enabled = false; ceilingScaleLabel.Enabled = false; } //floor scale scaleX = s.Fields.GetValue("xscalefloor", 1.0); scaleY = s.Fields.GetValue("yscalefloor", 1.0); if (scaleX != 1.0 || scaleY != 1.0) { showExtededFloorInfo = true; floorScale.Enabled = true; floorScaleLabel.Enabled = true; floorScale.Text = scaleX.ToString(CultureInfo.InvariantCulture) + ", " + scaleY.ToString(CultureInfo.InvariantCulture); } else { floorScale.Text = "--, --"; floorScale.Enabled = false; floorScaleLabel.Enabled = false; } //rotation double ceilangle = s.Fields.GetValue("rotationceiling", 0.0); if (ceilangle != 0.0) { showExtededCeilingInfo = true; ceilingAngle.Enabled = true; ceilingAngleLabel.Enabled = true; ceilingAngle.Text = ceilangle + "\u00B0"; } else { ceilingAngle.Text = "--"; ceilingAngle.Enabled = false; ceilingAngleLabel.Enabled = false; } double floorangle = s.Fields.GetValue("rotationfloor", 0.0); if (floorangle != 0f) { showExtededFloorInfo = true; floorAngle.Enabled = true; floorAngleLabel.Enabled = true; floorAngle.Text = floorangle + "\u00B0"; } else { floorAngle.Text = "--"; floorAngle.Enabled = false; floorAngleLabel.Enabled = false; } } //Flags flags.Items.Clear(); foreach (KeyValuePair <string, string> group in General.Map.Config.SectorFlags) { if (s.Flags.ContainsKey(group.Key) && s.Flags[group.Key]) { flags.Items.Add(new ListViewItem(group.Value) { Checked = true }); } } foreach (KeyValuePair <string, string> group in General.Map.Config.CeilingPortalFlags) { if (s.Flags.ContainsKey(group.Key) && s.Flags[group.Key]) { flags.Items.Add(new ListViewItem(group.Value + " (ceil. portal)") { Checked = true }); } } foreach (KeyValuePair <string, string> group in General.Map.Config.FloorPortalFlags) { if (s.Flags.ContainsKey(group.Key) && s.Flags[group.Key]) { flags.Items.Add(new ListViewItem(group.Value + " (floor portal)") { Checked = true }); } } //mxd. Flags panel visibility and size flagsPanel.Visible = (flags.Items.Count > 0); if (flags.Items.Count > 0) { Rectangle rect = flags.GetItemRect(0); int itemspercolumn = 1; // Check how many items per column we have... for (int i = 1; i < flags.Items.Count; i++) { if (flags.GetItemRect(i).X != rect.X) { break; } itemspercolumn++; } flags.Width = rect.Width * (int)Math.Ceiling(flags.Items.Count / (float)itemspercolumn); flagsPanel.Width = flags.Width + flags.Left * 2; } //mxd. Toggle visibility foreach (Label label in floorinfolabels) { label.Visible = showExtededFloorInfo; } foreach (Label label in floorlabels) { label.Visible = showExtededFloorInfo; } foreach (Label label in ceilinfolabels) { label.Visible = showExtededCeilingInfo; } foreach (Label label in ceillabels) { label.Visible = showExtededCeilingInfo; } } else { panelFadeColor.Visible = false; panelLightColor.Visible = false; labelFade.Visible = false; labelLight.Visible = false; flagsPanel.Visible = false; } //mxd. Resize panels UpdateTexturePanel(ceilingpanel, ceilingname, ceilinfolabels, ceilingtex, ceilingOffsetLabel.Location.X - 1, showExtededCeilingInfo); UpdateTexturePanel(floorpanel, floorname, floorinfolabels, floortex, floorOffsetLabel.Location.X - 1, showExtededFloorInfo); //mxd. Highlight ceiling or floor? Color floorhighlightcolor = (highlightfloor ? SystemColors.HotTrack : SystemColors.WindowText); Color ceilinghighlightcolor = (highlightceiling ? SystemColors.HotTrack : SystemColors.WindowText); floorpanel.ForeColor = floorhighlightcolor; floor.ForeColor = floorhighlightcolor; labelfloor.ForeColor = floorhighlightcolor; ceilingpanel.ForeColor = ceilinghighlightcolor; ceiling.ForeColor = ceilinghighlightcolor; labelceiling.ForeColor = ceilinghighlightcolor; // Show the whole thing this.Show(); //this.Update(); // ano - don't think this is needed, and is slow }
/// <summary> /// Goes through all tracks in the list and determines whether or not /// they can currently be seen. This function does not add or remove /// contacts from the list. That can only be done in ProcessAcquiredContacts. /// </summary> private void DoTrackingSweep() { //_logger.debugLog("Beginning sweep", "DoTrackingSweep"); Vector3D myPos = _grid.WorldAABB.Center; // Go through all current tracks and update their makers foreach (Track track in _allTracks.Values) { //_logger.debugLog($"For Track {track.trackId}", "DoTrackingSweep"); // If the entity is null, this track is only available on the // server so use the stored value. Otherwise get the most // up to date value if (track.ent != null) { //_logger.debugLog("Entity is not null", "DoTrackingSweep"); track.position = track.ent.WorldAABB.Center; } // Transform the coordinates into grid space so we // can compare it against our radar coverage VRageMath.Vector3D relative = VRageMath.Vector3D.Transform( track.position, _grid.WorldMatrixNormalizedInv); //Check that the sector is covered by our radars Sector sec = SectorExtensions.ClassifyVector(relative); if (IsSectorBlind(sec)) { //_logger.debugLog("Sector is blind", "DoTrackingSweep"); // If a contact is not trackable, clear its GPS marker ClearTrackMarker(track); continue; } // Vector to target Vector3D vecTo = track.position - myPos; // If the entity is available, calculate the cross-section // Otherwise we will use the stored value from the server if (track.ent != null) { track.xsec = EWMath.DetermineXSection(track.ent as IMyCubeGrid, vecTo); } double range = vecTo.Length(); double minxsec = EWMath.MinimumXSection( Constants.radarBeamWidths[(int)_assignedType], range); if (track.xsec < minxsec) { //_logger.debugLog("Cross-section not large enough", "DoTrackingSweep"); ClearTrackMarker(track); continue; } // TODO: raycast // If all of the previous checks passed, this contact should // be visible with a marker AddUpdateTrackMarker(track); } }
public ActivateQuestCommand(Quest quest, Sector sector, EditingContext context) : base(context) { this.quest = quest; this.sector = sector; }
public void Update(Sector sector) { sectorRepository.Update(sector); unitOfWork.SaveChanges(); }
/// <summary> /// Finds the path for executing this order. /// </summary> /// <param name="sobj">The space object executing the order.</param> /// <returns></returns> public override IEnumerable <Sector> Pathfind(IMobileSpaceObject me, Sector start) { return(Pathfinder.Pathfind(me, start, Destination, AvoidEnemies, true, me.DijkstraMap)); }
public bool CheckMovement(Mobile m, Map map, Point3D loc, Direction d, out int newZ) { if (map == null || map == Map.Internal) { newZ = 0; return(false); } int xStart = loc.X; int yStart = loc.Y; int xForward = xStart, yForward = yStart; int xRight = xStart, yRight = yStart; int xLeft = xStart, yLeft = yStart; bool checkDiagonals = ((int)d & 0x1) == 0x1; Offset(d, ref xForward, ref yForward); Offset((Direction)(((int)d - 1) & 0x7), ref xLeft, ref yLeft); Offset((Direction)(((int)d + 1) & 0x7), ref xRight, ref yRight); if (xForward < 0 || yForward < 0 || xForward >= map.Width || yForward >= map.Height) { newZ = 0; return(false); } int startZ, startTop; ArrayList itemsStart = m_Pools[0]; ArrayList itemsForward = m_Pools[1]; ArrayList itemsLeft = m_Pools[2]; ArrayList itemsRight = m_Pools[3]; ArrayList items; bool ignoreMovableImpassables = m_IgnoreMovableImpassables; TileFlag reqFlags = ImpassableSurface; if (m.CanSwim) { reqFlags |= TileFlag.Wet; } if (checkDiagonals) { Sector sectorStart = map.GetSector(xStart, yStart); Sector sectorForward = map.GetSector(xForward, yForward); Sector sectorLeft = map.GetSector(xLeft, yLeft); Sector sectorRight = map.GetSector(xRight, yRight); ArrayList sectors = m_Pools[4]; sectors.Add(sectorStart); if (!sectors.Contains(sectorForward)) { sectors.Add(sectorForward); } if (!sectors.Contains(sectorLeft)) { sectors.Add(sectorLeft); } if (!sectors.Contains(sectorRight)) { sectors.Add(sectorRight); } for (int i = 0; i < sectors.Count; ++i) { Sector sector = (Sector)sectors[i]; items = sector.Items; for (int j = 0; j < items.Count; ++j) { Item item = (Item)items[j]; if (ignoreMovableImpassables && item.Movable && item.ItemData.Impassable) { continue; } if ((item.ItemData.Flags & reqFlags) == 0) { continue; } if (sector == sectorStart && item.AtWorldPoint(xStart, yStart) && item.ItemID < 0x4000) { itemsStart.Add(item); } else if (sector == sectorForward && item.AtWorldPoint(xForward, yForward) && item.ItemID < 0x4000) { itemsForward.Add(item); } else if (sector == sectorLeft && item.AtWorldPoint(xLeft, yLeft) && item.ItemID < 0x4000) { itemsLeft.Add(item); } else if (sector == sectorRight && item.AtWorldPoint(xRight, yRight) && item.ItemID < 0x4000) { itemsRight.Add(item); } } } if (m_Pools[4].Count > 0) { m_Pools[4].Clear(); } } else { Sector sectorStart = map.GetSector(xStart, yStart); Sector sectorForward = map.GetSector(xForward, yForward); if (sectorStart == sectorForward) { items = sectorStart.Items; for (int i = 0; i < items.Count; ++i) { Item item = (Item)items[i]; if (ignoreMovableImpassables && item.Movable && item.ItemData.Impassable) { continue; } if ((item.ItemData.Flags & reqFlags) == 0) { continue; } if (item.AtWorldPoint(xStart, yStart) && item.ItemID < 0x4000) { itemsStart.Add(item); } else if (item.AtWorldPoint(xForward, yForward) && item.ItemID < 0x4000) { itemsForward.Add(item); } } } else { items = sectorForward.Items; for (int i = 0; i < items.Count; ++i) { Item item = (Item)items[i]; if (ignoreMovableImpassables && item.Movable && item.ItemData.Impassable) { continue; } if ((item.ItemData.Flags & reqFlags) == 0) { continue; } if (item.AtWorldPoint(xForward, yForward) && item.ItemID < 0x4000) { itemsForward.Add(item); } } items = sectorStart.Items; for (int i = 0; i < items.Count; ++i) { Item item = (Item)items[i]; if (ignoreMovableImpassables && item.Movable && item.ItemData.Impassable) { continue; } if ((item.ItemData.Flags & reqFlags) == 0) { continue; } if (item.AtWorldPoint(xStart, yStart) && item.ItemID < 0x4000) { itemsStart.Add(item); } } } } GetStartZ(m, map, loc, itemsStart, out startZ, out startTop); bool moveIsOk = Check(map, m, itemsForward, xForward, yForward, startTop, startZ, m.CanSwim, m.CantWalk, out newZ); if (moveIsOk && checkDiagonals) { int hold; if (!Check(map, m, itemsLeft, xLeft, yLeft, startTop, startZ, m.CanSwim, m.CantWalk, out hold) && !Check(map, m, itemsRight, xRight, yRight, startTop, startZ, m.CanSwim, m.CantWalk, out hold)) { moveIsOk = false; } } for (int i = 0; i < (checkDiagonals ? 4 : 2); ++i) { if (m_Pools[i].Count > 0) { m_Pools[i].Clear(); } } if (!moveIsOk) { newZ = startZ; } return(moveIsOk); }
//mxd. Sector brightness change public override void OnChangeTargetBrightness(bool up) { if (level != null && level.sector != Sector.Sector) { int index = -1; for (int i = 0; i < Sector.ExtraCeilings.Count; i++) { if (Sector.ExtraCeilings[i] == this) { index = i + 1; break; } } if (index > -1 && index < Sector.ExtraCeilings.Count) { ((BaseVisualSector)mode.GetVisualSector(Sector.ExtraCeilings[index].level.sector)).Floor.OnChangeTargetBrightness(up); } else { base.OnChangeTargetBrightness(up); } } else { //if a map is not in UDMF format, or this ceiling is part of 3D-floor... if (!General.Map.UDMF || (level != null && Sector.Sector != level.sector)) { base.OnChangeTargetBrightness(up); return; } int light = Sector.Sector.Fields.GetValue("lightceiling", 0); bool absolute = Sector.Sector.Fields.GetValue("lightceilingabsolute", false); int newLight; if (up) { newLight = General.Map.Config.BrightnessLevels.GetNextHigher(light, absolute); } else { newLight = General.Map.Config.BrightnessLevels.GetNextLower(light, absolute); } if (newLight == light) { return; } //create undo mode.CreateUndo("Change ceiling brightness", UndoGroup.SurfaceBrightnessChange, Sector.Sector.FixedIndex); Sector.Sector.Fields.BeforeFieldsChange(); //apply changes UniFields.SetInteger(Sector.Sector.Fields, "lightceiling", newLight, (absolute ? int.MinValue : 0)); mode.SetActionResult("Changed ceiling brightness to " + newLight + "."); Sector.Sector.UpdateNeeded = true; Sector.Sector.UpdateCache(); //rebuild sector Sector.UpdateSectorGeometry(false); } }
public static CustomRegion FindDRDTRegion(Map map, Point3D loc) { Point3D p = loc; if (p == Point3D.Zero) { return(null); } if (map == Map.Internal || map == null) { return(null); } Sector sector = map.GetSector(p); if (sector == null || sector.Owner == null || sector == sector.Owner.InvalidSector) { return(null); } if (sector.Regions == null) //new check 2/2/07 { return(null); } ArrayList list = sector.Regions; if (list == null || list.Count == 0) { return(null); } ArrayList list2 = new ArrayList(); for (int i = 0; i < list.Count; ++i) { if (list[i] is Region) //new check 2/2/07 { Region region = (Region)list[i]; if (region == null) { continue; } if (region.Contains(p)) { list2.Add(region); } } } foreach (Region reg in list2) { if (reg == null) { continue; } CustomRegion test = null; if (reg is CustomRegion) { test = reg as CustomRegion; if (test != null) { return(test); } } } //no custom region found return(null); }
public Point3D RandomSpawnLocation(int spawnHeight, bool land, bool water, Point3D home, int range) { Map map = Map; if (map == Map.Internal) { return(Point3D.Zero); } InitRectangles(); if (m_TotalWeight <= 0) { return(Point3D.Zero); } for (int i = 0; i < 10; i++) // Try 10 times { int x, y, minZ, maxZ; if (home == Point3D.Zero) { int rand = Utility.Random(m_TotalWeight); x = int.MinValue; y = int.MinValue; minZ = int.MaxValue; maxZ = int.MinValue; for (int j = 0; j < m_RectangleWeights.Length; j++) { int curWeight = m_RectangleWeights[j]; if (rand < curWeight) { Rectangle3D rect = m_Rectangles[j]; x = rect.Start.X + rand % rect.Width; y = rect.Start.Y + rand / rect.Width; minZ = rect.Start.Z; maxZ = rect.End.Z; break; } rand -= curWeight; } } else { x = Utility.RandomMinMax(home.X - range, home.X + range); y = Utility.RandomMinMax(home.Y - range, home.Y + range); minZ = int.MaxValue; maxZ = int.MinValue; for (int j = 0; j < Area.Length; j++) { Rectangle3D rect = Area[j]; if (x >= rect.Start.X && x < rect.End.X && y >= rect.Start.Y && y < rect.End.Y) { minZ = rect.Start.Z; maxZ = rect.End.Z; break; } } if (minZ == int.MaxValue) { continue; } } if (x < 0 || y < 0 || x >= map.Width || y >= map.Height) { continue; } LandTile lt = map.Tiles.GetLandTile(x, y); int ltLowZ = 0, ltAvgZ = 0, ltTopZ = 0; map.GetAverageZ(x, y, ref ltLowZ, ref ltAvgZ, ref ltTopZ); TileFlag ltFlags = TileData.LandTable[lt.ID & TileData.MaxLandValue].Flags; bool ltImpassable = ((ltFlags & TileFlag.Impassable) != 0); if (!lt.Ignored && ltAvgZ >= minZ && ltAvgZ < maxZ) { if ((ltFlags & TileFlag.Wet) != 0) { if (water) { m_SpawnBuffer1.Add(ltAvgZ); } } else if (land && !ltImpassable) { m_SpawnBuffer1.Add(ltAvgZ); } } StaticTile[] staticTiles = map.Tiles.GetStaticTiles(x, y, true); for (int j = 0; j < staticTiles.Length; j++) { StaticTile tile = staticTiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; int tileZ = tile.Z + id.CalcHeight; if (tileZ >= minZ && tileZ < maxZ) { if ((id.Flags & TileFlag.Wet) != 0) { if (water) { m_SpawnBuffer1.Add(tileZ); } } else if (land && id.Surface && !id.Impassable) { m_SpawnBuffer1.Add(tileZ); } } } Sector sector = map.GetSector(x, y); for (int j = 0; j < sector.Items.Count; j++) { Item item = sector.Items[j]; if (!(item is BaseMulti) && item.ItemID <= TileData.MaxItemValue && item.AtWorldPoint(x, y)) { m_SpawnBuffer2.Add(item); if (!item.Movable) { ItemData id = item.ItemData; int itemZ = item.Z + id.CalcHeight; if (itemZ >= minZ && itemZ < maxZ) { if ((id.Flags & TileFlag.Wet) != 0) { if (water) { m_SpawnBuffer1.Add(itemZ); } } else if (land && id.Surface && !id.Impassable) { m_SpawnBuffer1.Add(itemZ); } } } } } if (m_SpawnBuffer1.Count == 0) { m_SpawnBuffer1.Clear(); m_SpawnBuffer2.Clear(); continue; } int z; switch (m_SpawnZLevel) { case SpawnZLevel.Lowest: { z = int.MaxValue; for (int j = 0; j < m_SpawnBuffer1.Count; j++) { int l = m_SpawnBuffer1[j]; if (l < z) { z = l; } } break; } case SpawnZLevel.Highest: { z = int.MinValue; for (int j = 0; j < m_SpawnBuffer1.Count; j++) { int l = m_SpawnBuffer1[j]; if (l > z) { z = l; } } break; } default: // SpawnZLevel.Random { int index = Utility.Random(m_SpawnBuffer1.Count); z = m_SpawnBuffer1[index]; break; } } m_SpawnBuffer1.Clear(); if (!Find(new Point3D(x, y, z), map).AcceptsSpawnsFrom(this)) { m_SpawnBuffer2.Clear(); continue; } int top = z + spawnHeight; bool ok = true; for (int j = 0; j < m_SpawnBuffer2.Count; j++) { Item item = m_SpawnBuffer2[j]; ItemData id = item.ItemData; if ((id.Surface || id.Impassable) && item.Z + id.CalcHeight > z && item.Z < top) { ok = false; break; } } m_SpawnBuffer2.Clear(); if (!ok) { continue; } if (ltImpassable && ltAvgZ > z && ltLowZ < top) { continue; } for (int j = 0; j < staticTiles.Length; j++) { StaticTile tile = staticTiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; if ((id.Surface || id.Impassable) && tile.Z + id.CalcHeight > z && tile.Z < top) { ok = false; break; } } if (!ok) { continue; } for (int j = 0; j < sector.Mobiles.Count; j++) { Mobile m = sector.Mobiles[j]; if (m.X == x && m.Y == y && (m.IsPlayer() || !m.Hidden)) { if (m.Z + 16 > z && m.Z < top) { ok = false; break; } } } if (ok) { return(new Point3D(x, y, z)); } } return(Point3D.Zero); }
public static IDictionary <PathfinderNode <Sector>, ISet <PathfinderNode <Sector> > > CreateDijkstraMap(IMobileSpaceObject me, Sector start, Sector end, bool avoidEnemies, bool avoidDamagingSectors) { // step 2a (do it here so we can return map if start or end is null): empty map with nodes, their costs, and previous-node references var map = new Dictionary <PathfinderNode <Sector>, ISet <PathfinderNode <Sector> > >(); // if we are nowhere or we're going nowhere, that's impossible! if (start == null || end == null) { return(map); } var startSys = start.StarSystem; // pathfind! // step 1: empty priority queue with cost to reach each node var queue = new Dictionary <int, ISet <PathfinderNode <Sector> > >(); // step 2b: empty set of previously visited nodes var visited = new HashSet <Sector>(); // step 3: add start node and cost queue.Add(0, new HashSet <PathfinderNode <Sector> >()); queue[0].Add(new PathfinderNode <Sector>(start, 0, null, EstimateDistance(start, end, me == null ? null : me.Owner))); // step 4: quit if there are no nodes (all paths exhausted without finding goal) bool success = false; while (queue.SelectMany(kvp => kvp.Value).Any() && !success) { // step 5: take lowest cost node out of queue // TODO - also prefer straight line movement to diagonal? var minCost = queue.Keys.Min(); while (!queue[minCost].Any()) { queue.Remove(minCost); minCost = queue.Keys.Min(); } var node = queue[minCost].First(); queue[minCost].Remove(node); map.Add(node, new HashSet <PathfinderNode <Sector> >()); // step 6: if node is the goal, stop after it's done - success! if (node.Location == end) { success = true; } // step 7: check possible moves var moves = GetPossibleMoves(node.Location, me == null ? true : me.CanWarp, me == null ? null : me.Owner); // step 7a: remove blocked points (aka calculate cost) if (avoidEnemies) { // avoid enemies, except at the destination moves = moves.Where(m => m == null || m == end || !m.SpaceObjects.Where(sobj => sobj.CheckVisibility(me.Owner) >= Visibility.Visible || sobj.FindMemory(me.Owner)?.Sector == m).OfType <ICombatant>().Any(sobj => sobj.IsHostileTo(me == null ? null : me.Owner))); } if (avoidDamagingSectors) { // don't avoid the destination, even if it is a damaging sector moves = moves.Where(m => m == end || m == null || !m.SpaceObjects.Where(sobj => sobj.CheckVisibility(me.Owner) >= Visibility.Visible || sobj.FindMemory(me.Owner)?.Sector == m).Any(sobj => sobj.GetAbilityValue("Sector - Damage").ToInt() > 0)); } // step 7b: update priority queue Action <Sector> f = move => { // When we lock the queue, we do so because it is being checked and modified by other threads, // and we don't want them stepping on each other's toes. // e.g. thread 1 is checking for the existence of an item in the queue // while thread 2 is busy adding that same item! if (!visited.Contains(move)) { // didn't visit yet var newnode = new PathfinderNode <Sector>(move, node.Cost + 1, node, EstimateDistance(move, end, me == null ? null : me.Owner)); lock (queue) { if (!queue.ContainsKey(newnode.Cost)) { queue.Add(newnode.Cost, new HashSet <PathfinderNode <Sector> >()); } queue[newnode.Cost].Add(newnode); } if (!map.ContainsKey(node)) // don't need to lock map, we're only adding a node which should only get added once per run { map.Add(node, new HashSet <PathfinderNode <Sector> >()); } map[node].Add(newnode); visited.Add(move); } else { // already visited - but is it by a longer path? var moreCost = queue.Where(kvp => kvp.Key > node.Cost + 1).SelectMany(kvp => kvp.Value); var items = moreCost.Where(n => n.Location == move && n.Cost > node.Cost + 1); if (items.Any()) { PathfinderNode <Sector> newnode; foreach (var old in items.ToArray()) { lock (queue[old.Cost]) queue[old.Cost].Remove(old); map.Remove(old); } newnode = new PathfinderNode <Sector>(move, node.Cost + 1, node); lock (queue[newnode.Cost]) queue[newnode.Cost].Add(newnode); if (!map.ContainsKey(node)) // don't need to lock map, we're only adding a node which should only get added once per run { map.Add(node, new HashSet <PathfinderNode <Sector> >()); } map[node].Add(newnode); } } }; moves.SafeForeach(f); } return(map); }
public override void Process(ResourceManager resourceManager) { // // Jump // int jump = GetIntOption("jump", 6).Clamp(0, 20); // // Content & Coordinates // Selector selector; Location loc; if (Context.Request.HttpMethod == "POST") { Sector sector; bool lint = GetBoolOption("lint", defaultValue: false); Func <ErrorLogger.Record, bool> filter = null; if (lint) { bool hide_uwp = GetBoolOption("hide-uwp", defaultValue: false); bool hide_tl = GetBoolOption("hide-tl", defaultValue: false); filter = (ErrorLogger.Record record) => { if (hide_uwp && record.message.StartsWith("UWP")) { return(false); } if (hide_tl && record.message.StartsWith("UWP: TL")) { return(false); } return(true); }; } ErrorLogger errors = new ErrorLogger(filter); sector = GetPostedSector(Context.Request, errors) ?? throw new HttpError(400, "Bad Request", "Either file or data must be supplied in the POST data."); if (lint && !errors.Empty) { throw new HttpError(400, "Bad Request", errors.ToString()); } int hex = GetIntOption("hex", Astrometrics.SectorCentralHex); loc = new Location(new Point(0, 0), hex); selector = new HexSectorSelector(resourceManager, sector, loc.Hex, jump); } else { // NOTE: This (re)initializes a static data structure used for // resolving names into sector locations, so needs to be run // before any other objects (e.g. Worlds) are loaded. SectorMap.Milieu map = SectorMap.ForMilieu(resourceManager, GetStringOption("milieu")); if (HasOption("sector") && HasOption("hex")) { string sectorName = GetStringOption("sector"); int hex = GetIntOption("hex", 0); Sector sector = map.FromName(sectorName) ?? throw new HttpError(404, "Not Found", $"The specified sector '{sectorName}' was not found."); loc = new Location(sector.Location, hex); } else if (HasLocation()) { loc = GetLocation(); } else { loc = Location.Empty; } selector = new HexSelector(map, resourceManager, loc, jump); } // // Scale // double scale = GetDoubleOption("scale", 64).Clamp(MinScale, MaxScale); // // Options & Style // MapOptions options = MapOptions.BordersMajor | MapOptions.BordersMinor | MapOptions.ForceHexes; Style style = Style.Poster; ParseOptions(ref options, ref style); // // Border // bool border = GetBoolOption("border", defaultValue: true); // // Clip // bool clip = GetBoolOption("clip", defaultValue: true); // Hex Rotation int hrot = GetIntOption("hrotation", defaultValue: 0); // // What to render // RectangleF tileRect = new RectangleF(); Point coords = Astrometrics.LocationToCoordinates(loc); tileRect.X = coords.X - jump - 1; tileRect.Width = jump + 1 + jump; tileRect.Y = coords.Y - jump - 1; tileRect.Height = jump + 1 + jump; // Account for jagged hexes tileRect.Y += (coords.X % 2 == 0) ? 0 : 0.5f; tileRect.Inflate(0.35f, 0.15f); Size tileSize = new Size((int)Math.Floor(tileRect.Width * scale * Astrometrics.ParsecScaleX), (int)Math.Floor(tileRect.Height * scale * Astrometrics.ParsecScaleY)); // Construct clipping path List <Point> clipPath = new List <Point>(jump * 6 + 1); Point cur = coords; for (int i = 0; i < jump; ++i) { // Move J parsecs to the upper-left (start of border path logic) cur = Astrometrics.HexNeighbor(cur, 1); } clipPath.Add(cur); for (int dir = 0; dir < 6; ++dir) { for (int i = 0; i < jump; ++i) { cur = Astrometrics.HexNeighbor(cur, (dir + 3) % 6); // Clockwise from upper left clipPath.Add(cur); } } Stylesheet styles = new Stylesheet(scale, options, style); // If any names are showing, show them all if (styles.worldDetails.HasFlag(WorldDetails.KeyNames)) { styles.worldDetails |= WorldDetails.AllNames; } // Compute path RenderUtil.HexEdges(styles.hexStyle == HexStyle.Square ? PathUtil.PathType.Square : PathUtil.PathType.Hex, out float[] edgeX, out float[] edgeY); PathUtil.ComputeBorderPath(clipPath, edgeX, edgeY, out PointF[] boundingPathCoords, out byte[] boundingPathTypes); AbstractMatrix transform = AbstractMatrix.Identity; if (hrot != 0) { ApplyHexRotation(hrot, styles, ref tileSize, ref transform); } RenderContext ctx = new RenderContext(resourceManager, selector, tileRect, scale, options, styles, tileSize) { DrawBorder = border, ClipOutsectorBorders = true, // TODO: Widen path to allow for single-pixel border ClipPath = clip ? new AbstractPath(boundingPathCoords, boundingPathTypes) : null }; ProduceResponse(Context, "Jump Map", ctx, tileSize, transform, transparent: clip); }
/// <summary> /// Constructor /// </summary> /// <param name="parent">Padre</param> /// <param name="blockNum">Número de bloque</param> public TrailingBlock(Sector parent, byte blockNum) : base(parent, blockNum) { }
/// <summary> /// Constructor /// </summary> /// <param name="parent">Padre</param> /// <param name="blockNum">Número de bloque</param> public Block(Sector parent, byte blockNum) { _Parent = parent; _BlockNum = blockNum; }
/// <summary> /// Returns True when a VisualSector has been created for the specified Sector. /// </summary> public bool VisualSectorExists(Sector s) { return(allsectors.ContainsKey(s)); }
//mxd public bool Setup(SectorLevel level, Effect3DFloor extrafloor, bool innerside) { Sector s = level.sector; Vector2D texscale; this.innerside = innerside; //mxd base.Setup(level, extrafloor); // Fetch ZDoom fields float rotate = Angle2D.DegToRad(s.Fields.GetValue("rotationceiling", 0.0f)); Vector2D offset = new Vector2D(s.Fields.GetValue("xpanningceiling", 0.0f), s.Fields.GetValue("ypanningceiling", 0.0f)); Vector2D scale = new Vector2D(s.Fields.GetValue("xscaleceiling", 1.0f), s.Fields.GetValue("yscaleceiling", 1.0f)); //Load ceiling texture if (s.LongCeilTexture != MapSet.EmptyLongName) { base.Texture = General.Map.Data.GetFlatImage(s.LongCeilTexture); if (base.Texture == null || base.Texture is UnknownImage) { base.Texture = General.Map.Data.UnknownTexture3D; setuponloadedtexture = s.LongCeilTexture; } else if (!base.Texture.IsImageLoaded) { setuponloadedtexture = s.LongCeilTexture; } } else { // Use missing texture base.Texture = General.Map.Data.MissingTexture3D; setuponloadedtexture = 0; } // Determine texture scale if (base.Texture.IsImageLoaded) { texscale = new Vector2D(1.0f / base.Texture.ScaledWidth, 1.0f / base.Texture.ScaledHeight); } else { texscale = new Vector2D(1.0f / 64.0f, 1.0f / 64.0f); } // Determine brightness byte alpha = (byte)General.Clamp(level.alpha, 0, 255); int color = PixelColor.FromInt(level.color).WithAlpha(alpha).ToInt(); int targetbrightness; SectorData sd = mode.GetSectorData(this.Sector.Sector); if (extrafloor != null && !extrafloor.VavoomType && !level.disablelighting) { //mxd. Top extrafloor level should calculate fogdensity from the brightness of the level above it if (!innerside) { targetbrightness = 0; for (int i = 0; i < sd.LightLevels.Count - 1; i++) { if (sd.LightLevels[i] == level) { targetbrightness = sd.LightLevels[i + 1].brightnessbelow; break; } } } //mxd. Inner extrafloor ceilings must be colored using control sector's color and brightness else { targetbrightness = level.brightnessbelow; for (int i = 0; i < sd.LightLevels.Count; i++) { if (sd.LightLevels[i] == level) { if (i > 0) { color = PixelColor.FromInt(sd.LightLevels[i - 1].color).WithAlpha(alpha).ToInt(); } break; } } } } else { targetbrightness = level.brightnessbelow; } // [ZZ] Apply Doom 64 lighting here (for extrafloor) if (extrafloor != null) { color = PixelColor.Modulate(PixelColor.FromInt(color), extrafloor.ColorCeiling).WithAlpha(alpha).ToInt(); } //mxd. Determine fog density fogfactor = CalculateFogFactor(targetbrightness); // Make vertices ReadOnlyCollection <Vector2D> triverts = Sector.Sector.Triangles.Vertices; WorldVertex[] verts = new WorldVertex[triverts.Count]; for (int i = 0; i < triverts.Count; i++) { // Color shading verts[i].c = color; //mxd // Vertex coordinates verts[i].x = triverts[i].x; verts[i].y = triverts[i].y; verts[i].z = level.plane.GetZ(triverts[i]); // Texture coordinates Vector2D pos = triverts[i]; pos = pos.GetRotated(rotate); pos.y = -pos.y; pos = (pos + offset) * scale * texscale; verts[i].u = pos.x; verts[i].v = pos.y; } // The sector triangulation created clockwise triangles that // are right up for the floor. For the ceiling we must flip // the triangles upside down. if (extrafloor == null || extrafloor.VavoomType || innerside) { SwapTriangleVertices(verts); } // Determine render pass if (extrafloor != null) { if (extrafloor.Sloped3dFloor) //mxd { this.RenderPass = RenderPass.Mask; } else if (extrafloor.RenderAdditive) //mxd { this.RenderPass = RenderPass.Additive; } else if ((level.alpha < 255) || Texture.IsTranslucent) { this.RenderPass = RenderPass.Alpha; } else { this.RenderPass = RenderPass.Mask; } } else { this.RenderPass = RenderPass.Solid; } //mxd. Update sky render flag bool isrenderedassky = renderassky; renderassky = (level.sector.CeilTexture == General.Map.Config.SkyFlatName); if (isrenderedassky != renderassky && Sector.Sides != null) { // Upper sidedef geometry may need updating... foreach (Sidedef side in level.sector.Sidedefs) { VisualSidedefParts parts = Sector.GetSidedefParts(side); // Upper side can exist in either our, or the neightbouring sector, right? if (parts.upper != null && parts.upper.Triangles > 0) { parts.upper.UpdateSkyRenderFlag(); } else if (side.Other != null && side.Other.Sector != null && side.Other.Sector.CeilTexture == General.Map.Config.SkyFlatName) { // Update upper side of the neightbouring sector BaseVisualSector other = (BaseVisualSector)mode.GetVisualSector(side.Other.Sector); if (other != null && other.Sides != null) { parts = other.GetSidedefParts(side.Other); if (parts.upper != null && parts.upper.Triangles > 0) { parts.upper.UpdateSkyRenderFlag(); } } } } } // Apply vertices base.SetVertices(verts); return(verts.Length > 0); }
public static HousePlacementResult Check(Mobile from, int multiID, Point3D center, out ArrayList toMove) { // If this spot is considered valid, every item and mobile in this list will be moved under the house sign toMove = new ArrayList(); Map map = from.Map; if (map == null || map == Map.Internal) { return(HousePlacementResult.BadLand); // A house cannot go here } if (from.AccessLevel >= AccessLevel.GameMaster) { return(HousePlacementResult.Valid); // Staff can place anywhere } if (SpellHelper.IsFeluccaT2A(map, center)) { return(HousePlacementResult.BadRegion); // No houses in T2A } NoHousingRegion noHousingRegion = (NoHousingRegion)Region.Find(center, map).GetRegion(typeof(NoHousingRegion)); if (noHousingRegion != null) { return(HousePlacementResult.BadRegion); } // This holds data describing the internal structure of the house MultiComponentList mcl = MultiData.GetComponents(multiID); // Location of the nortwest-most corner of the house Point3D start = new Point3D(center.X + mcl.Min.X, center.Y + mcl.Min.Y, center.Z); // These are storage lists. They hold items and mobiles found in the map for further processing List <Item> items = new List <Item>(); List <Mobile> mobiles = new List <Mobile>(); // These are also storage lists. They hold location values indicating the yard and border locations. List <Point2D> yard = new List <Point2D>(), borders = new List <Point2D>(); /* RULES: * * 1) All tiles which are around the -outside- of the foundation must not have anything impassable. * 2) No impassable object or land tile may come in direct contact with any part of the house. * 3) Five tiles from the front and back of the house must be completely clear of all house tiles. * 4) The foundation must rest flatly on a surface. Any bumps around the foundation are not allowed. * 5) No foundation tile may reside over terrain which is viewed as a road. */ for (int x = 0; x < mcl.Width; ++x) { for (int y = 0; y < mcl.Height; ++y) { int tileX = start.X + x; int tileY = start.Y + y; StaticTile[] addTiles = mcl.Tiles[x][y]; if (addTiles.Length == 0) { continue; // There are no tiles here, continue checking somewhere else } Point3D testPoint = new Point3D(tileX, tileY, center.Z); Region reg = Region.Find(testPoint, map); if (!reg.AllowHousing(from, testPoint)) // Cannot place houses in dungeons, towns, treasure map areas etc { if (reg.IsPartOf(typeof(TreasureRegion)) || reg.IsPartOf(typeof(HouseRegion))) { return(HousePlacementResult.BadRegionHidden); } if (reg.IsPartOf(typeof(HouseRaffleRegion))) { return(HousePlacementResult.BadRegionRaffle); } return(HousePlacementResult.BadRegion); } LandTile landTile = map.Tiles.GetLandTile(tileX, tileY); int landID = landTile.ID & TileData.MaxLandValue; StaticTile[] oldTiles = map.Tiles.GetStaticTiles(tileX, tileY, true); Sector sector = map.GetSector(tileX, tileY); items.Clear(); for (int i = 0; i < sector.Items.Count; ++i) { Item item = sector.Items[i]; if (item.Visible && item.X == tileX && item.Y == tileY) { items.Add(item); } } mobiles.Clear(); for (int i = 0; i < sector.Mobiles.Count; ++i) { Mobile m = sector.Mobiles[i]; if (m.X == tileX && m.Y == tileY) { mobiles.Add(m); } } int landStartZ = 0, landAvgZ = 0, landTopZ = 0; map.GetAverageZ(tileX, tileY, ref landStartZ, ref landAvgZ, ref landTopZ); bool hasFoundation = false; for (int i = 0; i < addTiles.Length; ++i) { StaticTile addTile = addTiles[i]; if (addTile.ID == 0x1) // Nodraw { continue; } TileFlag addTileFlags = TileData.ItemTable[addTile.ID & TileData.MaxItemValue].Flags; bool isFoundation = addTile.Z == 0 && (addTileFlags & TileFlag.Wall) != 0; bool hasSurface = false; if (isFoundation) { hasFoundation = true; } int addTileZ = center.Z + addTile.Z; int addTileTop = addTileZ + addTile.Height; if ((addTileFlags & TileFlag.Surface) != 0) { addTileTop += 16; } if (addTileTop > landStartZ && landAvgZ > addTileZ) { return(HousePlacementResult.BadLand); // Broke rule #2 } if (isFoundation && (TileData.LandTable[landTile.ID & TileData.MaxLandValue].Flags & TileFlag.Impassable) == 0 && landAvgZ == center.Z) { hasSurface = true; } for (int j = 0; j < oldTiles.Length; ++j) { StaticTile oldTile = oldTiles[j]; ItemData id = TileData.ItemTable[oldTile.ID & TileData.MaxItemValue]; if ((id.Impassable || id.Surface && (id.Flags & TileFlag.Background) == 0) && addTileTop > oldTile.Z && oldTile.Z + id.CalcHeight > addTileZ) { return(HousePlacementResult.BadStatic); // Broke rule #2 } /*else if ( isFoundation && !hasSurface && (id.Flags & TileFlag.Surface) != 0 && (oldTile.Z + id.CalcHeight) == center.Z ) * hasSurface = true;*/ } for (int j = 0; j < items.Count; ++j) { Item item = items[j]; ItemData id = item.ItemData; if (addTileTop > item.Z && item.Z + id.CalcHeight > addTileZ) { if (item.Movable) { toMove.Add(item); } else if (id.Impassable || id.Surface && (id.Flags & TileFlag.Background) == 0) { return(HousePlacementResult.BadItem); // Broke rule #2 } } /*else if ( isFoundation && !hasSurface && (id.Flags & TileFlag.Surface) != 0 && (item.Z + id.CalcHeight) == center.Z ) * { * hasSurface = true; * }*/ } if (isFoundation && !hasSurface) { return(HousePlacementResult.NoSurface); // Broke rule #4 } for (int j = 0; j < mobiles.Count; ++j) { Mobile m = mobiles[j]; if (addTileTop > m.Z && m.Z + 16 > addTileZ) { toMove.Add(m); } } } for (int i = 0; i < m_RoadIDs.Length; i += 2) { if (landID >= m_RoadIDs[i] && landID <= m_RoadIDs[i + 1]) { return(HousePlacementResult.BadLand); // Broke rule #5 } } if (hasFoundation) { for (int xOffset = -1; xOffset <= 1; ++xOffset) { for (int yOffset = -YardSize; yOffset <= YardSize; ++yOffset) { Point2D yardPoint = new Point2D(tileX + xOffset, tileY + yOffset); if (!yard.Contains(yardPoint)) { yard.Add(yardPoint); } } } for (int xOffset = -1; xOffset <= 1; ++xOffset) { for (int yOffset = -1; yOffset <= 1; ++yOffset) { if (xOffset == 0 && yOffset == 0) { continue; } // To ease this rule, we will not add to the border list if the tile here is under a base floor (z<=8) int vx = x + xOffset; int vy = y + yOffset; if (vx >= 0 && vx < mcl.Width && vy >= 0 && vy < mcl.Height) { StaticTile[] breakTiles = mcl.Tiles[vx][vy]; bool shouldBreak = false; for (int i = 0; !shouldBreak && i < breakTiles.Length; ++i) { StaticTile breakTile = breakTiles[i]; if (breakTile.Height == 0 && breakTile.Z <= 8 && TileData.ItemTable[breakTile.ID & TileData.MaxItemValue].Surface) { shouldBreak = true; } } if (shouldBreak) { continue; } } Point2D borderPoint = new Point2D(tileX + xOffset, tileY + yOffset); if (!borders.Contains(borderPoint)) { borders.Add(borderPoint); } } } } } } for (int i = 0; i < borders.Count; ++i) { Point2D borderPoint = borders[i]; LandTile landTile = map.Tiles.GetLandTile(borderPoint.X, borderPoint.Y); int landID = landTile.ID & TileData.MaxLandValue; if ((TileData.LandTable[landID].Flags & TileFlag.Impassable) != 0) { return(HousePlacementResult.BadLand); } for (int j = 0; j < m_RoadIDs.Length; j += 2) { if (landID >= m_RoadIDs[j] && landID <= m_RoadIDs[j + 1]) { return(HousePlacementResult.BadLand); // Broke rule #5 } } StaticTile[] tiles = map.Tiles.GetStaticTiles(borderPoint.X, borderPoint.Y, true); for (int j = 0; j < tiles.Length; ++j) { StaticTile tile = tiles[j]; ItemData id = TileData.ItemTable[tile.ID & TileData.MaxItemValue]; if (id.Impassable || id.Surface && (id.Flags & TileFlag.Background) == 0 && tile.Z + id.CalcHeight > center.Z + 2) { return(HousePlacementResult.BadStatic); // Broke rule #1 } } Sector sector = map.GetSector(borderPoint.X, borderPoint.Y); List <Item> sectorItems = sector.Items; for (int j = 0; j < sectorItems.Count; ++j) { Item item = sectorItems[j]; if (item.X != borderPoint.X || item.Y != borderPoint.Y || item.Movable) { continue; } ItemData id = item.ItemData; if (id.Impassable || id.Surface && (id.Flags & TileFlag.Background) == 0 && item.Z + id.CalcHeight > center.Z + 2) { return(HousePlacementResult.BadItem); // Broke rule #1 } } } List <Sector> _sectors = new List <Sector>(); List <BaseHouse> _houses = new List <BaseHouse>(); for (int i = 0; i < yard.Count; i++) { Sector sector = map.GetSector(yard[i]); if (!_sectors.Contains(sector)) { _sectors.Add(sector); if (sector.Multis != null) { for (int j = 0; j < sector.Multis.Count; j++) { if (sector.Multis[j] is BaseHouse) { BaseHouse _house = (BaseHouse)sector.Multis[j]; if (!_houses.Contains(_house)) { _houses.Add(_house); } } } } } } for (int i = 0; i < yard.Count; ++i) { foreach (BaseHouse b in _houses) { if (b.Contains(yard[i])) { return(HousePlacementResult.BadStatic); // Broke rule #3 } } /*Point2D yardPoint = yard[i]; * * IPooledEnumerable eable = map.GetMultiTilesAt( yardPoint.X, yardPoint.Y ); * * foreach ( StaticTile[] tile in eable ) * { * for ( int j = 0; j < tile.Length; ++j ) * { * if ( (TileData.ItemTable[tile[j].ID & TileData.MaxItemValue].Flags & (TileFlag.Impassable | TileFlag.Surface)) != 0 ) * { * eable.Free(); * return HousePlacementResult.BadStatic; // Broke rule #3 * } * } * } * * eable.Free();*/ } return(HousePlacementResult.Valid); }
public override void Serialize(TextWriter writer, Sector sector) { new Serializer(sector, writer).Serialize(); writer.Flush(); }