Feature/rebase dr runtime #30

Merged
shenjackyuanjie merged 5 commits from feature/rebase_dr_runtime into main 2023-06-17 01:01:42 +08:00
11 changed files with 115 additions and 85 deletions

View File

@ -10,13 +10,10 @@ import rtoml
sys.path.append(os.path.abspath(os.curdir)) sys.path.append(os.path.abspath(os.curdir))
from Difficult_Rocket import DR_runtime from Difficult_Rocket.runtime import DR_runtime
args = ['-env', '-github-dev'] args = ['-env', '-github-dev']
# print(sys.argv)
if sys.argv == [__file__]: # 没有输入参数,直接输出默认信息并输出 if sys.argv == [__file__]: # 没有输入参数,直接输出默认信息并输出
print(sys.version) print(sys.version)

3
DR.py
View File

@ -58,7 +58,8 @@ def main() -> int:
pyglet.resource.path = ['/textures/'] pyglet.resource.path = ['/textures/']
pyglet.resource.reindex() pyglet.resource.reindex()
from Difficult_Rocket import main, DR_runtime from Difficult_Rocket import main
from Difficult_Rocket.runtime import DR_runtime
DR_runtime.start_time_ns = start_time_ns DR_runtime.start_time_ns = start_time_ns
# from pyglet.gl import glClearColor # 调整背景颜色 # from pyglet.gl import glClearColor # 调整背景颜色

View File

@ -4,14 +4,6 @@
# All rights reserved # All rights reserved
# ------------------------------- # -------------------------------
import sys
import importlib
import traceback
import contextlib
import importlib.util
from pathlib import Path
from typing import Optional, List, Tuple
from Difficult_Rocket.api.types import Options, Version from Difficult_Rocket.api.types import Options, Version
game_version = Version("0.8.2.0") # 游戏版本 game_version = Version("0.8.2.0") # 游戏版本
@ -20,6 +12,24 @@ Api_version = Version("0.1.1.0") # API 版本
__version__ = game_version __version__ = game_version
__all__ = [
# __init__
'DR_status',
# folder
'api',
'client',
'server',
'command',
'crash',
'exception',
'mod',
'utils',
# file
'main',
'runtime',
]
class _DR_status(Options): class _DR_status(Options):
""" """
DR 的特性开关 / 基本状态 DR 的特性开关 / 基本状态
@ -58,64 +68,7 @@ class _DR_status(Options):
return round(12 * self.gui_scale) return round(12 * self.gui_scale)
class _DR_runtime(Options):
"""
DR 的运行时配置 / 状态
"""
name = 'DR Runtime'
language: str = 'zh-CN'
mod_path: str = './mods'
DR_Mod_List: List[Tuple[str, Version]] = [] # DR Mod 列表 (name, version)
# run status
start_time_ns: Optional[int] = None
client_setup_cause_ns: Optional[int] = None
server_setup_cause_ns: Optional[int] = None
def load_file(self) -> bool:
with contextlib.suppress(FileNotFoundError):
with open('./configs/main.toml', 'r', encoding='utf-8') as f:
import rtoml
config_file = rtoml.load(f)
self.language = config_file['runtime']['language']
self.mod_path = config_file['game']['mods']['path']
return True
return False
def find_mods(self) -> List[str]:
mods = []
mod_path = Path(self.mod_path)
if not mod_path.exists():
mod_path.mkdir()
return []
paths = mod_path.iterdir()
sys.path.append(self.mod_path)
for mod_path in paths:
try:
if mod_path.is_dir() and mod_path.name != '__pycache__': # 处理文件夹 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
else:
print(f'can not import mod {mod_path} because importlib can not find spec')
elif mod_path.suffix in ('.pyz', '.zip'): # 处理压缩包 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
elif mod_path.suffix == '.pyd': # pyd 扩展 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
elif mod_path.suffix == '.py': # 处理单文件 mod
print(f'importing mod {mod_path=} {mod_path.stem}')
if importlib.util.find_spec(mod_path.stem) is not None:
mods.append(mod_path.stem)
except ImportError:
print(f'ImportError when loading mod {mod_path}')
traceback.print_exc()
return mods
DR_status = _DR_status() DR_status = _DR_status()
DR_runtime = _DR_runtime()
if DR_status.playing: if DR_status.playing:
from Difficult_Rocket.utils.thread import new_thread from Difficult_Rocket.utils.thread import new_thread

View File

