Here are the examples of the csharp api System.Math.Abs(decimal) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4277 Examples
19
Source : MetroColorPicker.xaml.cs
with MIT License
from 1217950746
with MIT License
from 1217950746
private void ViewChange()
{
ApplyColor(new HsbaColor(360.0 * thumbH.YPercent, thumbSB.XPercent, Math.Abs(1 - thumbSB.YPercent), Math.Abs(1 - thumbA.YPercent)));
}
19
Source : MetroColorPicker.xaml.cs
with MIT License
from 1217950746
with MIT License
from 1217950746
private void ApplyColor(HsbaColor hsba)
{
currentColor = hsba;
currentRgbaColor = currentColor.RgbaColor;
if (!rgbaR.IsSelectionActive) { rgbaR.Text = currentRgbaColor.R.ToString(); }
if (!rgbaG.IsSelectionActive) { rgbaG.Text = currentRgbaColor.G.ToString(); }
if (!rgbaB.IsSelectionActive) { rgbaB.Text = currentRgbaColor.B.ToString(); }
if (!rgbaA.IsSelectionActive) { rgbaA.Text = currentRgbaColor.A.ToString(); }
if (!hsbaH.IsSelectionActive) { hsbaH.Text = ((int)(currentColor.H / 3.6)).ToString(); }
if (!hsbaS.IsSelectionActive) { hsbaS.Text = ((int)(currentColor.S * 100)).ToString(); }
if (!hsbaB.IsSelectionActive) { hsbaB.Text = ((int)(currentColor.B * 100)).ToString(); }
if (!hsbaA.IsSelectionActive) { hsbaA.Text = ((int)(currentColor.A * 100)).ToString(); }
if (!hex.IsSelectionActive) { if (canTransparent) { hex.Text = currentColor.HexString; } else { hex.Text = string.Format("#{0:X2}{1:X2}{2:X2}", currentRgbaColor.R, currentRgbaColor.G, currentRgbaColor.B); } }
if (!thumbH.IsDragging) { thumbH.YPercent = currentColor.H / 360.0; }
if (!thumbSB.IsDragging) { thumbSB.XPercent = currentColor.S; thumbSB.YPercent = 1 - currentColor.B; }
if (!thumbA.IsDragging) { thumbA.YPercent = Math.Abs(1 - currentColor.A); }
selectColor.H = currentColor.H;
selectColor.A = currentColor.A;
viewSelectColor.Fill = selectColor.OpaqueSolidColorBrush;
if (canTransparent)
{
viewSelectColor.Opacity = viewSelectColor1.Opacity = viewSelectColor2.Opacity = 1 - thumbA.YPercent;
}
viewAlpha.Color = selectColor.OpaqueColor;
if (canTransparent)
{
Background = currentColor.SolidColorBrush;
}
else
{
Background = currentColor.OpaqueSolidColorBrush;
}
ColorChange?.Invoke(this, null);
}
19
Source : Math.cs
with MIT License
from 1CM69
with MIT License
from 1CM69
public static double AbsComplex(Complex z)
{
double num1 = System.Math.Abs(z.x);
double num2 = System.Math.Abs(z.y);
double num3 = num1 > num2 ? num1 : num2;
double num4 = num1 < num2 ? num1 : num2;
if (num4 == 0.0)
return num3;
double num5 = num4 / num3;
return num3 * System.Math.Sqrt(1.0 + num5 * num5);
}
19
Source : NumberFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private decimal TakeAValueInBetweenOrARandomBound(decimal minValue, decimal maxValue)
{
decimal result;
var maxIncrement = Math.Abs(maxValue - minValue);
var increment = (maxIncrement / _fuzzer.GenerateInteger(2, 15));
if (increment != 0)
{
if (_fuzzer.HeadsOrTails())
{
result = minValue + increment;
}
else
{
increment = (increment / _fuzzer.GenerateInteger(2, 15));
if (increment != 0)
{
result = minValue + increment;
}
else
{
result = _fuzzer.HeadsOrTails() ? minValue : maxValue;
}
}
}
else
{
result = _fuzzer.HeadsOrTails() ? minValue : maxValue;
}
return result;
}
19
Source : NotchSimulator.cs
with MIT License
from 5argon
with MIT License
from 5argon
void OnGUI()
{
win = this;
//Sometimes even with flag I can see it in hierarchy until I move a mouse over it??
EditorApplication.RepaintHierarchyWindow();
EditorGUI.BeginChangeCheck();
var settings = Settings.Instance;
string switchConfigShortcut = ShortcutManager.instance.GetShortcutBinding(NotchSolutionShortcuts.switchConfigurationShortcut).ToString();
if (string.IsNullOrEmpty(switchConfigShortcut)) switchConfigShortcut = "None";
string simulateShortcut = ShortcutManager.instance.GetShortcutBinding(NotchSolutionShortcuts.toggleSimulationShortcut).ToString();
if (string.IsNullOrEmpty(simulateShortcut)) simulateShortcut = "None";
settings.EnableSimulation = EditorGUILayout.BeginToggleGroup($"Simulate ({simulateShortcut})", settings.EnableSimulation);
int previousIndex = settings.ActiveConfiguration.DeviceIndex;
int currentIndex = Mathf.Clamp(settings.ActiveConfiguration.DeviceIndex, 0, SimulationDatabase.KeyList.Length - 1);
int selectedIndex = EditorGUILayout.Popup(currentIndex, SimulationDatabase.KeyList);
if (GUILayout.Button($"{settings.ActiveConfiguration.ConfigurationName} ({switchConfigShortcut})", EditorStyles.helpBox))
{
NotchSolutionShortcuts.SwitchConfiguration();
}
EditorGUILayout.EndToggleGroup();
settings.ActiveConfiguration.DeviceIndex = selectedIndex;
var simulationDevice = SimulationDatabase.Get(SimulationDatabase.KeyList[selectedIndex]);
//Draw warning about wrong aspect ratio
if (settings.EnableSimulation && simulationDevice != null)
{
ScreenOrientation gameViewOrientation = NotchSimulatorUtility.GetGameViewOrientation();
Vector2 gameViewSize = NotchSimulatorUtility.GetMainGameViewSize();
if (gameViewOrientation == ScreenOrientation.Landscape)
{
var flip = gameViewSize.x;
gameViewSize.x = gameViewSize.y;
gameViewSize.y = flip;
}
var screen = simulationDevice.Screens.FirstOrDefault();
var simAspect = NotchSolutionUtilityEditor.ScreenRatio(new Vector2(screen.width, screen.height));
var gameViewAspect = NotchSolutionUtilityEditor.ScreenRatio(gameViewSize);
var aspectDiff = Math.Abs((simAspect.x / simAspect.y) - (gameViewAspect.x / gameViewAspect.y));
if (aspectDiff > 0.01f)
{
EditorGUILayout.HelpBox($"The selected simulation device has an aspect ratio of {simAspect.y}:{simAspect.x} ({screen.height}x{screen.width}) but your game view is currently in aspect {gameViewAspect.y}:{gameViewAspect.x} ({gameViewSize.y}x{gameViewSize.x}). The overlay mockup won't be displayed correctly.", MessageType.Warning);
}
}
bool changed = EditorGUI.EndChangeCheck();
if (changed)
{
UpdateAllMockups();
settings.Save();
}
UpdateSimulatorTargets();
}
19
Source : LunarYear.cs
with MIT License
from 6tail
with MIT License
from 6tail
public int getLeapMonth()
{
foreach (LunarMonth m in months)
{
if (m.getYear() == year && m.isLeap())
{
return Math.Abs(m.getMonth());
}
}
return 0;
}
19
Source : Geometry.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
public static List<Polyline> Boolean(ClipType clipType, IEnumerable<Polyline> polyA, IEnumerable<Polyline> polyB,
Plane pln, double tolerance, bool evenOddFilling, double disregardPolygonsWithArea = 0.01) {
foreach (var pline0 in polyA) {
foreach (var pline1 in polyB) {
if (pline1.GetPlane().ClosestPoint(pline0[0]).DistanceToSquared(pline0[0]) > 0.001) {
return new List<Polyline>();
}
}
}
Clipper642.Clipper clipper = new Clipper642.Clipper();
PolyFillType polyfilltype = PolyFillType.pftEvenOdd;
if (!evenOddFilling) {
polyfilltype = PolyFillType.pftNonZero;
}
double area0 = 0;
int count = 0;
foreach (Polyline plA in polyA) {
var p0 = plA.ToPath2D(pln, tolerance);
clipper.AddPath(p0, PolyType.ptSubject, plA.IsClosed);
if (count == 0) {
area0 = Math.Abs(Clipper642.Clipper.Area(p0) * tolerance * tolerance);
count++;
}
}
double area1 = 0;
foreach (Polyline plB in polyB) {
var p0 = plB.ToPath2D(pln, tolerance);
clipper.AddPath(plB.ToPath2D(pln, tolerance), PolyType.ptClip, true);
if (count == 1) {
area1 = Math.Abs(Clipper642.Clipper.Area(p0) * tolerance * tolerance);
count++;
}
}
PolyTree polytree = new PolyTree();
clipper.Execute(clipType, polytree, polyfilltype, polyfilltype);
if (polytree.Total == 0)
return new List<Polyline>();
List<Polyline> output = new List<Polyline>();
// ReSharper disable once LoopCanBeConvertedToQuery
double AreaMin = Math.Min(area0, area1);
foreach (PolyNode pn in polytree.Iterate()) {
if (pn.Contour.Count > 1) {
if (disregardPolygonsWithArea > 0)
{
double area = Math.Abs(Clipper642.Clipper.Area(pn.Contour)*tolerance* tolerance);
//Rhino.RhinoApp.WriteLine(area.ToString());
if (area > AreaMin*disregardPolygonsWithArea)
{
output.Add(pn.Contour.ToPolyline(pln, tolerance, !pn.IsOpen));
}
}
}
}
return output;
}
19
Source : NpcCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public async Task<Unit> Handle(ChatWithNpcCommand command, CancellationToken cancellationToken)
{
var playerId = command.PlayerId;
var player = await _playerDomainService.Get(playerId);
if (player == null)
{
return Unit.Value;
}
var npcId = command.NpcId;
var npc = await _npcDomainService.Get(npcId);
if (npc == null)
{
return Unit.Value;
}
if (npc.Type != NpcTypeEnum.人物)
{
await _bus.RaiseEvent(new DomainNotification($"指令 错误!"));
return Unit.Value;
}
await _mudProvider.ShowMessage(player.Id, $"与 [{npc.Name}] 闲聊中...");
var chatWithNpcLike = await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpcLike, playerId, npcId));
if (chatWithNpcLike > 0)
{
return Unit.Value;
}
Random random = new Random();
int kar = Math.Abs(npc.Kar - player.Kar);
if (random.Next(1, 100) > kar)
{
var npcLiking = await _npcLikingDomainService.Get(x => x.PlayerId == player.Id && x.NpcId == npcId);
if (npcLiking == null)
{
npcLiking = new NpcLikingEnreplacedy
{
CreatedTime = DateTime.Now,
NpcId = npcId,
Liking = 1,
PlayerId = player.Id
};
await _npcLikingDomainService.Add(npcLiking);
}
else
{
if (npcLiking.Liking < 20)
{
npcLiking.Liking++;
await _npcLikingDomainService.Update(npcLiking);
}
}
await _mudProvider.ShowMessage(player.Id, $"交谈甚欢,与[{npc.Name}]的好感度上升");
}
await _bus.RaiseEvent(new ChatWithNpcEvent(playerId, npc.Id)).ConfigureAwait(false);
return Unit.Value;
}
19
Source : TextEditor.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction)
{
TextView textView = textArea.TextView;
TextDoreplacedent doreplacedent = textView.Doreplacedent;
if (scrollViewer != null && doreplacedent != null) {
if (line < 1)
line = 1;
if (line > doreplacedent.LineCount)
line = doreplacedent.LineCount;
IScrollInfo scrollInfo = textView;
if (!scrollInfo.CanHorizontallyScroll) {
// Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll
// to the correct position.
// This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines.
VisualLine vl = textView.GetOrConstructVisualLine(doreplacedent.GetLineByNumber(line));
double remainingHeight = referencedVerticalViewPortOffset;
while (remainingHeight > 0) {
DoreplacedentLine prevLine = vl.FirstDoreplacedentLine.PreviousLine;
if (prevLine == null)
break;
vl = textView.GetOrConstructVisualLine(prevLine);
remainingHeight -= vl.Height;
}
}
Point p = textArea.TextView.GetVisualPosition(new TextViewPosition(line, Math.Max(1, column)), yPositionMode);
double verticalPos = p.Y - referencedVerticalViewPortOffset;
if (Math.Abs(verticalPos - scrollViewer.VerticalOffset) > minimumScrollFraction * scrollViewer.ViewportHeight) {
scrollViewer.ScrollToVerticalOffset(Math.Max(0, verticalPos));
}
if (column > 0) {
if (p.X > scrollViewer.ViewportWidth - Caret.MinimumDistanceToViewBorder * 2) {
double horizontalPos = Math.Max(0, p.X - scrollViewer.ViewportWidth / 2);
if (Math.Abs(horizontalPos - scrollViewer.HorizontalOffset) > minimumScrollFraction * scrollViewer.ViewportWidth) {
scrollViewer.ScrollToHorizontalOffset(horizontalPos);
}
} else {
scrollViewer.ScrollToHorizontalOffset(0);
}
}
}
}
19
Source : MouseHoverLogic.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
void MouseHoverLogicMouseMove(object sender, MouseEventArgs e)
{
Vector mouseMovement = mouseHoverStartPoint - e.GetPosition(this.target);
if (Math.Abs(mouseMovement.X) > SystemParameters.MouseHoverWidth
|| Math.Abs(mouseMovement.Y) > SystemParameters.MouseHoverHeight) {
StartHovering(e);
}
// do not set e.Handled - allow others to also handle MouseMove
}
19
Source : SelectionMouseHandler.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
void textArea_MouseMove(object sender, MouseEventArgs e)
{
if (e.Handled)
return;
if (mode == MouseSelectionMode.Normal || mode == MouseSelectionMode.WholeWord || mode == MouseSelectionMode.WholeLine || mode == MouseSelectionMode.Rectangular) {
e.Handled = true;
if (textArea.TextView.VisualLinesValid) {
// If the visual lines are not valid, don't extend the selection.
// Extending the selection forces a VisualLine refresh, and it is sufficient
// to do that on MouseUp, we don't have to do it every MouseMove.
ExtendSelectionToMouse(e);
}
} else if (mode == MouseSelectionMode.PossibleDragStart) {
e.Handled = true;
Vector mouseMovement = e.GetPosition(textArea) - possibleDragStartMousePos;
if (Math.Abs(mouseMovement.X) > SystemParameters.MinimumHorizontalDragDistance
|| Math.Abs(mouseMovement.Y) > SystemParameters.MinimumVerticalDragDistance) {
StartDrag();
}
}
}
19
Source : BaseCursor.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public virtual CursorContextEnum CheckCursorContext()
{
if (CursorContext != CursorContextEnum.Contextual)
{
var cursorAction = CursorContextInfo.CursorAction.None;
Transform contextCenter = null;
if (TargetedObject)
{
var contextInfo = TargetedObject.GetComponent<CursorContextInfo>();
if (contextInfo != null)
{
cursorAction = contextInfo.CurrentCursorAction;
contextCenter = contextInfo.ObjectCenter;
}
}
Vector3 right = Vector3.zero;
Vector3 up = Vector3.zero;
Vector3 forward = Vector3.zero;
if (!GetCursorTargetAxes(focusDetails.Normal, ref right, ref up, ref forward))
{
return CursorContextEnum.None;
}
if (cursorAction == CursorContextInfo.CursorAction.Move)
{
return CursorContextEnum.MoveCross;
}
else if (cursorAction == CursorContextInfo.CursorAction.Scale)
{
if (contextCenter != null)
{
Vector3 adjustedCursorPos = Position - contextCenter.position;
if (Vector3.Dot(adjustedCursorPos, up) * Vector3.Dot(adjustedCursorPos, right) > 0) // quadrant 1 and 3
{
return CursorContextEnum.MoveNorthwestSoutheast;
}
else // quadrant 2 and 4
{
return CursorContextEnum.MoveNortheastSouthwest;
}
}
}
else if (cursorAction == CursorContextInfo.CursorAction.Rotate)
{
if (contextCenter != null)
{
Vector3 adjustedCursorPos = Position - contextCenter.position;
if (Math.Abs(Vector3.Dot(adjustedCursorPos, right)) >
Math.Abs(Vector3.Dot(adjustedCursorPos, up)))
{
return CursorContextEnum.RotateEastWest;
}
else
{
return CursorContextEnum.RotateNorthSouth;
}
}
}
return CursorContextEnum.None;
}
return CursorContextEnum.Contextual;
}
19
Source : NearInteractionTouchableInspector.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var t = (NearInteractionTouchable)target;
BoxCollider bc = t.GetComponent<BoxCollider>();
RectTransform rt = t.GetComponent<RectTransform>();
if (bc != null)
{
// project size to local coordinate system
Vector2 adjustedSize = new Vector2(
Math.Abs(Vector3.Dot(bc.size, t.LocalRight)),
Math.Abs(Vector3.Dot(bc.size, t.LocalUp)));
// Resize helper
if (adjustedSize != t.Bounds)
{
EditorGUILayout.HelpBox("Bounds do not match the BoxCollider size", MessageType.Warning);
if (GUILayout.Button("Fix Bounds"))
{
Undo.RecordObject(t, "Fix Bounds");
t.SetBounds(adjustedSize);
}
}
// Recentre helper
if (t.LocalCenter != bc.center + Vector3.Scale(bc.size / 2.0f, t.LocalForward))
{
EditorGUILayout.HelpBox("Center does not match the BoxCollider center", MessageType.Warning);
if (GUILayout.Button("Fix Center"))
{
Undo.RecordObject(t, "Fix Center");
t.SetLocalCenter(bc.center + Vector3.Scale(bc.size / 2.0f, t.LocalForward));
}
}
}
else if (rt != null)
{
// Resize Helper
if (rt.sizeDelta != t.Bounds)
{
EditorGUILayout.HelpBox("Bounds do not match the RectTransform size", MessageType.Warning);
if (GUILayout.Button("Fix Bounds"))
{
Undo.RecordObject(t, "Fix Bounds");
t.SetBounds(rt.sizeDelta);
}
}
if (t.GetComponentInParent<Canvas>() != null && t.LocalForward != new Vector3(0, 0, -1))
{
EditorGUILayout.HelpBox("Unity UI generally has forward facing away from the front. The LocalForward direction specified does not match the expected forward direction.", MessageType.Warning);
if (GUILayout.Button("Fix Forward Direction"))
{
Undo.RecordObject(t, "Fix Forward Direction");
t.SetLocalForward(new Vector3(0, 0, -1));
}
}
}
// Perpendicular forward/up vectors helpers
if (!t.AreLocalVectorsOrthogonal)
{
EditorGUILayout.HelpBox("Local Forward and Local Up are not perpendicular.", MessageType.Warning);
if (GUILayout.Button("Fix Local Up"))
{
Undo.RecordObject(t, "Fix Local Up");
t.SetLocalForward(t.LocalForward);
}
if (GUILayout.Button("Fix Local Forward"))
{
Undo.RecordObject(t, "Fix Local Forward");
t.SetLocalUp(t.LocalUp);
}
}
}
19
Source : NearInteractionTouchable.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public void SetTouchableCollider(BoxCollider newCollider)
{
if (newCollider != null)
{
// Set touchableCollider for possible reference in the future
touchableCollider = newCollider;
SetLocalForward(-Vector3.forward);
Vector2 adjustedSize = new Vector2(
Math.Abs(Vector3.Dot(newCollider.size, LocalRight)),
Math.Abs(Vector3.Dot(newCollider.size, LocalUp)));
SetBounds(adjustedSize);
// Set x and y center to match the newCollider but change the position of the
// z axis so the plane is always in front of the object
SetLocalCenter(newCollider.center + Vector3.Scale(newCollider.size / 2.0f, LocalForward));
// Set size and center of the gameObject's box collider to match the collider given, if there
// is no box collider behind the NearInteractionTouchable plane, an event will not be raised
BoxCollider attachedBoxCollider = GetComponent<BoxCollider>();
attachedBoxCollider.size = newCollider.size;
attachedBoxCollider.center = newCollider.center;
}
else
{
Debug.LogWarning("BoxCollider is null, cannot set bounds of NearInteractionTouchable plane");
}
}
19
Source : NearInteractionTouchable.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public override float DistanceToTouchable(Vector3 samplePoint, out Vector3 normal)
{
normal = Forward;
Vector3 localPoint = transform.InverseTransformPoint(samplePoint) - localCenter;
// Get surface coordinates
Vector3 planeSpacePoint = new Vector3(
Vector3.Dot(localPoint, LocalRight),
Vector3.Dot(localPoint, localUp),
Vector3.Dot(localPoint, localForward));
// touchables currently can only be touched within the bounds of the rectangle.
// We return infinity to ensure that any point outside the bounds does not get touched.
if (planeSpacePoint.x < -bounds.x / 2 ||
planeSpacePoint.x > bounds.x / 2 ||
planeSpacePoint.y < -bounds.y / 2 ||
planeSpacePoint.y > bounds.y / 2)
{
return float.PositiveInfinity;
}
// Scale back to 3D space
planeSpacePoint = transform.TransformSize(planeSpacePoint);
return Math.Abs(planeSpacePoint.z);
}
19
Source : NearInteractionTouchableUnityUI.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public override float DistanceToTouchable(Vector3 samplePoint, out Vector3 normal)
{
normal = transform.TransformDirection(-LocalPressDirection);
Vector3 localPoint = transform.InverseTransformPoint(samplePoint);
// touchables currently can only be touched within the bounds of the rectangle.
// We return infinity to ensure that any point outside the bounds does not get touched.
if (!rectTransform.Value.rect.Contains(localPoint))
{
return float.PositiveInfinity;
}
// Scale back to 3D space
localPoint = transform.TransformSize(localPoint);
return Math.Abs(localPoint.z);
}
19
Source : ViewModel3DFactory.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static UniformGridDataSeries3D<double> GetSurfaceMeshDataSeries()
{
var meshDataSeries = new UniformGridDataSeries3D<double>(80, 25) { StepX = 1, StepZ = 1 };
for (int x = 0; x < 80; x++)
{
for (int z = 0; z < 25; z++)
{
var s = DataManager.Instance.GetGaussianRandomNumber(100, 100);
double y = Math.Sin(x * 0.2 * s) / ((z + 1) * 2);
y = y >= 0 ? y : 0;
meshDataSeries[z, x] = y * Math.Abs(s);
}
}
return meshDataSeries;
}
19
Source : AutomationTestBase.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void SaveDiffImages(string resourceName, WriteableBitmap expectedBitmap, WriteableBitmap actualBitmap)
{
string expectedPath = Path.Combine(ExportActualPath,
Path.GetFileNameWithoutExtension(resourceName) + "-expected.png");
string actualPath = Path.Combine(ExportActualPath,
Path.GetFileNameWithoutExtension(resourceName) + "-actual.png");
SaveToPng(expectedPath, expectedBitmap);
Console.WriteLine(@"Expected bitmap saved to " + expectedPath);
SaveToPng(actualPath, actualBitmap);
Console.WriteLine(@"Actual bitmap saved to " + actualPath);
var byteExpected = expectedBitmap.ToByteArray();
var byteActual = actualBitmap.ToByteArray();
if (byteExpected.Length == byteActual.Length)
{
var byteDiff = new byte[byteExpected.Length];
for (int i = 0; i < byteExpected.Length; i++)
{
// For alpha use the average of both images (otherwise pixels with the same alpha won't be visible)
if ((i + 1) % 4 == 0)
byteDiff[i] = (byte)((byteActual[i] + byteExpected[i]) / 2);
else
byteDiff[i] = (byte)Math.Abs(byteActual[i] - byteExpected[i]);
}
var diffBmp = new WriteableBitmap(expectedBitmap.PixelWidth, expectedBitmap.PixelHeight, expectedBitmap.DpiX,
expectedBitmap.DpiY, expectedBitmap.Format, expectedBitmap.Palette);
diffBmp.WritePixels(new Int32Rect(0, 0, expectedBitmap.PixelWidth, expectedBitmap.PixelHeight), byteDiff,
expectedBitmap.BackBufferStride, 0);
string diffPath = Path.Combine(ExportActualPath, Path.GetFileNameWithoutExtension(resourceName) + "-diff.png");
SaveToPng(diffPath, diffBmp);
Console.WriteLine(@"Difference bitmap saved to " + diffPath);
}
}
19
Source : KeyboardMoveXozModifier3D.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static Vector3 GetForwardVector(ICameraController camera)
{
var fwd = camera.Forward;
var fwdDotUnitY = Vector3.DotProduct(fwd, _unitY);
if (Math.Abs(fwdDotUnitY) > 0.9)
{
fwd = camera.Up;
}
if (fwdDotUnitY > 0.0)
{
fwd.Negate();
}
fwd.Y = 0;
fwd.Normalize();
return fwd;
}
19
Source : MotionTable.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public float GetAnimationLength(AnimData anim)
{
var highFrame = anim.HighFrame;
// get the maximum # of animation frames
var animation = DatManager.PortalDat.ReadFromDat<Animation>(anim.AnimId);
if (anim.HighFrame == -1)
highFrame = (int)animation.NumFrames;
if (highFrame > animation.NumFrames)
{
// magic windup for level 6 spells appears to be the only animation w/ bugged data
//Console.WriteLine($"MotionTable.GetAnimationLength({anim}): highFrame({highFrame}) > animation.NumFrames({animation.NumFrames})");
highFrame = (int)animation.NumFrames;
}
var numFrames = highFrame - anim.LowFrame;
return numFrames / Math.Abs(anim.Framerate); // framerates can be negative, which tells the client to play in reverse
}
19
Source : MotionTable.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public ACE.Enreplacedy.Position GetAnimationFinalPositionFromStart(ACE.Enreplacedy.Position position, float objScale, MotionCommand currentMotionState, MotionStance style, MotionCommand motion)
{
float length = 0; // init our length var...will return as 0 if not found
ACE.Enreplacedy.Position finalPosition = new ACE.Enreplacedy.Position();
uint motionHash = ((uint)currentMotionState & 0xFFFFFF) | ((uint)style << 16);
if (Links.ContainsKey(motionHash))
{
Dictionary<uint, MotionData> links = Links[motionHash];
if (links.ContainsKey((uint)motion))
{
// loop through all that animations to get our total count
for (int i = 0; i < links[(uint)motion].Anims.Count; i++)
{
AnimData anim = links[(uint)motion].Anims[i];
uint numFrames;
// check if the animation is set to play the whole thing, in which case we need to get the numbers of frames in the raw animation
if ((anim.LowFrame == 0) && (anim.HighFrame == -1))
{
var animation = DatManager.PortalDat.ReadFromDat<Animation>(anim.AnimId);
numFrames = animation.NumFrames;
if (animation.PosFrames.Count > 0)
{
finalPosition = position;
var origin = new Vector3(position.PositionX, position.PositionY, position.PositionZ);
var orientation = new Quaternion(position.RotationX, position.RotationY, position.RotationZ, position.RotationW);
foreach (var posFrame in animation.PosFrames)
{
origin += Vector3.Transform(posFrame.Origin, orientation) * objScale;
orientation *= posFrame.Orientation;
orientation = Quaternion.Normalize(orientation);
}
finalPosition.PositionX = origin.X;
finalPosition.PositionY = origin.Y;
finalPosition.PositionZ = origin.Z;
finalPosition.RotationW = orientation.W;
finalPosition.RotationX = orientation.X;
finalPosition.RotationY = orientation.Y;
finalPosition.RotationZ = orientation.Z;
}
else
return position;
}
else
numFrames = (uint)(anim.HighFrame - anim.LowFrame);
length += numFrames / Math.Abs(anim.Framerate); // Framerates can be negative, which tells the client to play in reverse
}
}
}
return finalPosition;
}
19
Source : Fellowship.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void CalculateXPSharing()
{
// - If all members of the fellowship are level 50 or above, all members will share XP equally
// - If all members of the fellowship are within 5 levels of the founder, XP will be shared equally
// - If members are all within ten levels of the founder, XP will be shared proportionally.
var fellows = GetFellowshipMembers();
var allEvenShareLevel = PropertyManager.GetLong("fellowship_even_share_level").Item;
var allOverEvenShareLevel = !fellows.Values.Any(f => (f.Level ?? 1) < allEvenShareLevel);
if (allOverEvenShareLevel)
{
ShareXP = DesiredShareXP;
EvenShare = true;
return;
}
var leader = PlayerManager.GetOnlinePlayer(FellowshipLeaderGuid);
if (leader == null)
return;
var maxLevelDiff = fellows.Values.Max(f => Math.Abs((leader.Level ?? 1) - (f.Level ?? 1)));
if (maxLevelDiff <= 5)
{
ShareXP = DesiredShareXP;
EvenShare = true;
}
else if (maxLevelDiff <= 10)
{
ShareXP = DesiredShareXP;
EvenShare = false;
}
else
{
ShareXP = false;
EvenShare = false;
}
}
19
Source : LandblockGroup.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public int BoundaryDistance(Landblock landblock)
{
return (int)Math.Max(
Math.Abs(xCenter - landblock.Id.LandblockX) - (width + 1) / 2.0,
Math.Abs(yCenter - landblock.Id.LandblockY) - (height + 1) / 2.0);
}
19
Source : ChanceTable.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private void VerifyTable()
{
var total = 0.0M;
foreach (var entry in this)
total += (decimal)entry.chance;
if (Math.Abs(1.0M - total) > threshold)
log.Error($"Chance table adds up to {total}, expected 1.0: {string.Join(", ", this)}");
verified = true;
}
19
Source : PositionExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static string GetMapCoordStr(this Position pos)
{
var mapCoords = pos.GetMapCoords();
if (mapCoords == null)
return null;
var northSouth = mapCoords.Value.Y >= 0 ? "N" : "S";
var eastWest = mapCoords.Value.X >= 0 ? "E" : "W";
return string.Format("{0:0.0}", Math.Abs(mapCoords.Value.Y) - 0.05f) + northSouth + ", "
+ string.Format("{0:0.0}", Math.Abs(mapCoords.Value.X) - 0.05f) + eastWest;
}
19
Source : PositionExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsRotationValid(this Quaternion q)
{
if (q == Quaternion.Idenreplacedy)
return true;
if (float.IsNaN(q.X) || float.IsNaN(q.Y) || float.IsNaN(q.Z) || float.IsNaN(q.W))
return false;
var length = q.Length();
if (float.IsNaN(length))
return false;
if (Math.Abs(1.0f - length) > RotationEpsilon)
return false;
return true;
}
19
Source : AFrame.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool Equals(AFrame frame)
{
var originEpsilonEqual = Math.Abs(frame.Origin.X - Origin.X) <= PhysicsGlobals.EPSILON &&
Math.Abs(frame.Origin.Y - Origin.Y) <= PhysicsGlobals.EPSILON &&
Math.Abs(frame.Origin.Z - Origin.Z) <= PhysicsGlobals.EPSILON;
if (!originEpsilonEqual) return false;
var orientationEpsilonEqual = Math.Abs(frame.Orientation.X - frame.Orientation.X) <= PhysicsGlobals.EPSILON &&
Math.Abs(frame.Orientation.Y - frame.Orientation.Y) <= PhysicsGlobals.EPSILON &&
Math.Abs(frame.Orientation.Z - frame.Orientation.Z) <= PhysicsGlobals.EPSILON &&
Math.Abs(frame.Orientation.W - frame.Orientation.W) <= PhysicsGlobals.EPSILON;
return orientationEpsilonEqual;
}
19
Source : Sequence.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void update_internal(float timeElapsed, ref LinkedListNode<AnimSequenceNode> animNode, ref float frameNum, ref AFrame frame)
{
var currAnim = animNode.Value;
var framerate = currAnim.Framerate;
var frametime = framerate * timeElapsed;
var lastFrame = (int)Math.Floor(frameNum);
frameNum += frametime;
var frameTimeElapsed = 0.0f;
var animDone = false;
if (frametime > 0.0f)
{
if (currAnim.get_high_frame() < Math.Floor(frameNum))
{
var frameOffset = frameNum - currAnim.get_high_frame() - 1.0f;
if (frameOffset < 0.0f)
frameOffset = 0.0f;
if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
frameTimeElapsed = frameOffset / framerate;
frameNum = currAnim.get_high_frame();
animDone = true;
}
while (Math.Floor(frameNum) > lastFrame)
{
if (frame != null)
{
if (currAnim.Anim.PosFrames != null)
frame = AFrame.Combine(frame, currAnim.get_pos_frame(lastFrame));
if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / framerate, timeElapsed);
}
execute_hooks(currAnim.get_part_frame(lastFrame), AnimationHookDir.Forward);
lastFrame++;
}
}
else if (frametime < 0.0f)
{
if (currAnim.get_low_frame() > Math.Floor(frameNum))
{
var frameOffset = frameNum - currAnim.get_low_frame();
if (frameOffset > 0.0f)
frameOffset = 0.0f;
if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
frameTimeElapsed = frameOffset / framerate;
frameNum = currAnim.get_low_frame();
animDone = true;
}
while (Math.Floor(frameNum) < lastFrame)
{
if (frame != null)
{
if (currAnim.Anim.PosFrames != null)
frame.Subtract(currAnim.get_pos_frame(lastFrame));
if (Math.Abs(framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / framerate, timeElapsed);
}
execute_hooks(currAnim.get_part_frame(lastFrame), AnimationHookDir.Backward);
lastFrame--;
}
}
else
{
if (frame != null && Math.Abs(timeElapsed) > PhysicsGlobals.EPSILON)
apply_physics(frame, timeElapsed, timeElapsed);
}
if (!animDone)
return;
if (HookObj != null)
{
var node = AnimList.First;
if (!node.Equals(FirstCyclic))
HookObj.add_anim_hook(AnimationHook.AnimDoneHook);
}
advance_to_next_animation(timeElapsed, ref animNode, ref frameNum, ref frame);
timeElapsed = frameTimeElapsed;
// loop to next anim
update_internal(timeElapsed, ref animNode, ref frameNum, ref frame);
}
19
Source : MotionInterp.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool move_to_interpreted_state(InterpretedMotionState state)
{
if (PhysicsObj == null) return false;
RawState.CurrentStyle = state.CurrentStyle;
PhysicsObj.cancel_moveto();
var allowJump = motion_allows_jump(InterpretedState.ForwardCommand) == WeenieError.None ? true : false;
InterpretedState.copy_movement_from(state);
apply_current_movement(true, allowJump);
var movementParams = new MovementParameters();
foreach (var action in state.Actions)
{
var currentStamp = action.Stamp & 0x7FFF;
var serverStamp = ServerActionStamp & 0x7FFFF;
var deltaStamp = Math.Abs(currentStamp - serverStamp);
var diff = deltaStamp <= 0x3FFF ? serverStamp < currentStamp : currentStamp < serverStamp;
if (diff)
{
if (WeenieObj != null && WeenieObj.IsCreature() || action.Autonomous)
{
ServerActionStamp = action.Stamp;
movementParams.Speed = action.Speed;
movementParams.Autonomous = action.Autonomous;
DoInterpretedMotion(action.Action, movementParams);
}
}
}
return true;
}
19
Source : LandDefs.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool AdjustToOutside(ref uint blockCellID, ref Vector3 loc)
{
var cellID = (uint)(blockCellID & CellID_Mask);
if (cell_in_range(cellID))
{
if (Math.Abs(loc.X) < PhysicsGlobals.EPSILON)
loc.X = 0;
if (Math.Abs(loc.Y) < PhysicsGlobals.EPSILON)
loc.Y = 0;
var lcoord = get_outside_lcoord(blockCellID, loc.X, loc.Y);
if (lcoord.HasValue)
{
blockCellID = (uint)lcoord_to_gid(lcoord.Value.X, lcoord.Value.Y);
loc.X -= (float)Math.Floor(loc.X / BlockLength) * BlockLength;
loc.Y -= (float)Math.Floor(loc.Y / BlockLength) * BlockLength;
return true;
}
}
blockCellID = 0;
return false;
}
19
Source : AFrame.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool close_rotation(AFrame a, AFrame b)
{
var ao = a.Orientation;
var bo = b.Orientation;
return Math.Abs(ao.X - bo.X) < PhysicsGlobals.EPSILON &&
Math.Abs(ao.Y - bo.Y) < PhysicsGlobals.EPSILON &&
Math.Abs(ao.Z - bo.Z) < PhysicsGlobals.EPSILON &&
Math.Abs(ao.W - bo.W) < PhysicsGlobals.EPSILON;
}
19
Source : CylSphere.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public TransitionState IntersectsSphere(Transition transition)
{
var obj = transition.ObjectInfo;
var path = transition.SpherePath;
var globSphere = path.GlobalSphere[0];
var disp = globSphere.Center - LowPoint;
Sphere globSphere_ = null;
Vector3 disp_ = Vector3.Zero;
if (path.NumSphere > 1)
{
globSphere_ = path.GlobalSphere[1];
disp_ = globSphere_.Center - LowPoint;
}
var radsum = Radius - PhysicsGlobals.EPSILON + globSphere.Radius;
if (path.InsertType == InsertType.Placement || path.ObstructionEthereal)
{
if (CollidesWithSphere(globSphere, disp, radsum))
return TransitionState.Collided;
if (path.NumSphere > 1 && CollidesWithSphere(globSphere_, disp_, radsum))
return TransitionState.Collided;
return TransitionState.OK;
}
else
{
if (path.StepDown)
return StepSphereDown(transition, globSphere, disp, radsum);
if (path.CheckWalkable)
{
if (CollidesWithSphere(globSphere, disp, radsum))
return TransitionState.Collided;
if (path.NumSphere > 1)
{
if (CollidesWithSphere(globSphere_, disp_, radsum))
return TransitionState.Collided;
}
return TransitionState.OK;
}
if (!path.Collide)
{
if (obj.State.HasFlag(ObjectInfoState.Contact) || obj.State.HasFlag(ObjectInfoState.OnWalkable))
{
if (CollidesWithSphere(globSphere, disp, radsum))
return StepSphereUp(transition, globSphere, disp, radsum);
if (path.NumSphere > 1)
{
if (CollidesWithSphere(globSphere_, disp_, radsum))
return SlideSphere(transition, globSphere_, disp, radsum, 1);
}
}
else if (obj.State.HasFlag(ObjectInfoState.PathClipped))
{
if (CollidesWithSphere(globSphere, disp, radsum))
return CollideWithPoint(transition, globSphere, disp, radsum, 0);
}
else
{
if (CollidesWithSphere(globSphere, disp, radsum))
return LandOnCylinder(transition, globSphere, disp, radsum);
if (path.NumSphere > 1)
{
if (CollidesWithSphere(globSphere_, disp_, radsum))
return CollideWithPoint(transition, globSphere_, disp_, radsum, 1);
}
}
return TransitionState.OK;
}
if (CollidesWithSphere(globSphere, disp, radsum) || path.NumSphere > 1 && CollidesWithSphere(globSphere_, disp_, radsum))
{
var blockOffset = path.GetCurPosCheckPosBlockOffset();
var movement = path.GlobalCurrCenter[0].Center - globSphere.Center - blockOffset;
// what is v39 pointing to before this?
var distSq = movement.LengthSquared();
//var diff = -Vector3.Dot(movement, disp);
var diff = movement.Z * disp.Z - movement.Dot2D(disp);
if (Math.Abs(distSq) < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
radsum += PhysicsGlobals.EPSILON;
var t = Math.Sqrt(diff * diff - (disp.LengthSquared() - radsum * radsum) * distSq) + diff; // solve for t, no division?
if (t > 1)
t = diff * 2 - diff;
var time = diff / distSq;
var timecheck = (1 - time) * transition.SpherePath.WalkInterp;
if (timecheck >= transition.SpherePath.WalkInterp || timecheck < -0.1f)
return TransitionState.Collided;
movement *= time;
disp = (disp + movement) / radsum;
if (!transition.SpherePath.IsWalkableAllowable(disp.Z))
return TransitionState.OK;
var pDist = -Vector3.Dot(disp, globSphere.Center - disp * globSphere.Radius);
var contactPlane = new Plane(disp, pDist);
transition.CollisionInfo.SetContactPlane(contactPlane, true);
transition.CollisionInfo.ContactPlaneCellID = transition.SpherePath.CheckPos.ObjCellID;
transition.SpherePath.WalkInterp = timecheck;
transition.SpherePath.AddOffsetToCheckPos(movement, globSphere.Radius);
return TransitionState.Adjusted;
}
}
return TransitionState.OK;
}
19
Source : CylSphere.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public TransitionState StepSphereDown(Transition transition, Sphere checkPos, Vector3 disp, float radsum)
{
var path = transition.SpherePath;
Sphere globSphere_ = null;
Vector3 disp_ = Vector3.Zero;
if (path.NumSphere > 1)
{
globSphere_ = path.GlobalSphere[1];
disp_ = globSphere_.Center - LowPoint;
}
if (CollidesWithSphere(checkPos, disp, radsum) || path.NumSphere > 1 && CollidesWithSphere(globSphere_, disp_, radsum))
{
var stepScale = path.StepDownAmt * path.WalkInterp;
if (Math.Abs(stepScale) < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
var deltaz = Height + checkPos.Radius - disp.Z;
var interp = (1.0f - deltaz / stepScale) * path.WalkInterp;
if (interp >= path.WalkInterp || interp < -0.1f)
return TransitionState.Collided;
var normal = Vector3.UnitZ;
var contactPoint = new Vector3(checkPos.Center.X, checkPos.Center.Y, checkPos.Center.Z + (deltaz - checkPos.Radius));
var contactPlane = new Plane(normal, -Vector3.Dot(normal, contactPoint));
var collisions = transition.CollisionInfo;
collisions.SetContactPlane(contactPlane, true); // is water?
path.WalkInterp = interp;
path.AddOffsetToCheckPos(new Vector3(0, 0, deltaz), checkPos.Radius);
return TransitionState.Adjusted;
}
return TransitionState.OK;
}
19
Source : CylSphere.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool CollisionNormal(Transition transition, Sphere checkPos, Vector3 _disp, float radsum, int sphereNum, out Vector3 normal)
{
var disp = transition.SpherePath.GlobalCurrCenter[sphereNum].Center - LowPoint;
if (radsum * radsum < disp.LengthSquared2D())
{
normal = new Vector3(disp.X, disp.Y, 0);
return (checkPos.Radius - PhysicsGlobals.EPSILON + Height * 0.5f >= Math.Abs(Height * 0.5f - disp.Z)
|| Math.Abs(disp.Z - _disp.Z) <= PhysicsGlobals.EPSILON);
}
var normZ = (_disp.Z - disp.Z <= 0.0f) ? 1 : -1;
normal = new Vector3(0, 0, normZ);
return true;
}
19
Source : MotionTable.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static float GetTurnSpeed(uint motionTableID)
{
if (TurnSpeed.TryGetValue(motionTableID, out float turnSpeed))
return turnSpeed;
uint turnMotion = (uint)MotionCommand.TurnRight;
var motionData = GetMotionData(motionTableID, turnMotion);
if (motionData == null)
return 0.0f;
var speed = Math.Abs(motionData.Omega.Z);
TurnSpeed[motionTableID] = speed;
return speed;
}
19
Source : Sequence.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void advance_to_next_animation(float timeElapsed, ref LinkedListNode<AnimSequenceNode> animNode, ref float frameNum, ref AFrame frame)
{
var currAnim = animNode.Value;
if (timeElapsed >= 0.0f)
{
if (frame != null && currAnim.Framerate < 0.0f)
{
if (currAnim.Anim.PosFrames.Count > 0)
frame.Subtract(currAnim.get_pos_frame((int)frameNum));
if (Math.Abs(currAnim.Framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / currAnim.Framerate, timeElapsed);
}
if (animNode.Next != null)
animNode = animNode.Next;
else
animNode = FirstCyclic;
currAnim = animNode.Value;
frameNum = currAnim.get_starting_frame();
if (frame != null && currAnim.Framerate > 0.0f)
{
if (currAnim.Anim.PosFrames.Count > 0)
frame = AFrame.Combine(frame, currAnim.get_pos_frame((int)frameNum));
if (Math.Abs(currAnim.Framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / currAnim.Framerate, timeElapsed);
}
}
else
{
if (frame != null && currAnim.Framerate >= 0.0f)
{
if (currAnim.Anim.PosFrames.Count > 0)
frame.Subtract(currAnim.get_pos_frame((int)frameNum));
if (Math.Abs(currAnim.Framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / currAnim.Framerate, timeElapsed);
}
if (animNode.Previous != null)
animNode = animNode.Previous;
else
animNode = animNode.List.Last;
currAnim = animNode.Value;
frameNum = currAnim.get_ending_frame();
if (frame != null && currAnim.Framerate < 0.0f)
{
if (currAnim.Anim.PosFrames.Count > 0)
frame = AFrame.Combine(frame, currAnim.get_pos_frame((int)frameNum));
if (Math.Abs(currAnim.Framerate) > PhysicsGlobals.EPSILON)
apply_physics(frame, 1.0f / currAnim.Framerate, timeElapsed);
}
}
}
19
Source : Landblock.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void adjust_scene_obj_height()
{
foreach (var obj in StaticObjects)
{
var cell = (LandCell)obj.CurCell;
Polygon walkable = null;
var objPos = obj.Position.Frame.Origin;
if (!cell.find_terrain_poly(objPos, ref walkable))
continue;
var adjZ = objPos.Z;
if (Math.Abs(walkable.Plane.Normal.Z) > PhysicsGlobals.EPSILON)
adjZ = (objPos.Dot2D(walkable.Plane.Normal) + walkable.Plane.D) / walkable.Plane.Normal.Z * -1;
if (Math.Abs(objPos.Z - adjZ) > PhysicsGlobals.EPSILON)
{
objPos.Z = adjZ;
obj.set_initial_frame(obj.Position.Frame);
}
}
}
19
Source : Landblock.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public float GetZ(Vector3 point)
{
var cell = GetCell(point);
if (cell == null)
return point.Z;
Polygon walkable = null;
if (!cell.find_terrain_poly(point, ref walkable))
return point.Z;
var adjZ = point.Z;
if (Math.Abs(walkable.Plane.Normal.Z) > PhysicsGlobals.EPSILON)
adjZ = (point.Dot2D(walkable.Plane.Normal) + walkable.Plane.D) / walkable.Plane.Normal.Z * -1;
return adjZ;
}
19
Source : Vector.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsZero(Vector3 v)
{
return Math.Abs(v.X) < PhysicsGlobals.EPSILON &&
Math.Abs(v.Y) < PhysicsGlobals.EPSILON &&
Math.Abs(v.Z) < PhysicsGlobals.EPSILON;
}
19
Source : PlaneExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void SnapToPlane(this Plane p, ref Vector3 offset)
{
if (Math.Abs(p.Normal.Z) <= PhysicsGlobals.EPSILON)
return;
offset.Z = -(offset.Dot2D(p.Normal) + p.D) * (1.0f / p.Normal.Z) - 1.0f / p.Normal.Z * -p.D;
}
19
Source : PlaneExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool compute_time_of_intersection(this Plane p, Ray ray, ref float time)
{
var angle = Vector3.Dot(ray.Dir, p.Normal);
if (Math.Abs(angle) < PhysicsGlobals.EPSILON)
return false;
time = (Vector3.Dot(ray.Point, p.Normal) + p.D) * (-1.0f / angle);
return time >= 0.0f;
}
19
Source : PlaneExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool set_height(this Plane p, ref Vector3 v)
{
if (Math.Abs(p.Normal.Z) <= PhysicsGlobals.EPSILON)
return false;
v.Z = -((v.Y * p.Normal.Y + v.X * p.Normal.X + p.D) / p.Normal.Z);
return true;
}
19
Source : QuaternionExtensions.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static bool IsValid(this Quaternion q)
{
if (float.IsNaN(q.X) || float.IsNaN(q.Y) || float.IsNaN(q.Z) || float.IsNaN(q.W))
return false;
var length = q.Length();
if (float.IsNaN(length))
return false;
if (Math.Abs(length - 1.0f) > PhysicsGlobals.EPSILON * 5.0f)
return false;
return true;
}
19
Source : MoveToManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void MoveToObject_Internal(Position targetPosition, Position interpolatedPosition)
{
//Console.WriteLine("MoveToObject_Internal");
if (PhysicsObj == null)
{
CancelMoveTo(WeenieError.NoPhysicsObject);
return;
}
SoughtPosition = new Position(interpolatedPosition);
CurrentTargetPosition = new Position(targetPosition);
var iHeading = PhysicsObj.Position.heading(interpolatedPosition);
var heading = iHeading - PhysicsObj.get_heading();
var dist = GetCurrentDistance();
if (Math.Abs(heading) < PhysicsGlobals.EPSILON)
heading = 0.0f;
if (heading < -PhysicsGlobals.EPSILON)
heading += 360.0f;
HoldKey holdKey = HoldKey.Invalid;
uint motionID = 0;
bool moveAway = false;
MovementParams.get_command(dist, heading, ref motionID, ref holdKey, ref moveAway);
if (motionID != 0)
{
AddTurnToHeadingNode(iHeading);
AddMoveToPositionNode();
}
if (MovementParams.UseFinalHeading)
{
var dHeading = iHeading + MovementParams.DesiredHeading;
if (dHeading >= 360.0f)
dHeading -= 360.0f;
AddTurnToHeadingNode(dHeading);
}
Initialized = true;
BeginNextNode();
}
19
Source : StickyManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void adjust_offset(AFrame offset, double quantum)
{
if (PhysicsObj == null || TargetID == 0 || !Initialized)
return;
var target = PhysicsObj.GetObjectA(TargetID);
var targetPosition = target == null ? TargetPosition : target.Position;
offset.Origin = PhysicsObj.Position.GetOffset(targetPosition);
offset.Origin = PhysicsObj.Position.GlobalToLocalVec(offset.Origin);
offset.Origin.Z = 0.0f;
var radius = PhysicsObj.GetRadius();
var dist = Position.CylinderDistanceNoZ(radius, PhysicsObj.Position, TargetRadius, targetPosition) - StickyRadius;
if (Vec.NormalizeCheckSmall(ref offset.Origin))
offset.Origin = Vector3.Zero;
var speed = 0.0f;
var minterp = PhysicsObj.get_minterp();
if (minterp != null)
speed = minterp.get_max_speed() * 5.0f;
if (speed < PhysicsGlobals.EPSILON)
speed = 15.0f;
var delta = speed * (float)quantum;
if (delta >= Math.Abs(dist))
delta = dist;
offset.Origin *= delta;
var curHeading = PhysicsObj.Position.Frame.get_heading();
var targetHeading = PhysicsObj.Position.heading(targetPosition);
var heading = targetHeading - curHeading;
if (Math.Abs(heading) < PhysicsGlobals.EPSILON)
heading = 0.0f;
if (heading < -PhysicsGlobals.EPSILON)
heading += 360.0f;
//Console.WriteLine($"StickyManager.AdjustOffset(targetHeading={targetHeading}, curHeading={curHeading}, setHeading={heading})");
offset.set_heading(heading);
}
19
Source : CylSphere.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public TransitionState CollideWithPoint(Transition transition, Sphere checkPos, Vector3 disp, float radsum, int sphereNum)
{
var obj = transition.ObjectInfo;
var path = transition.SpherePath;
var collisions = transition.CollisionInfo;
Vector3 collisionNormal;
var definate = CollisionNormal(transition, checkPos, disp, radsum, sphereNum, out collisionNormal);
if (Vec.NormalizeCheckSmall(ref collisionNormal))
return TransitionState.Collided;
if (!obj.State.HasFlag(ObjectInfoState.PerfectClip))
{
collisions.SetCollisionNormal(collisionNormal);
return TransitionState.Collided;
}
var globCenter = path.GlobalCurrCenter[0].Center;
var movement = LandDefs.GetBlockOffset(path.CurPos.ObjCellID, path.CheckPos.ObjCellID);
movement += checkPos.Center - globCenter;
var old_disp = globCenter - LowPoint;
radsum += PhysicsGlobals.EPSILON;
// this is similar to ray/sphere intersection, could be inlined...
var xyMoveLenSq = movement.LengthSquared2D();
var xyDiff = -movement.Dot2D(old_disp);
var diffSq = xyDiff * xyDiff - (old_disp.LengthSquared2D() - radsum * radsum) * xyMoveLenSq;
var diff = (float)Math.Sqrt(diffSq);
Vector3 scaledMovement, offset;
float time; // calculated below, refactor
if (!definate)
{
if (Math.Abs(movement.Z) < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
if (movement.Z > 0.0f)
{
collisionNormal = new Vector3(0, 0, -1.0f);
time = (movement.Z + checkPos.Radius) / movement.Z * -1.0f;
}
else
{
collisionNormal = new Vector3(0, 0, 1.0f);
time = (checkPos.Radius + Height - movement.Z) / movement.Z;
}
scaledMovement = movement * time;
var scaledLenSq = (scaledMovement + old_disp).LengthSquared2D();
if (scaledLenSq >= radsum * radsum)
{
if (Math.Abs(xyMoveLenSq) < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
if (diffSq >= 0.0f && xyMoveLenSq > PhysicsGlobals.EPSILON)
{
if (xyDiff - diff < 0.0f)
time = (float)((diff - movement.Dot2D(old_disp)) / xyMoveLenSq);
else
time = (float)((xyDiff - diff) / xyMoveLenSq);
scaledMovement = movement * time;
}
collisionNormal = (scaledMovement + globCenter - LowPoint) / radsum;
collisionNormal.Z = 0.0f;
}
if (time < 0.0f || time > 1.0f)
return TransitionState.Collided;
offset = globCenter - scaledMovement - checkPos.Center;
path.AddOffsetToCheckPos(offset, checkPos.Radius);
collisions.SetCollisionNormal(collisionNormal);
return TransitionState.Adjusted;
}
if (collisionNormal.Z != 0.0f)
{
if (Math.Abs(movement.Z) < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
if (movement.Z > 0.0f)
time = -((old_disp.Z + checkPos.Radius) / movement.Z);
else
time = (checkPos.Radius + Height - old_disp.Z) / movement.Z;
scaledMovement = movement * time;
if (time < 0.0f || time > 1.0f)
return TransitionState.Collided;
offset = globCenter + scaledMovement - checkPos.Center;
path.AddOffsetToCheckPos(offset, checkPos.Radius);
collisions.SetCollisionNormal(collisionNormal);
return TransitionState.Adjusted;
}
// duplicated from above, refactor...
if (diffSq < 0.0f || xyMoveLenSq < PhysicsGlobals.EPSILON)
return TransitionState.Collided;
if (xyDiff - diff < 0.0f)
time = (float)((diff - movement.Dot2D(old_disp)) / xyMoveLenSq);
else
time = (float)((xyDiff - diff) / xyMoveLenSq);
scaledMovement = movement * time;
if (time < 0.0f || time > 1.0f)
return TransitionState.Collided;
collisionNormal = (scaledMovement + globCenter - LowPoint) / radsum;
collisionNormal.Z = 0.0f;
offset = globCenter + scaledMovement - checkPos.Center;
path.AddOffsetToCheckPos(offset, checkPos.Radius);
collisions.SetCollisionNormal(collisionNormal);
return TransitionState.Adjusted;
}
19
Source : CylSphere.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool CollidesWithSphere(Sphere checkPos, Vector3 disp, float radsum)
{
var result = false;
if (disp.X * disp.X + disp.Y * disp.Y <= radsum * radsum)
{
if (checkPos.Radius - PhysicsGlobals.EPSILON + Height * 0.5f >= Math.Abs(Height * 0.5f - disp.Z))
result = true;
}
return result;
}
19
Source : MoveToManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void MoveToPosition(Position position, MovementParameters movementParams)
{
//Console.WriteLine("MoveToPosition");
if (PhysicsObj == null) return;
PhysicsObj.StopCompletely(false);
CurrentTargetPosition = new Position(position);
SoughtObjectRadius = 0.0f;
var distance = GetCurrentDistance();
var headingDiff = PhysicsObj.Position.heading(position) - PhysicsObj.get_heading();
if (Math.Abs(headingDiff) < PhysicsGlobals.EPSILON)
headingDiff = 0.0f;
if (headingDiff < -PhysicsGlobals.EPSILON)
headingDiff += 360.0f;
HoldKey holdKey = HoldKey.Invalid;
uint command = 0;
bool moveAway = false;
movementParams.get_command(distance, headingDiff, ref command, ref holdKey, ref moveAway);
if (command != 0)
{
AddTurnToHeadingNode(PhysicsObj.Position.heading(position));
AddMoveToPositionNode();
}
if (MovementParams.UseFinalHeading)
AddTurnToHeadingNode(movementParams.DesiredHeading);
SoughtPosition = new Position(position);
StartingPosition = new Position(PhysicsObj.Position);
MovementType = MovementType.MoveToPosition;
MovementParams = new MovementParameters(movementParams);
//var flags = (MovementParamFlags)0xFFFFFF7F; // unset Sticky?
//MovementParams.Flags = MovementParams.Flags & flags;
MovementParams.Sticky = false;
BeginNextNode();
}
19
Source : MoveToManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void BeginMoveForward()
{
//Console.WriteLine("BeginMoveForward");
if (PhysicsObj == null)
{
CancelMoveTo(WeenieError.NoPhysicsObject);
return;
}
var dist = GetCurrentDistance();
var heading = PhysicsObj.Position.heading(CurrentTargetPosition) - PhysicsObj.get_heading();
if (Math.Abs(heading) < PhysicsGlobals.EPSILON)
heading = 0.0f;
if (heading < -PhysicsGlobals.EPSILON)
heading += 360.0f;
uint motion = 0;
bool moveAway = false;
HoldKey holdKey = HoldKey.Invalid;
MovementParams.get_command(dist, heading, ref motion, ref holdKey, ref moveAway);
if (motion == 0)
{
RemovePendingActionsHead();
BeginNextNode();
return;
}
var movementParams = new MovementParameters();
movementParams.HoldKeyToApply = holdKey;
movementParams.CancelMoveTo = false;
movementParams.Speed = MovementParams.Speed;
var result = _DoMotion(motion, movementParams);
if (result != WeenieError.None)
{
CancelMoveTo(result);
return;
}
CurrentCommand = motion;
MovingAway = moveAway;
MovementParams.HoldKeyToApply = holdKey;
PreviousDistance = dist;
PreviousDistanceTime = PhysicsTimer.CurrentTime;
OriginalDistance = dist;
OriginalDistanceTime = PhysicsTimer.CurrentTime;
}
19
Source : MoveToManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void HandleMoveToPosition()
{
//Console.WriteLine("HandleMoveToPosition");
if (PhysicsObj == null)
{
CancelMoveTo(WeenieError.NoPhysicsObject);
return;
}
var curPos = new Position(PhysicsObj.Position);
var movementParams = new MovementParameters();
movementParams.CancelMoveTo = false;
movementParams.Speed = MovementParams.Speed;
movementParams.HoldKeyToApply = MovementParams.HoldKeyToApply;
if (!PhysicsObj.IsAnimating)
{
var heading = MovementParams.get_desired_heading(CurrentCommand, MovingAway) + curPos.heading(CurrentTargetPosition);
if (heading >= 360.0f) heading -= 360.0f;
var diff = heading - PhysicsObj.get_heading();
if (Math.Abs(diff) < PhysicsGlobals.EPSILON) diff = 0.0f;
if (diff < -PhysicsGlobals.EPSILON)
diff += 360.0f;
if (diff > 20.0f && diff < 340.0f)
{
uint motionID = diff >= 180.0f ? (uint)MotionCommand.TurnLeft : (uint)MotionCommand.TurnRight;
if (motionID != AuxCommand)
{
_DoMotion(motionID, movementParams);
AuxCommand = motionID;
}
}
else
{
// custom: sync for server ticrate
if (AuxCommand != 0)
PhysicsObj.set_heading(heading, true);
stop_aux_command(movementParams);
}
}
else
stop_aux_command(movementParams);
var dist = GetCurrentDistance();
if (!CheckProgressMade(dist))
{
if (!PhysicsObj.IsInterpolating() && !PhysicsObj.IsAnimating)
FailProgressCount++;
}
else
{
// custom for low monster update rate
var inRange = false;
if (!MovementParams.UseSpheres)
{
if (dist < 1.0f && PreviousDistance < dist)
inRange = true;
PreviousDistance = dist;
PreviousDistanceTime = PhysicsTimer.CurrentTime;
}
FailProgressCount = 0;
if (MovingAway && dist >= MovementParams.MinDistance || !MovingAway && dist <= MovementParams.DistanceToObject || inRange)
{
PendingActions.RemoveAt(0);
_StopMotion(CurrentCommand, movementParams);
CurrentCommand = 0;
stop_aux_command(movementParams);
BeginNextNode();
}
else
{
if (StartingPosition.Distance(PhysicsObj.Position) > MovementParams.FailDistance)
CancelMoveTo(WeenieError.YouChargedTooFar);
}
}
if (TopLevelObjectID != 0 && MovementType != MovementType.Invalid)
{
var velocity = PhysicsObj.get_velocity();
var velocityLength = velocity.Length();
if (velocityLength > 0.1f)
{
var time = dist / velocityLength;
if (Math.Abs(time - PhysicsObj.get_target_quantum()) > 1.0f)
PhysicsObj.set_target_quantum(time);
}
}
}
See More Examples