new doors

This commit is contained in:
Regalis
2015-05-25 19:41:30 +03:00
parent fadb89ae9e
commit a1196d1876
12 changed files with 3494 additions and 3446 deletions
+578 -572
View File
File diff suppressed because it is too large Load Diff
+436 -436
View File
@@ -1,436 +1,436 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Subsurface
{
class Hull : MapEntity
{
public static List<Hull> hullList = new List<Hull>();
public static bool EditWater;
public static WaterRenderer renderer;
public static bool DebugDraw;
public const float OxygenDistributionSpeed = 500.0f;
public const float OxygenDetoriationSpeed = 0.3f;
public const float OxygenConsumptionSpeed = 1000.0f;
public const int WaveWidth = 16;
const float WaveStiffness = 0.003f;
const float WaveSpread = 0.05f;
const float WaveDampening = 0.01f;
//how much excess water the room can contain (= more than the volume of the room)
public const float MaxCompress = 10000f;
public readonly Dictionary<string, PropertyDescriptor> properties;
float lethalPressure;
float surface;
float volume;
float pressure;
float oxygen;
bool update;
float[] waveY; //displacement from the surface of the water
float[] waveVel; //velocity of the point
float[] leftDelta;
float[] rightDelta;
public override bool IsLinkable
{
get { return true; }
}
public float LethalPressure
{
get { return lethalPressure; }
set { lethalPressure = MathHelper.Clamp(value, 0.0f, 100.0f); }
}
public Vector2 Size
{
get { return new Vector2(rect.Width, rect.Height); }
}
public float Surface
{
get { return surface; }
}
public float Volume
{
get { return volume; }
set
{
volume = MathHelper.Clamp(value, 0.0f, FullVolume + MaxCompress);
if (volume < FullVolume) Pressure = rect.Y - rect.Height + volume / rect.Width;
if (volume > 0.0f) update = true;
}
}
public float Oxygen
{
get { return oxygen; }
set { oxygen = MathHelper.Clamp(value, 0.0f, FullVolume); }
}
public float OxygenPercentage
{
get { return oxygen / FullVolume * 100.0f; }
set { Oxygen = (value / 100.0f) * FullVolume; }
}
public float FullVolume
{
get { return (rect.Width * rect.Height); }
}
public float Pressure
{
get { return pressure; }
set { pressure = value; }
}
public float[] WaveY
{
get { return waveY; }
}
public float[] WaveVel
{
get { return waveVel; }
}
public Hull(Rectangle rectangle)
{
rect = rectangle;
OxygenPercentage = (float)(Game1.random.NextDouble() * 100.0);
properties = TypeDescriptor.GetProperties(this.GetType())
.Cast<PropertyDescriptor>()
.ToDictionary(pr => pr.Name);
int arraySize = (rectangle.Width / WaveWidth + 1);
waveY = new float[arraySize];
waveVel = new float[arraySize];
leftDelta = new float[arraySize];
rightDelta = new float[arraySize];
surface = rect.Y - rect.Height;
aiTarget = new AITarget(this);
aiTarget.SightRange = (rect.Width + rect.Height)*10.0f;
hullList.Add(this);
Item.UpdateHulls();
Gap.UpdateHulls();
Volume = 0.0f;
//add to list of entities as well
mapEntityList.Add(this);
}
public override bool Contains(Vector2 position)
{
return (Map.RectContains(rect, position) &&
!Map.RectContains(new Rectangle(rect.X + 8, rect.Y - 8, rect.Width -16, rect.Height -16), position));
}
public int GetWaveIndex(Vector2 position)
{
int index = (int)(position.X - rect.X) / WaveWidth;
index = MathHelper.Clamp(index, 0, waveY.Length-1);
return index;
}
public override void Move(Vector2 amount)
{
rect.X += (int)amount.X;
rect.Y += (int)amount.Y;
Item.UpdateHulls();
Gap.UpdateHulls();
}
public override void Remove()
{
base.Remove();
Item.UpdateHulls();
Gap.UpdateHulls();
//renderer.Dispose();
hullList.Remove(this);
}
public override void Update(Camera cam, float deltaTime)
{
Oxygen -= OxygenDetoriationSpeed * deltaTime;
if (EditWater)
{
Vector2 position = cam.ScreenToWorld(PlayerInput.MousePosition);
if (Map.RectContains(rect, position))
{
if (PlayerInput.LeftButtonDown())
{
waveY[(int)(position.X - rect.X) / Hull.WaveWidth] = 100.0f;
Volume = Volume + 1500.0f;
}
else if (PlayerInput.GetMouseState.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
Volume = Volume - 1500.0f;
}
}
}
if (!update) return;
float surfaceY = rect.Y - rect.Height + Volume / rect.Width;
for (int i = 0; i < waveY.Length; i++)
{
float maxDelta = Math.Max(Math.Abs(rightDelta[i]), Math.Abs(leftDelta[i]));
if (maxDelta > ToolBox.RandomFloat(0.2f,10.0f))
{
Game1.particleManager.CreateParticle(ConvertUnits.ToSimUnits(new Vector2(rect.X + WaveWidth * i,surface + waveY[i])),
0.0f, new Vector2(0.0f, waveVel[i]/10.0f-1.0f), "mist");
}
waveY[i] = waveY[i] + waveVel[i];
if (surfaceY + waveY[i] > rect.Y)
{
waveY[i] -= (surfaceY + waveY[i]) - rect.Y;
waveVel[i] = waveVel[i] * -0.5f;
}
else if (surfaceY + waveY[i] < rect.Y - rect.Height)
{
waveY[i] -= (surfaceY + waveY[i]) - (rect.Y - rect.Height);
waveVel[i] = waveVel[i] * -0.5f;
}
//acceleration
float a = -WaveStiffness * waveY[i] - waveVel[i] * WaveDampening;
waveVel[i] = waveVel[i] + a;
}
for (int j = 0; j < 2; j++)
{
for (int i = 1; i < waveY.Length - 1; i++)
{
leftDelta[i] = WaveSpread * (waveY[i] - waveY[i - 1]);
waveVel[i - 1] = waveVel[i - 1] + leftDelta[i];
rightDelta[i] = WaveSpread * (waveY[i] - waveY[i + 1]);
waveVel[i + 1] = waveVel[i + 1] + rightDelta[i];
}
for (int i = 1; i < waveY.Length - 1; i++)
{
waveY[i - 1] = waveY[i - 1] + leftDelta[i];
waveY[i + 1] = waveY[i + 1] + rightDelta[i];
}
}
if (volume<FullVolume)
{
LethalPressure -= 0.5f;
if (Volume == 0.0f)
{
for (int i = 1; i < waveY.Length - 1; i++)
{
if (waveY[i] > 0.1f) return;
}
update = false;
}
}
else
{
LethalPressure += 1.0f;
}
}
public override void Draw(SpriteBatch spriteBatch, bool editing)
{
if (!editing && !DebugDraw) return;
GUI.DrawRectangle(spriteBatch,
new Vector2(rect.X, -rect.Y),
new Vector2(rect.Width, rect.Height),
isHighlighted ? Color.Green : Color.Blue);
GUI.DrawRectangle(spriteBatch,
new Rectangle(rect.X, -rect.Y, rect.Width, rect.Height),
Color.Red*((100.0f-OxygenPercentage)/400.0f), true);
spriteBatch.DrawString(GUI.font, "Pressure: " + ((int)pressure - rect.Y).ToString() +
" - Lethality: " + lethalPressure +
" - Oxygen: "+((int)OxygenPercentage).ToString(), new Vector2(rect.X+10, -rect.Y+10), Color.Black);
spriteBatch.DrawString(GUI.font, volume.ToString() +" / "+ FullVolume.ToString(), new Vector2(rect.X+10, -rect.Y+30), Color.Black);
if (isSelected && editing)
{
GUI.DrawRectangle(spriteBatch,
new Vector2(rect.X - 5, -rect.Y - 5),
new Vector2(rect.Width + 10, rect.Height + 10),
Color.Red);
}
}
public void Render(GraphicsDevice graphicsDevice, Camera cam)
{
if (renderer.positionInBuffer > renderer.vertices.Length - 6) return;
//calculate where the surface should be based on the water volume
float top = rect.Y;
float bottom = rect.Y - rect.Height;
float surfaceY = bottom + Volume / rect.Width;
//interpolate the position of the rendered surface towards the "target surface"
surface = surface + (surfaceY - surface) / 10.0f;
Matrix transform =
cam.Transform
* Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f;
if (bottom > cam.WorldView.Y || top < cam.WorldView.Y - cam.WorldView.Height) return;
if (!update)
{
// create the four corners of our triangle.
Vector3 p1 = new Vector3(rect.X, top, 0.0f);
Vector3 p2 = new Vector3(rect.X + rect.Width, top, 0.0f);
Vector3 p3 = new Vector3(p2.X, bottom, 0.0f);
Vector3 p4 = new Vector3(p1.X, bottom, 0.0f);
renderer.vertices[renderer.positionInBuffer] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 1] = new WaterVertex(p2, new Vector2(p2.X, -p2.Y), transform);
renderer.vertices[renderer.positionInBuffer + 2] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 3] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 4] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 5] = new WaterVertex(p4, new Vector2(p4.X, -p4.Y), transform);
renderer.positionInBuffer += 6;
return;
}
int x = rect.X;
int start = (int)Math.Floor((float)(cam.WorldView.X - x) / WaveWidth);
start = Math.Max(start, 0);
int end = (waveY.Length - 1)
- (int)Math.Floor((float)((x + rect.Width) - (cam.WorldView.X + cam.WorldView.Width)) / WaveWidth);
end = Math.Min(end, waveY.Length - 1);
x += start * WaveWidth;
for (int i = start; i < end; i++)
{
if (renderer.positionInBuffer > renderer.vertices.Length - 6) return;
Vector3 p1 = new Vector3(x, top, 0.0f);
Vector3 p4 = new Vector3(p1.X, surface + waveY[i], 0.0f);
//skip adjacent "water rects" if the surface of the water is roughly at the same position
int width = WaveWidth;
while (i<end-1 && Math.Abs(waveY[i + 1] - waveY[i]) < 1.0f)
{
width += WaveWidth;
i++;
}
Vector3 p2 = new Vector3(x + width, top, 0.0f);
Vector3 p3 = new Vector3(p2.X, surface + waveY[i+1], 0.0f);
renderer.vertices[renderer.positionInBuffer] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 1] = new WaterVertex(p2, new Vector2(p2.X, -p2.Y), transform);
renderer.vertices[renderer.positionInBuffer + 2] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 3] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 4] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 5] = new WaterVertex(p4, new Vector2(p4.X, -p4.Y), transform);
renderer.positionInBuffer += 6;
x += width;
}
}
//returns the water block which contains the point (or null if it isn't inside any)
public static Hull FindHull(Vector2 position, Hull guess = null)
{
if (guess != null && hullList.Contains(guess))
{
if (Map.RectContains(guess.rect, position)) return guess;
}
foreach (Hull w in hullList)
{
if (Map.RectContains(w.rect, position)) return w;
}
return null;
}
public override XElement Save(XDocument doc)
{
XElement element = new XElement("Hull");
element.Add(new XAttribute("ID", ID),
new XAttribute("x", rect.X),
new XAttribute("y", rect.Y),
new XAttribute("width", rect.Width),
new XAttribute("height", rect.Height),
new XAttribute("water", volume));
doc.Root.Add(element);
return element;
}
public static void Load(XElement element)
{
Rectangle rect = new Rectangle(
int.Parse(element.Attribute("x").Value),
int.Parse(element.Attribute("y").Value),
int.Parse(element.Attribute("width").Value),
int.Parse(element.Attribute("height").Value));
Hull h = new Hull(rect);
h.volume = ToolBox.GetAttributeFloat(element, "pressure", 0.0f);
h.ID = int.Parse(element.Attribute("ID").Value);
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Xml.Linq;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Subsurface
{
class Hull : MapEntity
{
public static List<Hull> hullList = new List<Hull>();
public static bool EditWater;
public static WaterRenderer renderer;
public static bool DebugDraw;
public const float OxygenDistributionSpeed = 500.0f;
public const float OxygenDetoriationSpeed = 0.3f;
public const float OxygenConsumptionSpeed = 1000.0f;
public const int WaveWidth = 16;
const float WaveStiffness = 0.003f;
const float WaveSpread = 0.05f;
const float WaveDampening = 0.01f;
//how much excess water the room can contain (= more than the volume of the room)
public const float MaxCompress = 10000f;
public readonly Dictionary<string, PropertyDescriptor> properties;
float lethalPressure;
float surface;
float volume;
float pressure;
float oxygen;
bool update;
float[] waveY; //displacement from the surface of the water
float[] waveVel; //velocity of the point
float[] leftDelta;
float[] rightDelta;
public override bool IsLinkable
{
get { return true; }
}
public float LethalPressure
{
get { return lethalPressure; }
set { lethalPressure = MathHelper.Clamp(value, 0.0f, 100.0f); }
}
public Vector2 Size
{
get { return new Vector2(rect.Width, rect.Height); }
}
public float Surface
{
get { return surface; }
}
public float Volume
{
get { return volume; }
set
{
volume = MathHelper.Clamp(value, 0.0f, FullVolume + MaxCompress);
if (volume < FullVolume) Pressure = rect.Y - rect.Height + volume / rect.Width;
if (volume > 0.0f) update = true;
}
}
public float Oxygen
{
get { return oxygen; }
set { oxygen = MathHelper.Clamp(value, 0.0f, FullVolume); }
}
public float OxygenPercentage
{
get { return oxygen / FullVolume * 100.0f; }
set { Oxygen = (value / 100.0f) * FullVolume; }
}
public float FullVolume
{
get { return (rect.Width * rect.Height); }
}
public float Pressure
{
get { return pressure; }
set { pressure = value; }
}
public float[] WaveY
{
get { return waveY; }
}
public float[] WaveVel
{
get { return waveVel; }
}
public Hull(Rectangle rectangle)
{
rect = rectangle;
OxygenPercentage = (float)(Game1.random.NextDouble() * 100.0);
properties = TypeDescriptor.GetProperties(this.GetType())
.Cast<PropertyDescriptor>()
.ToDictionary(pr => pr.Name);
int arraySize = (rectangle.Width / WaveWidth + 1);
waveY = new float[arraySize];
waveVel = new float[arraySize];
leftDelta = new float[arraySize];
rightDelta = new float[arraySize];
surface = rect.Y - rect.Height;
aiTarget = new AITarget(this);
aiTarget.SightRange = (rect.Width + rect.Height)*10.0f;
hullList.Add(this);
Item.UpdateHulls();
Gap.UpdateHulls();
Volume = 0.0f;
//add to list of entities as well
mapEntityList.Add(this);
}
public override bool Contains(Vector2 position)
{
return (Map.RectContains(rect, position) &&
!Map.RectContains(new Rectangle(rect.X + 8, rect.Y - 8, rect.Width - 16, rect.Height - 16), position));
}
public int GetWaveIndex(Vector2 position)
{
int index = (int)(position.X - rect.X) / WaveWidth;
index = MathHelper.Clamp(index, 0, waveY.Length-1);
return index;
}
public override void Move(Vector2 amount)
{
rect.X += (int)amount.X;
rect.Y += (int)amount.Y;
Item.UpdateHulls();
Gap.UpdateHulls();
}
public override void Remove()
{
base.Remove();
Item.UpdateHulls();
Gap.UpdateHulls();
//renderer.Dispose();
hullList.Remove(this);
}
public override void Update(Camera cam, float deltaTime)
{
Oxygen -= OxygenDetoriationSpeed * deltaTime;
if (EditWater)
{
Vector2 position = cam.ScreenToWorld(PlayerInput.MousePosition);
if (Map.RectContains(rect, position))
{
if (PlayerInput.LeftButtonDown())
{
waveY[(int)(position.X - rect.X) / Hull.WaveWidth] = 100.0f;
Volume = Volume + 1500.0f;
}
else if (PlayerInput.GetMouseState.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
{
Volume = Volume - 1500.0f;
}
}
}
if (!update) return;
float surfaceY = rect.Y - rect.Height + Volume / rect.Width;
for (int i = 0; i < waveY.Length; i++)
{
float maxDelta = Math.Max(Math.Abs(rightDelta[i]), Math.Abs(leftDelta[i]));
if (maxDelta > ToolBox.RandomFloat(0.2f,10.0f))
{
Game1.particleManager.CreateParticle(ConvertUnits.ToSimUnits(new Vector2(rect.X + WaveWidth * i,surface + waveY[i])),
ToolBox.RandomFloat(0.0f,6.2f), new Vector2(0.0f, -0.5f), "mist");
}
waveY[i] = waveY[i] + waveVel[i];
if (surfaceY + waveY[i] > rect.Y)
{
waveY[i] -= (surfaceY + waveY[i]) - rect.Y;
waveVel[i] = waveVel[i] * -0.5f;
}
else if (surfaceY + waveY[i] < rect.Y - rect.Height)
{
waveY[i] -= (surfaceY + waveY[i]) - (rect.Y - rect.Height);
waveVel[i] = waveVel[i] * -0.5f;
}
//acceleration
float a = -WaveStiffness * waveY[i] - waveVel[i] * WaveDampening;
waveVel[i] = waveVel[i] + a;
}
for (int j = 0; j < 2; j++)
{
for (int i = 1; i < waveY.Length - 1; i++)
{
leftDelta[i] = WaveSpread * (waveY[i] - waveY[i - 1]);
waveVel[i - 1] = waveVel[i - 1] + leftDelta[i];
rightDelta[i] = WaveSpread * (waveY[i] - waveY[i + 1]);
waveVel[i + 1] = waveVel[i + 1] + rightDelta[i];
}
for (int i = 1; i < waveY.Length - 1; i++)
{
waveY[i - 1] = waveY[i - 1] + leftDelta[i];
waveY[i + 1] = waveY[i + 1] + rightDelta[i];
}
}
if (volume<FullVolume)
{
LethalPressure -= 0.5f;
if (Volume == 0.0f)
{
for (int i = 1; i < waveY.Length - 1; i++)
{
if (waveY[i] > 0.1f) return;
}
update = false;
}
}
else
{
LethalPressure += 1.0f;
}
}
public override void Draw(SpriteBatch spriteBatch, bool editing)
{
if (!editing && !DebugDraw) return;
GUI.DrawRectangle(spriteBatch,
new Vector2(rect.X, -rect.Y),
new Vector2(rect.Width, rect.Height),
isHighlighted ? Color.Green : Color.Blue);
GUI.DrawRectangle(spriteBatch,
new Rectangle(rect.X, -rect.Y, rect.Width, rect.Height),
Color.Red*((100.0f-OxygenPercentage)/400.0f), true);
spriteBatch.DrawString(GUI.font, "Pressure: " + ((int)pressure - rect.Y).ToString() +
" - Lethality: " + lethalPressure +
" - Oxygen: "+((int)OxygenPercentage).ToString(), new Vector2(rect.X+10, -rect.Y+10), Color.Black);
spriteBatch.DrawString(GUI.font, volume.ToString() +" / "+ FullVolume.ToString(), new Vector2(rect.X+10, -rect.Y+30), Color.Black);
if (isSelected && editing)
{
GUI.DrawRectangle(spriteBatch,
new Vector2(rect.X - 5, -rect.Y - 5),
new Vector2(rect.Width + 10, rect.Height + 10),
Color.Red);
}
}
public void Render(GraphicsDevice graphicsDevice, Camera cam)
{
if (renderer.positionInBuffer > renderer.vertices.Length - 6) return;
//calculate where the surface should be based on the water volume
float top = rect.Y;
float bottom = rect.Y - rect.Height;
float surfaceY = bottom + Volume / rect.Width;
//interpolate the position of the rendered surface towards the "target surface"
surface = surface + (surfaceY - surface) / 10.0f;
Matrix transform =
cam.Transform
* Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f;
if (bottom > cam.WorldView.Y || top < cam.WorldView.Y - cam.WorldView.Height) return;
if (!update)
{
// create the four corners of our triangle.
Vector3 p1 = new Vector3(rect.X, top, 0.0f);
Vector3 p2 = new Vector3(rect.X + rect.Width, top, 0.0f);
Vector3 p3 = new Vector3(p2.X, bottom, 0.0f);
Vector3 p4 = new Vector3(p1.X, bottom, 0.0f);
renderer.vertices[renderer.positionInBuffer] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 1] = new WaterVertex(p2, new Vector2(p2.X, -p2.Y), transform);
renderer.vertices[renderer.positionInBuffer + 2] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 3] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 4] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 5] = new WaterVertex(p4, new Vector2(p4.X, -p4.Y), transform);
renderer.positionInBuffer += 6;
return;
}
int x = rect.X;
int start = (int)Math.Floor((float)(cam.WorldView.X - x) / WaveWidth);
start = Math.Max(start, 0);
int end = (waveY.Length - 1)
- (int)Math.Floor((float)((x + rect.Width) - (cam.WorldView.X + cam.WorldView.Width)) / WaveWidth);
end = Math.Min(end, waveY.Length - 1);
x += start * WaveWidth;
for (int i = start; i < end; i++)
{
if (renderer.positionInBuffer > renderer.vertices.Length - 6) return;
Vector3 p1 = new Vector3(x, top, 0.0f);
Vector3 p4 = new Vector3(p1.X, surface + waveY[i], 0.0f);
//skip adjacent "water rects" if the surface of the water is roughly at the same position
int width = WaveWidth;
while (i<end-1 && Math.Abs(waveY[i + 1] - waveY[i]) < 1.0f)
{
width += WaveWidth;
i++;
}
Vector3 p2 = new Vector3(x + width, top, 0.0f);
Vector3 p3 = new Vector3(p2.X, surface + waveY[i+1], 0.0f);
renderer.vertices[renderer.positionInBuffer] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 1] = new WaterVertex(p2, new Vector2(p2.X, -p2.Y), transform);
renderer.vertices[renderer.positionInBuffer + 2] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 3] = new WaterVertex(p1, new Vector2(p1.X, -p1.Y), transform);
renderer.vertices[renderer.positionInBuffer + 4] = new WaterVertex(p3, new Vector2(p3.X, -p3.Y), transform);
renderer.vertices[renderer.positionInBuffer + 5] = new WaterVertex(p4, new Vector2(p4.X, -p4.Y), transform);
renderer.positionInBuffer += 6;
x += width;
}
}
//returns the water block which contains the point (or null if it isn't inside any)
public static Hull FindHull(Vector2 position, Hull guess = null)
{
if (guess != null && hullList.Contains(guess))
{
if (Map.RectContains(guess.rect, position)) return guess;
}
foreach (Hull w in hullList)
{
if (Map.RectContains(w.rect, position)) return w;
}
return null;
}
public override XElement Save(XDocument doc)
{
XElement element = new XElement("Hull");
element.Add(new XAttribute("ID", ID),
new XAttribute("x", rect.X),
new XAttribute("y", rect.Y),
new XAttribute("width", rect.Width),
new XAttribute("height", rect.Height),
new XAttribute("water", volume));
doc.Root.Add(element);
return element;
}
public static void Load(XElement element)
{
Rectangle rect = new Rectangle(
int.Parse(element.Attribute("x").Value),
int.Parse(element.Attribute("y").Value),
int.Parse(element.Attribute("width").Value),
int.Parse(element.Attribute("height").Value));
Hull h = new Hull(rect);
h.volume = ToolBox.GetAttributeFloat(element, "pressure", 0.0f);
h.ID = int.Parse(element.Attribute("ID").Value);
}
}
}
+183 -191
View File
@@ -1,191 +1,183 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Subsurface.Lights
{
class ConvexHull
{
public static List<ConvexHull> list = new List<ConvexHull>();
static BasicEffect drawingEffect;
private VertexPositionColor[] vertices;
private short[] indices;
int primitiveCount;
bool[] backFacing;
VertexPositionColor[] shadowVertices;
public bool Enabled
{
get;
set;
}
//private Vector2 position = Vector2.Zero;
//public Vector2 Position
//{
// get { return position; }
// set { position = value; }
//}
public ConvexHull(Vector2[] points, Color color)
{
int vertexCount = points.Length;
vertices = new VertexPositionColor[vertexCount + 1];
Vector2 center = Vector2.Zero;
for (int i = 0; i < vertexCount; i++)
{
vertices[i] = new VertexPositionColor(new Vector3(points[i], 0), color);
center += points[i];
}
center /= points.Length;
vertices[vertexCount] = new VertexPositionColor(new Vector3(center, 0), color);
primitiveCount = points.Length;
indices = new short[primitiveCount * 3];
for (int i = 0; i < primitiveCount; i++)
{
indices[3 * i] = (short)i;
indices[3 * i + 1] = (short)((i + 1) % vertexCount);
indices[3 * i + 2] = (short)vertexCount;
}
backFacing = new bool[vertexCount];
Enabled = true;
list.Add(this);
}
public void Move(Vector2 amount)
{
for (int i = 0; i < vertices.Count(); i++)
{
vertices[i].Position = new Vector3(vertices[i].Position.X + amount.X, vertices[i].Position.Y + amount.Y, vertices[i].Position.Z);
}
}
public void SetVertices(Vector2[] points)
{
int vertexCount = points.Length;
vertices = new VertexPositionColor[vertexCount + 1];
for (int i = 0; i < vertexCount; i++)
{
vertices[i] = new VertexPositionColor(new Vector3(points[i], 0), Color.Black);
}
}
//public void Draw(GameTime gameTime)
//{
// device.RasterizerState = RasterizerState.CullNone;
// device.BlendState = BlendState.Opaque;
// drawingEffect.World = Matrix.CreateTranslation(position.X, position.Y, 0);
// foreach (EffectPass pass in drawingEffect.CurrentTechnique.Passes)
// {
// pass.Apply();
// device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, primitiveCount);
// }
//}
public void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, Vector2 lightSourcePos)
{
if (!Enabled) return;
if (drawingEffect == null)
{
drawingEffect = new BasicEffect(graphicsDevice);
drawingEffect.VertexColorEnabled = true;
}
//compute facing of each edge, using N*L
for (int i = 0; i < primitiveCount; i++)
{
Vector2 firstVertex = new Vector2(vertices[i].Position.X, vertices[i].Position.Y);
int secondIndex = (i + 1) % primitiveCount;
Vector2 secondVertex = new Vector2(vertices[secondIndex].Position.X, vertices[secondIndex].Position.Y);
Vector2 middle = (firstVertex + secondVertex) / 2;
Vector2 L = lightSourcePos - middle;
Vector2 N = new Vector2();
N.X = -(secondVertex.Y - firstVertex.Y);
N.Y = secondVertex.X - firstVertex.X;
backFacing[i] = (Vector2.Dot(N, L) < 0);
}
//find beginning and ending vertices which
//belong to the shadow
int startingIndex = 0;
int endingIndex = 0;
for (int i = 0; i < primitiveCount; i++)
{
int currentEdge = i;
int nextEdge = (i + 1) % primitiveCount;
if (backFacing[currentEdge] && !backFacing[nextEdge])
endingIndex = nextEdge;
if (!backFacing[currentEdge] && backFacing[nextEdge])
startingIndex = nextEdge;
}
int shadowVertexCount;
//nr of vertices that are in the shadow
if (endingIndex > startingIndex)
shadowVertexCount = endingIndex - startingIndex + 1;
else
shadowVertexCount = primitiveCount + 1 - startingIndex + endingIndex;
shadowVertices = new VertexPositionColor[shadowVertexCount * 2];
//create a triangle strip that has the shape of the shadow
int currentIndex = startingIndex;
int svCount = 0;
while (svCount != shadowVertexCount * 2)
{
Vector3 vertexPos = vertices[currentIndex].Position;
//one vertex on the hull
shadowVertices[svCount] = new VertexPositionColor();
shadowVertices[svCount].Color = Color.Black;
shadowVertices[svCount].Position = vertexPos;
//one extruded by the light direction
shadowVertices[svCount + 1] = new VertexPositionColor();
shadowVertices[svCount + 1].Color = Color.Black;
Vector3 L2P = vertexPos - new Vector3(lightSourcePos, 0);
L2P.Normalize();
shadowVertices[svCount + 1].Position = new Vector3(lightSourcePos, 0) + L2P * 9000;
svCount += 2;
currentIndex = (currentIndex + 1) % primitiveCount;
}
drawingEffect.World = cam.ShaderTransform
* Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f;
drawingEffect.CurrentTechnique.Passes[0].Apply();
graphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, shadowVertices, 0, shadowVertexCount * 2 - 2);
}
public void Remove()
{
list.Remove(this);
}
}
}
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Subsurface.Lights
{
class ConvexHull
{
public static List<ConvexHull> list = new List<ConvexHull>();
static BasicEffect drawingEffect;
private VertexPositionColor[] vertices;
private short[] indices;
int primitiveCount;
bool[] backFacing;
VertexPositionColor[] shadowVertices;
public bool Enabled
{
get;
set;
}
public ConvexHull(Vector2[] points, Color color)
{
int vertexCount = points.Length;
vertices = new VertexPositionColor[vertexCount + 1];
Vector2 center = Vector2.Zero;
for (int i = 0; i < vertexCount; i++)
{
vertices[i] = new VertexPositionColor(new Vector3(points[i], 0), color);
center += points[i];
}
center /= points.Length;
vertices[vertexCount] = new VertexPositionColor(new Vector3(center, 0), color);
primitiveCount = points.Length;
indices = new short[primitiveCount * 3];
for (int i = 0; i < primitiveCount; i++)
{
indices[3 * i] = (short)i;
indices[3 * i + 1] = (short)((i + 1) % vertexCount);
indices[3 * i + 2] = (short)vertexCount;
}
backFacing = new bool[vertexCount];
Enabled = true;
list.Add(this);
}
public void Move(Vector2 amount)
{
for (int i = 0; i < vertices.Count(); i++)
{
vertices[i].Position = new Vector3(vertices[i].Position.X + amount.X, vertices[i].Position.Y + amount.Y, vertices[i].Position.Z);
}
}
public void SetVertices(Vector2[] points)
{
int vertexCount = points.Length;
vertices = new VertexPositionColor[vertexCount + 1];
for (int i = 0; i < vertexCount; i++)
{
vertices[i] = new VertexPositionColor(new Vector3(points[i], 0), Color.Black);
}
}
//public void Draw(GameTime gameTime)
//{
// device.RasterizerState = RasterizerState.CullNone;
// device.BlendState = BlendState.Opaque;
// drawingEffect.World = Matrix.CreateTranslation(position.X, position.Y, 0);
// foreach (EffectPass pass in drawingEffect.CurrentTechnique.Passes)
// {
// pass.Apply();
// device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, primitiveCount);
// }
//}
public void DrawShadows(GraphicsDevice graphicsDevice, Camera cam, Vector2 lightSourcePos)
{
if (!Enabled) return;
if (drawingEffect == null)
{
drawingEffect = new BasicEffect(graphicsDevice);
drawingEffect.VertexColorEnabled = true;
}
//compute facing of each edge, using N*L
for (int i = 0; i < primitiveCount; i++)
{
Vector2 firstVertex = new Vector2(vertices[i].Position.X, vertices[i].Position.Y);
int secondIndex = (i + 1) % primitiveCount;
Vector2 secondVertex = new Vector2(vertices[secondIndex].Position.X, vertices[secondIndex].Position.Y);
Vector2 middle = (firstVertex + secondVertex) / 2;
Vector2 L = lightSourcePos - middle;
Vector2 N = new Vector2();
N.X = -(secondVertex.Y - firstVertex.Y);
N.Y = secondVertex.X - firstVertex.X;
backFacing[i] = (Vector2.Dot(N, L) < 0);
}
//find beginning and ending vertices which
//belong to the shadow
int startingIndex = 0;
int endingIndex = 0;
for (int i = 0; i < primitiveCount; i++)
{
int currentEdge = i;
int nextEdge = (i + 1) % primitiveCount;
if (backFacing[currentEdge] && !backFacing[nextEdge])
endingIndex = nextEdge;
if (!backFacing[currentEdge] && backFacing[nextEdge])
startingIndex = nextEdge;
}
int shadowVertexCount;
//nr of vertices that are in the shadow
if (endingIndex > startingIndex)
shadowVertexCount = endingIndex - startingIndex + 1;
else
shadowVertexCount = primitiveCount + 1 - startingIndex + endingIndex;
shadowVertices = new VertexPositionColor[shadowVertexCount * 2];
//create a triangle strip that has the shape of the shadow
int currentIndex = startingIndex;
int svCount = 0;
while (svCount != shadowVertexCount * 2)
{
Vector3 vertexPos = vertices[currentIndex].Position;
//one vertex on the hull
shadowVertices[svCount] = new VertexPositionColor();
shadowVertices[svCount].Color = Color.Black;
shadowVertices[svCount].Position = vertexPos;
//one extruded by the light direction
shadowVertices[svCount + 1] = new VertexPositionColor();
shadowVertices[svCount + 1].Color = Color.Black;
Vector3 L2P = vertexPos - new Vector3(lightSourcePos, 0);
L2P.Normalize();
shadowVertices[svCount + 1].Position = new Vector3(lightSourcePos, 0) + L2P * 9000;
svCount += 2;
currentIndex = (currentIndex + 1) % primitiveCount;
}
drawingEffect.World = cam.ShaderTransform
* Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f;
drawingEffect.CurrentTechnique.Passes[0].Apply();
graphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, shadowVertices, 0, shadowVertexCount * 2 - 2);
}
public void Remove()
{
list.Remove(this);
}
}
}
+398 -381
View File
@@ -1,381 +1,398 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using FarseerPhysics.Collision;
namespace Subsurface
{
public enum Direction : byte
{
None = 0, Left = 1, Right = 2
}
static class Map
{
public static Vector2 gridSize = new Vector2(16.0f, 16.0f);
private static Vector2 lastPickedPosition;
private static float lastPickedFraction;
private static Rectangle borders;
private static string filePath;
public static Vector2 LastPickedPosition
{
get { return lastPickedPosition; }
}
public static float LastPickedFraction
{
get { return lastPickedFraction; }
}
public static Rectangle Borders
{
get { return borders; }
}
public static string FilePath
{
get { return filePath; }
}
public static void Draw(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++ )
{
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static void DrawFront(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++)
{
if (MapEntity.mapEntityList[i].sprite == null || MapEntity.mapEntityList[i].sprite.Depth < 0.5f)
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static void DrawBack(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++)
{
if (MapEntity.mapEntityList[i].sprite == null || MapEntity.mapEntityList[i].sprite.Depth >= 0.5f)
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static Vector2 MouseToWorldGrid(Camera cam)
{
Vector2 position = new Vector2(PlayerInput.GetMouseState.X, PlayerInput.GetMouseState.Y);
position = cam.ScreenToWorld(position);
return VectorToWorldGrid(position);
}
public static Vector2 VectorToWorldGrid(Vector2 position)
{
position.X = (float)Math.Floor(Convert.ToDouble(position.X / gridSize.X)) * gridSize.X;
position.Y = (float)Math.Ceiling(Convert.ToDouble(position.Y / gridSize.Y)) * gridSize.Y;
return position;
}
public static Rectangle AbsRect(Vector2 pos, Vector2 size)
{
if (size.X < 0.0f)
{
pos.X += size.X;
size.X = -size.X;
}
if (size.Y < 0.0f)
{
pos.Y -= size.Y;
size.Y = -size.Y;
}
return new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
}
public static bool RectContains(Rectangle rect, Vector2 pos)
{
return (pos.X > rect.X && pos.X < rect.X + rect.Width
&& pos.Y < rect.Y && pos.Y > rect.Y - rect.Height);
}
public static bool RectsOverlap(Rectangle rect1, Rectangle rect2)
{
return !(rect1.X > rect2.X + rect2.Width || rect1.X + rect1.Width < rect2.X ||
rect1.Y < rect2.Y - rect2.Height || rect1.Y - rect1.Height > rect2.Y);
}
public static Body PickBody(Vector2 rayStart, Vector2 rayEnd, List<Body> ignoredBodies = null)
{
float closestFraction = 1.0f;
Body closestBody = null;
Game1.world.RayCast((fixture, point, normal, fraction) =>
{
if (fixture == null || fixture.CollisionCategories == Category.None) return -1;
if (ignoredBodies != null && ignoredBodies.Contains(fixture.Body)) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null && (structure.IsPlatform || !structure.HasBody)) return -1;
if (fraction < closestFraction)
{
closestFraction = fraction;
if (fixture.Body!=null) closestBody = fixture.Body;
}
return fraction;
}
, rayStart, rayEnd);
lastPickedPosition = rayStart + (rayEnd - rayStart) * closestFraction;
lastPickedFraction = closestFraction;
return closestBody;
}
public static Structure CheckVisibility(Vector2 rayStart, Vector2 rayEnd)
{
Structure closestStructure = null;
float closestFraction = 1.0f;
if (Vector2.Distance(rayStart,rayEnd)<0.01f)
{
closestFraction = 0.01f;
return null;
}
Game1.world.RayCast((fixture, point, normal, fraction) =>
{
if (fixture == null || fixture.CollisionCategories != Physics.CollisionWall) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null)
{
if (structure.IsPlatform || structure.StairDirection != Direction.None) return -1;
int sectionIndex = structure.FindSectionIndex(ConvertUnits.ToDisplayUnits(point));
if (sectionIndex > -1 && structure.SectionHasHole(sectionIndex)) return -1;
}
if (fraction < closestFraction)
{
if (structure != null) closestStructure = structure;
closestFraction = fraction;
}
return closestFraction;
}
, rayStart, rayEnd);
lastPickedPosition = rayStart + (rayEnd - rayStart) * closestFraction;
lastPickedFraction = closestFraction;
return closestStructure;
}
public static Body PickBody(Vector2 point)
{
Body foundBody = null;
AABB aabb = new AABB(point, point);
Game1.world.QueryAABB(p =>
{
foundBody = p.Body;
return true;
}, ref aabb);
return foundBody;
}
public static bool InsideWall(Vector2 point)
{
Body foundBody = Map.PickBody(point);
if (foundBody==null) return false;
Structure wall = foundBody.UserData as Structure;
if (wall == null || wall.IsPlatform) return false;
return true;
}
public static void Save(string filePath, string fileName)
{
if (fileName==null)
{
DebugConsole.ThrowError("No save file selected");
return;
}
XDocument doc = new XDocument(
new XElement((XName)fileName));
foreach (MapEntity e in MapEntity.mapEntityList)
{
e.Save(doc);
}
try
{
string docString = doc.ToString();
ToolBox.CompressStringToFile(filePath+fileName+".gz", doc.ToString());
}
catch
{
DebugConsole.ThrowError("Saving map ''" + filePath + fileName + "'' failed!");
}
//doc.Save(filePath + fileName);
}
public static string[] GetMapFilePaths()
{
string[] mapFilePaths;
try
{
mapFilePaths = Directory.GetFiles("Content/SavedMaps");
}
catch (Exception e)
{
DebugConsole.ThrowError("Couldn't open directory ''Content/SavedMaps''!", e);
return null;
}
return mapFilePaths;
}
public static void Load(string filePath, string fileName)
{
Load(filePath + fileName);
}
public static void Load(string file)
{
Clear();
filePath = file;
XDocument doc = null;
string extension = Path.GetExtension(file);
if (extension==".gz")
{
Stream stream = ToolBox.DecompressFiletoStream(file);
if (stream == null)
{
DebugConsole.ThrowError("Loading map ''" + file + "'' failed!");
return;
}
try
{
stream.Position = 0;
doc = XDocument.Load(stream); //ToolBox.TryLoadXml(file);
stream.Close();
stream.Dispose();
}
catch
{
DebugConsole.ThrowError("Loading map ''" + file + "'' failed!");
return;
}
}
else if (extension ==".xml")
{
doc = XDocument.Load(file);
}
else
{
DebugConsole.ThrowError("Couldn't load map ''"+file+"! (Unrecognized file extension)");
return;
}
foreach (XElement element in doc.Root.Elements())
{
string typeName = element.Name.ToString();
Type t;
try
{
// Get the type of a specified class.
t = Type.GetType("Subsurface." + typeName + ", Subsurface", true, true);
if (t == null)
{
DebugConsole.ThrowError("Error in " + file + "! Could not find a entity of the type ''" + typeName + "''.");
continue;
}
}
catch (Exception e)
{
DebugConsole.ThrowError("Error in " + file + "! Could not find a entity of the type ''" + typeName + "''.", e);
continue;
}
try
{
MethodInfo loadMethod = t.GetMethod("Load");
loadMethod.Invoke(t, new object[] { element });
}
catch (Exception e)
{
DebugConsole.ThrowError("Could not find the method ''Load'' in " + t + ".", e);
}
}
borders = new Rectangle(0, 0, 1, 1);
foreach (Hull hull in Hull.hullList)
{
if (hull.Rect.X < borders.X || borders.X == 0) borders.X = hull.Rect.X;
if (hull.Rect.Y > borders.Y || borders.Y == 0) borders.Y = hull.Rect.Y;
if (hull.Rect.X + hull.Rect.Width > borders.X + borders.Width) borders.Width = hull.Rect.X + hull.Rect.Width - borders.X;
if (hull.Rect.Y - hull.Rect.Height < borders.Y - borders.Height) borders.Height = borders.Y - (hull.Rect.Y - hull.Rect.Height);
}
MapEntity.LinkAll();
foreach (Item item in Item.itemList)
{
foreach (ItemComponent ic in item.components)
{
ic.OnMapLoaded();
}
}
}
public static void Clear()
{
Map.filePath = "";
if (Game1.gameScreen.Cam != null) Game1.gameScreen.Cam.TargetPos = Vector2.Zero;
Entity.RemoveAll();
if (Game1.gameSession!=null)
Game1.gameSession.crewManager.EndShift();
PhysicsBody.list.Clear();
Ragdoll.list.Clear();
Game1.world.Clear();
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using FarseerPhysics.Collision;
namespace Subsurface
{
public enum Direction : byte
{
None = 0, Left = 1, Right = 2
}
static class Map
{
static string MapFolder = "Content/SavedMaps";
public static Vector2 gridSize = new Vector2(16.0f, 16.0f);
private static Vector2 lastPickedPosition;
private static float lastPickedFraction;
private static Rectangle borders;
private static string filePath;
public static Vector2 LastPickedPosition
{
get { return lastPickedPosition; }
}
public static float LastPickedFraction
{
get { return lastPickedFraction; }
}
public static Rectangle Borders
{
get { return borders; }
}
public static string FilePath
{
get { return filePath; }
}
public static void Draw(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++ )
{
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static void DrawFront(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++)
{
if (MapEntity.mapEntityList[i].sprite == null || MapEntity.mapEntityList[i].sprite.Depth < 0.5f)
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static void DrawBack(SpriteBatch spriteBatch, bool editing = false)
{
for (int i = 0; i < MapEntity.mapEntityList.Count(); i++)
{
if (MapEntity.mapEntityList[i].sprite == null || MapEntity.mapEntityList[i].sprite.Depth >= 0.5f)
MapEntity.mapEntityList[i].Draw(spriteBatch, editing);
}
}
public static Vector2 MouseToWorldGrid(Camera cam)
{
Vector2 position = new Vector2(PlayerInput.GetMouseState.X, PlayerInput.GetMouseState.Y);
position = cam.ScreenToWorld(position);
return VectorToWorldGrid(position);
}
public static Vector2 VectorToWorldGrid(Vector2 position)
{
position.X = (float)Math.Floor(Convert.ToDouble(position.X / gridSize.X)) * gridSize.X;
position.Y = (float)Math.Ceiling(Convert.ToDouble(position.Y / gridSize.Y)) * gridSize.Y;
return position;
}
public static Rectangle AbsRect(Vector2 pos, Vector2 size)
{
if (size.X < 0.0f)
{
pos.X += size.X;
size.X = -size.X;
}
if (size.Y < 0.0f)
{
pos.Y -= size.Y;
size.Y = -size.Y;
}
return new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
}
public static bool RectContains(Rectangle rect, Vector2 pos)
{
return (pos.X > rect.X && pos.X < rect.X + rect.Width
&& pos.Y < rect.Y && pos.Y > rect.Y - rect.Height);
}
public static bool RectsOverlap(Rectangle rect1, Rectangle rect2)
{
return !(rect1.X > rect2.X + rect2.Width || rect1.X + rect1.Width < rect2.X ||
rect1.Y < rect2.Y - rect2.Height || rect1.Y - rect1.Height > rect2.Y);
}
public static Body PickBody(Vector2 rayStart, Vector2 rayEnd, List<Body> ignoredBodies = null)
{
float closestFraction = 1.0f;
Body closestBody = null;
Game1.world.RayCast((fixture, point, normal, fraction) =>
{
if (fixture == null || fixture.CollisionCategories == Category.None) return -1;
if (ignoredBodies != null && ignoredBodies.Contains(fixture.Body)) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null && (structure.IsPlatform || !structure.HasBody)) return -1;
if (fraction < closestFraction)
{
closestFraction = fraction;
if (fixture.Body!=null) closestBody = fixture.Body;
}
return fraction;
}
, rayStart, rayEnd);
lastPickedPosition = rayStart + (rayEnd - rayStart) * closestFraction;
lastPickedFraction = closestFraction;
return closestBody;
}
public static Structure CheckVisibility(Vector2 rayStart, Vector2 rayEnd)
{
Structure closestStructure = null;
float closestFraction = 1.0f;
if (Vector2.Distance(rayStart,rayEnd)<0.01f)
{
closestFraction = 0.01f;
return null;
}
Game1.world.RayCast((fixture, point, normal, fraction) =>
{
if (fixture == null || fixture.CollisionCategories != Physics.CollisionWall) return -1;
Structure structure = fixture.Body.UserData as Structure;
if (structure != null)
{
if (structure.IsPlatform || structure.StairDirection != Direction.None) return -1;
int sectionIndex = structure.FindSectionIndex(ConvertUnits.ToDisplayUnits(point));
if (sectionIndex > -1 && structure.SectionHasHole(sectionIndex)) return -1;
}
if (fraction < closestFraction)
{
if (structure != null) closestStructure = structure;
closestFraction = fraction;
}
return closestFraction;
}
, rayStart, rayEnd);
lastPickedPosition = rayStart + (rayEnd - rayStart) * closestFraction;
lastPickedFraction = closestFraction;
return closestStructure;
}
public static Body PickBody(Vector2 point)
{
Body foundBody = null;
AABB aabb = new AABB(point, point);
Game1.world.QueryAABB(p =>
{
foundBody = p.Body;
return true;
}, ref aabb);
return foundBody;
}
public static bool InsideWall(Vector2 point)
{
Body foundBody = Map.PickBody(point);
if (foundBody==null) return false;
Structure wall = foundBody.UserData as Structure;
if (wall == null || wall.IsPlatform) return false;
return true;
}
public static void Save(string filePath, string fileName)
{
if (fileName==null)
{
DebugConsole.ThrowError("No save file selected");
return;
}
XDocument doc = new XDocument(
new XElement((XName)fileName));
foreach (MapEntity e in MapEntity.mapEntityList)
{
e.Save(doc);
}
try
{
string docString = doc.ToString();
ToolBox.CompressStringToFile(filePath+fileName+".gz", doc.ToString());
}
catch
{
DebugConsole.ThrowError("Saving map ''" + filePath + fileName + "'' failed!");
}
//doc.Save(filePath + fileName);
}
public static string[] GetMapFilePaths()
{
string[] mapFilePaths;
if (!Directory.Exists(MapFolder))
{
try
{
Directory.CreateDirectory(MapFolder);
}
catch
{
DebugConsole.ThrowError("Directory ''Content/SavedMaps'' not found and creating the directory failed.");
return null;
}
}
try
{
mapFilePaths = Directory.GetFiles(MapFolder);
}
catch (Exception e)
{
DebugConsole.ThrowError("Couldn't open directory ''Content/SavedMaps''!", e);
return null;
}
return mapFilePaths;
}
public static void Load(string filePath, string fileName)
{
Load(filePath + fileName);
}
public static void Load(string file)
{
Clear();
filePath = file;
XDocument doc = null;
string extension = Path.GetExtension(file);
if (extension==".gz")
{
Stream stream = ToolBox.DecompressFiletoStream(file);
if (stream == null)
{
DebugConsole.ThrowError("Loading map ''" + file + "'' failed!");
return;
}
try
{
stream.Position = 0;
doc = XDocument.Load(stream); //ToolBox.TryLoadXml(file);
stream.Close();
stream.Dispose();
}
catch
{
DebugConsole.ThrowError("Loading map ''" + file + "'' failed!");
return;
}
}
else if (extension ==".xml")
{
doc = XDocument.Load(file);
}
else
{
DebugConsole.ThrowError("Couldn't load map ''"+file+"! (Unrecognized file extension)");
return;
}
foreach (XElement element in doc.Root.Elements())
{
string typeName = element.Name.ToString();
Type t;
try
{
// Get the type of a specified class.
t = Type.GetType("Subsurface." + typeName + ", Subsurface", true, true);
if (t == null)
{
DebugConsole.ThrowError("Error in " + file + "! Could not find a entity of the type ''" + typeName + "''.");
continue;
}
}
catch (Exception e)
{
DebugConsole.ThrowError("Error in " + file + "! Could not find a entity of the type ''" + typeName + "''.", e);
continue;
}
try
{
MethodInfo loadMethod = t.GetMethod("Load");
loadMethod.Invoke(t, new object[] { element });
}
catch (Exception e)
{
DebugConsole.ThrowError("Could not find the method ''Load'' in " + t + ".", e);
}
}
borders = new Rectangle(0, 0, 1, 1);
foreach (Hull hull in Hull.hullList)
{
if (hull.Rect.X < borders.X || borders.X == 0) borders.X = hull.Rect.X;
if (hull.Rect.Y > borders.Y || borders.Y == 0) borders.Y = hull.Rect.Y;
if (hull.Rect.X + hull.Rect.Width > borders.X + borders.Width) borders.Width = hull.Rect.X + hull.Rect.Width - borders.X;
if (hull.Rect.Y - hull.Rect.Height < borders.Y - borders.Height) borders.Height = borders.Y - (hull.Rect.Y - hull.Rect.Height);
}
MapEntity.LinkAll();
foreach (Item item in Item.itemList)
{
foreach (ItemComponent ic in item.components)
{
ic.OnMapLoaded();
}
}
}
public static void Clear()
{
Map.filePath = "";
if (Game1.gameScreen.Cam != null) Game1.gameScreen.Cam.TargetPos = Vector2.Zero;
Entity.RemoveAll();
if (Game1.gameSession!=null)
Game1.gameSession.crewManager.EndShift();
PhysicsBody.list.Clear();
Ragdoll.list.Clear();
Game1.world.Clear();
}
}
}