(61d00a474) v0.9.7.1
This commit is contained in:
@@ -0,0 +1,679 @@
|
||||
using Barotrauma.Extensions;
|
||||
using Barotrauma.Items.Components;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
|
||||
namespace Barotrauma.Lights
|
||||
{
|
||||
class ConvexHullList
|
||||
{
|
||||
private List<ConvexHull> list;
|
||||
public HashSet<ConvexHull> IsHidden;
|
||||
|
||||
public readonly Submarine Submarine;
|
||||
public List<ConvexHull> List
|
||||
{
|
||||
get { return list; }
|
||||
set
|
||||
{
|
||||
Debug.Assert(value != null);
|
||||
Debug.Assert(!list.Contains(null));
|
||||
list = value;
|
||||
IsHidden.RemoveWhere(ch => !list.Contains(ch));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public ConvexHullList(Submarine submarine)
|
||||
{
|
||||
Submarine = submarine;
|
||||
list = new List<ConvexHull>();
|
||||
IsHidden = new HashSet<ConvexHull>();
|
||||
}
|
||||
}
|
||||
|
||||
class Segment
|
||||
{
|
||||
public SegmentPoint Start;
|
||||
public SegmentPoint End;
|
||||
|
||||
public ConvexHull ConvexHull;
|
||||
|
||||
public bool IsHorizontal;
|
||||
public bool IsAxisAligned;
|
||||
|
||||
public Segment(SegmentPoint start, SegmentPoint end, ConvexHull convexHull)
|
||||
{
|
||||
if (start.Pos.Y > end.Pos.Y)
|
||||
{
|
||||
var temp = start;
|
||||
start = end;
|
||||
end = temp;
|
||||
}
|
||||
|
||||
Start = start;
|
||||
End = end;
|
||||
ConvexHull = convexHull;
|
||||
|
||||
start.ConvexHull = convexHull;
|
||||
end.ConvexHull = convexHull;
|
||||
|
||||
IsHorizontal = Math.Abs(start.Pos.X - end.Pos.X) > Math.Abs(start.Pos.Y - end.Pos.Y);
|
||||
IsAxisAligned = Math.Abs(start.Pos.X - end.Pos.X) < 0.1f || Math.Abs(start.Pos.Y - end.Pos.Y) < 0.001f;
|
||||
}
|
||||
}
|
||||
|
||||
struct SegmentPoint
|
||||
{
|
||||
public Vector2 Pos;
|
||||
public Vector2 WorldPos;
|
||||
|
||||
public ConvexHull ConvexHull;
|
||||
|
||||
public SegmentPoint(Vector2 pos, ConvexHull convexHull)
|
||||
{
|
||||
Pos = pos;
|
||||
WorldPos = pos;
|
||||
ConvexHull = convexHull;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Pos.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
class ConvexHull
|
||||
{
|
||||
public static List<ConvexHullList> HullLists = new List<ConvexHullList>();
|
||||
public static BasicEffect shadowEffect;
|
||||
public static BasicEffect penumbraEffect;
|
||||
|
||||
private Segment[] segments = new Segment[4];
|
||||
private SegmentPoint[] vertices = new SegmentPoint[4];
|
||||
private SegmentPoint[] losVertices = new SegmentPoint[4];
|
||||
|
||||
private readonly bool[] backFacing;
|
||||
private readonly bool[] ignoreEdge;
|
||||
|
||||
private readonly bool isHorizontal;
|
||||
|
||||
public VertexPositionColor[] ShadowVertices { get; private set; }
|
||||
public VertexPositionTexture[] PenumbraVertices { get; private set; }
|
||||
public int ShadowVertexCount { get; private set; }
|
||||
|
||||
public MapEntity ParentEntity { get; private set; }
|
||||
|
||||
private bool enabled;
|
||||
public bool Enabled
|
||||
{
|
||||
get
|
||||
{
|
||||
return enabled;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (enabled == value) return;
|
||||
enabled = value;
|
||||
LastVertexChangeTime = (float)Timing.TotalTime;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The elapsed gametime when the vertices of this hull last changed
|
||||
/// </summary>
|
||||
public float LastVertexChangeTime
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
public Rectangle BoundingBox { get; private set; }
|
||||
|
||||
public ConvexHull(Vector2[] points, Color color, MapEntity parent)
|
||||
{
|
||||
if (shadowEffect == null)
|
||||
{
|
||||
shadowEffect = new BasicEffect(GameMain.Instance.GraphicsDevice)
|
||||
{
|
||||
VertexColorEnabled = true
|
||||
};
|
||||
}
|
||||
if (penumbraEffect == null)
|
||||
{
|
||||
penumbraEffect = new BasicEffect(GameMain.Instance.GraphicsDevice)
|
||||
{
|
||||
TextureEnabled = true,
|
||||
LightingEnabled = false,
|
||||
Texture = TextureLoader.FromFile("Content/Lights/penumbra.png")
|
||||
};
|
||||
}
|
||||
|
||||
ParentEntity = parent;
|
||||
|
||||
ShadowVertices = new VertexPositionColor[6 * 2];
|
||||
PenumbraVertices = new VertexPositionTexture[6];
|
||||
|
||||
backFacing = new bool[4];
|
||||
ignoreEdge = new bool[4];
|
||||
|
||||
SetVertices(points);
|
||||
|
||||
Enabled = true;
|
||||
|
||||
isHorizontal = BoundingBox.Width > BoundingBox.Height;
|
||||
if (ParentEntity is Structure structure)
|
||||
{
|
||||
isHorizontal = structure.IsHorizontal;
|
||||
}
|
||||
else if (ParentEntity is Item item)
|
||||
{
|
||||
var door = item.GetComponent<Door>();
|
||||
if (door != null) { isHorizontal = door.IsHorizontal; }
|
||||
}
|
||||
|
||||
var chList = HullLists.Find(x => x.Submarine == parent.Submarine);
|
||||
if (chList == null)
|
||||
{
|
||||
chList = new ConvexHullList(parent.Submarine);
|
||||
HullLists.Add(chList);
|
||||
}
|
||||
|
||||
foreach (ConvexHull ch in chList.List)
|
||||
{
|
||||
MergeOverlappingSegments(ch);
|
||||
ch.MergeOverlappingSegments(this);
|
||||
}
|
||||
|
||||
chList.List.Add(this);
|
||||
}
|
||||
|
||||
private void MergeOverlappingSegments(ConvexHull ch)
|
||||
{
|
||||
if (ch == this) return;
|
||||
|
||||
if (isHorizontal == ch.isHorizontal)
|
||||
{
|
||||
//hide segments that are roughly at the some position as some other segment (e.g. the ends of two adjacent wall pieces)
|
||||
float mergeDist = 32;
|
||||
float mergeDistSqr = mergeDist * mergeDist;
|
||||
for (int i = 0; i < segments.Length; i++)
|
||||
{
|
||||
for (int j = 0; j < ch.segments.Length; j++)
|
||||
{
|
||||
if (segments[i].IsHorizontal != ch.segments[j].IsHorizontal) { continue; }
|
||||
|
||||
//the segments must be at different sides of the convex hulls to be merged
|
||||
//(e.g. the right edge of a wall piece and the left edge of another one)
|
||||
var segment1Center = (segments[i].Start.Pos + segments[i].End.Pos) / 2.0f;
|
||||
var segment2Center = (ch.segments[j].Start.Pos + ch.segments[j].End.Pos) / 2.0f;
|
||||
if (Vector2.Dot(segment1Center - BoundingBox.Center.ToVector2(), segment2Center - ch.BoundingBox.Center.ToVector2()) > 0) { continue; }
|
||||
|
||||
if (Vector2.DistanceSquared(segments[i].Start.Pos, ch.segments[j].Start.Pos) < mergeDistSqr &&
|
||||
Vector2.DistanceSquared(segments[i].End.Pos, ch.segments[j].End.Pos) < mergeDistSqr)
|
||||
{
|
||||
ignoreEdge[i] = true;
|
||||
ch.ignoreEdge[j] = true;
|
||||
MergeSegments(segments[i], ch.segments[j], true);
|
||||
}
|
||||
else if (Vector2.DistanceSquared(segments[i].Start.Pos, ch.segments[j].End.Pos) < mergeDistSqr &&
|
||||
Vector2.DistanceSquared(segments[i].End.Pos, ch.segments[j].Start.Pos) < mergeDistSqr)
|
||||
{
|
||||
ignoreEdge[i] = true;
|
||||
ch.ignoreEdge[j] = true;
|
||||
MergeSegments(segments[i], ch.segments[j], false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//TODO: do something to corner areas where a vertical wall meets a horizontal one
|
||||
}
|
||||
|
||||
//ignore edges that are inside some other convex hull
|
||||
for (int i = 0; i < vertices.Length; i++)
|
||||
{
|
||||
if (vertices[i].Pos.X >= ch.BoundingBox.X && vertices[i].Pos.X <= ch.BoundingBox.Right &&
|
||||
vertices[i].Pos.Y >= ch.BoundingBox.Y && vertices[i].Pos.Y <= ch.BoundingBox.Bottom)
|
||||
{
|
||||
Vector2 p = vertices[(i + 1) % vertices.Length].Pos;
|
||||
|
||||
if (p.X >= ch.BoundingBox.X && p.X <= ch.BoundingBox.Right &&
|
||||
p.Y >= ch.BoundingBox.Y && p.Y <= ch.BoundingBox.Bottom)
|
||||
{
|
||||
ignoreEdge[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void MergeSegments(Segment segment1, Segment segment2, bool startPointsMatch)
|
||||
{
|
||||
int startPointIndex = -1, endPointIndex = -1;
|
||||
for (int i = 0; i < vertices.Length; i++)
|
||||
{
|
||||
if (vertices[i].Pos.NearlyEquals(segment1.Start.Pos))
|
||||
startPointIndex = i;
|
||||
else if (vertices[i].Pos.NearlyEquals(segment1.End.Pos))
|
||||
endPointIndex = i;
|
||||
}
|
||||
if (startPointIndex == -1 || endPointIndex == -1) { return; }
|
||||
|
||||
int startPoint2Index = -1, endPoint2Index = -1;
|
||||
for (int i = 0; i < segment2.ConvexHull.vertices.Length; i++)
|
||||
{
|
||||
if (segment2.ConvexHull.vertices[i].Pos.NearlyEquals(segment2.Start.Pos))
|
||||
startPoint2Index = i;
|
||||
else if (segment2.ConvexHull.vertices[i].Pos.NearlyEquals(segment2.End.Pos))
|
||||
endPoint2Index = i;
|
||||
}
|
||||
if (startPoint2Index == -1 || endPoint2Index == -1) { return; }
|
||||
|
||||
if (startPointsMatch)
|
||||
{
|
||||
losVertices[startPointIndex].Pos = segment2.ConvexHull.losVertices[startPoint2Index].Pos =
|
||||
(segment1.Start.Pos + segment2.Start.Pos) / 2.0f;
|
||||
losVertices[endPointIndex].Pos = segment2.ConvexHull.losVertices[endPoint2Index].Pos =
|
||||
(segment1.End.Pos + segment2.End.Pos) / 2.0f;
|
||||
}
|
||||
else
|
||||
{
|
||||
losVertices[startPointIndex].Pos = segment2.ConvexHull.losVertices[startPoint2Index].Pos =
|
||||
(segment1.Start.Pos + segment2.End.Pos) / 2.0f;
|
||||
losVertices[endPointIndex].Pos = segment2.ConvexHull.losVertices[endPoint2Index].Pos =
|
||||
(segment1.End.Pos + segment2.Start.Pos) / 2.0f;
|
||||
}
|
||||
}
|
||||
|
||||
public void Rotate(Vector2 origin, float amount)
|
||||
{
|
||||
Matrix rotationMatrix =
|
||||
Matrix.CreateTranslation(-origin.X, -origin.Y, 0.0f) *
|
||||
Matrix.CreateRotationZ(amount) *
|
||||
Matrix.CreateTranslation(origin.X, origin.Y, 0.0f);
|
||||
SetVertices(vertices.Select(v => v.Pos).ToArray(), rotationMatrix);
|
||||
}
|
||||
|
||||
private void CalculateDimensions()
|
||||
{
|
||||
float minX = vertices[0].Pos.X, minY = vertices[0].Pos.Y, maxX = vertices[0].Pos.X, maxY = vertices[0].Pos.Y;
|
||||
|
||||
for (int i = 1; i < vertices.Length; i++)
|
||||
{
|
||||
if (vertices[i].Pos.X < minX) minX = vertices[i].Pos.X;
|
||||
if (vertices[i].Pos.Y < minY) minY = vertices[i].Pos.Y;
|
||||
|
||||
if (vertices[i].Pos.X > maxX) maxX = vertices[i].Pos.X;
|
||||
if (vertices[i].Pos.Y > minY) maxY = vertices[i].Pos.Y;
|
||||
}
|
||||
|
||||
BoundingBox = new Rectangle((int)minX, (int)minY, (int)(maxX - minX), (int)(maxY - minY));
|
||||
}
|
||||
|
||||
public void Move(Vector2 amount)
|
||||
{
|
||||
for (int i = 0; i < vertices.Length; i++)
|
||||
{
|
||||
vertices[i].Pos += amount;
|
||||
losVertices[i].Pos += amount;
|
||||
|
||||
segments[i].Start.Pos += amount;
|
||||
segments[i].End.Pos += amount;
|
||||
}
|
||||
|
||||
LastVertexChangeTime = (float)Timing.TotalTime;
|
||||
|
||||
CalculateDimensions();
|
||||
}
|
||||
|
||||
public void SetVertices(Vector2[] points, Matrix? rotationMatrix = null)
|
||||
{
|
||||
Debug.Assert(points.Length == 4, "Only rectangular convex hulls are supported");
|
||||
|
||||
LastVertexChangeTime = (float)Timing.TotalTime;
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
vertices[i] = new SegmentPoint(points[i], this);
|
||||
losVertices[i] = new SegmentPoint(points[i], this);
|
||||
}
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
ignoreEdge[i] = false;
|
||||
}
|
||||
|
||||
int margin = 0;
|
||||
if (Math.Abs(points[0].X - points[2].X) < Math.Abs(points[0].Y - points[2].Y))
|
||||
{
|
||||
losVertices[0].Pos = new Vector2(points[0].X + margin, points[0].Y);
|
||||
losVertices[1].Pos = new Vector2(points[1].X + margin, points[1].Y);
|
||||
losVertices[2].Pos = new Vector2(points[2].X - margin, points[2].Y);
|
||||
losVertices[3].Pos = new Vector2(points[3].X - margin, points[3].Y);
|
||||
}
|
||||
else
|
||||
{
|
||||
losVertices[0].Pos = new Vector2(points[0].X, points[0].Y + margin);
|
||||
losVertices[1].Pos = new Vector2(points[1].X, points[1].Y - margin);
|
||||
losVertices[2].Pos = new Vector2(points[2].X, points[2].Y - margin);
|
||||
losVertices[3].Pos = new Vector2(points[3].X, points[3].Y + margin);
|
||||
}
|
||||
|
||||
if (rotationMatrix.HasValue)
|
||||
{
|
||||
for (int i = 0; i < vertices.Length; i++)
|
||||
{
|
||||
vertices[i].Pos = Vector2.Transform(vertices[i].Pos, rotationMatrix.Value);
|
||||
losVertices[i].Pos = Vector2.Transform(losVertices[i].Pos, rotationMatrix.Value);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
segments[i] = new Segment(vertices[i], vertices[(i + 1) % 4], this);
|
||||
}
|
||||
|
||||
CalculateDimensions();
|
||||
|
||||
if (ParentEntity == null) return;
|
||||
|
||||
var chList = HullLists.Find(x => x.Submarine == ParentEntity.Submarine);
|
||||
if (chList != null)
|
||||
{
|
||||
foreach (ConvexHull ch in chList.List)
|
||||
{
|
||||
MergeOverlappingSegments(ch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool Intersects(Rectangle rect)
|
||||
{
|
||||
if (!Enabled) return false;
|
||||
|
||||
Rectangle transformedBounds = BoundingBox;
|
||||
if (ParentEntity != null && ParentEntity.Submarine != null)
|
||||
{
|
||||
transformedBounds.X += (int)ParentEntity.Submarine.Position.X;
|
||||
transformedBounds.Y += (int)ParentEntity.Submarine.Position.Y;
|
||||
}
|
||||
return transformedBounds.Intersects(rect);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the segments that are facing towards viewPosition
|
||||
/// </summary>
|
||||
public void GetVisibleSegments(Vector2 viewPosition, List<Segment> visibleSegments, bool ignoreEdges)
|
||||
{
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
if (ignoreEdge[i] && ignoreEdges) continue;
|
||||
|
||||
Vector2 pos1 = vertices[i].WorldPos;
|
||||
Vector2 pos2 = vertices[(i + 1) % 4].WorldPos;
|
||||
|
||||
Vector2 middle = (pos1 + pos2) / 2;
|
||||
|
||||
Vector2 L = viewPosition - middle;
|
||||
|
||||
Vector2 N = new Vector2(
|
||||
-(pos2.Y - pos1.Y),
|
||||
pos2.X - pos1.X);
|
||||
|
||||
if (Vector2.Dot(N, L) > 0)
|
||||
{
|
||||
visibleSegments.Add(segments[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void RefreshWorldPositions()
|
||||
{
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
vertices[i].WorldPos = vertices[i].Pos;
|
||||
segments[i].Start.WorldPos = segments[i].Start.Pos;
|
||||
segments[i].End.WorldPos = segments[i].End.Pos;
|
||||
}
|
||||
if (ParentEntity == null || ParentEntity.Submarine == null) { return; }
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
vertices[i].WorldPos += ParentEntity.Submarine.DrawPosition;
|
||||
segments[i].Start.WorldPos += ParentEntity.Submarine.DrawPosition;
|
||||
segments[i].End.WorldPos += ParentEntity.Submarine.DrawPosition;
|
||||
}
|
||||
}
|
||||
|
||||
public void CalculateShadowVertices(Vector2 lightSourcePos, bool los = true)
|
||||
{
|
||||
Vector3 offset = Vector3.Zero;
|
||||
if (ParentEntity != null && ParentEntity.Submarine != null)
|
||||
{
|
||||
offset = new Vector3(ParentEntity.Submarine.DrawPosition.X, ParentEntity.Submarine.DrawPosition.Y, 0.0f);
|
||||
}
|
||||
|
||||
ShadowVertexCount = 0;
|
||||
|
||||
var vertices = los ? losVertices : this.vertices;
|
||||
|
||||
//compute facing of each edge, using N*L
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
if (ignoreEdge[i])
|
||||
{
|
||||
backFacing[i] = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
Vector2 firstVertex = vertices[i].Pos;
|
||||
Vector2 secondVertex = vertices[(i+1) % 4].Pos;
|
||||
|
||||
Vector2 L = lightSourcePos - ((firstVertex + secondVertex) / 2.0f);
|
||||
|
||||
Vector2 N = new Vector2(
|
||||
-(secondVertex.Y - firstVertex.Y),
|
||||
secondVertex.X - firstVertex.X);
|
||||
|
||||
backFacing[i] = (Vector2.Dot(N, L) < 0) == los;
|
||||
}
|
||||
|
||||
//find beginning and ending vertices which
|
||||
//belong to the shadow
|
||||
int startingIndex = 0;
|
||||
int endingIndex = 0;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
int currentEdge = i;
|
||||
int nextEdge = (i + 1) % 4;
|
||||
|
||||
if (backFacing[currentEdge] && !backFacing[nextEdge])
|
||||
endingIndex = nextEdge;
|
||||
|
||||
if (!backFacing[currentEdge] && backFacing[nextEdge])
|
||||
startingIndex = nextEdge;
|
||||
}
|
||||
|
||||
//nr of vertices that are in the shadow
|
||||
if (endingIndex > startingIndex)
|
||||
ShadowVertexCount = endingIndex - startingIndex + 1;
|
||||
else
|
||||
ShadowVertexCount = 4 + 1 - startingIndex + endingIndex;
|
||||
|
||||
//shadowVertices = new VertexPositionColor[shadowVertexCount * 2];
|
||||
|
||||
//create a triangle strip that has the shape of the shadow
|
||||
int currentIndex = startingIndex;
|
||||
int svCount = 0;
|
||||
while (svCount != ShadowVertexCount * 2)
|
||||
{
|
||||
Vector3 vertexPos = new Vector3(vertices[currentIndex].Pos, 0.0f);
|
||||
|
||||
int i = los ? svCount : svCount + 1;
|
||||
int j = los ? svCount + 1 : svCount;
|
||||
|
||||
//one vertex on the hull
|
||||
ShadowVertices[i] = new VertexPositionColor
|
||||
{
|
||||
Color = los ? Color.Black : Color.Transparent,
|
||||
Position = vertexPos + offset
|
||||
};
|
||||
|
||||
//one extruded by the light direction
|
||||
ShadowVertices[j] = new VertexPositionColor
|
||||
{
|
||||
Color = ShadowVertices[i].Color
|
||||
};
|
||||
|
||||
Vector3 L2P = vertexPos - new Vector3(lightSourcePos, 0);
|
||||
L2P.Normalize();
|
||||
|
||||
ShadowVertices[j].Position = new Vector3(lightSourcePos, 0) + L2P * 9000 + offset;
|
||||
|
||||
svCount += 2;
|
||||
currentIndex = (currentIndex + 1) % 4;
|
||||
}
|
||||
|
||||
if (los)
|
||||
{
|
||||
CalculatePenumbraVertices(startingIndex, endingIndex, lightSourcePos, los);
|
||||
}
|
||||
}
|
||||
|
||||
private void CalculatePenumbraVertices(int startingIndex, int endingIndex, Vector2 lightSourcePos, bool los)
|
||||
{
|
||||
var vertices = los ? losVertices : this.vertices;
|
||||
|
||||
Vector3 offset = Vector3.Zero;
|
||||
if (ParentEntity != null && ParentEntity.Submarine != null)
|
||||
{
|
||||
offset = new Vector3(ParentEntity.Submarine.DrawPosition.X, ParentEntity.Submarine.DrawPosition.Y, 0.0f);
|
||||
}
|
||||
|
||||
for (int n = 0; n < 4; n += 3)
|
||||
{
|
||||
Vector3 penumbraStart = new Vector3((n == 0) ? vertices[startingIndex].Pos : vertices[endingIndex].Pos, 0.0f);
|
||||
|
||||
PenumbraVertices[n] = new VertexPositionTexture
|
||||
{
|
||||
Position = penumbraStart + offset,
|
||||
TextureCoordinate = new Vector2(0.0f, 1.0f)
|
||||
};
|
||||
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
PenumbraVertices[n + i + 1] = new VertexPositionTexture();
|
||||
Vector3 vertexDir = penumbraStart - new Vector3(lightSourcePos, 0);
|
||||
vertexDir.Normalize();
|
||||
|
||||
Vector3 normal = (i == 0) ? new Vector3(-vertexDir.Y, vertexDir.X, 0.0f) : new Vector3(vertexDir.Y, -vertexDir.X, 0.0f) * 0.05f;
|
||||
if (n > 0) normal = -normal;
|
||||
|
||||
vertexDir = penumbraStart - (new Vector3(lightSourcePos, 0) - normal * 20.0f);
|
||||
vertexDir.Normalize();
|
||||
PenumbraVertices[n + i + 1].Position = new Vector3(lightSourcePos, 0) + vertexDir * 9000 + offset;
|
||||
|
||||
if (los)
|
||||
{
|
||||
PenumbraVertices[n + i + 1].TextureCoordinate = (i == 0) ? new Vector2(0.05f, 0.0f) : new Vector2(1.0f, 0.0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
PenumbraVertices[n + i + 1].TextureCoordinate = (i == 0) ? new Vector2(1.0f, 0.0f) : Vector2.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
if (n > 0)
|
||||
{
|
||||
var temp = PenumbraVertices[4];
|
||||
PenumbraVertices[4] = PenumbraVertices[5];
|
||||
PenumbraVertices[5] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static List<ConvexHull> GetHullsInRange(Vector2 position, float range, Submarine ParentSub)
|
||||
{
|
||||
List<ConvexHull> list = new List<ConvexHull>();
|
||||
|
||||
foreach (ConvexHullList chList in HullLists)
|
||||
{
|
||||
Vector2 lightPos = position;
|
||||
if (ParentSub == null)
|
||||
{
|
||||
//light and the convexhull are both outside
|
||||
if (chList.Submarine == null)
|
||||
{
|
||||
list.AddRange(chList.List.FindAll(ch => MathUtils.CircleIntersectsRectangle(lightPos, range, ch.BoundingBox)));
|
||||
|
||||
}
|
||||
//light is outside, convexhull inside a sub
|
||||
else
|
||||
{
|
||||
Rectangle subBorders = chList.Submarine.Borders;
|
||||
subBorders.Y -= chList.Submarine.Borders.Height;
|
||||
if (!MathUtils.CircleIntersectsRectangle(lightPos - chList.Submarine.WorldPosition, range, subBorders)) continue;
|
||||
|
||||
lightPos -= (chList.Submarine.WorldPosition - chList.Submarine.HiddenSubPosition);
|
||||
|
||||
list.AddRange(chList.List.FindAll(ch => MathUtils.CircleIntersectsRectangle(lightPos, range, ch.BoundingBox)));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
//light is inside, convexhull outside
|
||||
if (chList.Submarine == null)
|
||||
{
|
||||
lightPos += (ParentSub.WorldPosition - ParentSub.HiddenSubPosition);
|
||||
HashSet<RuinGeneration.Ruin> visibleRuins = new HashSet<RuinGeneration.Ruin>();
|
||||
foreach (RuinGeneration.Ruin ruin in Level.Loaded.Ruins)
|
||||
{
|
||||
if (!MathUtils.CircleIntersectsRectangle(lightPos, range, ruin.Area)) { continue; }
|
||||
visibleRuins.Add(ruin);
|
||||
}
|
||||
list.AddRange(chList.List.FindAll(ch => ch.ParentEntity?.ParentRuin != null && visibleRuins.Contains(ch.ParentEntity.ParentRuin)));
|
||||
continue;
|
||||
}
|
||||
//light and convexhull are both inside the same sub
|
||||
if (chList.Submarine == ParentSub)
|
||||
{
|
||||
list.AddRange(chList.List.FindAll(ch => MathUtils.CircleIntersectsRectangle(lightPos, range, ch.BoundingBox)));
|
||||
}
|
||||
//light and convexhull are inside different subs
|
||||
else
|
||||
{
|
||||
lightPos -= (chList.Submarine.Position - ParentSub.Position);
|
||||
|
||||
Rectangle subBorders = chList.Submarine.Borders;
|
||||
subBorders.Location += chList.Submarine.HiddenSubPosition.ToPoint() - new Point(0, chList.Submarine.Borders.Height);
|
||||
|
||||
if (!MathUtils.CircleIntersectsRectangle(lightPos, range, subBorders)) continue;
|
||||
|
||||
list.AddRange(chList.List.FindAll(ch => MathUtils.CircleIntersectsRectangle(lightPos, range, ch.BoundingBox)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public void Remove()
|
||||
{
|
||||
var chList = HullLists.Find(x => x.Submarine == ParentEntity.Submarine);
|
||||
|
||||
if (chList != null)
|
||||
{
|
||||
chList.List.Remove(this);
|
||||
if (chList.List.Count == 0)
|
||||
{
|
||||
HullLists.Remove(chList);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using Microsoft.Xna.Framework.Content;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using Barotrauma.Items.Components;
|
||||
using Barotrauma.Extensions;
|
||||
|
||||
namespace Barotrauma.Lights
|
||||
{
|
||||
class LightManager
|
||||
{
|
||||
private const float AmbientLightUpdateInterval = 0.2f;
|
||||
private const float AmbientLightFalloff = 0.8f;
|
||||
|
||||
/// <summary>
|
||||
/// Enables a feature that makes lights inside the hull increase the brightness of the entire hull
|
||||
/// and adjacent ones to some extent, if there are gaps for the lights to pass through.
|
||||
/// Prevents unnaturally dark looking shadows in otherwise well-lit submarines, but disabled at least for
|
||||
/// the time being because it makes the lighting behave unpredictably and may cause rooms to appear
|
||||
/// excessively bright if different lighting conditions aren't tested and accounted for.
|
||||
/// </summary>
|
||||
private static readonly bool UseHullSpecificAmbientLight = false;
|
||||
|
||||
public static Entity ViewTarget { get; set; }
|
||||
|
||||
private float currLightMapScale;
|
||||
|
||||
public Color AmbientLight;
|
||||
|
||||
public RenderTarget2D LightMap
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public RenderTarget2D LimbLightMap
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public RenderTarget2D LosTexture
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
public RenderTarget2D HighlightMap
|
||||
{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
private readonly Texture2D highlightRaster;
|
||||
|
||||
private BasicEffect lightEffect;
|
||||
|
||||
public Effect LosEffect { get; private set; }
|
||||
public Effect SolidColorEffect { get; private set; }
|
||||
|
||||
private List<LightSource> lights;
|
||||
|
||||
public bool LosEnabled = true;
|
||||
public LosMode LosMode = LosMode.Transparent;
|
||||
|
||||
public bool LightingEnabled = true;
|
||||
|
||||
public bool ObstructVision;
|
||||
|
||||
private Texture2D visionCircle;
|
||||
|
||||
private Dictionary<Hull, Color> hullAmbientLights;
|
||||
private Dictionary<Hull, Color> smoothedHullAmbientLights;
|
||||
|
||||
private float ambientLightUpdateTimer;
|
||||
|
||||
public IEnumerable<LightSource> Lights
|
||||
{
|
||||
get { return lights; }
|
||||
}
|
||||
|
||||
public LightManager(GraphicsDevice graphics, ContentManager content)
|
||||
{
|
||||
lights = new List<LightSource>();
|
||||
|
||||
AmbientLight = new Color(20, 20, 20, 255);
|
||||
|
||||
visionCircle = Sprite.LoadTexture("Content/Lights/visioncircle.png");
|
||||
highlightRaster = Sprite.LoadTexture("Content/UI/HighlightRaster.png");
|
||||
|
||||
GameMain.Instance.OnResolutionChanged += () =>
|
||||
{
|
||||
CreateRenderTargets(graphics);
|
||||
};
|
||||
|
||||
CrossThread.RequestExecutionOnMainThread(() =>
|
||||
{
|
||||
CreateRenderTargets(graphics);
|
||||
|
||||
#if WINDOWS
|
||||
LosEffect = content.Load<Effect>("Effects/losshader");
|
||||
SolidColorEffect = content.Load<Effect>("Effects/solidcolor");
|
||||
#else
|
||||
LosEffect = content.Load<Effect>("Effects/losshader_opengl");
|
||||
SolidColorEffect = content.Load<Effect>("Effects/solidcolor_opengl");
|
||||
#endif
|
||||
|
||||
if (lightEffect == null)
|
||||
{
|
||||
lightEffect = new BasicEffect(GameMain.Instance.GraphicsDevice)
|
||||
{
|
||||
VertexColorEnabled = true,
|
||||
TextureEnabled = true,
|
||||
Texture = LightSource.LightTexture
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
hullAmbientLights = new Dictionary<Hull, Color>();
|
||||
smoothedHullAmbientLights = new Dictionary<Hull, Color>();
|
||||
}
|
||||
|
||||
private void CreateRenderTargets(GraphicsDevice graphics)
|
||||
{
|
||||
var pp = graphics.PresentationParameters;
|
||||
|
||||
currLightMapScale = GameMain.Config.LightMapScale;
|
||||
|
||||
LightMap?.Dispose();
|
||||
LightMap = CreateRenderTarget();
|
||||
|
||||
LimbLightMap?.Dispose();
|
||||
LimbLightMap = CreateRenderTarget();
|
||||
|
||||
HighlightMap?.Dispose();
|
||||
HighlightMap = CreateRenderTarget();
|
||||
|
||||
RenderTarget2D CreateRenderTarget()
|
||||
{
|
||||
return new RenderTarget2D(graphics,
|
||||
(int)(GameMain.GraphicsWidth * GameMain.Config.LightMapScale), (int)(GameMain.GraphicsHeight * GameMain.Config.LightMapScale), false,
|
||||
pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
|
||||
RenderTargetUsage.DiscardContents);
|
||||
}
|
||||
|
||||
LosTexture?.Dispose();
|
||||
LosTexture = new RenderTarget2D(graphics,
|
||||
(int)(GameMain.GraphicsWidth * GameMain.Config.LightMapScale),
|
||||
(int)(GameMain.GraphicsHeight * GameMain.Config.LightMapScale), false, SurfaceFormat.Color, DepthFormat.None);
|
||||
}
|
||||
|
||||
public void AddLight(LightSource light)
|
||||
{
|
||||
if (!lights.Contains(light)) lights.Add(light);
|
||||
}
|
||||
|
||||
public void RemoveLight(LightSource light)
|
||||
{
|
||||
lights.Remove(light);
|
||||
}
|
||||
|
||||
public void OnMapLoaded()
|
||||
{
|
||||
foreach (LightSource light in lights)
|
||||
{
|
||||
light.NeedsHullCheck = true;
|
||||
light.NeedsRecalculation = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Update(float deltaTime)
|
||||
{
|
||||
if (UseHullSpecificAmbientLight)
|
||||
{
|
||||
if (ambientLightUpdateTimer > 0.0f)
|
||||
{
|
||||
ambientLightUpdateTimer -= deltaTime;
|
||||
}
|
||||
else
|
||||
{
|
||||
CalculateAmbientLights();
|
||||
ambientLightUpdateTimer = AmbientLightUpdateInterval;
|
||||
}
|
||||
|
||||
foreach (Hull hull in hullAmbientLights.Keys)
|
||||
{
|
||||
if (!smoothedHullAmbientLights.ContainsKey(hull))
|
||||
{
|
||||
smoothedHullAmbientLights.Add(hull, Color.TransparentBlack);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (Hull hull in smoothedHullAmbientLights.Keys.ToList())
|
||||
{
|
||||
Color targetColor = Color.TransparentBlack;
|
||||
hullAmbientLights.TryGetValue(hull, out targetColor);
|
||||
smoothedHullAmbientLights[hull] = Color.Lerp(smoothedHullAmbientLights[hull], targetColor, deltaTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<LightSource> activeLights = new List<LightSource>(capacity: 100);
|
||||
|
||||
public void UpdateLightMap(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam, RenderTarget2D backgroundObstructor = null)
|
||||
{
|
||||
if (!LightingEnabled) return;
|
||||
|
||||
if (Math.Abs(currLightMapScale - GameMain.Config.LightMapScale) > 0.01f)
|
||||
{
|
||||
//lightmap scale has changed -> recreate render targets
|
||||
CreateRenderTargets(graphics);
|
||||
}
|
||||
|
||||
Matrix spriteBatchTransform = cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f));
|
||||
Matrix transform = cam.ShaderTransform
|
||||
* Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f;
|
||||
|
||||
bool highlightsVisible = UpdateHighlights(graphics, spriteBatch, spriteBatchTransform, cam);
|
||||
|
||||
Rectangle viewRect = cam.WorldView;
|
||||
viewRect.Y -= cam.WorldView.Height;
|
||||
//check which lights need to be drawn
|
||||
activeLights.Clear();
|
||||
foreach (LightSource light in lights)
|
||||
{
|
||||
if (!light.Enabled) { continue; }
|
||||
if ((light.Color.A < 1 || light.Range < 1.0f) && !light.LightSourceParams.OverrideLightSpriteAlpha.HasValue) { continue; }
|
||||
if (light.ParentBody != null)
|
||||
{
|
||||
light.Position = light.ParentBody.DrawPosition;
|
||||
if (light.ParentSub != null) { light.Position -= light.ParentSub.DrawPosition; }
|
||||
}
|
||||
if (!MathUtils.CircleIntersectsRectangle(light.WorldPosition, light.LightSourceParams.TextureRange, viewRect)) { continue; }
|
||||
activeLights.Add(light);
|
||||
}
|
||||
|
||||
//draw light sprites attached to characters
|
||||
//render into a separate rendertarget using alpha blending (instead of on top of everything else with alpha blending)
|
||||
//to prevent the lights from showing through other characters or other light sprites attached to the same character
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
graphics.SetRenderTarget(LimbLightMap);
|
||||
graphics.Clear(Color.Black);
|
||||
graphics.BlendState = BlendState.NonPremultiplied;
|
||||
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
|
||||
foreach (LightSource light in activeLights)
|
||||
{
|
||||
if (light.IsBackground) { continue; }
|
||||
//draw limb lights at this point, because they were skipped over previously to prevent them from being obstructed
|
||||
if (light.ParentBody?.UserData is Limb) { light.DrawSprite(spriteBatch, cam); }
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
//draw background lights
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
graphics.SetRenderTarget(LightMap);
|
||||
graphics.Clear(Color.Black);
|
||||
graphics.BlendState = BlendState.Additive;
|
||||
bool backgroundSpritesDrawn = false;
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
|
||||
foreach (LightSource light in activeLights)
|
||||
{
|
||||
if (!light.IsBackground) { continue; }
|
||||
light.DrawSprite(spriteBatch, cam);
|
||||
if (light.Color.A > 0 && light.Range > 0.0f) { light.DrawLightVolume(spriteBatch, lightEffect, transform); }
|
||||
backgroundSpritesDrawn = true;
|
||||
}
|
||||
GameMain.ParticleManager.Draw(spriteBatch, true, null, Particles.ParticleBlendState.Additive);
|
||||
spriteBatch.End();
|
||||
|
||||
//draw a black rectangle on hulls to hide background lights behind subs
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
|
||||
Dictionary<Hull, Rectangle> visibleHulls = null;
|
||||
if (backgroundSpritesDrawn)
|
||||
{
|
||||
if (backgroundObstructor != null)
|
||||
{
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
|
||||
spriteBatch.Draw(backgroundObstructor, new Rectangle(0, 0,
|
||||
(int)(GameMain.GraphicsWidth * currLightMapScale), (int)(GameMain.GraphicsHeight * currLightMapScale)), Color.Black);
|
||||
spriteBatch.End();
|
||||
}
|
||||
|
||||
visibleHulls = GetVisibleHulls(cam);
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, transformMatrix: spriteBatchTransform);
|
||||
foreach (Rectangle drawRect in visibleHulls.Values)
|
||||
{
|
||||
//TODO: draw some sort of smoothed rectangle
|
||||
GUI.DrawRectangle(spriteBatch,
|
||||
new Vector2(drawRect.X, -drawRect.Y),
|
||||
new Vector2(drawRect.Width, drawRect.Height),
|
||||
Color.Black, true);
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
|
||||
graphics.BlendState = BlendState.Additive;
|
||||
}
|
||||
|
||||
//draw the focused item and character to highlight them,
|
||||
//and light sprites (done before drawing the actual light volumes so we can make characters obstruct the highlights and sprites)
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
|
||||
foreach (LightSource light in activeLights)
|
||||
{
|
||||
//don't draw limb lights at this point, they need to be drawn after lights have been obstructed by characters
|
||||
if (light.IsBackground || light.ParentBody?.UserData is Limb) { continue; }
|
||||
light.DrawSprite(spriteBatch, cam);
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
if (highlightsVisible)
|
||||
{
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
|
||||
spriteBatch.Draw(HighlightMap, Vector2.Zero, Color.White);
|
||||
spriteBatch.End();
|
||||
}
|
||||
|
||||
//draw characters to obstruct the highlighted items/characters and light sprites
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
|
||||
SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidColor"];
|
||||
SolidColorEffect.Parameters["color"].SetValue(Color.Black.ToVector4());
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, effect: SolidColorEffect, transformMatrix: spriteBatchTransform);
|
||||
foreach (Character character in Character.CharacterList)
|
||||
{
|
||||
if (character.CurrentHull == null || !character.Enabled) continue;
|
||||
if (Character.Controlled?.FocusedCharacter == character) continue;
|
||||
foreach (Limb limb in character.AnimController.Limbs)
|
||||
{
|
||||
if (limb.DeformSprite != null) continue;
|
||||
limb.Draw(spriteBatch, cam, Color.Black);
|
||||
}
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShaderSolidColor"];
|
||||
DeformableSprite.Effect.Parameters["solidColor"].SetValue(Color.Black.ToVector4());
|
||||
DeformableSprite.Effect.CurrentTechnique.Passes[0].Apply();
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
|
||||
foreach (Character character in Character.CharacterList)
|
||||
{
|
||||
if (character.CurrentHull == null || !character.Enabled) continue;
|
||||
if (Character.Controlled?.FocusedCharacter == character) continue;
|
||||
foreach (Limb limb in character.AnimController.Limbs)
|
||||
{
|
||||
if (limb.DeformSprite == null) continue;
|
||||
limb.Draw(spriteBatch, cam, Color.Black);
|
||||
}
|
||||
}
|
||||
spriteBatch.End();
|
||||
DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShader"];
|
||||
graphics.BlendState = BlendState.Additive;
|
||||
|
||||
//draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
|
||||
|
||||
GUI.DrawRectangle(spriteBatch, new Rectangle(cam.WorldView.X, -cam.WorldView.Y, cam.WorldView.Width, cam.WorldView.Height), AmbientLight, isFilled: true);
|
||||
|
||||
spriteBatch.Draw(LimbLightMap, new Rectangle(cam.WorldView.X, -cam.WorldView.Y, cam.WorldView.Width, cam.WorldView.Height), Color.White);
|
||||
|
||||
foreach (ElectricalDischarger discharger in ElectricalDischarger.List)
|
||||
{
|
||||
discharger.DrawElectricity(spriteBatch);
|
||||
}
|
||||
|
||||
foreach (LightSource light in activeLights)
|
||||
{
|
||||
if (light.IsBackground) { continue; }
|
||||
if (light.Color.A > 0 && light.Range > 0.0f) { light.DrawLightVolume(spriteBatch, lightEffect, transform); }
|
||||
}
|
||||
|
||||
lightEffect.World = transform;
|
||||
|
||||
GameMain.ParticleManager.Draw(spriteBatch, false, null, Particles.ParticleBlendState.Additive);
|
||||
|
||||
if (UseHullSpecificAmbientLight)
|
||||
{
|
||||
if (visibleHulls == null)
|
||||
{
|
||||
visibleHulls = GetVisibleHulls(cam);
|
||||
}
|
||||
foreach (Hull hull in smoothedHullAmbientLights.Keys)
|
||||
{
|
||||
if (smoothedHullAmbientLights[hull].A < 0.01f) continue;
|
||||
if (!visibleHulls.TryGetValue(hull, out Rectangle drawRect)) continue;
|
||||
GUI.DrawRectangle(spriteBatch,
|
||||
new Vector2(drawRect.X, -drawRect.Y),
|
||||
new Vector2(hull.Rect.Width, hull.Rect.Height),
|
||||
smoothedHullAmbientLights[hull], true);
|
||||
}
|
||||
}
|
||||
|
||||
if (Character.Controlled != null)
|
||||
{
|
||||
Vector2 haloDrawPos = Character.Controlled.DrawPosition;
|
||||
haloDrawPos.Y = -haloDrawPos.Y;
|
||||
|
||||
//ambient light decreases the brightness of the halo (no need for a bright halo if the ambient light is bright enough)
|
||||
float ambientBrightness = (AmbientLight.R + AmbientLight.B + AmbientLight.G) / 255.0f / 3.0f;
|
||||
Color haloColor = Color.White.Multiply(0.3f - ambientBrightness);
|
||||
if (haloColor.A > 0)
|
||||
{
|
||||
float scale = 512.0f / LightSource.LightTexture.Width;
|
||||
spriteBatch.Draw(
|
||||
LightSource.LightTexture, haloDrawPos, null, haloColor, 0.0f,
|
||||
new Vector2(LightSource.LightTexture.Width, LightSource.LightTexture.Height) / 2, scale, SpriteEffects.None, 0.0f);
|
||||
}
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
//draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
|
||||
//---------------------------------------------------------------------------------------------------
|
||||
|
||||
graphics.SetRenderTarget(null);
|
||||
graphics.BlendState = BlendState.NonPremultiplied;
|
||||
}
|
||||
|
||||
private readonly List<Entity> highlightedEntities = new List<Entity>();
|
||||
|
||||
private bool UpdateHighlights(GraphicsDevice graphics, SpriteBatch spriteBatch, Matrix spriteBatchTransform, Camera cam)
|
||||
{
|
||||
if (GUI.DisableItemHighlights) { return false; }
|
||||
|
||||
highlightedEntities.Clear();
|
||||
if (Character.Controlled != null)
|
||||
{
|
||||
if (Character.Controlled.FocusedItem != null)
|
||||
{
|
||||
highlightedEntities.Add(Character.Controlled.FocusedItem);
|
||||
}
|
||||
if (Character.Controlled.FocusedCharacter != null)
|
||||
{
|
||||
highlightedEntities.Add(Character.Controlled.FocusedCharacter);
|
||||
}
|
||||
foreach (Item item in Item.ItemList)
|
||||
{
|
||||
if (item.IsHighlighted && !highlightedEntities.Contains(item))
|
||||
{
|
||||
highlightedEntities.Add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (highlightedEntities.Count == 0) { return false; }
|
||||
|
||||
//draw characters in light blue first
|
||||
graphics.SetRenderTarget(HighlightMap);
|
||||
SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidColor"];
|
||||
SolidColorEffect.Parameters["color"].SetValue(Color.LightBlue.ToVector4());
|
||||
SolidColorEffect.CurrentTechnique.Passes[0].Apply();
|
||||
DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShaderSolidColor"];
|
||||
DeformableSprite.Effect.Parameters["solidColor"].SetValue(Color.LightBlue.ToVector4());
|
||||
DeformableSprite.Effect.CurrentTechnique.Passes[0].Apply();
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, samplerState: SamplerState.LinearWrap, effect: SolidColorEffect, transformMatrix: spriteBatchTransform);
|
||||
foreach (Entity highlighted in highlightedEntities)
|
||||
{
|
||||
if (highlighted is Item item)
|
||||
{
|
||||
item.Draw(spriteBatch, false, true);
|
||||
}
|
||||
else if (highlighted is Character character)
|
||||
{
|
||||
character.Draw(spriteBatch, cam);
|
||||
}
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
//draw characters in black with a bit of blur, leaving the white edges visible
|
||||
float phase = (float)(Math.Sin(Timing.TotalTime * 3.0f) + 1.0f) / 2.0f; //phase oscillates between 0 and 1
|
||||
Vector4 overlayColor = Color.Black.ToVector4() * MathHelper.Lerp(0.5f, 0.9f, phase);
|
||||
SolidColorEffect.Parameters["color"].SetValue(overlayColor);
|
||||
SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidColorBlur"];
|
||||
SolidColorEffect.CurrentTechnique.Passes[0].Apply();
|
||||
DeformableSprite.Effect.Parameters["solidColor"].SetValue(overlayColor);
|
||||
DeformableSprite.Effect.CurrentTechnique.Passes[0].Apply();
|
||||
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, samplerState: SamplerState.LinearWrap, effect: SolidColorEffect, transformMatrix: spriteBatchTransform);
|
||||
foreach (Entity highlighted in highlightedEntities)
|
||||
{
|
||||
if (highlighted is Item item)
|
||||
{
|
||||
SolidColorEffect.Parameters["blurDistance"].SetValue(0.02f);
|
||||
item.Draw(spriteBatch, false, true);
|
||||
}
|
||||
else if (highlighted is Character character)
|
||||
{
|
||||
SolidColorEffect.Parameters["blurDistance"].SetValue(0.05f);
|
||||
character.Draw(spriteBatch, cam);
|
||||
}
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
//raster pattern on top of everything
|
||||
spriteBatch.Begin(blendState: BlendState.NonPremultiplied, samplerState: SamplerState.LinearWrap);
|
||||
spriteBatch.Draw(highlightRaster,
|
||||
new Rectangle(0, 0, HighlightMap.Width, HighlightMap.Height),
|
||||
new Rectangle(0, 0, (int)(HighlightMap.Width / currLightMapScale * 0.5f), (int)(HighlightMap.Height / currLightMapScale * 0.5f)),
|
||||
Color.White * 0.5f);
|
||||
spriteBatch.End();
|
||||
|
||||
DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShader"];
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private Dictionary<Hull, Rectangle> GetVisibleHulls(Camera cam)
|
||||
{
|
||||
Dictionary<Hull, Rectangle> visibleHulls = new Dictionary<Hull, Rectangle>();
|
||||
foreach (Hull hull in Hull.hullList)
|
||||
{
|
||||
var drawRect =
|
||||
hull.Submarine == null ?
|
||||
hull.Rect :
|
||||
new Rectangle((int)(hull.Submarine.DrawPosition.X + hull.Rect.X), (int)(hull.Submarine.DrawPosition.Y + hull.Rect.Y), hull.Rect.Width, hull.Rect.Height);
|
||||
|
||||
if (drawRect.Right < cam.WorldView.X || drawRect.X > cam.WorldView.Right ||
|
||||
drawRect.Y - drawRect.Height > cam.WorldView.Y || drawRect.Y < cam.WorldView.Y - cam.WorldView.Height)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
visibleHulls.Add(hull, drawRect);
|
||||
}
|
||||
return visibleHulls;
|
||||
}
|
||||
|
||||
public void UpdateObstructVision(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam, Vector2 lookAtPosition)
|
||||
{
|
||||
if ((!LosEnabled || LosMode == LosMode.None) && !ObstructVision) return;
|
||||
if (ViewTarget == null) return;
|
||||
|
||||
graphics.SetRenderTarget(LosTexture);
|
||||
|
||||
spriteBatch.Begin(SpriteSortMode.Deferred, transformMatrix: cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f)));
|
||||
if (ObstructVision)
|
||||
{
|
||||
graphics.Clear(Color.Black);
|
||||
Vector2 diff = lookAtPosition - ViewTarget.WorldPosition;
|
||||
diff.Y = -diff.Y;
|
||||
float rotation = MathUtils.VectorToAngle(diff);
|
||||
|
||||
Vector2 scale = new Vector2(
|
||||
MathHelper.Clamp(diff.Length() / 256.0f, 2.0f, 5.0f), 2.0f);
|
||||
|
||||
spriteBatch.Draw(visionCircle, new Vector2(ViewTarget.WorldPosition.X, -ViewTarget.WorldPosition.Y), null, Color.White, rotation,
|
||||
new Vector2(visionCircle.Width * 0.2f, visionCircle.Height / 2), scale, SpriteEffects.None, 0.0f);
|
||||
}
|
||||
else
|
||||
{
|
||||
graphics.Clear(Color.White);
|
||||
}
|
||||
spriteBatch.End();
|
||||
|
||||
|
||||
//--------------------------------------
|
||||
|
||||
if (LosEnabled && LosMode != LosMode.None && ViewTarget != null)
|
||||
{
|
||||
Vector2 pos = ViewTarget.DrawPosition;
|
||||
|
||||
Rectangle camView = new Rectangle(cam.WorldView.X, cam.WorldView.Y - cam.WorldView.Height, cam.WorldView.Width, cam.WorldView.Height);
|
||||
|
||||
Matrix shadowTransform = cam.ShaderTransform
|
||||
* Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f;
|
||||
|
||||
var convexHulls = ConvexHull.GetHullsInRange(ViewTarget.Position, cam.WorldView.Width*0.75f, ViewTarget.Submarine);
|
||||
if (convexHulls != null)
|
||||
{
|
||||
List<VertexPositionColor> shadowVerts = new List<VertexPositionColor>();
|
||||
List<VertexPositionTexture> penumbraVerts = new List<VertexPositionTexture>();
|
||||
foreach (ConvexHull convexHull in convexHulls)
|
||||
{
|
||||
if (!convexHull.Enabled || !convexHull.Intersects(camView)) continue;
|
||||
|
||||
Vector2 relativeLightPos = pos;
|
||||
if (convexHull.ParentEntity?.Submarine != null) relativeLightPos -= convexHull.ParentEntity.Submarine.Position;
|
||||
|
||||
convexHull.CalculateShadowVertices(relativeLightPos, true);
|
||||
|
||||
//convert triangle strips to a triangle list
|
||||
for (int i = 0; i < convexHull.ShadowVertexCount * 2 - 2; i++)
|
||||
{
|
||||
if (i % 2 == 0)
|
||||
{
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i]);
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i + 1]);
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i + 2]);
|
||||
}
|
||||
else
|
||||
{
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i]);
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i + 2]);
|
||||
shadowVerts.Add(convexHull.ShadowVertices[i + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
penumbraVerts.AddRange(convexHull.PenumbraVertices);
|
||||
}
|
||||
|
||||
if (shadowVerts.Count > 0)
|
||||
{
|
||||
ConvexHull.shadowEffect.World = shadowTransform;
|
||||
ConvexHull.shadowEffect.CurrentTechnique.Passes[0].Apply();
|
||||
graphics.DrawUserPrimitives(PrimitiveType.TriangleList, shadowVerts.ToArray(), 0, shadowVerts.Count / 3, VertexPositionColor.VertexDeclaration);
|
||||
|
||||
if (penumbraVerts.Count > 0)
|
||||
{
|
||||
ConvexHull.penumbraEffect.World = shadowTransform;
|
||||
ConvexHull.penumbraEffect.CurrentTechnique.Passes[0].Apply();
|
||||
graphics.DrawUserPrimitives(PrimitiveType.TriangleList, penumbraVerts.ToArray(), 0, penumbraVerts.Count / 3, VertexPositionTexture.VertexDeclaration);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
graphics.SetRenderTarget(null);
|
||||
}
|
||||
|
||||
|
||||
private void CalculateAmbientLights()
|
||||
{
|
||||
hullAmbientLights.Clear();
|
||||
|
||||
foreach (LightSource light in lights)
|
||||
{
|
||||
if (light.Color.A < 1f || light.Range < 1.0f || light.IsBackground) continue;
|
||||
|
||||
var newAmbientLights = AmbientLightHulls(light);
|
||||
foreach (Hull hull in newAmbientLights.Keys)
|
||||
{
|
||||
if (hullAmbientLights.ContainsKey(hull))
|
||||
{
|
||||
//hull already lit by some other light source -> add the ambient lights up
|
||||
hullAmbientLights[hull] = new Color(
|
||||
hullAmbientLights[hull].R + newAmbientLights[hull].R,
|
||||
hullAmbientLights[hull].G + newAmbientLights[hull].G,
|
||||
hullAmbientLights[hull].B + newAmbientLights[hull].B,
|
||||
hullAmbientLights[hull].A + newAmbientLights[hull].A);
|
||||
}
|
||||
else
|
||||
{
|
||||
hullAmbientLights.Add(hull, newAmbientLights[hull]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Add ambient light to the hull the lightsource is inside + all adjacent hulls connected by a gap
|
||||
/// </summary>
|
||||
private Dictionary<Hull, Color> AmbientLightHulls(LightSource light)
|
||||
{
|
||||
Dictionary<Hull, Color> hullAmbientLight = new Dictionary<Hull, Color>();
|
||||
|
||||
var hull = Hull.FindHull(light.WorldPosition);
|
||||
if (hull == null) return hullAmbientLight;
|
||||
|
||||
return AmbientLightHulls(hull, hullAmbientLight, light.Color * Math.Min(light.Range / 1000.0f, 1.0f));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A flood fill algorithm that adds ambient light to all hulls the starting hull is connected to
|
||||
/// </summary>
|
||||
private Dictionary<Hull, Color> AmbientLightHulls(Hull hull, Dictionary<Hull, Color> hullAmbientLight, Color currColor)
|
||||
{
|
||||
if (hullAmbientLight.ContainsKey(hull))
|
||||
{
|
||||
if (hullAmbientLight[hull].A > currColor.A)
|
||||
return hullAmbientLight;
|
||||
else
|
||||
hullAmbientLight[hull] = currColor;
|
||||
}
|
||||
else
|
||||
{
|
||||
hullAmbientLight.Add(hull, currColor);
|
||||
}
|
||||
|
||||
Color nextHullLight = currColor * AmbientLightFalloff;
|
||||
//light getting too dark to notice -> no need to spread further
|
||||
if (nextHullLight.A < 20) return hullAmbientLight;
|
||||
|
||||
//use hashset to make sure that each hull is only included once
|
||||
HashSet<Hull> hulls = new HashSet<Hull>();
|
||||
foreach (Gap g in hull.ConnectedGaps)
|
||||
{
|
||||
if (!g.IsRoomToRoom || !g.PassAmbientLight || g.Open < 0.5f) continue;
|
||||
|
||||
hulls.Add((g.linkedTo[0] == hull ? g.linkedTo[1] : g.linkedTo[0]) as Hull);
|
||||
}
|
||||
|
||||
foreach (Hull h in hulls)
|
||||
{
|
||||
hullAmbientLight = AmbientLightHulls(h, hullAmbientLight, nextHullLight);
|
||||
}
|
||||
|
||||
return hullAmbientLight;
|
||||
}
|
||||
|
||||
public void ClearLights()
|
||||
{
|
||||
lights.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CustomBlendStates
|
||||
{
|
||||
static CustomBlendStates()
|
||||
{
|
||||
Multiplicative = new BlendState
|
||||
{
|
||||
ColorSourceBlend = Blend.DestinationColor,
|
||||
ColorDestinationBlend = Blend.SourceColor,
|
||||
ColorBlendFunction = BlendFunction.Add
|
||||
};
|
||||
}
|
||||
public static BlendState Multiplicative { get; private set; }
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user