Here are the examples of the csharp api float.ToString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
818 Examples
19
View Source File : G_FloatString.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static void Init(float minNegativeValue, float maxPositiveValue, int decimals = 1)
{
decimalMultiplier = Pow(10, Mathf.Clamp(decimals, 1, 5));
int negativeLength = minNegativeValue.ToIndex();
int positiveLength = maxPositiveValue.ToIndex();
if (negativeLength >= 0)
{
negativeBuffer = new string[negativeLength];
for (int i = 0; i < negativeLength; i++)
{
negativeBuffer[i] = (-i).FromIndex().ToString(floatFormat);
}
}
if (positiveLength >= 0)
{
positiveBuffer = new string[positiveLength];
for (int i = 0; i < positiveLength; i++)
{
positiveBuffer[i] = i.FromIndex().ToString(floatFormat);
}
}
}
19
View Source File : G_FloatString.cs
License : MIT License
Project Creator : 1ZouLTReX1
License : MIT License
Project Creator : 1ZouLTReX1
public static string ToStringNonAlloc(this float value, string format)
{
int valIndex = value.ToIndex();
if (value < 0 && valIndex < negativeBuffer.Length)
{
return negativeBuffer[valIndex];
}
if (value >= 0 && valIndex < positiveBuffer.Length)
{
return positiveBuffer[valIndex];
}
return value.ToString(format);
}
19
View Source File : GradeManager.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
void PlayScoreAnimation()
{
if (!scoreAnimationDone)
{
hitCount = Mathf.SmoothStep(hitCount, RuntimeData.hitCount, 0.1f);
perfectCountLabel.text = string.Format("{0}/{1}", Mathf.RoundToInt(hitCount), RuntimeData.hitCount + RuntimeData.missCount);
missCount = Mathf.SmoothStep(missCount, RuntimeData.missCount, 0.1f);
missCountLabel.text = (Mathf.RoundToInt(missCount)).ToString();
maxCombo = Mathf.SmoothStep(maxCombo, RuntimeData.maxCombo, 0.1f);
comboCountLabel.text = (Mathf.RoundToInt(maxCombo)).ToString();
score += Mathf.Max((RuntimeData.score - score), 0.0001f) * 4 * Time.deltaTime;
score = Mathf.Min(score, RuntimeData.score);
string scoreString = (score * 100).ToString("0.00");
scoreCountLabel.text = scoreString.Substring(0, Mathf.Min(6, scoreString.Length)) + "%";
if ((Mathf.RoundToInt(hitCount) == RuntimeData.hitCount) &&
(Mathf.RoundToInt(missCount) == RuntimeData.missCount) &&
(Mathf.RoundToInt(maxCombo) == RuntimeData.maxCombo) &&
(Mathf.Abs(RuntimeData.score - score) < 0.00005f))
{
scoreAnimationDone = true;
rankGroup.DOFade(1, 0.75f).SetEase(Ease.InOutCubic).SetDelay(0.5f);
}
}
}
19
View Source File : ColorLabel.cs
License : MIT License
Project Creator : 734843327
License : MIT License
Project Creator : 734843327
private string ConvertToDisplayString(float value)
{
if (precision > 0)
return value.ToString("f " + precision);
else
return Mathf.FloorToInt(value).ToString();
}
19
View Source File : DecorationMaster.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public override string GetVersion()
{
replacedembly asm = replacedembly.GetExecutingreplacedembly();
string ver = Version.ToString("0.000");
using SHA1 sha1 = SHA1.Create();
using FileStream stream = File.OpenRead(asm.Location);
byte[] hashBytes = sha1.ComputeHash(stream);
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
return $"{ver}-{hash.Substring(0, 6)}";
}
19
View Source File : Inspector.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void Show()
{
OpLock.Apply();
try
{
Item item = ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().item;
if (!cache_prop.ContainsKey(item.GetType()))
{
_reflectProps(item.GetType());
}
if (cache_prop.TryGetValue(item.GetType(), out var itemProps))
{
var insp = new InspectPanel();
currentEdit = insp;
int idx = 0;
foreach (var kv in itemProps)
{
string name = kv.Key;
Type propType = kv.Value.PropertyType;
object value = kv.Value.GetValue(item, null);
value = Convert.ToSingle(value);
ConstraintAttribute con = kv.Value.GetCustomAttributes(typeof(ConstraintAttribute), true).OfType<ConstraintAttribute>().FirstOrDefault();
LogProp(propType, name, value);
if(idx == 0)
{
insp.UpdateName(idx,name);
if(con is IntConstraint)
{
//Logger.LogDebug($"Check1 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)Convert.ChangeType(con.Min, typeof(float)), Convert.ToInt32(con.Max), true);
}
else if(con is FloatConstraint)
{
//Logger.LogDebug($"Check2 {con.Min}-{con.Max}");
insp.UpdateSliderConstrain(name,idx, (float)(con.Min), (float)(con.Max), false);
}
else
{
throw new ArgumentException();
}
//Logger.LogDebug($"Check3 {value}-{value.GetType()}");
insp.UpdateValue(idx, (float)value);
}
else
{
insp.AppendPropPanel(name);
if (con is IntConstraint)
{
insp.UpdateSliderConstrain(name,idx, (int)con.Min, (int)con.Max, true);
}
else if (con is FloatConstraint)
{
insp.UpdateSliderConstrain(name,idx, (float)con.Min, (float)con.Max, false);
}
else
{
throw new ArgumentException();
}
insp.UpdateValue(idx, (float)value);
insp.UpdateTextDelegate(idx);//insp.AddListener(idx, insp.UpdateTextDelegate(idx));
}
//insp.AddListener(idx, (v) => { kv.Value.SetValue(item, Convert.ChangeType(v, kv.Value.PropertyType), null); });
insp.AddListener(idx, (v) => {
if (ItemManager.Instance.currentSelect == null)
return;
object val;
try
{
if (kv.Value.PropertyType.IsSubclreplacedOf(typeof(Enum)))
{
val = Enum.Parse(kv.Value.PropertyType, v.ToString("0"));
}
else
val = Convert.ChangeType(v, kv.Value.PropertyType);
ItemManager.Instance.currentSelect.GetComponent<CustomDecoration>().Setup(handler[kv.Value], val);
}
catch
{
Logger.LogError("Error occour at Inspect OnValue Chnaged");
Hide();
}
});
idx++;
}
}
else
{
Logger.LogError($"KeyNotFount at cache_prop,{item.GetType()}");
}
}
catch(NullReferenceException e)
{
Logger.LogError($"NulRef Error at Inspector.Show:{e}");
OpLock.Undo();
}
}
19
View Source File : CameraBodyEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void DrawDepthOfFieldField () {
float dofTotal, dofNear, dofFar;
dofTotal = _dofDistTotal.floatValue;
dofNear = _dofNearLimit.floatValue;
dofFar = _dofFarLimit.floatValue;
if (((UnitOfMeasure)_unitOfMeasure.enumValueIndex == UnitOfMeasure.Imperial))
{
float totalR, nearT, farT;
totalR = Mathf.Floor((dofTotal - Mathf.Floor(dofTotal)) * 12);
dofTotal = Mathf.Floor(dofTotal);
nearT = Mathf.Floor((dofNear - Mathf.Floor(dofNear)) * 12);
dofNear = Mathf.Floor(dofNear);
farT = Mathf.Floor((dofFar - Mathf.Floor(dofFar)) * 12);
dofFar = Mathf.Floor(dofFar);
string dof = dofTotal >= 0 ? "" + dofTotal + "' " + totalR + "\"" : "INF";
EditorGUILayout.LabelField("Depth of Field", dof);
EditorGUILayout.LabelField("Near Limit", "" + dofNear + "' " + nearT + "\"");
string farLimit = dofFar >= 0 ? "" + dofFar + "' " + farT + "\"" : "INF";
EditorGUILayout.LabelField("Far Limit", farLimit);
}
else
{
float dof = ProCamsUtility.Convert(dofTotal, Units.Foot, Units.Meter);
float dn = ProCamsUtility.Convert(dofNear, Units.Foot, Units.Meter);
float df = ProCamsUtility.Convert(dofFar, Units.Foot, Units.Meter);
string dofString = dofTotal >= 0 ? dof.ToString("0.00") +"m": "INF";
EditorGUILayout.LabelField("Depth of Field", dofString);
EditorGUILayout.LabelField("Near Limit", dn.ToString("0.00") + "m");
string farLimit = dofFar >= 0 ? df.ToString("0.00") + "m" : "INF";
EditorGUILayout.LabelField("Far Limit", farLimit);
}
}
19
View Source File : CameraBodyEditorWindow.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void DrawDepthOfFieldField () {
float F, f, H, S, DN, DF, D, TI, NI, FI;
//float focalLength = ProCamsDataTable.list[_lensKitIndex].lenses[_lensIndex].length;
float focalLength = 0;
ProCamsLensDataTable.FilmFormatData curFilmFormat = ProCamsLensDataTable.Instance.GetFilmFormat(_ffList[_currentFilmFormatIndex]);
if(curFilmFormat != null)
{
ProCamsLensDataTable.FOVData fovData = curFilmFormat.GetFOVData(_lensKitIndex, _lensIndex);
if(fovData != null)
{
focalLength = fovData._focalLength;
}
}
F = ProCamsUtility.Convert(
focalLength,
Units.Millimeter, // from mm
Units.Inch); // to inches
f = FStop.list[_fstopIndex].fstop;
H = (F * F) / (f * 0.001f); // 0.001 = Circle of Confusion
if (_unitOfMeasure == UnitOfMeasure.Imperial)
{
S = ProCamsUtility.Convert(_focusDistance, Units.Foot, Units.Inch);
}
else
{
S = ProCamsUtility.Convert(_focusDistance, Units.Meter, Units.Inch);
}
DN = (H * S) / ( H + (S - F)); // near depth of field
DF = (H * S) / ( H - (S - F)); // far depth of field
D = DF - DN; // depth of field
if (_unitOfMeasure == UnitOfMeasure.Imperial)
{
// rounding to two decimal places
D = ProCamsUtility.Convert(D, Units.Inch, Units.Foot); // from inches to feet
D = Mathf.Floor(D * 100) / 100f;
DN = ProCamsUtility.Convert(DN, Units.Inch, Units.Foot);
DN = Mathf.Floor(DN * 100) / 100f;
DF = ProCamsUtility.Convert(DF, Units.Inch, Units.Foot);
DF = Mathf.Floor(DF * 100) / 100f;
TI = Mathf.Floor(
ProCamsUtility.Convert(
D - Mathf.Floor(D),
Units.Foot,
Units.Inch));
NI = Mathf.Floor(
ProCamsUtility.Convert(
DN - Mathf.Floor(DN),
Units.Foot,
Units.Inch));
FI = Mathf.Floor(
ProCamsUtility.Convert(
DF - Mathf.Floor(DF),
Units.Foot,
Units.Inch));
D = Mathf.Floor(D);
DN = Mathf.Floor(DN);
DF = Mathf.Floor(DF);
if (D >= 0)
EditorGUILayout.LabelField("Depth of Field", "" + D + "' " + TI + "\"");
else
EditorGUILayout.LabelField("Depth of Field", "INF");
EditorGUILayout.LabelField("Near Depth", "" + DN + "' " + NI + "\"");
if (DF >= 0)
EditorGUILayout.LabelField("Far Depth", "" + DF + "' " + FI + "\"");
else
EditorGUILayout.LabelField("Far Depth", "INF");
}
else
{
float dof = ProCamsUtility.Convert(D, Units.Inch, Units.Meter);
float dn = ProCamsUtility.Convert(DN, Units.Inch, Units.Meter);
float df = ProCamsUtility.Convert(DF, Units.Inch, Units.Meter);
if (D >= 0)
EditorGUILayout.LabelField("Depth of Field", dof.ToString("0.00") + "m");
else
EditorGUILayout.LabelField("Depth of Field", "INF");
EditorGUILayout.LabelField("Near Depth", dn.ToString("0.00") + "m");
if (DF >= 0)
EditorGUILayout.LabelField("Far Depth", df.ToString("0.00") + "m");
else
EditorGUILayout.LabelField("Far Depth", "INF");
}
}
19
View Source File : FMailIncident.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public bool Run(ServiceContext context)
{
///Определяем прошел ли срок с момента запуска последнего события
if (!AlreadyStart)
{
/*
var currentIncident = context.Player.FunctionMails
.Any(m => (m as FMailIncident)?.AlreadyStart ?? false
&& (m as FMailIncident)?.NumberOrder == NumberOrder);
*/
var currentIncident = context.Player.FunctionMails
.Where(m => m is FMailIncident)
.Cast<FMailIncident>()
.Where(m => m.AlreadyStart && m.NumberOrder == NumberOrder)
.Any();
if (currentIncident) return false;
///Перед нами в очереди никого. Начинает операцию!
///Проверяем нужно ли перед наподением предупредить
var delay = Mail.IncidentMult >= 5 ? CalcDelayStart() : 0;
SendTick = context.Player.Public.LastTick + delay;
if (delay > 0)
{
Loger.Log($"IncidentLod FMailIncident.Run 1 NO={NumberOrder} SendTick={SendTick} MailSended={MailSended} EndTick={EndTick}");
context.Player.Mails.Add(GetWarningMail(context));
return false;
}
}
///Если ожидание перед атакой прошло, то отправляем основное письмо с инциндентом
if (context.Player.Public.LastTick < SendTick) return false;
if (!MailSended)
{
Loger.Log($"IncidentLod FMailIncident.Run 2 NO={NumberOrder} SendTick={SendTick} MailSended={MailSended} EndTick={EndTick}");
var countInOrder_ = context.Player.FunctionMails.Count(m => m != this && (m as FMailIncident)?.NumberOrder == NumberOrder).ToString();
context.Player.Mails.Add(Mail);
SendTick = context.Player.Public.LastTick;
MailSended = true;
WorthBefore = GetWorthTarget(context.Player);
context.Player.AttacksWonCount++; //не прибавлять положительные инцинденты!
CallIncident.IncidentLogAppend("SendMail", Mail, $"{(int)WorthBefore};;{NumberOrder};{countInOrder_}");
return false;
}
///Уже отправили письмо. Проверяем прошла ли минимальная задержка.
if (context.Player.Public.LastTick - SendTick < ServerManager.ServerSettings.GeneralSettings.IncidentTickDelayBetween) return false;
///После суток оцениваем задержку и устанавливаем поле EndTick.
if (EndTick == 0)
{
Loger.Log($"IncidentLod FMailIncident.Run 3 NO={NumberOrder} SendTick={SendTick} MailSended={MailSended} EndTick={EndTick}");
var countInOrder_ = context.Player.FunctionMails.Count(m => m != this && (m as FMailIncident)?.NumberOrder == NumberOrder).ToString();
WorthAfter = GetWorthTarget(context.Player);
var delayAfterMail = CalcDelayEnd();
EndTick = SendTick + delayAfterMail;
if (MainHelper.DebugMode)
{
context.Player.Mails.Add(new ModelMailMessadge()
{
From = Repository.GetData.PlayerSystem.Public,
To = context.Player.Public,
type = ModelMailMessadge.MessadgeTypes.Neutral,
label = "Dev: Сутки после инциндента",
text = "Прошли сутки после инциндента. Начато ожидание на восстановление перед разблокированием очереди №"
+ NumberOrder.ToString()
+ " дней: "
+ (delayAfterMail / 60000f).ToString("N2")
+ ". Всего ещё в этой очереди: "
+ countInOrder_
});
}
CallIncident.IncidentLogAppend("DayAfterMail", Mail,
$"{(int)WorthBefore}->{(int)WorthAfter}({(int)(WorthAfter - WorthBefore)});" +
$"{(delayAfterMail / 60000f).ToString("N2")};{NumberOrder};{countInOrder_}");
}
///Просто ждем окончания EndTick и убираем себя, чтобы очистить очередь ожидания.
if (context.Player.Public.LastTick < EndTick) return false;
Loger.Log($"IncidentLod FMailIncident.Run 4 NO={NumberOrder} SendTick={SendTick} MailSended={MailSended} EndTick={EndTick}");
var countInOrder = context.Player.FunctionMails.Count(m => m != this && (m as FMailIncident)?.NumberOrder == NumberOrder).ToString();
if (MainHelper.DebugMode)
{
context.Player.Mails.Add(new ModelMailMessadge()
{
From = Repository.GetData.PlayerSystem.Public,
To = context.Player.Public,
type = ModelMailMessadge.MessadgeTypes.Neutral,
label = "Dev: Инциндент разблокировал очередь",
text = "Инциндент разблокировал очередь №"
+ NumberOrder.ToString()
+ ". Всего ещё в этой очереди: "
+ countInOrder
});
}
var worth = GetWorthTarget(context.Player);
CallIncident.IncidentLogAppend("End", Mail, $"{(int)WorthBefore}->{(int)WorthAfter}->{(int)worth}({(int)(worth - WorthBefore)});;{NumberOrder};{countInOrder}");
return true;
}
19
View Source File : Dialog_TradeOnline.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static void DrawMreplacedInfo(Rect rect, float usedMreplaced, float availableMreplaced, float lastMreplacedFlashTime = -9999f, bool alignRight = false)
{
if (usedMreplaced > availableMreplaced)
{
GUI.color = Color.red;
}
else
{
GUI.color = Color.gray;
}
string text = $" {usedMreplaced.ToString("0.##")} / {availableMreplaced.ToString("0.##")} kg";
Vector2 vector = Text.CalcSize(text);
Rect rect2;
if (alignRight)
{
rect2 = new Rect(rect.xMax - vector.x, rect.y, vector.x, vector.y);
}
else
{
rect2 = new Rect(rect.x, rect.y, vector.x, vector.y);
}
bool flag = Time.time - lastMreplacedFlashTime < 1f;
if (flag)
{
GUI.DrawTexture(rect2, TransferableUIUtility.FlashTex);
}
Widgets.Label(rect2, text);
GUI.color = Color.white;
}
19
View Source File : ONSPPropagationMaterialEditor.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void DrawDataTicks(Rect r){
const int ticks = 10;
Rect label = new Rect(r.xMax + 9, r.y - r.height / (2 * ticks), 24, r.height / ticks);
Rect tick = new Rect(r.xMax + 2, r.y - 1, 4.5f, 2);
for(int i = 0; i <= ticks; i++){
float value = MapData(1 - (float)i / ticks, false);
EditorGUI.DrawRect(tick, textStyle.normal.textColor);
GUI.Label(label, value.ToString("0.000"), textStyle);
tick.y += label.height;
label.y += label.height;
}
}
19
View Source File : SQLWriter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
protected static float? TrimNegativeZero(float? input, int places = 6)
{
if (input == null)
return null;
var str = input.Value.ToString($"0.{new string('#', places)}");
if (str == $"-0.{new string('#', places)}" || str == "-0")
str = str.Substring(1, str.Length - 1);
var ret = float.Parse(str);
return ret;
}
19
View Source File : MiniJson.cs
License : MIT License
Project Creator : AdamCarballo
License : MIT License
Project Creator : AdamCarballo
void SerializeOther(object value) {
// NOTE: decimals lose precision during serialization.
// They always have, I'm just letting you know.
// Previously floats and doubles lost precision too.
if (value is float) {
builder.Append(((float) value).ToString("R"));
} else if (value is int
|| value is uint
|| value is long
|| value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is ulong) {
builder.Append(value);
} else if (value is double
|| value is decimal) {
builder.Append(Convert.ToDouble(value).ToString("R"));
} else {
SerializeString(value.ToString());
}
}
19
View Source File : ClonesManager.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
private static void CopyDirectoryWithProgressBarRecursive(DirectoryInfo source, DirectoryInfo destination,
ref long totalBytes, ref long copiedBytes, string progressBarPrefix = "")
{
/// Directory cannot be copied into itself.
if (source.FullName.ToLower() == destination.FullName.ToLower())
{
Debug.LogError("Cannot copy directory into itself.");
return;
}
/// Calculate total bytes, if required.
if (totalBytes == 0)
{
totalBytes = ClonesManager.GetDirectorySize(source, true, progressBarPrefix);
}
/// Create destination directory, if required.
if (!Directory.Exists(destination.FullName))
{
Directory.CreateDirectory(destination.FullName);
}
/// Copy all files from the source.
foreach (FileInfo file in source.GetFiles())
{
try
{
file.CopyTo(Path.Combine(destination.ToString(), file.Name), true);
}
catch (IOException)
{
/// Some files may throw IOException if they are currently open in Unity editor.
/// Just ignore them in such case.
}
/// Account the copied file size.
copiedBytes += file.Length;
/// Display the progress bar.
float progress = (float)copiedBytes / (float)totalBytes;
bool cancelCopy = EditorUtility.DisplayCancelableProgressBar(
progressBarPrefix + "Copying '" + source.FullName + "' to '" + destination.FullName + "'...",
"(" + (progress * 100f).ToString("F2") + "%) Copying file '" + file.Name + "'...",
progress);
if (cancelCopy) return;
}
/// Copy all nested directories from the source.
foreach (DirectoryInfo sourceNestedDir in source.GetDirectories())
{
DirectoryInfo nextDestingationNestedDir = destination.CreateSubdirectory(sourceNestedDir.Name);
ClonesManager.CopyDirectoryWithProgressBarRecursive(sourceNestedDir, nextDestingationNestedDir,
ref totalBytes, ref copiedBytes, progressBarPrefix);
}
}
19
View Source File : BombDefusal.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
private void FixedUpdate() {
if (defusing) {
fillPercentage -= defusalAmount;
fillPercentage = Mathf.Clamp(fillPercentage, 0f, 1f);
mat.SetFloat("_Fillpercentage", fillPercentage);
timerText.text = "00:0" + (fillPercentage*defusalTime).ToString("F3");
if (fillPercentage <= 0f) {
bombDefused();
}
}
}
19
View Source File : MotionBlurModelEditor.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public void DrawShutterGraph(float angle)
{
var center = GUILayoutUtility.GetRect(128, k_Height).center;
// Parameters used to make transitions smooth.
var zeroWhenOff = Mathf.Min(1f, angle * 0.1f);
var zeroWhenFull = Mathf.Min(1f, (360f - angle) * 0.02f);
// Shutter angle graph
var discCenter = center - new Vector2(k_Height * 2.4f, 0f);
// - exposure duration indicator
DrawDisc(discCenter, k_Height * Mathf.Lerp(0.5f, 0.38f, zeroWhenFull), m_ColorGray);
// - shutter disc
DrawDisc(discCenter, k_Height * 0.16f * zeroWhenFull, m_ColorDark);
// - shutter blade
DrawArc(discCenter, k_Height * 0.5f, 360f - angle, m_ColorDark);
// - shutter axis
DrawDisc(discCenter, zeroWhenOff, m_ColorGray);
// Shutter label (off/full)
var labelSize = new Vector2(k_Height, k_Height);
var labelOrigin = discCenter - labelSize * 0.5f;
var labelRect = new Rect(labelOrigin, labelSize);
if (Mathf.Approximately(angle, 0f))
GUI.Label(labelRect, "Off", m_MiddleCenterStyle);
else if (Mathf.Approximately(angle, 360f))
GUI.Label(labelRect, "Full", m_MiddleCenterStyle);
// Exposure time bar graph
var outerBarSize = new Vector2(4.75f, 0.5f) * k_Height;
var innerBarSize = outerBarSize;
innerBarSize.x *= angle / 360f;
var barCenter = center + new Vector2(k_Height * 0.9f, 0f);
var barOrigin = barCenter - outerBarSize * 0.5f;
DrawRect(barOrigin, outerBarSize, m_ColorDark);
DrawRect(barOrigin, innerBarSize, m_ColorGray);
var barText = "Exposure time = " + (angle / 3.6f).ToString("0") + "% of ΔT";
GUI.Label(new Rect(barOrigin, outerBarSize), barText, m_MiddleCenterStyle);
}
19
View Source File : MotionBlurModelEditor.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
public void DrawBlendingGraph(float strength)
{
var center = GUILayoutUtility.GetRect(128, k_Height).center;
var iconSize = new Vector2(k_Height, k_Height);
var iconStride = new Vector2(k_Height * 0.9f, 0f);
var iconOrigin = center - iconSize * 0.5f - iconStride * 2f;
for (var i = 0; i < 5; i++)
{
var weight = BlendingWeight(strength, i / 60f);
var rect = new Rect(iconOrigin + iconStride * i, iconSize);
var color = m_ColorGray;
color.a = weight;
GUI.color = color;
GUI.Label(rect, m_BlendingIcon);
GUI.color = Color.white;
GUI.Label(rect, (weight * 100).ToString("0") + "%", m_LowerCenterStyle);
}
// EditorGUIUtility.isProSkin
}
19
View Source File : HealBar.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
void FixedUpdate () {
//IF HOLDING H
if (Input.GetKey(KeyCode.E)) {
//IF STILL NOT FULL
setTextColor();
if (fillPercentage < 1f) {
fillPercentage += increaseAmount;
fillPercentage = Mathf.Clamp(fillPercentage, 0f, 1f);
mat.SetFloat("_Fillpercentage", fillPercentage);
countDowntext.gameObject.SetActive(true);
countDowntext.text = (fillTime * (1 - fillPercentage)).ToString("F1");
}
else {
countDowntext.gameObject.SetActive(false);
}
}
else {
resetTextColor();
if (fillPercentage > 0f) {
countDowntext.gameObject.SetActive(true);
fillPercentage -= decreaseAmount;
fillPercentage = Mathf.Clamp(fillPercentage, 0f, 1f);
mat.SetFloat("_Fillpercentage", fillPercentage);
countDowntext.text = (fillTime * (1 - fillPercentage)).ToString("F1");
}
else {
countDowntext.gameObject.SetActive(false);
}
}
}
19
View Source File : SpeedBar.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
private void setText() {
speedValueText.text = (fillPercentage*maxSpeed).ToString("F0");
}
19
View Source File : TimeController.cs
License : MIT License
Project Creator : AdultLink
License : MIT License
Project Creator : AdultLink
private void setTimescale() {
timeScale = Mathf.Clamp(timeScale, 0f, 1f);
timeSlider.sizeDelta = new Vector2 (timeScale * initialWidth, initialHeight);
timeText.text = timeScale.ToString("F1");
Time.timeScale = timeScale;
}
19
View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void Apply()
{
forcedChange = false;
if (nextFloats != null)
{
for (int i = 0; i < nextFloats.Length; i++)
{
if (float.TryParse(floatStrings[i], out float val))
{
nextFloats[i] = val;
}
}
}
if (nextIntegers != null)
{
for (int i = 0; i < nextIntegers.Length; i++)
{
if (int.TryParse(integerStrings[i], out int val))
{
nextIntegers[i] = val;
}
}
}
onApplyCallback(this, state, nextSelection, nextFloats, nextIntegers);
appliedState = state;
if (nextSelection >= 0)
{
appliedSelection = nextSelection + 1;
}
if (nextFloats != null)
{
for (int i = 0; i < nextFloats.Length; i++)
{
appliedFloats[i] = nextFloats[i];
floatStrings[i] = nextFloats[i].ToString("F2");
}
}
if (nextIntegers != null)
{
for (int i = 0; i < nextIntegers.Length; i++)
{
appliedIntegers[i] = nextIntegers[i];
integerStrings[i] = nextIntegers[i].ToString();
}
}
onStateChanged(this, state, false);
}
19
View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public override string ToString()
{
List<object> args = new List<object>();
if (nextSelection >= 0)
{
args.Add(english.GetArray(key + "Selection")[nextSelection]);
}
if (nextFloats != null)
{
for (int i = 0; i < nextFloats.Length; i++)
{
args.Add(GetFloat(i).ToString("F2"));
}
}
if (nextIntegers != null)
{
for (int i = 0; i < nextIntegers.Length; i++)
{
args.Add(GetInt(i).ToString());
}
}
string format = english.Get(key + "Info" + (state ? "Enabled" : "Disabled")).Replace(@"\n", System.Environment.NewLine);
if (state)
{
if (GameModes.EnabledColor.Value.Length != 6)
{
GameModes.EnabledColor.Value = "CCFFCC";
}
format = format.Replace("$eColor$", GameModes.EnabledColor.Value);
}
else
{
if (GameModes.DisabledColor.Value.Length != 6)
{
GameModes.DisabledColor.Value = "FFAACC";
}
format = format.Replace("$dColor$", GameModes.DisabledColor.Value);
}
return string.Format(format, args.ToArray());
}
19
View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public string ToStringLocal()
{
List<object> args = new List<object>();
if (nextSelection >= 0)
{
args.Add(Lang.GetArray(key + "Selection")[nextSelection]);
}
if (nextFloats != null)
{
for (int i = 0; i < nextFloats.Length; i++)
{
args.Add(GetFloat(i).ToString("F2"));
}
}
if (nextIntegers != null)
{
for (int i = 0; i < nextIntegers.Length; i++)
{
args.Add(GetInt(i).ToString());
}
}
string format = Lang.Get(key + "Info" + (state ? "Enabled" : "Disabled")).Replace(@"\n", System.Environment.NewLine);
if (state)
{
if (GameModes.EnabledColor.Value.Length != 6)
{
GameModes.EnabledColor.Value = "CCFFCC";
}
format = format.Replace("$eColor$", GameModes.EnabledColor.Value);
}
else
{
if (GameModes.DisabledColor.Value.Length != 6)
{
GameModes.DisabledColor.Value = "FFAACC";
}
format = format.Replace("$dColor$", GameModes.DisabledColor.Value);
}
return string.Format(format, args.ToArray());
}
19
View Source File : GameModeSetting.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void Load()
{
IDataStorage storage = Settings.Storage;
state = storage.GetBool(saveKey + "State", false);
if (nextSelection >= 0)
{
nextSelection = storage.GetInt(saveKey + "Selection", nextSelection);
}
if (nextFloats != null)
{
floatStrings = new string[nextFloats.Length];
appliedFloats = new float[nextFloats.Length];
for (int i = 0; i < nextFloats.Length; i++)
{
floatStrings[i] = storage.GetFloat(saveKey + "Float" + i.ToString(), nextFloats[i]).ToString();
if (!float.TryParse(floatStrings[i], out float val))
{
floatStrings[i] = nextFloats[i].ToString("F2");
}
else
{
nextFloats[i] = val;
}
appliedFloats[i] = nextFloats[i];
}
}
if (nextIntegers != null)
{
integerStrings = new string[nextIntegers.Length];
appliedIntegers = new int[nextIntegers.Length];
for (int i = 0; i < nextIntegers.Length; i++)
{
integerStrings[i] = storage.GetInt(saveKey + "Int" + i.ToString(), nextIntegers[i]).ToString();
if (!int.TryParse(integerStrings[i], out int val))
{
integerStrings[i] = nextIntegers[i].ToString();
}
else
{
nextIntegers[i] = val;
}
appliedIntegers[i] = nextIntegers[i];
}
}
}
19
View Source File : SingleRunStats.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public override string ToString()
{
var bld = new StringBuilder();
bld.AppendLine($"Time: {TimeStamp.ToString("F3")}, last kill at {LastKillTime.ToString("F2")}");
bld.AppendLine($"Name: {Name}");
bld.AppendLine($"Statistics");
bld.AppendLine($"Kills: {Kills}. Average kill time: {KillTimeAverage.ToString("F2")}");
bld.AppendLine($"Total damage: {TotalDamage}. Average total damage: {TotalPerKill.ToString("F2")}");
bld.AppendLine($"Max damage: {MaxDamage}");
bld.AppendLine($"Misc statistics");
bld.AppendLine($"Physics update: {UnityEngine.Mathf.RoundToInt(1f / FixedDeltaTime)}/sec. ({FixedDeltaTime.ToString("F3")} ms)");
bld.AppendLine($"Refills. Refills count: {GasRefillsCount}. Last refill at: {LastRefill.ToString("F2")}");
bld.AppendLine($"Reloads. Reloads count: {Reloads}. Last reload at: {LastReload.ToString("F2")}");
bld.AppendLine($"Hero stats. Name: {Stats.name}");
bld.AppendLine($"Spd: {Stats.Spd}, Bla: {Stats.Bla}, Acl {Stats.Acl}, Gas: {Stats.Acl}, Skill: {Stats.skillID}");
bld.AppendLine($"Anarchy version: {Version}");
return bld.ToString();
}
19
View Source File : PauseWindow.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
protected internal override void Draw()
{
string label = PauseWaitTime <= 3f ? locale.Format("unpausing", PauseWaitTime.ToString("F1")) : locale["pauseEnabled"];
GUI.Box(windowRect, string.Empty);
GUI.LabelCenter(windowRect, label);
}
19
View Source File : AutoScaleFloat.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public override string ToString()
{
return Value.ToString("F2");
}
19
View Source File : GameLogic.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
protected virtual void UpdateRespawnTime()
{
if ((IN_GAME_MAIN_CAMERA.MainCamera.gameOver && !FengGameManagerMKII.FGM.needChooseSide) && (FengGameManagerMKII.Level.RespawnMode == RespawnMode.DEATHMATCH || GameModes.EndlessRespawn.Enabled || ((GameModes.BombMode.Enabled || GameModes.BladePvp.Enabled) && GameModes.PointMode.Enabled)) && !SpectateCommand.IsInSpecMode)
{
this.MyRespawnTime += UpdateInterval;
int num = 10;
if (PhotonNetwork.player.Isreplacedan)
{
num = 15;
}
if (GameModes.EndlessRespawn.Enabled)
{
num = GameModes.EndlessRespawn.GetInt(0);
}
Labels.Center += "\n" + Lang.Format("respawnTime", (num - MyRespawnTime).ToString("F0")) + "\n\n";
if (this.MyRespawnTime > (float)num)
{
this.MyRespawnTime = 0f;
IN_GAME_MAIN_CAMERA.MainCamera.gameOver = false;
if (PhotonNetwork.player.Isreplacedan)
{
FengGameManagerMKII.FGM.SpawnNonAireplacedan(FengGameManagerMKII.FGM.myLastHero, "replacedanRespawn");
}
else
{
FengGameManagerMKII.FGM.SpawnPlayer(FengGameManagerMKII.FGM.myLastHero);
}
IN_GAME_MAIN_CAMERA.MainCamera.gameOver = false;
Labels.Center = string.Empty;
}
}
}
19
View Source File : RacingLogic.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public void OnPlayerFinished(float time, string name)
{
//if (finishers.Count >= MaxFinishers)
//{
// return;
//}
if (!Round.IsWinning)
{
finishers.Clear();
GameWin();
}
lock (finishers)
{
finishers.Add(Lang.Format("racingPlayerResult", (finishers.Count + 1).ToString(), name.ToHTMLFormat(), time.ToString("F2")));
UpdateLabels();
OnUpdateRacingResult();
}
}
19
View Source File : RacingLogic.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
protected override void UpdateLabels()
{
if (RaceStart)
{
topCenter = Lang.Format("time", (Round.Time - StartTime).ToString("F1"));
if (PhotonNetwork.IsMasterClient && GameModes.RacingTimeLimit.Enabled)
{
if ((Round.Time - StartTime) >= GameModes.RacingTimeLimit.GetInt(0))
{
FengGameManagerMKII.FGM.RestartGame(false, false);
return;
}
}
if (!Multiplayer)
{
float currentSpeed = IN_GAME_MAIN_CAMERA.MainR.velocity.magnitude;
maxSpeed = Mathf.Max(maxSpeed, currentSpeed);
Labels.TopLeft = Lang.Format("speedLabel", currentSpeed.ToString("F2"), maxSpeed.ToString("F2"));
}
center = "";
if (Round.IsWinning)
{
if (needShowFinishers)
{
center += GetFinishers() + "\n\n";
}
if (Multiplayer)
{
topCenter += "\n\n" + Lang.Format("racingRestart", Round.GameEndCD.ToString("F0"));
}
}
}
else
{
topCenter = Lang["racingWaiting"] + "\n";
center = "";
if (Multiplayer && CurrentRound > 1 && GetFinishers().Length > 0)
{
center += Lang["racingLastResult"] + "\n";
center += GetFinishers();
center += "\n\n";
}
topCenter += "\n" + Lang.Format("racingRemaining", (StartTime - Round.Time).ToString("F1"));
}
Labels.TopCenter = topCenter;
Labels.Center = center;
center = "";
topCenter = "";
}
19
View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string ToFixLenString(this float d, int len, int dit)
{
var s = d.ToString("F" + dit);
var sb = new StringBuilder();
var l = len - s.Length;
if (l > 0)
sb.Append(' ', l);
sb.Append(s);
return sb.ToString();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
static void Measure<T>(string text, bool warmup, Func<T> func)
{
if (warmup)
{
Console.WriteLine($"Warming up... ");
func.Invoke();
return;
}
Console.Write($"Measuring... ");
sw_.Restart();
T r = func.Invoke();
float elapsedMicroseconds = sw_.ElapsedMicroseconds();
if (!results_.ContainsKey(text))
results_[text] = new List<float>();
results_[text].Add(elapsedMicroseconds);
Console.WriteLine($"it took {elapsedMicroseconds.ToString("f0").PadLeft(5)} µs to {text}. Result: {r}");
}
19
View Source File : GvrFPS.cs
License : MIT License
Project Creator : alanplotko
License : MIT License
Project Creator : alanplotko
void LateUpdate() {
float deltaTime = Time.unscaledDeltaTime;
float interp = deltaTime / (0.5f + deltaTime);
float currentFPS = 1.0f / deltaTime;
fps = Mathf.Lerp(fps, currentFPS, interp);
float msf = MS_PER_SEC / fps;
textField.text = string.Format(DISPLAY_TEXT_FORMAT,
msf.ToString(MSF_FORMAT), Mathf.RoundToInt(fps));
}
19
View Source File : SpeedChecker.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
private static void DrawVehicleInfo(object sender, GraphicsEventArgs e)
{
if (CurrentSpeedCheckerState == SpeedCheckerStates.FixedPoint)
{
Rectangle drawRect = new Rectangle(1, 250, 230, 117);
e.Graphics.DrawRectangle(drawRect, Color.FromArgb(200, Color.Black));
e.Graphics.DrawText("Plate: " + TargetLicencePlate, "Arial Bold", 20.0f, new PointF(3f, 253f), Color.White, drawRect);
e.Graphics.DrawText("Model: " + TargetModel, "Arial Bold", 20.0f, new PointF(3f, 278f), Color.White, drawRect);
e.Graphics.DrawText("Speed: " + TargetSpeed + " " + SpeedUnit, "Arial Bold", 20.0f, new PointF(3f, 303f), SpeedColour, drawRect);
//e.Graphics.DrawText(TargetSpeedLimit, "Arial Bold", 15.0f, new PointF(3f, 293f), Color.White, drawRect);
e.Graphics.DrawText("Flags: " + TargetFlag, "Arial Bold", 20.0f, new PointF(3f, 328f), FlagsTextColour, drawRect);
}
else if (CurrentSpeedCheckerState == SpeedCheckerStates.Speedgun)
{
Rectangle drawRect = new Rectangle(1, 250, 230, 70);
e.Graphics.DrawRectangle(drawRect, Color.FromArgb(200, Color.Black));
e.Graphics.DrawText("Model: " + TargetModel, "Arial Bold", 20.0f, new PointF(3f, 253f), Color.White, drawRect);
e.Graphics.DrawText("Speed: " + TargetSpeed + " " + SpeedUnit, "Arial Bold", 20.0f, new PointF(3f, 278f), SpeedColour, drawRect);
}
else if (CurrentSpeedCheckerState == SpeedCheckerStates.Average)
{
Rectangle drawRect = new Rectangle(1, 250, 230, 117);
e.Graphics.DrawRectangle(drawRect, Color.FromArgb(200, Color.Black));
e.Graphics.DrawText("D: " + AverageSpeedCheckDistance + "m", "Arial Bold", 20.0f, new PointF(3f, 253f), Color.White, drawRect);
e.Graphics.DrawText("T: " + AverageSpeedCheckSecondsPreplaceded.ToString("N2") + "s", "Arial Bold", 20.0f, new PointF(3f, 278f), Color.White, drawRect);
e.Graphics.DrawText("O: " + AverageSpeedCheckCurrentSpeed + " " + SpeedUnit, "Arial Bold", 20.0f, new PointF(3f, 303f), Color.White, drawRect);
e.Graphics.DrawText("S: " + AverageSpeed.ToString("N2") + " " + SpeedUnit, "Arial Bold", 20.0f, new PointF(3f, 328f), AverageSpeedCheckerColor, drawRect);
}
}
19
View Source File : Breathalyzer.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
internal static void TestNearestPedForAlcohol()
{
if (!Game.LocalPlayer.Character.IsInAnyVehicle(false) && !TrafficPolicerHandler.PerformingImpairmentTest)
{
TrafficPolicerHandler.PerformingImpairmentTest = true;
GameFiber.StartNew(delegate
{
Ped[] nearbypeds = Game.LocalPlayer.Character.GetNearbyPeds(1);
if (nearbypeds.Length != 0)
{
Ped nearestPed = nearbypeds[0];
if (nearestPed.Exists())
{
if (Vector3.Distance(nearestPed.Position, Game.LocalPlayer.Character.Position) < 2.5f && nearestPed.RelationshipGroup != "COP" && nearestPed.RelationshipGroup != "PLAYER" && nearestPed.IsHuman)
{
Game.LocalPlayer.Character.Inventory.GiveNewWeapon("WEAPON_UNARMED", 1, true);
AddPedToDictionaries(nearestPed);
AlcoholLevels PedAlcoholLevel = PedAlcoholLevels[nearestPed.Handle];
float Reading = DetermineAlcoholReading(nearestPed, PedAlcoholLevel);
try
{
if (!nearestPed.IsInAnyVehicle(false))
{
nearestPed.BlockPermanentEvents = true;
nearestPed.IsPersistent = true;
}
Rage.Native.NativeFunction.Natives.SET_PED_STEALTH_MOVEMENT(Game.LocalPlayer.Character, 0, 0);
Vector3 directionFromPedToNearest = (nearestPed.Position - Game.LocalPlayer.Character.Position);
directionFromPedToNearest.Normalize();
if (!nearestPed.IsInAnyVehicle(false))
{
nearestPed.Tasks.AchieveHeading(MathHelper.ConvertDirectionToHeading(directionFromPedToNearest) + 180f).WaitForCompletion(1500);
}
//Game.LocalPlayer.Character.Tasks.GoStraightToPosition(nearestPed.Position, MathHelper.ConvertDirectionToHeading(directionFromPedToNearest), 0.9f).WaitForCompletion(600);
directionFromPedToNearest = (nearestPed.Position - Game.LocalPlayer.Character.Position);
directionFromPedToNearest.Normalize();
Game.LocalPlayer.Character.Tasks.AchieveHeading(MathHelper.ConvertDirectionToHeading(directionFromPedToNearest)).WaitForCompletion(1600);
if (nearestPed.IsInAnyVehicle(false))
{
//Game.LocalPlayer.Character.Tasks.PlayAnimation("missfbi3_party_b", "walk_to_balcony_male2", 0.5f, AnimationFlags.None).WaitForCompletion(500);
Game.LocalPlayer.Character.Tasks.PlayAnimation("amb@code_human_police_investigate@idle_b", "idle_e", 2f, 0);
if(!nearestPed.CurrentVehicle.IsBike)
{
nearestPed.Tasks.PlayAnimation("amb@incar@male@smoking_low@idle_a", "idle_a", 2f, 0);
}
GameFiber.Sleep(2000);
}
else
{
nearestPed.Tasks.PlayAnimation("switch@michael@smoking", "michael_smoking_loop", 2f, AnimationFlags.SecondaryTask).WaitForCompletion(8000);
Game.LocalPlayer.Character.Tasks.Clear();
}
}
catch (Exception e) { }
finally
{
//GameFiber.Sleep(1800);
//Game.LocalPlayer.Character.Tasks.ClearImmediately();
uint noti = Game.DisplayNotification("Waiting for ~b~breathalyzer~s~ result...");
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "Breathalyzer tests conducted");
}
GameFiber.Sleep(3000);
Game.LocalPlayer.Character.Tasks.Clear();
Game.RemoveNotification(noti);
if (Reading == -1)
{
Game.DisplayNotification("The person ~r~failed to provide ~s~ a valid breath sample.");
}
else
{
Game.DisplayNotification("~b~Alcohol Reading: " + DetermineColourCode(PedAlcoholLevel) + Reading.ToString("n" + CountDigitsAfterDecimal(AlcoholLimit)) + AlcoholLimitUnit + ".~n~~b~Limit: " + AlcoholLimit.ToString() + "" + AlcoholLimitUnit + ".");
}
TrafficPolicerHandler.PerformingImpairmentTest = false;
if (nearestPed.Exists())
{
if (!nearestPed.IsInAnyVehicle(false))
{
if (nearestPed.LastVehicle.Exists())
{
if (nearestPed.DistanceTo(nearestPed.LastVehicle) < 20f)
{
if (IsPedOverTheLimit(nearestPed) && !TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Contains(nearestPed))
{
TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Add(nearestPed);
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "People caught driving over alcohol limit");
}
}
}
}
nearestPed.Tasks.StandStill(7000).WaitForCompletion(7000);
if (nearestPed.Exists())
{
if (!Functions.IsPedGettingArrested(nearestPed) && !Functions.IsPedArrested(nearestPed) && !Functions.IsPedStoppedByPlayer(nearestPed))
{
nearestPed.Dismiss();
}
}
}
else if (nearestPed.CurrentVehicle.Driver == nearestPed)
{
if (IsPedOverTheLimit(nearestPed) && !TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Contains(nearestPed))
{
TrafficPolicerHandler.PedsToChargeWithDrinkDriving.Add(nearestPed);
if (TrafficPolicerHandler.IsLSPDFRPlusRunning)
{
API.LSPDFRPlusFunctions.AddCountToStatistic(Main.PluginName, "People caught driving over alcohol limit");
}
}
}
}
}
}
}
}
TrafficPolicerHandler.PerformingImpairmentTest = false;
});
}
}
19
View Source File : MixtureNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
internal virtual string FormatProcessingTime(float time) => time.ToString("F2") + " ms";
19
View Source File : BiomeSwitchListDrawer.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
public void OnGUI(BiomeData biomeData)
{
base.OnGUI(new Rect());
if (biomeReparreplacedionPreview == null)
{
biomeReparreplacedionPreview = new Texture2D(previewTextureWidth, 1);
UpdateBiomeReparreplacedionPreview(biomeData);
}
using (DefaultGUISkin.Get())
{
reorderableSwitchDataList.DoLayoutList();
}
EditorGUILayout.LabelField("reparreplacedion map: (" + localCoveragePercent.ToString("F1") + "%)");
Rect previewRect = EditorGUILayout.GetControlRect(GUILayout.ExpandWidth(true), GUILayout.Height(0));
previewRect.height = previewTextureHeight;
GUILayout.Space(previewTextureHeight);
PWGUI.TexturePreview(previewRect, biomeReparreplacedionPreview, false);
PWGUI.SetScaleModeForField(PWGUIFieldType.Sampler2DPreview, -1, ScaleMode.StretchToFill);
}
19
View Source File : OutputNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
internal override string FormatProcessingTime(float time) => "total: " + time.ToString("F2") + " ms";
19
View Source File : CircleRadiansView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
void UpdateOutputRadians(int count)
{
node.outputRadians = new List<float>();
listContainer.Clear();
for (int i = 0; i < count; i++)
{
float r = (Mathf.PI * 2 / count) * i;
node.outputRadians.Add(r);
listContainer.Add(new Label(r.ToString("F3")));
}
}
19
View Source File : ProceduralWorldsGUI.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
void DrawBiomeMapDebugBox(BiomeData biomeData, Vector2 pixelPos, Sampler terrain)
{
int x = (int)Mathf.Clamp(pixelPos.x, 0, terrain.size - 1);
int y = (int)Mathf.Clamp(pixelPos.y, 0, terrain.size - 1);
BiomeBlendPoint point = biomeData.biomeMap.GetBiomeBlendInfo(x, y);
EditorGUILayout.BeginVertical(Styles.debugBox);
{
for (int i = 0; i < point.length; i++)
{
short biomeId = point.biomeIds[i];
float biomeBlend = point.biomeBlends[i];
PartialBiome biome = biomeData.biomeSwitchGraph.GetBiome(biomeId);
if (biome == null)
continue ;
EditorGUILayout.LabelField("Biome " + i + " (id: " + biomeId + "):" + biome.name);
EditorGUI.indentLevel++;
for (int j = 0; j < biomeData.length; j++)
{
float val = biomeData.GetSampler2D(j)[x, y];
EditorGUILayout.LabelField(biomeData.GetBiomeKey(j) + ": " + val);
}
EditorGUILayout.LabelField("blend: " + (biomeBlend * 100).ToString("F1") + "%");
EditorGUI.indentLevel--;
}
EditorGUILayout.LabelField("Total blend: " + point.totalBlend);
}
EditorGUILayout.EndVertical();
}
19
View Source File : RespawnView.cs
License : MIT License
Project Creator : alerdenisov
License : MIT License
Project Creator : alerdenisov
public void RespawnWait(float time)
{
respawnTimer.text = time.ToString("0.00");
}
19
View Source File : TimerController.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
string FormatTime(float currentTime) {
float minute = Mathf.Floor(currentTime / 60);
float second = Mathf.Floor(currentTime - minute * 60);
float centi = Mathf.Floor(100 * (currentTime - minute * 60 - second));
return minute.ToString("00")+ ":" + second.ToString("00")+ ":" + centi.ToString("00");
}
19
View Source File : InputPort.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void UpdateInternalDataFromVariables( bool forceDecimal = false )
{
switch( m_dataType )
{
case WirePortDataType.OBJECT:
case WirePortDataType.FLOAT:
{
if( forceDecimal && m_previewInternalFloat == (int)m_previewInternalFloat )
m_internalData = m_previewInternalFloat.ToString("0.0##############"); // to make sure integer values like 0 or 1 are generated as 0.0 and 1.0
else
m_internalData = m_previewInternalFloat.ToString();
m_internalDataWrapper = string.Empty;
}
break;
case WirePortDataType.INT:
{
m_internalData = m_previewInternalInt.ToString();
m_internalDataWrapper = string.Empty;
}
break;
case WirePortDataType.FLOAT2:
{
m_internalData = m_previewInternalVec2.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec2.y.ToString();
m_internalDataWrapper = "float2( {0} )";
}
break;
case WirePortDataType.FLOAT3:
{
m_internalData = m_previewInternalVec3.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec3.y.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec3.z.ToString();
m_internalDataWrapper = "float3( {0} )";
}
break;
case WirePortDataType.FLOAT4:
{
m_internalData = m_previewInternalVec4.x.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.y.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.z.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalVec4.w.ToString();
m_internalDataWrapper = "float4( {0} )";
}
break;
case WirePortDataType.COLOR:
{
m_internalData = m_previewInternalColor.r.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.g.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.b.ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalColor.a.ToString();
m_internalDataWrapper = "float4( {0} )";
}
break;
case WirePortDataType.FLOAT3x3:
case WirePortDataType.FLOAT4x4:
{
m_internalData = m_previewInternalMatrix4x4[ 0, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 0, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 1, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 1, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 2, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 2, 3 ].ToString() + IOUtils.VECTOR_SEPARATOR +
m_previewInternalMatrix4x4[ 3, 0 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 1 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 2 ].ToString() + IOUtils.VECTOR_SEPARATOR + m_previewInternalMatrix4x4[ 3, 3 ].ToString();
if( m_dataType == WirePortDataType.FLOAT3x3 )
m_internalDataWrapper = "float3x3( {0} )";
else
m_internalDataWrapper = "float4x4( {0} )";
}
break;
}
}
19
View Source File : Simulation.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
protected void OnGUI()
{
if ( m_simulation == null )
return;
if ( !NativeHandler.Instance.HasValidLicense ) {
GUILayout.Window( GUIUtility.GetControlID( FocusType.Preplacedive ),
new Rect( new Vector2( 16,
0.5f * Screen.height ),
new Vector2( Screen.width - 32, 32 ) ),
id =>
{
// Invalid license if initialized.
if ( NativeHandler.Instance.Initialized && agx.Runtime.instance().getStatus().Length > 0 )
GUILayout.Label( Utils.GUI.MakeLabel( "AGX Dynamics: " + agx.Runtime.instance().getStatus(),
Color.red,
18,
true ),
Utils.GUI.Skin.label );
else
GUILayout.Label( Utils.GUI.MakeLabel( "AGX Dynamics: Errors occurred during initialization of AGX Dynamics.",
Color.red,
18,
true ),
Utils.GUI.Skin.label );
},
"AGX Dynamics not properly initialized",
Utils.GUI.Skin.window );
return;
}
if ( m_statisticsWindowData == null )
return;
var simColor = Color.Lerp( Color.white, Color.blue, 0.2f );
var spaceColor = Color.Lerp( Color.white, Color.green, 0.2f );
var dynamicsColor = Color.Lerp( Color.white, Color.yellow, 0.2f );
var eventColor = Color.Lerp( Color.white, Color.cyan, 0.2f );
var dataColor = Color.Lerp( Color.white, Color.magenta, 0.2f );
var memoryColor = Color.Lerp( Color.white, Color.red, 0.2f );
var labelStyle = m_statisticsWindowData.LabelStyle;
var stats = agx.Statistics.instance();
var simTime = stats.getTimingInfo( "Simulation", "Step forward time" );
var spaceTime = stats.getTimingInfo( "Simulation", "Collision-detection time" );
var dynamicsSystemTime = stats.getTimingInfo( "Simulation", "Dynamics-system time" );
var preCollideTime = stats.getTimingInfo( "Simulation", "Pre-collide event time" );
var preTime = stats.getTimingInfo( "Simulation", "Pre-step event time" );
var postTime = stats.getTimingInfo( "Simulation", "Post-step event time" );
var lastTime = stats.getTimingInfo( "Simulation", "Last-step event time" );
var contactEventsTime = stats.getTimingInfo( "Simulation", "Triggering contact events" );
var numBodies = m_system.getRigidBodies().Count;
var numShapes = m_space.getGeometries().Count;
var numConstraints = m_system.getConstraints().Count +
m_space.getGeometryContacts().Count;
var numParticles = Native.getParticleSystem() != null ?
(int)Native.getParticleSystem().getNumParticles() :
0;
GUILayout.Window( m_statisticsWindowData.Id,
DisplayMemoryAllocations ? m_statisticsWindowData.RectMemoryEnabled : m_statisticsWindowData.Rect,
id =>
{
StatisticsLabel( "Total time: ", simTime, simColor, labelStyle, true );
StatisticsLabel( " - Pre-collide step: ", preCollideTime, eventColor, labelStyle );
StatisticsLabel( " - Collision detection: ", spaceTime, spaceColor, labelStyle );
StatisticsLabel( " - Contact event: ", contactEventsTime, eventColor, labelStyle );
StatisticsLabel( " - Pre step: ", preTime, eventColor, labelStyle );
StatisticsLabel( " - Dynamics solvers: ", dynamicsSystemTime, dynamicsColor, labelStyle );
StatisticsLabel( " - Post step: ", postTime, eventColor, labelStyle );
StatisticsLabel( " - Last step: ", lastTime, eventColor, labelStyle );
StatisticsLabel( "Data: ", dataColor, labelStyle, true );
StatisticsLabel( " - Update frequency: ", (int)( 1.0f / TimeStep + 0.5f ) + " Hz", dataColor, labelStyle );
StatisticsLabel( " - Number of bodies: ", numBodies.ToString(), dataColor, labelStyle );
StatisticsLabel( " - Number of shapes: ", numShapes.ToString(), dataColor, labelStyle );
StatisticsLabel( " - Number of constraints: ", numConstraints.ToString(), dataColor, labelStyle );
StatisticsLabel( " - Number of particles: ", numParticles.ToString(), dataColor, labelStyle );
GUILayout.Space( 12 );
StatisticsLabel( "StepForward (managed):", memoryColor, labelStyle, true );
StatisticsLabel( " - Step forward: ",
m_statisticsWindowData.ManagedStepForward.ToString( "0.00" ).PadLeft( 5, ' ' ) + " ms",
memoryColor,
labelStyle );
if ( !DisplayMemoryAllocations )
return;
StatisticsLabel( "Allocations (managed):", memoryColor, labelStyle, true );
StatisticsLabel( " - Pre step callbacks: ",
MemoryAllocations.GetDeltaString( MemoryAllocations.Section.PreStepForward ).PadLeft( 6, ' ' ),
memoryColor,
labelStyle );
StatisticsLabel( " - Pre synchronize: ",
MemoryAllocations.GetDeltaString( MemoryAllocations.Section.PreSynchronizeTransforms ).PadLeft( 6, ' ' ),
memoryColor,
labelStyle );
StatisticsLabel( " - Step forward: ",
MemoryAllocations.GetDeltaString( MemoryAllocations.Section.StepForward ).PadLeft( 6, ' ' ),
memoryColor,
labelStyle );
StatisticsLabel( " - Post synchronize: ",
MemoryAllocations.GetDeltaString( MemoryAllocations.Section.PostSynchronizeTransforms ).PadLeft( 6, ' ' ),
memoryColor,
labelStyle );
StatisticsLabel( " - Post step callbacks: ",
MemoryAllocations.GetDeltaString( MemoryAllocations.Section.PostStepForward ).PadLeft( 6, ' ' ),
memoryColor,
labelStyle );
},
"AGX Dynamics statistics",
m_statisticsWindowData.WindowStyle );
}
19
View Source File : GeneratorWorker.cs
License : MIT License
Project Creator : AliTsuki
License : MIT License
Project Creator : AliTsuki
public static void CreateNormalMap(IProgress<string> progressLabelText, IProgress<int> progressBarValue, IProgress<string> progressLabelDetailText)
{
CurrentProgress = 0;
MaximumPixelsToCheck = (nmg.ImageWidth * nmg.ImageHeight) + 1;
progressLabelText.Report("In Progress...");
try
{
CurrentProgress = 1;
for(int x = 0; x < nmg.ImageWidth; x++)
{
for(int y = 0; y < nmg.ImageHeight; y++)
{
nmg.cToken.ThrowIfCancellationRequested();
Color currentPixelColor = nmg.OriginalImageBitmap.GetPixel(x, y);
if(IsColorWithinColorDistance(currentPixelColor, ColorType.Background))
{
nmg.NormalMapImageBitmap.SetPixel(x, y, nmg.DefaultNormalMapBGColor);
}
else if(IsColorWithinColorDistance(currentPixelColor, ColorType.Separator))
{
nmg.NormalMapImageBitmap.SetPixel(x, y, nmg.DefaultNormalMapBGColor);
}
else if(IsColorWithinColorDistance(currentPixelColor, ColorType.Individual))
{
if(HasPixelAlreadyBeenAdded(x, y) == false)
{
ConvexObject co = new ConvexObject();
FloodFill(co, x, y);
co.CalculateBounds(nmg.ImageWidth, nmg.ImageHeight);
AddToTile(co);
}
}
CurrentProgress++;
}
progressBarValue.Report(CurrentProgress);
float percent = (float)CurrentProgress / (float)MaximumPixelsToCheck * 100f;
progressLabelDetailText.Report($@"{percent.ToString("00.00")}% --- {CurrentProgress.ToString("0,0")} / {MaximumPixelsToCheck.ToString("0,0")}");
}
foreach(KeyValuePair<Vector2Int, Tile> tile in nmg.Tiles)
{
foreach(ConvexObject co in tile.Value.ConvexObjects)
{
CreateNormalMapForConvexObject(co);
}
}
progressLabelText.Report("Finished");
nmg.CreatingNormalMap = false;
}
catch(OperationCanceledException)
{
MessageBox.Show($@"Operation cancelled!{Environment.NewLine}");
nmg.CreatingNormalMap = false;
progressLabelText.Report("Stopped");
}
catch(Exception e)
{
MessageBox.Show($@"Error creating Normal Map!{Environment.NewLine}{e.ToString()}");
Console.WriteLine(e.ToString());
nmg.CreatingNormalMap = false;
progressLabelText.Report("Error!");
}
}
19
View Source File : I360Render.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static byte[] DoTheHardWork_JPEG( byte[] fileBytes, int imageWidth, int imageHeight )
{
int xmpIndex = 0, xmpContentSize = 0;
while( !SearchChunkForXMP_JPEG( fileBytes, ref xmpIndex, ref xmpContentSize ) )
{
if( xmpIndex == -1 )
break;
}
int copyBytesUntil, copyBytesFrom;
if( xmpIndex == -1 )
{
copyBytesUntil = copyBytesFrom = FindIndexToInsertXMPCode_JPEG( fileBytes );
}
else
{
copyBytesUntil = xmpIndex;
copyBytesFrom = xmpIndex + 2 + xmpContentSize;
}
string xmpContent = string.Concat( XMP_NAMESPACE_JPEG, "\0", string.Format( XMP_CONTENT_TO_FORMAT_JPEG, 75f.ToString( "F1" ), imageWidth, imageHeight ) );
int xmpLength = xmpContent.Length + 2;
xmpContent = string.Concat( (char) 0xFF, (char) 0xE1, (char) ( xmpLength / 256 ), (char) ( xmpLength % 256 ), xmpContent );
byte[] result = new byte[copyBytesUntil + xmpContent.Length + ( fileBytes.Length - copyBytesFrom )];
Array.Copy( fileBytes, 0, result, 0, copyBytesUntil );
for( int i = 0; i < xmpContent.Length; i++ )
{
result[copyBytesUntil + i] = (byte) xmpContent[i];
}
Array.Copy( fileBytes, copyBytesFrom, result, copyBytesUntil + xmpContent.Length, fileBytes.Length - copyBytesFrom );
return result;
}
19
View Source File : I360Render.cs
License : Apache License 2.0
Project Creator : allenai
License : Apache License 2.0
Project Creator : allenai
private static byte[] DoTheHardWork_PNG( byte[] fileBytes, int imageWidth, int imageHeight )
{
string xmpContent = "iTXt" + string.Format( XMP_CONTENT_TO_FORMAT_PNG, 75f.ToString( "F1" ), imageWidth, imageHeight );
int copyBytesUntil = 33;
int xmpLength = xmpContent.Length - 4; // minus iTXt
string xmpCRC = CalculateCRC_PNG( xmpContent );
xmpContent = string.Concat( (char) ( xmpLength >> 24 ), (char) ( xmpLength >> 16 ), (char) ( xmpLength >> 8 ), (char) ( xmpLength ),
xmpContent, xmpCRC );
byte[] result = new byte[fileBytes.Length + xmpContent.Length];
Array.Copy( fileBytes, 0, result, 0, copyBytesUntil );
for( int i = 0; i < xmpContent.Length; i++ )
{
result[copyBytesUntil + i] = (byte) xmpContent[i];
}
Array.Copy( fileBytes, copyBytesUntil, result, copyBytesUntil + xmpContent.Length, fileBytes.Length - copyBytesUntil );
return result;
}
19
View Source File : TMP_SpriteAssetImportFormats.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
public override string ToString()
{
string s = "x: " + x.ToString("f2") + " y: " + y.ToString("f2") + " h: " + h.ToString("f2") + " w: " + w.ToString("f2");
return s;
}
19
View Source File : TMP_SpriteAssetImportFormats.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
public override string ToString()
{
string s = "w: " + w.ToString("f2") + " h: " + h.ToString("f2");
return s;
}
19
View Source File : Tools.cs
License : MIT License
Project Creator : AmigoCap
License : MIT License
Project Creator : AmigoCap
public static void AddClockStop(string message) {
if (!Visualization.Instance.debugMode)
return;
float delta = Time.realtimeSinceStartup - time;
clockString += delta.ToString("F4") + " - " + message + '\n';
time = Time.realtimeSinceStartup;
subTime = time;
}
See More Examples