GUIStyle improvements & some simple UI graphics, networking bugfixes, separate Random class, some StyleCop cleanup

This commit is contained in:
Regalis
2015-07-02 22:24:50 +03:00
parent b493ed2b39
commit d836a99515
119 changed files with 8842 additions and 1277 deletions
+7
View File
@@ -0,0 +1,7 @@
<stylecopresultscache>
<version>12</version>
<project key="427911471">
<configuration>
</configuration>
</project>
</stylecopresultscache>
+8 -15
View File
@@ -6,27 +6,22 @@ namespace Subsurface
{ {
public class Camera public class Camera
{ {
float zoom;
const float DefaultZoom = 1.0f; const float DefaultZoom = 1.0f;
const float ZoomSmoothness = 8.0f; const float ZoomSmoothness = 8.0f;
const float MoveSmoothness = 8.0f; const float MoveSmoothness = 8.0f;
float offsetAmount; private float zoom;
Matrix transform; private float offsetAmount;
Matrix shaderTransform;
Matrix viewMatrix; private Matrix transform, shaderTransform, viewMatrix;
private Vector2 position; private Vector2 position;
float rotation; private float rotation;
//the area of the world inside the camera view //the area of the world inside the camera view
//used by the sprite drawing functions to determine whether private Rectangle worldView;
//a sprite should be drawn
Rectangle worldView;
Point resolution; private Point resolution;
private Vector2 targetPos; private Vector2 targetPos;
@@ -35,7 +30,6 @@ namespace Subsurface
get { return zoom; } get { return zoom; }
set set
{ {
//prevZoom = zoom;
zoom = value; zoom = value;
if (zoom < 0.1f) zoom = 0.1f; if (zoom < 0.1f) zoom = 0.1f;
@@ -46,8 +40,8 @@ namespace Subsurface
float newHeight = resolution.Y / zoom; float newHeight = resolution.Y / zoom;
worldView = new Rectangle( worldView = new Rectangle(
(int)(center.X - newWidth/2.0f), (int)(center.X - newWidth / 2.0f),
(int)(center.Y - newHeight/2.0f), (int)(center.Y - newHeight / 2.0f),
(int)newWidth, (int)newWidth,
(int)newHeight); (int)newHeight);
@@ -110,7 +104,6 @@ namespace Subsurface
resolution = new Point(Game1.GraphicsWidth, Game1.GraphicsHeight); resolution = new Point(Game1.GraphicsWidth, Game1.GraphicsHeight);
viewMatrix = viewMatrix =
//Matrix.CreateRotationZ(Rotation) *
Matrix.CreateTranslation(new Vector3(Game1.GraphicsWidth / 2.0f, Game1.GraphicsHeight / 2.0f, 0)); Matrix.CreateTranslation(new Vector3(Game1.GraphicsWidth / 2.0f, Game1.GraphicsHeight / 2.0f, 0));
} }
+6 -6
View File
@@ -9,7 +9,7 @@ namespace Subsurface
public enum AiState { None, Attack, GoTo, Escape } public enum AiState { None, Attack, GoTo, Escape }
public enum SteeringState { Wander, Seek, Escape } public enum SteeringState { Wander, Seek, Escape }
public Character character; public Character Character;
protected AiState state; protected AiState state;
@@ -17,18 +17,18 @@ namespace Subsurface
public Vector2 Steering public Vector2 Steering
{ {
get { return character.animController.TargetMovement; } get { return Character.AnimController.TargetMovement; }
set { character.animController.TargetMovement = value; } set { Character.AnimController.TargetMovement = value; }
} }
public Vector2 Position public Vector2 Position
{ {
get { return character.animController.limbs[0].SimPosition; } get { return Character.AnimController.limbs[0].SimPosition; }
} }
public Vector2 Velocity public Vector2 Velocity
{ {
get { return character.animController.limbs[0].LinearVelocity; } get { return Character.AnimController.limbs[0].LinearVelocity; }
} }
public AiState State public AiState State
@@ -38,7 +38,7 @@ namespace Subsurface
public AIController (Character c) public AIController (Character c)
{ {
character = c; Character = c;
steeringManager = new SteeringManager(this); steeringManager = new SteeringManager(this);
} }
+6 -7
View File
@@ -5,14 +5,13 @@ namespace Subsurface
{ {
class AITarget class AITarget
{ {
public static List<AITarget> list = new List<AITarget>(); public static List<AITarget> List = new List<AITarget>();
public Entity Entity;
protected float soundRange; protected float soundRange;
protected float sightRange; protected float sightRange;
public Entity entity;
public float SoundRange public float SoundRange
{ {
get get
@@ -30,18 +29,18 @@ namespace Subsurface
public Vector2 Position public Vector2 Position
{ {
get { return entity.SimPosition; } get { return Entity.SimPosition; }
} }
public AITarget(Entity e) public AITarget(Entity e)
{ {
entity = e; Entity = e;
list.Add(this); List.Add(this);
} }
public void Remove() public void Remove()
{ {
list.Remove(this); List.Remove(this);
} }
} }
+37 -36
View File
@@ -11,7 +11,12 @@ namespace Subsurface
{ {
class EnemyAIController : AIController class EnemyAIController : AIController
{ //the preference to attack a specific type of target (-1.0 - 1.0) {
private const float UpdateTargetsInterval = 5.0f;
private const float RaycastInterval = 1.0f;
//the preference to attack a specific type of target (-1.0 - 1.0)
//0.0 = doesn't attack targets of the type //0.0 = doesn't attack targets of the type
//positive values = attacks targets of this type //positive values = attacks targets of this type
//negative values = escapes targets of this type //negative values = escapes targets of this type
@@ -20,13 +25,9 @@ namespace Subsurface
private float attackWeaker; private float attackWeaker;
private float attackStronger; private float attackStronger;
private float updateTargetsTimer; private float updateTargetsTimer;
private const float UpdateTargetsInterval = 5.0f;
private float raycastTimer; private float raycastTimer;
private const float RaycastInterval = 1.0f;
private Vector2 prevPosition; private Vector2 prevPosition;
private float distanceAccumulator; private float distanceAccumulator;
@@ -85,7 +86,7 @@ namespace Subsurface
{ {
UpdateDistanceAccumulator(); UpdateDistanceAccumulator();
character.animController.IgnorePlatforms = (-character.animController.TargetMovement.Y > Math.Abs(character.animController.TargetMovement.X)); Character.AnimController.IgnorePlatforms = (-Character.AnimController.TargetMovement.Y > Math.Abs(Character.AnimController.TargetMovement.X));
if (updateTargetsTimer > 0.0) if (updateTargetsTimer > 0.0)
{ {
@@ -94,7 +95,7 @@ namespace Subsurface
else else
{ {
System.Diagnostics.Debug.WriteLine("updatetargets"); System.Diagnostics.Debug.WriteLine("updatetargets");
UpdateTargets(character); UpdateTargets(Character);
updateTargetsTimer = UpdateTargetsInterval; updateTargetsTimer = UpdateTargetsInterval;
if (selectedTarget == null) if (selectedTarget == null)
@@ -136,7 +137,7 @@ namespace Subsurface
private void UpdateDistanceAccumulator() private void UpdateDistanceAccumulator()
{ {
Limb limb = character.animController.limbs[0]; Limb limb = Character.AnimController.limbs[0];
distanceAccumulator += (limb.SimPosition - prevPosition).Length(); distanceAccumulator += (limb.SimPosition - prevPosition).Length();
prevPosition = limb.body.Position; prevPosition = limb.body.Position;
@@ -178,10 +179,10 @@ namespace Subsurface
//check if any of the limbs is close enough to attack the target //check if any of the limbs is close enough to attack the target
if (attackingLimb == null) if (attackingLimb == null)
{ {
foreach (Limb limb in character.animController.limbs) foreach (Limb limb in Character.AnimController.limbs)
{ {
if (limb.attack==null || limb.attack.type == Attack.Type.None) continue; if (limb.attack==null || limb.attack.Type == AttackType.None) continue;
if (Vector2.Distance(limb.SimPosition, attackPosition) > limb.attack.range) continue; if (Vector2.Distance(limb.SimPosition, attackPosition) > limb.attack.Range) continue;
attackingLimb = limb; attackingLimb = limb;
break; break;
@@ -200,8 +201,8 @@ namespace Subsurface
//System.Diagnostics.Debug.WriteLine("cooldown"); //System.Diagnostics.Debug.WriteLine("cooldown");
if (selectedTarget.entity is Hull || if (selectedTarget.Entity is Hull ||
Vector2.Distance(attackPosition, character.animController.limbs[0].SimPosition) < ConvertUnits.ToSimUnits(500.0f)) Vector2.Distance(attackPosition, Character.AnimController.limbs[0].SimPosition) < ConvertUnits.ToSimUnits(500.0f))
{ {
steeringManager.SteeringSeek(attackPosition, -0.8f); steeringManager.SteeringSeek(attackPosition, -0.8f);
steeringManager.SteeringAvoid(deltaTime, 1.0f); steeringManager.SteeringAvoid(deltaTime, 1.0f);
@@ -217,7 +218,7 @@ namespace Subsurface
{ {
targetEntity = null; targetEntity = null;
//check if there's a wall between the target and the character //check if there's a wall between the target and the character
Vector2 rayStart = character.animController.limbs[0].SimPosition; Vector2 rayStart = Character.AnimController.limbs[0].SimPosition;
Vector2 rayEnd = selectedTarget.Position; Vector2 rayEnd = selectedTarget.Position;
Body closestBody = Submarine.CheckVisibility(rayStart, rayEnd); Body closestBody = Submarine.CheckVisibility(rayStart, rayEnd);
@@ -257,12 +258,12 @@ namespace Subsurface
{ {
IDamageable damageTarget = null; IDamageable damageTarget = null;
switch (limb.attack.type) switch (limb.attack.Type)
{ {
case Attack.Type.PinchCW: case AttackType.PinchCW:
case Attack.Type.PinchCCW: case AttackType.PinchCCW:
float dir = (limb.attack.type == Attack.Type.PinchCW) ? 1.0f : -1.0f; float dir = (limb.attack.Type == AttackType.PinchCW) ? 1.0f : -1.0f;
float dist = Vector2.Distance(limb.SimPosition, attackPosition); float dist = Vector2.Distance(limb.SimPosition, attackPosition);
if (wallAttackPos != Vector2.Zero && targetEntity != null) if (wallAttackPos != Vector2.Zero && targetEntity != null)
@@ -271,21 +272,21 @@ namespace Subsurface
} }
else else
{ {
damageTarget = selectedTarget.entity as IDamageable; damageTarget = selectedTarget.Entity as IDamageable;
} }
attackTimer += deltaTime*0.05f; attackTimer += deltaTime*0.05f;
if (damageTarget == null) if (damageTarget == null)
{ {
attackTimer = limb.attack.duration; attackTimer = limb.attack.Duration;
break; break;
} }
if (dist < limb.attack.range * 0.5f) if (dist < limb.attack.Range * 0.5f)
{ {
attackTimer += deltaTime; attackTimer += deltaTime;
limb.body.ApplyTorque(limb.Mass * 50.0f * character.animController.Dir * dir); limb.body.ApplyTorque(limb.Mass * 50.0f * Character.AnimController.Dir * dir);
limb.attack.DoDamage(damageTarget, limb.SimPosition, deltaTime, (limb.soundTimer <= 0.0f)); limb.attack.DoDamage(damageTarget, limb.SimPosition, deltaTime, (limb.soundTimer <= 0.0f));
@@ -303,11 +304,11 @@ namespace Subsurface
break; break;
default: default:
attackTimer = limb.attack.duration; attackTimer = limb.attack.Duration;
break; break;
} }
if (attackTimer >= limb.attack.duration) if (attackTimer >= limb.attack.Duration)
{ {
attackTimer = 0.0f; attackTimer = 0.0f;
if (Vector2.Distance(limb.SimPosition, attackPosition)<5.0) coolDownTimer = attackCoolDown; if (Vector2.Distance(limb.SimPosition, attackPosition)<5.0) coolDownTimer = attackCoolDown;
@@ -320,10 +321,10 @@ namespace Subsurface
//sight/hearing range //sight/hearing range
public void UpdateTargets(Character character) public void UpdateTargets(Character character)
{ {
if (distanceAccumulator<5.0f && Game1.random.Next(1,3)==1) if (distanceAccumulator<5.0f && Rand.Range(1,3, false)==1)
{ {
selectedTarget = null; selectedTarget = null;
character.animController.TargetMovement = -character.animController.TargetMovement; character.AnimController.TargetMovement = -character.AnimController.TargetMovement;
state = AiState.None; state = AiState.None;
return; return;
} }
@@ -335,35 +336,35 @@ namespace Subsurface
UpdateTargetMemories(); UpdateTargetMemories();
foreach (AITarget target in AITarget.list) foreach (AITarget target in AITarget.List)
{ {
float valueModifier = 0.0f; float valueModifier = 0.0f;
float dist = 0.0f; float dist = 0.0f;
IDamageable targetDamageable = target.entity as IDamageable; IDamageable targetDamageable = target.Entity as IDamageable;
if (targetDamageable!=null && targetDamageable.Health <= 0.0f) continue; if (targetDamageable!=null && targetDamageable.Health <= 0.0f) continue;
Character targetCharacter = target.entity as Character; Character targetCharacter = target.Entity as Character;
//ignore the aitarget if it is the character itself //ignore the aitarget if it is the character itself
if (targetCharacter == character) continue; if (targetCharacter == character) continue;
if (targetCharacter!=null) if (targetCharacter!=null)
{ {
if (attackHumans == 0.0f || targetCharacter.speciesName != "human") continue; if (attackHumans == 0.0f || targetCharacter.SpeciesName != "human") continue;
valueModifier = attackHumans; valueModifier = attackHumans;
} }
else if (target.entity!=null && attackRooms!=0.0f) else if (target.Entity!=null && attackRooms!=0.0f)
{ {
//skip the target if it's the room the character is inside of //skip the target if it's the room the character is inside of
if (character.animController.CurrentHull != null && character.animController.CurrentHull == target.entity as Hull) continue; if (character.AnimController.CurrentHull != null && character.AnimController.CurrentHull == target.Entity as Hull) continue;
valueModifier = attackRooms; valueModifier = attackRooms;
} }
dist = Vector2.Distance( dist = Vector2.Distance(
character.animController.limbs[0].SimPosition, character.AnimController.limbs[0].SimPosition,
target.Position); target.Position);
dist = ConvertUnits.ToDisplayUnits(dist); dist = ConvertUnits.ToDisplayUnits(dist);
@@ -374,7 +375,7 @@ namespace Subsurface
if (Math.Abs(valueModifier) > Math.Abs(targetValue) && (dist < target.SightRange * sight || dist < target.SoundRange * hearing)) if (Math.Abs(valueModifier) > Math.Abs(targetValue) && (dist < target.SightRange * sight || dist < target.SoundRange * hearing))
{ {
Vector2 rayStart = character.animController.limbs[0].SimPosition; Vector2 rayStart = character.AnimController.limbs[0].SimPosition;
Vector2 rayEnd = target.Position; Vector2 rayEnd = target.Position;
Body closestBody = Submarine.CheckVisibility(rayStart, rayEnd); Body closestBody = Submarine.CheckVisibility(rayStart, rayEnd);
@@ -414,7 +415,7 @@ namespace Subsurface
selectedTargetMemory = targetMemory; selectedTargetMemory = targetMemory;
targetValue = valueModifier; targetValue = valueModifier;
Debug.WriteLine(selectedTarget.entity+": "+targetValue); Debug.WriteLine(selectedTarget.Entity+": "+targetValue);
} }
} }
} }
@@ -448,7 +449,7 @@ namespace Subsurface
foreach(KeyValuePair<AITarget, AITargetMemory> memory in targetMemories) foreach(KeyValuePair<AITarget, AITargetMemory> memory in targetMemories)
{ {
memory.Value.Priority += 0.5f; memory.Value.Priority += 0.5f;
if (memory.Value.Priority == 0.0f || !AITarget.list.Contains(memory.Key)) toBeRemoved.Add(memory.Key); if (memory.Value.Priority == 0.0f || !AITarget.List.Contains(memory.Key)) toBeRemoved.Add(memory.Key);
} }
foreach (AITarget target in toBeRemoved) foreach (AITarget target in toBeRemoved)
+4 -4
View File
@@ -32,7 +32,7 @@ namespace Subsurface
{ {
this.host = host; this.host = host;
wanderAngle = MathUtils.RandomFloatLocal(0.0f, MathHelper.TwoPi); wanderAngle = Rand.Range(0.0f, MathHelper.TwoPi);
} }
public void SteeringSeek(Vector2 target, float speed = 1.0f) public void SteeringSeek(Vector2 target, float speed = 1.0f)
@@ -90,7 +90,7 @@ namespace Subsurface
float angleChange = 1.5f; float angleChange = 1.5f;
wanderAngle += MathUtils.RandomFloatLocal(0.0f, 1.0f) * angleChange - angleChange * 0.5f; wanderAngle += Rand.Range(0.0f, 1.0f) * angleChange - angleChange * 0.5f;
Vector2 newSteering = circleCenter + displacement; Vector2 newSteering = circleCenter + displacement;
float steeringSpeed = (newSteering + host.Steering).Length(); float steeringSpeed = (newSteering + host.Steering).Length();
@@ -106,9 +106,9 @@ namespace Subsurface
{ {
if (steering == Vector2.Zero || host.Steering == Vector2.Zero) return Vector2.Zero; if (steering == Vector2.Zero || host.Steering == Vector2.Zero) return Vector2.Zero;
float MaxDistance = 2.0f; float maxDistance = 2.0f;
Vector2 ahead = host.Position + Vector2.Normalize(host.Steering)*MaxDistance; Vector2 ahead = host.Position + Vector2.Normalize(host.Steering)*maxDistance;
if (rayCastTimer <= 0.0f) if (rayCastTimer <= 0.0f)
{ {
+2 -2
View File
@@ -7,7 +7,7 @@ namespace Subsurface
{ {
private Queue<Vector2> nodes; private Queue<Vector2> nodes;
const float minDistance = 0.1f; const float MinDistance = 0.1f;
Vector2 currentNode; Vector2 currentNode;
@@ -30,7 +30,7 @@ namespace Subsurface
public Vector2 GetNode(Vector2 pos) public Vector2 GetNode(Vector2 pos)
{ {
if (nodes.Count == 0) return Vector2.Zero; if (nodes.Count == 0) return Vector2.Zero;
if (currentNode==Vector2.Zero || Vector2.Distance(pos, currentNode)<minDistance) currentNode = nodes.Dequeue(); if (currentNode == Vector2.Zero || Vector2.Distance(pos, currentNode) < MinDistance) currentNode = nodes.Dequeue();
return currentNode; return currentNode;
} }
+6 -6
View File
@@ -6,17 +6,17 @@ namespace Subsurface
{ {
class AnimController : Ragdoll class AnimController : Ragdoll
{ {
protected Character character; public bool IsStanding;
public bool isStanding;
public enum Animation { None, Climbing, UsingConstruction, Struggle }; public enum Animation { None, Climbing, UsingConstruction, Struggle };
public Animation anim; public Animation Anim;
public Direction TargetDir;
protected Character character;
protected float walkSpeed, swimSpeed; protected float walkSpeed, swimSpeed;
public Direction targetDir;
//how large impacts the character can take before being stunned //how large impacts the character can take before being stunned
//protected float impactTolerance; //protected float impactTolerance;
+38 -38
View File
@@ -1,48 +1,48 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq; using System.Xml.Linq;
namespace Subsurface namespace Subsurface
{ {
public enum DamageType { None, Blunt, Slash }; public enum DamageType { None, Blunt, Slash }
public enum AttackType
{
None, PinchCW, PinchCCW
}
struct AttackResult struct AttackResult
{ {
public readonly float damage; public readonly float Damage;
public readonly float bleeding; public readonly float Bleeding;
public readonly bool hitArmor; public readonly bool HitArmor;
public AttackResult(float damage, float bleeding, bool hitArmor=false) public AttackResult(float damage, float bleeding, bool hitArmor=false)
{ {
this.damage = damage; this.Damage = damage;
this.bleeding = bleeding; this.Bleeding = bleeding;
this.hitArmor = hitArmor; this.HitArmor = hitArmor;
} }
} }
class Attack class Attack
{ {
public enum Type
{
None, PinchCW, PinchCCW
};
public readonly Type type;
public readonly float range;
public readonly float duration;
public readonly DamageType damageType; public readonly AttackType Type;
public readonly float Range;
public readonly float Duration;
public readonly float structureDamage; public readonly DamageType DamageType;
public readonly float damage;
public readonly float bleedingDamage;
public readonly float stun; public readonly float StructureDamage;
public readonly float Damage;
public readonly float BleedingDamage;
public readonly float Stun;
private float priority; private float priority;
@@ -50,62 +50,62 @@ namespace Subsurface
{ {
try try
{ {
type = (Type)Enum.Parse(typeof(Type), element.Attribute("type").Value, true); Type = (AttackType)Enum.Parse(typeof(AttackType), element.Attribute("type").Value, true);
} }
catch catch
{ {
type = Type.None; Type = AttackType.None;
} }
try try
{ {
damageType = (DamageType)Enum.Parse(typeof(DamageType), ToolBox.GetAttributeString(element, "damagetype", "None"), true); DamageType = (DamageType)Enum.Parse(typeof(DamageType), ToolBox.GetAttributeString(element, "damagetype", "None"), true);
} }
catch catch
{ {
damageType = DamageType.None; DamageType = DamageType.None;
} }
damage = ToolBox.GetAttributeFloat(element, "damage", 0.0f); Damage = ToolBox.GetAttributeFloat(element, "damage", 0.0f);
structureDamage = ToolBox.GetAttributeFloat(element, "structuredamage", 0.0f); StructureDamage = ToolBox.GetAttributeFloat(element, "structuredamage", 0.0f);
bleedingDamage = ToolBox.GetAttributeFloat(element, "bleedingdamage", 0.0f); BleedingDamage = ToolBox.GetAttributeFloat(element, "bleedingdamage", 0.0f);
stun = ToolBox.GetAttributeFloat(element, "stun", 0.0f); Stun = ToolBox.GetAttributeFloat(element, "stun", 0.0f);
range = FarseerPhysics.ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "range", 0.0f)); Range = FarseerPhysics.ConvertUnits.ToSimUnits(ToolBox.GetAttributeFloat(element, "range", 0.0f));
duration = ToolBox.GetAttributeFloat(element, "duration", 0.0f); Duration = ToolBox.GetAttributeFloat(element, "duration", 0.0f);
priority = ToolBox.GetAttributeFloat(element, "priority", 1.0f); priority = ToolBox.GetAttributeFloat(element, "priority", 1.0f);
} }
public AttackResult DoDamage(IDamageable target, Vector2 position, float deltaTime, bool playSound=true) public AttackResult DoDamage(IDamageable target, Vector2 position, float deltaTime, bool playSound = true)
{ {
float damageAmount = 0.0f; float damageAmount = 0.0f;
//DamageSoundType damageSoundType = DamageSoundType.None; //DamageSoundType damageSoundType = DamageSoundType.None;
if (target as Character == null) if (target as Character == null)
{ {
damageAmount = structureDamage; damageAmount = StructureDamage;
//damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.StructureBlunt: DamageSoundType.StructureSlash; //damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.StructureBlunt: DamageSoundType.StructureSlash;
} }
else else
{ {
damageAmount = damage; damageAmount = Damage;
//damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.LimbBlunt : DamageSoundType.LimbSlash; //damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.LimbBlunt : DamageSoundType.LimbSlash;
} }
//damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.StructureBlunt : DamageSoundType.StructureSlash; //damageSoundType = (damageType == DamageType.Blunt) ? DamageSoundType.StructureBlunt : DamageSoundType.StructureSlash;
//if (playSound) AmbientSoundManager.PlayDamageSound(damageSoundType, damageAmount, position); //if (playSound) AmbientSoundManager.PlayDamageSound(damageSoundType, damageAmount, position);
if (duration > 0.0f) damageAmount *= deltaTime; if (Duration > 0.0f) damageAmount *= deltaTime;
float bleedingAmount = (duration == 0.0f) ? bleedingDamage : bleedingDamage * deltaTime; float bleedingAmount = (Duration == 0.0f) ? BleedingDamage : BleedingDamage * deltaTime;
if (damageAmount > 0.0f) if (damageAmount > 0.0f)
{ {
return target.AddDamage(position, damageType, damageAmount, bleedingAmount, stun, playSound); return target.AddDamage(position, DamageType, damageAmount, bleedingAmount, Stun, playSound);
} }
else else
{ {
+155 -141
View File
@@ -16,11 +16,11 @@ namespace Subsurface
{ {
class Character : Entity, IDamageable, IPropertyObject class Character : Entity, IDamageable, IPropertyObject
{ {
public static List<Character> characterList = new List<Character>(); public static List<Character> CharacterList = new List<Character>();
public static Queue<CharacterInfo> newCharacterQueue = new Queue<CharacterInfo>(); public static Queue<CharacterInfo> NewCharacterQueue = new Queue<CharacterInfo>();
public static bool disableControls; public static bool DisableControls;
//the character that the player is currently controlling //the character that the player is currently controlling
private static Character controlled; private static Character controlled;
@@ -35,14 +35,14 @@ namespace Subsurface
private Inventory inventory; private Inventory inventory;
public double lastNetworkUpdate; public double LastNetworkUpdate;
public byte largeUpdateTimer; public byte LargeUpdateTimer;
public readonly Dictionary<string, ObjectProperty> properties; public readonly Dictionary<string, ObjectProperty> Properties;
public Dictionary<string, ObjectProperty> ObjectProperties public Dictionary<string, ObjectProperty> ObjectProperties
{ {
get { return properties; } get { return Properties; }
} }
protected Key selectKeyHit; protected Key selectKeyHit;
@@ -52,7 +52,7 @@ namespace Subsurface
private Item selectedConstruction; private Item selectedConstruction;
private Item[] selectedItems; private Item[] selectedItems;
public AnimController animController; public AnimController AnimController;
private AIController aiController; private AIController aiController;
private Vector2 cursorPosition; private Vector2 cursorPosition;
@@ -71,9 +71,9 @@ namespace Subsurface
bool isHumanoid; bool isHumanoid;
//the name of the species (e.q. human) //the name of the species (e.q. human)
public readonly string speciesName; public readonly string SpeciesName;
public CharacterInfo info; public CharacterInfo Info;
protected float soundTimer; protected float soundTimer;
protected float soundInterval; protected float soundInterval;
@@ -89,7 +89,7 @@ namespace Subsurface
{ {
get get
{ {
return speciesName; return SpeciesName;
} }
} }
@@ -251,12 +251,12 @@ namespace Subsurface
public override Vector2 SimPosition public override Vector2 SimPosition
{ {
get { return animController.limbs[0].SimPosition; } get { return AnimController.limbs[0].SimPosition; }
} }
public Vector2 Position public Vector2 Position
{ {
get { return ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition); } get { return ConvertUnits.ToDisplayUnits(AnimController.limbs[0].SimPosition); }
} }
public Character(string file) : this(file, Vector2.Zero, null) public Character(string file) : this(file, Vector2.Zero, null)
@@ -269,7 +269,7 @@ namespace Subsurface
} }
public Character(CharacterInfo characterInfo, Vector2 position, bool isNetworkPlayer = false) public Character(CharacterInfo characterInfo, Vector2 position, bool isNetworkPlayer = false)
: this(characterInfo.file, position, characterInfo, isNetworkPlayer) : this(characterInfo.File, position, characterInfo, isNetworkPlayer)
{ {
} }
@@ -289,33 +289,33 @@ namespace Subsurface
//blood = 100.0f; //blood = 100.0f;
aiTarget = new AITarget(this); aiTarget = new AITarget(this);
properties = ObjectProperty.GetProperties(this); Properties = ObjectProperty.GetProperties(this);
info = characterInfo==null ? new CharacterInfo(file) : characterInfo; Info = characterInfo==null ? new CharacterInfo(file) : characterInfo;
XDocument doc = ToolBox.TryLoadXml(file); XDocument doc = ToolBox.TryLoadXml(file);
if (doc == null) return; if (doc == null) return;
speciesName = ToolBox.GetAttributeString(doc.Root, "name", "Unknown"); SpeciesName = ToolBox.GetAttributeString(doc.Root, "name", "Unknown");
isHumanoid = ToolBox.GetAttributeBool(doc.Root, "humanoid", false); isHumanoid = ToolBox.GetAttributeBool(doc.Root, "humanoid", false);
if (isHumanoid) if (isHumanoid)
{ {
animController = new HumanoidAnimController(this, doc.Root.Element("ragdoll")); AnimController = new HumanoidAnimController(this, doc.Root.Element("ragdoll"));
animController.targetDir = Direction.Right; AnimController.TargetDir = Direction.Right;
inventory = new CharacterInventory(10, this); inventory = new CharacterInventory(10, this);
} }
else else
{ {
animController = new FishAnimController(this, doc.Root.Element("ragdoll")); AnimController = new FishAnimController(this, doc.Root.Element("ragdoll"));
PressureProtection = 100.0f; PressureProtection = 100.0f;
//FishAnimController fishAnim = (FishAnimController)animController; //FishAnimController fishAnim = (FishAnimController)animController;
aiController = new EnemyAIController(this, file); aiController = new EnemyAIController(this, file);
} }
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
limb.body.SetTransform(position+limb.SimPosition, 0.0f); limb.body.SetTransform(position+limb.SimPosition, 0.0f);
//limb.prevPosition = ConvertUnits.ToDisplayUnits(position); //limb.prevPosition = ConvertUnits.ToDisplayUnits(position);
@@ -329,44 +329,40 @@ namespace Subsurface
soundInterval = ToolBox.GetAttributeFloat(doc.Root, "soundinterval", 10.0f); soundInterval = ToolBox.GetAttributeFloat(doc.Root, "soundinterval", 10.0f);
var xSounds = doc.Root.Elements("sound").ToList(); var soundElements = doc.Root.Elements("sound").ToList();
if (xSounds.Any()) if (soundElements.Any())
{ {
sounds = new Sound[xSounds.Count()]; sounds = new Sound[soundElements.Count()];
soundStates = new AIController.AiState[xSounds.Count()]; soundStates = new AIController.AiState[soundElements.Count()];
int i = 0; int i = 0;
foreach (XElement xSound in xSounds) foreach (XElement soundElement in soundElements)
{ {
sounds[i] = Sound.Load(xSound.Attribute("file").Value); sounds[i] = Sound.Load(soundElement.Attribute("file").Value);
if (xSound.Attribute("state") == null) if (soundElement.Attribute("state") == null)
{ {
soundStates[i] = AIController.AiState.None; soundStates[i] = AIController.AiState.None;
} }
else else
{ {
soundStates[i] = (AIController.AiState)Enum.Parse( soundStates[i] = (AIController.AiState)Enum.Parse(
typeof(AIController.AiState), xSound.Attribute("state").Value, true); typeof(AIController.AiState), soundElement.Attribute("state").Value, true);
} }
i++; i++;
} }
} }
animController.FindHull(); AnimController.FindHull();
//if (info.ID >= 0) //if (info.ID >= 0)
//{ //{
// ID = info.ID; // ID = info.ID;
//} //}
characterList.Add(this); CharacterList.Add(this);
} }
public void Control(float deltaTime, Camera cam, bool forcePick = false)
/// <summary>
/// Control the characte
/// </summary>
public void Control(float deltaTime, Camera cam, bool forcePick=false)
{ {
if (isDead) return; if (isDead) return;
@@ -416,7 +412,7 @@ namespace Subsurface
private Item FindClosestItem(Vector2 mouseSimPos) private Item FindClosestItem(Vector2 mouseSimPos)
{ {
Limb torso = animController.GetLimb(LimbType.Torso); Limb torso = AnimController.GetLimb(LimbType.Torso);
Vector2 pos = (torso.body.TargetPosition != Vector2.Zero) ? torso.body.TargetPosition : torso.SimPosition; Vector2 pos = (torso.body.TargetPosition != Vector2.Zero) ? torso.body.TargetPosition : torso.SimPosition;
return Item.FindPickable(pos, selectedConstruction == null ? mouseSimPos : selectedConstruction.SimPosition, null, selectedItems); return Item.FindPickable(pos, selectedConstruction == null ? mouseSimPos : selectedConstruction.SimPosition, null, selectedItems);
@@ -433,13 +429,13 @@ namespace Subsurface
// return; // return;
//} //}
Limb head = animController.GetLimb(LimbType.Head); Limb head = AnimController.GetLimb(LimbType.Head);
Lights.LightManager.viewPos = ConvertUnits.ToDisplayUnits(head.SimPosition); Lights.LightManager.ViewPos = ConvertUnits.ToDisplayUnits(head.SimPosition);
Vector2 targetMovement = Vector2.Zero; Vector2 targetMovement = Vector2.Zero;
if (!disableControls) if (!DisableControls)
{ {
if (PlayerInput.KeyDown(Keys.W)) targetMovement.Y += 1.0f; if (PlayerInput.KeyDown(Keys.W)) targetMovement.Y += 1.0f;
if (PlayerInput.KeyDown(Keys.S)) targetMovement.Y -= 1.0f; if (PlayerInput.KeyDown(Keys.S)) targetMovement.Y -= 1.0f;
@@ -448,13 +444,13 @@ namespace Subsurface
//the vertical component is only used for falling through platforms and climbing ladders when not in water, //the vertical component is only used for falling through platforms and climbing ladders when not in water,
//so the movement can't be normalized or the character would walk slower when pressing down/up //so the movement can't be normalized or the character would walk slower when pressing down/up
if (animController.InWater) if (AnimController.InWater)
{ {
float length = targetMovement.Length(); float length = targetMovement.Length();
if (length > 0.0f) targetMovement = targetMovement / length; if (length > 0.0f) targetMovement = targetMovement / length;
} }
if (Keyboard.GetState().IsKeyDown(Keys.LeftShift) && Math.Sign(targetMovement.X) == Math.Sign(animController.Dir)) if (Keyboard.GetState().IsKeyDown(Keys.LeftShift) && Math.Sign(targetMovement.X) == Math.Sign(AnimController.Dir))
targetMovement *= 3.0f; targetMovement *= 3.0f;
selectKeyHit.SetState(PlayerInput.KeyHit(Keys.E)); selectKeyHit.SetState(PlayerInput.KeyHit(Keys.E));
@@ -472,53 +468,53 @@ namespace Subsurface
secondaryKeyDown.SetState(false); secondaryKeyDown.SetState(false);
} }
animController.TargetMovement = targetMovement; AnimController.TargetMovement = targetMovement;
animController.isStanding = true; AnimController.IsStanding = true;
if (moveCam) if (moveCam)
{ {
cam.TargetPos = ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition); cam.TargetPos = ConvertUnits.ToDisplayUnits(AnimController.limbs[0].SimPosition);
cam.OffsetAmount = 250.0f; cam.OffsetAmount = 250.0f;
} }
cursorPosition = cam.ScreenToWorld(PlayerInput.MousePosition); cursorPosition = cam.ScreenToWorld(PlayerInput.MousePosition);
Vector2 mouseSimPos = ConvertUnits.ToSimUnits(cursorPosition); Vector2 mouseSimPos = ConvertUnits.ToSimUnits(cursorPosition);
if (animController.onGround && if (AnimController.onGround &&
!animController.InWater && !AnimController.InWater &&
animController.anim != AnimController.Animation.UsingConstruction) AnimController.Anim != AnimController.Animation.UsingConstruction)
{ {
if (mouseSimPos.X < head.SimPosition.X-1.0f) if (mouseSimPos.X < head.SimPosition.X-1.0f)
{ {
animController.targetDir = Direction.Left; AnimController.TargetDir = Direction.Left;
} }
else if (mouseSimPos.X > head.SimPosition.X + 1.0f) else if (mouseSimPos.X > head.SimPosition.X + 1.0f)
{ {
animController.targetDir = Direction.Right; AnimController.TargetDir = Direction.Right;
} }
} }
disableControls = false; DisableControls = false;
} }
public static void UpdateAnimAll(float deltaTime) public static void UpdateAnimAll(float deltaTime)
{ {
foreach (Character c in characterList) foreach (Character c in CharacterList)
{ {
if (c.isDead) continue; if (c.isDead) continue;
c.animController.UpdateAnim(deltaTime); c.AnimController.UpdateAnim(deltaTime);
} }
} }
public static void UpdateAll(Camera cam, float deltaTime) public static void UpdateAll(Camera cam, float deltaTime)
{ {
if (newCharacterQueue.Count>0) if (NewCharacterQueue.Count>0)
{ {
new Character(newCharacterQueue.Dequeue(), Vector2.Zero); new Character(NewCharacterQueue.Dequeue(), Vector2.Zero);
} }
foreach (Character c in characterList) foreach (Character c in CharacterList)
{ {
c.Update(cam, deltaTime); c.Update(cam, deltaTime);
} }
@@ -531,14 +527,14 @@ namespace Subsurface
if (controlled == this) if (controlled == this)
{ {
cam.Zoom = MathHelper.Lerp(cam.Zoom, 1.5f, 0.1f); cam.Zoom = MathHelper.Lerp(cam.Zoom, 1.5f, 0.1f);
cam.TargetPos = ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition); cam.TargetPos = ConvertUnits.ToDisplayUnits(AnimController.limbs[0].SimPosition);
cam.OffsetAmount = 0.0f; cam.OffsetAmount = 0.0f;
} }
return; return;
} }
if (PressureProtection==0.0f && if (PressureProtection==0.0f &&
(animController.CurrentHull == null || animController.CurrentHull.LethalPressure >= 100.0f)) (AnimController.CurrentHull == null || AnimController.CurrentHull.LethalPressure >= 100.0f))
{ {
Implode(); Implode();
return; return;
@@ -553,18 +549,18 @@ namespace Subsurface
if (needsAir) if (needsAir)
{ {
if (animController.HeadInWater) if (AnimController.HeadInWater)
{ {
Oxygen -= deltaTime*100.0f / drowningTime; Oxygen -= deltaTime*100.0f / drowningTime;
} }
else if (animController.CurrentHull != null) else if (AnimController.CurrentHull != null)
{ {
float hullOxygen = animController.CurrentHull.OxygenPercentage; float hullOxygen = AnimController.CurrentHull.OxygenPercentage;
hullOxygen -= 30.0f; hullOxygen -= 30.0f;
Oxygen += deltaTime * 100.0f * (hullOxygen / 500.0f); Oxygen += deltaTime * 100.0f * (hullOxygen / 500.0f);
animController.CurrentHull.Oxygen -= Hull.OxygenConsumptionSpeed * deltaTime; AnimController.CurrentHull.Oxygen -= Hull.OxygenConsumptionSpeed * deltaTime;
} }
PressureProtection -= deltaTime*100.0f; PressureProtection -= deltaTime*100.0f;
} }
@@ -593,12 +589,12 @@ namespace Subsurface
//distance is approximated based on the mass of the character //distance is approximated based on the mass of the character
//(which corresponds to size because all the characters have the same limb density) //(which corresponds to size because all the characters have the same limb density)
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
aiTarget.SightRange += limb.Mass * 1000.0f; aiTarget.SightRange += limb.Mass * 1000.0f;
} }
//the faster the character is moving, the easier it is to see it //the faster the character is moving, the easier it is to see it
Limb torso = animController.GetLimb(LimbType.Torso); Limb torso = AnimController.GetLimb(LimbType.Torso);
if (torso !=null) if (torso !=null)
{ {
aiTarget.SightRange += torso.LinearVelocity.Length() * 500.0f; aiTarget.SightRange += torso.LinearVelocity.Length() * 500.0f;
@@ -607,13 +603,13 @@ namespace Subsurface
public void Draw(SpriteBatch spriteBatch) public void Draw(SpriteBatch spriteBatch)
{ {
animController.Draw(spriteBatch); AnimController.Draw(spriteBatch);
if (IsNetworkPlayer) if (IsNetworkPlayer)
{ {
Vector2 namePos = new Vector2(Position.X, -Position.Y - 80.0f) - GUI.font.MeasureString(info.name) * 0.5f; Vector2 namePos = new Vector2(Position.X, -Position.Y - 80.0f) - GUI.font.MeasureString(Info.Name) * 0.5f;
spriteBatch.DrawString(GUI.font, info.name, namePos - new Vector2(1.0f, 1.0f), Color.Black); spriteBatch.DrawString(GUI.font, Info.Name, namePos - new Vector2(1.0f, 1.0f), Color.Black);
spriteBatch.DrawString(GUI.font, info.name, namePos, Color.White); spriteBatch.DrawString(GUI.font, Info.Name, namePos, Color.White);
} }
if (this == Character.controlled) return; if (this == Character.controlled) return;
@@ -622,7 +618,9 @@ namespace Subsurface
GUI.DrawRectangle(spriteBatch, new Rectangle((int)healthBarPos.X-2, (int)healthBarPos.Y-2, 100+4, 15+4), Color.Black, false); GUI.DrawRectangle(spriteBatch, new Rectangle((int)healthBarPos.X-2, (int)healthBarPos.Y-2, 100+4, 15+4), Color.Black, false);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)healthBarPos.X, (int)healthBarPos.Y, (int)(100.0f*(health/maxHealth)), 15), Color.Red, true); GUI.DrawRectangle(spriteBatch, new Rectangle((int)healthBarPos.X, (int)healthBarPos.Y, (int)(100.0f*(health/maxHealth)), 15), Color.Red, true);
//spriteBatch.DrawString(GUI.font, ID.ToString(), ConvertUnits.ToDisplayUnits(animController.limbs[0].Position), Color.White); Vector2 pos = ConvertUnits.ToDisplayUnits(AnimController.limbs[0].SimPosition);
pos.Y = -pos.Y;
spriteBatch.DrawString(GUI.font, ID.ToString(), pos, Color.White);
//GUI.DrawLine(spriteBatch, ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition.X, animController.limbs[0].SimPosition.Y), //GUI.DrawLine(spriteBatch, ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition.X, animController.limbs[0].SimPosition.Y),
// ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition.X, animController.limbs[0].SimPosition.Y) + // ConvertUnits.ToDisplayUnits(animController.limbs[0].SimPosition.X, animController.limbs[0].SimPosition.Y) +
// ConvertUnits.ToDisplayUnits(animController.targetMovement.X, animController.targetMovement.Y), Color.Green); // ConvertUnits.ToDisplayUnits(animController.targetMovement.X, animController.targetMovement.Y), Color.Green);
@@ -681,7 +679,7 @@ namespace Subsurface
if (sounds == null || !sounds.Any()) return; if (sounds == null || !sounds.Any()) return;
var matchingSoundStates = soundStates.Where(x => x == state).ToList(); var matchingSoundStates = soundStates.Where(x => x == state).ToList();
int selectedSound = Game1.localRandom.Next(matchingSoundStates.Count()); int selectedSound = Rand.Int(matchingSoundStates.Count());
int n = 0; int n = 0;
for (int i = 0; i < sounds.Count(); i++) for (int i = 0; i < sounds.Count(); i++)
@@ -690,7 +688,7 @@ namespace Subsurface
if (n == selectedSound) if (n == selectedSound)
{ {
sounds[i].Play(1.0f, 2000.0f, sounds[i].Play(1.0f, 2000.0f,
animController.limbs[0].body.FarseerBody); AnimController.limbs[0].body.FarseerBody);
Debug.WriteLine("playing: " + sounds[i]); Debug.WriteLine("playing: " + sounds[i]);
return; return;
} }
@@ -700,11 +698,11 @@ namespace Subsurface
public AttackResult AddDamage(Vector2 position, DamageType damageType, float amount, float bleedingAmount, float stun, bool playSound = false) public AttackResult AddDamage(Vector2 position, DamageType damageType, float amount, float bleedingAmount, float stun, bool playSound = false)
{ {
animController.StunTimer = Math.Max(animController.StunTimer, stun); AnimController.StunTimer = Math.Max(AnimController.StunTimer, stun);
Limb closestLimb = null; Limb closestLimb = null;
float closestDistance = 0.0f; float closestDistance = 0.0f;
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
float distance = Vector2.Distance(position, limb.SimPosition); float distance = Vector2.Distance(position, limb.SimPosition);
if (closestLimb == null || distance < closestDistance) if (closestLimb == null || distance < closestDistance)
@@ -720,8 +718,8 @@ namespace Subsurface
AttackResult attackResult = closestLimb.AddDamage(position, damageType, amount, bleedingAmount, playSound); AttackResult attackResult = closestLimb.AddDamage(position, damageType, amount, bleedingAmount, playSound);
health -= attackResult.damage; health -= attackResult.Damage;
bleeding += attackResult.bleeding; bleeding += attackResult.Bleeding;
return attackResult; return attackResult;
@@ -741,12 +739,12 @@ namespace Subsurface
private void Implode() private void Implode()
{ {
Limb torso= animController.GetLimb(LimbType.Torso); Limb torso= AnimController.GetLimb(LimbType.Torso);
if (torso == null) torso = animController.GetLimb(LimbType.Head); if (torso == null) torso = AnimController.GetLimb(LimbType.Head);
Vector2 centerOfMass = Vector2.Zero; Vector2 centerOfMass = Vector2.Zero;
float totalMass = 0.0f; float totalMass = 0.0f;
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
centerOfMass += limb.Mass * limb.SimPosition; centerOfMass += limb.Mass * limb.SimPosition;
totalMass += limb.Mass; totalMass += limb.Mass;
@@ -756,7 +754,7 @@ namespace Subsurface
health = 0.0f; health = 0.0f;
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
Vector2 diff = centerOfMass - limb.SimPosition; Vector2 diff = centerOfMass - limb.SimPosition;
if (diff == Vector2.Zero) continue; if (diff == Vector2.Zero) continue;
@@ -769,16 +767,16 @@ namespace Subsurface
for (int i = 0; i < 10; i++) for (int i = 0; i < 10; i++)
{ {
Particle p = Game1.particleManager.CreateParticle("waterblood", Particle p = Game1.particleManager.CreateParticle("waterblood",
torso.SimPosition + new Vector2(MathUtils.RandomFloatLocal(-0.5f, 0.5f), MathUtils.RandomFloatLocal(-0.5f, 0.5f)), torso.SimPosition + new Vector2(Rand.Range(-0.5f, 0.5f), Rand.Range(-0.5f, 0.5f)),
Vector2.Zero); Vector2.Zero);
if (p!=null) p.Size *= 2.0f; if (p!=null) p.Size *= 2.0f;
Game1.particleManager.CreateParticle("bubbles", Game1.particleManager.CreateParticle("bubbles",
torso.SimPosition, torso.SimPosition,
new Vector2(MathUtils.RandomFloatLocal(-0.5f, 0.5f), MathUtils.RandomFloatLocal(-1.0f,0.5f))); new Vector2(Rand.Range(-0.5f, 0.5f), Rand.Range(-1.0f,0.5f)));
} }
foreach (var joint in animController.limbJoints) foreach (var joint in AnimController.limbJoints)
{ {
joint.LimitEnabled = false; joint.LimitEnabled = false;
} }
@@ -790,8 +788,8 @@ namespace Subsurface
if (isDead) return; if (isDead) return;
isDead = true; isDead = true;
animController.movement = Vector2.Zero; AnimController.movement = Vector2.Zero;
animController.TargetMovement = Vector2.Zero; AnimController.TargetMovement = Vector2.Zero;
for (int i = 0; i < selectedItems.Length; i++ ) for (int i = 0; i < selectedItems.Length; i++ )
{ {
@@ -802,13 +800,13 @@ namespace Subsurface
aiTarget.Remove(); aiTarget.Remove();
aiTarget = null; aiTarget = null;
foreach (Limb limb in animController.limbs) foreach (Limb limb in AnimController.limbs)
{ {
if (limb.pullJoint == null) continue; if (limb.pullJoint == null) continue;
limb.pullJoint.Enabled = false; limb.pullJoint.Enabled = false;
} }
foreach (RevoluteJoint joint in animController.limbJoints) foreach (RevoluteJoint joint in AnimController.limbJoints)
{ {
joint.MotorEnabled = false; joint.MotorEnabled = false;
joint.MaxMotorTorque = 0.0f; joint.MaxMotorTorque = 0.0f;
@@ -863,20 +861,25 @@ namespace Subsurface
message.Write(NetTime.Now); message.Write(NetTime.Now);
// Write byte = move direction // Write byte = move direction
message.Write(animController.TargetMovement.X); message.Write(AnimController.TargetMovement.X);
message.Write(animController.TargetMovement.Y); message.Write(AnimController.TargetMovement.Y);
message.Write(animController.targetDir==Direction.Right); message.Write(AnimController.TargetDir==Direction.Right);
message.Write(cursorPosition.X); message.Write(cursorPosition.X);
message.Write(cursorPosition.Y); message.Write(cursorPosition.Y);
message.Write(largeUpdateTimer <= 0); message.Write(AnimController.limbs.Count());
if (largeUpdateTimer<=0)
message.Write(LargeUpdateTimer <= 0);
if (LargeUpdateTimer<=0)
{ {
foreach (Limb limb in animController.limbs) int i = 0;
foreach (Limb limb in AnimController.limbs)
{ {
message.Write(42.0f+i);
message.Write(limb.body.Position.X); message.Write(limb.body.Position.X);
message.Write(limb.body.Position.Y); message.Write(limb.body.Position.Y);
@@ -885,19 +888,20 @@ namespace Subsurface
message.Write(limb.body.Rotation); message.Write(limb.body.Rotation);
message.Write(limb.body.AngularVelocity); message.Write(limb.body.AngularVelocity);
i++;
} }
message.Write(animController.StunTimer); message.Write(AnimController.StunTimer);
largeUpdateTimer = 5; LargeUpdateTimer = 5;
} }
else else
{ {
Limb torso = animController.GetLimb(LimbType.Torso); Limb torso = AnimController.GetLimb(LimbType.Torso);
message.Write(torso.body.Position.X); message.Write(torso.body.Position.X);
message.Write(torso.body.Position.Y); message.Write(torso.body.Position.Y);
largeUpdateTimer = (byte)Math.Max(0, largeUpdateTimer-1); LargeUpdateTimer = (byte)Math.Max(0, LargeUpdateTimer-1);
} }
@@ -950,7 +954,7 @@ namespace Subsurface
targetMovement.X = message.ReadFloat(); targetMovement.X = message.ReadFloat();
targetMovement.Y = message.ReadFloat(); targetMovement.Y = message.ReadFloat();
animController.isStanding = true; AnimController.IsStanding = true;
bool targetDir = message.ReadBoolean(); bool targetDir = message.ReadBoolean();
@@ -958,67 +962,77 @@ namespace Subsurface
cursorPos.X = message.ReadFloat(); cursorPos.X = message.ReadFloat();
cursorPos.Y = message.ReadFloat(); cursorPos.Y = message.ReadFloat();
if (sendingTime > lastNetworkUpdate) int num1 = message.ReadInt32();
System.Diagnostics.Debug.WriteLine(num1);
if (sendingTime <= LastNetworkUpdate) return;
cursorPosition = cursorPos;
AnimController.TargetMovement= targetMovement;
AnimController.TargetDir = (targetDir) ? Direction.Right : Direction.Left;
if (message.ReadBoolean())
{ {
cursorPosition = cursorPos; foreach (Limb limb in AnimController.limbs)
animController.TargetMovement= targetMovement;
animController.targetDir = (targetDir) ? Direction.Right : Direction.Left;
if (message.ReadBoolean())
{ {
foreach (Limb limb in animController.limbs) float num = message.ReadFloat();
System.Diagnostics.Debug.WriteLine(num);
Vector2 pos = Vector2.Zero;
pos.X = message.ReadFloat();
pos.Y = message.ReadFloat();
Vector2 vel = Vector2.Zero;
vel.X = message.ReadFloat();
vel.Y = message.ReadFloat();
float rotation = message.ReadFloat();
float angularVel = message.ReadFloat();
if (vel != Vector2.Zero && vel.Length() > 100.0f) { }
if (pos != Vector2.Zero && pos.Length() > 100.0f) { }
if (limb.body != null)
{ {
Vector2 pos = Vector2.Zero;
pos.X = message.ReadFloat();
pos.Y = message.ReadFloat();
Vector2 vel = Vector2.Zero;
vel.X = message.ReadFloat();
vel.Y = message.ReadFloat();
float rotation = message.ReadFloat();
float angularVel = message.ReadFloat();
if (limb.body == null) continue;
if (vel != Vector2.Zero && vel.Length() > 100.0f) { }
if (pos != Vector2.Zero && pos.Length() > 100.0f) { }
limb.body.TargetVelocity = vel; limb.body.TargetVelocity = vel;
limb.body.TargetPosition = pos;// +vel * (float)(deltaTime / 60.0); limb.body.TargetPosition = pos;// +vel * (float)(deltaTime / 60.0);
limb.body.TargetRotation = rotation;// +angularVel * (float)(deltaTime / 60.0); limb.body.TargetRotation = rotation;// +angularVel * (float)(deltaTime / 60.0);
limb.body.TargetAngularVelocity = angularVel; limb.body.TargetAngularVelocity = angularVel;
} }
animController.StunTimer = message.ReadFloat();
largeUpdateTimer = 1;
}
else
{
Vector2 pos = Vector2.Zero;
pos.X = message.ReadFloat();
pos.Y = message.ReadFloat();
Limb torso = animController.GetLimb(LimbType.Torso);
torso.body.TargetPosition = pos;
largeUpdateTimer = 0;
} }
if (aiController != null) aiController.ReadNetworkData(message); AnimController.StunTimer = message.ReadFloat();
lastNetworkUpdate = sendingTime; LargeUpdateTimer = 1;
} }
else
{
Vector2 pos = Vector2.Zero;
pos.X = message.ReadFloat();
pos.Y = message.ReadFloat();
Limb torso = AnimController.GetLimb(LimbType.Torso);
torso.body.TargetPosition = pos;
LargeUpdateTimer = 0;
}
if (aiController != null) aiController.ReadNetworkData(message);
LastNetworkUpdate = sendingTime;
} }
public override void Remove() public override void Remove()
{ {
base.Remove(); base.Remove();
characterList.Remove(this); CharacterList.Remove(this);
if (controlled == this) controlled = null; if (controlled == this) controlled = null;
@@ -1027,8 +1041,8 @@ namespace Subsurface
if (aiTarget != null) if (aiTarget != null)
aiTarget.Remove(); aiTarget.Remove();
if (animController!=null) if (AnimController!=null)
animController.Remove(); AnimController.Remove();
} }
} }
+27 -27
View File
@@ -7,17 +7,17 @@ namespace Subsurface
class CharacterInfo class CharacterInfo
{ {
public string name; public string Name;
public readonly string file; public readonly string File;
public readonly int headSpriteId; public int HeadSpriteId;
//public int ID; //public int ID;
public Gender gender; public Gender Gender;
public int salary; public int Salary;
//public string GenderString() //public string GenderString()
//{ //{
@@ -26,25 +26,25 @@ namespace Subsurface
public CharacterInfo(string file, string name = "", Gender gender = Gender.None) public CharacterInfo(string file, string name = "", Gender gender = Gender.None)
{ {
this.file = file; this.File = file;
//ID = -1; //ID = -1;
XDocument doc = ToolBox.TryLoadXml(file); XDocument doc = ToolBox.TryLoadXml(file);
if (doc == null) return; if (doc == null) return;
salary = 500; Salary = 500;
if (ToolBox.GetAttributeBool(doc.Root, "genders", false)) if (ToolBox.GetAttributeBool(doc.Root, "genders", false))
{ {
if (gender == Gender.None) if (gender == Gender.None)
{ {
float femaleRatio = ToolBox.GetAttributeFloat(doc.Root, "femaleratio", 0.5f); float femaleRatio = ToolBox.GetAttributeFloat(doc.Root, "femaleratio", 0.5f);
this.gender = (Game1.random.NextDouble() < femaleRatio) ? Gender.Female : Gender.Male; this.Gender = (Rand.Range(0.0f, 1.0f, false) < femaleRatio) ? Gender.Female : Gender.Male;
} }
else else
{ {
this.gender = gender; this.Gender = gender;
} }
} }
@@ -53,18 +53,18 @@ namespace Subsurface
{ {
headSpriteRange = ToolBox.GetAttributeVector2( headSpriteRange = ToolBox.GetAttributeVector2(
doc.Root, doc.Root,
this.gender == Gender.Female ? "femaleheadid" : "maleheadid", this.Gender == Gender.Female ? "femaleheadid" : "maleheadid",
Vector2.Zero); Vector2.Zero);
} }
if (headSpriteRange != Vector2.Zero) if (headSpriteRange != Vector2.Zero)
{ {
headSpriteId = Game1.localRandom.Next((int)headSpriteRange.X, (int)headSpriteRange.Y + 1); HeadSpriteId = Rand.Range((int)headSpriteRange.X, (int)headSpriteRange.Y + 1);
} }
if (!string.IsNullOrEmpty(name)) if (!string.IsNullOrEmpty(name))
{ {
this.name = name; this.Name = name;
return; return;
} }
@@ -73,32 +73,32 @@ namespace Subsurface
string firstNamePath = (ToolBox.GetAttributeString(doc.Root.Element("name"), "firstname", "")); string firstNamePath = (ToolBox.GetAttributeString(doc.Root.Element("name"), "firstname", ""));
if (firstNamePath != "") if (firstNamePath != "")
{ {
firstNamePath = firstNamePath.Replace("[GENDER]", (this.gender == Gender.Female) ? "f" : ""); firstNamePath = firstNamePath.Replace("[GENDER]", (this.Gender == Gender.Female) ? "f" : "");
this.name = ToolBox.GetRandomLine(firstNamePath); this.Name = ToolBox.GetRandomLine(firstNamePath);
} }
string lastNamePath = (ToolBox.GetAttributeString(doc.Root.Element("name"), "lastname", "")); string lastNamePath = (ToolBox.GetAttributeString(doc.Root.Element("name"), "lastname", ""));
if (lastNamePath != "") if (lastNamePath != "")
{ {
lastNamePath = lastNamePath.Replace("[GENDER]", (this.gender == Gender.Female) ? "f" : ""); lastNamePath = lastNamePath.Replace("[GENDER]", (this.Gender == Gender.Female) ? "f" : "");
if (this.name != "") this.name += " "; if (this.Name != "") this.Name += " ";
this.name += ToolBox.GetRandomLine(lastNamePath); this.Name += ToolBox.GetRandomLine(lastNamePath);
} }
} }
} }
public CharacterInfo(XElement element) public CharacterInfo(XElement element)
{ {
name = ToolBox.GetAttributeString(element, "name", "unnamed"); Name = ToolBox.GetAttributeString(element, "name", "unnamed");
string genderStr = ToolBox.GetAttributeString(element, "gender", "male").ToLower(); string genderStr = ToolBox.GetAttributeString(element, "gender", "male").ToLower();
gender = (genderStr == "male") ? Gender.Male : Gender.Female; Gender = (genderStr == "male") ? Gender.Male : Gender.Female;
file = ToolBox.GetAttributeString(element, "file", ""); File = ToolBox.GetAttributeString(element, "file", "");
salary = ToolBox.GetAttributeInt(element, "salary", 1000); Salary = ToolBox.GetAttributeInt(element, "salary", 1000);
headSpriteId = ToolBox.GetAttributeInt(element, "headspriteid", 1); HeadSpriteId = ToolBox.GetAttributeInt(element, "headspriteid", 1);
} }
public virtual XElement Save(XElement parentElement) public virtual XElement Save(XElement parentElement)
@@ -106,11 +106,11 @@ namespace Subsurface
XElement componentElement = new XElement("character"); XElement componentElement = new XElement("character");
componentElement.Add( componentElement.Add(
new XAttribute("name", name), new XAttribute("name", Name),
new XAttribute("file", file), new XAttribute("file", File),
new XAttribute("gender", gender == Gender.Male ? "male" : "female"), new XAttribute("gender", Gender == Gender.Male ? "male" : "female"),
new XAttribute("salary", salary), new XAttribute("salary", Salary),
new XAttribute("headspriteid", headSpriteId)); new XAttribute("headspriteid", HeadSpriteId));
parentElement.Add(componentElement); parentElement.Add(componentElement);
return componentElement; return componentElement;
+7 -7
View File
@@ -6,15 +6,15 @@ namespace Subsurface
{ {
class DelayedEffect : StatusEffect class DelayedEffect : StatusEffect
{ {
public static List<DelayedEffect> list = new List<DelayedEffect>(); public static List<DelayedEffect> List = new List<DelayedEffect>();
float delay; private float delay;
float timer; private float timer;
Vector2 position; private Vector2 position;
List<IPropertyObject> targets; private List<IPropertyObject> targets;
public float Timer public float Timer
{ {
@@ -36,7 +36,7 @@ namespace Subsurface
this.targets = targets; this.targets = targets;
list.Add(this); List.Add(this);
} }
public void Update(float deltaTime) public void Update(float deltaTime)
@@ -46,7 +46,7 @@ namespace Subsurface
if (timer > 0.0f) return; if (timer > 0.0f) return;
base.Apply(1.0f, position, targets); base.Apply(1.0f, position, targets);
list.Remove(this); List.Remove(this);
} }
} }
+6 -6
View File
@@ -62,11 +62,11 @@ namespace Subsurface
//targetDir = (movement.X > 0.0f) ? Direction.Right : Direction.Left; //targetDir = (movement.X > 0.0f) ? Direction.Right : Direction.Left;
if (movement.X > 0.1f && movement.X > Math.Abs(movement.Y)) if (movement.X > 0.1f && movement.X > Math.Abs(movement.Y))
{ {
targetDir = Direction.Right; TargetDir = Direction.Right;
} }
else if (movement.X < -0.1f && movement.X < -Math.Abs(movement.Y)) else if (movement.X < -0.1f && movement.X < -Math.Abs(movement.Y))
{ {
targetDir = Direction.Left; TargetDir = Direction.Left;
} }
} }
else else
@@ -79,17 +79,17 @@ namespace Subsurface
if (rotation > 20 && rotation < 160) if (rotation > 20 && rotation < 160)
{ {
targetDir = Direction.Left; TargetDir = Direction.Left;
} }
else if (rotation > 200 && rotation < 340) else if (rotation > 200 && rotation < 340)
{ {
targetDir = Direction.Right; TargetDir = Direction.Right;
} }
} }
//if (stunTimer > gameTime.TotalGameTime.TotalMilliseconds) return; //if (stunTimer > gameTime.TotalGameTime.TotalMilliseconds) return;
if (targetDir != dir) if (TargetDir != dir)
{ {
Flip(); Flip();
if (flip) Mirror(); if (flip) Mirror();
@@ -213,7 +213,7 @@ namespace Subsurface
//out whether the ragdoll is standing on ground //out whether the ragdoll is standing on ground
float closestFraction = 1; float closestFraction = 1;
//Structure closestStructure = null; //Structure closestStructure = null;
Game1.world.RayCast((fixture, point, normal, fraction) => Game1.World.RayCast((fixture, point, normal, fraction) =>
{ {
//other limbs and bodies with no collision detection are ignored //other limbs and bodies with no collision detection are ignored
if (fixture == null || if (fixture == null ||
+10 -10
View File
@@ -20,13 +20,13 @@ namespace Subsurface
Vector2 rayStart = colliderPos; // at the bottom of the player sprite Vector2 rayStart = colliderPos; // at the bottom of the player sprite
Vector2 rayEnd = rayStart - new Vector2(0.0f, TorsoPosition); Vector2 rayEnd = rayStart - new Vector2(0.0f, TorsoPosition);
if (stairs != null) rayEnd.Y -= 0.5f; if (stairs != null) rayEnd.Y -= 0.5f;
if (anim != Animation.UsingConstruction) ResetPullJoints(); if (Anim != Animation.UsingConstruction) ResetPullJoints();
//do a raytrace straight down from the torso to figure //do a raytrace straight down from the torso to figure
//out whether the ragdoll is standing on ground //out whether the ragdoll is standing on ground
float closestFraction = 1; float closestFraction = 1;
Structure closestStructure = null; Structure closestStructure = null;
Game1.world.RayCast((fixture, point, normal, fraction) => Game1.World.RayCast((fixture, point, normal, fraction) =>
{ {
switch (fixture.CollisionCategories) switch (fixture.CollisionCategories)
{ {
@@ -119,7 +119,7 @@ namespace Subsurface
return; return;
} }
switch (anim) switch (Anim)
{ {
case Animation.Climbing: case Animation.Climbing:
UpdateClimbing(); UpdateClimbing();
@@ -129,13 +129,13 @@ namespace Subsurface
default: default:
if (inWater) if (inWater)
UpdateSwimming(); UpdateSwimming();
else if (isStanding) else if (IsStanding)
UpdateStanding(); UpdateStanding();
break; break;
} }
if (targetDir != dir) Flip(); if (TargetDir != dir) Flip();
foreach (Limb limb in limbs) foreach (Limb limb in limbs)
{ {
@@ -376,9 +376,9 @@ namespace Subsurface
if (!character.IsNetworkPlayer) if (!character.IsNetworkPlayer)
{ {
if (rotation > 20 && rotation < 170) if (rotation > 20 && rotation < 170)
targetDir = Direction.Left; TargetDir = Direction.Left;
else if (rotation > 190 && rotation < 340) else if (rotation > 190 && rotation < 340)
targetDir = Direction.Right; TargetDir = Direction.Right;
} }
if (TargetMovement == Vector2.Zero) return; if (TargetMovement == Vector2.Zero) return;
@@ -520,7 +520,7 @@ namespace Subsurface
{ {
if (character.SelectedConstruction == null) if (character.SelectedConstruction == null)
{ {
anim = Animation.None; Anim = Animation.None;
return; return;
} }
@@ -597,7 +597,7 @@ namespace Subsurface
torso.body.ApplyForce(climbForce * 65.0f * torso.Mass); torso.body.ApplyForce(climbForce * 65.0f * torso.Mass);
head.body.SmoothRotate(0.0f); head.body.SmoothRotate(0.0f);
Rectangle trigger = character.SelectedConstruction.Prefab.triggers.First(); Rectangle trigger = character.SelectedConstruction.Prefab.Triggers.First();
trigger = character.SelectedConstruction.TransformTrigger(trigger); trigger = character.SelectedConstruction.TransformTrigger(trigger);
//stop climbing if: //stop climbing if:
@@ -609,7 +609,7 @@ namespace Subsurface
(TargetMovement.Y < 0.0f && ConvertUnits.ToSimUnits(trigger.Height) + handPos.Y < HeadPosition*2.0f) || (TargetMovement.Y < 0.0f && ConvertUnits.ToSimUnits(trigger.Height) + handPos.Y < HeadPosition*2.0f) ||
(TargetMovement.Y > 0.0f && -handPos.Y < ConvertUnits.ToSimUnits(10.0f))) (TargetMovement.Y > 0.0f && -handPos.Y < ConvertUnits.ToSimUnits(10.0f)))
{ {
anim = Animation.None; Anim = Animation.None;
character.SelectedConstruction = null; character.SelectedConstruction = null;
IgnorePlatforms = false; IgnorePlatforms = false;
} }
+6 -6
View File
@@ -208,7 +208,7 @@ namespace Subsurface
pullJoint.Enabled = false; pullJoint.Enabled = false;
pullJoint.MaxForce = 150.0f * body.Mass; pullJoint.MaxForce = 150.0f * body.Mass;
Game1.world.AddJoint(pullJoint); Game1.World.AddJoint(pullJoint);
} }
else else
{ {
@@ -235,10 +235,10 @@ namespace Subsurface
case "sprite": case "sprite":
string spritePath = subElement.Attribute("texture").Value; string spritePath = subElement.Attribute("texture").Value;
if (character.info!=null) if (character.Info!=null)
{ {
spritePath = spritePath.Replace("[GENDER]", (character.info.gender == Gender.Female) ? "f" : ""); spritePath = spritePath.Replace("[GENDER]", (character.Info.Gender == Gender.Female) ? "f" : "");
spritePath = spritePath.Replace("[HEADID]", character.info.headSpriteId.ToString()); spritePath = spritePath.Replace("[HEADID]", character.Info.HeadSpriteId.ToString());
} }
@@ -323,7 +323,7 @@ namespace Subsurface
Game1.particleManager.CreateParticle("blood", Game1.particleManager.CreateParticle("blood",
SimPosition, SimPosition,
particleVel * MathUtils.RandomFloatLocal(1.0f, 3.0f)); particleVel * Rand.Range(1.0f, 3.0f));
} }
for (int i = 0; i < bloodAmount / 2; i++) for (int i = 0; i < bloodAmount / 2; i++)
@@ -339,7 +339,7 @@ namespace Subsurface
if (LinearVelocity.X>100.0f) if (LinearVelocity.X>100.0f)
{ {
DebugConsole.ThrowError("CHARACTER EXPLODED"); DebugConsole.ThrowError("CHARACTER EXPLODED");
foreach (Limb limb in character.animController.limbs) foreach (Limb limb in character.AnimController.limbs)
{ {
limb.body.ResetDynamics(); limb.body.ResetDynamics();
limb.body.SetTransform(body.Position, 0.0f); limb.body.SetTransform(body.Position, 0.0f);
+4 -4
View File
@@ -197,7 +197,7 @@ namespace Subsurface
joint.MotorEnabled = true; joint.MotorEnabled = true;
joint.MaxMotorTorque = 0.25f; joint.MaxMotorTorque = 0.25f;
Game1.world.AddJoint(joint); Game1.World.AddJoint(joint);
for (int i = 0; i < limbJoints.Length; i++ ) for (int i = 0; i < limbJoints.Length; i++ )
{ {
@@ -223,7 +223,7 @@ namespace Subsurface
float startDepth = 0.1f; float startDepth = 0.1f;
float increment = 0.0001f; float increment = 0.0001f;
foreach (Character otherCharacter in Character.characterList) foreach (Character otherCharacter in Character.CharacterList)
{ {
if (otherCharacter==character) continue; if (otherCharacter==character) continue;
startDepth+=increment; startDepth+=increment;
@@ -541,7 +541,7 @@ namespace Subsurface
float allowedDistance = 0.1f; float allowedDistance = 0.1f;
float dist = Vector2.Distance(limbs[0].body.Position, refLimb.body.TargetPosition); float dist = Vector2.Distance(limbs[0].body.Position, refLimb.body.TargetPosition);
bool resetAll = (dist > resetDistance && character.largeUpdateTimer == 1); bool resetAll = (dist > resetDistance && character.LargeUpdateTimer == 1);
Vector2 newMovement = (refLimb.body.TargetPosition - refLimb.body.Position); Vector2 newMovement = (refLimb.body.TargetPosition - refLimb.body.Position);
@@ -632,7 +632,7 @@ namespace Subsurface
foreach (Limb l in limbs) l.Remove(); foreach (Limb l in limbs) l.Remove();
foreach (RevoluteJoint joint in limbJoints) foreach (RevoluteJoint joint in limbJoints)
{ {
Game1.world.RemoveJoint(joint); Game1.World.RemoveJoint(joint);
} }
} }
+2 -2
View File
@@ -237,9 +237,9 @@ namespace Subsurface
public static void UpdateAll(float deltaTime) public static void UpdateAll(float deltaTime)
{ {
for (int i = DelayedEffect.list.Count-1; i>= 0; i--) for (int i = DelayedEffect.List.Count-1; i>= 0; i--)
{ {
DelayedEffect.list[i].Update(deltaTime); DelayedEffect.List[i].Update(deltaTime);
} }
} }
-11
View File
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<style
smallpadding="20.0, 20.0, 20.0, 20.0"
largepadding="40.0, 40.0, 40.0, 40.0"
backgroundcolor="0.2, 0.2, 0.2, 0.8"
foregroundcolor="1.0, 1.0, 1.0, 1.0"
textcolor="0.0, 0.0, 0.0, 1.0"
hovercolor="0.8, 0.8, 0.8, 1.0"
selectedcolor="1.0, 0.82, 0.05, 1.0"/>
+1 -1
View File
@@ -8,7 +8,7 @@
<Sprite texture ="engine.png" depth="0.8"/> <Sprite texture ="engine.png" depth="0.8"/>
<Engine minvoltage="0.5" powerperforce="10.0" maxforce="50" canbeselected = "true"> <Engine minvoltage="0.5" powerperforce="10.0" maxforce="500" canbeselected = "true">
<GuiFrame rect="0,0,0.3,0.3" alignment="Center" color="0.0,0.0,0.0,0.8"/> <GuiFrame rect="0,0,0.3,0.3" alignment="Center" color="0.0,0.0,0.0,0.8"/>
</Engine> </Engine>
+1
View File
@@ -13,5 +13,6 @@
<input name="toggle"/> <input name="toggle"/>
<input name="set_active"/> <input name="set_active"/>
<input name="set_speed"/> <input name="set_speed"/>
<input name="set_targetlevel"/>
</ConnectionPanel> </ConnectionPanel>
</Item> </Item>

Before

Width:  |  Height:  |  Size: 123 B

After

Width:  |  Height:  |  Size: 123 B

+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8" ?>
<style>
<GUIFrame
padding="40.0, 40.0, 40.0, 40.0"
color="1.0, 1.0, 1.0, 1.0"
textcolor="0.0, 0.0, 0.0, 1.0"
hovercolor="0.8, 0.8, 0.8, 1.0"
selectedcolor="1.0, 0.82, 0.05, 1.0"
outlinecolor="0.5, 0.57, 0.6, 1.0">
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 0.0" sourcerect ="0.0, 90.0, 0.0, 100.0"/>
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 1.0" sourcerect ="0.0, 0.0, 0.0, 90.0"/>
</GUIFrame>
<GUIButton
color="0.6, 0.2, 0.2, 1.0"
textcolor="1.0, 1.0, 1.0, 1.0"
hovercolor="0.88, 0.19, 0.16, 1.0"
selectedcolor="0.8, 0.8, 0.8, 1.0"/>
<GUITextBlock
textcolor="1.0, 1.0, 1.0, 1.0"
hovercolor="1.0, 1.0, 1.0, 0.3"
selectedcolor="1.0, 0.6, 0.0, 0.3"/>
<GUIListBox
color="0.5, 0.5, 0.5, 1.0"
textcolor="1.0, 1.0, 1.0, 1.0"
outlinecolor="0.5, 0.57, 0.6, 1.0">
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 0.0" sourcerect ="0.0, 90.0, 0.0, 100.0"/>
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 1.0" sourcerect ="0.0, 0.0, 0.0, 90.0"/>
</GUIListBox>
<GUIScrollBar
color="0.5, 0.5, 0.5, 1.0"
textcolor="1.0, 1.0, 1.0, 1.0"
outlinecolor="0.5, 0.57, 0.6, 1.0">
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 0.0"/>
</GUIScrollBar>
<GUITextBox
color="0.5, 0.5, 0.5, 1.0"
textcolor="1.0, 1.0, 1.0, 1.0"
outlinecolor="0.5, 0.57, 0.6, 1.0">
<Sprite texture="Content\UI\uiBackground.png" size="0.0, 1.0" sourcerect ="0.0, 0.0, 0.0, 90.0"/>
</GUITextBox>
</style>

Before

Width:  |  Height:  |  Size: 685 B

After

Width:  |  Height:  |  Size: 685 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

+6 -5
View File
@@ -61,7 +61,7 @@ namespace Subsurface
if (isOpen) if (isOpen)
{ {
Character.disableControls = true; Character.DisableControls = true;
if (PlayerInput.KeyHit(Keys.Up)) if (PlayerInput.KeyHit(Keys.Up))
{ {
@@ -165,7 +165,7 @@ namespace Subsurface
break; break;
case "startserver": case "startserver":
if (Game1.Server==null) if (Game1.Server==null)
Game1.Server = new GameServer(); Game1.NetworkMember = new GameServer();
break; break;
case "kick": case "kick":
if (Game1.Server == null) break; if (Game1.Server == null) break;
@@ -175,7 +175,7 @@ namespace Subsurface
if (commands.Length == 1) return; if (commands.Length == 1) return;
if (Game1.Client == null) if (Game1.Client == null)
{ {
Game1.Client = new GameClient("Name"); Game1.NetworkMember = new GameClient("Name");
Game1.Client.ConnectToServer(commands[1]); Game1.Client.ConnectToServer(commands[1]);
} }
break; break;
@@ -198,6 +198,7 @@ namespace Subsurface
Game1.EditCharacterScreen.Select(); Game1.EditCharacterScreen.Select();
break; break;
case "freecamera": case "freecamera":
case "freecam":
Character.Controlled = null; Character.Controlled = null;
Game1.GameScreen.Cam.TargetPos = Vector2.Zero; Game1.GameScreen.Cam.TargetPos = Vector2.Zero;
break; break;
@@ -209,13 +210,13 @@ namespace Subsurface
} }
break; break;
case "generatelevel": case "generatelevel":
Game1.Level = new Level(100, 500,500, 50); Game1.Level = new Level("asdf", 500,500, 50);
Game1.Level.Generate(100.0f); Game1.Level.Generate(100.0f);
break; break;
case "fowenabled": case "fowenabled":
case "fow": case "fow":
case "drawfow": case "drawfow":
Lights.LightManager.fowEnabled = !Lights.LightManager.fowEnabled; Lights.LightManager.FowEnabled = !Lights.LightManager.FowEnabled;
break; break;
case "lobbyscreen": case "lobbyscreen":
case "lobby": case "lobby":
+3 -3
View File
@@ -25,15 +25,15 @@ namespace Subsurface
{ {
WayPoint randomWayPoint = WayPoint.GetRandom(WayPoint.SpawnType.Enemy); WayPoint randomWayPoint = WayPoint.GetRandom(WayPoint.SpawnType.Enemy);
int amount = Game1.random.Next(minAmount, maxAmount); int amount = Rand.Range(minAmount, maxAmount, false);
monsters = new Character[amount]; monsters = new Character[amount];
for (int i = 0; i < amount; i++) for (int i = 0; i < amount; i++)
{ {
Vector2 position = (randomWayPoint == null) ? Vector2.Zero : randomWayPoint.SimPosition; Vector2 position = (randomWayPoint == null) ? Vector2.Zero : randomWayPoint.SimPosition;
position.X += MathUtils.RandomFloatLocal(-0.5f,0.5f); position.X += Rand.Range(-0.5f, 0.5f);
position.Y += MathUtils.RandomFloatLocal(-0.5f,0.5f); position.Y += Rand.Range(-0.5f, 0.5f);
monsters[i] = new Character(characterFile, position); monsters[i] = new Character(characterFile, position);
} }
} }
+2 -2
View File
@@ -125,7 +125,7 @@ namespace Subsurface
i++; i++;
} }
float randomNumber = (float)Game1.random.NextDouble() * probabilitySum; float randomNumber = Rand.Range(0.0f,probabilitySum);
i = 0; i = 0;
foreach (XElement element in doc.Root.Elements()) foreach (XElement element in doc.Root.Elements())
@@ -169,7 +169,7 @@ namespace Subsurface
{ {
isStarted = false; isStarted = false;
isFinished = false; isFinished = false;
startTimer = Game1.random.Next(startTimeMin, startTimeMax); startTimer = Rand.Range(startTimeMin, startTimeMax, false);
} }
protected virtual void Start() protected virtual void Start()
+4 -4
View File
@@ -35,7 +35,7 @@ namespace Subsurface
taskListBox = new GUIListBox(new Rectangle(Game1.GraphicsWidth - 250, 50, 250, 500), Color.Transparent); taskListBox = new GUIListBox(new Rectangle(Game1.GraphicsWidth - 250, 50, 250, 500), Color.Transparent);
//taskListBox.ScrollBarEnabled = false; //taskListBox.ScrollBarEnabled = false;
taskListBox.Padding = GUI.style.smallPadding; //taskListBox.Padding = GUI.style.smallPadding;
} }
public void AddTask(Task newTask) public void AddTask(Task newTask)
@@ -83,12 +83,12 @@ namespace Subsurface
color = Color.Orange; color = Color.Orange;
} }
GUIFrame frame = new GUIFrame(new Rectangle(0,0,width,40), Color.Transparent, Alignment.Right, taskListBox); GUIFrame frame = new GUIFrame(new Rectangle(0,0,width,40), Color.Transparent, Alignment.Right, null, taskListBox);
frame.UserData = task; frame.UserData = task;
frame.Padding = new Vector4(0.0f, 5.0f, 5.0f, 5.0f); frame.Padding = new Vector4(0.0f, 5.0f, 5.0f, 5.0f);
GUIFrame colorFrame = new GUIFrame(new Rectangle(0, 0, 0, 0), color * 0.5f, Alignment.Right, frame); GUIFrame colorFrame = new GUIFrame(new Rectangle(0, 0, 0, 0), color * 0.5f, Alignment.Right, null, frame);
GUITextBlock textBlock = new GUITextBlock(new Rectangle(5, 5, 0, 20), task.Name, Color.Transparent, Color.Black, Alignment.Right, colorFrame); GUITextBlock textBlock = new GUITextBlock(new Rectangle(5, 5, 0, 20), task.Name, Color.Transparent, Color.Black, Alignment.Right, null, colorFrame);
//textBlock.Padding = new Vector4(10.0f, 10.0f, 0.0f, 0.0f); //textBlock.Padding = new Vector4(10.0f, 10.0f, 0.0f, 0.0f);
//colorFrame.AddChild(textBlock); //colorFrame.AddChild(textBlock);
+5 -5
View File
@@ -12,7 +12,7 @@ namespace Subsurface
public const int MaximumSamples = 10; public const int MaximumSamples = 10;
private Queue<double> _sampleBuffer = new Queue<double>(); private Queue<double> sampleBuffer = new Queue<double>();
public bool Update(double deltaTime) public bool Update(double deltaTime)
{ {
@@ -23,12 +23,12 @@ namespace Subsurface
CurrentFramesPerSecond = (1.0 / deltaTime); CurrentFramesPerSecond = (1.0 / deltaTime);
_sampleBuffer.Enqueue(CurrentFramesPerSecond); sampleBuffer.Enqueue(CurrentFramesPerSecond);
if (_sampleBuffer.Count > MaximumSamples) if (sampleBuffer.Count > MaximumSamples)
{ {
_sampleBuffer.Dequeue(); sampleBuffer.Dequeue();
AverageFramesPerSecond = _sampleBuffer.Average(i => i); AverageFramesPerSecond = sampleBuffer.Average(i => i);
} }
else else
{ {
+58
View File
@@ -0,0 +1,58 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Subsurface
{
class GUIComponentStyle
{
public readonly Vector4 Padding;
public readonly Color Color;
public readonly Color textColor;
public readonly Color HoverColor;
public readonly Color SelectedColor;
public readonly Color OutlineColor;
public readonly List<Sprite> Sprites;
public GUIComponentStyle(XElement element)
{
Sprites = new List<Sprite>();
Padding = ToolBox.GetAttributeVector4(element, "padding", Vector4.Zero);
Vector4 colorVector = ToolBox.GetAttributeVector4(element, "color", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
Color = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(element, "textcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
textColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(element, "hovercolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
HoverColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(element, "selectedcolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
SelectedColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(element, "outlinecolor", new Vector4(0.0f, 0.0f, 0.0f, 0.0f));
OutlineColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLower())
{
case "sprite":
Sprites.Add(new Sprite(subElement));
break;
}
}
}
}
}
+1 -1
View File
@@ -92,7 +92,7 @@ namespace Subsurface
t.SetData<Color>( t.SetData<Color>(
new Color[] { Color.White });// fill the texture with white new Color[] { Color.White });// fill the texture with white
style = new GUIStyle("Content/HUD/style.xml"); style = new GUIStyle("Content/UI/style.xml");
} }
public static void DrawLine(SpriteBatch sb, Vector2 start, Vector2 end, Color clr, float depth = 0.0f) public static void DrawLine(SpriteBatch sb, Vector2 start, Vector2 end, Color clr, float depth = 0.0f)
+29 -18
View File
@@ -7,6 +7,7 @@ namespace Subsurface
class GUIButton : GUIComponent class GUIButton : GUIComponent
{ {
protected GUITextBlock textBlock; protected GUITextBlock textBlock;
protected GUIFrame frame;
public delegate bool OnClickedHandler(GUIButton button, object obj); public delegate bool OnClickedHandler(GUIButton button, object obj);
public OnClickedHandler OnClicked; public OnClickedHandler OnClicked;
@@ -22,22 +23,26 @@ namespace Subsurface
set { textBlock.Text = value; } set { textBlock.Text = value; }
} }
public GUIButton(Rectangle rect, string text, GUIStyle style, Alignment alignment, GUIComponent parent = null) public GUIButton(Rectangle rect, string text, GUIStyle style, GUIComponent parent = null)
: this(rect, text, style.foreGroundColor, alignment, parent) : this(rect, text, null, Alignment.Left, style, parent)
{
hoverColor = style.hoverColor;
selectedColor = style.selectedColor;
}
public GUIButton(Rectangle rect, string text, Color color, GUIComponent parent = null)
: this(rect, text, color, (Alignment.Left | Alignment.Top), parent)
{ {
} }
public GUIButton(Rectangle rect, string text, Color color, Alignment alignment, GUIComponent parent = null) public GUIButton(Rectangle rect, string text, Alignment alignment, GUIStyle style, GUIComponent parent = null)
: this(rect, text, null, alignment, style, parent)
{
}
public GUIButton(Rectangle rect, string text, Color? color, GUIStyle style, GUIComponent parent = null)
: this(rect, text, color, (Alignment.Left | Alignment.Top), style, parent)
{
}
public GUIButton(Rectangle rect, string text, Color? color, Alignment alignment, GUIStyle style, GUIComponent parent = null)
:base (style)
{ {
this.rect = rect; this.rect = rect;
this.color = color; if (color!=null) this.color = (Color)color;
this.alignment = alignment; this.alignment = alignment;
Enabled = true; Enabled = true;
@@ -45,8 +50,12 @@ namespace Subsurface
if (parent != null) if (parent != null)
parent.AddChild(this); parent.AddChild(this);
textBlock = new GUITextBlock(new Rectangle(0,0,0,0), text, Color.Transparent, Color.Black, (Alignment.CenterX | Alignment.CenterY), this); frame = new GUIFrame(new Rectangle(0,0,0,0), style, this);
if (style!=null) style.Apply(frame, this);
textBlock = new GUITextBlock(new Rectangle(0, 0, 0, 0), text,
Color.Transparent, (this.style==null) ? Color.Black : this.style.textColor,
Alignment.Center, style, this);
} }
public override void Draw(SpriteBatch spriteBatch) public override void Draw(SpriteBatch spriteBatch)
@@ -74,15 +83,17 @@ namespace Subsurface
state = ComponentState.None; state = ComponentState.None;
} }
Color currColor = color; frame.State = state;
if (state == ComponentState.Hover) currColor = hoverColor;
if (state == ComponentState.Selected) currColor = selectedColor;
GUI.DrawRectangle(spriteBatch, rect, currColor * alpha, true); //Color currColor = color;
//if (state == ComponentState.Hover) currColor = hoverColor;
//if (state == ComponentState.Selected) currColor = selectedColor;
//spriteBatch.DrawString(HUD.font, text, new Vector2(rect.X+rect.Width/2, rect.Y+rect.Height/2), Color.Black, 0.0f, new Vector2(0.5f,0.5f), 1.0f, SpriteEffects.None, 0.0f); //GUI.DrawRectangle(spriteBatch, rect, currColor * alpha, true);
GUI.DrawRectangle(spriteBatch, rect, Color.Black * alpha, false); ////spriteBatch.DrawString(HUD.font, text, new Vector2(rect.X+rect.Width/2, rect.Y+rect.Height/2), Color.Black, 0.0f, new Vector2(0.5f,0.5f), 1.0f, SpriteEffects.None, 0.0f);
//GUI.DrawRectangle(spriteBatch, rect, Color.Black * alpha, false);
DrawChildren(spriteBatch); DrawChildren(spriteBatch);
+45 -20
View File
@@ -9,14 +9,15 @@ namespace Subsurface
{ {
abstract class GUIComponent abstract class GUIComponent
{ {
public static GUIComponent MouseOn; public static GUIComponent MouseOn;
protected static KeyboardDispatcher keyboardDispatcher;
public enum ComponentState { None, Hover, Selected}; public enum ComponentState { None, Hover, Selected};
protected Alignment alignment; protected Alignment alignment;
protected static KeyboardDispatcher keyboardDispatcher; protected GUIComponentStyle style;
protected object userData; protected object userData;
@@ -33,7 +34,7 @@ namespace Subsurface
protected ComponentState state; protected ComponentState state;
protected float alpha; //protected float alpha;
public GUIComponent Parent public GUIComponent Parent
{ {
@@ -68,6 +69,12 @@ namespace Subsurface
} }
} }
protected List<Sprite> sprites;
//public Alignment SpriteAlignment { get; set; }
//public bool RepeatSpriteX, RepeatSpriteY;
public Color OutlineColor { get; set; }
public ComponentState State public ComponentState State
{ {
get { return state; } get { return state; }
@@ -110,27 +117,32 @@ namespace Subsurface
} }
public float Alpha //public float Alpha
{ //{
get // get
{ // {
return alpha; // return alpha;
} // }
set // set
{ // {
alpha = MathHelper.Clamp(value, 0.0f, 1.0f); // alpha = MathHelper.Clamp(value, 0.0f, 1.0f);
foreach (GUIComponent child in children) // foreach (GUIComponent child in children)
{ // {
child.Alpha = value; // child.Alpha = value;
} // }
} // }
} //}
protected GUIComponent() protected GUIComponent(GUIStyle style)
{ {
alpha = 1.0f; //alpha = 1.0f;
OutlineColor = Color.Transparent;
sprites = new List<Sprite>();
children = new List<GUIComponent>(); children = new List<GUIComponent>();
if (style!=null) style.Apply(this);
} }
public static void Init(GameWindow window) public static void Init(GameWindow window)
@@ -234,7 +246,20 @@ namespace Subsurface
{ {
rect.Y += parentRect.Y + (int)padding.Y; rect.Y += parentRect.Y + (int)padding.Y;
} }
}
public virtual void ApplyStyle(GUIComponentStyle style)
{
color = style.Color;
hoverColor = style.HoverColor;
selectedColor = style.SelectedColor;
padding = style.Padding;
sprites = style.Sprites;
OutlineColor = style.OutlineColor;
this.style = style;
} }
public virtual void DrawChildren(SpriteBatch spriteBatch) public virtual void DrawChildren(SpriteBatch spriteBatch)
+39 -15
View File
@@ -1,28 +1,29 @@
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System;
namespace Subsurface namespace Subsurface
{ {
class GUIFrame : GUIComponent class GUIFrame : GUIComponent
{ {
public GUIFrame(Rectangle rect, Color color, Alignment alignment, GUIStyle style, GUIComponent parent = null) public GUIFrame(Rectangle rect, GUIStyle style = null, GUIComponent parent = null)
: this(rect, color, alignment, parent) : this(rect, null, (Alignment.Left | Alignment.Top), style, parent)
{
hoverColor = style.hoverColor;
selectedColor = style.selectedColor;
}
public GUIFrame(Rectangle rect, Color color, GUIComponent parent = null)
: this(rect,color,(Alignment.Left | Alignment.Top), parent)
{ {
} }
public GUIFrame(Rectangle rect, Color color, Alignment alignment, GUIComponent parent = null)
public GUIFrame(Rectangle rect, Color color, GUIStyle style = null, GUIComponent parent = null)
: this(rect, color, (Alignment.Left | Alignment.Top), style, parent)
{
}
public GUIFrame(Rectangle rect, Color? color, Alignment alignment, GUIStyle style = null, GUIComponent parent = null)
: base(style)
{ {
this.rect = rect; this.rect = rect;
this.alignment = alignment; this.alignment = alignment;
this.color = color; if (color!=null) this.color = (Color)color;
if (parent != null) if (parent != null)
{ {
@@ -32,17 +33,40 @@ namespace Subsurface
{ {
UpdateDimensions(); UpdateDimensions();
} }
//if (style != null) ApplyStyle(style);
} }
public override void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch) public override void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
{ {
base.Draw(spriteBatch); base.Draw(spriteBatch);
Color newColor = color; Color currColor = color;
if (state == ComponentState.Selected) newColor = selectedColor; if (state == ComponentState.Selected) currColor = selectedColor;
if (state == ComponentState.Hover) newColor = hoverColor; if (state == ComponentState.Hover) currColor = hoverColor;
GUI.DrawRectangle(spriteBatch, rect, currColor * (currColor.A/255.0f), true);
if (sprites != null)
{
foreach (Sprite sprite in sprites)
{
Vector2 startPos = new Vector2(rect.X, rect.Y);
Vector2 size = new Vector2(sprite.SourceRect.Width, sprite.SourceRect.Height);
if (sprite.size.X == 0.0f) size.X = rect.Width;
if (sprite.size.Y == 0.0f) size.Y = rect.Height;
sprite.DrawTiled(spriteBatch, startPos, size, currColor * (currColor.A / 255.0f));
}
}
if (OutlineColor != Color.Transparent)
{
GUI.DrawRectangle(spriteBatch, rect, OutlineColor * (OutlineColor.A/255.0f), false);
}
GUI.DrawRectangle(spriteBatch, rect, newColor * alpha, true);
DrawChildren(spriteBatch); DrawChildren(spriteBatch);
} }
+3 -2
View File
@@ -47,6 +47,7 @@ namespace Subsurface
} }
public GUIImage(Rectangle rect, Sprite sprite, Alignment alignment, GUIComponent parent = null) public GUIImage(Rectangle rect, Sprite sprite, Alignment alignment, GUIComponent parent = null)
: base(null)
{ {
this.rect = rect; this.rect = rect;
@@ -54,7 +55,7 @@ namespace Subsurface
color = Color.White; color = Color.White;
alpha = 1.0f; //alpha = 1.0f;
Scale = 1.0f; Scale = 1.0f;
@@ -75,7 +76,7 @@ namespace Subsurface
if (state == ComponentState.Hover) currColor = hoverColor; if (state == ComponentState.Hover) currColor = hoverColor;
if (state == ComponentState.Selected) currColor = selectedColor; if (state == ComponentState.Selected) currColor = selectedColor;
spriteBatch.Draw(sprite.Texture, new Vector2(rect.X, rect.Y), sourceRect, currColor * alpha, 0.0f, Vector2.Zero, spriteBatch.Draw(sprite.Texture, new Vector2(rect.X, rect.Y), sourceRect, currColor * (currColor.A / 255.0f), 0.0f, Vector2.Zero,
Scale, SpriteEffects.None, 0.0f); Scale, SpriteEffects.None, 0.0f);
DrawChildren(spriteBatch); DrawChildren(spriteBatch);
+28 -10
View File
@@ -16,6 +16,7 @@ namespace Subsurface
public CheckSelectedHandler CheckSelected; public CheckSelectedHandler CheckSelected;
private GUIScrollBar scrollBar; private GUIScrollBar scrollBar;
private GUIFrame frame;
private int totalSize; private int totalSize;
@@ -73,36 +74,46 @@ namespace Subsurface
} }
} }
public GUIListBox(Rectangle rect, GUIStyle style, GUIComponent parent = null)
: this(rect, style, Alignment.TopLeft, parent)
{
}
public GUIListBox(Rectangle rect, GUIStyle style, Alignment alignment, GUIComponent parent = null) public GUIListBox(Rectangle rect, GUIStyle style, Alignment alignment, GUIComponent parent = null)
: this(rect, style.foreGroundColor, alignment, parent) : this(rect, null, style, parent)
{ {
} }
public GUIListBox(Rectangle rect, Color color, GUIComponent parent = null) public GUIListBox(Rectangle rect, Color? color, GUIStyle style = null, GUIComponent parent = null)
: this(rect, color, (Alignment.Left | Alignment.Top), parent) : this(rect, color, (Alignment.Left | Alignment.Top), style, parent)
{ {
} }
public GUIListBox(Rectangle rect, Color color, Alignment alignment, GUIComponent parent = null) public GUIListBox(Rectangle rect, Color? color, Alignment alignment, GUIStyle style = null, GUIComponent parent = null)
: base(style)
{ {
this.rect = rect; this.rect = rect;
this.alignment = alignment; this.alignment = alignment;
this.color = color; if (color!=null) this.color = (Color)color;
if (parent != null) if (parent != null)
parent.AddChild(this); parent.AddChild(this);
this.rect.Width -= 20;
scrollBar = new GUIScrollBar( scrollBar = new GUIScrollBar(
new Rectangle(this.rect.X + this.rect.Width, this.rect.Y, 20, this.rect.Height), color, 1.0f); new Rectangle(this.rect.X + this.rect.Width, this.rect.Y, 20, this.rect.Height), color, 1.0f, style);
frame = new GUIFrame(Rectangle.Empty, style, this);
if (style != null) style.Apply(frame, this);
UpdateScrollBarSize(); UpdateScrollBarSize();
enabled = true; enabled = true;
scrollBarEnabled = true; scrollBarEnabled = true;
scrollBar.BarScroll = 0.0f;
} }
public void Select(object selection) public void Select(object selection)
@@ -126,6 +137,9 @@ namespace Subsurface
public void Select(int childIndex) public void Select(int childIndex)
{ {
//children[0] is the GUIFrame, ignore it
childIndex += 1;
if (childIndex >= children.Count || childIndex<0) return; if (childIndex >= children.Count || childIndex<0) return;
selected = children[childIndex]; selected = children[childIndex];
@@ -142,6 +156,7 @@ namespace Subsurface
totalSize = 0; totalSize = 0;
foreach (GUIComponent child in children) foreach (GUIComponent child in children)
{ {
if (child == frame) continue;
totalSize += (scrollBar.IsHorizontal) ? child.Rect.Width : child.Rect.Height; totalSize += (scrollBar.IsHorizontal) ? child.Rect.Width : child.Rect.Height;
totalSize += spacing; totalSize += spacing;
} }
@@ -162,7 +177,7 @@ namespace Subsurface
float oldSize = scrollBar.BarSize; float oldSize = scrollBar.BarSize;
UpdateScrollBarSize(); UpdateScrollBarSize();
if (scrollBar.BarSize<1.0f && (oldSize>=1.0f || oldScroll==1.0f)) if (scrollBar.BarSize < 1.0f && oldScroll == 1.0f)
{ {
scrollBar.BarScroll = 1.0f; scrollBar.BarScroll = 1.0f;
} }
@@ -199,7 +214,9 @@ namespace Subsurface
public override void Draw(SpriteBatch spriteBatch) public override void Draw(SpriteBatch spriteBatch)
{ {
base.Draw(spriteBatch); base.Draw(spriteBatch);
GUI.DrawRectangle(spriteBatch, rect, color*alpha, true);
frame.Draw(spriteBatch);
//GUI.DrawRectangle(spriteBatch, rect, color*alpha, true);
int x = rect.X, y = rect.Y; int x = rect.X, y = rect.Y;
@@ -219,6 +236,7 @@ namespace Subsurface
for (int i = 0; i < children.Count; i++ ) for (int i = 0; i < children.Count; i++ )
{ {
GUIComponent child = children[i]; GUIComponent child = children[i];
if (child == frame) continue;
child.Rect = new Rectangle(child.Rect.X, y, child.Rect.Width, child.Rect.Height); child.Rect = new Rectangle(child.Rect.X, y, child.Rect.Width, child.Rect.Height);
y += child.Rect.Height + spacing; y += child.Rect.Height + spacing;
@@ -241,7 +259,7 @@ namespace Subsurface
if (CheckSelected() != selected.UserData) selected = null; if (CheckSelected() != selected.UserData) selected = null;
} }
} }
else if (enabled && (MouseOn==this || ( MouseOn!=null && this.IsParentOf(MouseOn))) && child.Rect.Contains(PlayerInput.GetMouseState.Position)) else if (enabled && (MouseOn == this || (MouseOn != null && this.IsParentOf(MouseOn))) && child.Rect.Contains(PlayerInput.GetMouseState.Position))
{ {
child.State = ComponentState.Hover; child.State = ComponentState.Hover;
if (PlayerInput.LeftButtonClicked()) if (PlayerInput.LeftButtonClicked())
+5 -5
View File
@@ -23,9 +23,9 @@ namespace Subsurface
public GUIMessageBox(string header, string text, string[] buttons, Alignment textAlignment = (Alignment.Left | Alignment.Top)) public GUIMessageBox(string header, string text, string[] buttons, Alignment textAlignment = (Alignment.Left | Alignment.Top))
: base(new Rectangle(Game1.GraphicsWidth / 2 - DefaultWidth / 2, Game1.GraphicsHeight / 2 - DefaultHeight / 2, DefaultWidth, DefaultHeight), : base(new Rectangle(Game1.GraphicsWidth / 2 - DefaultWidth / 2, Game1.GraphicsHeight / 2 - DefaultHeight / 2, DefaultWidth, DefaultHeight),
GUI.style.backGroundColor, Alignment.CenterX, GUI.style) null, Alignment.CenterX, GUI.style, null)
{ {
Padding = GUI.style.smallPadding; //Padding = GUI.style.smallPadding;
if (buttons == null || buttons.Length == 0) if (buttons == null || buttons.Length == 0)
{ {
@@ -33,14 +33,14 @@ namespace Subsurface
return; return;
} }
new GUITextBlock(new Rectangle(0, 0, 0, 30), header, Color.Transparent, Color.White, textAlignment, this, true); new GUITextBlock(new Rectangle(0, 0, 0, 30), header, Color.Transparent, Color.White, textAlignment, GUI.style, this, true);
new GUITextBlock(new Rectangle(0, 30, 0, DefaultHeight - 70), text, Color.Transparent, Color.White, textAlignment, this, true); new GUITextBlock(new Rectangle(0, 30, 0, DefaultHeight - 70), text, Color.Transparent, Color.White, textAlignment, GUI.style, this, true);
int x = 0; int x = 0;
this.Buttons = new GUIButton[buttons.Length]; this.Buttons = new GUIButton[buttons.Length];
for (int i = 0; i < buttons.Length; i++) for (int i = 0; i < buttons.Length; i++)
{ {
this.Buttons[i] = new GUIButton(new Rectangle(x, 0, 150, 30), buttons[i], GUI.style, Alignment.Left | Alignment.Bottom, this); this.Buttons[i] = new GUIButton(new Rectangle(x, 0, 150, 30), buttons[i], Alignment.Left | Alignment.Bottom, GUI.style, this);
x += this.Buttons[i].Rect.Width + 20; x += this.Buttons[i].Rect.Width + 20;
} }
+3 -2
View File
@@ -37,6 +37,7 @@ namespace Subsurface
} }
public GUIProgressBar(Rectangle rect, Color color, float barSize, Alignment alignment, GUIComponent parent = null) public GUIProgressBar(Rectangle rect, Color color, float barSize, Alignment alignment, GUIComponent parent = null)
: base(null)
{ {
this.rect = rect; this.rect = rect;
this.color = color; this.color = color;
@@ -49,7 +50,7 @@ namespace Subsurface
if (parent != null) if (parent != null)
parent.AddChild(this); parent.AddChild(this);
frame = new GUIFrame(new Rectangle(0,0,0,0), Color.White, this); frame = new GUIFrame(new Rectangle(0,0,0,0), Color.White, null, this);
this.barSize = barSize; this.barSize = barSize;
UpdateRect(); UpdateRect();
@@ -70,7 +71,7 @@ namespace Subsurface
DrawChildren(spriteBatch); DrawChildren(spriteBatch);
GUI.DrawRectangle(spriteBatch, rect, color*alpha, true); GUI.DrawRectangle(spriteBatch, rect, color * (color.A / 255.0f), true);
} }
} }
+9 -7
View File
@@ -63,22 +63,23 @@ namespace Subsurface
{ {
float oldBarSize = barSize; float oldBarSize = barSize;
barSize = Math.Min(Math.Max(value, 0.0f), 1.0f); barSize = Math.Min(Math.Max(value, 0.0f), 1.0f);
if (barSize!=oldBarSize) UpdateRect(); if (barSize != oldBarSize) UpdateRect();
} }
} }
public GUIScrollBar(Rectangle rect, GUIStyle style, float barSize, GUIComponent parent = null) public GUIScrollBar(Rectangle rect, GUIStyle style, float barSize, GUIComponent parent = null)
: this(rect, style.foreGroundColor, barSize, parent) : this(rect, null, barSize, style, parent)
{ {
} }
public GUIScrollBar(Rectangle rect, Color color, float barSize, GUIComponent parent = null) public GUIScrollBar(Rectangle rect, Color? color, float barSize, GUIStyle style = null, GUIComponent parent = null)
: this(rect, color, barSize, (Alignment.Left | Alignment.Top), parent) : this(rect, color, barSize, Alignment.TopLeft, style, parent)
{ {
} }
public GUIScrollBar(Rectangle rect, Color color, float barSize, Alignment alignment, GUIComponent parent = null) public GUIScrollBar(Rectangle rect, Color? color, float barSize, Alignment alignment, GUIStyle style = null, GUIComponent parent = null)
: base(style)
{ {
this.rect = rect; this.rect = rect;
//GetDimensions(parent); //GetDimensions(parent);
@@ -89,12 +90,13 @@ namespace Subsurface
parent.AddChild(this); parent.AddChild(this);
isHorizontal = (rect.Width > rect.Height); isHorizontal = (rect.Width > rect.Height);
frame = new GUIFrame(new Rectangle(0,0,0,0), Color.White, this); frame = new GUIFrame(new Rectangle(0,0,0,0), Color.White, style, this);
//AddChild(frame); //AddChild(frame);
//System.Diagnostics.Debug.WriteLine(frame.rect); //System.Diagnostics.Debug.WriteLine(frame.rect);
bar = new GUIButton(new Rectangle(0, 0, 0, 0), "", color, this); bar = new GUIButton(new Rectangle(0, 0, 0, 0), "", color, style, this);
bar.OnPressed = SelectBar; bar.OnPressed = SelectBar;
//AddChild(bar); //AddChild(bar);
+39 -22
View File
@@ -1,24 +1,19 @@
using System.Xml.Linq; using System.Xml.Linq;
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework;
using System; using System;
using System.Collections.Generic;
namespace Subsurface namespace Subsurface
{ {
class GUIStyle class GUIStyle
{ {
public readonly Vector4 smallPadding; private Dictionary<string, GUIComponentStyle> componentStyles;
public readonly Vector4 largePadding;
public readonly Color backGroundColor;
public readonly Color foreGroundColor;
public readonly Color textColor;
public readonly Color hoverColor;
public readonly Color selectedColor;
public GUIStyle(string file) public GUIStyle(string file)
{ {
componentStyles = new Dictionary<string, GUIComponentStyle>();
XDocument doc; XDocument doc;
try { doc = XDocument.Load(file); } try { doc = XDocument.Load(file); }
catch (Exception e) catch (Exception e)
@@ -27,24 +22,46 @@ namespace Subsurface
return; return;
} }
smallPadding = ToolBox.GetAttributeVector4(doc.Root, "smallpadding", Vector4.Zero); //smallPadding = ToolBox.GetAttributeVector4(doc.Root, "smallpadding", Vector4.Zero);
largePadding = ToolBox.GetAttributeVector4(doc.Root, "largepadding", Vector4.Zero); //largePadding = ToolBox.GetAttributeVector4(doc.Root, "largepadding", Vector4.Zero);
Vector4 colorVector = ToolBox.GetAttributeVector4(doc.Root, "backgroundcolor", new Vector4(0.0f,0.0f,0.0f,1.0f)); //Vector4 colorVector = ToolBox.GetAttributeVector4(doc.Root, "backgroundcolor", new Vector4(0.0f,0.0f,0.0f,1.0f));
backGroundColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W); //backGroundColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(doc.Root, "foregroundcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); //colorVector = ToolBox.GetAttributeVector4(doc.Root, "foregroundcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
foreGroundColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W); //foreGroundColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(doc.Root, "textcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); //colorVector = ToolBox.GetAttributeVector4(doc.Root, "textcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
textColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W); //textColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(doc.Root, "hovercolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); //colorVector = ToolBox.GetAttributeVector4(doc.Root, "hovercolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
hoverColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W); //hoverColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
colorVector = ToolBox.GetAttributeVector4(doc.Root, "selectedcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); //colorVector = ToolBox.GetAttributeVector4(doc.Root, "selectedcolor", new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
selectedColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W); //selectedColor = new Color(colorVector.X, colorVector.Y, colorVector.Z, colorVector.W);
foreach (XElement subElement in doc.Root.Elements())
{
GUIComponentStyle componentStyle = new GUIComponentStyle(subElement);
componentStyles.Add(subElement.Name.ToString().ToLower(), componentStyle);
}
} }
public void Apply(GUIComponent targetComponent, GUIComponent parent = null)
{
GUIComponentStyle componentStyle = null;
string name = (parent==null) ? targetComponent.GetType().Name.ToLower() : parent.GetType().Name.ToLower();
componentStyles.TryGetValue(name, out componentStyle);
if (componentStyle==null)
{
DebugConsole.ThrowError("Couldn't find a GUI style for "+targetComponent.GetType().Name);
return;
}
targetComponent.ApplyStyle(componentStyle);
}
} }
} }
+27 -11
View File
@@ -61,15 +61,23 @@ namespace Subsurface
get { return caretPos; } get { return caretPos; }
} }
public GUITextBlock(Rectangle rect, string text, GUIStyle style, Alignment alignment, Alignment textAlignment, GUIComponent parent = null, bool wrap = false) public GUITextBlock(Rectangle rect, string text, GUIStyle style, GUIComponent parent = null, bool wrap = false)
: this (rect, text, style.foreGroundColor, style.textColor, alignment, textAlignment, parent, wrap) : this(rect, text, style, Alignment.TopLeft, Alignment.TopLeft, parent, wrap)
{ {
hoverColor = style.hoverColor; //hoverColor = style.hoverColor;
selectedColor = style.selectedColor; //selectedColor = style.selectedColor;
} }
public GUITextBlock(Rectangle rect, string text, Color color, Color textColor, Alignment textAlignment = Alignment.Left, GUIComponent parent = null, bool wrap = false)
: this(rect, text,color, textColor, (Alignment.Left | Alignment.Top), textAlignment, parent, wrap) public GUITextBlock(Rectangle rect, string text, GUIStyle style, Alignment alignment = (Alignment.Left | Alignment.Top), Alignment textAlignment = (Alignment.Left | Alignment.Top), GUIComponent parent = null, bool wrap = false)
: this (rect, text, null, null, alignment, textAlignment, style, parent, wrap)
{
//hoverColor = style.hoverColor;
//selectedColor = style.selectedColor;
}
public GUITextBlock(Rectangle rect, string text, Color? color, Color? textColor, Alignment textAlignment = Alignment.Left, GUIStyle style = null, GUIComponent parent = null, bool wrap = false)
: this(rect, text,color, textColor, (Alignment.Left | Alignment.Top), textAlignment, style, parent, wrap)
{ {
} }
@@ -80,13 +88,21 @@ namespace Subsurface
SetTextPos(); SetTextPos();
} }
public override void ApplyStyle(GUIComponentStyle style)
{
base.ApplyStyle(style);
public GUITextBlock(Rectangle rect, string text, Color color, Color textColor, Alignment alignment, Alignment textAlignment = Alignment.Left, GUIComponent parent = null, bool wrap = false) textColor = style.textColor;
}
public GUITextBlock(Rectangle rect, string text, Color? color, Color? textColor, Alignment alignment, Alignment textAlignment = Alignment.Left, GUIStyle style = null, GUIComponent parent = null, bool wrap = false)
:base (style)
{ {
this.rect = rect; this.rect = rect;
this.color = color; if (color!=null) this.color = (Color)color;
this.textColor = textColor; if (textColor!=null) this.textColor = (Color)textColor;
this.text = text; this.text = text;
this.alignment = alignment; this.alignment = alignment;
@@ -174,7 +190,7 @@ namespace Subsurface
if (state == ComponentState.Hover) currColor = hoverColor; if (state == ComponentState.Hover) currColor = hoverColor;
if (state == ComponentState.Selected) currColor = selectedColor; if (state == ComponentState.Selected) currColor = selectedColor;
GUI.DrawRectangle(spriteBatch, rect, currColor*alpha, true); GUI.DrawRectangle(spriteBatch, rect, currColor*(currColor.A/255.0f), true);
if (TextGetter != null) text = TextGetter(); if (TextGetter != null) text = TextGetter();
@@ -183,7 +199,7 @@ namespace Subsurface
spriteBatch.DrawString(GUI.font, spriteBatch.DrawString(GUI.font,
text, text,
new Vector2(rect.X, rect.Y) + textPos, new Vector2(rect.X, rect.Y) + textPos,
textColor * alpha, textColor * (textColor.A / 255.0f),
0.0f, origin, 1.0f, 0.0f, origin, 1.0f,
SpriteEffects.None, 0.0f); SpriteEffects.None, 0.0f);
} }
+30 -11
View File
@@ -24,6 +24,12 @@ namespace Subsurface
public delegate bool OnTextChangedHandler(GUITextBox textBox, string text); public delegate bool OnTextChangedHandler(GUITextBox textBox, string text);
public OnTextChangedHandler OnTextChanged; public OnTextChangedHandler OnTextChanged;
public bool Enabled
{
get;
set;
}
public override Color Color public override Color Color
{ {
get { return color; } get { return color; }
@@ -68,11 +74,24 @@ namespace Subsurface
} }
} }
public GUITextBox(Rectangle rect, Color color, Color textColor, Alignment alignment, Alignment textAlignment = Alignment.Left, GUIComponent parent = null) public GUITextBox(Rectangle rect, GUIStyle style = null, GUIComponent parent = null)
: this(rect, null, null, Alignment.Left, Alignment.Left, style, parent)
{
}
public GUITextBox(Rectangle rect, Alignment alignment = Alignment.Left, GUIStyle style = null, GUIComponent parent = null)
: this(rect, null, null, alignment, Alignment.Left, style, parent)
{
}
public GUITextBox(Rectangle rect, Color? color, Color? textColor, Alignment alignment, Alignment textAlignment = Alignment.Left, GUIStyle style = null, GUIComponent parent = null)
: base(style)
{ {
this.rect = rect; this.rect = rect;
this.color = color; if (color!=null) this.color = (Color)color;
this.alignment = alignment; this.alignment = alignment;
@@ -81,10 +100,11 @@ namespace Subsurface
if (parent != null) if (parent != null)
parent.AddChild(this); parent.AddChild(this);
textBlock = new GUITextBlock(new Rectangle(0,0,0,0), "", color, textColor, textAlignment, this); textBlock = new GUITextBlock(new Rectangle(0,0,0,0), "", color, textColor, textAlignment, null, this);
textBlock.Padding = new Vector4(10.0f, 0.0f, 10.0f, 0.0f); textBlock.Padding = new Vector4(10.0f, 0.0f, 10.0f, 0.0f);
if (style != null) style.Apply(textBlock, this);
_previousMouse = PlayerInput.GetMouseState; previousMouse = PlayerInput.GetMouseState;
//SetTextPos(); //SetTextPos();
} }
@@ -99,19 +119,18 @@ namespace Subsurface
if (keyboardDispatcher.Subscriber == this) keyboardDispatcher.Subscriber = null; if (keyboardDispatcher.Subscriber == this) keyboardDispatcher.Subscriber = null;
} }
MouseState _previousMouse; MouseState previousMouse;
public override void Update(float deltaTime) public override void Update(float deltaTime)
{ {
if (!Enabled) return;
caretTimer += deltaTime; caretTimer += deltaTime;
caretVisible = ((caretTimer*1000.0f) % 1000) < 500; caretVisible = ((caretTimer*1000.0f) % 1000) < 500;
if (rect.Contains(PlayerInput.GetMouseState.Position)) if (rect.Contains(PlayerInput.GetMouseState.Position))
{ {
state = ComponentState.Hover; state = ComponentState.Hover;
if (PlayerInput.LeftButtonClicked()) if (PlayerInput.LeftButtonClicked()) Select();
{
Select();
}
} }
else else
{ {
@@ -120,7 +139,7 @@ namespace Subsurface
if (keyboardDispatcher.Subscriber == this) if (keyboardDispatcher.Subscriber == this)
{ {
Character.disableControls = true; Character.DisableControls = true;
if (OnEnter != null && PlayerInput.KeyHit(Keys.Enter)) if (OnEnter != null && PlayerInput.KeyHit(Keys.Enter))
{ {
string input = Text; string input = Text;
@@ -143,7 +162,7 @@ namespace Subsurface
GUI.DrawLine(spriteBatch, GUI.DrawLine(spriteBatch,
new Vector2((int)caretPos.X + 2, caretPos.Y + 3), new Vector2((int)caretPos.X + 2, caretPos.Y + 3),
new Vector2((int)caretPos.X + 2, caretPos.Y + rect.Height - 3), new Vector2((int)caretPos.X + 2, caretPos.Y + rect.Height - 3),
textBlock.TextColor * alpha); textBlock.TextColor * (textBlock.TextColor.A / 255.0f));
} }
} }
+4 -3
View File
@@ -15,12 +15,13 @@ namespace Subsurface
bool selected; bool selected;
public GUITickBox(Rectangle rect, string label, Alignment alignment, GUIComponent parent) public GUITickBox(Rectangle rect, string label, Alignment alignment, GUIComponent parent)
: base(null)
{ {
if (parent != null) if (parent != null)
parent.AddChild(this); parent.AddChild(this);
box = new GUIFrame(new Rectangle(rect.X, rect.Y, 30, 30), Color.LightGray, this); box = new GUIFrame(new Rectangle(rect.X, rect.Y, 30, 30), Color.LightGray, null, this);
text = new GUITextBlock(new Rectangle(rect.X + 40, rect.Y, 200, 30), label, Color.Transparent, Color.White, Alignment.Left | Alignment.CenterY, this); text = new GUITextBlock(new Rectangle(rect.X + 40, rect.Y, 200, 30), label, Color.Transparent, Color.White, Alignment.Left | Alignment.CenterY, null, this);
} }
public override void Update(float deltaTime) public override void Update(float deltaTime)
@@ -53,7 +54,7 @@ namespace Subsurface
if (selected) if (selected)
{ {
GUI.DrawRectangle(spriteBatch, new Rectangle(box.Rect.X + 5, box.Rect.Y + 5, box.Rect.Width - 10, box.Rect.Height - 10), Color.Green * alpha, true); GUI.DrawRectangle(spriteBatch, new Rectangle(box.Rect.X + 5, box.Rect.Y + 5, box.Rect.Width - 10, box.Rect.Height - 10), Color.Green * (color.A / 255.0f), true);
} }
} }
} }
+24 -29
View File
@@ -10,12 +10,9 @@ using Subsurface.Particles;
namespace Subsurface namespace Subsurface
{ {
/// <summary>
/// This is the main type for your game
/// </summary>
class Game1 : Game class Game1 : Game
{ {
public static GraphicsDeviceManager graphics; public static GraphicsDeviceManager Graphics;
static int graphicsWidth, graphicsHeight; static int graphicsWidth, graphicsHeight;
static SpriteBatch spriteBatch; static SpriteBatch spriteBatch;
@@ -23,7 +20,7 @@ namespace Subsurface
public static FrameCounter frameCounter; public static FrameCounter frameCounter;
public static readonly Version version = Assembly.GetEntryAssembly().GetName().Version; public static readonly Version Version = Assembly.GetEntryAssembly().GetName().Version;
public static GameScreen GameScreen; public static GameScreen GameScreen;
public static MainMenuScreen MainMenuScreen; public static MainMenuScreen MainMenuScreen;
@@ -36,17 +33,16 @@ namespace Subsurface
public static GameSession GameSession; public static GameSession GameSession;
public static GameClient Client; public static NetworkMember NetworkMember;
public static GameServer Server;
public static ParticleManager particleManager; public static ParticleManager particleManager;
public static TextureLoader textureLoader; public static TextureLoader textureLoader;
public static World world; public static World World;
public static Random localRandom; //public static Random localRandom;
public static Random random; //public static Random random;
//private Stopwatch renderTimer; //private Stopwatch renderTimer;
//public static int renderTimeElapsed; //public static int renderTimeElapsed;
@@ -57,7 +53,6 @@ namespace Subsurface
get { return GameScreen.Cam; } get { return GameScreen.Cam; }
} }
public static int GraphicsWidth public static int GraphicsWidth
{ {
get { return graphicsWidth; } get { return graphicsWidth; }
@@ -68,16 +63,26 @@ namespace Subsurface
get { return graphicsHeight; } get { return graphicsHeight; }
} }
public static GameServer Server
{
get { return NetworkMember as GameServer; }
}
public static GameClient Client
{
get { return NetworkMember as GameClient; }
}
public Game1() public Game1()
{ {
graphics = new GraphicsDeviceManager(this); Graphics = new GraphicsDeviceManager(this);
graphicsWidth = 1280; graphicsWidth = 1280;
graphicsHeight = 720; graphicsHeight = 720;
//graphics.IsFullScreen = true; //graphics.IsFullScreen = true;
graphics.PreferredBackBufferWidth = graphicsWidth; Graphics.PreferredBackBufferWidth = graphicsWidth;
graphics.PreferredBackBufferHeight = graphicsHeight; Graphics.PreferredBackBufferHeight = graphicsHeight;
Content.RootDirectory = "Content"; Content.RootDirectory = "Content";
//graphics.SynchronizeWithVerticalRetrace = false; //graphics.SynchronizeWithVerticalRetrace = false;
@@ -92,12 +97,9 @@ namespace Subsurface
IsFixedTimeStep = false; IsFixedTimeStep = false;
//TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 55); //TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 55);
world = new World(new Vector2(0, -9.82f)); World = new World(new Vector2(0, -9.82f));
Settings.VelocityIterations = 2; Settings.VelocityIterations = 2;
Settings.PositionIterations = 1; Settings.PositionIterations = 1;
random = new Random();
localRandom = new Random();
} }
/// <summary> /// <summary>
@@ -151,7 +153,7 @@ namespace Subsurface
AmbientSoundManager.Init("Content/Sounds/Sounds.xml"); AmbientSoundManager.Init("Content/Sounds/Sounds.xml");
Submarine.Preload("Content/SavedMaps"); Submarine.Preload("Content/SavedMaps");
GameScreen = new GameScreen(graphics.GraphicsDevice); GameScreen = new GameScreen(Graphics.GraphicsDevice);
MainMenuScreen = new MainMenuScreen(this); MainMenuScreen = new MainMenuScreen(this);
LobbyScreen = new LobbyScreen(); LobbyScreen = new LobbyScreen();
NetLobbyScreen = new NetLobbyScreen(); NetLobbyScreen = new NetLobbyScreen();
@@ -190,18 +192,11 @@ namespace Subsurface
DebugConsole.Update(this, (float)deltaTime); DebugConsole.Update(this, (float)deltaTime);
if (!DebugConsole.IsOpen || Server != null || Client != null) Screen.Selected.Update(deltaTime); if (!DebugConsole.IsOpen || NetworkMember != null) Screen.Selected.Update(deltaTime);
GUI.Update((float)deltaTime); GUI.Update((float)deltaTime);
if (Server != null) if (NetworkMember != null) NetworkMember.Update();
{
Server.Update();
}
else if (Client != null)
{
Client.Update();
}
else else
{ {
NetworkEvent.events.Clear(); NetworkEvent.events.Clear();
@@ -228,7 +223,7 @@ namespace Subsurface
protected override void OnExiting(object sender, EventArgs args) protected override void OnExiting(object sender, EventArgs args)
{ {
if (Client != null) Client.Disconnect(); if (NetworkMember != null) NetworkMember.Disconnect();
base.OnExiting(sender, args); base.OnExiting(sender, args);
} }
+10 -11
View File
@@ -33,7 +33,7 @@ namespace Subsurface
guiFrame = new GUIFrame(new Rectangle(0, 50, 150, 450), Color.Transparent); guiFrame = new GUIFrame(new Rectangle(0, 50, 150, 450), Color.Transparent);
listBox = new GUIListBox(new Rectangle(0, 0, 150, 0), Color.Transparent, guiFrame); listBox = new GUIListBox(new Rectangle(0, 0, 150, 0), Color.Transparent, null, guiFrame);
listBox.ScrollBarEnabled = false; listBox.ScrollBarEnabled = false;
listBox.OnSelected = SelectCharacter; listBox.OnSelected = SelectCharacter;
@@ -72,29 +72,28 @@ namespace Subsurface
public void AddCharacter(Character character) public void AddCharacter(Character character)
{ {
characters.Add(character); characters.Add(character);
if (!characterInfos.Contains(character.info)) if (!characterInfos.Contains(character.Info))
{ {
characterInfos.Add(character.info); characterInfos.Add(character.Info);
} }
GUIFrame frame = new GUIFrame(new Rectangle(0, 0, 0, 40), Color.Transparent, listBox); GUIFrame frame = new GUIFrame(new Rectangle(0, 0, 0, 40), Color.Transparent, null, listBox);
frame.UserData = character; frame.UserData = character;
frame.Padding = new Vector4(5.0f, 5.0f, 5.0f, 5.0f); frame.Padding = new Vector4(5.0f, 5.0f, 5.0f, 5.0f);
frame.HoverColor = Color.LightGray * 0.5f; frame.HoverColor = Color.LightGray * 0.5f;
frame.SelectedColor = Color.Gold * 0.5f; frame.SelectedColor = Color.Gold * 0.5f;
string name = character.info.name.Replace(' ', '\n'); string name = character.Info.Name.Replace(' ', '\n');
GUITextBlock textBlock = new GUITextBlock( GUITextBlock textBlock = new GUITextBlock(
new Rectangle(40, 0, 0, 25), new Rectangle(40, 0, 0, 25),
name, name,
Color.Transparent, Color.White, Color.Transparent, Color.White,
Alignment.Left, Alignment.Left, Alignment.Left,
Alignment.Left, null, frame);
frame);
textBlock.Padding = new Vector4(5.0f, 0.0f, 5.0f, 0.0f); textBlock.Padding = new Vector4(5.0f, 0.0f, 5.0f, 0.0f);
new GUIImage(new Rectangle(-10, -10, 0, 0), character.animController.limbs[0].sprite, Alignment.Left, frame); new GUIImage(new Rectangle(-10, -10, 0, 0), character.AnimController.limbs[0].sprite, Alignment.Left, frame);
} }
public void Update(float deltaTime) public void Update(float deltaTime)
@@ -123,7 +122,7 @@ namespace Subsurface
WayPoint randomWayPoint = WayPoint.GetRandom(WayPoint.SpawnType.Human); WayPoint randomWayPoint = WayPoint.GetRandom(WayPoint.SpawnType.Human);
Vector2 position = (randomWayPoint == null) ? Vector2.Zero : randomWayPoint.SimPosition; Vector2 position = (randomWayPoint == null) ? Vector2.Zero : randomWayPoint.SimPosition;
Character character = new Character(ci.file, position, ci); Character character = new Character(ci.File, position, ci);
Character.Controlled = character; Character.Controlled = character;
AddCharacter(character); AddCharacter(character);
} }
@@ -137,7 +136,7 @@ namespace Subsurface
{ {
if (!c.IsDead) continue; if (!c.IsDead) continue;
CharacterInfo deadInfo = characterInfos.Find(x => c.info == x); CharacterInfo deadInfo = characterInfos.Find(x => c.Info == x);
if (deadInfo != null) characterInfos.Remove(deadInfo); if (deadInfo != null) characterInfos.Remove(deadInfo);
} }
+22 -27
View File
@@ -57,20 +57,20 @@ namespace Subsurface
guiRoot = new GUIFrame(new Rectangle(0,0,Game1.GraphicsWidth,Game1.GraphicsWidth), Color.Transparent); guiRoot = new GUIFrame(new Rectangle(0,0,Game1.GraphicsWidth,Game1.GraphicsWidth), Color.Transparent);
map = new Map(Game1.random.Next(), 500); map = new Map(Rand.Int(), 500);
int width = 350, height = 100; int width = 350, height = 100;
if (Game1.Client!=null || Game1.Server!=null) if (Game1.NetworkMember!=null)
{ {
chatBox = new GUIListBox(new Rectangle( chatBox = new GUIListBox(new Rectangle(
Game1.GraphicsWidth - (int)GUI.style.smallPadding.X - width, Game1.GraphicsWidth - 20 - width,
Game1.GraphicsHeight - (int)GUI.style.smallPadding.W*2 - 25 - height, Game1.GraphicsHeight - 40 - 25 - height,
width, height), width, height),
Color.White * 0.5f, guiRoot); Color.White * 0.5f, GUI.style, guiRoot);
textBox = new GUITextBox( textBox = new GUITextBox(
new Rectangle(chatBox.Rect.X, chatBox.Rect.Y + chatBox.Rect.Height + (int)GUI.style.smallPadding.W, chatBox.Rect.Width, 25), new Rectangle(chatBox.Rect.X, chatBox.Rect.Y + chatBox.Rect.Height + 20, chatBox.Rect.Width, 25),
Color.White * 0.5f, Color.Black, Alignment.Bottom, Alignment.Left, guiRoot); Color.White * 0.5f, Color.Black, Alignment.Bottom, Alignment.Left, GUI.style, guiRoot);
textBox.OnEnter = EnterChatMessage; textBox.OnEnter = EnterChatMessage;
} }
@@ -91,8 +91,8 @@ namespace Subsurface
} }
public GameSession(Submarine selectedMap, string savePath, string filePath) public GameSession(Submarine selectedSub, string savePath, string filePath)
: this(selectedMap) : this(selectedSub)
{ {
XDocument doc = ToolBox.TryLoadXml(filePath); XDocument doc = ToolBox.TryLoadXml(filePath);
if (doc == null) return; if (doc == null) return;
@@ -111,27 +111,26 @@ namespace Subsurface
this.savePath = savePath; this.savePath = savePath;
} }
public void StartShift(TimeSpan duration, Level level) public void StartShift(TimeSpan duration, string levelSeed, int scriptedEventCount = 1)
{ {
submarine.Load();
level.Generate(submarine==null ? 100.0f : Math.Max(Submarine.Borders.Width, Submarine.Borders.Height));
this.level = level;
StartShift(duration, 1);
} }
public void StartShift(TimeSpan duration, int scriptedEventCount = 1) public void StartShift(TimeSpan duration, Level level, int scriptedEventCount = 1)
{ {
//if (crewManager.characterInfos.Count == 0) return; //if (crewManager.characterInfos.Count == 0) return;
this.level = level;
if (Submarine.Loaded!=submarine) submarine.Load(); if (Submarine.Loaded!=submarine) submarine.Load();
if (gameMode!=null) gameMode.Start(duration); if (gameMode!=null) gameMode.Start(duration);
if (level!=null) if (level != null)
{ {
level.Generate(submarine == null ? 100.0f : Math.Max(Submarine.Borders.Width, Submarine.Borders.Height));
submarine.SetPosition(level.StartPosition); submarine.SetPosition(level.StartPosition);
} }
@@ -177,13 +176,9 @@ namespace Subsurface
{ {
if (string.IsNullOrWhiteSpace(message)) return false; if (string.IsNullOrWhiteSpace(message)) return false;
if (Game1.Server!=null) else if (Game1.NetworkMember != null)
{ {
Game1.Server.SendChatMessage(message); Game1.NetworkMember.SendChatMessage(Game1.NetworkMember.Name + ": " + message);
}
else if (Game1.Client!=null)
{
Game1.Client.SendChatMessage(Game1.Client.Name + ": " + message);
} }
textBox.Deselect(); textBox.Deselect();
@@ -195,9 +190,9 @@ namespace Subsurface
{ {
GUITextBlock msg = new GUITextBlock(new Rectangle(0, 0, 0, 20), text, GUITextBlock msg = new GUITextBlock(new Rectangle(0, 0, 0, 20), text,
((chatBox.CountChildren % 2) == 0) ? Color.Transparent : Color.Black * 0.1f, color, ((chatBox.CountChildren % 2) == 0) ? Color.Transparent : Color.Black * 0.1f, color,
Alignment.Left, null, true); Alignment.Left, null, null, true);
msg.Padding = new Vector4(GUI.style.smallPadding.X, 0, 0, 0); msg.Padding = new Vector4(20.0f, 0, 0, 0);
chatBox.AddChild(msg); chatBox.AddChild(msg);
while (chatBox.CountChildren > 20) while (chatBox.CountChildren > 20)
@@ -244,7 +239,7 @@ namespace Subsurface
//crewManager.Draw(spriteBatch); //crewManager.Draw(spriteBatch);
taskManager.Draw(spriteBatch); taskManager.Draw(spriteBatch);
gameMode.Draw(spriteBatch); if (gameMode!=null) gameMode.Draw(spriteBatch);
//chatBox.Draw(spriteBatch); //chatBox.Draw(spriteBatch);
//textBox.Draw(spriteBatch); //textBox.Draw(spriteBatch);
+6 -6
View File
@@ -31,7 +31,7 @@ namespace Subsurface
crewManager = new CrewManager(); crewManager = new CrewManager();
hireManager = new HireManager(); hireManager = new HireManager();
endShiftButton = new GUIButton(new Rectangle(Game1.GraphicsWidth - 240, 20, 100, 25), "End shift", Color.White, Alignment.Left | Alignment.Top); endShiftButton = new GUIButton(new Rectangle(Game1.GraphicsWidth - 240, 20, 100, 25), "End shift", Alignment.Left | Alignment.Top, GUI.style);
endShiftButton.OnClicked = EndShift; endShiftButton.OnClicked = EndShift;
hireManager.GenerateCharacters("Content/Characters/Human/human.xml", 10); hireManager.GenerateCharacters("Content/Characters/Human/human.xml", 10);
@@ -61,12 +61,12 @@ namespace Subsurface
public bool TryHireCharacter(CharacterInfo characterInfo) public bool TryHireCharacter(CharacterInfo characterInfo)
{ {
if (crewManager.Money < characterInfo.salary) return false; if (crewManager.Money < characterInfo.Salary) return false;
hireManager.availableCharacters.Remove(characterInfo); hireManager.availableCharacters.Remove(characterInfo);
crewManager.characterInfos.Add(characterInfo); crewManager.characterInfos.Add(characterInfo);
crewManager.Money -= characterInfo.salary; crewManager.Money -= characterInfo.Salary;
return true; return true;
} }
@@ -137,7 +137,7 @@ namespace Subsurface
sb.Append("Casualties: \n"); sb.Append("Casualties: \n");
foreach (Character c in casualties) foreach (Character c in casualties)
{ {
sb.Append(" - " + c.info.name + "\n"); sb.Append(" - " + c.Info.Name + "\n");
} }
} }
else else
@@ -151,9 +151,9 @@ namespace Subsurface
} }
crewManager.EndShift(); crewManager.EndShift();
for (int i = Character.characterList.Count-1; i>=0; i--) for (int i = Character.CharacterList.Count-1; i>=0; i--)
{ {
Character.characterList.RemoveAt(i); Character.CharacterList.RemoveAt(i);
} }
Game1.GameSession.EndShift(""); Game1.GameSession.EndShift("");
+9 -9
View File
@@ -31,9 +31,9 @@ namespace Subsurface
if (DateTime.Now >= endTime) if (DateTime.Now >= endTime)
{ {
string endMessage = traitor.character.info.name + " was a traitor! "; string endMessage = traitor.character.Info.Name + " was a traitor! ";
endMessage += (traitor.character.info.gender == Gender.Male) ? "His" : "Her"; endMessage += (traitor.character.Info.Gender == Gender.Male) ? "His" : "Her";
endMessage += " task was to assassinate " + target.character.info.name + ". The task was unsuccesful."; endMessage += " task was to assassinate " + target.character.Info.Name + ". The task was unsuccesful.";
End(endMessage); End(endMessage);
return; return;
} }
@@ -44,13 +44,13 @@ namespace Subsurface
int clientCount = Game1.Server.connectedClients.Count(); int clientCount = Game1.Server.connectedClients.Count();
if (clientCount < 2) return; if (clientCount < 2) return;
int traitorIndex = Game1.localRandom.Next(clientCount); int traitorIndex = Rand.Int(clientCount, false);
traitor = Game1.Server.connectedClients[traitorIndex]; traitor = Game1.Server.connectedClients[traitorIndex];
int targetIndex = 0; int targetIndex = 0;
while (targetIndex==traitorIndex) while (targetIndex == traitorIndex)
{ {
targetIndex = Game1.localRandom.Next(clientCount); targetIndex = Rand.Int(clientCount, false);
} }
target = Game1.Server.connectedClients[targetIndex]; target = Game1.Server.connectedClients[targetIndex];
@@ -61,9 +61,9 @@ namespace Subsurface
{ {
if (target.character.IsDead) if (target.character.IsDead)
{ {
string endMessage = traitor.character.info.name + " was a traitor! "; string endMessage = traitor.character.Info.Name + " was a traitor! ";
endMessage += (traitor.character.info.gender == Gender.Male) ? "his" : "her"; endMessage += (traitor.character.Info.Gender == Gender.Male) ? "his" : "her";
endMessage += " task was to assassinate " + target.character.info.name + ". The task was succesful."; endMessage += " task was to assassinate " + target.character.Info.Name + ". The task was succesful.";
End(endMessage); End(endMessage);
} }
} }
+7 -7
View File
@@ -120,7 +120,7 @@ namespace Subsurface.Items.Components
(int)doorSprite.size.Y); (int)doorSprite.size.Y);
body = new PhysicsBody(BodyFactory.CreateRectangle(Game1.world, body = new PhysicsBody(BodyFactory.CreateRectangle(Game1.World,
ConvertUnits.ToSimUnits(Math.Max(doorRect.Width, 1)), ConvertUnits.ToSimUnits(Math.Max(doorRect.Width, 1)),
ConvertUnits.ToSimUnits(Math.Max(doorRect.Height, 1)), ConvertUnits.ToSimUnits(Math.Max(doorRect.Height, 1)),
1.5f)); 1.5f));
@@ -281,10 +281,10 @@ namespace Subsurface.Items.Components
Vector2 simSize = ConvertUnits.ToSimUnits(new Vector2(item.Rect.Width, Vector2 simSize = ConvertUnits.ToSimUnits(new Vector2(item.Rect.Width,
item.Rect.Height * (1.0f - openState))); item.Rect.Height * (1.0f - openState)));
foreach (Character c in Character.characterList) foreach (Character c in Character.CharacterList)
{ {
int dir = Math.Sign(c.animController.limbs[0].SimPosition.X - simPos.X); int dir = Math.Sign(c.AnimController.limbs[0].SimPosition.X - simPos.X);
foreach (Limb l in c.animController.limbs) foreach (Limb l in c.AnimController.limbs)
{ {
if (l.SimPosition.Y < simPos.Y || l.SimPosition.Y > simPos.Y - simSize.Y) continue; if (l.SimPosition.Y < simPos.Y || l.SimPosition.Y > simPos.Y - simSize.Y) continue;
if (Math.Abs(l.SimPosition.X - simPos.X) > simSize.X * 2.0f) continue; if (Math.Abs(l.SimPosition.X - simPos.X) > simSize.X * 2.0f) continue;
@@ -300,7 +300,7 @@ namespace Subsurface.Items.Components
{ {
base.Remove(); base.Remove();
Game1.world.RemoveBody(body.FarseerBody); Game1.World.RemoveBody(body.FarseerBody);
if (linkedGap!=null) linkedGap.Remove(); if (linkedGap!=null) linkedGap.Remove();
@@ -312,11 +312,11 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
if (connection.name=="toggle") if (connection.Name=="toggle")
{ {
isOpen = !isOpen; isOpen = !isOpen;
} }
else if (connection.name == "set_state") else if (connection.Name == "set_state")
{ {
isOpen = (signal!="0"); isOpen = (signal!="0");
} }
@@ -129,7 +129,7 @@ namespace Subsurface.Items.Components
if (!item.body.Enabled) if (!item.body.Enabled)
{ {
Limb rightHand = picker.animController.GetLimb(LimbType.RightHand); Limb rightHand = picker.AnimController.GetLimb(LimbType.RightHand);
item.SetTransform(rightHand.SimPosition, 0.0f); item.SetTransform(rightHand.SimPosition, 0.0f);
} }
@@ -197,9 +197,9 @@ namespace Subsurface.Items.Components
ApplyStatusEffects(ActionType.OnActive, deltaTime, picker); ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);
if (item.body.Dir != picker.animController.Dir) Flip(item); if (item.body.Dir != picker.AnimController.Dir) Flip(item);
AnimController ac = picker.animController; AnimController ac = picker.AnimController;
ac.HoldItem(deltaTime, cam, item, handlePos, holdPos, aimPos, holdAngle); ac.HoldItem(deltaTime, cam, item, handlePos, holdPos, aimPos, holdAngle);
} }
@@ -81,7 +81,7 @@ namespace Subsurface.Items.Components
if (item.body!= null && !item.body.Enabled) if (item.body!= null && !item.body.Enabled)
{ {
Limb rightHand = picker.animController.GetLimb(LimbType.RightHand); Limb rightHand = picker.AnimController.GetLimb(LimbType.RightHand);
item.SetTransform(rightHand.SimPosition, 0.0f); item.SetTransform(rightHand.SimPosition, 0.0f);
item.body.Enabled = true; item.body.Enabled = true;
} }
@@ -58,7 +58,7 @@ namespace Subsurface.Items.Components
reload = 1.0f; reload = 1.0f;
List<Body> limbBodies = new List<Body>(); List<Body> limbBodies = new List<Body>();
foreach (Limb l in character.animController.limbs) foreach (Limb l in character.AnimController.limbs)
{ {
limbBodies.Add(l.body.FarseerBody); limbBodies.Add(l.body.FarseerBody);
} }
@@ -104,7 +104,7 @@ namespace Subsurface.Items.Components
(float)Math.Sin(item.body.Rotation)) * range * item.body.Dir; (float)Math.Sin(item.body.Rotation)) * range * item.body.Dir;
List<Body> ignoredBodies = new List<Body>(); List<Body> ignoredBodies = new List<Body>();
foreach (Limb limb in character.animController.limbs) foreach (Limb limb in character.AnimController.limbs)
{ {
ignoredBodies.Add(limb.body.FarseerBody); ignoredBodies.Add(limb.body.FarseerBody);
} }
@@ -64,9 +64,9 @@ namespace Subsurface.Items.Components
ApplyStatusEffects(ActionType.OnActive, deltaTime, picker); ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);
if (item.body.Dir != picker.animController.Dir) Flip(item); if (item.body.Dir != picker.AnimController.Dir) Flip(item);
AnimController ac = picker.animController; AnimController ac = picker.AnimController;
ac.HoldItem(deltaTime, cam, item, handlePos, new Vector2(throwPos, 0.0f), aimPos, holdAngle); ac.HoldItem(deltaTime, cam, item, handlePos, new Vector2(throwPos, 0.0f), aimPos, holdAngle);
+15 -15
View File
@@ -15,18 +15,18 @@ namespace Subsurface
{ {
class ItemSound class ItemSound
{ {
public readonly Sound sound; public readonly Sound Sound;
public readonly ActionType type; public readonly ActionType Type;
public string volumeProperty; public string VolumeProperty;
public readonly float range; public readonly float Range;
public ItemSound(Sound sound, ActionType type, float range) public ItemSound(Sound sound, ActionType type, float range)
{ {
this.sound = sound; this.Sound = sound;
this.type = type; this.Type = type;
this.range = range; this.Range = range;
} }
} }
@@ -191,7 +191,7 @@ namespace Subsurface
guiFrame = new GUIFrame( guiFrame = new GUIFrame(
new Rectangle((int)rect.X, (int)rect.Y, (int)rect.Z, (int)rect.W), new Rectangle((int)rect.X, (int)rect.Y, (int)rect.Z, (int)rect.W),
new Color(color.X, color.Y, color.Z), alignment); new Color(color.X, color.Y, color.Z), alignment);
guiFrame.Alpha = color.W; //guiFrame.Alpha = color.W;
break; break;
case "sound": case "sound":
@@ -218,7 +218,7 @@ namespace Subsurface
float range = ToolBox.GetAttributeFloat(subElement, "range", 800.0f); float range = ToolBox.GetAttributeFloat(subElement, "range", 800.0f);
ItemSound itemSound = new ItemSound(sound, type, range); ItemSound itemSound = new ItemSound(sound, type, range);
itemSound.volumeProperty = ToolBox.GetAttributeString(subElement, "volume", ""); itemSound.VolumeProperty = ToolBox.GetAttributeString(subElement, "volume", "");
sounds.Add(itemSound); sounds.Add(itemSound);
break; break;
} }
@@ -233,16 +233,16 @@ namespace Subsurface
ItemSound itemSound = null; ItemSound itemSound = null;
if (!loop || !Sounds.SoundManager.IsPlaying(loopingSoundIndex)) if (!loop || !Sounds.SoundManager.IsPlaying(loopingSoundIndex))
{ {
List<ItemSound> matchingSounds = sounds.FindAll(x => x.type == type); List<ItemSound> matchingSounds = sounds.FindAll(x => x.Type == type);
if (matchingSounds.Count == 0) return; if (matchingSounds.Count == 0) return;
int index = Game1.localRandom.Next(matchingSounds.Count); int index = Rand.Int(matchingSounds.Count);
itemSound = sounds[index]; itemSound = sounds[index];
if (itemSound.volumeProperty != "") if (itemSound.VolumeProperty != "")
{ {
ObjectProperty op = null; ObjectProperty op = null;
if (properties.TryGetValue(itemSound.volumeProperty.ToLower(), out op)) if (properties.TryGetValue(itemSound.VolumeProperty.ToLower(), out op))
{ {
float newVolume = 0.0f; float newVolume = 0.0f;
float.TryParse(op.GetValue().ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out newVolume); float.TryParse(op.GetValue().ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out newVolume);
@@ -258,12 +258,12 @@ namespace Subsurface
if (loop) if (loop)
{ {
//if (loopingSound != null && loopingSound.volumeProperty != "") volume = float.Parse(properties[loopingSound.volumeProperty].GetValue().ToString()); //if (loopingSound != null && loopingSound.volumeProperty != "") volume = float.Parse(properties[loopingSound.volumeProperty].GetValue().ToString());
loopingSoundIndex = loopingSound.sound.Loop(loopingSoundIndex, volume, position, loopingSound.range); loopingSoundIndex = loopingSound.Sound.Loop(loopingSoundIndex, volume, position, loopingSound.Range);
} }
else else
{ {
itemSound.sound.Play(volume, itemSound.range, position); itemSound.Sound.Play(volume, itemSound.Range, position);
} }
} }
+1 -1
View File
@@ -14,7 +14,7 @@ namespace Subsurface.Items.Components
{ {
if (picker == null) return false; if (picker == null) return false;
picker.animController.anim = AnimController.Animation.Climbing; picker.AnimController.Anim = AnimController.Animation.Climbing;
//picker.SelectedConstruction = item; //picker.SelectedConstruction = item;
return true; return true;
@@ -80,7 +80,7 @@ namespace Subsurface.Items.Components
if (character != null) if (character != null)
{ {
character.SelectedConstruction = null; character.SelectedConstruction = null;
character.animController.anim = AnimController.Animation.None; character.AnimController.Anim = AnimController.Animation.None;
character = null; character = null;
} }
isActive = false; isActive = false;
@@ -89,33 +89,33 @@ namespace Subsurface.Items.Components
ApplyStatusEffects(ActionType.OnActive, deltaTime, character); ApplyStatusEffects(ActionType.OnActive, deltaTime, character);
if (userPos != 0.0f && character.animController.anim != AnimController.Animation.UsingConstruction) if (userPos != 0.0f && character.AnimController.Anim != AnimController.Animation.UsingConstruction)
{ {
Limb torso = character.animController.GetLimb(LimbType.Torso); Limb torso = character.AnimController.GetLimb(LimbType.Torso);
float torsoX = ConvertUnits.ToDisplayUnits(torso.SimPosition.X); float torsoX = ConvertUnits.ToDisplayUnits(torso.SimPosition.X);
if (Math.Abs(torsoX - item.Rect.X + userPos) > 10.0f) if (Math.Abs(torsoX - item.Rect.X + userPos) > 10.0f)
{ {
character.animController.anim = AnimController.Animation.None; character.AnimController.Anim = AnimController.Animation.None;
character.animController.TargetMovement = character.AnimController.TargetMovement =
new Vector2( new Vector2(
Math.Min(Math.Max(item.Rect.X + userPos - torsoX, -1.0f), 1.0f), Math.Min(Math.Max(item.Rect.X + userPos - torsoX, -1.0f), 1.0f),
0.0f); 0.0f);
character.animController.targetDir = (Math.Sign(torsoX - item.Rect.X + userPos) == 1) ? Direction.Right : Direction.Left; character.AnimController.TargetDir = (Math.Sign(torsoX - item.Rect.X + userPos) == 1) ? Direction.Right : Direction.Left;
return; return;
} }
} }
if (limbPositions.Count == 0) return; if (limbPositions.Count == 0) return;
character.animController.anim = AnimController.Animation.UsingConstruction; character.AnimController.Anim = AnimController.Animation.UsingConstruction;
character.animController.ResetPullJoints(); character.AnimController.ResetPullJoints();
if (dir != 0) character.animController.targetDir = dir; if (dir != 0) character.AnimController.TargetDir = dir;
foreach (LimbPos lb in limbPositions) foreach (LimbPos lb in limbPositions)
{ {
Limb limb = character.animController.GetLimb(lb.limbType); Limb limb = character.AnimController.GetLimb(lb.limbType);
if (limb == null) continue; if (limb == null) continue;
FixedMouseJoint fmj = limb.pullJoint; FixedMouseJoint fmj = limb.pullJoint;
@@ -167,7 +167,7 @@ namespace Subsurface.Items.Components
{ {
character = null; character = null;
isActive = false; isActive = false;
if (activator != null) activator.animController.anim = AnimController.Animation.None; if (activator != null) activator.AnimController.Anim = AnimController.Animation.None;
return false; return false;
} }
+14 -5
View File
@@ -30,7 +30,7 @@ namespace Subsurface.Items.Components
} }
} }
[Editable, HasDefaultValue(50000.0f, true)] [Editable, HasDefaultValue(500.0f, true)]
public float MaxForce public float MaxForce
{ {
get { return maxForce; } get { return maxForce; }
@@ -62,7 +62,15 @@ namespace Subsurface.Items.Components
Force = MathHelper.Lerp(force, (voltage < minVoltage) ? 0.0f : targetForce, 0.1f); Force = MathHelper.Lerp(force, (voltage < minVoltage) ? 0.0f : targetForce, 0.1f);
if (Force != 0.0f) if (Force != 0.0f)
{ {
Submarine.Loaded.ApplyForce(new Vector2((force / 100.0f) * maxForce * (voltage / minVoltage), 0.0f)); Vector2 currForce = new Vector2((force / 100.0f) * maxForce * (voltage / minVoltage), 0.0f);
Submarine.Loaded.ApplyForce(currForce);
for (int i = 0; i < 5; i++)
{
Game1.particleManager.CreateParticle("bubbles", item.SimPosition,
-currForce/500.0f + new Vector2(Rand.Range(-1.0f, 1.0f), Rand.Range(-0.5f, 0.5f)));
}
} }
voltage = 0.0f; voltage = 0.0f;
@@ -79,7 +87,7 @@ namespace Subsurface.Items.Components
//GUI.DrawRectangle(spriteBatch, new Rectangle(x, y, width, height), Color.Black, true); //GUI.DrawRectangle(spriteBatch, new Rectangle(x, y, width, height), Color.Black, true);
spriteBatch.DrawString(GUI.font, "Force: " + (int)targetForce + " %", new Vector2(GuiFrame.Rect.X + 30, GuiFrame.Rect.Y + 30), Color.White); spriteBatch.DrawString(GUI.font, "Force: " + (int)(targetForce) + " %", new Vector2(GuiFrame.Rect.X + 30, GuiFrame.Rect.Y + 30), Color.White);
if (GUI.DrawButton(spriteBatch, new Rectangle(GuiFrame.Rect.X + 280, GuiFrame.Rect.Y + 30, 40, 40), "+", true)) targetForce += 1.0f; if (GUI.DrawButton(spriteBatch, new Rectangle(GuiFrame.Rect.X + 280, GuiFrame.Rect.Y + 30, 40, 40), "+", true)) targetForce += 1.0f;
if (GUI.DrawButton(spriteBatch, new Rectangle(GuiFrame.Rect.X + 280, GuiFrame.Rect.Y + 80, 40, 40), "-", true)) targetForce -= 1.0f; if (GUI.DrawButton(spriteBatch, new Rectangle(GuiFrame.Rect.X + 280, GuiFrame.Rect.Y + 80, 40, 40), "-", true)) targetForce -= 1.0f;
@@ -96,12 +104,13 @@ namespace Subsurface.Items.Components
{ {
base.ReceiveSignal(signal, connection, sender, power); base.ReceiveSignal(signal, connection, sender, power);
if (connection.name == "set_force") if (connection.Name == "set_force")
{ {
float tempForce; float tempForce;
if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out tempForce)) if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out tempForce))
{ {
Force = tempForce; targetForce = tempForce;
targetForce = MathHelper.Clamp(targetForce, -100.0f, 100.0f);
} }
} }
} }
@@ -90,12 +90,9 @@ namespace Subsurface.Items.Components
//frame.SelectedColor = Color.Gold * 0.5f; //frame.SelectedColor = Color.Gold * 0.5f;
GUITextBlock textBlock = new GUITextBlock( GUITextBlock textBlock = new GUITextBlock(
new Rectangle(0, 0, 0, 25), new Rectangle(0, 0, 0, 25), fi.TargetItem.Name,
fi.TargetItem.Name,
color, Color.Black, color, Color.Black,
Alignment.Left, Alignment.Left, Alignment.Left, null, itemList);
Alignment.Left,
itemList);
textBlock.UserData = fi; textBlock.UserData = fi;
textBlock.Padding = new Vector4(5.0f, 5.0f, 5.0f, 5.0f); textBlock.Padding = new Vector4(5.0f, 5.0f, 5.0f, 5.0f);
@@ -114,7 +111,7 @@ namespace Subsurface.Items.Components
int width = 200, height = 150; int width = 200, height = 150;
selectedItemFrame = new GUIFrame(new Rectangle(Game1.GraphicsWidth / 2 - width / 2, itemList.Rect.Bottom+20, width, height), Color.Black*0.8f); selectedItemFrame = new GUIFrame(new Rectangle(Game1.GraphicsWidth / 2 - width / 2, itemList.Rect.Bottom+20, width, height), Color.Black*0.8f);
selectedItemFrame.Padding = GUI.style.smallPadding; //selectedItemFrame.Padding = GUI.style.smallPadding;
if (targetItem.TargetItem.sprite != null) if (targetItem.TargetItem.sprite != null)
{ {
@@ -134,10 +131,10 @@ namespace Subsurface.Items.Components
text, text,
Color.Transparent, Color.White, Color.Transparent, Color.White,
Alignment.CenterX | Alignment.CenterY, Alignment.CenterX | Alignment.CenterY,
Alignment.Left, Alignment.Left, null,
selectedItemFrame); selectedItemFrame);
GUIButton button = new GUIButton(new Rectangle(0,0,100,20), "Create", Color.White, Alignment.CenterX | Alignment.Bottom, selectedItemFrame); GUIButton button = new GUIButton(new Rectangle(0,0,100,20), "Create", Color.White, Alignment.CenterX | Alignment.Bottom, GUI.style, selectedItemFrame);
button.OnClicked = StartFabricating; button.OnClicked = StartFabricating;
button.UserData = targetItem; button.UserData = targetItem;
@@ -67,9 +67,9 @@ namespace Subsurface.Items.Components
GUI.DrawRectangle(spriteBatch, hullRect, Color.White); GUI.DrawRectangle(spriteBatch, hullRect, Color.White);
} }
foreach (Character c in Character.characterList) foreach (Character c in Character.CharacterList)
{ {
if (c.animController.CurrentHull!=null) continue; if (c.AnimController.CurrentHull!=null) continue;
Rectangle characterRect = new Rectangle( Rectangle characterRect = new Rectangle(
miniMap.X + (int)((c.Position.X - Submarine.Borders.X) * size), miniMap.X + (int)((c.Position.X - Submarine.Borders.X) * size),
@@ -36,7 +36,7 @@ namespace Subsurface.Items.Components
currPowerConsumption = powerConsumption; currPowerConsumption = powerConsumption;
if (item.currentHull == null) return; if (item.CurrentHull == null) return;
if (voltage < minVoltage) if (voltage < minVoltage)
{ {
@@ -56,7 +56,7 @@ namespace Subsurface.Items.Components
running = true; running = true;
float deltaOxygen = Math.Min(voltage, 1.0f) * 50000.0f; float deltaOxygen = Math.Min(voltage, 1.0f) * 50000.0f;
item.currentHull.Oxygen += deltaOxygen * deltaTime; item.CurrentHull.Oxygen += deltaOxygen * deltaTime;
UpdateVents(deltaOxygen); UpdateVents(deltaOxygen);
+25 -4
View File
@@ -10,6 +10,8 @@ namespace Subsurface.Items.Components
float flowPercentage; float flowPercentage;
float maxFlow; float maxFlow;
float? targetLevel;
//bool flowIn; //bool flowIn;
Hull hull1, hull2; Hull hull1, hull2;
@@ -41,7 +43,18 @@ namespace Subsurface.Items.Components
float powerFactor = (currPowerConsumption==0.0f) ? 1.0f : voltage; float powerFactor = (currPowerConsumption==0.0f) ? 1.0f : voltage;
//flowPercentage = maxFlow * powerFactor; //flowPercentage = maxFlow * powerFactor;
float deltaVolume = (flowPercentage/100.0f) * maxFlow * powerFactor; float deltaVolume = 0.0f;
if (targetLevel!=null)
{
float hullPercentage = 0.0f;
if (hull1 != null) hullPercentage = (hull1.Volume / hull1.FullVolume)*100.0f;
deltaVolume = ((float)targetLevel - hullPercentage)/100.0f * maxFlow * powerFactor;
}
else
{
deltaVolume = (flowPercentage/100.0f) * maxFlow * powerFactor;
}
hull1.Volume += deltaVolume; hull1.Volume += deltaVolume;
if (hull2 != null) hull2.Volume -= deltaVolume; if (hull2 != null) hull2.Volume -= deltaVolume;
@@ -139,15 +152,15 @@ namespace Subsurface.Items.Components
isActive = true; isActive = true;
if (connection.name == "toggle") if (connection.Name == "toggle")
{ {
isActive = !isActive; isActive = !isActive;
} }
else if (connection.name == "set_active") else if (connection.Name == "set_active")
{ {
isActive = (signal != "0"); isActive = (signal != "0");
} }
else if (connection.name == "set_speed") else if (connection.Name == "set_speed")
{ {
float tempSpeed; float tempSpeed;
if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out tempSpeed)) if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out tempSpeed))
@@ -155,6 +168,14 @@ namespace Subsurface.Items.Components
flowPercentage = MathHelper.Clamp(tempSpeed, -100.0f, 100.0f); flowPercentage = MathHelper.Clamp(tempSpeed, -100.0f, 100.0f);
} }
} }
else if (connection.Name == "set_targetlevel")
{
float tempTarget;
if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out tempTarget))
{
targetLevel = MathHelper.Clamp(tempTarget, 0.0f, 100.0f);
}
}
} }
@@ -55,7 +55,7 @@ namespace Subsurface.Items.Components
float scale = 0.01f; float scale = 0.01f;
List<Vector2[]> edges = Level.Loaded.GetCellEdges(-Level.Loaded.position, 5); List<Vector2[]> edges = Level.Loaded.GetCellEdges(-Level.Loaded.Position, 5);
Vector2 offset = Vector2.Zero; //Level.Loaded.position; Vector2 offset = Vector2.Zero; //Level.Loaded.position;
//offset.Y = -offset.Y; //offset.Y = -offset.Y;
@@ -181,10 +181,10 @@ namespace Subsurface.Items.Components
//the power generated by the reactor is equal to the temperature //the power generated by the reactor is equal to the temperature
currPowerConsumption = -temperature*powerPerTemp; currPowerConsumption = -temperature*powerPerTemp;
if (item.currentHull != null) if (item.CurrentHull != null)
{ {
//the sound can be heard from 20 000 display units away when everything running at 100% //the sound can be heard from 20 000 display units away when everything running at 100%
item.currentHull.SoundRange += (coolingRate + fissionRate) * 100; item.CurrentHull.SoundRange += (coolingRate + fissionRate) * 100;
} }
UpdateGraph(deltaTime); UpdateGraph(deltaTime);
@@ -68,7 +68,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
if (connection.name == "velocity_in") if (connection.Name == "velocity_in")
{ {
currVelocity = ToolBox.ParseToVector2(signal, false); currVelocity = ToolBox.ParseToVector2(signal, false);
} }
+2 -2
View File
@@ -23,9 +23,9 @@ namespace Subsurface.Items.Components
{ {
base.Update(deltaTime, cam); base.Update(deltaTime, cam);
if (item.currentHull == null) return; if (item.CurrentHull == null) return;
item.currentHull.Oxygen += oxygenFlow * deltaTime; item.CurrentHull.Oxygen += oxygenFlow * deltaTime;
OxygenFlow -= deltaTime * 1000.0f; OxygenFlow -= deltaTime * 1000.0f;
} }
} }
@@ -141,7 +141,7 @@ namespace Subsurface.Items.Components
{ {
base.ReceiveSignal(signal, connection, sender, power); base.ReceiveSignal(signal, connection, sender, power);
if (connection.name=="signal") if (connection.Name=="signal")
{ {
connection.SendSignal(signal, item, 0.0f); connection.SendSignal(signal, item, 0.0f);
} }
+1 -1
View File
@@ -61,7 +61,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power)
{ {
if (connection.name=="power_in") voltage = power; if (connection.Name=="power_in") voltage = power;
} }
public override void Update(float deltaTime, Camera cam) public override void Update(float deltaTime, Camera cam)
+4 -4
View File
@@ -106,7 +106,7 @@ namespace Subsurface.Items.Components
if (stickJoint != null && doesStick) if (stickJoint != null && doesStick)
{ {
if (stickTarget!=null) item.body.FarseerBody.RestoreCollisionWith(stickTarget); if (stickTarget!=null) item.body.FarseerBody.RestoreCollisionWith(stickTarget);
Game1.world.RemoveJoint(stickJoint); Game1.World.RemoveJoint(stickJoint);
stickJoint = null; stickJoint = null;
} }
} }
@@ -122,7 +122,7 @@ namespace Subsurface.Items.Components
item.body.FarseerBody.RestoreCollisionWith(stickTarget); item.body.FarseerBody.RestoreCollisionWith(stickTarget);
} }
Game1.world.RemoveJoint(stickJoint); Game1.World.RemoveJoint(stickJoint);
stickJoint = null; stickJoint = null;
isActive = false; isActive = false;
@@ -181,7 +181,7 @@ namespace Subsurface.Items.Components
ignoredBodies.Clear(); ignoredBodies.Clear();
if (attackResult.hitArmor) if (attackResult.HitArmor)
{ {
item.body.LinearVelocity *= 0.5f; item.body.LinearVelocity *= 0.5f;
} }
@@ -211,7 +211,7 @@ namespace Subsurface.Items.Components
item.body.FarseerBody.IgnoreCollisionWith(targetBody); item.body.FarseerBody.IgnoreCollisionWith(targetBody);
stickTarget = targetBody; stickTarget = targetBody;
Game1.world.AddJoint(stickJoint); Game1.World.AddJoint(stickJoint);
isActive = true; isActive = true;
+7 -7
View File
@@ -90,7 +90,7 @@ namespace Subsurface.Items.Components
Vertices box = PolygonTools.CreateRectangle(sectionLength, 0.05f); Vertices box = PolygonTools.CreateRectangle(sectionLength, 0.05f);
PolygonShape shape = new PolygonShape(box, 5); PolygonShape shape = new PolygonShape(box, 5);
List<Body>ropeList = PathManager.EvenlyDistributeShapesAlongPath(Game1.world, ropePath, shape, BodyType.Dynamic, (int)(length/sectionLength)); List<Body>ropeList = PathManager.EvenlyDistributeShapesAlongPath(Game1.World, ropePath, shape, BodyType.Dynamic, (int)(length/sectionLength));
ropeBodies = new PhysicsBody[ropeList.Count()]; ropeBodies = new PhysicsBody[ropeList.Count()];
for (int i = 0; i<ropeBodies.Length; i++) for (int i = 0; i<ropeBodies.Length; i++)
@@ -104,14 +104,14 @@ namespace Subsurface.Items.Components
ropeBodies[i] = new PhysicsBody(ropeList[i]); ropeBodies[i] = new PhysicsBody(ropeList[i]);
} }
List<RevoluteJoint> joints = PathManager.AttachBodiesWithRevoluteJoint(Game1.world, ropeList, List<RevoluteJoint> joints = PathManager.AttachBodiesWithRevoluteJoint(Game1.World, ropeList,
new Vector2(-sectionLength/2, 0.0f), new Vector2(sectionLength/2, 0.0f), false, false); new Vector2(-sectionLength/2, 0.0f), new Vector2(sectionLength/2, 0.0f), false, false);
ropeJoints = new RevoluteJoint[joints.Count+1]; ropeJoints = new RevoluteJoint[joints.Count+1];
//ropeJoints[0] = JointFactory.CreateRevoluteJoint(Game1.world, item.body, ropeList[0], new Vector2(0f, -0.0f)); //ropeJoints[0] = JointFactory.CreateRevoluteJoint(Game1.world, item.body, ropeList[0], new Vector2(0f, -0.0f));
for (int i = 0; i < joints.Count; i++) for (int i = 0; i < joints.Count; i++)
{ {
var distanceJoint = JointFactory.CreateDistanceJoint(Game1.world, ropeList[i], ropeList[i + 1]); var distanceJoint = JointFactory.CreateDistanceJoint(Game1.World, ropeList[i], ropeList[i + 1]);
distanceJoint.Length = sectionLength; distanceJoint.Length = sectionLength;
distanceJoint.DampingRatio = 1.0f; distanceJoint.DampingRatio = 1.0f;
@@ -299,8 +299,8 @@ namespace Subsurface.Items.Components
ropeBodies[ropeBodies.Length - 1].SetTransform(projectile.body.Position, projectile.body.Rotation); ropeBodies[ropeBodies.Length - 1].SetTransform(projectile.body.Position, projectile.body.Rotation);
//attach projectile to the last section of the rope //attach projectile to the last section of the rope
if (ropeJoints[ropeJoints.Length-1] != null) Game1.world.RemoveJoint(ropeJoints[ropeJoints.Length-1]); if (ropeJoints[ropeJoints.Length-1] != null) Game1.World.RemoveJoint(ropeJoints[ropeJoints.Length-1]);
ropeJoints[ropeJoints.Length - 1] = JointFactory.CreateRevoluteJoint(Game1.world, ropeJoints[ropeJoints.Length - 1] = JointFactory.CreateRevoluteJoint(Game1.World,
projectile.body.FarseerBody, ropeBodies[ropeBodies.Length - 1].FarseerBody, projectile.body.FarseerBody, ropeBodies[ropeBodies.Length - 1].FarseerBody,
projectileAnchor, new Vector2(sectionLength / 2, 0.0f)); projectileAnchor, new Vector2(sectionLength / 2, 0.0f));
@@ -315,7 +315,7 @@ namespace Subsurface.Items.Components
body.SetTransform(TransformedBarrelPos, rotation); body.SetTransform(TransformedBarrelPos, rotation);
//Vector2 axis = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)); //Vector2 axis = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation));
if (gunJoint != null) Game1.world.RemoveJoint(gunJoint); if (gunJoint != null) Game1.World.RemoveJoint(gunJoint);
gunJoint = new DistanceJoint(item.body.FarseerBody, body, BarrelPos, gunJoint = new DistanceJoint(item.body.FarseerBody, body, BarrelPos,
new Vector2(sectionLength / 2, 0.0f)); new Vector2(sectionLength / 2, 0.0f));
@@ -328,7 +328,7 @@ namespace Subsurface.Items.Components
//gunJoint.LimitEnabled = true; //gunJoint.LimitEnabled = true;
//gunJoint.ReferenceAngle = 0.0f; //gunJoint.ReferenceAngle = 0.0f;
Game1.world.AddJoint(gunJoint); Game1.World.AddJoint(gunJoint);
} }
} }
@@ -55,7 +55,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
switch (connection.name) switch (connection.Name)
{ {
case "signal_in1": case "signal_in1":
if (signal == "0") return; if (signal == "0") return;
@@ -16,13 +16,13 @@ namespace Subsurface.Items.Components
//how many wires can be linked to a single connector //how many wires can be linked to a single connector
private const int MaxLinked = 5; private const int MaxLinked = 5;
public readonly string name; public readonly string Name;
public Wire[] wires; public Wire[] Wires;
private Item item; private Item item;
public readonly bool isOutput; public readonly bool IsOutput;
private static Item draggingConnected; private static Item draggingConnected;
@@ -35,8 +35,8 @@ namespace Subsurface.Items.Components
List<Connection> recipients = new List<Connection>(); List<Connection> recipients = new List<Connection>();
for (int i = 0; i<MaxLinked; i++) for (int i = 0; i<MaxLinked; i++)
{ {
if (wires[i] == null) continue; if (Wires[i] == null) continue;
Connection recipient = wires[i].OtherConnection(this); Connection recipient = Wires[i].OtherConnection(this);
if (recipient != null) recipients.Add(recipient); if (recipient != null) recipients.Add(recipient);
} }
return recipients; return recipients;
@@ -62,10 +62,10 @@ namespace Subsurface.Items.Components
this.item = item; this.item = item;
//recipient = new Connection[MaxLinked]; //recipient = new Connection[MaxLinked];
wires = new Wire[MaxLinked]; Wires = new Wire[MaxLinked];
isOutput = (element.Name.ToString() == "output"); IsOutput = (element.Name.ToString() == "output");
name = ToolBox.GetAttributeString(element, "name", (isOutput) ? "output" : "input"); Name = ToolBox.GetAttributeString(element, "name", (IsOutput) ? "output" : "input");
wireId = new int[MaxLinked]; wireId = new int[MaxLinked];
@@ -88,7 +88,7 @@ namespace Subsurface.Items.Components
{ {
for (int i = 0; i < MaxLinked; i++) for (int i = 0; i < MaxLinked; i++)
{ {
if (wires[i]==null) return i; if (Wires[i]==null) return i;
} }
return -1; return -1;
} }
@@ -107,8 +107,8 @@ namespace Subsurface.Items.Components
{ {
for (int i = 0; i < MaxLinked; i++) for (int i = 0; i < MaxLinked; i++)
{ {
if (wires[i] == null && wireItem == null) return i; if (Wires[i] == null && wireItem == null) return i;
if (wires[i] != null && wires[i].Item == wireItem) return i; if (Wires[i] != null && Wires[i].Item == wireItem) return i;
} }
return -1; return -1;
} }
@@ -117,7 +117,7 @@ namespace Subsurface.Items.Components
{ {
//linked[index] = connectedItem; //linked[index] = connectedItem;
//recipient[index] = otherConnection; //recipient[index] = otherConnection;
wires[index] = wire; Wires[index] = wire;
} }
//public bool AddLink(Item connectedItem, Connection otherConnection) //public bool AddLink(Item connectedItem, Connection otherConnection)
@@ -139,9 +139,9 @@ namespace Subsurface.Items.Components
{ {
for (int i = 0; i<MaxLinked; i++) for (int i = 0; i<MaxLinked; i++)
{ {
if (wires[i]==null) continue; if (Wires[i]==null) continue;
Connection recipient = wires[i].OtherConnection(this); Connection recipient = Wires[i].OtherConnection(this);
if (recipient == null) continue; if (recipient == null) continue;
foreach (ItemComponent ic in recipient.item.components) foreach (ItemComponent ic in recipient.item.components)
@@ -155,10 +155,10 @@ namespace Subsurface.Items.Components
{ {
for (int i = 0; i<MaxLinked; i++) for (int i = 0; i<MaxLinked; i++)
{ {
if (wires[i] == null) continue; if (Wires[i] == null) continue;
wires[i].RemoveConnection(this); Wires[i].RemoveConnection(this);
wires[i] = null; Wires[i] = null;
} }
} }
@@ -204,12 +204,12 @@ namespace Subsurface.Items.Components
int linkIndex = c.FindWireIndex(draggingConnected); int linkIndex = c.FindWireIndex(draggingConnected);
if (linkIndex>-1) if (linkIndex>-1)
{ {
Inventory.draggingItem = c.wires[linkIndex].Item; Inventory.draggingItem = c.Wires[linkIndex].Item;
} }
} }
//outputs are drawn at the right side of the panel, inputs at the left //outputs are drawn at the right side of the panel, inputs at the left
if (c.isOutput) if (c.IsOutput)
{ {
c.Draw(spriteBatch, panel.Item, rightPos, c.Draw(spriteBatch, panel.Item, rightPos,
new Vector2(rightPos.X + 20, rightPos.Y), new Vector2(rightPos.X + 20, rightPos.Y),
@@ -235,7 +235,7 @@ namespace Subsurface.Items.Components
//and the wire hasn't been connected yet, draw it on the panel //and the wire hasn't been connected yet, draw it on the panel
if (equippedWire!=null) if (equippedWire!=null)
{ {
if (panel.connections.Find(c => c.wires.Contains(equippedWire)) == null) if (panel.connections.Find(c => c.Wires.Contains(equippedWire)) == null)
{ {
DrawWire(spriteBatch, equippedWire.Item, equippedWire.Item, DrawWire(spriteBatch, equippedWire.Item, equippedWire.Item,
new Vector2(x + width / 2, y + height - 100), new Vector2(x + width / 2, y + height - 100),
@@ -274,19 +274,19 @@ namespace Subsurface.Items.Components
private void Draw(SpriteBatch spriteBatch, Item item, Vector2 position, Vector2 labelPos, Vector2 wirePosition, bool mouseIn, bool wireEquipped) private void Draw(SpriteBatch spriteBatch, Item item, Vector2 position, Vector2 labelPos, Vector2 wirePosition, bool mouseIn, bool wireEquipped)
{ {
spriteBatch.DrawString(GUI.font, name, new Vector2(labelPos.X, labelPos.Y-10), Color.White); spriteBatch.DrawString(GUI.font, Name, new Vector2(labelPos.X, labelPos.Y-10), Color.White);
GUI.DrawRectangle(spriteBatch, new Rectangle((int)position.X-10, (int)position.Y-10, 20, 20), Color.White); GUI.DrawRectangle(spriteBatch, new Rectangle((int)position.X-10, (int)position.Y-10, 20, 20), Color.White);
for (int i = 0; i<MaxLinked; i++) for (int i = 0; i<MaxLinked; i++)
{ {
if (wires[i]==null) continue; if (Wires[i]==null) continue;
Connection recipient = wires[i].OtherConnection(this); Connection recipient = Wires[i].OtherConnection(this);
DrawWire(spriteBatch, wires[i].Item, (recipient == null) ? wires[i].Item : recipient.item, position, wirePosition, mouseIn, wireEquipped); DrawWire(spriteBatch, Wires[i].Item, (recipient == null) ? Wires[i].Item : recipient.item, position, wirePosition, mouseIn, wireEquipped);
wirePosition.X += (isOutput) ? -20 : 20; wirePosition.X += (IsOutput) ? -20 : 20;
} }
//dragging a wire and released the mouse -> see if the wire can be connected to this connection //dragging a wire and released the mouse -> see if the wire can be connected to this connection
@@ -301,9 +301,9 @@ namespace Subsurface.Items.Components
Wire wireComponent = draggingConnected.GetComponent<Wire>(); Wire wireComponent = draggingConnected.GetComponent<Wire>();
if (index>-1 && wireComponent!=null && !wires.Contains(wireComponent)) if (index>-1 && wireComponent!=null && !Wires.Contains(wireComponent))
{ {
wires[index] = wireComponent; Wires[index] = wireComponent;
wireComponent.Connect(this); wireComponent.Connect(this);
} }
} }
@@ -313,11 +313,11 @@ namespace Subsurface.Items.Components
int index = FindWireIndex(draggingConnected); int index = FindWireIndex(draggingConnected);
if (index>-1) if (index>-1)
{ {
wires[index].RemoveConnection(this); Wires[index].RemoveConnection(this);
wires[index].Item.SetTransform(item.SimPosition, 0.0f); Wires[index].Item.SetTransform(item.SimPosition, 0.0f);
wires[index].Item.Drop(); Wires[index].Item.Drop();
wires[index].Item.body.Enabled = true; Wires[index].Item.body.Enabled = true;
wires[index] = null; Wires[index] = null;
} }
} }
} }
@@ -396,9 +396,9 @@ namespace Subsurface.Items.Components
public void Save(XElement parentElement) public void Save(XElement parentElement)
{ {
XElement newElement = new XElement(isOutput ? "output" : "input", new XAttribute("name", name)); XElement newElement = new XElement(IsOutput ? "output" : "input", new XAttribute("name", Name));
Array.Sort(wires, delegate(Wire wire1, Wire wire2) Array.Sort(Wires, delegate(Wire wire1, Wire wire2)
{ {
if (wire1 == null) return 1; if (wire1 == null) return 1;
if (wire2 == null) return -1; if (wire2 == null) return -1;
@@ -407,13 +407,13 @@ namespace Subsurface.Items.Components
for (int i = 0; i < MaxLinked; i++ ) for (int i = 0; i < MaxLinked; i++ )
{ {
if (wires[i] == null) continue; if (Wires[i] == null) continue;
//Connection recipient = wires[i].OtherConnection(this); //Connection recipient = wires[i].OtherConnection(this);
//int connectionIndex = recipient.item.Connections.FindIndex(x => x == recipient); //int connectionIndex = recipient.item.Connections.FindIndex(x => x == recipient);
newElement.Add(new XElement("link", newElement.Add(new XElement("link",
new XAttribute("w", wires[i].Item.ID.ToString()))); new XAttribute("w", Wires[i].Item.ID.ToString())));
} }
parentElement.Add(newElement); parentElement.Add(newElement);
@@ -432,12 +432,12 @@ namespace Subsurface.Items.Components
Item wireItem = MapEntity.FindEntityByID(wireId[i]) as Item; Item wireItem = MapEntity.FindEntityByID(wireId[i]) as Item;
if (wireItem == null) continue; if (wireItem == null) continue;
wires[i] = wireItem.GetComponent<Wire>(); Wires[i] = wireItem.GetComponent<Wire>();
if (wires[i]!=null) if (Wires[i]!=null)
{ {
wires[i].Item.body.Enabled = false; Wires[i].Item.body.Enabled = false;
wires[i].Connect(this, false); Wires[i].Connect(this, false);
} }
} }
@@ -107,10 +107,10 @@ namespace Subsurface.Items.Components
{ {
foreach (Connection c in connections) foreach (Connection c in connections)
{ {
int wireCount = c.wires.Length; int wireCount = c.Wires.Length;
for (int i = 0 ; i < wireCount; i++) for (int i = 0 ; i < wireCount; i++)
{ {
message.Write(c.wires[i]==null ? -1 : c.wires[i].Item.ID); message.Write(c.Wires[i]==null ? -1 : c.Wires[i].Item.ID);
} }
} }
} }
@@ -120,7 +120,7 @@ namespace Subsurface.Items.Components
System.Diagnostics.Debug.WriteLine("connectionpanel update"); System.Diagnostics.Debug.WriteLine("connectionpanel update");
foreach (Connection c in connections) foreach (Connection c in connections)
{ {
int wireCount = c.wires.Length; int wireCount = c.Wires.Length;
c.ClearConnections(); c.ClearConnections();
for (int i = 0; i < wireCount; i++) for (int i = 0; i < wireCount; i++)
@@ -134,7 +134,7 @@ namespace Subsurface.Items.Components
Wire wireComponent = wireItem.GetComponent<Wire>(); Wire wireComponent = wireItem.GetComponent<Wire>();
if (wireComponent == null) continue; if (wireComponent == null) continue;
c.wires[i] = wireComponent; c.Wires[i] = wireComponent;
wireComponent.Connect(c, false); wireComponent.Connect(c, false);
} }
} }
@@ -40,7 +40,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
switch (connection.name) switch (connection.Name)
{ {
case "toggle": case "toggle":
isActive = !isActive; isActive = !isActive;
@@ -11,7 +11,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
if (connection.name != "signal_in") return; if (connection.Name != "signal_in") return;
item.SendSignal(signal=="0" ? "1" : "0", "signal_out"); item.SendSignal(signal=="0" ? "1" : "0", "signal_out");
} }
@@ -30,7 +30,7 @@ namespace Subsurface.Items.Components
public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f) public override void ReceiveSignal(string signal, Connection connection, Item sender, float power=0.0f)
{ {
switch (connection.name) switch (connection.Name)
{ {
case "signal_in": case "signal_in":
if (string.IsNullOrWhiteSpace(expression)) return; if (string.IsNullOrWhiteSpace(expression)) return;
+3 -3
View File
@@ -123,15 +123,15 @@ namespace Subsurface.Items.Components
Vector2 position = item.Position; Vector2 position = item.Position;
position.X = MathUtils.Round(item.Position.X, nodeDistance); position.X = MathUtils.Round(item.Position.X, nodeDistance);
if (item.currentHull == null) if (item.CurrentHull == null)
{ {
position.Y = MathUtils.Round(item.Position.Y, nodeDistance); position.Y = MathUtils.Round(item.Position.Y, nodeDistance);
} }
else else
{ {
position.Y -= item.currentHull.Rect.Y - item.currentHull.Rect.Height; position.Y -= item.CurrentHull.Rect.Y - item.CurrentHull.Rect.Height;
position.Y = Math.Max(MathUtils.Round(position.Y, nodeDistance), heightFromFloor); position.Y = Math.Max(MathUtils.Round(position.Y, nodeDistance), heightFromFloor);
position.Y += item.currentHull.Rect.Y - item.currentHull.Rect.Height; position.Y += item.CurrentHull.Rect.Y - item.CurrentHull.Rect.Height;
} }
newNodePos = position; newNodePos = position;
+1 -1
View File
@@ -137,7 +137,7 @@ namespace Subsurface.Items.Components
if (character == Character.Controlled && cam!=null) if (character == Character.Controlled && cam!=null)
{ {
Lights.LightManager.viewPos = centerPos; Lights.LightManager.ViewPos = centerPos;
cam.TargetPos = new Vector2(item.Rect.X + barrelPos.X, item.Rect.Y - barrelPos.Y); cam.TargetPos = new Vector2(item.Rect.X + barrelPos.X, item.Rect.Y - barrelPos.Y);
} }
} }
+2 -2
View File
@@ -55,7 +55,7 @@ namespace Subsurface.Items.Components
picker = character; picker = character;
for (int i = 0; i < sprite.Length; i++ ) for (int i = 0; i < sprite.Length; i++ )
{ {
Limb equipLimb = character.animController.GetLimb(limbType[i]); Limb equipLimb = character.AnimController.GetLimb(limbType[i]);
if (equipLimb == null) continue; if (equipLimb == null) continue;
//something is already on the limb -> unequip it //something is already on the limb -> unequip it
@@ -91,7 +91,7 @@ namespace Subsurface.Items.Components
if (picker == null) return; if (picker == null) return;
for (int i = 0; i < sprite.Length; i++) for (int i = 0; i < sprite.Length; i++)
{ {
Limb equipLimb = character.animController.GetLimb(limbType[i]); Limb equipLimb = character.AnimController.GetLimb(limbType[i]);
if (equipLimb == null) continue; if (equipLimb == null) continue;
if (equipLimb.WearingItem != item) continue; if (equipLimb.WearingItem != item) continue;
+17 -17
View File
@@ -27,7 +27,7 @@ namespace Subsurface
private List<string> tags; private List<string> tags;
public Hull currentHull; public Hull CurrentHull;
//components that determine the functionality of the item //components that determine the functionality of the item
public List<ItemComponent> components; public List<ItemComponent> components;
@@ -318,8 +318,8 @@ namespace Subsurface
public virtual Hull FindHull() public virtual Hull FindHull()
{ {
currentHull = Hull.FindHull((body == null) ? Position : ConvertUnits.ToDisplayUnits(body.Position), currentHull); CurrentHull = Hull.FindHull((body == null) ? Position : ConvertUnits.ToDisplayUnits(body.Position), CurrentHull);
return currentHull; return CurrentHull;
} }
@@ -441,9 +441,9 @@ namespace Subsurface
body.SetToTargetPosition(); body.SetToTargetPosition();
if (currentHull != null) if (CurrentHull != null)
{ {
float surfaceY = ConvertUnits.ToSimUnits(currentHull.Surface); float surfaceY = ConvertUnits.ToSimUnits(CurrentHull.Surface);
if (surfaceY > body.Position.Y) return; if (surfaceY > body.Position.Y) return;
//the item has gone through the surface of the water -> apply an impulse which serves as surface tension //the item has gone through the surface of the water -> apply an impulse which serves as surface tension
@@ -451,8 +451,8 @@ namespace Subsurface
{ {
Vector2 impulse = -body.LinearVelocity * (body.Mass / body.Density); Vector2 impulse = -body.LinearVelocity * (body.Mass / body.Density);
body.ApplyLinearImpulse(impulse); body.ApplyLinearImpulse(impulse);
int n = (int)((displayPos.X - currentHull.Rect.X) / Hull.WaveWidth); int n = (int)((displayPos.X - CurrentHull.Rect.X) / Hull.WaveWidth);
currentHull.WaveVel[n] = impulse.Y * 10.0f; CurrentHull.WaveVel[n] = impulse.Y * 10.0f;
} }
} }
@@ -509,7 +509,7 @@ namespace Subsurface
GUI.DrawRectangle(spriteBatch, new Vector2(rect.X, -rect.Y), new Vector2(rect.Width, rect.Height), Color.Green); GUI.DrawRectangle(spriteBatch, new Vector2(rect.X, -rect.Y), new Vector2(rect.Width, rect.Height), Color.Green);
foreach (Rectangle t in prefab.triggers) foreach (Rectangle t in prefab.Triggers)
{ {
Rectangle transformedTrigger = TransformTrigger(t); Rectangle transformedTrigger = TransformTrigger(t);
GUI.DrawRectangle(spriteBatch, GUI.DrawRectangle(spriteBatch,
@@ -574,7 +574,7 @@ namespace Subsurface
editingHUD.Padding = new Vector4(10, 10, 0, 0); editingHUD.Padding = new Vector4(10, 10, 0, 0);
editingHUD.UserData = this; editingHUD.UserData = this;
new GUITextBlock(new Rectangle(0, 0, 100, 20), prefab.Name, Color.Transparent, Color.White, Alignment.Left, editingHUD); new GUITextBlock(new Rectangle(0, 0, 100, 20), prefab.Name, GUI.style, editingHUD);
y += 20; y += 20;
@@ -582,7 +582,7 @@ namespace Subsurface
{ {
if (prefab.IsLinkable) if (prefab.IsLinkable)
{ {
new GUITextBlock(new Rectangle(0, 20, 100, 20), "Hold space to link to another construction", Color.Transparent, Color.White, Alignment.Left, editingHUD); new GUITextBlock(new Rectangle(0, 20, 100, 20), "Hold space to link to another construction", GUI.style, editingHUD);
y += 25; y += 25;
} }
foreach (ItemComponent ic in components) foreach (ItemComponent ic in components)
@@ -590,8 +590,8 @@ namespace Subsurface
foreach (RelatedItem relatedItem in ic.requiredItems) foreach (RelatedItem relatedItem in ic.requiredItems)
{ {
new GUITextBlock(new Rectangle(0, y, 100, 20),ic.Name+ ": "+relatedItem.Type.ToString()+" required", Color.Transparent, Color.White, Alignment.Left, editingHUD); new GUITextBlock(new Rectangle(0, y, 100, 20), ic.Name + ": " + relatedItem.Type.ToString() + " required", GUI.style, editingHUD);
GUITextBox namesBox = new GUITextBox(new Rectangle(0, y, 200, 20), Color.White, Color.Black, Alignment.Right, Alignment.Left, editingHUD); GUITextBox namesBox = new GUITextBox(new Rectangle(0, y, 200, 20), Alignment.Right, GUI.style, editingHUD);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (relatedItem); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties (relatedItem);
PropertyDescriptor property = properties.Find("JoinedNames", false); PropertyDescriptor property = properties.Find("JoinedNames", false);
@@ -609,8 +609,8 @@ namespace Subsurface
foreach (var objectProperty in editableProperties) foreach (var objectProperty in editableProperties)
{ {
new GUITextBlock(new Rectangle(0, y, 100, 20), objectProperty.Name, Color.Transparent, Color.White, Alignment.Left, editingHUD); new GUITextBlock(new Rectangle(0, y, 100, 20), objectProperty.Name, Color.Transparent, Color.White, Alignment.Left, null, editingHUD);
GUITextBox propertyBox = new GUITextBox(new Rectangle(100, y, 200, 20), Color.White, Color.Black, Alignment.Left, Alignment.Left, editingHUD); GUITextBox propertyBox = new GUITextBox(new Rectangle(100, y, 200, 20), GUI.style, editingHUD);
object value = objectProperty.GetValue(); object value = objectProperty.GetValue();
if (value != null) if (value != null)
@@ -647,7 +647,7 @@ namespace Subsurface
if (panel == null) return; if (panel == null) return;
foreach (Connection c in panel.connections) foreach (Connection c in panel.connections)
{ {
if (c.name != connectionName) continue; if (c.Name != connectionName) continue;
c.SendSignal(signal, this, power); c.SendSignal(signal, this, power);
} }
@@ -669,13 +669,13 @@ namespace Subsurface
foreach (Item item in itemList) foreach (Item item in itemList)
{ {
if (ignoredItems!=null && ignoredItems.Contains(item)) continue; if (ignoredItems!=null && ignoredItems.Contains(item)) continue;
if (hull != null && item.currentHull != hull) continue; if (hull != null && item.CurrentHull != hull) continue;
if (item.body != null && !item.body.Enabled) continue; if (item.body != null && !item.body.Enabled) continue;
Pickable pickableComponent = item.GetComponent<Pickable>(); Pickable pickableComponent = item.GetComponent<Pickable>();
if (pickableComponent != null && (pickableComponent.Picker != null && !pickableComponent.Picker.IsDead)) continue; if (pickableComponent != null && (pickableComponent.Picker != null && !pickableComponent.Picker.IsDead)) continue;
foreach (Rectangle trigger in item.prefab.triggers) foreach (Rectangle trigger in item.prefab.Triggers)
{ {
Rectangle transformedTrigger = item.TransformTrigger(trigger); Rectangle transformedTrigger = item.TransformTrigger(trigger);
+1 -1
View File
@@ -43,7 +43,7 @@ namespace Subsurface
if (wasPut) if (wasPut)
{ {
foreach (Character c in Character.characterList) foreach (Character c in Character.CharacterList)
{ {
if (!c.HasSelectedItem(item)) continue; if (!c.HasSelectedItem(item)) continue;
+4 -4
View File
@@ -23,14 +23,14 @@ namespace Subsurface
protected Vector2 size; protected Vector2 size;
//how close the character has to be to the item to pick it up //how close the character has to be to the item to pick it up
float pickDistance; private float pickDistance;
//public List<Sound> sounds; //public List<Sound> sounds;
//an area next to the construction //an area next to the construction
//the construction can be Activated() by a character inside the area //the construction can be Activated() by a character inside the area
public List<Rectangle> triggers; public List<Rectangle> Triggers;
public string ConfigFile public string ConfigFile
{ {
@@ -177,7 +177,7 @@ namespace Subsurface
offsetOnSelected = ToolBox.GetAttributeFloat(element, "offsetonselected", 0.0f); offsetOnSelected = ToolBox.GetAttributeFloat(element, "offsetonselected", 0.0f);
triggers = new List<Rectangle>(); Triggers = new List<Rectangle>();
foreach (XElement subElement in element.Elements()) foreach (XElement subElement in element.Elements())
{ {
switch (subElement.Name.ToString().ToLower()) switch (subElement.Name.ToString().ToLower())
@@ -195,7 +195,7 @@ namespace Subsurface
trigger.Width = ToolBox.GetAttributeInt(subElement, "width", 0); trigger.Width = ToolBox.GetAttributeInt(subElement, "width", 0);
trigger.Height = ToolBox.GetAttributeInt(subElement, "height", 0); trigger.Height = ToolBox.GetAttributeInt(subElement, "height", 0);
triggers.Add(trigger); Triggers.Add(trigger);
break; break;
} }
+1
View File
@@ -25,6 +25,7 @@ namespace Subsurface
Entity existingEntity; Entity existingEntity;
if (dictionary.TryGetValue(value, out existingEntity)) if (dictionary.TryGetValue(value, out existingEntity))
{ {
System.Diagnostics.Debug.WriteLine(existingEntity+" had the same ID as "+this);
dictionary.Remove(value); dictionary.Remove(value);
dictionary.Add(id, existingEntity); dictionary.Add(id, existingEntity);
existingEntity.id = id; existingEntity.id = id;
+3 -4
View File
@@ -48,8 +48,7 @@ namespace Subsurface
for (int i = 0; i<range*10; i++) for (int i = 0; i<range*10; i++)
{ {
Game1.particleManager.CreateParticle("explosionfire", position, Game1.particleManager.CreateParticle("explosionfire", position,
Vector2.Normalize(new Vector2(MathUtils.RandomFloatLocal(-1.0f, 1.0f), MathUtils.RandomFloatLocal(-1.0f, 1.0f))) * MathUtils.RandomFloatLocal(3.0f, 4.0f), Rand.Vector(Rand.Range(3.0f, 4.0f)), 0.0f);
0.0f);
} }
Vector2 displayPosition = ConvertUnits.ToDisplayUnits(position); Vector2 displayPosition = ConvertUnits.ToDisplayUnits(position);
@@ -83,7 +82,7 @@ namespace Subsurface
} }
} }
foreach (Character c in Character.characterList) foreach (Character c in Character.CharacterList)
{ {
float dist = Vector2.Distance(c.SimPosition, position); float dist = Vector2.Distance(c.SimPosition, position);
@@ -91,7 +90,7 @@ namespace Subsurface
float distFactor = 1.0f - dist / range; float distFactor = 1.0f - dist / range;
foreach (Limb limb in c.animController.limbs) foreach (Limb limb in c.AnimController.limbs)
{ {
distFactor = 1.0f - Vector2.Distance(limb.SimPosition, position)/range; distFactor = 1.0f - Vector2.Distance(limb.SimPosition, position)/range;
+6 -6
View File
@@ -250,20 +250,20 @@ namespace Subsurface
pos.Y = ConvertUnits.ToSimUnits(MathHelper.Clamp(lowerSurface, rect.Y-rect.Height, rect.Y)); pos.Y = ConvertUnits.ToSimUnits(MathHelper.Clamp(lowerSurface, rect.Y-rect.Height, rect.Y));
Game1.particleManager.CreateParticle("watersplash", Game1.particleManager.CreateParticle("watersplash",
new Vector2(pos.X, pos.Y - MathUtils.RandomFloatLocal(0.0f, 0.1f)), new Vector2(pos.X, pos.Y - Rand.Range(0.0f, 0.1f)),
new Vector2(flowForce.X * MathUtils.RandomFloatLocal(0.005f, 0.007f), flowForce.Y * MathUtils.RandomFloatLocal(0.005f, 0.007f))); new Vector2(flowForce.X * Rand.Range(0.005f, 0.007f), flowForce.Y * Rand.Range(0.005f, 0.007f)));
pos.Y = ConvertUnits.ToSimUnits(MathUtils.RandomFloatLocal(lowerSurface, rect.Y - rect.Height)); pos.Y = ConvertUnits.ToSimUnits(Rand.Range(lowerSurface, rect.Y - rect.Height));
Game1.particleManager.CreateParticle("bubbles", pos, flowForce / 200.0f); Game1.particleManager.CreateParticle("bubbles", pos, flowForce / 200.0f);
} }
else else
{ {
pos.Y += Math.Sign(flowForce.Y) * ConvertUnits.ToSimUnits(rect.Height / 2.0f); pos.Y += Math.Sign(flowForce.Y) * ConvertUnits.ToSimUnits(rect.Height / 2.0f);
for (int i = 0; i < rect.Width; i += (int)MathUtils.RandomFloatLocal(80, 100)) for (int i = 0; i < rect.Width; i += (int)Rand.Range(80, 100))
{ {
pos.X = ConvertUnits.ToSimUnits(MathUtils.RandomFloatLocal(rect.X, rect.X+rect.Width)); pos.X = ConvertUnits.ToSimUnits(Rand.Range(rect.X, rect.X+rect.Width));
Subsurface.Particles.Particle splash = Game1.particleManager.CreateParticle("watersplash", pos, Subsurface.Particles.Particle splash = Game1.particleManager.CreateParticle("watersplash", pos,
new Vector2(flowForce.X * MathUtils.RandomFloatLocal(0.005f, 0.008f), flowForce.Y * MathUtils.RandomFloatLocal(0.005f, 0.008f))); new Vector2(flowForce.X * Rand.Range(0.005f, 0.008f), flowForce.Y * Rand.Range(0.005f, 0.008f)));
if (splash!=null) splash.Size = splash.Size * MathHelper.Clamp(rect.Width / 50.0f, 0.8f, 4.0f); if (splash!=null) splash.Size = splash.Size * MathHelper.Clamp(rect.Width / 50.0f, 0.8f, 4.0f);
+2 -2
View File
@@ -119,7 +119,7 @@ namespace Subsurface
{ {
rect = rectangle; rect = rectangle;
OxygenPercentage = (float)(Game1.random.NextDouble() * 100.0); OxygenPercentage = Rand.Range(0.0f, 100.0f, false);
properties = TypeDescriptor.GetProperties(GetType()) properties = TypeDescriptor.GetProperties(GetType())
.Cast<PropertyDescriptor>() .Cast<PropertyDescriptor>()
@@ -210,7 +210,7 @@ namespace Subsurface
for (int i = 0; i < waveY.Length; i++) for (int i = 0; i < waveY.Length; i++)
{ {
float maxDelta = Math.Max(Math.Abs(rightDelta[i]), Math.Abs(leftDelta[i])); float maxDelta = Math.Max(Math.Abs(rightDelta[i]), Math.Abs(leftDelta[i]));
if (maxDelta > MathUtils.RandomFloatLocal(0.2f,10.0f)) if (maxDelta > Rand.Range(0.2f,10.0f))
{ {
Game1.particleManager.CreateParticle("mist", Game1.particleManager.CreateParticle("mist",
ConvertUnits.ToSimUnits(new Vector2(rect.X + WaveWidth * i,surface + waveY[i])), ConvertUnits.ToSimUnits(new Vector2(rect.X + WaveWidth * i,surface + waveY[i])),
+158 -140
View File
@@ -20,7 +20,7 @@ namespace Subsurface
static Level loaded; static Level loaded;
private int seed; private string seed;
private int siteInterval; private int siteInterval;
@@ -45,7 +45,12 @@ namespace Subsurface
get { return startPosition; } get { return startPosition; }
} }
public Level(int seed, int width, int height, int siteInterval) public Vector2 Position
{
get { return ConvertUnits.ToDisplayUnits(cells[0].body.Position); }
}
public Level(string seed, int width, int height, int siteInterval)
{ {
this.seed = seed; this.seed = seed;
@@ -54,9 +59,14 @@ namespace Subsurface
borders = new Rectangle(0, 0, width, height); borders = new Rectangle(0, 0, width, height);
} }
public static Level CreateRandom() public static Level CreateRandom(string seed = "")
{ {
return new Level(100, 100000, 40000, 2000);
if (seed == "")
{
seed = Rand.Range(0, int.MaxValue).ToString();
}
return new Level((string)seed, 100000, 40000, 2000);
} }
public void Generate(float minWidth) public void Generate(float minWidth)
@@ -64,7 +74,7 @@ namespace Subsurface
Stopwatch sw = new Stopwatch(); Stopwatch sw = new Stopwatch();
sw.Start(); sw.Start();
Game1.random = new Random(seed); //Game1.random = new Random(ToolBox.SeedToInt(seed));
if (loaded != null) if (loaded != null)
{ {
@@ -76,7 +86,7 @@ namespace Subsurface
Voronoi voronoi = new Voronoi(1.0); Voronoi voronoi = new Voronoi(1.0);
List<Vector2> sites = new List<Vector2>(); List<Vector2> sites = new List<Vector2>();
Random rand = new Random(seed); Random rand = new Random(ToolBox.SeedToInt(seed));
float siteVariance = siteInterval * 0.8f; float siteVariance = siteInterval * 0.8f;
for (int x = siteInterval/2; x < borders.Width; x += siteInterval) for (int x = siteInterval/2; x < borders.Width; x += siteInterval)
@@ -84,8 +94,8 @@ namespace Subsurface
for (int y = siteInterval / 2; y < borders.Height; y += siteInterval) for (int y = siteInterval / 2; y < borders.Height; y += siteInterval)
{ {
sites.Add(new Vector2( sites.Add(new Vector2(
x + (float)(Game1.random.NextDouble() - 0.5) * siteVariance, x + (float)(rand.NextDouble() - 0.5) * siteVariance,
y + (float)(Game1.random.NextDouble() - 0.5) * siteVariance)); y + (float)(rand.NextDouble() - 0.5) * siteVariance));
} }
} }
@@ -146,25 +156,28 @@ namespace Subsurface
borders.X + (int)minWidth, borders.Y + (int)minWidth, borders.X + (int)minWidth, borders.Y + (int)minWidth,
borders.Right - (int)minWidth, borders.Y + borders.Height - (int)minWidth); borders.Right - (int)minWidth, borders.Y + borders.Height - (int)minWidth);
List<VoronoiCell> pathCells = GeneratePath( List<VoronoiCell> pathCells = GeneratePath(rand,
new Vector2((int)minWidth, Game1.random.Next((int)minWidth, borders.Height - (int)minWidth)), new Vector2((int)minWidth, rand.Next((int)minWidth, borders.Height - (int)minWidth)),
new Vector2(borders.Width - (int)minWidth, Game1.random.Next((int)minWidth, borders.Height - (int)minWidth)), new Vector2(borders.Width - (int)minWidth, rand.Next((int)minWidth, borders.Height - (int)minWidth)),
cells, pathBorders, minWidth); cells, pathBorders, minWidth);
//generate a couple of random paths //generate a couple of random paths
for (int i = 0; i < Game1.random.Next() % 3; i++ ) for (int i = 0; i < rand.Next() % 3; i++ )
{ {
pathBorders = new Rectangle( pathBorders = new Rectangle(
borders.X + siteInterval * 2, borders.Y - siteInterval * 2, borders.X + siteInterval * 2, borders.Y - siteInterval * 2,
borders.Right - siteInterval * 2, borders.Y + borders.Height - siteInterval * 2); borders.Right - siteInterval * 2, borders.Y + borders.Height - siteInterval * 2);
Vector2 start = pathCells[Game1.random.Next(1,pathCells.Count-2)].Center; Vector2 start = pathCells[rand.Next(1,pathCells.Count-2)].Center;
Vector2 end = new Vector2(MathUtils.RandomFloat(pathBorders.X, pathBorders.Right), MathUtils.RandomFloat(pathBorders.Y, pathBorders.Bottom));
float x = pathBorders.X + (float)rand.NextDouble() * (pathBorders.Right - pathBorders.X);
float y = pathBorders.Y + (float)rand.NextDouble() * (pathBorders.Bottom - pathBorders.Y);
Vector2 end = new Vector2(x,y);
pathCells.AddRange pathCells.AddRange
( (
GeneratePath( start,end, cells, pathBorders, 0.0f) GeneratePath(rand, start,end, cells, pathBorders, 0.0f, 0.8f)
); );
} }
@@ -221,7 +234,7 @@ namespace Subsurface
Debug.WriteLine("Generated a map with "+sites.Count+" sites in "+sw.ElapsedMilliseconds+" ms"); Debug.WriteLine("Generated a map with "+sites.Count+" sites in "+sw.ElapsedMilliseconds+" ms");
} }
private List<VoronoiCell> GeneratePath(Vector2 start, Vector2 end, List<VoronoiCell> cells, Microsoft.Xna.Framework.Rectangle limits, float minWidth, float wanderAmount = 0.3f) private List<VoronoiCell> GeneratePath(Random rand, Vector2 start, Vector2 end, List<VoronoiCell> cells, Microsoft.Xna.Framework.Rectangle limits, float minWidth, float wanderAmount = 0.3f)
{ {
Stopwatch sw2 = new Stopwatch(); Stopwatch sw2 = new Stopwatch();
@@ -243,7 +256,7 @@ namespace Subsurface
int edgeIndex = 0; int edgeIndex = 0;
//steer towards target //steer towards target
if (Game1.random.NextDouble()>wanderAmount) if (rand.NextDouble()>wanderAmount)
{ {
for (int i = 0; i < currentCell.edges.Count; i++) for (int i = 0; i < currentCell.edges.Count; i++)
{ {
@@ -264,7 +277,7 @@ namespace Subsurface
allowedEdges.Add(edge); allowedEdges.Add(edge);
} }
edgeIndex = (allowedEdges.Count==0) ? edgeIndex = (allowedEdges.Count==0) ?
0 : currentCell.edges.IndexOf(allowedEdges[Game1.random.Next() % allowedEdges.Count]); 0 : currentCell.edges.IndexOf(allowedEdges[rand.Next() % allowedEdges.Count]);
} }
currentCell = currentCell.edges[edgeIndex].AdjacentCell(currentCell); currentCell = currentCell.edges[edgeIndex].AdjacentCell(currentCell);
@@ -412,45 +425,6 @@ namespace Subsurface
return cells.IndexOf(closestCell); return cells.IndexOf(closestCell);
} }
private void GenerateBodies(List<VoronoiCell> cells, List<VoronoiCell> emptyCells)
{
foreach (VoronoiCell cell in cells)
{
List<Vector2> points = new List<Vector2>();
foreach (GraphEdge edge in cell.edges)
{
VoronoiCell adjacentCell = edge.AdjacentCell(cell);
if (!emptyCells.Contains(adjacentCell)) continue;
if (!points.Contains(edge.point1)) points.Add(edge.point1);
if (!points.Contains(edge.point2)) points.Add(edge.point2);
}
if (points.Count == 0) continue;
for (int i = 0 ; i<points.Count; i++)
{
points[i] = ConvertUnits.ToSimUnits(points[i]);
}
Vertices vertices = new Vertices(points);
Debug.WriteLine("simple: "+vertices.IsSimple());
Debug.WriteLine("convex: "+vertices.IsConvex());
Debug.WriteLine("ccw: "+ vertices.IsCounterClockWise());
Body edgeBody = BodyFactory.CreateChainShape(
Game1.world, vertices, cell);
edgeBody.BodyType = BodyType.Static;
edgeBody.CollisionCategories = Physics.CollisionWall | Physics.CollisionLevel;
cell.body = edgeBody;
}
}
private void GeneratePolygons(List<VoronoiCell> cells, List<VoronoiCell> emptyCells) private void GeneratePolygons(List<VoronoiCell> cells, List<VoronoiCell> emptyCells)
{ {
List<VertexPositionColor> verticeList = new List<VertexPositionColor>(); List<VertexPositionColor> verticeList = new List<VertexPositionColor>();
@@ -490,8 +464,8 @@ namespace Subsurface
int lastIndex = 1; int lastIndex = 1;
for (int i = 0; i < triangleCount; i++ ) for (int i = 0; i < triangleCount; i++ )
{ {
//simple triangulation
List<Vector2> triangleVertices = new List<Vector2>(); List<Vector2> triangleVertices = new List<Vector2>();
triangleVertices.Add(tempVertices[0]); triangleVertices.Add(tempVertices[0]);
for (int j = lastIndex; j<=lastIndex+1; j++) for (int j = lastIndex; j<=lastIndex+1; j++)
{ {
@@ -504,31 +478,43 @@ namespace Subsurface
verticeList.Add(new VertexPositionColor(new Vector3(vertex, 0.0f), Color.LightGray*0.8f));//new Color(n,(n*2)%255,(n*3)%255)*0.5f)); verticeList.Add(new VertexPositionColor(new Vector3(vertex, 0.0f), Color.LightGray*0.8f));//new Color(n,(n*2)%255,(n*3)%255)*0.5f));
} }
bool isSame = false; //bool isSame = false;
if (triangleVertices[0].Y == triangleVertices[1].Y && triangleVertices[1].Y == triangleVertices[2].Y) isSame = true; //if (triangleVertices[0].Y == triangleVertices[1].Y && triangleVertices[1].Y == triangleVertices[2].Y) isSame = true;
if (triangleVertices[0].X == triangleVertices[1].X && triangleVertices[1].X == triangleVertices[2].X) isSame = true; //if (triangleVertices[0].X == triangleVertices[1].X && triangleVertices[1].X == triangleVertices[2].X) isSame = true;
if (isSame) continue; //if (isSame) continue;
//CreateBody(cell, triangleVertices); //CreateBody(cell, triangleVertices);
} }
if (bodyPoints.Count < 2) continue; if (bodyPoints.Count < 2) continue;
//todo: make sure the first point is the one where the edge should start from
bodyPoints.Sort(new CompareCCW(cell.Center)); bodyPoints.Sort(new CompareCCW(cell.Center));
if (bodyPoints.Count == tempVertices.Count)
{
}
for (int i = 0; i < bodyPoints.Count; i++) for (int i = 0; i < bodyPoints.Count; i++)
{ {
cell.bodyVertices.Add(bodyPoints[i]);
bodyPoints[i] = ConvertUnits.ToSimUnits(bodyPoints[i]); bodyPoints[i] = ConvertUnits.ToSimUnits(bodyPoints[i]);
} }
Vertices bodyVertices = new Vertices(bodyPoints); Vertices bodyVertices = new Vertices(bodyPoints);
Body edgeBody = BodyFactory.CreateChainShape( Body edgeBody = BodyFactory.CreateLoopShape(Game1.World, bodyVertices);
Game1.world, bodyVertices, cell);
//Body edgeBody = (bodyVertices.Count == tempVertices.Count) ?
// BodyFactory.CreateLoopShape(Game1.world, bodyVertices) :
// BodyFactory.CreateChainShape(Game1.world, bodyVertices);
edgeBody.UserData = cell; edgeBody.UserData = cell;
edgeBody.BodyType = BodyType.Static; edgeBody.BodyType = BodyType.Kinematic;
edgeBody.CollisionCategories = Physics.CollisionWall | Physics.CollisionLevel; edgeBody.CollisionCategories = Physics.CollisionWall | Physics.CollisionLevel;
cell.body = edgeBody; cell.body = edgeBody;
@@ -539,75 +525,118 @@ namespace Subsurface
//return bodies; //return bodies;
} }
//private void CreateBody(VoronoiCell cell, List<Vector2> bodyVertices)
//{
// for (int i = 0; i < bodyVertices.Count; i++)
// {
// bodyVertices[i] = ConvertUnits.ToSimUnits(bodyVertices[i]);
// }
// //get farseer 'vertices' from vectors
// Vertices _shapevertices = new Vertices(bodyVertices);
// //_shapevertices.Sort(new CompareCCW(cell.Center));
// //feed vertices array to BodyFactory.CreatePolygon to get a new farseer polygonal body
// Body _newBody = BodyFactory.CreatePolygon(Game1.world, _shapevertices, 15);
// _newBody.BodyType = BodyType.Static;
// _newBody.CollisionCategories = Physics.CollisionWall | Physics.CollisionLevel;
// _newBody.UserData = cell;
// cell.body = _newBody;
//}
public Vector2 position;
public void SetPosition(Vector2 pos) public void SetPosition(Vector2 pos)
{ {
Vector2 amount = ConvertUnits.ToSimUnits(pos - position); Vector2 amount = ConvertUnits.ToSimUnits(pos - Position);
foreach (VoronoiCell cell in cells) foreach (VoronoiCell cell in cells)
{ {
if (cell.body == null) continue; if (cell.body == null) continue;
//foreach (Body b in cell.bodies) cell.body.SleepingAllowed = false;
//{
cell.body.SetTransform(cell.body.Position + amount, cell.body.Rotation); cell.body.SetTransform(cell.body.Position + amount, cell.body.Rotation);
//}
} }
position = pos;
} }
Vector2 prevVelocity;
public void Move(Vector2 amount) public void Move(Vector2 amount)
{ {
position += amount; //position += amount;
Vector2 velocity = amount;
Vector2 simVelocity = ConvertUnits.ToSimUnits(amount / (float)Physics.step);
//DebugCheckPos();
amount = ConvertUnits.ToSimUnits(amount);
foreach (VoronoiCell cell in cells) foreach (VoronoiCell cell in cells)
{ {
if (cell.body == null) continue; if (cell.body == null) continue;
//foreach (Body b in cell.bodies) cell.body.LinearVelocity = simVelocity;
//{
// b.SetTransform(b.Position+amount, b.Rotation);
//}
cell.body.SetTransform(cell.body.Position + amount, cell.body.Rotation);
} }
foreach (Character character in Character.characterList) foreach (Character character in Character.CharacterList)
{ {
if (character.animController.CurrentHull==null) foreach (Limb limb in character.AnimController.limbs)
{ {
foreach (Limb limb in character.animController.limbs) //limb.body.SetTransform(limb.body.Position + amount * (float)Physics.step, limb.body.Rotation);
if (character.AnimController.CurrentHull == null)
{ {
limb.body.SetTransform(limb.body.Position + amount, limb.body.Rotation); limb.body.LinearVelocity += simVelocity;
}
else
{
if (limb.type == LimbType.LeftFoot || limb.type == LimbType.RightFoot) continue;
limb.body.ApplyForce((simVelocity - prevVelocity) * 10.0f * limb.Mass);
} }
} }
} }
foreach (Item item in Item.itemList)
{
if (item.CurrentHull != null) continue;
if (item.body == null)
{
item.Move(velocity);
}
else
{
item.body.LinearVelocity += simVelocity;
}
}
prevVelocity = simVelocity;
} }
public static void AfterWorldStep()
{
if (loaded == null) return;
loaded.ResetBodyVelocities();
}
private void ResetBodyVelocities()
{
foreach (Character character in Character.CharacterList)
{
if (character.AnimController.CurrentHull != null) continue;
foreach (Limb limb in character.AnimController.limbs)
{
limb.body.LinearVelocity -= prevVelocity;
}
}
foreach (Item item in Item.itemList)
{
if (item.body == null || item.CurrentHull != null) continue;
item.body.LinearVelocity -= prevVelocity;
}
}
public void DebugCheckPos()
{
Vector2 avgPos = Vector2.Zero;
foreach (VoronoiCell cell in cells)
{
if (cell.body == null) continue;
System.Diagnostics.Debug.WriteLine(cell.body.Position);
avgPos += cell.body.Position;
}
System.Diagnostics.Debug.WriteLine("avgpos: "+avgPos / cells.Count);
System.Diagnostics.Debug.WriteLine("pos: " + Position);
}
Vector2 observerPosition; Vector2 observerPosition;
public void SetObserverPosition(Vector2 position) public void SetObserverPosition(Vector2 position)
{ {
observerPosition = position - this.position; observerPosition = position - this.Position;
int gridPosX = (int)Math.Floor(observerPosition.X / gridCellWidth); int gridPosX = (int)Math.Floor(observerPosition.X / gridCellWidth);
int gridPosY = (int)Math.Floor(observerPosition.Y / gridCellWidth); int gridPosY = (int)Math.Floor(observerPosition.Y / gridCellWidth);
int searchOffset = 2; int searchOffset = 2;
@@ -627,7 +656,7 @@ namespace Subsurface
//foreach (Body b in cellGrid[x, y][i].bodies) //foreach (Body b in cellGrid[x, y][i].bodies)
//{ //{
if (cellGrid[x, y][i].body == null) continue; if (cellGrid[x, y][i].body == null) continue;
cellGrid[x, y][i].body.Enabled = (x >= startX && x <= endX && y >= startY && y <= endY); cellGrid[x, y][i].body.Enabled = true;// (x >= startX && x <= endX && y >= startY && y <= endY);
//} //}
} }
} }
@@ -669,26 +698,30 @@ namespace Subsurface
// } // }
//} //}
List<Vector2[]> edges = GetCellEdges(-observerPosition); List<Vector2[]> edges = GetCellEdges(observerPosition, 1, false);
for (int i = 0; i < edges.Count; i++ ) //for (int i = 0; i < edges.Count; i++)
//{
// GUI.DrawLine(spriteBatch, edges[i][0], edges[i][1], Color.Green);
//}
foreach (VoronoiCell cell in cells)
{ {
GUI.DrawLine(spriteBatch, edges[i][0], edges[i][1], Color.Green); for (int i = 0; i < cell.bodyVertices.Count-1; i++)
{
Vector2 start = cell.bodyVertices[i];
start.X += Position.X;
start.Y = -start.Y - Position.Y;
start.X += Rand.Range(-10.0f, 10.0f);
Vector2 end = cell.bodyVertices[i+1];
end.X += Position.X;
end.Y = -end.Y - Position.Y;
end.X += Rand.Range(-10.0f, 10.0f);
GUI.DrawLine(spriteBatch, start, end, (cell.body != null && cell.body.Enabled) ? Color.Red : Color.Red);
}
} }
//foreach (VoronoiCell cell in cells)
//{
// for (int i = 0; i < cell.edges.Count; i++)
// {
// Vector2 start = cell.edges[i].point1 + position;
// start.Y = -start.Y;
// Vector2 end = cell.edges[i].point2 + position;
// end.Y = -end.Y;
// GUI.DrawLine(spriteBatch, start, end, (cell.body != null && cell.body.Enabled) ? Color.Green : Color.Red);
// }
//}
} }
public List<Vector2[]> GetCellEdges(Vector2 refPos, int searchDepth = 2, bool onlySolid = true) public List<Vector2[]> GetCellEdges(Vector2 refPos, int searchDepth = 2, bool onlySolid = true)
@@ -715,10 +748,10 @@ namespace Subsurface
for (int i = 0; i < cell.edges.Count; i++) for (int i = 0; i < cell.edges.Count; i++)
{ {
if (onlySolid && !cell.edges[i].isSolid) continue; if (onlySolid && !cell.edges[i].isSolid) continue;
Vector2 start = cell.edges[i].point1 + position; Vector2 start = cell.edges[i].point1 + Position;
start.Y = -start.Y; start.Y = -start.Y;
Vector2 end = cell.edges[i].point2 + position; Vector2 end = cell.edges[i].point2 + Position;
end.Y = -end.Y; end.Y = -end.Y;
edges.Add(new Vector2[] { start, end }); edges.Add(new Vector2[] { start, end });
@@ -728,21 +761,6 @@ namespace Subsurface
} }
} }
//foreach (VoronoiCell cell in cells)
//{
// for (int i = 0; i < cell.edges.Count; i++)
// {
// Vector2 start = cell.edges[i].point1 + position;
// start.Y = -start.Y;
// Vector2 end = cell.edges[i].point2 + position;
// end.Y = -end.Y;
// edges.Add(new Vector2[] {start, end});
// //GUI.DrawLine(spriteBatch, start, end, (cell.body != null && cell.body.Enabled) ? Color.Green : Color.Red);
// }
//}
return edges; return edges;
} }
@@ -751,7 +769,7 @@ namespace Subsurface
if (vertices == null) return; if (vertices == null) return;
if (vertices.Length <= 0) return; if (vertices.Length <= 0) return;
basicEffect.World = Matrix.CreateTranslation(new Vector3(position, 0.0f))*cam.ShaderTransform basicEffect.World = Matrix.CreateTranslation(new Vector3(Position, 0.0f))*cam.ShaderTransform
* Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f; * Matrix.CreateOrthographic(Game1.GraphicsWidth, Game1.GraphicsHeight, -1, 1) * 0.5f;
@@ -763,7 +781,7 @@ namespace Subsurface
private void Unload() private void Unload()
{ {
position = Vector2.Zero; //position = Vector2.Zero;
//foreach (VoronoiCell cell in cells) //foreach (VoronoiCell cell in cells)
//{ //{
+4 -4
View File
@@ -5,16 +5,16 @@ namespace Subsurface.Lights
{ {
class LightManager class LightManager
{ {
public static Vector2 viewPos; public static Vector2 ViewPos;
public static bool fowEnabled = true; public static bool FowEnabled = true;
public static void DrawFow(GraphicsDevice graphics, Camera cam) public static void DrawFow(GraphicsDevice graphics, Camera cam)
{ {
if (!fowEnabled) return; if (!FowEnabled) return;
foreach (ConvexHull convexHull in ConvexHull.list) foreach (ConvexHull convexHull in ConvexHull.list)
{ {
convexHull.DrawShadows(graphics, cam, viewPos); convexHull.DrawShadows(graphics, cam, ViewPos);
} }
} }
} }
+1 -1
View File
@@ -31,7 +31,7 @@ namespace Subsurface
public static Location CreateRandom(Vector2 position) public static Location CreateRandom(Vector2 position)
{ {
return new Location("Location " + (Game1.random.Next() % 10000), position); return new Location("Location " + Rand.Int(10000, false), position);
} }
} }
} }
+8 -3
View File
@@ -77,7 +77,7 @@ namespace Subsurface
// connections.Add(new LocationConnection(locations[i], locations[closestIndex], level)); // connections.Add(new LocationConnection(locations[i], locations[closestIndex], level));
//} //}
currentLocation = locations[0]; currentLocation = locations[locations.Count/2];
} }
private void GenerateLocations() private void GenerateLocations()
@@ -87,8 +87,9 @@ namespace Subsurface
List<Vector2> sites = new List<Vector2>(); List<Vector2> sites = new List<Vector2>();
for (int i = 0; i < 50; i++) for (int i = 0; i < 50; i++)
{ {
sites.Add(new Vector2((float)Game1.random.NextDouble() * size, (float)Game1.random.NextDouble() * size)); sites.Add(new Vector2(Rand.Range(0.0f, size), Rand.Range(0.0f, size)));
} }
List<GraphEdge> edges = voronoi.MakeVoronoiGraph(sites, size, size); List<GraphEdge> edges = voronoi.MakeVoronoiGraph(sites, size, size);
sites.Clear(); sites.Clear();
@@ -106,7 +107,7 @@ namespace Subsurface
Vector2[] points = new Vector2[] { edge.point1, edge.point2 }; Vector2[] points = new Vector2[] { edge.point1, edge.point2 };
int positionIndex = Game1.random.Next(0, 1); int positionIndex = Rand.Int(1);
Vector2 position = points[positionIndex]; Vector2 position = points[positionIndex];
if (newLocations[1 - i] != null && newLocations[1 - i].MapPosition == position) position = points[1 - positionIndex]; if (newLocations[1 - i] != null && newLocations[1 - i].MapPosition == position) position = points[1 - positionIndex];
@@ -167,6 +168,8 @@ namespace Subsurface
if (highlightedLocation!=null) if (highlightedLocation!=null)
{ {
Vector2 pos = highlightedLocation.MapPosition * scale; Vector2 pos = highlightedLocation.MapPosition * scale;
pos.X = (int)pos.X;
pos.Y = (int)pos.Y;
spriteBatch.DrawString(GUI.font, highlightedLocation.Name, pos + new Vector2(rect.X - 50, rect.Y), Color.White); spriteBatch.DrawString(GUI.font, highlightedLocation.Name, pos + new Vector2(rect.X - 50, rect.Y), Color.White);
GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X + (int)pos.X - 4, rect.Y + (int)pos.Y - 4, 5 + 8, 5 + 8), Color.White, false); GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X + (int)pos.X - 4, rect.Y + (int)pos.Y - 4, 5 + 8, 5 + 8), Color.White, false);
} }
@@ -174,6 +177,8 @@ namespace Subsurface
if (selectedLocation != null) if (selectedLocation != null)
{ {
Vector2 pos = selectedLocation.MapPosition * scale; Vector2 pos = selectedLocation.MapPosition * scale;
pos.X = (int)pos.X;
pos.Y = (int)pos.Y;
spriteBatch.DrawString(GUI.font, selectedLocation.Name, pos + new Vector2(rect.X - 50, rect.Y), Color.White); spriteBatch.DrawString(GUI.font, selectedLocation.Name, pos + new Vector2(rect.X - 50, rect.Y), Color.White);
GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X + (int)pos.X - 4, rect.Y + (int)pos.Y - 4, 5 + 8, 5 + 8), Color.White, false); GUI.DrawRectangle(spriteBatch, new Rectangle(rect.X + (int)pos.X - 4, rect.Y + (int)pos.Y - 4, 5 + 8, 5 + 8), Color.White, false);
} }
+1 -1
View File
@@ -235,7 +235,7 @@ namespace Subsurface
selectionSize.Y = selectionPos.Y - position.Y; selectionSize.Y = selectionPos.Y - position.Y;
List<MapEntity> newSelection = new List<MapEntity>();// FindSelectedEntities(selectionPos, selectionSize); List<MapEntity> newSelection = new List<MapEntity>();// FindSelectedEntities(selectionPos, selectionSize);
if (Math.Abs(selectionSize.X) > Submarine.gridSize.X || Math.Abs(selectionSize.Y) > Submarine.gridSize.Y) if (Math.Abs(selectionSize.X) > Submarine.GridSize.X || Math.Abs(selectionSize.Y) > Submarine.GridSize.Y)
{ {
newSelection = FindSelectedEntities(selectionPos, selectionSize); newSelection = FindSelectedEntities(selectionPos, selectionSize);
} }
+3 -3
View File
@@ -73,7 +73,7 @@ namespace Subsurface
public virtual void UpdatePlacing(SpriteBatch spriteBatch, Camera cam) public virtual void UpdatePlacing(SpriteBatch spriteBatch, Camera cam)
{ {
Vector2 placeSize = Submarine.gridSize; Vector2 placeSize = Submarine.GridSize;
if (placePosition == Vector2.Zero) if (placePosition == Vector2.Zero)
{ {
@@ -88,8 +88,8 @@ namespace Subsurface
if (resizeVertical) placeSize.Y = placePosition.Y - position.Y; if (resizeVertical) placeSize.Y = placePosition.Y - position.Y;
Rectangle newRect = Submarine.AbsRect(placePosition, placeSize); Rectangle newRect = Submarine.AbsRect(placePosition, placeSize);
newRect.Width = (int)Math.Max(newRect.Width, Submarine.gridSize.X); newRect.Width = (int)Math.Max(newRect.Width, Submarine.GridSize.X);
newRect.Height = (int)Math.Max(newRect.Height, Submarine.gridSize.Y); newRect.Height = (int)Math.Max(newRect.Height, Submarine.GridSize.Y);
if (PlayerInput.GetMouseState.LeftButton == ButtonState.Released) if (PlayerInput.GetMouseState.LeftButton == ButtonState.Released)
{ {
+9 -9
View File
@@ -144,7 +144,7 @@ namespace Subsurface
bodies = new List<Body>(); bodies = new List<Body>();
//gaps = new List<Gap>(); //gaps = new List<Gap>();
Body newBody = BodyFactory.CreateRectangle(Game1.world, Body newBody = BodyFactory.CreateRectangle(Game1.World,
ConvertUnits.ToSimUnits(rect.Width), ConvertUnits.ToSimUnits(rect.Width),
ConvertUnits.ToSimUnits(rect.Height), ConvertUnits.ToSimUnits(rect.Height),
1.5f); 1.5f);
@@ -202,16 +202,16 @@ namespace Subsurface
{ {
bodies = new List<Body>(); bodies = new List<Body>();
Body newBody = BodyFactory.CreateRectangle(Game1.world, Body newBody = BodyFactory.CreateRectangle(Game1.World,
ConvertUnits.ToSimUnits(rect.Width * Math.Sqrt(2.0) - Submarine.gridSize.X), ConvertUnits.ToSimUnits(rect.Width * Math.Sqrt(2.0) - Submarine.GridSize.X),
ConvertUnits.ToSimUnits(10), ConvertUnits.ToSimUnits(10),
1.5f); 1.5f);
newBody.BodyType = BodyType.Static; newBody.BodyType = BodyType.Static;
Vector2 stairPos = new Vector2(Position.X, rect.Y - rect.Height + rect.Width / 2.0f); Vector2 stairPos = new Vector2(Position.X, rect.Y - rect.Height + rect.Width / 2.0f);
stairPos += new Vector2( stairPos += new Vector2(
(StairDirection == Direction.Right) ? -Submarine.gridSize.X*1.5f : Submarine.gridSize.X*1.5f, (StairDirection == Direction.Right) ? -Submarine.GridSize.X*1.5f : Submarine.GridSize.X*1.5f,
- Submarine.gridSize.Y*2.0f); - Submarine.GridSize.Y*2.0f);
newBody.Position = ConvertUnits.ToSimUnits(stairPos); newBody.Position = ConvertUnits.ToSimUnits(stairPos);
@@ -251,7 +251,7 @@ namespace Subsurface
if (bodies != null) if (bodies != null)
{ {
foreach (Body b in bodies) foreach (Body b in bodies)
Game1.world.RemoveBody(b); Game1.World.RemoveBody(b);
} }
if (convexHull != null) convexHull.Remove(); if (convexHull != null) convexHull.Remove();
@@ -299,7 +299,7 @@ namespace Subsurface
Limb limb; Limb limb;
if ((limb = f2.Body.UserData as Limb) != null) if ((limb = f2.Body.UserData as Limb) != null)
{ {
if (limb.character.animController.IgnorePlatforms) return false; if (limb.character.AnimController.IgnorePlatforms) return false;
} }
} }
@@ -443,7 +443,7 @@ namespace Subsurface
{ {
foreach (Body b in bodies) foreach (Body b in bodies)
{ {
Game1.world.RemoveBody(b); Game1.World.RemoveBody(b);
} }
bodies.Clear(); bodies.Clear();
@@ -497,7 +497,7 @@ namespace Subsurface
private Body CreateRectBody(Rectangle rect) private Body CreateRectBody(Rectangle rect)
{ {
Body newBody = BodyFactory.CreateRectangle(Game1.world, Body newBody = BodyFactory.CreateRectangle(Game1.World,
ConvertUnits.ToSimUnits(rect.Width), ConvertUnits.ToSimUnits(rect.Width),
ConvertUnits.ToSimUnits(rect.Height), ConvertUnits.ToSimUnits(rect.Height),
1.5f); 1.5f);
+16 -15
View File
@@ -28,7 +28,7 @@ namespace Subsurface
private static Submarine loaded; private static Submarine loaded;
public static readonly Vector2 gridSize = new Vector2(16.0f, 16.0f); public static readonly Vector2 GridSize = new Vector2(16.0f, 16.0f);
private static Vector2 lastPickedPosition; private static Vector2 lastPickedPosition;
private static float lastPickedFraction; private static float lastPickedFraction;
@@ -253,8 +253,8 @@ namespace Subsurface
public static Vector2 VectorToWorldGrid(Vector2 position) public static Vector2 VectorToWorldGrid(Vector2 position)
{ {
position.X = (float)Math.Floor(Convert.ToDouble(position.X / gridSize.X)) * gridSize.X; 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; position.Y = (float)Math.Ceiling(Convert.ToDouble(position.Y / GridSize.Y)) * GridSize.Y;
return position; return position;
} }
@@ -299,7 +299,7 @@ namespace Subsurface
{ {
float closestFraction = 1.0f; float closestFraction = 1.0f;
Body closestBody = null; Body closestBody = null;
Game1.world.RayCast((fixture, point, normal, fraction) => Game1.World.RayCast((fixture, point, normal, fraction) =>
{ {
if (fixture == null || fixture.CollisionCategories == Category.None) return -1; if (fixture == null || fixture.CollisionCategories == Category.None) return -1;
if (ignoredBodies != null && ignoredBodies.Contains(fixture.Body)) return -1; if (ignoredBodies != null && ignoredBodies.Contains(fixture.Body)) return -1;
@@ -332,7 +332,7 @@ namespace Subsurface
return null; return null;
} }
Game1.world.RayCast((fixture, point, normal, fraction) => Game1.World.RayCast((fixture, point, normal, fraction) =>
{ {
if (fixture == null || fixture.CollisionCategories != Physics.CollisionWall) return -1; if (fixture == null || fixture.CollisionCategories != Physics.CollisionWall) return -1;
@@ -364,7 +364,7 @@ namespace Subsurface
Body foundBody = null; Body foundBody = null;
AABB aabb = new AABB(point, point); AABB aabb = new AABB(point, point);
Game1.world.QueryAABB(p => Game1.World.QueryAABB(p =>
{ {
foundBody = p.Body; foundBody = p.Body;
@@ -408,7 +408,8 @@ namespace Subsurface
} }
//hullBodies[0].body.LinearVelocity = -hullBodies[0].body.Position; //hullBodies[0].body.LinearVelocity = -hullBodies[0].body.Position;
hullBody.SetTransform(Vector2.Zero , 0.0f); //hullBody.SetTransform(Vector2.Zero , 0.0f);
hullBody.LinearVelocity = -hullBody.Position;
if (collidingCell == null) if (collidingCell == null)
{ {
@@ -419,8 +420,8 @@ namespace Subsurface
foreach (GraphEdge ge in collidingCell.edges) foreach (GraphEdge ge in collidingCell.edges)
{ {
Body body = PickBody( Body body = PickBody(
ConvertUnits.ToSimUnits(ge.point1+ Game1.GameSession.Level.position), ConvertUnits.ToSimUnits(ge.point1+ Game1.GameSession.Level.Position),
ConvertUnits.ToSimUnits(ge.point2 + Game1.GameSession.Level.position), new List<Body>(){collidingCell.body}); ConvertUnits.ToSimUnits(ge.point2 + Game1.GameSession.Level.Position), new List<Body>(){collidingCell.body});
if (body == null || body.UserData == null) continue; if (body == null || body.UserData == null) continue;
Structure structure = body.UserData as Structure; Structure structure = body.UserData as Structure;
@@ -461,7 +462,7 @@ namespace Subsurface
public void SetPosition(Vector2 position) public void SetPosition(Vector2 position)
{ {
//hullBodies[0].body.SetTransform(position, 0.0f); //hullBodies[0].body.SetTransform(position, 0.0f);
Translate(position); Level.Loaded.SetPosition(-position);
//prevPosition = position; //prevPosition = position;
} }
@@ -712,9 +713,9 @@ namespace Subsurface
convexHull.Reverse(); convexHull.Reverse();
//get farseer 'vertices' from vectors //get farseer 'vertices' from vectors
Vertices _shapevertices = new Vertices(convexHull); Vertices shapevertices = new Vertices(convexHull);
AABB hullAABB = _shapevertices.GetAABB(); AABB hullAABB = shapevertices.GetAABB();
borders = new Rectangle( borders = new Rectangle(
(int)ConvertUnits.ToDisplayUnits(hullAABB.LowerBound.X), (int)ConvertUnits.ToDisplayUnits(hullAABB.LowerBound.X),
@@ -723,9 +724,9 @@ namespace Subsurface
(int)ConvertUnits.ToDisplayUnits(hullAABB.Extents.Y * 2.0f)); (int)ConvertUnits.ToDisplayUnits(hullAABB.Extents.Y * 2.0f));
var triangulatedVertices = Triangulate.ConvexPartition(_shapevertices, TriangulationAlgorithm.Bayazit); var triangulatedVertices = Triangulate.ConvexPartition(shapevertices, TriangulationAlgorithm.Bayazit);
hullBody = BodyFactory.CreateCompoundPolygon(Game1.world, triangulatedVertices, 5.0f); hullBody = BodyFactory.CreateCompoundPolygon(Game1.World, triangulatedVertices, 5.0f);
hullBody.BodyType = BodyType.Dynamic; hullBody.BodyType = BodyType.Dynamic;
hullBody.CollisionCategories = Physics.CollisionMisc; hullBody.CollisionCategories = Physics.CollisionMisc;
@@ -787,7 +788,7 @@ namespace Subsurface
Ragdoll.list.Clear(); Ragdoll.list.Clear();
Game1.world.Clear(); Game1.World.Clear();
} }
} }
+3 -1
View File
@@ -121,6 +121,8 @@ namespace Voronoi2
public List<GraphEdge> edges; public List<GraphEdge> edges;
public Site site; public Site site;
public List<Vector2> bodyVertices;
public Body body; public Body body;
public Vector2 Center public Vector2 Center
@@ -131,7 +133,7 @@ namespace Voronoi2
public VoronoiCell(Site site) public VoronoiCell(Site site)
{ {
edges = new List<GraphEdge>(); edges = new List<GraphEdge>();
bodyVertices = new List<Vector2>();
//bodies = new List<Body>(); //bodies = new List<Body>();
this.site = site; this.site = site;
} }
+2 -2
View File
@@ -91,7 +91,7 @@ namespace Subsurface
if (!wayPoints.Any()) return null; if (!wayPoints.Any()) return null;
return wayPoints[Game1.random.Next(wayPoints.Count())]; return wayPoints[Rand.Int(wayPoints.Count())];
} }
public override XElement Save(XDocument doc) public override XElement Save(XDocument doc)
@@ -123,7 +123,7 @@ namespace Subsurface
Rectangle rect = new Rectangle( Rectangle rect = new Rectangle(
int.Parse(element.Attribute("x").Value), int.Parse(element.Attribute("x").Value),
int.Parse(element.Attribute("y").Value), int.Parse(element.Attribute("y").Value),
(int)Submarine.gridSize.X, (int)Submarine.gridSize.Y); (int)Submarine.GridSize.X, (int)Submarine.GridSize.Y);
WayPoint w = new WayPoint(rect); WayPoint w = new WayPoint(rect);
-25
View File
@@ -20,31 +20,6 @@ namespace Subsurface
return (float)Math.Floor(value / div) * div; return (float)Math.Floor(value / div) * div;
} }
public static float RandomFloat(int minimum, int maximum)
{
return RandomFloat((float)minimum, (float)maximum);
}
public static float RandomFloat(float minimum, float maximum)
{
return (float)Game1.random.NextDouble() * (maximum - minimum) + minimum;
}
public static int RandomInt(int minimum, int maximum)
{
return Game1.random.Next(maximum - minimum) + minimum;
}
public static float RandomFloatLocal(float minimum, float maximum)
{
return (float)Game1.localRandom.NextDouble() * (maximum - minimum) + minimum;
}
public static int RandomIntLocal(int minimum, int maximum)
{
return Game1.localRandom.Next(maximum - minimum) + minimum;
}
public static float VectorToAngle(Vector2 vector) public static float VectorToAngle(Vector2 vector)
{ {
return (float)Math.Atan2(vector.Y, vector.X); return (float)Math.Atan2(vector.Y, vector.X);
+18 -38
View File
@@ -14,11 +14,6 @@ namespace Subsurface.Networking
private Character myCharacter; private Character myCharacter;
private CharacterInfo characterInfo; private CharacterInfo characterInfo;
string name;
// Create timer that tells client, when to send update
// System.Timers.Timer update;
public Character Character public Character Character
{ {
get { return myCharacter; } get { return myCharacter; }
@@ -30,16 +25,6 @@ namespace Subsurface.Networking
get { return characterInfo; } get { return characterInfo; }
} }
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(name)) return;
name = value;
}
}
public GameClient(string newName) public GameClient(string newName)
{ {
name = newName; name = newName;
@@ -64,7 +49,7 @@ namespace Subsurface.Networking
Client.Start(); Client.Start();
outmsg.Write((byte)PacketTypes.Login); outmsg.Write((byte)PacketTypes.Login);
outmsg.Write(Game1.version.ToString()); outmsg.Write(Game1.Version.ToString());
outmsg.Write(name); outmsg.Write(name);
// Connect client, to ip previously requested from user // Connect client, to ip previously requested from user
@@ -163,7 +148,7 @@ namespace Subsurface.Networking
} }
} }
public void Update() public override void Update()
{ {
if (updateTimer > DateTime.Now) return; if (updateTimer > DateTime.Now) return;
@@ -222,8 +207,10 @@ namespace Subsurface.Networking
case (byte)PacketTypes.StartGame: case (byte)PacketTypes.StartGame:
if (gameStarted) continue; if (gameStarted) continue;
if (this.Character != null) Character.Remove();
int seed = inc.ReadInt32(); int seed = inc.ReadInt32();
Game1.random = new Random(seed); Rand.SetSyncedSeed(seed);
string mapName = inc.ReadString(); string mapName = inc.ReadString();
string mapHash = inc.ReadString(); string mapHash = inc.ReadString();
@@ -241,7 +228,7 @@ namespace Subsurface.Networking
//int gameModeIndex = inc.ReadInt32(); //int gameModeIndex = inc.ReadInt32();
Game1.GameSession = new GameSession(Submarine.Loaded); Game1.GameSession = new GameSession(Submarine.Loaded);
Game1.GameSession.StartShift(duration, 1); Game1.GameSession.StartShift(duration, "asdf");
myCharacter = ReadCharacterData(inc); myCharacter = ReadCharacterData(inc);
Character.Controlled = myCharacter; Character.Controlled = myCharacter;
@@ -270,14 +257,6 @@ namespace Subsurface.Networking
Game1.NetLobbyScreen.AddPlayer(otherClient.name); Game1.NetLobbyScreen.AddPlayer(otherClient.name);
//string newPlayerName = inc.ReadString();
//int newPlayerID = inc.ReadInt32();
//CharacterInfo ch = new CharacterInfo("Content/Characters/Human/human.xml", newPlayerName);
//ch.ID = newPlayerID;
//Character.newCharacterQueue.Enqueue(ch);
AddChatMessage(otherClient.name + " has joined the server", ChatMessageType.Server); AddChatMessage(otherClient.name + " has joined the server", ChatMessageType.Server);
break; break;
@@ -289,7 +268,7 @@ namespace Subsurface.Networking
break; break;
case (byte)PacketTypes.KickedOut: case (byte)PacketTypes.KickedOut:
string msg= inc.ReadString(); string msg = inc.ReadString();
DebugConsole.ThrowError(msg); DebugConsole.ThrowError(msg);
@@ -336,7 +315,7 @@ namespace Subsurface.Networking
gameStarted = false; gameStarted = false;
} }
public void Disconnect() public override void Disconnect()
{ {
NetOutgoingMessage msg = Client.CreateMessage(); NetOutgoingMessage msg = Client.CreateMessage();
msg.Write((byte)PacketTypes.PlayerLeft); msg.Write((byte)PacketTypes.PlayerLeft);
@@ -350,8 +329,9 @@ namespace Subsurface.Networking
NetOutgoingMessage msg = Client.CreateMessage(); NetOutgoingMessage msg = Client.CreateMessage();
msg.Write((byte)PacketTypes.CharacterInfo); msg.Write((byte)PacketTypes.CharacterInfo);
msg.Write(characterInfo.name); msg.Write(characterInfo.Name);
msg.Write(characterInfo.gender == Gender.Male); msg.Write(characterInfo.Gender == Gender.Male);
msg.Write(characterInfo.HeadSpriteId);
Client.SendMessage(msg, NetDeliveryMethod.ReliableUnordered); Client.SendMessage(msg, NetDeliveryMethod.ReliableUnordered);
@@ -359,11 +339,11 @@ namespace Subsurface.Networking
private Character ReadCharacterData(NetIncomingMessage inc) private Character ReadCharacterData(NetIncomingMessage inc)
{ {
string newName = inc.ReadString(); string newName = inc.ReadString();
int ID = inc.ReadInt32(); int ID = inc.ReadInt32();
bool isFemale = inc.ReadBoolean(); bool isFemale = inc.ReadBoolean();
int inventoryID = inc.ReadInt32(); int inventoryID = inc.ReadInt32();
Vector2 position = new Vector2(inc.ReadFloat(), inc.ReadFloat()); Vector2 position = new Vector2(inc.ReadFloat(), inc.ReadFloat());
CharacterInfo ch = new CharacterInfo("Content/Characters/Human/human.xml", newName, isFemale ? Gender.Female : Gender.Male); CharacterInfo ch = new CharacterInfo("Content/Characters/Human/human.xml", newName, isFemale ? Gender.Female : Gender.Male);
Character character = new Character(ch, position); Character character = new Character(ch, position);
@@ -373,11 +353,11 @@ namespace Subsurface.Networking
return character; return character;
} }
public void SendChatMessage(string message) public override void SendChatMessage(string message, ChatMessageType type = ChatMessageType.Default)
{ {
//AddChatMessage(message); //AddChatMessage(message);
ChatMessageType type = (gameStarted && myCharacter != null && myCharacter.IsDead) ? ChatMessageType.Dead : ChatMessageType.Default; type = (gameStarted && myCharacter != null && myCharacter.IsDead) ? ChatMessageType.Dead : ChatMessageType.Default;
NetOutgoingMessage msg = Client.CreateMessage(); NetOutgoingMessage msg = Client.CreateMessage();
msg.Write((byte)PacketTypes.Chatmessage); msg.Write((byte)PacketTypes.Chatmessage);
+19 -19
View File
@@ -9,22 +9,20 @@ namespace Subsurface.Networking
{ {
class GameServer : NetworkMember class GameServer : NetworkMember
{ {
// Server object
NetServer Server; NetServer Server;
// Configuration object
NetPeerConfiguration Config; NetPeerConfiguration Config;
public List<Client> connectedClients = new List<Client>(); public List<Client> connectedClients = new List<Client>();
//NetIncomingMessage inc; const int SparseUpdateInterval = 150;
const int sparseUpdateInterval = 150;
int sparseUpdateTimer; int sparseUpdateTimer;
Client myClient; Client myClient;
public GameServer() public GameServer()
{ {
name = "Server";
Config = new NetPeerConfiguration("subsurface"); Config = new NetPeerConfiguration("subsurface");
Config.Port = 14242; Config.Port = 14242;
@@ -54,7 +52,7 @@ namespace Subsurface.Networking
} }
public void Update() public override void Update()
{ {
// Server.ReadMessage() Returns new messages, that have not yet been read. // Server.ReadMessage() Returns new messages, that have not yet been read.
// If "inc" is null -> ReadMessage returned null -> Its null, so dont do this :) // If "inc" is null -> ReadMessage returned null -> Its null, so dont do this :)
@@ -109,10 +107,10 @@ namespace Subsurface.Networking
if (sender == null) break; if (sender == null) break;
if (sender.version != Game1.version.ToString()) if (sender.version != Game1.Version.ToString())
{ {
DisconnectClient(sender, sender.name+" was unable to connect to the server (nonmatching game version)", DisconnectClient(sender, sender.name+" was unable to connect to the server (nonmatching game version)",
"Subsurface version " + Game1.version + " required to connect to the server (Your version: " + sender.version + ")"); "Subsurface version " + Game1.Version + " required to connect to the server (Your version: " + sender.version + ")");
} }
else else
@@ -208,7 +206,7 @@ namespace Subsurface.Networking
private void SparseUpdate() private void SparseUpdate()
{ {
foreach (Character c in Character.characterList) foreach (Character c in Character.CharacterList)
{ {
bool isClient = false; bool isClient = false;
foreach (Client client in connectedClients) foreach (Client client in connectedClients)
@@ -220,12 +218,12 @@ namespace Subsurface.Networking
if (!isClient) if (!isClient)
{ {
c.largeUpdateTimer = 0; c.LargeUpdateTimer = 0;
new NetworkEvent(c.ID, false); new NetworkEvent(c.ID, false);
} }
} }
sparseUpdateTimer = sparseUpdateInterval; sparseUpdateTimer = SparseUpdateInterval;
} }
private void SendMessage(NetOutgoingMessage msg, NetDeliveryMethod deliveryMethod, NetConnection excludedConnection) private void SendMessage(NetOutgoingMessage msg, NetDeliveryMethod deliveryMethod, NetConnection excludedConnection)
@@ -268,14 +266,14 @@ namespace Subsurface.Networking
public bool StartGame(GUIButton button, object obj) public bool StartGame(GUIButton button, object obj)
{ {
int seed = DateTime.Now.Millisecond; int seed = DateTime.Now.Millisecond;
Game1.random = new Random(seed); Rand.SetSyncedSeed(seed);
Submarine selectedMap = Game1.NetLobbyScreen.SelectedMap as Submarine; Submarine selectedMap = Game1.NetLobbyScreen.SelectedMap as Submarine;
//selectedMap.Load(); //selectedMap.Load();
Game1.GameSession = new GameSession(selectedMap, Game1.NetLobbyScreen.SelectedMode); Game1.GameSession = new GameSession(selectedMap, Game1.NetLobbyScreen.SelectedMode);
Game1.GameSession.StartShift(Game1.NetLobbyScreen.GameDuration, 1); Game1.GameSession.StartShift(Game1.NetLobbyScreen.GameDuration, "asdf", 1);
//EventManager.SelectEvent(Game1.netLobbyScreen.SelectedEvent); //EventManager.SelectEvent(Game1.netLobbyScreen.SelectedEvent);
foreach (Client client in connectedClients) foreach (Client client in connectedClients)
@@ -446,17 +444,17 @@ namespace Subsurface.Networking
public void SendChatMessage(string message, ChatMessageType type = ChatMessageType.Server) public override void SendChatMessage(string message, ChatMessageType type = ChatMessageType.Server)
{ {
AddChatMessage(message, type); AddChatMessage(message, type);
if (Server.Connections.Count == 0) return;
NetOutgoingMessage msg = Server.CreateMessage(); NetOutgoingMessage msg = Server.CreateMessage();
msg.Write((byte)PacketTypes.Chatmessage); msg.Write((byte)PacketTypes.Chatmessage);
msg.Write((byte)type); msg.Write((byte)type);
msg.Write(message); msg.Write(message);
if (Server.Connections.Count == 0) return;
if (type==ChatMessageType.Dead) if (type==ChatMessageType.Dead)
{ {
List<NetConnection> recipients = new List<NetConnection>(); List<NetConnection> recipients = new List<NetConnection>();
@@ -478,13 +476,15 @@ namespace Subsurface.Networking
private void ReadCharacterData(NetIncomingMessage message) private void ReadCharacterData(NetIncomingMessage message)
{ {
string name = message.ReadString(); string name = message.ReadString();
Gender gender = message.ReadBoolean() ? Gender.Male : Gender.Female; Gender gender = message.ReadBoolean() ? Gender.Male : Gender.Female;
int headSpriteId = message.ReadInt32();
foreach (Client c in connectedClients) foreach (Client c in connectedClients)
{ {
if (c.Connection != message.SenderConnection) continue; if (c.Connection != message.SenderConnection) continue;
c.characterInfo = new CharacterInfo("Content/Characters/Human/human.xml", name, gender); c.characterInfo = new CharacterInfo("Content/Characters/Human/human.xml", name, gender);
c.characterInfo.HeadSpriteId = headSpriteId;
} }
} }
@@ -492,7 +492,7 @@ namespace Subsurface.Networking
{ {
message.Write(name); message.Write(name);
message.Write(character.ID); message.Write(character.ID);
message.Write(character.info.gender==Gender.Female); message.Write(character.Info.Gender == Gender.Female);
message.Write(character.Inventory.ID); message.Write(character.Inventory.ID);
message.Write(character.SimPosition.X); message.Write(character.SimPosition.X);
message.Write(character.SimPosition.Y); message.Write(character.SimPosition.Y);
+18
View File
@@ -30,11 +30,23 @@ namespace Subsurface.Networking
{ {
protected static Color[] messageColor = { Color.Black, Color.DarkRed, Color.DarkBlue, Color.DarkGreen }; protected static Color[] messageColor = { Color.Black, Color.DarkRed, Color.DarkBlue, Color.DarkGreen };
protected string name;
protected TimeSpan updateInterval; protected TimeSpan updateInterval;
protected DateTime updateTimer; protected DateTime updateTimer;
protected bool gameStarted; protected bool gameStarted;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(name)) return;
name = value;
}
}
public void AddChatMessage(string message, ChatMessageType messageType) public void AddChatMessage(string message, ChatMessageType messageType)
{ {
Game1.NetLobbyScreen.NewChatMessage(message, messageColor[(int)messageType]); Game1.NetLobbyScreen.NewChatMessage(message, messageColor[(int)messageType]);
@@ -42,6 +54,12 @@ namespace Subsurface.Networking
GUI.PlayMessageSound(); GUI.PlayMessageSound();
} }
public virtual void SendChatMessage(string message, ChatMessageType type = ChatMessageType.Server) { }
public virtual void Update() { }
public virtual void Disconnect() { }
} }
enum ChatMessageType enum ChatMessageType

Some files were not shown because too many files have changed in this diff Show More