Survivalcraft API 1.8.2.3 v1.8.2.3
Survivalcraft 2.4
载入中...
搜索中...
未找到
Program.cs
浏览该文件的文档.
1#if ANDROID
2using Android.Content;
3#elif BROWSER
4using System.Runtime.Versioning;
6#else
7using Engine.Input;
8using System.Diagnostics;
9#if WINDOWS
10using ImeSharp;
11using System.Security.Cryptography;
12using System.Text;
13using System.Reflection;
14#endif
15#endif
16using System.Globalization;
17using Engine;
18using Engine.Graphics;
19
20#if BROWSER
21[assembly: SupportedOSPlatform("browser")]
22#endif
23namespace Game {
24 public static class Program {
25 public static double m_frameBeginTime;
26 public static double m_cpuEndTime;
27 public static List<Uri> m_urisToHandle = [];
28#if WINDOWS
29 public static Mutex m_mutex;
30 public static bool m_mutexHandled;
31#endif
32 public static string SystemLanguage { get; set; }
33 public static float LastFrameTime { get; set; }
34
35 public static float LastCpuFrameTime { get; set; }
36
37 public static event Action<Uri> HandleUri;
38#if ANDROID || BROWSER
39 public static bool m_firstFramePrepared;
40#endif
41
42#if !ANDROID
43 // ReSharper disable UnusedMember.Local
44#if BROWSER
45 public static async Task Main2(string[] args) {
49 unsafe {
50 Emscripten.RequestAnimationFrameLoop((delegate* unmanaged<double, nint, int>)&Frame, nint.Zero);
51 }
52 }
53
54 public static int Counter;
55 [System.Runtime.InteropServices.UnmanagedCallersOnly]
56 public static int Frame(double time, nint userData)
57 {
60 PrimitivesRenderer2D primitivesRenderer2D = new PrimitivesRenderer2D();
61 FlatBatch2D flatBatch2D = primitivesRenderer2D.FlatBatch();
63 flatBatch2D.QueueLine(new Vector2(Counter, 0f), new Vector2(size.X - Counter, size.Y), 0f, Color.Black);
64 primitivesRenderer2D.Flush();
65 if (++Counter >= size.X) {
66 Counter = 0;
67 }
68 return 1;
69 }
70
71 public static async Task Main(string[] args) {
72#else
73 static void Main(string[] args) {
74#endif
75 // ReSharper restore UnusedMember.Local
76#if WINDOWS
77 if (args != null
78 && args.Length > 0) {
79 switch (args.Length) {
80 case 1: {
81 string path = args[0];
84 && File.Exists(path)) {
85 using (FileStream fileStream = File.OpenRead(path)) {
86 string fileName = Storage.GetFileName(path);
87 try {
88 ExternalContentManager.ImportExternalContentSync(fileStream, type, fileName);
89 Window.MessageBox(IntPtr.Zero, $"Successfully imported {fileName}.\n导入 {fileName} 成功", "Success 成功", 0x40u);
90 }
91 catch (Exception e) {
92 Window.MessageBox(IntPtr.Zero, $"Failed to import {fileName}, reason:\n导入 {fileName} 失败,原因:\n{e}", null, 0x10u);
93 }
94 }
95 }
96 return;
97 }
98 case 2:
99 if (args[0] != "--wait") {
100 break;
101 }
102 if (int.TryParse(args[1], out int pid)) {
103 try {
104 Process.GetProcessById(pid)?.WaitForExit();
105 }
106 catch {
107 // ignored
108 }
109 }
110 break;
111 }
112 }
113 string mutexName;
114 using (SHA256 sha256 = SHA256.Create()) {
115 byte[] hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(Assembly.GetEntryAssembly()?.Location ?? "SurvivalcraftApi"));
116 mutexName = $"Global\\{BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant()}";
117 }
118 m_mutex = new Mutex(true, mutexName, out m_mutexHandled);
119 if (!m_mutexHandled) {
120
121 string str =
122 "This game is already running! If you cannot find the window, please stop it from the Task Manager, and check the log file in Bugs directory.\n游戏已经在运行!如果找不到游戏窗口,请从任务管理器终止它,并检查 Bugs 目录中的日志文件。";
123 Window.MessageBox(IntPtr.Zero, str, null, 0x10u);
124 return;
125 }
126#endif
127
128 // Process.Start("C:\\Windows\\System32\\msg.exe", "/server:127.0.0.1 * \"此版本为预览版 不建议长期使用");
129#if WINDOWS
130 Window.Created += () => {
131 InputMethod.Initialize(Process.GetCurrentProcess().MainWindowHandle);
132 InputMethod.Enabled = false;
133 };
134#endif
135 EntryPoint();
136#if WINDOWS
137 m_mutex.ReleaseMutex();
138 m_mutex.Dispose();
139#endif
140 /*AppDomain.CurrentDomain.AssemblyResolve += (_, e) => {
141 //在程序目录下面寻找dll,解决部分设备找不到目录下程序集的问题
142 string location = new FileInfo(typeof(Program).Assembly.Location).Directory!.FullName;
143 return Assembly.LoadFrom(Path.Combine(location, e.Name));
144 };*/
145
146 //RootCommand rootCommand =
147 //[
148 // new Option<string>(["-m", "--mod-import"], ""),
149 // new Option<string>(["-l", "--language"], "")
150 //];
151 }
152#endif // !ANDROID
153
154 [STAThread]
155 public static void EntryPoint() {
156#if BROWSER
158#else
159 SystemLanguage = CultureInfo.CurrentUICulture.Name;
160#endif
161 if (string.IsNullOrEmpty(SystemLanguage)) {
162 SystemLanguage = RegionInfo.CurrentRegion.DisplayName != "United States" ? "zh-CN" : "en-US";
163 }
164 //预加载
172 CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
173 CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
174 string title = $"Survivalcraft {ModsManager.ShortGameVersion} - API {ModsManager.APIVersionString}";
176#if DEBUG
177 title = $"[DEBUG]{title}";
178#endif
180 ExceptionManager.ReportExceptionToUser("Unhandled exception.", e.Exception);
181 e.IsHandled = true;
182 };
183 Window.Run(0, 0, WindowMode.Resizable, title);
184 }
185
186 public static void HandleUriHandler(Uri uri) {
187 m_urisToHandle.Add(uri);
188 }
189
190 public static void DeactivatedHandler() {
191 GC.Collect();
192 }
193
194 public static void FrameHandler() {
195 if (Time.FrameIndex < 0) {
197 }
198 else if (Time.FrameIndex == 0) {
200 Initialize();
201 }
202 else {
203 Run();
204 }
205 }
206
207 public static void Initialize() {
209 $"Survivalcraft starting up at {DateTime.Now}, GameVersion={VersionsManager.Version}, BuildConfiguration={VersionsManager.BuildConfiguration}, Platform={VersionsManager.PlatformString}, Storage.AvailableFreeSpace={Storage.FreeSpace / 1024 / 1024}MB, ApproximateScreenDpi={ScreenResolutionManager.ApproximateScreenDpi:0.0}, ApproxScreenInches={ScreenResolutionManager.ApproximateScreenInches:0.0}, ScreenResolution={Window.Size}, ProcessorsCount={Environment.ProcessorCount}, APIVersion={ModsManager.APIVersionString}, 64bit={Environment.Is64BitProcess}"
210 );
211 try {
217 Log.Information("Program Initialize Success");
218 }
219 catch (Exception e) {
220 Log.Error(e.ToString());
221 }
222 }
223
224 public static void Run() {
228#if !MOBILE && !BROWSER
229 if (Keyboard.IsKeyDownOnce(Key.F11)) {
232 }
233#endif
234 try {
235 if (ExceptionManager.Error == null) {
236 foreach (Uri obj in m_urisToHandle) {
237 HandleUri?.Invoke(obj);
238 }
239 m_urisToHandle.Clear();
245#if !IOS && !BROWSER
247#endif
248 }
249 else {
251 }
252 }
253 catch (Exception e) {
254 //ModsManager.AddException(e);
255 Log.Error("Game Running Error!");
256 Log.Error(e);
257 try {
258 ScreensManager.SwitchScreen("MainMenu");
259 ViewGameLogDialog dialog = new();
260 dialog.SetErrorHead(9, 10);
261 DialogsManager.ShowDialog(null, dialog);
263 }
264 catch (Exception e3) {
265 Log.Error(e3);
266 }
267 }
269 try {
270 Display.RenderTarget = null;
271 if (ExceptionManager.Error == null) {
276 }
277 else {
279 }
280 }
281 else {
283 }
284 }
285 catch (Exception e2) {
286 if (GameManager.Project != null) {
288 }
289 Log.Error(e2);
291 ScreensManager.SwitchScreen("MainMenu");
292 }
293 finally {
294#if ANDROID
296 m_firstFramePrepared = true;
297 }
298#elif BROWSER
299 if (!m_firstFramePrepared && LoadingScreen.m_isContentLoaded) {
300 m_firstFramePrepared = true;
302 }
303#endif
304 }
305 }
306
307 public static void ToRestartHandler() {
308#if ANDROID
309#pragma warning disable CA1416
310 Intent intent = new Intent(Window.Activity, Window.Activity.Class);
311 Window.Activity.StartActivity(intent);
312#elif !BROWSER
313 Process current = Process.GetCurrentProcess();
314 Process.Start(new ProcessStartInfo
315 {
316 FileName = current.MainModule!.FileName!,
317 Arguments = $"--wait {current.Id}",
318 UseShellExecute = false
319 });
320#endif
321 }
322
323 public static void FileDropHandler(List<(Stream stream, string fileName)> files) {
325 return;
326 }
328 }
329 }
330}
Android.Net.Uri Uri
unsafe
定义 Main.cs:15
static partial void FirstFramePrepared()
static partial string GetLanguage()
static partial void Initialize(IntPtr sharedInputMemoryPtr)
static unsafe void RequestAnimationFrameLoop(void *f, nint userDataPtr)
static void Clear(Vector4? color, float? depth=null, int? stencil=null)
static Point2 BackbufferSize
void QueueLine(Vector2 p1, Vector2 p2, float depth, Color color)
FlatBatch2D FlatBatch(int layer=0, DepthStencilState depthStencilState=null, RasterizerState rasterizerState=null, BlendState blendState=null)
void Flush(bool clearAfterFlush=true, int maxLayer=int.MaxValue)
static bool IsKeyDownOnce(Key key)
static ? Point2 m_lastMousePosition
static void Error(object message)
定义 Log.cs:80
static void Information(object message)
定义 Log.cs:56
static void AddLogSink(ILogSink logSink)
定义 Log.cs:110
static string GetExtension(string path)
static string GetFileName(string path)
static void Initialize()
static int FrameIndex
定义 Time.cs:26
static double RealTime
定义 Time.cs:38
static Action Created
static void Run(int width=0, int height=0, WindowMode windowMode=WindowMode.Resizable, string title="")
static Action ToRestart
static Action Frame
static Action Deactivated
static Action< UnhandledExceptionInfo > UnhandledException
static Action< Uri > HandleUri
static Action< List<(Stream stream, string fileName)> > FileDropped
static void ShowDialog(ContainerWidget parentWidget, Dialog dialog)
static void ReportExceptionToUser(string additionalMessage, Exception e)
static bool IsEntryTypeDownloadSupported(ExternalContentType type)
static async Task ImportExternalContentsAsync(List<(Stream stream, string fileName)> files, bool showResultDialog)
static ExternalContentType ExtensionToType(string extension)
static string ImportExternalContentSync(Stream stream, ExternalContentType type, string name)
static void DisposeProject()
static Project Project
static void FileDropHandler(List<(Stream stream, string fileName)> files)
static float LastFrameTime
static void EntryPoint()
static Action< Uri > HandleUri
static void Run()
static float LastCpuFrameTime
static void Main(string[] args)
static void FrameHandler()
static void ToRestartHandler()
static double m_frameBeginTime
static void HandleUriHandler(Uri uri)
static string SystemLanguage
static double m_cpuEndTime
static List< Uri > m_urisToHandle
static void Initialize()
static void DeactivatedHandler()
static void SwitchScreen(string name, params object[] parameters)
void SetErrorHead(int headLangIndex, int adviceLangIndex)
static Color White
static Color Black
定义 Color.cs:7