@ -30,10 +30,10 @@ from pyglet.window import key, mouse
if TYPE_CHECKING: if TYPE_CHECKING:
from Difficult_Rocket.main import Game from Difficult_Rocket.main import Game
from Difficult_Rocket.utils import tools from Difficult_Rocket.utils import tools
from Difficult_Rocket.api.types import Options
from Difficult_Rocket.command import line from Difficult_Rocket.command import line
from Difficult_Rocket.api.types import Options
from Difficult_Rocket.utils.translate import tr from Difficult_Rocket.utils.translate import tr
from Difficult_Rocket import DR_runtime from Difficult_Rocket.runtime import DR_runtime
from Difficult_Rocket.api.screen import BaseScreen from Difficult_Rocket.api.screen import BaseScreen
from Difficult_Rocket.utils.thread import new_thread from Difficult_Rocket.utils.thread import new_thread
from Difficult_Rocket.client.fps.fps_log import FpsLogger from Difficult_Rocket.client.fps.fps_log import FpsLogger
@ -51,7 +51,7 @@ class ClientOption(Options):
resizeable: bool = True resizeable: bool = True
visible: bool = True visible: bool = True
gui_scale: float = 1.0 gui_scale: float = 1.0
caption: str = "Difficult Rocket v{DR_version}|DR_rs v{DR_Rust_get_version}" caption: str = "Difficult Rocket v{DR_version}"
def load_file(self) -> None: def load_file(self) -> None:
file: dict = tools.load_file('./configs/main.toml') file: dict = tools.load_file('./configs/main.toml')
@ -223,7 +223,7 @@ class ClientWindow(Window):
print("==========client stop. KeyboardInterrupt info==========") print("==========client stop. KeyboardInterrupt info==========")
traceback.print_exc() traceback.print_exc()
print("==========client stop. KeyboardInterrupt info end==========") print("==========client stop. KeyboardInterrupt info end==========")
self.dispatch_event("on_close") self.dispatch_event("on_close", 'input')
sys.exit(0) sys.exit(0)
@new_thread('window save_info') @new_thread('window save_info')
@ -388,7 +388,7 @@ class ClientWindow(Window):
if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK | if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK |
key.MOD_CAPSLOCK | key.MOD_CAPSLOCK |
key.MOD_SCROLLLOCK)): key.MOD_SCROLLLOCK)):
self.dispatch_event('on_close') self.dispatch_event('on_close', 'window')
if symbol == key.SLASH: if symbol == key.SLASH:
self.input_box._set_focus(True) self.input_box._set_focus(True)
self.logger.debug( self.logger.debug(

View File

@ -99,7 +99,8 @@ def write_cache(cache_stream, crash_info):
def write_info_to_cache(cache_stream): def write_info_to_cache(cache_stream):
# 运行状态信息 # 运行状态信息
from Difficult_Rocket import DR_status, DR_runtime from Difficult_Rocket import DR_status
from Difficult_Rocket.runtime import DR_runtime
cache_stream.write(Run_message) cache_stream.write(Run_message)
cache_stream.write(markdown_line_handler(f'DR Version: {Difficult_Rocket.game_version}', level=1)) cache_stream.write(markdown_line_handler(f'DR Version: {Difficult_Rocket.game_version}', level=1))
cache_stream.write(markdown_line_handler(f'DR language: {DR_runtime.language}', level=1)) cache_stream.write(markdown_line_handler(f'DR language: {DR_runtime.language}', level=1))

View File

@ -24,10 +24,6 @@ from io import StringIO
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING, List, Optional, Dict, TypeVar from typing import TYPE_CHECKING, List, Optional, Dict, TypeVar
if __name__ == '__main__': # been start will not run this
sys.path.append('/bin/libs')
sys.path.append('/bin')
if TYPE_CHECKING: if TYPE_CHECKING:
from Difficult_Rocket.api.mod import ModInfo from Difficult_Rocket.api.mod import ModInfo
else: else:
@ -35,9 +31,10 @@ else:
from Difficult_Rocket.utils import tools from Difficult_Rocket.utils import tools
from Difficult_Rocket.api.types import Options from Difficult_Rocket.api.types import Options
from Difficult_Rocket.utils.translate import tr from Difficult_Rocket.utils.translate import tr
from Difficult_Rocket.runtime import DR_runtime
from Difficult_Rocket.utils.thread import new_thread from Difficult_Rocket.utils.thread import new_thread
from Difficult_Rocket.crash import write_info_to_cache from Difficult_Rocket.crash import write_info_to_cache
from Difficult_Rocket import client, server, DR_status, DR_runtime from Difficult_Rocket import client, server, DR_status
class Console(Options): class Console(Options):

View File

@ -0,0 +1,79 @@
# -------------------------------
# Difficult Rocket
# Copyright © 2020-2023 by shenjackyuanjie 3695888@qq.com
# All rights reserved
# -------------------------------
import sys
import importlib
import traceback
import contextlib
import importlib.util
from pathlib import Path
from typing import Optional, List, Tuple
from Difficult_Rocket.api.types import Options, Version
__all__ = [
'DR_runtime'
]
class _DR_runtime(Options):
"""
DR 的运行时配置 / 状态
"""
name = 'DR Runtime'
language: str = 'zh-CN'
mod_path: str = './mods'
DR_Mod_List: List[Tuple[str, Version]] = [] # DR Mod 列表 (name, version)
# run status
start_time_ns: Optional[int] = None
client_setup_cause_ns: Optional[int] = None
server_setup_cause_ns: Optional[int] = None
def load_file(self) -> bool:
with contextlib.suppress(FileNotFoundError):
with open('./configs/main.toml', 'r', encoding='utf-8') as f:
import rtoml
config_file = rtoml.load(f)
self.language = config_file['runtime']['language']
self.mod_path = config_file['game']['mods']['path']
return True
return False
def find_mods(self) -> List[str]:
mods = []
mod_path = Path(self.mod_path)
if not mod_path.exists():
mod_path.mkdir()
return []
paths = mod_path.iterdir()
sys.path.append(self.mod_path)
for mod_path in paths:
try:
if mod_path.is_dir() and mod_path.name != '__pycache__': # 处理文件夹 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
else:
print(f'can not import mod {mod_path} because importlib can not find spec')
elif mod_path.suffix in ('.pyz', '.zip'): # 处理压缩包 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
elif mod_path.suffix == '.pyd': # pyd 扩展 mod
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
elif mod_path.suffix == '.py': # 处理单文件 mod
print(f'importing mod {mod_path=} {mod_path.stem}')
if importlib.util.find_spec(mod_path.stem) is not None:
mods.append(mod_path.stem)
except ImportError:
print(f'ImportError when loading mod {mod_path}')
traceback.print_exc()
return mods
DR_runtime = _DR_runtime()

View File

@ -17,8 +17,9 @@ import inspect
from dataclasses import dataclass from dataclasses import dataclass
from typing import Union, Tuple, Any, List, Dict, Hashable, Optional from typing import Union, Tuple, Any, List, Dict, Hashable, Optional
from Difficult_Rocket import DR_runtime, DR_status from Difficult_Rocket import DR_status
from Difficult_Rocket.utils import tools from Difficult_Rocket.utils import tools
from Difficult_Rocket.runtime import DR_runtime
from Difficult_Rocket.exception.language import (LanguageNotFound, from Difficult_Rocket.exception.language import (LanguageNotFound,
TranslateKeyNotFound) TranslateKeyNotFound)

View File

@ -29,6 +29,7 @@ mod.load.info = "mod id: {} version: {}"
mod.load.faild.info = "Mod load failed: {} error info: {}" mod.load.faild.info = "Mod load failed: {} error info: {}"
mod.load.faild.no_mod_class = "Can't find Mod class" mod.load.faild.no_mod_class = "Can't find Mod class"
mod.load.done = "All Mod loaded" mod.load.done = "All Mod loaded"
mod.event.error = "Mod evenet {} caught error: {} Mod: {}"
[client] [client]
setup.start = "Client start loading" setup.start = "Client start loading"
@ -71,8 +72,8 @@ os.pid_is = "Server PID: {} PPID: {}"
[game] [game]
input = "console" input = "console"
command = "in game commands"
window = "window" window = "window"
command = "in game commands"
require_DR_rs = "require DR_rs module" require_DR_rs = "require DR_rs module"
[client.sr1_render] [client.sr1_render]

View File

@ -72,8 +72,8 @@ os.pid_is = "服务端 PID: {} PPID: {}"
[game] [game]
input = "控制台" input = "控制台"
command = "游戏内命令行"
window = "窗口" window = "窗口"
command = "游戏内命令行"
require_DR_rs = "需要 DR_rs 模块" require_DR_rs = "需要 DR_rs 模块"
[client.sr1_render] [client.sr1_render]

View File

@ -12,8 +12,8 @@ from typing import Optional
from Difficult_Rocket import DR_status from Difficult_Rocket import DR_status
from Difficult_Rocket.main import Game from Difficult_Rocket.main import Game
from Difficult_Rocket.api.mod import ModInfo from Difficult_Rocket.api.mod import ModInfo
from Difficult_Rocket.api.types import Options, Version
from Difficult_Rocket.client import ClientWindow from Difficult_Rocket.client import ClientWindow
from Difficult_Rocket.api.types import Options, Version
DR_rust_version = Version("0.2.10.1") # DR_mod 的 Rust 编写部分的兼容版本 DR_rust_version = Version("0.2.10.1") # DR_mod 的 Rust 编写部分的兼容版本