Here are the examples of the csharp api System.Collections.Generic.List.Sort(System.Comparison) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2679 Examples
19
Source : DBHelperMySQL.cs
with Apache License 2.0
from 0nise
with Apache License 2.0
from 0nise
public static string Top30Money()
{
// 未提取存款
Hashtable userMoney = new Hashtable();
Hashtable userInfo = new Hashtable();
// 已经提取存款
Hashtable userBlank = new Hashtable();
// 财富榜前20
Hashtable userData = new Hashtable();
string resultMsg = "";
MySqlConnection connection = null;
try
{
connection = ConnectionPool.getPool().getConnection();
// 链接为null就执行等待
while (connection == null)
{
}
string sql = "SELECT bbs_nick_name,user_money,user_qq FROM ichunqiu_blank";
using (MySqlCommand cmd = new MySqlCommand(sql,connection))
{
using (MySqlDataReader myDataReader = cmd.ExecuteReader())
{
while (myDataReader.Read() == true)
{
userMoney.Add(myDataReader["bbs_nick_name"], myDataReader["user_money"]);
userInfo.Add(myDataReader["user_qq"], myDataReader["bbs_nick_name"]);
}
}
}
// 提取历史提取总金额
userBlank = getAllHistorySumMoney(userInfo);
// ArrayList allMoney = new ArrayList();
List<Decimal> allMoney = new List<decimal>();
foreach (DictionaryEntry item in userMoney)
{
decimal blance = Convert.ToDecimal(item.Value);
decimal historyBlance = Convert.ToDecimal(userBlank[item.Key]);
userData.Add(item.Key, historyBlance + blance);
allMoney.Add(historyBlance + blance);
}
/*
List<decimal> allMoney = new List<decimal>();
foreach (string item in userData.Values)
{
allMoney.Add(Convert.ToDecimal(item));
}*/
// 降序
allMoney.Sort((x, y) => -x.CompareTo(y));
int i = 0;
foreach (decimal money in allMoney)
{
foreach (DictionaryEntry item in userData)
{
if (Convert.ToDecimal(item.Value) == money)
{
resultMsg += string.Format("NO【{0}】:{1}身价{2},已提取存款{3},未提取存款{4}\n", (i + 1).ToString(), Convert.ToString(item.Key), Convert.ToString(money), Convert.ToString(userBlank[item.Key]), Convert.ToString(userMoney[item.Key]));
// 删除用户避免出现重复的情况
userData.Remove(item.Key);
break;
}
}
i++;
if (i > 29)
{
break;
}
}
}
catch (Exception)
{
throw;
}
finally {
if (connection != null) {
connection.Close();
}
// 关闭数据库链接
ConnectionPool.getPool().closeConnection(connection);
}
return resultMsg;
}
19
Source : ExprXmlReader.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public IEnumerable<XmlElement>? EnumerateList(XmlElement node, string propertyName)
{
var result = this.FindElement(node, propertyName);
if (result != null)
{
List<IndexXElement> buffer = new List<IndexXElement>();
foreach (var childNode in result.ChildNodes)
{
if (childNode is XmlElement childElement)
{
string indexStr = childElement.Name.Substring(propertyName.Length);
if (int.TryParse(indexStr, out var index))
{
buffer.Add(new IndexXElement(index, childElement));
}
}
}
if (buffer.Count == 0)
{
return null;
}
buffer.Sort((x,y)=> x.Index - y.Index);
return buffer.SelectToReadOnlyList(i => i.Element);
}
return null;
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
{
List<NodeModel> result = new List<NodeModel>();
var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);
files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));
var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);
foreach (var tree in trees)
{
var semantic = cSharpCompilation.GetSemanticModel(tree);
foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
{
var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
var isSuitable = clreplacedSymbol != null
&& !clreplacedSymbol.IsAbstract
&& clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
&& IsExpr(clreplacedSymbol)
&& clreplacedSymbol.Name.StartsWith("Expr");
if (!isSuitable)
{
continue;
}
var properties = GetProperties(clreplacedSymbol);
var subNodes = new List<SubNodeModel>();
var modelProps = new List<SubNodeModel>();
foreach (var constructor in clreplacedSymbol.Constructors)
{
foreach (var parameter in constructor.Parameters)
{
INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;
var correspondingProperty = properties.FirstOrDefault(prop =>
string.Equals(prop.Name,
parameter.Name,
StringComparison.CurrentCultureIgnoreCase));
if (correspondingProperty == null)
{
throw new Exception(
$"Could not find a property for the constructor arg: '{parameter.Name}'");
}
var ta = replacedyzeSymbol(ref pType);
var subNodeModel = new SubNodeModel(correspondingProperty.Name,
parameter.Name,
pType.Name,
ta.ListName,
ta.IsNullable,
ta.HostTypeName);
if (ta.Expr)
{
subNodes.Add(subNodeModel);
}
else
{
modelProps.Add(subNodeModel);
}
}
}
result.Add(new NodeModel(clreplacedSymbol.Name,
modelProps.Count == 0 && subNodes.Count == 0,
subNodes,
modelProps));
}
}
result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));
return result;
bool IsExpr(INamedTypeSymbol symbol)
{
if (symbol.Name == "IExpr")
{
return true;
}
while (symbol != null)
{
if (symbol.Interfaces.Any(HasA))
{
return true;
}
symbol = symbol.BaseType;
}
return false;
bool HasA(INamedTypeSymbol iSym)
{
if (iSym.Name == "IExpr")
{
return true;
}
return IsExpr(iSym);
}
}
List<ISymbol> GetProperties(INamedTypeSymbol symbol)
{
List<ISymbol> result = new List<ISymbol>();
while (symbol != null)
{
result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
symbol = symbol.BaseType;
}
return result;
}
Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
{
string listName = null;
string hostType = null;
if (typeSymbol.ContainingType != null)
{
var host = typeSymbol.ContainingType;
hostType = host.Name;
}
var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;
if (nullable && typeSymbol.Name == "Nullable")
{
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
if (typeSymbol.IsGenericType)
{
if (typeSymbol.Name.Contains("List"))
{
listName = typeSymbol.Name;
}
if (typeSymbol.Name == "Nullable")
{
nullable = true;
}
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
}
}
19
Source : Disassembler.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
public void Disreplacedemble(Formatter formatter, TextWriter output, DisasmInfo method) {
formatterOutput.writer = output;
targets.Clear();
sortedTargets.Clear();
bool uppercaseHex = formatter.Options.UppercaseHex;
output.Write(commentPrefix);
output.WriteLine("================================================================================");
output.Write(commentPrefix);
output.WriteLine(method.MethodFullName);
uint codeSize = 0;
foreach (var info in method.Code)
codeSize += (uint)info.Code.Length;
var codeSizeHexText = codeSize.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{codeSize} (0x{codeSizeHexText}) bytes");
var instrCount = method.Instructions.Count;
var instrCountHexText = instrCount.ToString(uppercaseHex ? "X" : "x");
output.WriteLine($"{commentPrefix}{instrCount} (0x{instrCountHexText}) instructions");
void Add(ulong address, TargetKind kind) {
if (!targets.TryGetValue(address, out var addrInfo))
targets[address] = new AddressInfo(kind);
else if (addrInfo.Kind < kind)
addrInfo.Kind = kind;
}
if (method.Instructions.Count > 0)
Add(method.Instructions[0].IP, TargetKind.Unknown);
foreach (ref var instr in method.Instructions) {
switch (instr.FlowControl) {
case FlowControl.Next:
case FlowControl.Interrupt:
break;
case FlowControl.UnconditionalBranch:
Add(instr.NextIP, TargetKind.Unknown);
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.ConditionalBranch:
case FlowControl.XbeginXabortXend:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Branch);
break;
case FlowControl.Call:
if (instr.Op0Kind == OpKind.NearBranch16 || instr.Op0Kind == OpKind.NearBranch32 || instr.Op0Kind == OpKind.NearBranch64)
Add(instr.NearBranchTarget, TargetKind.Call);
break;
case FlowControl.IndirectBranch:
Add(instr.NextIP, TargetKind.Unknown);
// Unknown target
break;
case FlowControl.IndirectCall:
// Unknown target
break;
case FlowControl.Return:
case FlowControl.Exception:
Add(instr.NextIP, TargetKind.Unknown);
break;
default:
Debug.Fail($"Unknown flow control: {instr.FlowControl}");
break;
}
var baseReg = instr.MemoryBase;
if (baseReg == Register.RIP || baseReg == Register.EIP) {
int opCount = instr.OpCount;
for (int i = 0; i < opCount; i++) {
if (instr.GetOpKind(i) == OpKind.Memory) {
if (method.Contains(instr.IPRelativeMemoryAddress))
Add(instr.IPRelativeMemoryAddress, TargetKind.Branch);
break;
}
}
}
else if (instr.MemoryDisplSize >= 2) {
ulong displ;
switch (instr.MemoryDisplSize) {
case 2:
case 4: displ = instr.MemoryDisplacement; break;
case 8: displ = (ulong)(int)instr.MemoryDisplacement; break;
default:
Debug.Fail($"Unknown mem displ size: {instr.MemoryDisplSize}");
goto case 8;
}
if (method.Contains(displ))
Add(displ, TargetKind.Branch);
}
}
foreach (var map in method.ILMap) {
if (targets.TryGetValue(map.nativeStartAddress, out var info)) {
if (info.Kind < TargetKind.BlockStart && info.Kind != TargetKind.Unknown)
info.Kind = TargetKind.BlockStart;
}
else
targets.Add(map.nativeStartAddress, info = new AddressInfo(TargetKind.Unknown));
if (info.ILOffset < 0)
info.ILOffset = map.ilOffset;
}
int labelIndex = 0, methodIndex = 0;
string GetLabel(int index) => LABEL_PREFIX + index.ToString();
string GetFunc(int index) => FUNC_PREFIX + index.ToString();
foreach (var kv in targets) {
if (method.Contains(kv.Key))
sortedTargets.Add(kv);
}
sortedTargets.Sort((a, b) => a.Key.CompareTo(b.Key));
foreach (var kv in sortedTargets) {
var address = kv.Key;
var info = kv.Value;
switch (info.Kind) {
case TargetKind.Unknown:
info.Name = null;
break;
case TargetKind.Data:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.BlockStart:
case TargetKind.Branch:
info.Name = GetLabel(labelIndex++);
break;
case TargetKind.Call:
info.Name = GetFunc(methodIndex++);
break;
default:
throw new InvalidOperationException();
}
}
foreach (ref var instr in method.Instructions) {
ulong ip = instr.IP;
if (targets.TryGetValue(ip, out var lblInfo)) {
output.WriteLine();
if (!(lblInfo.Name is null)) {
output.Write(lblInfo.Name);
output.Write(':');
output.WriteLine();
}
if (lblInfo.ILOffset >= 0) {
if (ShowSourceCode) {
foreach (var info in sourceCodeProvider.GetStatementLines(method, lblInfo.ILOffset)) {
output.Write(commentPrefix);
var line = info.Line;
int column = commentPrefix.Length;
WriteWithTabs(output, line, 0, line.Length, '\0', ref column);
output.WriteLine();
if (info.Partial) {
output.Write(commentPrefix);
column = commentPrefix.Length;
WriteWithTabs(output, line, 0, info.Span.Start, ' ', ref column);
output.WriteLine(new string('^', info.Span.Length));
}
}
}
}
}
if (ShowAddresses) {
var address = FormatAddress(bitness, ip, uppercaseHex);
output.Write(address);
output.Write(" ");
}
else
output.Write(formatter.Options.TabSize > 0 ? "\t\t" : " ");
if (ShowHexBytes) {
if (!method.TryGetCode(ip, out var nativeCode))
throw new InvalidOperationException();
var codeBytes = nativeCode.Code;
int index = (int)(ip - nativeCode.IP);
int instrLen = instr.Length;
for (int i = 0; i < instrLen; i++) {
byte b = codeBytes[index + i];
output.Write(b.ToString(uppercaseHex ? "X2" : "x2"));
}
int missingBytes = HEXBYTES_COLUMN_BYTE_LENGTH - instrLen;
for (int i = 0; i < missingBytes; i++)
output.Write(" ");
output.Write(" ");
}
formatter.Format(instr, formatterOutput);
output.WriteLine();
}
}
19
Source : Program.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static DisasmJob[] GetJobs(DisasmInfo[] methods, string outputDir, FileOutputKind fileOutputKind, FilenameFormat filenameFormat, out string? baseDir) {
FilenameProvider filenameProvider;
var jobs = new List<DisasmJob>();
switch (fileOutputKind) {
case FileOutputKind.Stdout:
baseDir = null;
return new[] { new DisasmJob(() => (Console.Out, false), methods) };
case FileOutputKind.OneFile:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing filename");
baseDir = Path.GetDirectoryName(outputDir);
return new[] { new DisasmJob(() => (File.CreateText(outputDir), true), methods) };
case FileOutputKind.OneFilePerType:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
var types = new Dictionary<uint, List<DisasmInfo>>();
foreach (var method in methods) {
if (!types.TryGetValue(method.TypeToken, out var typeMethods))
types.Add(method.TypeToken, typeMethods = new List<DisasmInfo>());
typeMethods.Add(method);
}
var allTypes = new List<List<DisasmInfo>>(types.Values);
allTypes.Sort((a, b) => StringComparer.Ordinal.Compare(a[0].TypeFullName, b[0].TypeFullName));
foreach (var typeMethods in allTypes) {
uint token = typeMethods[0].TypeToken;
var name = GetTypeName(typeMethods[0].TypeFullName);
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, typeMethods.ToArray()));
}
return jobs.ToArray();
case FileOutputKind.OneFilePerMethod:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
foreach (var method in methods) {
uint token = method.MethodToken;
var name = method.MethodName.Replace('.', '_');
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, new[] { method }));
}
return jobs.ToArray();
default:
throw new InvalidOperationException();
}
}
19
Source : Player.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public void MergeWithBuffer()
{
lock (userCommandBufferList)
{
// TODO work out why some User Commands are null
// it works for now tho
for (int i = userCommandBufferList.Count - 1; i >= 0; i--)
{
if (userCommandBufferList[i] == null)
{
userCommandBufferList.RemoveAt(i);
}
else
{
jitter.Update(userCommandBufferList[i].serverRecTime - lastRecTime);
lastRecTime = userCommandBufferList[i].serverRecTime;
}
}
userCommandList.AddRange(userCommandBufferList);
userCommandBufferList.Clear();
}
userCommandList.Sort((a, b) => a.serverRecTime.CompareTo(b.serverRecTime));
// DEBUG Jitter
//Debug.Log(jitter.stdDeviation + ", " + jitter.average);
}
19
Source : JcApiHelper.cs
with MIT License
from 279328316
with MIT License
from 279328316
private static void InitController(IActionDescriptorCollectionProvider actionProvider)
{
lock (controllerList)
{
if (controllerList.Count > 0)
{
return;
}
#region 获取Controller,Action,TypeModel信息
List<ActionDescriptor> actionDescList = actionProvider.ActionDescriptors.Items.ToList();
for (int i = 0; i < actionDescList.Count; i++)
{
ControllerActionDescriptor actionDescriptor = actionDescList[i] as ControllerActionDescriptor;
ControllerModel controller = controllerList.Where(a =>
a.Id == TypeHelper.GetModuleMark(actionDescriptor.ControllerTypeInfo)).FirstOrDefault();
if (controller == null)
{
controller = GetControllerModel(actionDescriptor);
if (controller.ControllerName == "ApiHelper")
{
continue;
}
controllerList.Add(controller);
}
ActionModel action = GetActionModel(actionDescriptor);
controller.ActionList.Add(action);
}
#endregion
#region Controller,Action 排序
for (int i = 0; i < controllerList.Count; i++)
{
controllerList[i].ActionList.Sort((a1, a2) =>
{
return a1.ActionName.CompareTo(a2.ActionName);
});
}
controllerList.Sort((a1, a2) =>
{
return a1.ControllerName.CompareTo(a2.ControllerName);
});
#endregion
}
}
19
Source : Search.cs
with MIT License
from 3583Bytes
with MIT License
from 3583Bytes
private static int AlphaBeta(Board examineBoard, byte depth, int alpha, int beta, ref int nodesSearched, ref int nodesQuiessence, ref List<Position> pvLine, bool extended)
{
nodesSearched++;
if (examineBoard.HalfMoveClock >= 100 || examineBoard.RepeatedMove >= 3)
return 0;
//End Main Search with Quiescence
if (depth == 0)
{
if (!extended && examineBoard.BlackCheck || examineBoard.WhiteCheck)
{
depth++;
extended = true;
}
else
{
//Perform a Quiessence Search
return Quiescence(examineBoard, alpha, beta, ref nodesQuiessence);
}
}
List<Position> positions = EvaluateMoves(examineBoard, depth);
if (examineBoard.WhiteCheck || examineBoard.BlackCheck || positions.Count == 0)
{
if (SearchForMate(examineBoard.WhoseMove, examineBoard, ref examineBoard.BlackMate, ref examineBoard.WhiteMate, ref examineBoard.StaleMate))
{
if (examineBoard.BlackMate)
{
if (examineBoard.WhoseMove == ChessPieceColor.Black)
return -32767-depth;
return 32767 + depth;
}
if (examineBoard.WhiteMate)
{
if (examineBoard.WhoseMove == ChessPieceColor.Black)
return 32767 + depth;
return -32767 - depth;
}
//If Not Mate then StaleMate
return 0;
}
}
positions.Sort(Sort);
foreach (Position move in positions)
{
List<Position> pvChild = new List<Position>();
//Make a copy
Board board = examineBoard.FastCopy();
//Move Piece
Board.MovePiece(board, move.SrcPosition, move.DstPosition, ChessPieceType.Queen);
//We Generate Valid Moves for Board
PieceValidMoves.GenerateValidMoves(board);
if (board.BlackCheck)
{
if (examineBoard.WhoseMove == ChessPieceColor.Black)
{
//Invalid Move
continue;
}
}
if (board.WhiteCheck)
{
if (examineBoard.WhoseMove == ChessPieceColor.White)
{
//Invalid Move
continue;
}
}
int value = -AlphaBeta(board, (byte)(depth - 1), -beta, -alpha, ref nodesSearched, ref nodesQuiessence, ref pvChild, extended);
if (value >= beta)
{
KillerMove[kIndex, depth].SrcPosition = move.SrcPosition;
KillerMove[kIndex, depth].DstPosition = move.DstPosition;
kIndex = ((kIndex + 1) % 2);
return beta;
}
if (value > alpha)
{
Position pvPos = new Position();
pvPos.SrcPosition = board.LastMove.MovingPiecePrimary.SrcPosition;
pvPos.DstPosition = board.LastMove.MovingPiecePrimary.DstPosition;
pvPos.Move = board.LastMove.ToString();
pvChild.Insert(0, pvPos);
pvLine = pvChild;
alpha = (int)value;
}
}
return alpha;
}
19
Source : Search.cs
with MIT License
from 3583Bytes
with MIT License
from 3583Bytes
private static int Quiescence(Board examineBoard, int alpha, int beta, ref int nodesSearched)
{
nodesSearched++;
//Evaluate Score
Evaluation.EvaluateBoardScore(examineBoard);
//Invert Score to support Negamax
examineBoard.Score = SideToMoveScore(examineBoard.Score, examineBoard.WhoseMove);
if (examineBoard.Score >= beta)
return beta;
if (examineBoard.Score > alpha)
alpha = examineBoard.Score;
List<Position> positions;
if (examineBoard.WhiteCheck || examineBoard.BlackCheck)
{
positions = EvaluateMoves(examineBoard, 0);
}
else
{
positions = EvaluateMovesQ(examineBoard);
}
if (positions.Count == 0)
{
return examineBoard.Score;
}
positions.Sort(Sort);
foreach (Position move in positions)
{
if (StaticExchangeEvaluation(examineBoard.Squares[move.DstPosition]) >= 0)
{
continue;
}
//Make a copy
Board board = examineBoard.FastCopy();
//Move Piece
Board.MovePiece(board, move.SrcPosition, move.DstPosition, ChessPieceType.Queen);
//We Generate Valid Moves for Board
PieceValidMoves.GenerateValidMoves(board);
if (board.BlackCheck)
{
if (examineBoard.WhoseMove == ChessPieceColor.Black)
{
//Invalid Move
continue;
}
}
if (board.WhiteCheck)
{
if (examineBoard.WhoseMove == ChessPieceColor.White)
{
//Invalid Move
continue;
}
}
int value = -Quiescence(board, - beta, -alpha, ref nodesSearched);
if (value >= beta)
{
KillerMove[2, 0].SrcPosition = move.SrcPosition;
KillerMove[2, 0].DstPosition = move.DstPosition;
return beta;
}
if (value > alpha)
{
alpha = value;
}
}
return alpha;
}
19
Source : Utility.cs
with MIT License
from 5argon
with MIT License
from 5argon
private static GameObject RaycastFirst(PointerEventData fakeClick)
{
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(fakeClick, results);
RaycastResult FindFirstRaycast(List<RaycastResult> candidates)
{
//Debug.Log($"Hit {candidates.Count} count {string.Join(" ", candidates.Select(x => x.gameObject.name))}");
candidates.Sort(RaycastComparer);
//Debug.Log($"After sort {candidates.Count} count {string.Join(" ", candidates.Select(x => x.gameObject.name))}");
for (var i = 0; i < candidates.Count; ++i)
{
if (candidates[i].gameObject == null)
{
continue;
}
//Debug.Log($"Choosing {candidates[i].gameObject.name}");
return candidates[i];
}
return new RaycastResult();
}
var rr = FindFirstRaycast(results);
var rrgo = rr.gameObject;
//Debug.Log($"{rrgo}");
return rrgo;
}
19
Source : OverlayLibraryEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public override void OnInspectorGUI(){
m_Object.Update();
serializedObject.Update();
GUILayout.Label ("overlayList", EditorStyles.boldLabel);
OverlayDatareplacedet[] overlayElementList = GetOverlayDataArray();
GUILayout.Space(30);
GUILayout.Label ("Overlays reduced " + scaleAdjust.intValue +" time(s)");
GUILayout.BeginHorizontal();
if(scaleAdjust.intValue > 0){
if(GUILayout.Button("Resolution +")){
ScaleUpTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue --;
}
}
if(GUILayout.Button("Resolution -")){
ScaleDownTextures();
isDirty = true;
canUpdate = false;
scaleAdjust.intValue ++;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
compress.boolValue = GUILayout.Toggle (compress.boolValue ? true : false," Compress Textures");
readWrite.boolValue = GUILayout.Toggle (readWrite.boolValue ? true : false," Read/Write");
if(GUILayout.Button(" Apply")){
ConfigureTextures();
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.BeginHorizontal();
if(GUILayout.Button("Order by Name")){
canUpdate = false;
List<OverlayDatareplacedet> OverlayDataTemp = overlayElementList.ToList();
//Make sure there's no invalid data
for(int i = 0; i < OverlayDataTemp.Count; i++){
if(OverlayDataTemp[i] == null){
OverlayDataTemp.RemoveAt(i);
i--;
}
}
OverlayDataTemp.Sort((x,y) => x.name.CompareTo(y.name));
for(int i = 0; i < OverlayDataTemp.Count; i++){
SetOverlayData(i,OverlayDataTemp[i]);
}
}
if(GUILayout.Button("Update List")){
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<OverlayDatareplacedet> Overlays = new HashSet<OverlayDatareplacedet>();
foreach(OverlayDatareplacedet oda in overlayElementList)
{
Overlays.Add(oda);
}
m_OverlayDataCount.intValue = Overlays.Count;
for(int i=0;i<Overlays.Count;i++)
{
SetOverlayData(i,Overlays.ElementAt(i));
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f,50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea,"Drag Overlays here");
GUILayout.Space(20);
for(int i = 0; i < m_OverlayDataCount.intValue; i ++){
GUILayout.BeginHorizontal();
var result = EditorGUILayout.ObjectField(overlayElementList[i], typeof(OverlayDatareplacedet), true) as OverlayDatareplacedet;
if(GUI.changed && canUpdate){
SetOverlayData(i,result);
}
if(GUILayout.Button("-", GUILayout.Width(20.0f))){
canUpdate = false;
RemoveOverlayDataAtIndex(i);
}
GUILayout.EndHorizontal();
if(i == m_OverlayDataCount.intValue -1){
canUpdate = true;
if(isDirty){
overlayLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if(GUILayout.Button("Add OverlayData")){
AddOverlayData(null);
}
if(GUILayout.Button("Clear List")){
m_OverlayDataCount.intValue = 0;
}
m_Object.ApplyModifiedProperties();
serializedObject.ApplyModifiedProperties();
}
19
Source : SlotLibraryEditor.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public override void OnInspectorGUI()
{
m_Object.Update();
GUILayout.Label("slotElementList", EditorStyles.boldLabel);
SlotDatareplacedet[] slotElementList = GetSlotDatareplacedetArray();
GUILayout.BeginHorizontal();
if (GUILayout.Button("Order by Name"))
{
canUpdate = false;
List<SlotDatareplacedet> SlotDatareplacedetTemp = slotElementList.ToList();
//Make sure there's no invalid data
for (int i = 0; i < SlotDatareplacedetTemp.Count; i++)
{
if (SlotDatareplacedetTemp[i] == null)
{
SlotDatareplacedetTemp.RemoveAt(i);
i--;
}
}
SlotDatareplacedetTemp.Sort((x, y) => x.name.CompareTo(y.name));
for (int i = 0; i < SlotDatareplacedetTemp.Count; i++)
{
SetSlotDatareplacedet(i, SlotDatareplacedetTemp[i]);
}
}
if (GUILayout.Button("Update List"))
{
isDirty = true;
canUpdate = false;
}
if (GUILayout.Button("Remove Duplicates"))
{
HashSet<SlotDatareplacedet> Slots = new HashSet<SlotDatareplacedet>();
foreach(SlotDatareplacedet osa in slotElementList)
{
Slots.Add(osa);
}
m_SlotDatareplacedetCount.intValue = Slots.Count;
for(int i=0;i<Slots.Count;i++)
{
SetSlotDatareplacedet(i,Slots.ElementAt(i));
}
isDirty = true;
canUpdate = false;
}
GUILayout.EndHorizontal();
GUILayout.Space(20);
Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
GUI.Box(dropArea, "Drag Slots here");
GUILayout.Space(20);
for (int i = 0; i < m_SlotDatareplacedetCount.intValue; i++)
{
GUILayout.BeginHorizontal();
SlotDatareplacedet result = EditorGUILayout.ObjectField(slotElementList[i], typeof(SlotDatareplacedet), true) as SlotDatareplacedet;
if (GUI.changed && canUpdate)
{
SetSlotDatareplacedet(i, result);
}
if (GUILayout.Button("-", GUILayout.Width(20.0f)))
{
canUpdate = false;
RemoveSlotDatareplacedetAtIndex(i);
}
GUILayout.EndHorizontal();
if (i == m_SlotDatareplacedetCount.intValue - 1)
{
canUpdate = true;
if (isDirty)
{
slotLibrary.UpdateDictionary();
isDirty = false;
}
}
}
DropAreaGUI(dropArea);
if (GUILayout.Button("Add SlotDatareplacedet"))
{
AddSlotDatareplacedet(null);
}
if (GUILayout.Button("Clear List"))
{
m_SlotDatareplacedetCount.intValue = 0;
}
if (GUILayout.Button("Remove Invalid Slot Data"))
{
RemoveInvalidSlotDatareplacedet(slotElementList);
}
m_Object.ApplyModifiedProperties();
}
19
Source : AccelCalculator.cs
with MIT License
from a1xd
with MIT License
from a1xd
public ReadOnlyCollection<SimulatedMouseInput> GetSimulatedInput()
{
var magnitudes = new List<SimulatedMouseInput>();
foreach (var slowMoveX in SlowMovements)
{
var slowMoveY = 0.0;
var ceilX = (int)Math.Round(slowMoveX*50);
var ceilY = (int)Math.Round(slowMoveY*50);
var ceilMagnitude = Magnitude(ceilX, ceilY);
var timeFactor = ceilMagnitude / Magnitude(slowMoveX, slowMoveY);
SimulatedMouseInput mouseInputData;
mouseInputData.x = ceilX;
mouseInputData.y = ceilY;
mouseInputData.time = MeasurementTime*timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(ceilX, ceilY, mouseInputData.time));
mouseInputData.angle = Math.Atan2(ceilY, ceilX);
magnitudes.Add(mouseInputData);
}
for (double i = 5; i < MaxVelocity; i+=Increment)
{
SimulatedMouseInput mouseInputData;
var ceil = (int)Math.Ceiling(i);
var timeFactor = ceil / i;
mouseInputData.x = ceil;
mouseInputData.y = 0;
mouseInputData.time = MeasurementTime * timeFactor;
mouseInputData.velocity = DecimalCheck(Velocity(ceil, 0, mouseInputData.time));
mouseInputData.angle = Math.Atan2(ceil, 0);
magnitudes.Add(mouseInputData);
}
magnitudes.Sort((m1, m2) => m1.velocity.CompareTo(m2.velocity));
return magnitudes.AsReadOnly();
}
19
Source : XmlFoldingStrategy.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public IEnumerable<NewFolding> CreateNewFoldings(TextDoreplacedent doreplacedent, XmlReader reader, out int firstErrorOffset)
{
Stack<XmlFoldStart> stack = new Stack<XmlFoldStart>();
List<NewFolding> foldMarkers = new List<NewFolding>();
try {
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
if (!reader.IsEmptyElement) {
XmlFoldStart newFoldStart = CreateElementFoldStart(doreplacedent, reader);
stack.Push(newFoldStart);
}
break;
case XmlNodeType.EndElement:
XmlFoldStart foldStart = stack.Pop();
CreateElementFold(doreplacedent, foldMarkers, reader, foldStart);
break;
case XmlNodeType.Comment:
CreateCommentFold(doreplacedent, foldMarkers, reader);
break;
}
}
firstErrorOffset = -1;
} catch (XmlException ex) {
// ignore errors at invalid positions (prevent ArgumentOutOfRangeException)
if (ex.LineNumber >= 1 && ex.LineNumber <= doreplacedent.LineCount)
firstErrorOffset = doreplacedent.GetOffset(ex.LineNumber, ex.LinePosition);
else
firstErrorOffset = 0;
}
foldMarkers.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
return foldMarkers;
}
19
Source : TypeReferencePropertyDrawer.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static List<Type> GetFilteredTypes(SystemTypeAttribute filter)
{
var types = new List<Type>();
var excludedTypes = ExcludedTypeCollectionGetter?.Invoke();
// We prefer using this over CompilationPipeline.Getreplacedemblies() because
// some types may come from plugins and other sources that have already
// been compiled.
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (var replacedembly in replacedemblies)
{
FilterTypes(replacedembly, filter, excludedTypes, types);
}
types.Sort((a, b) => string.Compare(a.FullName, b.FullName, StringComparison.Ordinal));
return types;
}
19
Source : MixedRealitySearchUtility.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static async void StartProfileSearch(UnityEngine.Object profile, SearchConfig config, Action<bool, UnityEngine.Object, IReadOnlyCollection<ProfileSearchResult>> onSearchComplete)
{
if (activeTask != null && !activeTask.IsCompleted)
{
throw new Exception("Can't start a new search until the old one has completed.");
}
List<ProfileSearchResult> searchResults = new List<ProfileSearchResult>();
// Validate search configuration
if (string.IsNullOrEmpty(config.SearchFieldString))
{ // If the config is empty, bail early
onSearchComplete?.Invoke(true, profile, searchResults);
return;
}
// Generate keywords if we haven't yet
if (config.Keywords == null)
{
config.Keywords = new HashSet<string>(config.SearchFieldString.Split(new string[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries));
config.Keywords.RemoveWhere(s => s.Length < minSearchStringLength);
}
if (config.Keywords.Count == 0)
{ // If there are no useful keywords, bail early
onSearchComplete?.Invoke(true, profile, searchResults);
return;
}
// Launch the search task
bool cancelled = false;
try
{
activeTask = SearchProfileField(profile, config, searchResults);
await activeTask;
}
catch (Exception e)
{
// Profile was probably deleted in the middle of searching.
Debug.LogException(e);
cancelled = true;
}
finally
{
searchResults.Sort(delegate (ProfileSearchResult r1, ProfileSearchResult r2)
{
if (r1.ProfileMatchStrength != r2.ProfileMatchStrength)
{
return r2.ProfileMatchStrength.CompareTo(r1.ProfileMatchStrength);
}
else
{
return r2.Profile.name.CompareTo(r1.Profile.name);
}
});
searchResults.RemoveAll(r => r.Fields.Count <= 0);
onSearchComplete?.Invoke(cancelled, profile, searchResults);
}
}
19
Source : AppBar.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private void UpdateButtons()
{
// First just count how many buttons are visible
int activeButtonNum = 0;
for (int i = 0; i < buttons.Count; i++)
{
AppBarButton button = buttons[i];
switch (button.ButtonType)
{
case ButtonTypeEnum.Custom:
break;
default:
button.SetVisible(GetButtonVisible(button.ButtonType));
break;
}
if (!buttons[i].Visible)
{
continue;
}
activeButtonNum++;
}
// Sort the buttons by display order
buttons.Sort(delegate (AppBarButton b1, AppBarButton b2) { return b2.DisplayOrder.CompareTo(b1.DisplayOrder); });
// Use active button number to determine background size and offset
float backgroundBarSize = ButtonWidth * activeButtonNum;
Vector3 positionOffset = Vector3.right * ((backgroundBarSize / 2) - (ButtonWidth / 2));
// Go through them again, setting active as
activeButtonNum = 0;
for (int i = 0; i < buttons.Count; i++)
{
// Set the sibling index and target position so the button will behave predictably when set visible
buttons[i].transform.SetSiblingIndex(i);
buttons[i].SetTargetPosition((Vector3.left * ButtonWidth * activeButtonNum) + positionOffset);
if (!buttons[i].Visible)
continue;
activeButtonNum++;
}
targetBarSize.x = backgroundBarSize;
BackgroundBar.transform.localScale = Vector3.Lerp(BackgroundBar.transform.localScale, targetBarSize, Time.deltaTime * backgroundBarMoveSpeed);
BackgroundBar.transform.localPosition = Vector3.forward * ButtonDepth / 2;
}
19
Source : BaseObjectCollection.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
protected void SortNodes()
{
switch (SortType)
{
case CollationOrder.ChildOrder:
NodeList.Sort((c1, c2) => (c1.Transform.GetSiblingIndex().CompareTo(c2.Transform.GetSiblingIndex())));
break;
case CollationOrder.Alphabetical:
NodeList.Sort((c1, c2) => (string.CompareOrdinal(c1.Name, c2.Name)));
break;
case CollationOrder.AlphabeticalReversed:
NodeList.Sort((c1, c2) => (string.CompareOrdinal(c1.Name, c2.Name)));
NodeList.Reverse();
break;
case CollationOrder.ChildOrderReversed:
NodeList.Sort((c1, c2) => (c1.Transform.GetSiblingIndex().CompareTo(c2.Transform.GetSiblingIndex())));
NodeList.Reverse();
break;
}
}
19
Source : ScatterObjectCollection.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void IterateScatterPacking(List<ObjectCollectionNode> nodes, float radiusPadding)
{
// Sort by closest to center (don't worry about z axis)
// Use the position of the collection as the packing center
nodes.Sort(ScatterSort);
Vector3 difference;
Vector2 difference2D;
// Move them closer together
float radiusPaddingSquared = Mathf.Pow(radiusPadding, 2f);
for (int i = 0; i < nodes.Count - 1; i++)
{
for (int j = i + 1; j < nodes.Count; j++)
{
if (i != j)
{
difference = nodes[j].Transform.localPosition - nodes[i].Transform.localPosition;
// Ignore Z axis
difference2D.x = difference.x;
difference2D.y = difference.y;
float combinedRadius = nodes[i].Radius + nodes[j].Radius;
float distance = difference2D.SqrMagnitude() - radiusPaddingSquared;
float minSeparation = Mathf.Min(distance, radiusPaddingSquared);
distance -= minSeparation;
if (distance < (Mathf.Pow(combinedRadius, 2)))
{
difference2D.Normalize();
difference *= ((combinedRadius - Mathf.Sqrt(distance)) * 0.5f);
nodes[j].Transform.localPosition += difference;
nodes[i].Transform.localPosition -= difference;
}
}
}
}
}
19
Source : AudioManagerInspector.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
void DrawCategories( Event e ) {
// do any housework before we start drawing
if ( moveQueued ) {
// make a temp copy
List<SoundFX> origSoundList = new List<SoundFX>( audioManager.soundGroupings[origGroup].soundList );
SoundFX temp = origSoundList[origIndex];
List<SoundFX> moveToSoundList = new List<SoundFX>( audioManager.soundGroupings[moveToGroup].soundList );
// add it to the move to group
moveToSoundList.Add( temp );
audioManager.soundGroupings[moveToGroup].soundList = moveToSoundList.ToArray();
// and finally, remove it from the original group
origSoundList.RemoveAt( origIndex );
audioManager.soundGroupings[origGroup].soundList = origSoundList.ToArray();
Debug.Log( "> Moved '" + temp.name + "' from " + "'" + audioManager.soundGroupings[origGroup].name + "' to '" + audioManager.soundGroupings[moveToGroup].name );
MarkDirty();
moveQueued = false;
}
// switch to the next group
if ( nextGroup > -1 ) {
selectedGroup = nextGroup;
nextGroup = -1;
}
// add a sound
if ( addSound ) {
List<SoundFX> soundList = new List<SoundFX>( audioManager.soundGroupings[selectedGroup].soundList );
SoundFX soundFX = new SoundFX();
soundFX.name = audioManager.soundGroupings[selectedGroup].name.ToLower() + "_new_unnamed_sound_fx";
soundList.Add( soundFX );
audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray();
MarkDirty();
addSound = false;
}
// sort the sounds
if ( sortSounds ) {
List<SoundFX> soundList = new List<SoundFX>( audioManager.soundGroupings[selectedGroup].soundList );
soundList.Sort( delegate ( SoundFX sfx1, SoundFX sfx2 ) { return string.Compare( sfx1.name, sfx2.name ); } );
audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray();
MarkDirty();
sortSounds = false;
}
// delete a sound
if ( deleteSoundIdx > -1 ) {
List<SoundFX> soundList = new List<SoundFX>( audioManager.soundGroupings[selectedGroup].soundList );
soundList.RemoveAt( deleteSoundIdx );
audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray();
MarkDirty();
deleteSoundIdx = -1;
}
// duplicate a sound
if ( dupeSoundIdx > -1 ) {
List<SoundFX> soundList = new List<SoundFX>( audioManager.soundGroupings[selectedGroup].soundList );
SoundFX origSoundFX = soundList[dupeSoundIdx];
// clone this soundFX
string json = JsonUtility.ToJson( origSoundFX );
SoundFX soundFX = JsonUtility.FromJson<SoundFX>( json );
soundFX.name += "_duplicated";
soundList.Insert( dupeSoundIdx + 1, soundFX );
audioManager.soundGroupings[selectedGroup].soundList = soundList.ToArray();
MarkDirty();
dupeSoundIdx = -1;
}
if ( e.type == EventType.Repaint ) {
groups.Clear();
}
GUILayout.Space( 6f );
Color defaultColor = GUI.contentColor;
BeginContents();
if ( DrawHeader( "Sound FX Groups", true ) ) {
EditorGUILayout.BeginVertical( GUI.skin.box );
soundGroups.Clear();
for ( int i = 0; i < audioManager.soundGroupings.Length; i++ ) {
soundGroups.Add( audioManager.soundGroupings[i] );
}
for ( int i = 0; i < soundGroups.size; i++ ) {
EditorGUILayout.BeginHorizontal();
{
if ( i == selectedGroup ) {
GUI.contentColor = ( i == editGroup ) ? Color.white : Color.yellow;
} else {
GUI.contentColor = defaultColor;
}
if ( ( e.type == EventType.KeyDown ) && ( ( e.keyCode == KeyCode.Return ) || ( e.keyCode == KeyCode.KeypadEnter ) ) ) {
// toggle editing
if ( editGroup >= 0 ) {
editGroup = -1;
}
Event.current.Use();
}
if ( i == editGroup ) {
soundGroups[i].name = GUILayout.TextField( soundGroups[i].name, GUILayout.MinWidth( Screen.width - 80f ) );
} else {
GUILayout.Label( soundGroups[i].name, ( i == selectedGroup ) ? EditorStyles.whiteLabel : EditorStyles.label, GUILayout.ExpandWidth( true ) );
}
GUILayout.FlexibleSpace();
if ( GUILayout.Button( GUIContent.none, "OL Minus", GUILayout.Width(17f) ) ) { // minus button
if ( EditorUtility.DisplayDialog( "Delete '" + soundGroups[i].name + "'", "Are you sure you want to delete the selected sound group?", "Continue", "Cancel" ) ) {
soundGroups.RemoveAt( i );
MarkDirty();
}
}
}
EditorGUILayout.EndHorizontal();
// build a list of items
Rect lastRect = GUILayoutUtility.GetLastRect();
if ( e.type == EventType.Repaint ) {
groups.Add ( new ItemRect( i, lastRect, null ) );
}
if ( ( e.type == EventType.MouseDown ) && lastRect.Contains( e.mousePosition ) ) {
if ( ( i != selectedGroup ) || ( e.clickCount == 2 ) ) {
nextGroup = i;
if ( e.clickCount == 2 ) {
editGroup = i;
} else if ( editGroup != nextGroup ) {
editGroup = -1;
}
Repaint();
}
}
}
// add the final plus button
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if ( GUILayout.Button( GUIContent.none, "OL Plus", GUILayout.Width(17f) ) ) { // plus button
soundGroups.Add( new SoundGroup( "unnamed sound group" ) );
selectedGroup = editGroup = soundGroups.size - 1;
MarkDirty();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
// reset the color
GUI.contentColor = defaultColor;
// the sort and import buttons
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if ( GUILayout.Button( "Sort", GUILayout.Width( 70f ) ) ) {
soundGroups.Sort( delegate( SoundGroup sg1, SoundGroup sg2 ) { return string.Compare( sg1.name, sg2.name ); } );
MarkDirty();
}
EditorGUILayout.EndHorizontal();
// draw a rect around the selected item
if ( ( selectedGroup >= 0 ) && ( selectedGroup < groups.size ) ) {
EditorGUI.DrawRect( groups[selectedGroup].rect, new Color( 1f, 1f, 1f, 0.06f ) );
}
// finally move the sound groups back into the audio manager
if ( soundGroups.size > 0 ) {
audioManager.soundGroupings = soundGroups.ToArray();
}
// calculate the drop area rect
if ( ( e.type == EventType.Repaint ) && ( groups.size > 0 ) ) {
dropArea.x = groups[0].rect.x;
dropArea.y = groups[0].rect.y;
dropArea.width = groups[0].rect.width;
dropArea.height = ( groups[groups.size-1].rect.y - groups[0].rect.y ) + groups[groups.size-1].rect.height;
}
}
// draw the sound group properties now
DrawSoundGroupProperties();
EndContents();
EditorGUILayout.HelpBox("Create and delete sound groups by clicking + and - respectively. Double click to rename sound groups. Drag and drop sounds from below to the groups above to move them.", MessageType.Info);
}
19
Source : OVRRaycaster.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private void GraphicRaycast(Canvas canvas, Ray ray, List<RaycastHit> results)
{
//This function is based closely on :
// void GraphicRaycaster.Raycast(Canvas canvas, Camera eventCamera, Vector2 pointerPosition, List<Graphic> results)
// But modified to take a Ray instead of a canvas pointer, and also to explicitly ignore
// the graphic replacedociated with the pointer
// Necessary for the event system
var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
s_SortedGraphics.Clear();
for (int i = 0; i < foundGraphics.Count; ++i)
{
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1 || (pointer == graphic.gameObject))
continue;
Vector3 worldPos;
if (RayIntersectsRectTransform(graphic.rectTransform, ray, out worldPos))
{
//Work out where this is on the screen for compatibility with existing Unity UI code
Vector2 screenPos = eventCamera.WorldToScreenPoint(worldPos);
// mask/image intersection - See Unity docs on eventAlphaThreshold for when this does anything
if (graphic.Raycast(screenPos, eventCamera))
{
RaycastHit hit;
hit.graphic = graphic;
hit.worldPos = worldPos;
hit.fromMouse = false;
s_SortedGraphics.Add(hit);
}
}
}
s_SortedGraphics.Sort((g1, g2) => g2.graphic.depth.CompareTo(g1.graphic.depth));
for (int i = 0; i < s_SortedGraphics.Count; ++i)
{
results.Add(s_SortedGraphics[i]);
}
}
19
Source : HighlightTextBlock.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private static List<(int start, int end)> MergeIntervals(List<(int start, int end)> intervals)
{
if (!intervals?.Any() ?? true) return new List<(int, int)>();
intervals.Sort((x, y) => x.start != y.start ? x.start - y.start : x.end - y.end);
(int startPointer, int endPointer) = intervals[0];
var result = new List<(int, int)>();
foreach ((int start, int end) in intervals.Skip(1))
{
if (start <= endPointer)
{
if (endPointer < end)
{
endPointer = end;
}
}
else
{
result.Add((startPointer, endPointer));
(startPointer, endPointer) = (start, end);
}
}
result.Add((startPointer, endPointer));
return result;
}
19
Source : Program.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static async Task Main(string[] args)
{
var launcherArgs = ParseLauncherArgs(args);
if (launcherArgs.Delay > 0)
{
await Task.Delay(TimeSpan.FromMilliseconds(launcherArgs.Delay));
}
// 1. Find the latest version bin folder.
var bins = GetBinDirectories(CurrentDirectory).ToList();
if (!bins.Any()) return;
bins.Sort((x, y) => x.Version > y.Version ? -1 : 1);
foreach (var bin in bins)
{
// 2. Try to start the main program.
try
{
var process = new Process
{
StartInfo =
{
FileName = Path.Combine(bin.DirectoryName, MainProgramName),
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = launcherArgs.AutoLogin ? "--auto-login" : string.Empty
}
};
process.Start();
// 3. Clear history versions.
foreach (var directory in bins.Where(item => !bin.Equals(item)))
{
await DeleteDirectoryAsync(directory.DirectoryName);
}
}
catch (Win32Exception)
{
// TODO: Logging or Notify.
await DeleteDirectoryAsync(bin.DirectoryName);
}
}
}
19
Source : MessageBuffer.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public ClientMessage GetMessage()
{
fragments.Sort(delegate (ClientPacketFragment x, ClientPacketFragment y) { return x.Header.Index - y.Header.Index; });
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
foreach (ClientPacketFragment fragment in fragments)
{
writer.Write(fragment.Data);
}
stream.Seek(0, SeekOrigin.Begin);
return new ClientMessage(stream);
}
19
Source : Container.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public bool TryAddToInventory(WorldObject worldObject, out Container container, int placementPosition = 0, bool limitToMainPackOnly = false, bool burdenCheck = true)
{
// bug: should be root owner
if (this is Player player && burdenCheck)
{
if (!player.HasEnoughBurdenToAddToInventory(worldObject))
{
container = null;
return false;
}
}
IList<WorldObject> containerItems;
if (worldObject.UseBackpackSlot)
{
containerItems = Inventory.Values.Where(i => i.UseBackpackSlot).ToList();
if ((ContainerCapacity ?? 0) <= containerItems.Count)
{
container = null;
return false;
}
}
else
{
containerItems = Inventory.Values.Where(i => !i.UseBackpackSlot).ToList();
if ((ItemCapacity ?? 0) <= containerItems.Count)
{
// Can we add this to any side pack?
if (!limitToMainPackOnly)
{
var containers = Inventory.Values.OfType<Container>().ToList();
containers.Sort((a, b) => (a.Placement ?? 0).CompareTo(b.Placement ?? 0));
foreach (var sidePack in containers)
{
if (sidePack.TryAddToInventory(worldObject, out container, placementPosition, true))
{
EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
Value += (worldObject.Value ?? 0);
return true;
}
}
}
container = null;
return false;
}
}
if (Inventory.ContainsKey(worldObject.Guid))
{
container = null;
return false;
}
worldObject.Location = null;
worldObject.Placement = ACE.Enreplacedy.Enum.Placement.Resting;
worldObject.OwnerId = Guid.Full;
worldObject.ContainerId = Guid.Full;
worldObject.Container = this;
worldObject.PlacementPosition = placementPosition; // Server only variable that we use to remember/restore the order in which items exist in a container
// Move all the existing items PlacementPosition over.
if (!worldObject.UseBackpackSlot)
containerItems.Where(i => !i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);
else
containerItems.Where(i => i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);
Inventory.Add(worldObject.Guid, worldObject);
EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
Value += (worldObject.Value ?? 0);
container = this;
OnAddItem();
return true;
}
19
Source : SortableBindingList.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
{
List<T> itemsList = (List<T>)this.Items;
Type propertyType = property.PropertyType;
PropertyComparer<T> comparer;
if (!this.comparers.TryGetValue(propertyType, out comparer))
{
comparer = new PropertyComparer<T>(property, direction);
this.comparers.Add(propertyType, comparer);
}
comparer.SetPropertyAndDirection(property, direction);
itemsList.Sort(comparer);
this.propertyDescriptor = property;
this.listSortDirection = direction;
this.isSorted = true;
this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
19
Source : ApplicationViewModel.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void UpdateSearchResults() {
var list = new List<ProducreplacedemInfo>();
// Score all items
var searchParts = this.SearchText.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var productFamily in this.ProductData.ProductFamilies) {
foreach (var producreplacedemInfo in productFamily.Items) {
producreplacedemInfo.SearchScore = SampleSearchScorer.Score(producreplacedemInfo, searchParts);
if (producreplacedemInfo.SearchScore > 0)
list.Add(producreplacedemInfo);
}
}
// Sort
list.Sort((x, y) => y.SearchScore.CompareTo(x.SearchScore));
// Trim to the maximum number of results
if (list.Count > MaximumSearchResults)
list.RemoveRange(MaximumSearchResults, list.Count - MaximumSearchResults);
this.SearchResults = list;
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void BindProducts() {
// Manually reference these type to ensure the related replacedemblies are loaded since they may not yet have been loaded by default
var srTypes = new Type[] {
// None: typeof(ActiproSoftware.Products.SyntaxEditor.Addons.JavaScript.SR),
typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Python.SR),
typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Xml.SR),
typeof(ActiproSoftware.Products.Text.Addons.JavaScript.SR),
typeof(ActiproSoftware.Products.Text.Addons.Python.SR),
typeof(ActiproSoftware.Products.Text.Addons.Xml.SR),
};
var productResources = new List<ProductResource>();
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
var name = replacedembly.GetName().Name;
if ((name.StartsWith("ActiproSoftware.", StringComparison.OrdinalIgnoreCase)) && (name.EndsWith(".Wpf", StringComparison.OrdinalIgnoreCase))) {
var productResource = new ProductResource(replacedembly);
if (productResource.IsValid)
productResources.Add(productResource);
}
}
productResources.Sort((x, y) => x.Name.CompareTo(y.Name));
productComboBox.ItemsSource = productResources;
if (productComboBox.Items.Count > 0)
productComboBox.SelectedIndex = 0;
}
19
Source : Diagnostics.cs
with MIT License
from adamant
with MIT License
from adamant
public FixedList<Diagnostic> Build()
{
items.Sort((d1, d2) => d1.StartPosition.CompareTo(d2.StartPosition));
return items.ToFixedList();
}
19
Source : ContentMapCrmSiteMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private SiteMapNodeCollection GetChildNodes(SiteMapNode node, ContentMap map)
{
WebsiteNode site;
IContentMapEnreplacedyUrlProvider urlProvider;
using (PerformanceProfiler.Instance.StartMarker(PerformanceMarkerName.SiteMapProvider, PerformanceMarkerArea.Cms, PerformanceMarkerTagName.GetChildNodes))
{
if (!TryGetWebsite(map, out site, out urlProvider))
{
return base.GetChildNodes(node);
}
var children = new List<SiteMapNode>();
// Shorcuts do not have children, may have the same Url as a web page.
if (IsShortcutNode(node))
{
return new SiteMapNodeCollection();
}
// SiteMap is not language-aware, so the node.Url will always be URL of the root WebPage, so look for root.
var langContext = HttpContext.Current.GetContextLanguageInfo();
var filterResult = ContentMapUrlMapping.LookupPageByUrlPath(site, node.Url, ContentMapUrlMapping.WebPageLookupOptions.RootOnly, langContext);
if (filterResult.Node != null && filterResult.IsUnique)
{
var portal = PortalContext;
var context = portal.ServiceContext;
foreach (var child in filterResult.Node.WebPages)
{
// Only get children pages who match the current active language.
var childNode = IsValidLanguageContentPage(child, langContext) ? GetNode(map, child, HttpStatusCode.OK, urlProvider) : null;
if (childNode == null)
{
continue;
}
if (ChildNodeValidator.Validate(context, childNode))
{
children.Add(childNode);
}
}
foreach (var file in filterResult.Node.WebFiles)
{
var childNode = GetNode(map, file, urlProvider);
if (ChildNodeValidator.Validate(context, childNode))
{
children.Add(childNode);
}
}
foreach (var shortcut in filterResult.Node.Shortcuts)
{
var childNode = GetNode(map, shortcut, urlProvider);
if (childNode != null && ChildNodeValidator.Validate(context, childNode))
{
children.Add(childNode);
}
}
}
// Append values from other site map providers.
foreach (SiteMapProvider subProvider in SiteMap.Providers)
{
// Skip this provider if it is the same as this one.
if (subProvider.Name == Name) continue;
// Check if the provider has solution dependencies
var solutionDependent = subProvider as ISolutionDependent;
if (solutionDependent != null)
{
if (map.Solution.Solutions.Intersect(solutionDependent.RequiredSolutions).Count() != solutionDependent.RequiredSolutions.Count())
{
continue;
}
}
var subProviderChildNodes = subProvider.GetChildNodes(node);
if (subProviderChildNodes == null) continue;
foreach (SiteMapNode childNode in subProviderChildNodes)
{
children.Add(childNode);
}
}
children.Sort(new SiteMapNodeDisplayOrderComparer());
return new SiteMapNodeCollection(children.ToArray());
}
}
19
Source : CrmSiteMapProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
{
TraceInfo("GetChildNodes({0})", node.Key);
var children = new List<SiteMapNode>();
var portal = PortalContext;
var context = portal.ServiceContext;
var website = portal.Website;
// Shorcuts do not have children, may have the same Url as a web page.
if (IsShortcutNode(node))
{
return new SiteMapNodeCollection();
}
var pageMappingResult = UrlMapping.LookupPageByUrlPath(context, website, node.Url);
// If the node URL is that of a web page...
if (pageMappingResult.Node != null && pageMappingResult.IsUnique)
{
var childEnreplacedies = context.GetChildPages(pageMappingResult.Node).Union(context.GetChildFiles(pageMappingResult.Node)).Union(context.GetChildShortcuts(pageMappingResult.Node));
foreach (var enreplacedy in childEnreplacedies)
{
try
{
if (enreplacedy.LogicalName == "adx_shortcut")
{
var targetNode = GetShortcutTargetNode(context, enreplacedy);
var shortcutChildNode = GetShortcutCrmNode(context, enreplacedy, targetNode);
if (shortcutChildNode != null && ChildNodeValidator.Validate(context, shortcutChildNode))
{
children.Add(shortcutChildNode);
}
}
else
{
var childNode = GetNode(context, enreplacedy);
if (childNode != null && ChildNodeValidator.Validate(context, childNode))
{
children.Add(childNode);
}
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception creating child node for node child enreplacedy [{0}:{1}]: {2}", EnreplacedyNamePrivacy.GetEnreplacedyName(enreplacedy.LogicalName), enreplacedy.Id, e.ToString()));
continue;
}
}
}
// Append values from other site map providers.
foreach (SiteMapProvider subProvider in SiteMap.Providers)
{
// Skip this provider if it is the same as this one.
if (subProvider.Name == Name) continue;
var subProviderChildNodes = subProvider.GetChildNodes(node);
if (subProviderChildNodes == null) continue;
foreach (SiteMapNode childNode in subProviderChildNodes)
{
children.Add(childNode);
}
}
children.Sort(new SiteMapNodeDisplayOrderComparer());
return new SiteMapNodeCollection(children.ToArray());
}
19
Source : TreeViewWithTreeModel.cs
with MIT License
from Adsito
with MIT License
from Adsito
protected virtual void SortSearchResult (List<TreeViewItem> rows)
{
rows.Sort ((x,y) => EditorUtility.NaturalCompare (x.displayName, y.displayName)); // sort by displayName by default, can be overriden for multicolumn solutions
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public T Load<T>(IreplacedetInfo replacedet)
{
Monitor.Log($"loading replacedet for {replacedet.replacedetName}");
if (replacedet.replacedetName.StartsWith("Characters\\Baby") || replacedet.replacedetName.StartsWith("Characters\\Toddler") || replacedet.replacedetName.StartsWith("Characters/Baby") || replacedet.replacedetName.StartsWith("Characters/Toddler"))
{
if(replacedet.replacedetNameEquals("Characters\\Baby") || replacedet.replacedetNameEquals("Characters\\Baby_dark") || replacedet.replacedetNameEquals("Characters\\Toddler") || replacedet.replacedetNameEquals("Characters\\Toddler_dark") || replacedet.replacedetNameEquals("Characters\\Toddler_girl") || replacedet.replacedetNameEquals("Characters\\Toddler_girl_dark"))
{
Monitor.Log($"loading default child replacedet for {replacedet.replacedetName}");
return (T)(object)Helper.Content.Load<Texture2D>($"replacedets/{replacedet.replacedetName.Replace("Characters\\", "").Replace("Characters/", "")}.png", ContentSource.ModFolder);
}
if(replacedet.replacedetNameEquals("Characters/Baby") || replacedet.replacedetNameEquals("Characters/Baby_dark") || replacedet.replacedetNameEquals("Characters/Toddler") || replacedet.replacedetNameEquals("Characters/Toddler_dark") || replacedet.replacedetNameEquals("Characters/Toddler_girl") || replacedet.replacedetNameEquals("Characters/Toddler_girl_dark"))
{
Monitor.Log($"loading default child replacedet for {replacedet.replacedetName}");
return (T)(object)Helper.Content.Load<Texture2D>($"replacedets/{replacedet.replacedetName.Replace("Characters/", "")}.png", ContentSource.ModFolder);
}
Monitor.Log($"loading child replacedet for {replacedet.replacedetName}");
string[] names = replacedet.replacedetName.Split('_');
Texture2D babySheet = Helper.Content.Load<Texture2D>(string.Join("_", names.Take(names.Length - 1)), ContentSource.GameContent);
Texture2D parentTexSheet = null;
string parent = names[names.Length - 1];
try
{
parentTexSheet = Helper.Content.Load<Texture2D>($"Characters/{parent}", ContentSource.GameContent);
}
catch
{
return (T)(object)babySheet;
}
if (parentTexSheet == null)
{
Monitor.Log($"couldn't find parent sheet for {replacedet.replacedetName}");
return (T)(object)babySheet;
}
Rectangle newBounds = parentTexSheet.Bounds;
newBounds.X = 0;
newBounds.Y = 64;
newBounds.Width = 16;
newBounds.Height = 32;
Texture2D parentTex = new Texture2D(Game1.graphics.GraphicsDevice, 16, 32);
Color[] data = new Color[parentTex.Width * parentTex.Height];
parentTexSheet.GetData(0, newBounds, data, 0, newBounds.Width * newBounds.Height);
int start = -1;
Dictionary<Color, int> colorCounts = new Dictionary<Color, int>();
for (int i = 0; i < data.Length; i++)
{
if(data[i] != Color.Transparent)
{
if(start == -1)
{
start = i / 16;
}
else
{
if (i / 16 - start > 8)
break;
}
if (colorCounts.ContainsKey(data[i]))
{
colorCounts[data[i]]++;
}
else
{
colorCounts.Add(data[i], 1);
Monitor.Log($"got hair color: {data[i]}");
}
}
}
if(colorCounts.Count == 0)
{
Monitor.Log($"parent sheet empty for {replacedet.replacedetName}");
return (T)(object)babySheet;
}
var countsList = colorCounts.ToList();
countsList.Sort((pair1, pair2) => pair2.Value.CompareTo(pair1.Value));
List<Color> hairColors = new List<Color>();
for (int k = 0; k < Math.Min(countsList.Count, 4); k++)
{
Monitor.Log($"using hair color: {countsList[k].Key} {countsList[k].Value}");
hairColors.Add(countsList[k].Key);
}
hairColors.Sort((color1, color2) => (color1.R + color1.G + color1.B).CompareTo(color2.R + color2.G + color2.B));
Texture2D hairSheet = Helper.Content.Load<Texture2D>($"replacedets/hair/{string.Join("_", names.Take(names.Length - 1)).Replace("Characters\\","").Replace("Characters/","").Replace("_dark","")}.png", ContentSource.ModFolder);
Color[] babyData = new Color[babySheet.Width * babySheet.Height];
Color[] hairData = new Color[babySheet.Width * babySheet.Height];
babySheet.GetData(babyData);
hairSheet.GetData(hairData);
for(int i = 0; i < babyData.Length; i++)
{
if(hairData[i] != Color.Transparent)
{
if(hairColors.Count == 1)
{
hairColors.Add(hairColors[0]);
hairColors.Add(hairColors[0]);
hairColors.Add(hairColors[0]);
}
else if(hairColors.Count == 2)
{
hairColors.Add(hairColors[1]);
hairColors.Add(hairColors[1]);
hairColors[1] = new Color((hairColors[0].R + hairColors[0].R + hairColors[1].R) / 3, (hairColors[0].G + hairColors[0].G + hairColors[1].G) / 3, (hairColors[0].B + hairColors[0].B + hairColors[1].B) / 3);
hairColors[2] = new Color((hairColors[0].R + hairColors[2].R + hairColors[2].R) / 3, (hairColors[0].G + hairColors[2].G + hairColors[2].G) / 3, (hairColors[0].B + hairColors[2].B + hairColors[2].B) / 3);
}
else if(hairColors.Count == 3)
{
hairColors.Add(hairColors[2]);
hairColors[2] = new Color((hairColors[1].R + hairColors[2].R + hairColors[2].R) / 3, (hairColors[1].G + hairColors[2].G + hairColors[2].G) / 3, (hairColors[1].B + hairColors[2].B + hairColors[2].B) / 3);
hairColors[1] = new Color((hairColors[0].R + hairColors[0].R + hairColors[1].R) / 3, (hairColors[0].G + hairColors[0].G + hairColors[1].G) / 3, (hairColors[0].B + hairColors[0].B + hairColors[1].B) / 3);
}
//Monitor.Log($"Hair grey: {hairData[i].R}");
switch (hairData[i].R)
{
case 42:
babyData[i] = hairColors[0];
break;
case 60:
babyData[i] = hairColors[1];
break;
case 66:
babyData[i] = hairColors[1];
break;
case 82:
babyData[i] = hairColors[2];
break;
case 93:
babyData[i] = hairColors[2];
break;
case 114:
babyData[i] = hairColors[3];
break;
}
//Monitor.Log($"Hair color: {babyData[i]}");
}
}
babySheet.SetData(babyData);
return (T)(object)babySheet;
}
throw new InvalidOperationException($"Unexpected replacedet '{replacedet.replacedetName}'.");
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
private void ResortSocialList()
{
if (Game1.activeClickableMenu is GameMenu)
{
SocialPage page = (Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab] as SocialPage;
List<ClickableTextureComponent> sprites = new List<ClickableTextureComponent>(Helper.Reflection.GetField<List<ClickableTextureComponent>>(page, "sprites").GetValue());
List<NameSpriteSlot> nameSprites = new List<NameSpriteSlot>();
for(int i = 0; i < page.names.Count; i++)
{
nameSprites.Add(new NameSpriteSlot(page.names[i], sprites[i], page.characterSlots[i]));
}
switch (Config.CurrentSort)
{
case 0: // friend asc
Monitor.Log("sorting by friend asc");
nameSprites.Sort(delegate (NameSpriteSlot x, NameSpriteSlot y)
{
if (x.name is long && y.name is long) return 0;
else if (x.name is long) return -1;
else if (y.name is long) return 1;
return Game1.player.getFriendshipLevelForNPC(x.name as string).CompareTo(Game1.player.getFriendshipLevelForNPC(y.name as string));
});
break;
case 1: // friend desc
Monitor.Log("sorting by friend desc");
nameSprites.Sort(delegate (NameSpriteSlot x, NameSpriteSlot y)
{
if (x.name is long && y.name is long) return 0;
else if (x.name is long) return -1;
else if (y.name is long) return 1;
return -(Game1.player.getFriendshipLevelForNPC(x.name as string).CompareTo(Game1.player.getFriendshipLevelForNPC(y.name as string)));
});
break;
case 2: // alpha asc
Monitor.Log("sorting by alpha asc");
nameSprites.Sort(delegate (NameSpriteSlot x, NameSpriteSlot y)
{
return (x.name is long ? Game1.getFarmer((long)x.name).name : GetNPCDisplayName(x.name as string)).CompareTo(y.name is long ? Game1.getFarmer((long)y.name).name : GetNPCDisplayName(y.name as string));
});
break;
case 3: // alpha desc
Monitor.Log("sorting by alpha desc");
nameSprites.Sort(delegate (NameSpriteSlot x, NameSpriteSlot y)
{
return -((x.name is long ? Game1.getFarmer((long)x.name).name : GetNPCDisplayName(x.name as string)).CompareTo(y.name is long ? Game1.getFarmer((long)y.name).name : GetNPCDisplayName(y.name as string)));
});
break;
}
for(int i = 0; i < nameSprites.Count; i++)
{
((Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab] as SocialPage).names[i] = nameSprites[i].name;
sprites[i] = nameSprites[i].sprite;
((Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab] as SocialPage).characterSlots[i] = nameSprites[i].slot;
}
Helper.Reflection.GetField<List<ClickableTextureComponent>>((Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab], "sprites").SetValue(new List<ClickableTextureComponent>(sprites));
int first_character_index = 0;
for (int l = 0; l < page.names.Count; l++)
{
if (!(((SocialPage)(Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab]).names[l] is long))
{
first_character_index = l;
break;
}
}
Helper.Reflection.GetField<int>((Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab], "slotPosition").SetValue(first_character_index);
Helper.Reflection.GetMethod((Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab], "setScrollBarToCurrentIndex").Invoke();
((SocialPage)(Game1.activeClickableMenu as GameMenu).pages[GameMenu.socialTab]).updateSlots();
}
}
19
Source : UIGrid.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public void Reposition()
{
if (!this.mStarted)
{
this.repositionNow = true;
return;
}
Transform transform = base.transform;
int num = 0;
int num2 = 0;
if (this.sorted)
{
List<Transform> list = new List<Transform>();
for (int i = 0; i < transform.childCount; i++)
{
Transform child = transform.GetChild(i);
if (child && (!this.hideInactive || NGUITools.GetActive(child.gameObject)))
{
list.Add(child);
}
}
list.Sort(new Comparison<Transform>(UIGrid.SortByName));
int j = 0;
int count = list.Count;
while (j < count)
{
Transform transform2 = list[j];
if (NGUITools.GetActive(transform2.gameObject) || !this.hideInactive)
{
float z = transform2.localPosition.z;
transform2.localPosition = ((this.arrangement != UIGrid.Arrangement.Horizontal) ? new Vector3(this.cellWidth * (float)num2, -this.cellHeight * (float)num, z) : new Vector3(this.cellWidth * (float)num, -this.cellHeight * (float)num2, z));
if (++num >= this.maxPerLine && this.maxPerLine > 0)
{
num = 0;
num2++;
}
}
j++;
}
}
else
{
for (int k = 0; k < transform.childCount; k++)
{
Transform child2 = transform.GetChild(k);
if (NGUITools.GetActive(child2.gameObject) || !this.hideInactive)
{
float z2 = child2.localPosition.z;
child2.localPosition = ((this.arrangement != UIGrid.Arrangement.Horizontal) ? new Vector3(this.cellWidth * (float)num2, -this.cellHeight * (float)num, z2) : new Vector3(this.cellWidth * (float)num, -this.cellHeight * (float)num2, z2));
if (++num >= this.maxPerLine && this.maxPerLine > 0)
{
num = 0;
num2++;
}
}
}
}
UIDraggablePanel uidraggablePanel = NGUITools.FindInParents<UIDraggablePanel>(base.gameObject);
if (uidraggablePanel != null)
{
uidraggablePanel.UpdateScrollbars(true);
}
}
19
Source : UpdateManager.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private void Add(MonoBehaviour mb, int updateOrder, UpdateManager.OnUpdate func, List<UpdateManager.UpdateEntry> list)
{
int i = 0;
int count = list.Count;
while (i < count)
{
UpdateManager.UpdateEntry updateEntry = list[i];
if (updateEntry.func == func)
{
return;
}
i++;
}
list.Add(new UpdateManager.UpdateEntry
{
index = updateOrder,
func = func,
mb = mb,
isMonoBehaviour = (mb != null)
});
if (updateOrder != 0)
{
list.Sort(new Comparison<UpdateManager.UpdateEntry>(UpdateManager.Compare));
}
}
19
Source : UICamera.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
private void Start()
{
UICamera.mList.Add(this);
UICamera.mList.Sort(new Comparison<UICamera>(UICamera.CompareFunc));
}
19
Source : InvGameItem.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public List<InvStat> CalculateStats()
{
List<InvStat> list = new List<InvStat>();
if (this.baseItem != null)
{
float statMultiplier = this.statMultiplier;
List<InvStat> stats = this.baseItem.stats;
int i = 0;
int count = stats.Count;
while (i < count)
{
InvStat invStat = stats[i];
int num = Mathf.RoundToInt(statMultiplier * (float)invStat.amount);
if (num != 0)
{
bool flag = false;
int j = 0;
int count2 = list.Count;
while (j < count2)
{
InvStat invStat2 = list[j];
if (invStat2.id == invStat.id && invStat2.modifier == invStat.modifier)
{
invStat2.amount += num;
flag = true;
break;
}
j++;
}
if (!flag)
{
list.Add(new InvStat
{
id = invStat.id,
amount = num,
modifier = invStat.modifier
});
}
}
i++;
}
list.Sort(new Comparison<InvStat>(InvStat.CompareArmor));
}
return list;
}
19
Source : StatusPanel.cs
with GNU General Public License v3.0
from aenemenate
with GNU General Public License v3.0
from aenemenate
public static void RenderStatus()
{
Color textColor = Color.AntiqueWhite, highlightedColor = Color.OrangeRed, bgColor = statusColorDarker;
Point mousePos = new Point( SadConsole.Global.MouseState.ScreenPosition.X / SadConsole.Global.FontDefault.Size.X,
SadConsole.Global.MouseState.ScreenPosition.Y / SadConsole.Global.FontDefault.Size.Y );
// FUNCTIONS //
void PrintLookFunc()
{
int currentFloor = Program.Player.CurrentFloor;
Point worldIndex = Program.Player.WorldIndex;
Block[] blocks = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Blocks : Program.WorldMap[worldIndex.X, worldIndex.Y].Blocks;
Tile[] tiles = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Floor : Program.WorldMap[worldIndex.X, worldIndex.Y].Floor;
int width = Program.WorldMap.TileWidth, height = Program.WorldMap.TileHeight;
Point mapPos = Program.WorldMap[worldIndex.X, worldIndex.Y].GetMousePos(mousePos);
bool mouseIsOnMap = !(mousePos.X < 0 || mousePos.X >= Program.Console.Width - StatusPanel.Width);
Program.Window.Print(StartX + 1, Program.Window.Height - 3, " ", 18);
Program.Window.Print(StartX + 1, Program.Window.Height - 2, " ", 18);
if (Program.CurrentState is Play && Program.WorldMap[worldIndex.X, worldIndex.Y].PointWithinBounds(mapPos) && mouseIsOnMap && blocks[mapPos.X * width + mapPos.Y].Explored)
{
if (blocks[mapPos.X * width + mapPos.Y].Type != BlockType.Empty) {
if (blocks[mapPos.X * width + mapPos.Y] is Item item) {
Program.Window.Print(StartX + 1, Program.Window.Height - (2 + item.Name.Length / 17), item.Name, 17);
Tuple<byte, Color> comparisonArrow = GUI.GereplacedemArrow(item);
int arrowX = StartX + 1 + item.Name.Length + 2, arrowY = Program.Window.Height - 2;
for (int i = StartX + 1; i < Program.Window.Width; i++) {
if (Program.Console.GetGlyph(i - 1, Program.Window.Height - 2) == 32 && Program.Console.GetGlyph(i, Program.Window.Height - 2) == 32) {
arrowX = i;
break;
}
}
if (comparisonArrow.Item1 != 0)
Program.Console.SetGlyph(arrowX, arrowY, comparisonArrow.Item1, comparisonArrow.Item2);
}
else if (blocks[mapPos.X * width + mapPos.Y] is Player player)
Program.Window.Print(StartX + 1, Program.Window.Height - 3, $"You, on {player.CurrentBlock.Name}.", 18);
else
Program.Window.Print(StartX + 1, Program.Window.Height - 3, blocks[mapPos.X * width + mapPos.Y].Name, 18);
}
else
Program.Window.Print(StartX + 1, Program.Window.Height - 3, tiles[mapPos.X * width + mapPos.Y].Name, 18);
}
}
void PrintBgColor()
{
// fill the background
if (!Program.Console.GetBackground( Program.Window.Width - 1, 0 ).Equals( statusColorDarker ))
for (int i = Program.Window.Width - 1; i >= StartX; i--)
for (int j = 0; j < Program.Console.Height; j++)
Program.Console.SetGlyph( i, j, ' ', statusColorDarker, statusColorDarker );
}
void DrawResourceBar(int y, int hp, int maxhp, int barWidth, Color barColor, string text = "")
{
for (int i = 0; i < barWidth; i++)
{
if (( ( i * maxhp ) / barWidth ) + 1 <= hp && hp != 0)
Program.Console.SetGlyph( StartX + 1 + i, y, 178, barColor, barColor );
else
Program.Console.Print( StartX + 1 + i, y, " ", bgColor * 0.98F, bgColor * 0.98F );
}
string healthNum = text == "" ? $"{hp}/{maxhp}" : text;
int numStartX = StartX + 1 + barWidth / 2 - healthNum.Length / 2;
Program.Console.Print( numStartX, y, healthNum, textColor );
}
void PrintTime()
{
string hour = $"{Program.TimeHandler.CurrentTime.Hour}";
string minute = $"{Program.TimeHandler.CurrentTime.Minute}";
string second = $"{Program.TimeHandler.CurrentTime.Second}";
if (hour.Length == 1)
hour = "0" + hour;
if (minute.Length == 1)
minute = "0" + minute;
if (second.Length == 1)
second = "0" + second;
string time = hour + ":" + minute + ":" + second;
Program.Console.Print( StartX + ( width / 2 - time.Length / 2 ), tabStartY - 4, time, textColor );
}
void PrintTabs()
{
Color borderColor = textColor * 0.95F;
byte topLeft = 218, topRight = 191, bottomLeft = 192, bottomRight = 217, bottomLeftT = 195, bottomRightT = 180, horizontal = 196, vertical = 179, topT = 194, bottomT = 193;
void PrintTabMarker( int tab )
{
int leftMargin = 1;
string tabName = "locals";
if (tab != 0)
{
leftMargin = tab == 1 ? 8 : 15;
tabName = tab == 1 ? "skills" : "quests";
}
Program.Console.Print( StartX + leftMargin, tabStartY - 2, tabName, textColor );
if (tab == selectedTab)
{
Program.Console.Print( StartX + leftMargin, tabStartY - 1, " " );
Program.Console.SetGlyph( StartX + leftMargin - 1, tabStartY - 1, selectedTab != 0 ? bottomRight : vertical, borderColor );
Program.Console.SetGlyph( StartX + leftMargin + 6, tabStartY - 1, selectedTab != 2 ? bottomLeft : vertical, borderColor );
}
}
// print tabs and their borders
for (int i = StartX; i < Program.Console.Width; i++)
for (int j = tabStartY - 3; j < tabStartY; j++)
{
byte character = horizontal;
if (j == tabStartY - 3 || j == tabStartY - 1)
{
if (i == StartX)
character = j == tabStartY - 3 ? topLeft : bottomLeftT;
else if (i == Program.Window.Width - 1)
character = j == tabStartY - 3 ? topRight : bottomRightT;
else if (i == StartX + 7 || i == StartX + 14)
character = j == tabStartY - 3 ? topT : bottomT;
} else
character = vertical;
Program.Console.SetGlyph( i, j, character, borderColor );
}
if (Program.Console.GetGlyph( StartX, tabStartY ) != vertical)
// print left and right side of tab window border
for (int j = tabStartY; j < Program.Window.Height - 1; j++)
{
Program.Console.SetGlyph( StartX, j, vertical, borderColor );
Program.Console.SetGlyph( Program.Window.Width - 1, j, vertical, borderColor );
}
// bottom row
for (int i = StartX + 1; i < Program.Window.Width - 1; i++)
Program.Console.SetGlyph( i, Program.Window.Height - 1, horizontal, borderColor );
Program.Console.SetGlyph( StartX, Program.Window.Height - 1, bottomLeft, borderColor );
Program.Console.SetGlyph( Program.Window.Width - 1, Program.Window.Height - 1, bottomRight, borderColor );
PrintTabMarker( 0 );
PrintTabMarker( 1 );
PrintTabMarker( 2 );
for (int j = tabStartY; j < Program.Window.Height - 1; j++)
Program.Console.Print( StartX + 1, j, " ", statusColorDarker, statusColorDarker );
switch (selectedTab) {
case 0: // locals
PrintLocals();
return;
case 1: // skills
PrintSkills();
return;
case 2: // quests
PrintQuests();
return;
}
}
void PrintLocals()
{
List<Creature> locals = Program.Player.LocalCreatures;
locals.Sort( ( x, y ) => x.Position.DistFrom(Program.Player.Position).CompareTo( y.Position.DistFrom( Program.Player.Position ) ) );
int heightofDisplay = Program.Console.Height - 3 - tabStartY;
//float bgAlpha = 0.99F, fgAlpha = 0.99F; //might use these at some point
void PrintCreatures ()
{
int padding = 0;
for (int i = 1, index = 0; i < heightofDisplay && index < locals.Count; i += padding, index++)
{
int curY = i + tabStartY;
Color tempBG = bgColor;
Creature creature = locals[index];
if (mousePos.Y >= curY && mousePos.Y <= curY + 1 & mousePos.X > StartX + 1 && mousePos.X < Program.Window.Width - 1) {
tempBG = bgColor * 1.3F;
curCreature = creature;
}
// draw creature name
curY += Program.Window.Print( Program.Console, StartX + 1, curY, creature.Name + " / LVL " + creature.Stats.Level.Lvl, 20, creature.Alive ? textColor : Color.DarkRed, tempBG);
// draw creature hp
if (creature.Alive)
DrawResourceBar(curY, creature.Stats.Resources[Resource.HP], creature.Stats.Resources[Resource.MaxHP], 20, new Color(45, 51, 122));
curY++;
// for each stat, draw if appropriate
if (creature is Player) {
DrawResourceBar(curY, creature.Stats.Resources[Resource.HV], creature.Stats.Resources[Resource.MaxHV], 20, new Color(45, 122, 51));
curY++;
DrawResourceBar( curY, creature.Stats.Resources[Resource.MP], creature.Stats.Resources[Resource.MaxMP], 20, new Color( 45, 122, 116 ) );
curY++;
DrawResourceBar( curY, creature.Stats.Resources[Resource.SP], creature.Stats.Resources[Resource.MaxSP], 20, new Color( 122, 116, 45 ) );
curY++;
}
// draw status effects
foreach (Effect effect in creature.Effects) {
DrawResourceBar( curY, effect.Turns, effect.TotalTurns, 20, new Color( 122, 45, 90 ), effect.Name );
curY++;
}
padding = 1 + curY - i - tabStartY;
}
}
PrintCreatures();
}
bool PrintSkills()
{
Program.Window.Print( Program.Console, StartX + 1, tabStartY + 1, "You haven't learned any skills.", width - 3, Color.LightGray );
return false;
}
bool PrintQuests()
{
Program.Window.Print(Program.Console, StartX + 1, tabStartY + 1, "You haven't embarked upon any quests.", width - 3, Color.LightGray );
return false;
}
// START //
PrintBgColor();
PrintTime();
PrintTabs();
PrintLookFunc();
}
19
Source : Planet.PrepareSubdivision.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
void Phase_3_Sort()
{
// bigger weight is first
toGenerateChunks.Sort((ToGenerateChunk a, ToGenerateChunk b) => b.weight.CompareTo(a.weight));
}
19
Source : Planet.PrepareSubdivision.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
void Phase_4_Sort()
{
// bigger weight is first
toRenderChunks.Sort((ToRenderChunks a, ToRenderChunks b) => b.weight.CompareTo(a.weight));
if (toRenderChunks.Count > maxChunksToRender)
{
toRenderChunks.RemoveRange(maxChunksToRender, toRenderChunks.Count - maxChunksToRender);
}
}
19
Source : AssetTreeView.cs
with MIT License
from akof1314
with MIT License
from akof1314
protected virtual bool OnWatcherMovedreplacedetsEvent(string[] movedFromreplacedetPaths, string[] movedreplacedets, bool resorreplacedem)
{
m_WatcherItems.Clear();
FindItemsByreplacedetPaths(rooreplacedem, movedFromreplacedetPaths, m_WatcherItems);
List<string> importedreplacedets = movedreplacedets.ToList();
if (m_WatcherItems.Count > 0)
{
var movedFromreplacedetPathsList = movedFromreplacedetPaths.ToList();
foreach (var item in m_WatcherItems)
{
var replacedetInfo = GereplacedemreplacedetInfo(item);
if (replacedetInfo != null)
{
int idx = movedFromreplacedetPathsList.IndexOf(replacedetInfo.fileRelativePath);
if (idx != -1)
{
replacedetInfo.fileRelativePath = movedreplacedets[idx];
replacedetInfo.displayName = Path.GetFileName(replacedetInfo.fileRelativePath);
importedreplacedets.Remove(movedreplacedets[idx]);
}
}
}
// 移除掉额外显示的项,因为不需要变动
m_WatcherItems.RemoveAll(IsExtraItem);
}
if (resorreplacedem && m_WatcherItems.Count > 0)
{
// 先移除
foreach (var watcherItem in m_WatcherItems)
{
if (watcherItem.parent != null)
{
watcherItem.parent.children.Remove(watcherItem);
}
watcherItem.parent = null;
var replacedetInfo = GereplacedemreplacedetInfo(watcherItem);
if (replacedetInfo != null)
{
if (replacedetInfo.parent != null)
{
replacedetInfo.parent.children.Remove(replacedetInfo);
}
replacedetInfo.parent = null;
}
}
// 排序,以防止先处理了文件
m_WatcherItems.Sort((a, b) =>
{
var aa = GereplacedemreplacedetInfo(a);
var bb = GereplacedemreplacedetInfo(b);
if (aa != null && bb != null)
{
return EditorUtility.NaturalCompare(aa.fileRelativePath, bb.fileRelativePath);
}
return EditorUtility.NaturalCompare(a.displayName, b.displayName);
});
foreach (var watcherItem in m_WatcherItems)
{
var replacedetInfo = GereplacedemreplacedetInfo(watcherItem);
if (replacedetInfo == null)
{
continue;
}
var item = FindItemByreplacedetPath(rooreplacedem, Path.GetDirectoryName(replacedetInfo.fileRelativePath));
if (item == null)
{
continue;
}
var replacedetInfo2 = GereplacedemreplacedetInfo(item);
if (replacedetInfo2 == null)
{
continue;
}
item.AddChild(watcherItem);
replacedetInfo2.AddChild(replacedetInfo);
}
SetupDepthsFromParentsAndChildren(rooreplacedem);
SortTreeViewNaturalCompare(rooreplacedem);
}
bool ret = OnWatcherImportedreplacedetsEvent(importedreplacedets.ToArray(), resorreplacedem);
return m_WatcherItems.Count > 0 || ret;
}
19
Source : DSPAudioKernelWidget.cs
with MIT License
from aksyr
with MIT License
from aksyr
public override void Init()
{
base.Init();
if (DSPReady)
{
using (var block = DSPGraph.CreateCommandBlock())
{
_DSPNode = block.CreateDSPNode<TParameters, TProviders, TAudioKernel>();
// gather possible inlets and outlets
List<DSPPortAttribute> inlets = new List<DSPPortAttribute>();
List<DSPPortAttribute> outlets = new List<DSPPortAttribute>();
{
var fields = NodeDataCache.GetNodeFields(GetType());
foreach (var field in fields)
{
var attributes = field.GetCustomAttributes(false).ToList();
var dspPort = attributes.Find(x => x is DSPPortAttribute) as DSPPortAttribute;
if (dspPort != null)
{
if (attributes.Find(x => x is InputAttribute) != null)
{
inlets.Add(dspPort);
}
else if (attributes.Find(x => x is OutputAttribute) != null)
{
outlets.Add(dspPort);
}
}
}
}
// sort by index
inlets.Sort((l, r) =>
{
return l.portIndex - r.portIndex;
});
outlets.Sort((l, r) =>
{
return l.portIndex - r.portIndex;
});
#if UNITY_replacedERTIONS
// validate
for (int i = 0; i < inlets.Count; ++i) Debug.replacedert(inlets[i].portIndex == i);
for (int i = 0; i < outlets.Count; ++i) Debug.replacedert(outlets[i].portIndex == i);
#endif
// add inlets and outlets
foreach (var inlet in inlets) block.AddInletPort(_DSPNode, inlet.channels, inlet.format);
foreach (var outlet in outlets) block.AddOutletPort(_DSPNode, outlet.channels, outlet.format);
AddUpdateParametersToBlock(block);
}
}
}
19
Source : Triangulator.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
private void CreateMountains()
{
foreach (Edge edge in _edgeList)
{
if (edge.MPoints.Count > 2)
{
MonotoneMountain mountain = new MonotoneMountain();
// Sorting is a perfromance hit. Literature says this can be accomplised in
// linear time, although I don't see a way around using traditional methods
// when using a randomized incremental algorithm
// Insertion sort is one of the fastest algorithms for sorting arrays containing
// fewer than ten elements, or for lists that are already mostly sorted.
List<Point> points = new List<Point>(edge.MPoints);
points.Sort((p1, p2) => p1.X.CompareTo(p2.X));
foreach (Point p in points)
mountain.Add(p);
// Triangulate monotone mountain
mountain.Process();
// Extract the triangles into a single list
foreach (List<Point> t in mountain.Triangles)
{
Triangles.Add(t);
}
_xMonoPoly.Add(mountain);
}
}
}
19
Source : ImagePacker.cs
with MIT License
from Alan-FGR
with MIT License
from Alan-FGR
public int PackImage(
IEnumerable<string> imageFiles,
bool requirePowerOfTwo,
bool requireSquareImage,
int maximumWidth,
int maximumHeight,
int imagePadding,
bool generateMap,
out Bitmap outputImage,
out Dictionary<string, Rectangle> outputMap)
{
files = new List<string>(imageFiles);
requirePow2 = requirePowerOfTwo;
requireSquare = requireSquareImage;
outputWidth = maximumWidth;
outputHeight = maximumHeight;
padding = imagePadding;
outputImage = null;
outputMap = null;
// make sure our dictionaries are cleared before starting
imageSizes.Clear();
imagePlacement.Clear();
// get the sizes of all the images
foreach (var filePath in files)
{
Bitmap bitmap;
using (var b = new Bitmap(filePath))
{
bitmap = new Bitmap(b); //FIXED! DARN NOOBS LOCKING MY FILESS!!!!! :trollface: - Alan, May 21, 3199BC
b.Dispose();
}
imageSizes.Add(filePath, bitmap.Size);
}
// sort our files by file size so we place large sprites first
files.Sort(
(f1, f2) =>
{
Size b1 = imageSizes[f1];
Size b2 = imageSizes[f2];
int c = -b1.Width.CompareTo(b2.Width);
if (c != 0)
return c;
c = -b1.Height.CompareTo(b2.Height);
if (c != 0)
return c;
return f1.CompareTo(f2);
});
// try to pack the images
if (!PackImageRectangles())
return -2;
// make our output image
outputImage = CreateOutputImage();
if (outputImage == null)
return -3;
if (generateMap)
{
// go through our image placements and replace the width/height found in there with
// each image's actual width/height (since the ones in imagePlacement will have padding)
string[] keys = new string[imagePlacement.Keys.Count];
imagePlacement.Keys.CopyTo(keys, 0);
foreach (var k in keys)
{
// get the actual size
Size s = imageSizes[k];
// get the placement rectangle
Rectangle r = imagePlacement[k];
// set the proper size
r.Width = s.Width;
r.Height = s.Height;
// insert back into the dictionary
imagePlacement[k] = r;
}
// copy the placement dictionary to the output
outputMap = new Dictionary<string, Rectangle>();
foreach (var pair in imagePlacement)
{
outputMap.Add(pair.Key, pair.Value);
}
}
// clear our dictionaries just to free up some memory
imageSizes.Clear();
imagePlacement.Clear();
return 0;
}
19
Source : GvrPointerGraphicRaycaster.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
private static void Raycast(Canvas canvas, Ray ray, Camera cam, float maxPointerDistance,
List<Graphic> results, out Ray finalRay) {
Vector3 screenPoint = cam.WorldToScreenPoint(ray.GetPoint(maxPointerDistance));
finalRay = cam.ScreenPointToRay(screenPoint);
// Necessary for the event system
IList<Graphic> foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas);
for (int i = 0; i < foundGraphics.Count; ++i) {
Graphic graphic = foundGraphics[i];
// -1 means it hasn't been processed by the canvas, which means it isn't actually drawn
if (graphic.depth == -1 || !graphic.raycastTarget) {
continue;
}
if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, screenPoint, cam)) {
continue;
}
if (graphic.Raycast(screenPoint, cam)) {
sortedGraphics.Add(graphic);
}
}
sortedGraphics.Sort((g1, g2) => g2.depth.CompareTo(g1.depth));
for (int i = 0; i < sortedGraphics.Count; ++i) {
results.Add(sortedGraphics[i]);
}
sortedGraphics.Clear();
}
19
Source : MixtureDocumentationWindow.cs
with MIT License
from alelievr
with MIT License
from alelievr
IEnumerator GenerateScreenshots()
{
var t = Resources.Load<Texture>("DoreplacedentationGraph");//.FirstOrDefault(g => { Debug.Log(g); return g is MixtureGraph;}) as MixtureGraph;
MixtureGraph docGraph = replacedetDatabase.LoadAllreplacedetsAtPath(replacedetDatabase.GetreplacedetPath(t)).FirstOrDefault(g => g is MixtureGraph) as MixtureGraph;
// Setup doc graph properties:
docGraph.scale = Vector3.one;
docGraph.position = new Vector3(0, toolbarHeight, 0);
docGraph.nodes.RemoveAll(n => !(n is OutputNode));
// yield return null;
var window = EditorWindow.CreateWindow<MixtureGraphWindow>();
window.Show();
window.Focus();
window.minSize = new Vector2(1024, 1024);
window.maxSize = new Vector2(1024, 1024);
var nodeViews = new List<BaseNodeView>();
foreach (var nodeType in TypeCache.GetTypesWithAttribute<NodeMenuItemAttribute>())
{
if (nodeType.IsAbstract)
continue;
Debug.Log("Generating doreplacedentation for " + nodeType);
var pathes = nodeType.GetCustomAttributes<NodeMenuItemAttribute>();
if (pathes.Any(p => p.menureplacedle.Contains("Experimental")))
continue;
// Skip non-mixture nodes:
if (!nodeType.FullName.Contains("Mixture"))
continue;
// We'll suport loops after
if (typeof(ILoopStart).IsreplacedignableFrom(nodeType) || typeof(ILoopEnd).IsreplacedignableFrom(nodeType))
continue;
window.InitializeGraph(docGraph);
var graphView = window.view;
var newNode = BaseNode.CreateFromType(nodeType, new Vector2(0, toolbarHeight));
var nodeView = graphView.AddNode(newNode);
nodeViews.Add(nodeView);
graphView.Add(nodeView);
SetupNodeIfNeeded(nodeView);
graphView.MarkDirtyRepaint();
graphView.UpdateViewTransform(new Vector3(0, 0, 0), Vector3.one * graphView.scale);
graphView.Focus();
MixtureGraphProcessor.RunOnce(docGraph);
yield return new WaitForEndOfFrame();
if (window == null)
yield break;
graphView.MarkDirtyRepaint();
TakeAndSaveNodeScreenshot(window, nodeView);
GenerateNodeMarkdownDoc(nodeView);
graphView.RemoveNodeView(nodeView);
graphView.graph.RemoveNode(nodeView.nodeTarget);
graphView.MarkDirtyRepaint();
yield return new WaitForEndOfFrame();
}
nodeViews.Sort((n1, n2) => n1.nodeTarget.name.CompareTo(n2.nodeTarget.name));
GenerateNodeIndexFiles(nodeViews);
foreach (var node in docGraph.nodes.ToList())
if (!(node is OutputNode))
docGraph.RemoveNode(node);
window.Close();
}
19
Source : MicroSplatShaderGUI_Compiler.cs
with MIT License
from alelievr
with MIT License
from alelievr
void WriteFeatures(string[] features, StringBuilder sb)
{
sb.AppendLine();
for (int i = 0; i < features.Length; ++i)
{
sb.AppendLine(" #define " + features[i] + " 1");
}
sb.AppendLine();
sb.AppendLine(sharedInc.text);
// sort for compile order
extensions.Sort(delegate(FeatureDescriptor p1, FeatureDescriptor p2)
{
if (p1.CompileSortOrder() != p2.CompileSortOrder())
return (p1.CompileSortOrder() < p2.CompileSortOrder()) ? -1 : 1;
return p1.GetType().Name.CompareTo(p2.GetType().Name);
});
for (int i = 0; i < extensions.Count; ++i)
{
var ext = extensions[i];
if (ext.GetVersion() == MicroSplatVersion)
{
extensions[i].WriteFunctions(sb);
}
}
// sort by name, then display order..
extensions.Sort(delegate(FeatureDescriptor p1, FeatureDescriptor p2)
{
if (p1.DisplaySortOrder() != 0 || p2.DisplaySortOrder() != 0)
{
return p1.DisplaySortOrder().CompareTo(p2.DisplaySortOrder());
}
return p1.GetType().Name.CompareTo(p2.GetType().Name);
});
}
19
Source : BiomeSurfaceGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
public bool BuildGraph(List< BiomeSurfaceSwitch > surfacesSwitches)
{
var bSwitchCellMap = new Dictionary< BiomeSurfaceSwitch, BiomeSurfaceCell >();
isBuilt = false;
if (surfacesSwitches.Count == 0)
return false;
surfaceType = surfacesSwitches.First().surface.type;
Action< BiomeSurfaceCell, BiomeSurfaceSwitch > AddLink = (cell, s) => {
var link = new BiomeSurfaceLink();
link.toCell = bSwitchCellMap[s];
if (!cell.links.Any(c => c.toCell == link.toCell))
cell.links.Add(link);
};
//calcul ranges
float heightRange = surfacesSwitches.Max(s => s.maxHeight) - surfacesSwitches.Min(s => s.minHeight);
float slopeRange = surfacesSwitches.Max(s => s.maxSlope) - surfacesSwitches.Min(s => s.minSlope);
float paramRange = surfacesSwitches.Max(s => s.maxParam) - surfacesSwitches.Min(s => s.minParam);
//Generate surface switches nodes:
foreach (var bSwitch in surfacesSwitches)
bSwitchCellMap[bSwitch] = new BiomeSurfaceCell();
cells.Clear();
lastCell = null;
foreach (var bSwitch in surfacesSwitches)
{
BiomeSurfaceCell cell = bSwitchCellMap[bSwitch];
cell.surface = bSwitch.surface;
cell.surfaceSwitch = bSwitch;
cell.weight = bSwitch.GetWeight(heightRange, slopeRange, paramRange);
foreach (var biomeSwitch in surfacesSwitches)
if (biomeSwitch.Overlaps(bSwitch))
AddLink(cell, biomeSwitch);
cell.links.Sort((l1, l2) => {
float w1 = l1.toCell.weight;
float w2 = l2.toCell.weight;
//reverse sort
return w2.CompareTo(w1);
});
cells.Add(cell);
}
rootCell = cells.First();
if (!CheckValid())
return false;
isBuilt = true;
return true;
}
19
Source : BaseGraph.cs
with MIT License
from alelievr
with MIT License
from alelievr
public List< BaseNode > GetNodeChildsRecursive(BaseNode begin)
{
var nodeStack = new Stack< BaseNode >();
var nodesMap = new HashSet< BaseNode >();
var nodesList = new List< BaseNode >();
nodeStack.Push(begin);
while (nodeStack.Count != 0)
{
var node = nodeStack.Pop();
foreach (var outNode in node.GetOutputNodes())
nodeStack.Push(outNode);
if (node != begin)
{
if (!nodesMap.Contains(node))
nodesList.Add(node);
nodesMap.Add(node);
}
}
nodesList.Sort((n1, n2) => n1.computeOrder.CompareTo(n2.computeOrder));
return nodesList;
}
See More Examples