feat: add MeshPort overlay networking, item actions window, and AVA2 client enhancements
- add MeshPort peer-to-peer overlay networking SDK, C++ integration, and Python bindings - add item actions quick use/split/delete/lock overlay window (mt_item_actions) - add shop name range and NPC name visibility settings to system display options - support battlepass ticket activation and month validation in mt_battlepass - support boss tracking teleport destination button in mt_bosses - support asynchronous account registration cancellation and pending login cancellation - update AVA2 item conversion for attr lock scrolls and battlepass tickets - update .gitignore for local build outputs and caches
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
set(mt_mesh_default OFF)
|
||||
if(APPLE OR ANDROID)
|
||||
set(mt_mesh_default ON)
|
||||
endif()
|
||||
option(MT_ENABLE_MESHPORT "Embed MeshPort application networking" ${mt_mesh_default})
|
||||
if(NOT MT_ENABLE_MESHPORT)
|
||||
return()
|
||||
endif()
|
||||
set(MT_MESHPORT_ROOT "${PROJECT_SOURCE_DIR}/third_party/meshport" CACHE PATH "MeshPort source checkout")
|
||||
if(ANDROID)
|
||||
set(mt_mesh_library "${PROJECT_SOURCE_DIR}/build/meshport-runtime/aarch64-linux-android/release/libmetin2_meshport.a")
|
||||
else()
|
||||
set(mt_mesh_library "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/libmetin2_meshport.a")
|
||||
endif()
|
||||
set(MT_MESHPORT_LIBRARY "${mt_mesh_library}" CACHE FILEPATH "MeshPort static library for this target")
|
||||
if(NOT EXISTS "${MT_MESHPORT_LIBRARY}")
|
||||
message(FATAL_ERROR "Build MeshPort first: scripts/build_meshport.sh (or set MT_MESHPORT_LIBRARY)")
|
||||
endif()
|
||||
# A private build input, never copy network credentials into the source tree.
|
||||
set(mt_mesh_config "${PROJECT_SOURCE_DIR}/config/meshport.private.toml")
|
||||
if(EXISTS "$ENV{HOME}/Library/Application Support/MeshPort/network-profile.toml")
|
||||
set(mt_mesh_config "$ENV{HOME}/Library/Application Support/MeshPort/network-profile.toml")
|
||||
endif()
|
||||
set(MT_MESHPORT_CONFIG "${mt_mesh_config}"
|
||||
CACHE FILEPATH "Saved MeshPort network configuration to embed")
|
||||
set(MT_MESHPORT_TOML "")
|
||||
if(EXISTS "${MT_MESHPORT_CONFIG}")
|
||||
file(READ "${MT_MESHPORT_CONFIG}" MT_MESHPORT_TOML)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${MT_MESHPORT_CONFIG}")
|
||||
else()
|
||||
message(WARNING "MeshPort network profile missing: LAN login works, remote login requires MT_MESHPORT_CONFIG")
|
||||
endif()
|
||||
configure_file(config.h.in "${CMAKE_CURRENT_BINARY_DIR}/MeshPortConfig.h" @ONLY)
|
||||
add_library(mt_meshport STATIC transport.cpp)
|
||||
target_include_directories(mt_meshport PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}"
|
||||
PRIVATE "${MT_MESHPORT_ROOT}/crates/meshport-ffi/include")
|
||||
target_compile_definitions(mt_meshport PUBLIC MT_HAS_MESHPORT=1)
|
||||
target_link_libraries(mt_meshport PUBLIC "${MT_MESHPORT_LIBRARY}")
|
||||
if(APPLE)
|
||||
target_link_libraries(mt_meshport PUBLIC "-framework Security" "-framework SystemConfiguration"
|
||||
"-framework CoreFoundation" resolv iconv)
|
||||
elseif(ANDROID)
|
||||
target_link_libraries(mt_meshport PUBLIC log android dl m)
|
||||
endif()
|
||||
if(BUILD_TESTING AND NOT ANDROID)
|
||||
add_executable(meshport_transport_test "${PROJECT_SOURCE_DIR}/tests/meshport/transport_test.cpp")
|
||||
target_link_libraries(meshport_transport_test PRIVATE mt_meshport)
|
||||
add_test(NAME meshport.transport COMMAND meshport_transport_test)
|
||||
add_executable(meshport_network_paths_test "${PROJECT_SOURCE_DIR}/tests/meshport/network_paths_test.cpp")
|
||||
target_link_libraries(meshport_network_paths_test PRIVATE mt_meshport)
|
||||
find_package(Python3 COMPONENTS Interpreter)
|
||||
if(Python3_FOUND)
|
||||
add_test(NAME meshport.login COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/tests/meshport/test_login.py")
|
||||
if(EXISTS "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/examples/gateway_fixture")
|
||||
add_test(NAME meshport.network_paths COMMAND "${Python3_EXECUTABLE}"
|
||||
"${PROJECT_SOURCE_DIR}/tests/meshport/test_network_paths.py" "$<TARGET_FILE:meshport_network_paths_test>")
|
||||
set_tests_properties(meshport.network_paths PROPERTIES TIMEOUT 120)
|
||||
endif()
|
||||
if(APPLE AND EXISTS "${PROJECT_SOURCE_DIR}/build/meshport-runtime/release/libmetin2_meshport.dylib")
|
||||
add_test(NAME meshport.dhcp COMMAND "${Python3_EXECUTABLE}"
|
||||
"${PROJECT_SOURCE_DIR}/tests/meshport/sdk_smoke.py")
|
||||
set_tests_properties(meshport.dhcp PROPERTIES TIMEOUT 55)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
// Generated private build input. Network credentials are intentionally not logged.
|
||||
static const char* const kMeshPortConfig = R"MESHCONFIG(@MT_MESHPORT_TOML@)MESHCONFIG";
|
||||
Generated
+4911
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "metin2-meshport"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "cdylib"]
|
||||
|
||||
[dependencies]
|
||||
meshport-ffi = { path = "../../../third_party/meshport/crates/meshport-ffi" }
|
||||
serde_json = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { path = "../../../third_party/meshport/vendor/easytier/easytier", default-features = false, features = ["aes-gcm", "ffi-dataplane", "proxy-cidr-monitor", "dhcp-ipv4", "tcp-hole-punch", "proxy-packet"] }
|
||||
easytier-core = { path = "../../../third_party/meshport/vendor/easytier/easytier-core", default-features = false, features = ["proxy-smoltcp-stack"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "io-util", "sync", "time"] }
|
||||
@@ -0,0 +1,38 @@
|
||||
//! Isolated test gateway. Maps a private advertised subnet to loopback; no OS routes/TUN.
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
|
||||
use tokio::{net::{TcpListener,UdpSocket},io::{AsyncReadExt,AsyncWriteExt}};
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let tcp=TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let tcp_port=tcp.local_addr().unwrap().port();
|
||||
let udp=UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let udp_port=udp.local_addr().unwrap().port();
|
||||
let reserve=std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let mesh_port=reserve.local_addr().unwrap().port();drop(reserve);
|
||||
let name=format!("metin2-gateway-test-{}",std::process::id());
|
||||
let config=format!("ipv4='10.253.85.1/24'\nlisteners=['tcp://127.0.0.1:{mesh_port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/24'\nmapped_cidr='10.253.79.0/24'\n[network_identity]\nnetwork_name='{name}'\nnetwork_secret='isolated-test-only'\n[flags]\nno_tun=true\nuse_smoltcp=true\nenable_encryption=true\n");
|
||||
let parsed=TomlConfig::new_from_str(&config).unwrap();
|
||||
eprintln!("fixture proxy networks: {:?}",parsed.get_proxy_cidrs());
|
||||
let server=create_native_instance(parsed).unwrap();
|
||||
server.start().await.unwrap();
|
||||
println!("{{\"mesh_port\":{mesh_port},\"tcp_port\":{tcp_port},\"udp_port\":{udp_port},\"network_name\":\"{name}\"}}");
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut stream,_))=tcp.accept().await {
|
||||
tokio::spawn(async move {
|
||||
let mut data=[0u8;16384];
|
||||
while let Ok(size)=stream.read(&mut data).await {
|
||||
if size==0 {break}
|
||||
if data[..size].starts_with(b"POST /register") {
|
||||
let _=stream.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nOK\n").await;break
|
||||
}
|
||||
if stream.write_all(&data[..size]).await.is_err(){break}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
let mut data=[0u8;65536];
|
||||
loop {
|
||||
if let Ok((size,peer))=udp.recv_from(&mut data).await {let _=udp.send_to(&data[..size],peer).await;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Metin2 host policy around the vendored MeshPort SDK. No sockets or OS routes are intercepted.
|
||||
use serde_json::{json, Value};
|
||||
use std::{collections::HashMap, ffi::{c_char, CStr, CString}, net::Ipv4Addr,
|
||||
sync::{Arc, Condvar, Mutex, OnceLock}, thread::{self, JoinHandle}, time::{Duration, Instant}};
|
||||
|
||||
struct Target { since: Instant, touched: Instant }
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
config: String, targets: HashMap<u32, Target>, routes: Vec<String>, port: u16,
|
||||
stop: bool, failed: bool, retry: bool, event: i32, connected: bool,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Runtime { state: Arc<(Mutex<State>, Condvar)>, worker: Option<JoinHandle<()>> }
|
||||
static RUNTIME: OnceLock<Mutex<Runtime>> = OnceLock::new();
|
||||
fn runtime() -> &'static Mutex<Runtime> { RUNTIME.get_or_init(|| Mutex::new(Runtime::default())) }
|
||||
|
||||
fn matches(cidr: &str, address: u32) -> bool {
|
||||
let Some((ip, bits)) = cidr.split_once('/') else { return false };
|
||||
let (Ok(ip), Ok(bits)) = (ip.parse::<Ipv4Addr>(), bits.parse::<u32>()) else { return false };
|
||||
if !(1..=32).contains(&bits) { return false }
|
||||
let mask = u32::MAX << (32 - bits);
|
||||
(u32::from(ip) & mask) == (address & mask)
|
||||
}
|
||||
fn call(context: u64, request: Value) -> Result<Value, ()> {
|
||||
let text = CString::new(request.to_string()).map_err(|_| ())?;
|
||||
let pointer = unsafe { meshport_ffi::meshport_call(context, text.as_ptr()) };
|
||||
if pointer.is_null() { return Err(()) }
|
||||
let decoded = unsafe { serde_json::from_slice::<Value>(CStr::from_ptr(pointer).to_bytes()) };
|
||||
unsafe { meshport_ffi::meshport_string_free(pointer) };
|
||||
let decoded = decoded.map_err(|_| ())?;
|
||||
if decoded["ok"] != true {
|
||||
if std::env::var_os("MT_MESHPORT_TRACE").is_some() { eprintln!("MeshPort SDK operation failed: {}",request["op"]); }
|
||||
return Err(())
|
||||
}
|
||||
Ok(decoded["data"].clone())
|
||||
}
|
||||
fn start(context: u64, config: &str) -> Result<u16, ()> {
|
||||
let info = call(context, json!({"op":"abi_info"}))?;
|
||||
if info["abi"] != 1 || info["revision"].as_u64().unwrap_or(0) < 2 { return Err(()) }
|
||||
let migrated = call(context, json!({"op":"migrate_config","toml":config}))?;
|
||||
let mut profile = call(context, json!({"op":"validate","toml":migrated["toml"],"include_profile":true}))?["profile"].clone();
|
||||
profile["runtime_mode"] = json!("application");
|
||||
profile["dhcp"] = json!(true); profile["ipv4"] = json!("");
|
||||
profile["hostname"] = json!("Metin2"); profile["listeners"] = json!([]);
|
||||
let built = call(context, json!({"op":"build_config","profile":profile}))?;
|
||||
let started = call(context, json!({"op":"start_bridged","toml":built["toml"],"check_local_overlap":true}))?;
|
||||
let listen = started["listen"].as_str().ok_or(())?;
|
||||
let port = listen.strip_prefix("127.0.0.1:").ok_or(())?.parse::<u16>().map_err(|_| ())?;
|
||||
if port == 0 { return Err(()) }
|
||||
Ok(port)
|
||||
}
|
||||
fn run(shared: Arc<(Mutex<State>, Condvar)>) {
|
||||
let (lock, wake) = &*shared;
|
||||
let mut context = 0;
|
||||
let mut last_projection = String::new();
|
||||
loop {
|
||||
let mut state = lock.lock().unwrap();
|
||||
if state.stop { break }
|
||||
if state.failed && !state.retry || context == 0 && state.targets.is_empty() {
|
||||
drop(wake.wait_timeout(state, Duration::from_secs(1)).unwrap());
|
||||
continue
|
||||
}
|
||||
if state.retry {
|
||||
state.retry = false; state.failed = false; state.routes.clear(); state.port = 0;
|
||||
state.connected = false; state.event = 1;
|
||||
drop(state);
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); context = 0; }
|
||||
continue
|
||||
}
|
||||
if context == 0 {
|
||||
state.event = 1; state.connected = false;
|
||||
let config = state.config.clone(); drop(state);
|
||||
context = meshport_ffi::meshport_context_new();
|
||||
let prepared = if context == 0 { Err(()) } else { start(context, &config) };
|
||||
state = lock.lock().unwrap();
|
||||
match prepared {
|
||||
Ok(port) => state.port = port,
|
||||
Err(_) => {
|
||||
state.failed = true; state.event = 3; state.port = 0;
|
||||
drop(state);
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); context = 0; }
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(state);
|
||||
let snapshot = call(context, json!({"op":"status"}));
|
||||
state = lock.lock().unwrap();
|
||||
match snapshot {
|
||||
Ok(data) if data["health"]["engine_running"] == true && data["health"]["bridge_running"] == true => {
|
||||
let ready = data["health"]["mesh_routable"] == true && data["platform_network"]["overlay"]["address"].as_str().is_some_and(|ip| ip != "0.0.0.0");
|
||||
if std::env::var_os("MT_MESHPORT_TRACE").is_some() {
|
||||
let projection = format!("ready={ready} overlay={} routes={}",data["platform_network"]["overlay"]["address"],data["platform_network"]["mesh_cidrs"]);
|
||||
if projection != last_projection { eprintln!("MeshPort {projection}"); last_projection = projection; }
|
||||
}
|
||||
state.routes = if ready { data["platform_network"]["mesh_cidrs"].as_array()
|
||||
.map(|items| items.iter().filter_map(|v|v.as_str().map(String::from)).collect()).unwrap_or_default() } else { vec![] };
|
||||
}
|
||||
_ => { state.routes.clear(); state.port = 0; state.failed = true; state.event = 3; }
|
||||
}
|
||||
state.targets.retain(|_,target| target.touched.elapsed() < Duration::from_secs(120));
|
||||
let interval = if state.connected { 1000 } else { 250 };
|
||||
drop(wake.wait_timeout(state, Duration::from_millis(interval)).unwrap());
|
||||
}
|
||||
if context != 0 { meshport_ffi::meshport_context_free(context); }
|
||||
}
|
||||
|
||||
/// Store a private profile; no network starts until a remote socket asks for a route.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn mt_mesh_configure(config: *const c_char) {
|
||||
if config.is_null() { return }
|
||||
let Ok(config) = unsafe { CStr::from_ptr(config) }.to_str() else { return };
|
||||
let rt = runtime().lock().unwrap();
|
||||
rt.state.0.lock().unwrap().config = config.to_owned();
|
||||
}
|
||||
/// Host-order IPv4. Positive = healthy bridge port, zero = waiting, -1 = unavailable.
|
||||
/// fresh=true only on a new operation; polling must not restart its timeout or retry.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_route(address: u32, fresh: bool) -> i32 {
|
||||
let mut rt = runtime().lock().unwrap();
|
||||
let mut state = rt.state.0.lock().unwrap();
|
||||
if state.stop { return -1 }
|
||||
let now = Instant::now();
|
||||
if fresh && state.failed { state.retry = true; }
|
||||
let target = state.targets.entry(address).or_insert(Target { since: now, touched: now });
|
||||
if fresh { target.since = now; }
|
||||
target.touched = now;
|
||||
let expired = target.since.elapsed() > Duration::from_secs(60);
|
||||
let answer = if state.failed && !state.retry || expired { -1 }
|
||||
else if !state.retry && state.port != 0 && state.routes.iter().any(|cidr|matches(cidr,address)) { state.port as i32 }
|
||||
else { 0 };
|
||||
if expired && !state.connected { state.event = 3; }
|
||||
drop(state);
|
||||
if rt.worker.is_none() {
|
||||
let shared = rt.state.clone(); rt.worker = Some(thread::spawn(move ||run(shared)));
|
||||
}
|
||||
if fresh { rt.state.1.notify_one(); }
|
||||
answer
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_connected() {
|
||||
let rt = runtime().lock().unwrap(); let mut state = rt.state.0.lock().unwrap();
|
||||
if !state.connected { state.connected = true; state.event = 2; }
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_event() -> i32 {
|
||||
let rt = runtime().lock().unwrap(); let mut state = rt.state.0.lock().unwrap();
|
||||
let event = state.event; state.event = 0; event
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn mt_mesh_shutdown() {
|
||||
let worker = {
|
||||
let mut rt = runtime().lock().unwrap();
|
||||
rt.state.0.lock().unwrap().stop = true; rt.state.1.notify_all(); rt.worker.take()
|
||||
};
|
||||
if let Some(worker) = worker { let _ = worker.join(); }
|
||||
let mut rt = runtime().lock().unwrap(); rt.state = Arc::new((Mutex::new(State::default()), Condvar::new()));
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
#include "transport.h"
|
||||
#include <arpa/inet.h>
|
||||
#include <ifaddrs.h>
|
||||
#include <net/if.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <stdexcept>
|
||||
#include <chrono>
|
||||
#include <deque>
|
||||
#include <set>
|
||||
#include <array>
|
||||
#include <fcntl.h>
|
||||
#include <algorithm>
|
||||
|
||||
extern "C" {
|
||||
void mt_mesh_configure(const char*);
|
||||
int mt_mesh_route(uint32_t, bool);
|
||||
void mt_mesh_connected();
|
||||
int mt_mesh_event();
|
||||
void mt_mesh_shutdown();
|
||||
}
|
||||
|
||||
namespace mt::meshport {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Handshake {
|
||||
sockaddr_in target{};
|
||||
const void* owner = nullptr;
|
||||
int stage = -1;
|
||||
size_t offset = 0;
|
||||
unsigned char bytes[10] = {5, 1, 0};
|
||||
unsigned char command = 1;
|
||||
Clock::time_point deadline = Clock::now() + std::chrono::seconds(75);
|
||||
};
|
||||
struct Packet { sockaddr_in target{}; std::vector<unsigned char> bytes; Clock::time_point deadline; };
|
||||
struct Udp {
|
||||
int control = -1, relay = -1;
|
||||
uint16_t port = 0;
|
||||
Handshake handshake;
|
||||
bool ready = false;
|
||||
std::deque<Packet> outgoing, incoming;
|
||||
std::set<std::pair<uint32_t,uint16_t>> peers;
|
||||
size_t queued_bytes = 0;
|
||||
};
|
||||
std::mutex transport_mutex;
|
||||
std::map<int, Handshake> handshakes;
|
||||
std::map<int, Udp> datagrams;
|
||||
std::vector<std::string> routes;
|
||||
sockaddr_in proxy{};
|
||||
bool fixture = false;
|
||||
std::atomic<int> transport_event{0};
|
||||
bool ipv4(const std::string& text, uint32_t& result) {
|
||||
in_addr ip{};
|
||||
if (inet_pton(AF_INET, text.c_str(), &ip) != 1) return false;
|
||||
result = ip.s_addr;
|
||||
return true;
|
||||
}
|
||||
std::string address(uint32_t ip) {
|
||||
char buf[INET_ADDRSTRLEN];
|
||||
in_addr value{}; value.s_addr = ip;
|
||||
return inet_ntop(AF_INET, &value, buf, sizeof(buf)) ? buf : "";
|
||||
}
|
||||
}
|
||||
bool in_subnet(uint32_t ip, uint32_t local, uint32_t mask) {
|
||||
return mask != 0 && (ip & mask) == (local & mask);
|
||||
}
|
||||
bool contains(const std::string& cidr, const std::string& ip) {
|
||||
const auto slash = cidr.find('/');
|
||||
if (slash == std::string::npos) return false;
|
||||
uint32_t network, target;
|
||||
if (!ipv4(cidr.substr(0, slash), network) || !ipv4(ip, target)) return false;
|
||||
const auto suffix = cidr.substr(slash + 1);
|
||||
if (suffix.empty() || suffix.find_first_not_of("0123456789") != std::string::npos) return false;
|
||||
if (suffix.size() > 2) return false;
|
||||
const int prefix = std::stoi(suffix);
|
||||
if (prefix < 1 || prefix > 32) return false;
|
||||
return in_subnet(target, network, htonl(0xffffffffu << (32 - prefix)));
|
||||
}
|
||||
bool same_subnet(const std::string& ip) {
|
||||
uint32_t target;
|
||||
if (!ipv4(ip, target)) return false;
|
||||
if ((ntohl(target) >> 24) == 127) return true;
|
||||
ifaddrs* interfaces = nullptr;
|
||||
if (getifaddrs(&interfaces) != 0) return false;
|
||||
bool local = false;
|
||||
for (auto* i = interfaces; i; i = i->ifa_next) {
|
||||
if (!i->ifa_addr || !i->ifa_netmask || i->ifa_addr->sa_family != AF_INET) continue;
|
||||
if (!(i->ifa_flags & IFF_UP) || (i->ifa_flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) continue;
|
||||
const std::string name = i->ifa_name;
|
||||
if (name.find("tun") == 0 || name.find("utun") == 0 || name.find("tap") == 0) continue;
|
||||
const auto* a = reinterpret_cast<sockaddr_in*>(i->ifa_addr);
|
||||
const auto* m = reinterpret_cast<sockaddr_in*>(i->ifa_netmask);
|
||||
if (in_subnet(target, a->sin_addr.s_addr, m->sin_addr.s_addr)) { local = true; break; }
|
||||
}
|
||||
freeifaddrs(interfaces);
|
||||
return local;
|
||||
}
|
||||
void set_routes(const std::string& listen, const std::vector<std::string>& cidrs) {
|
||||
sockaddr_in next{};
|
||||
if (!listen.empty()) {
|
||||
const auto colon = listen.find(':');
|
||||
if (colon == std::string::npos || listen.substr(0, colon) != "127.0.0.1")
|
||||
throw std::runtime_error("MeshPort bridge must listen on loopback");
|
||||
const auto port_text = listen.substr(colon + 1);
|
||||
if (port_text.empty() || port_text.size() > 5 || port_text.find_first_not_of("0123456789") != std::string::npos)
|
||||
throw std::runtime_error("Invalid MeshPort bridge port");
|
||||
int port = std::stoi(port_text);
|
||||
if (port < 1 || port > 65535) throw std::runtime_error("Invalid MeshPort bridge port");
|
||||
next.sin_family = AF_INET;
|
||||
next.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
next.sin_port = htons(port);
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
proxy = next;
|
||||
routes = cidrs;
|
||||
fixture = !listen.empty();
|
||||
}
|
||||
void configure(const std::string& config) { mt_mesh_configure(config.c_str()); }
|
||||
namespace {
|
||||
int route(const sockaddr_in& target, bool fresh) {
|
||||
if (fixture) {
|
||||
for (const auto& cidr : routes)
|
||||
if (contains(cidr, address(target.sin_addr.s_addr))) return ntohs(proxy.sin_port);
|
||||
return -1; // Missing routes never fall back to the OS network.
|
||||
}
|
||||
return mt_mesh_route(ntohl(target.sin_addr.s_addr), fresh);
|
||||
}
|
||||
sockaddr_in loopback(int port) {
|
||||
sockaddr_in value{}; value.sin_family = AF_INET;
|
||||
value.sin_addr.s_addr = htonl(INADDR_LOOPBACK); value.sin_port = htons(port); return value;
|
||||
}
|
||||
int fail(int error) { errno = error; transport_event = 3; return -1; }
|
||||
int advance(int fd, Handshake& h, sockaddr_in* bound = nullptr) {
|
||||
if (Clock::now() > h.deadline) return fail(ETIMEDOUT);
|
||||
if (h.stage == -1) {
|
||||
int port = route(h.target, false);
|
||||
if (port < 0) return fail(EHOSTUNREACH);
|
||||
if (!port) return 0;
|
||||
auto endpoint = loopback(port);
|
||||
int status = ::connect(fd, reinterpret_cast<const sockaddr*>(&endpoint), sizeof(endpoint));
|
||||
if (status < 0 && errno != EINPROGRESS && errno != EWOULDBLOCK) return fail(errno);
|
||||
h.stage = 0;
|
||||
h.deadline = Clock::now() + std::chrono::seconds(10);
|
||||
}
|
||||
if (h.stage == 0) {
|
||||
int error = 0; socklen_t len = sizeof(error);
|
||||
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) < 0) return fail(errno);
|
||||
if (error) return fail(error);
|
||||
sockaddr_in peer{}; len = sizeof(peer);
|
||||
if (getpeername(fd, reinterpret_cast<sockaddr*>(&peer), &len) < 0) return 0;
|
||||
h.stage = 1;
|
||||
}
|
||||
const bool sending = h.stage == 1 || h.stage == 3;
|
||||
const size_t length = h.stage == 1 ? 3 : h.stage == 2 ? 2 : 10;
|
||||
#ifdef MSG_NOSIGNAL
|
||||
constexpr int send_flags = MSG_NOSIGNAL;
|
||||
#else
|
||||
constexpr int send_flags = 0;
|
||||
#endif
|
||||
const auto count = sending ? ::send(fd, h.bytes + h.offset, length - h.offset, send_flags)
|
||||
: ::recv(fd, h.bytes + h.offset, length - h.offset, 0);
|
||||
if (count < 0) return (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) ? 0 : fail(errno);
|
||||
if (!count) return fail(ECONNRESET);
|
||||
h.offset += static_cast<size_t>(count);
|
||||
if (h.offset != length) return 0;
|
||||
h.offset = 0;
|
||||
if (h.stage == 2) {
|
||||
if (h.bytes[0] != 5 || h.bytes[1] != 0) return fail(EPROTO);
|
||||
h.bytes[0] = 5; h.bytes[1] = h.command; h.bytes[2] = 0; h.bytes[3] = 1;
|
||||
if (h.command == 1) {
|
||||
std::memcpy(h.bytes + 4, &h.target.sin_addr.s_addr, 4);
|
||||
std::memcpy(h.bytes + 8, &h.target.sin_port, 2);
|
||||
} else { std::memset(h.bytes + 4, 0, 6); }
|
||||
} else if (h.stage == 4) {
|
||||
if (h.bytes[0] != 5 || h.bytes[1] != 0 || h.bytes[2] != 0 || h.bytes[3] != 1) return fail(EPROTO);
|
||||
if (bound) {
|
||||
bound->sin_family = AF_INET;
|
||||
std::memcpy(&bound->sin_addr.s_addr, h.bytes + 4, 4);
|
||||
std::memcpy(&bound->sin_port, h.bytes + 8, 2);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
++h.stage; return 0;
|
||||
}
|
||||
void close_udp(Udp& udp) {
|
||||
if (udp.control >= 0) ::close(udp.control);
|
||||
if (udp.relay >= 0) ::close(udp.relay);
|
||||
udp.control = udp.relay = -1; udp.ready = false; udp.port = 0;
|
||||
}
|
||||
void pump_udp(int fd, Udp& udp) {
|
||||
const auto now = Clock::now();
|
||||
while (!udp.outgoing.empty() && udp.outgoing.front().deadline < now) {
|
||||
udp.queued_bytes -= udp.outgoing.front().bytes.size(); udp.outgoing.pop_front(); transport_event = 3;
|
||||
}
|
||||
// A queued request can become local while DHCP/peer discovery is pending.
|
||||
while (!udp.outgoing.empty() && same_subnet(address(udp.outgoing.front().target.sin_addr.s_addr))) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
auto count = ::sendto(fd,packet.bytes.data(),packet.bytes.size(),MSG_DONTWAIT,
|
||||
reinterpret_cast<sockaddr*>(&packet.target),sizeof(packet.target));
|
||||
if (count < 0 && (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)) break;
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front();
|
||||
}
|
||||
if (udp.control >= 0 && udp.ready) {
|
||||
char probe;
|
||||
auto result = ::recv(udp.control, &probe, 1, MSG_PEEK | MSG_DONTWAIT);
|
||||
if (result == 0 || (result < 0 && errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) close_udp(udp);
|
||||
}
|
||||
if (udp.control < 0 && !udp.outgoing.empty()) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
const int port = route(packet.target, false);
|
||||
if (port < 0) {
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front(); transport_event = 3; return;
|
||||
}
|
||||
if (!port) return;
|
||||
udp.control = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (udp.control < 0) return;
|
||||
fcntl(udp.control, F_SETFL, O_NONBLOCK);
|
||||
#ifdef SO_NOSIGPIPE
|
||||
int one=1;setsockopt(udp.control,SOL_SOCKET,SO_NOSIGPIPE,&one,sizeof(one));
|
||||
#endif
|
||||
udp.port = port; udp.handshake = Handshake{};
|
||||
udp.handshake.target = packet.target; udp.handshake.command = 3;
|
||||
}
|
||||
if (udp.control < 0) return;
|
||||
if (!udp.ready) {
|
||||
sockaddr_in relay{};
|
||||
int result = advance(udp.control, udp.handshake, &relay);
|
||||
if (result < 0) { close_udp(udp); return; }
|
||||
if (!result) return;
|
||||
// The SDK bridge is IPv4 loopback-only. Do not accept a redirect to an external relay.
|
||||
if (relay.sin_addr.s_addr != htonl(INADDR_LOOPBACK) || !relay.sin_port) { close_udp(udp); transport_event=3;return; }
|
||||
udp.relay = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (udp.relay < 0) { close_udp(udp);return; }
|
||||
fcntl(udp.relay,F_SETFL,O_NONBLOCK);
|
||||
if (::connect(udp.relay,reinterpret_cast<sockaddr*>(&relay),sizeof(relay)) < 0) {close_udp(udp);return;}
|
||||
udp.ready = true;
|
||||
}
|
||||
for (size_t sent=0; !udp.outgoing.empty() && sent<32; ++sent) {
|
||||
auto& packet = udp.outgoing.front();
|
||||
const int port = route(packet.target,false);
|
||||
if (port == 0) break;
|
||||
if (port < 0) {
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front(); transport_event=3;continue;
|
||||
}
|
||||
if (port != udp.port) {close_udp(udp);return;}
|
||||
std::vector<unsigned char> envelope(10+packet.bytes.size());
|
||||
envelope[3]=1;
|
||||
std::memcpy(envelope.data()+4,&packet.target.sin_addr.s_addr,4);
|
||||
std::memcpy(envelope.data()+8,&packet.target.sin_port,2);
|
||||
std::copy(packet.bytes.begin(),packet.bytes.end(),envelope.begin()+10);
|
||||
auto count = ::send(udp.relay,envelope.data(),envelope.size(),0);
|
||||
if (count < 0 && (errno == EWOULDBLOCK || errno == EAGAIN || errno == EINTR)) break;
|
||||
if (count < 0) {close_udp(udp);return;}
|
||||
if(udp.peers.size()<128)udp.peers.emplace(packet.target.sin_addr.s_addr,packet.target.sin_port);
|
||||
udp.queued_bytes -= packet.bytes.size(); udp.outgoing.pop_front();
|
||||
}
|
||||
for (int i=0;i<32;++i) {
|
||||
std::array<unsigned char,65536> envelope;
|
||||
auto count = ::recv(udp.relay,envelope.data(),envelope.size(),0);
|
||||
if (count < 0) break;
|
||||
if (count<10 || envelope[0] || envelope[1] || envelope[2] || envelope[3]!=1) continue;
|
||||
sockaddr_in source{};source.sin_family=AF_INET;
|
||||
std::memcpy(&source.sin_addr.s_addr,envelope.data()+4,4);
|
||||
std::memcpy(&source.sin_port,envelope.data()+8,2);
|
||||
if (!udp.peers.count({source.sin_addr.s_addr,source.sin_port})) continue;
|
||||
if (udp.incoming.size()>=64) continue;
|
||||
udp.incoming.push_back({source,{envelope.begin()+10,envelope.begin()+count},now});
|
||||
if (!fixture) mt_mesh_connected(); else transport_event=2;
|
||||
}
|
||||
}
|
||||
}
|
||||
int connect_socket(int fd, const sockaddr_in& target, const void* owner) {
|
||||
if (same_subnet(address(target.sin_addr.s_addr)))
|
||||
return ::connect(fd,reinterpret_cast<const sockaddr*>(&target),sizeof(target));
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
if (route(target,true)<0) return fail(EHOSTUNREACH);
|
||||
Handshake h; h.target=target; h.owner=owner; handshakes[fd]=h;
|
||||
errno=EINPROGRESS;return -1;
|
||||
}
|
||||
bool pending_owner(const void* owner) {
|
||||
if(!owner)return false;
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for(const auto& [fd,h]:handshakes)if(h.owner==owner)return true;
|
||||
return false;
|
||||
}
|
||||
bool pending(int fd) { std::lock_guard<std::mutex> guard(transport_mutex);return handshakes.count(fd)!=0; }
|
||||
int poll_socket(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=handshakes.find(fd);if(it==handshakes.end()) return 1;
|
||||
int result=advance(fd,it->second);
|
||||
if (result==1) {
|
||||
handshakes.erase(it);
|
||||
if(!fixture) mt_mesh_connected();else transport_event=2;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
void forget_socket(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);handshakes.erase(fd);
|
||||
auto it=datagrams.find(fd);if(it!=datagrams.end()){close_udp(it->second);datagrams.erase(it);}
|
||||
}
|
||||
ssize_t send_datagram(int fd,const void* bytes,size_t size,int flags,const sockaddr_in& target) {
|
||||
if (same_subnet(address(target.sin_addr.s_addr)))
|
||||
return ::sendto(fd,bytes,size,flags,reinterpret_cast<const sockaddr*>(&target),sizeof(target));
|
||||
if (size>65497) {errno=EMSGSIZE;return -1;}
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
if (route(target,true)<0) return fail(EHOSTUNREACH);
|
||||
if(fcntl(fd,F_GETFD)<0)return -1;
|
||||
auto& udp=datagrams[fd];
|
||||
if (udp.outgoing.size()>=64 || udp.queued_bytes+size>1024*1024) {errno=EWOULDBLOCK;return -1;}
|
||||
const auto* begin=static_cast<const unsigned char*>(bytes);
|
||||
udp.outgoing.push_back({target,{begin,begin+size},Clock::now()+std::chrono::seconds(60)});
|
||||
udp.queued_bytes+=size;pump_udp(fd,udp);return static_cast<ssize_t>(size);
|
||||
}
|
||||
bool datagram_ready(int fd) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=datagrams.find(fd);if(it==datagrams.end())return false;
|
||||
pump_udp(fd,it->second);return !it->second.incoming.empty();
|
||||
}
|
||||
ssize_t recv_datagram(int fd,void* bytes,size_t size,int flags,sockaddr_in* source) {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
auto it=datagrams.find(fd);
|
||||
if(it!=datagrams.end()) {
|
||||
auto& udp=it->second;pump_udp(fd,udp);
|
||||
if(!udp.incoming.empty()) {
|
||||
auto& packet=udp.incoming.front();
|
||||
const size_t count=std::min(size,packet.bytes.size());
|
||||
std::memcpy(bytes,packet.bytes.data(),count);if(source)*source=packet.target;
|
||||
const auto result=(flags&MSG_TRUNC)?packet.bytes.size():count;
|
||||
if(!(flags&MSG_PEEK))udp.incoming.pop_front();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
socklen_t length=sizeof(sockaddr_in);
|
||||
return ::recvfrom(fd,bytes,size,flags,reinterpret_cast<sockaddr*>(source),source?&length:nullptr);
|
||||
}
|
||||
void pump() {
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for(auto& [fd,udp]:datagrams)pump_udp(fd,udp);
|
||||
}
|
||||
int take_event() { pump();int event=transport_event.exchange(0);int runtime=mt_mesh_event();return event?event:runtime; }
|
||||
|
||||
void shutdown() {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(transport_mutex);
|
||||
for (auto& [fd, udp] : datagrams) {
|
||||
if (udp.control >= 0) ::close(udp.control);
|
||||
if (udp.relay >= 0) ::close(udp.relay);
|
||||
}
|
||||
datagrams.clear(); handshakes.clear(); routes.clear(); proxy = {}; fixture = false;
|
||||
}
|
||||
mt_mesh_shutdown(); transport_event = 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
namespace mt::meshport {
|
||||
bool in_subnet(uint32_t address, uint32_t local, uint32_t mask);
|
||||
bool same_subnet(const std::string& address);
|
||||
bool contains(const std::string& cidr, const std::string& address);
|
||||
void configure(const std::string& private_profile);
|
||||
// Explicit fixture bridge. Production obtains its routes exclusively from the native runtime.
|
||||
void set_routes(const std::string& listen, const std::vector<std::string>& cidrs);
|
||||
int connect_socket(int fd, const sockaddr_in& target, const void* owner = nullptr);
|
||||
bool pending_owner(const void* owner);
|
||||
int poll_socket(int fd); // 0 waiting; 1 ready; -1 failed. Includes preparation and SOCKS handshake.
|
||||
bool pending(int fd);
|
||||
void forget_socket(int fd);
|
||||
ssize_t send_datagram(int fd, const void* bytes, size_t size, int flags, const sockaddr_in& target);
|
||||
ssize_t recv_datagram(int fd, void* bytes, size_t size, int flags, sockaddr_in* source);
|
||||
bool datagram_ready(int fd);
|
||||
void pump();
|
||||
int take_event(); // 1 preparing; 2 remote transport verified; 3 failed.
|
||||
void shutdown();
|
||||
}
|
||||
@@ -21,3 +21,7 @@ if(TARGET mtpython)
|
||||
set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/ScriptLib/PythonBoot.cpp
|
||||
PROPERTY COMPILE_DEFINITIONS ${MT_PORT_DEFINES_UserInterface})
|
||||
endif()
|
||||
|
||||
if(TARGET mt_meshport)
|
||||
target_include_directories(port_platform PRIVATE "${PROJECT_BINARY_DIR}/src/meshport")
|
||||
endif()
|
||||
|
||||
@@ -11,6 +11,7 @@ import grp
|
||||
import item
|
||||
import net
|
||||
import nonplayer
|
||||
import player
|
||||
import ui
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
@@ -29,7 +30,8 @@ TYPES={1:('击杀怪物','击杀 ','mob'),2:('击杀 Boss','击杀 Boss ','mob')
|
||||
9:(None,'向 NPC 出售 ','item')}
|
||||
ERRORS={'loading':'数据加载中,请稍后再试','slot':'没有这个任务','claimed':'奖励已经领取过了','incomplete':'任务尚未完成',
|
||||
'space':'背包空间不足,请整理后再领取','config':'奖励配置有误,请联系管理员','db':'服务器繁忙,请稍后再试',
|
||||
'rate':'操作过快,请稍后再试','invalid':'参数无效'}
|
||||
'rate':'操作过快,请稍后再试','invalid':'参数无效','ticket':'请使用当月战令票激活','month':'这张战令票不属于当前月份',
|
||||
'activated':'本月战令已经激活过了','busy':'请先结束交易、商店、仓库或传送'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=10**12):
|
||||
@@ -86,7 +88,7 @@ class Pass(object):
|
||||
self.Clear()
|
||||
|
||||
def Clear(self):
|
||||
self.season=None;self.missions={};self.final=None;self.reading=None;self.none=False;self.error=None;self.claiming=None
|
||||
self.season=None;self.missions={};self.final=None;self.reading=None;self.none=False;self.error=None;self.claiming=None;self.access=None;self.month=None
|
||||
|
||||
def Ready(self):
|
||||
return self.waiting is None or self.now()>=self.waiting
|
||||
@@ -104,10 +106,15 @@ class Pass(object):
|
||||
return self.Post('/mt_bp 1 info')
|
||||
|
||||
def Claim(self,slot):
|
||||
if self.claiming is not None or not self.season:return False
|
||||
if self.claiming is not None or not self.season or self.access not in (None,1):return False
|
||||
if self.Post('/mt_bp 1 claim %d'%slot):self.claiming=slot;self.error=None;return True
|
||||
return False
|
||||
|
||||
def Activate(self,cell,vnum):
|
||||
if self.access!=0 or self.waiting is not None or not 25150<=vnum<=25161:return False
|
||||
if player.GetItemIndex(cell)!=vnum:return False
|
||||
return self.Post('/mt_bp 1 activate %d %d'%(cell,vnum))
|
||||
|
||||
def Close(self):
|
||||
self.send('/mt_bp 1 close')
|
||||
|
||||
@@ -135,7 +142,10 @@ class Pass(object):
|
||||
def Parse(self,kind,args):
|
||||
if kind=='season' and len(args)==5:
|
||||
seasonId,start,end,now=[Number(w,0,2**32-1) for w in args[:4]];count=Number(args[4],1,MAX_SLOT)
|
||||
self.reading=dict(season=(seasonId,start,end,now,self.now()),count=count,missions={},final=None)
|
||||
self.reading=dict(season=(seasonId,start,end,now,self.now()),count=count,missions={},final=None,access=None,month=None)
|
||||
elif kind=='access' and len(args) in (1,2) and self.reading is not None:
|
||||
self.reading['access']=Number(args[0],0,2)
|
||||
if len(args)==2:self.reading['month']=Number(args[1],1,12)
|
||||
elif kind=='mission' and self.reading is not None and len(args)>=6:
|
||||
slot=Number(args[0],1,MAX_SLOT);kind=Number(args[1],1,9)
|
||||
self.reading['missions'][slot]=dict(slot=slot,type=kind,sub=Number(args[2],0,2**32-1),target=Number(args[3],1),
|
||||
@@ -145,7 +155,7 @@ class Pass(object):
|
||||
elif kind=='end' and not args and self.reading is not None:
|
||||
r=self.reading;self.reading=None
|
||||
if len(r['missions'])!=r['count'] or r['final'] is None:return
|
||||
self.season=r['season'];self.missions=r['missions'];self.final=r['final'];self.none=False
|
||||
self.season=r['season'];self.missions=r['missions'];self.final=r['final'];self.access=r['access'];self.month=r['month'];self.none=False
|
||||
self.Answered('info')
|
||||
elif kind=='none' and not args:
|
||||
self.Clear();self.none=True;self.Answered('none')
|
||||
@@ -214,6 +224,8 @@ class BattlePassWindow(ui.Window):
|
||||
self.finalState=Text(self,330,y+4,'')
|
||||
self.finalReward=Text(self,18,y+26,'',0xffb3aa98)
|
||||
self.finalButton=Action(self,WIDTH-118,y,100,'领取',lambda:self.state.Claim(0) and self.Refresh())
|
||||
self.activateButton=Action(self,WIDTH-218,y,200,'使用当月战令票激活',self.AskActivate)
|
||||
self.activateButton.Hide();self.confirm=None;self.pendingTicket=None
|
||||
y=self.GetHeight()-56
|
||||
self.prev=Action(self,18,y,80,'上一页',lambda:self.Turn(-1))
|
||||
self.pageText=Text(self,140,y+24,'');self.pageText.SetHorizontalAlignCenter()
|
||||
@@ -232,8 +244,43 @@ class BattlePassWindow(ui.Window):
|
||||
def Hide(self):
|
||||
state=self.__dict__.get('state') # ui.Window.__init__ hides the window before state is set
|
||||
if self.IsShow() and state and state.season:state.Close()
|
||||
self.pendingTicket=None
|
||||
self.CloseConfirm()
|
||||
ui.Window.Hide(self)
|
||||
|
||||
def CloseConfirm(self):
|
||||
confirm=self.__dict__.get('confirm')
|
||||
if confirm:
|
||||
confirm.Close();confirm.SetAcceptEvent(None);confirm.SetCancelEvent(None);self.confirm=None
|
||||
|
||||
def OfferTicket(self,cell,vnum):
|
||||
self.pendingTicket=(cell,vnum)
|
||||
self.Open()
|
||||
|
||||
def AskTicket(self,cell,vnum):
|
||||
if self.state.access!=0 or player.GetItemIndex(cell)!=vnum:return
|
||||
item.SelectItem(vnum)
|
||||
if item.GetValue(0)!=self.state.month:self.state.error='month';self.Refresh();return
|
||||
import uiCommon
|
||||
self.CloseConfirm();self.confirm=uiCommon.QuestionDialog()
|
||||
self.confirm.SetText(L('消耗战令票并激活本月战令?'))
|
||||
self.confirm.SetAcceptEvent(lambda:self.ConfirmActivate(cell,vnum))
|
||||
self.confirm.SetCancelEvent(self.CloseConfirm);self.confirm.Open()
|
||||
|
||||
def AskActivate(self):
|
||||
if self.state.access!=0:return
|
||||
for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if not 25150<=vnum<=25161:continue
|
||||
item.SelectItem(vnum)
|
||||
# Display uses server time, not the phone's local month/time zone.
|
||||
if item.GetValue(0)!=self.state.month:continue
|
||||
self.AskTicket(cell,vnum);return
|
||||
self.state.error='ticket';self.Refresh()
|
||||
|
||||
def ConfirmActivate(self,cell,vnum):
|
||||
self.CloseConfirm();self.state.Activate(cell,vnum);self.Refresh()
|
||||
|
||||
def Slots(self):
|
||||
return sorted(self.state.missions)
|
||||
|
||||
@@ -264,7 +311,7 @@ class BattlePassWindow(ui.Window):
|
||||
if m['claimed']:row['button'].SetText('已领取')
|
||||
elif s.claiming==m['slot']:row['button'].SetText('领取中')
|
||||
else:row['button'].SetText('领取' if done else '未完成')
|
||||
row['button'].SetEnabled(done and not m['claimed'] and bool(m['rewards']) and s.claiming is None)
|
||||
row['button'].SetEnabled(s.access in (None,1) and done and not m['claimed'] and bool(m['rewards']) and s.claiming is None)
|
||||
f=s.final
|
||||
for w in (self.finalName,self.finalState,self.finalReward,self.finalButton):
|
||||
if f:w.Show()
|
||||
@@ -274,7 +321,11 @@ class BattlePassWindow(ui.Window):
|
||||
self.finalState.SetText(L('已领取' if f['claimed'] else '全部任务完成' if ready else '完成全部任务后可领取'))
|
||||
self.finalReward.SetText(L('奖励:')+RewardText(f['rewards']))
|
||||
self.finalButton.SetText('已领取' if f['claimed'] else '领取中' if s.claiming==0 else '领取')
|
||||
self.finalButton.SetEnabled(ready and not f['claimed'] and s.claiming is None)
|
||||
self.finalButton.SetEnabled(s.access in (None,1) and ready and not f['claimed'] and s.claiming is None)
|
||||
if s.access==0:
|
||||
self.finalButton.Hide();self.finalState.Hide();self.finalReward.Hide();self.activateButton.Show()
|
||||
self.activateButton.SetEnabled(s.waiting is None)
|
||||
else:self.activateButton.Hide()
|
||||
many=self.Pages()>1
|
||||
for w in (self.prev,self.next,self.pageText):
|
||||
if many and s.season:w.Show()
|
||||
@@ -288,6 +339,8 @@ class BattlePassWindow(ui.Window):
|
||||
elif s.none:note='当前没有进行中的战令赛季'
|
||||
elif not s.season:note='正在查询……'
|
||||
elif s.claiming is not None:note='正在领取……'
|
||||
elif s.access==0:note='激活后才开始累计进度'
|
||||
elif s.access==2:note='本月战令已完成'
|
||||
else:note='击杀、钓鱼、强化等都会自动计入进度'
|
||||
self.note.SetText(L(note))
|
||||
|
||||
@@ -305,7 +358,7 @@ class BattlePassWindow(ui.Window):
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide();self.closeButton.event=self.finalButton.event=self.prev.event=self.next.event=None
|
||||
self.Hide();self.closeButton.event=self.finalButton.event=self.activateButton.event=self.prev.event=self.next.event=None
|
||||
for row in self.rows:row['button'].event=None
|
||||
self.state=None
|
||||
|
||||
@@ -327,7 +380,10 @@ def OnPass(kind,value):
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L('战令任务完成:')+name+L(',按 F6 领取奖励'))
|
||||
elif kind=='claimed':chat.AppendChat(chat.CHAT_TYPE_INFO,L('战令奖励已放入背包' if value else '战令最终奖励已放入背包'))
|
||||
elif kind=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[s.error]))
|
||||
if g_window and g_window.IsShow():g_window.Refresh()
|
||||
if g_window and g_window.IsShow():
|
||||
if kind=='info' and g_window.pendingTicket:
|
||||
ticket=g_window.pendingTicket;g_window.pendingTicket=None;g_window.AskTicket(*ticket)
|
||||
g_window.Refresh()
|
||||
|
||||
|
||||
g_pass=Pass(net.SendChatPacket,app.GetTime,OnPass)
|
||||
|
||||
@@ -24,6 +24,20 @@ g_tick=None
|
||||
PAGE=8
|
||||
REFRESH=30.
|
||||
SHARED_CHANNEL=99
|
||||
TRAVEL_LEVELS={9844:(40,60),9836:(65,85),9838:(80,100),9840:(95,115),9842:(105,120),
|
||||
1093:(40,120),2092:(70,120),2493:(75,120),2598:(80,120),6091:(90,120),
|
||||
6191:(90,120),9018:(105,120),20442:(110,120)}
|
||||
|
||||
|
||||
def Travel(vnum,done=None):
|
||||
service=mt_feature_service.g_service
|
||||
if not service:return
|
||||
def received(data,error):
|
||||
errors={'unsupported':'服务器未启用此入口传送','level':'等级不符合入口要求',
|
||||
'busy':'当前状态不能传送,请稍后再试','unavailable':'服务器尚未开放该地图'}
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L(errors.get(error,'传送失败,请稍后重试') if error else '正在前往入口'))
|
||||
if done:done(data,error)
|
||||
service.Request('travel',vnum,0,received)
|
||||
# Server map index -> map directory (share/locale/<locale>/map/index), for localeInfo.MINIMAP_ZONE_NAME_DICT.
|
||||
MAPS={1:'metin2_map_a1',3:'metin2_map_a3',4:'metin2_map_guild_01',5:'metin2_map_monkey_dungeon_11',
|
||||
6:'metin2_guild_village_01',21:'metin2_map_b1',23:'metin2_map_b3',24:'metin2_map_guild_02',
|
||||
@@ -117,10 +131,11 @@ class BossWindow(ui.Window):
|
||||
self.lines=[Text(self,18,0,'',0xffefdfc3) for i in range(PAGE)]
|
||||
self.details=[Text(self,30,0,'',0xffb2aa9a) for i in range(PAGE)]
|
||||
self.remindButtons=[Action(self,0,0,92,'',lambda i=i:self.Remind(i)) for i in range(PAGE)]
|
||||
self.travelButtons=[Action(self,0,0,72,'传送',lambda i=i:self.Teleport(i)) for i in range(PAGE)]
|
||||
self.note=Text(self,18,0,'提醒:Boss 刷新后在聊天框提示;以服务器刷新为准。',0xffb2aa9a)
|
||||
self.Reflow();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons
|
||||
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons+self.travelButtons
|
||||
|
||||
def Open(self):
|
||||
self.Reflow();self.SetCenterPosition();self.Show();self.SetTop();self.Query()
|
||||
@@ -147,6 +162,12 @@ class BossWindow(ui.Window):
|
||||
rows=self.tracker.rows or [];index=self.page*PAGE+i
|
||||
if index<len(rows):self.tracker.Toggle(rows[index]);self.Render()
|
||||
|
||||
def Teleport(self,i):
|
||||
rows=self.tracker.rows or [];index=self.page*PAGE+i
|
||||
if index>=len(rows) or rows[index]['vnum'] not in TRAVEL_LEVELS:return
|
||||
self.travelButtons[i].SetEnabled(False)
|
||||
Travel(rows[index]['vnum'],lambda data,error:self.Render())
|
||||
|
||||
def Render(self):
|
||||
t=self.tracker;rows=t.rows or [];self.page=min(self.page,self.Pages()-1)
|
||||
if t.error:self.status.SetText(L('服务端未启用 Boss 追踪' if t.error=='unsupported' else '未同步,请稍后刷新'))
|
||||
@@ -156,6 +177,7 @@ class BossWindow(ui.Window):
|
||||
self.prevButton.SetEnabled(self.page>0);self.nextButton.SetEnabled(self.page+1<self.Pages())
|
||||
for i in range(PAGE):
|
||||
index=self.page*PAGE+i;line=self.lines[i];detail=self.details[i];button=self.remindButtons[i]
|
||||
travel=self.travelButtons[i];travel.Hide()
|
||||
if index>=len(rows):line.Hide();detail.Hide();button.Hide();continue
|
||||
r=rows[index];left=t.Left(r)
|
||||
channel='共享' if r['channel']==SHARED_CHANNEL else 'CH%d'%r['channel']
|
||||
@@ -169,6 +191,9 @@ class BossWindow(ui.Window):
|
||||
button.SetText(L('提醒:'+('开' if Key(r) in t.reminders else '关')))
|
||||
button.SetEnabled(bool(r['alive']==0 and r['next']) or Key(r) in t.reminders)
|
||||
line.Show();detail.Show();button.Show()
|
||||
service=mt_feature_service.g_service
|
||||
if r['vnum'] in TRAVEL_LEVELS and service and service.mask is not None and service.mask&512:
|
||||
travel.Show();travel.SetEnabled(not service.pending and not service.queue)
|
||||
|
||||
def Reflow(self):
|
||||
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
|
||||
@@ -179,6 +204,7 @@ class BossWindow(ui.Window):
|
||||
for i in range(PAGE):
|
||||
y=88+i*spacing
|
||||
self.lines[i].SetPosition(18,y);self.details[i].SetPosition(30,y+18);self.remindButtons[i].SetPosition(width-110,y)
|
||||
self.travelButtons[i].SetPosition(width-190,y)
|
||||
self.note.SetPosition(18,height-22);self.SetCenterPosition()
|
||||
|
||||
def OnUpdate(self):
|
||||
|
||||
@@ -21,18 +21,22 @@ LEVEL_HINTS=('显示所有角色的特效','隐藏其他玩家和NPC的特效,
|
||||
|
||||
|
||||
class Options(object):
|
||||
def __init__(self):self.effect=0;self.tree=True;self.cloud=True
|
||||
def __init__(self):self.effect=0;self.tree=True;self.cloud=True;self.shopRange=0;self.npcNames=True
|
||||
|
||||
def Load(self,text):
|
||||
words=text.split()
|
||||
if len(words)!=3 or not all(w.isdigit() and len(w)==1 for w in words):return
|
||||
effect,tree,cloud=[int(w) for w in words]
|
||||
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1):self.effect=effect;self.tree=tree==1;self.cloud=cloud==1
|
||||
if len(words) not in (3,5) or not all(w.isdigit() and len(w)==1 for w in words):return
|
||||
effect,tree,cloud=[int(w) for w in words[:3]]
|
||||
shop,names=[int(w) for w in words[3:]] if len(words)==5 else (0,1)
|
||||
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1) and shop<5 and names in (0,1):
|
||||
self.effect=effect;self.tree=tree==1;self.cloud=cloud==1;self.shopRange=shop;self.npcNames=names==1
|
||||
|
||||
def Dump(self):return '%d %d %d'%(self.effect,int(self.tree),int(self.cloud))
|
||||
def Dump(self):return '%d %d %d %d %d'%(self.effect,int(self.tree),int(self.cloud),self.shopRange,int(self.npcNames))
|
||||
|
||||
def Apply(self):
|
||||
systemSetting.SetEffectLevel(self.effect)
|
||||
systemSetting.SetShopNamesRange(self.shopRange)
|
||||
systemSetting.SetShopNameStatus(self.npcNames)
|
||||
background.SetVisiblePart(background.PART_TREE,int(self.tree))
|
||||
background.SetVisiblePart(background.PART_CLOUD,int(self.cloud))
|
||||
|
||||
@@ -55,7 +59,7 @@ def Mark(text,on):return L(B(u'【%s】'%text if on else text))
|
||||
class DisplayWindow(ui.Window):
|
||||
def __init__(self,options):
|
||||
ui.Window.__init__(self);self.SetWindowName('DisplayWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.options=options;self.SetSize(332,404)
|
||||
self.options=options;self.SetSize(332,456)
|
||||
self.heading=Text(self,18,18,'显示设置',0xffffd68b)
|
||||
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
|
||||
self.effectText=Text(self,18,54,'特效',0xffc3b7a1)
|
||||
@@ -65,10 +69,12 @@ class DisplayWindow(ui.Window):
|
||||
self.cloudButton=Action(self,170,260,144,'',self.ToggleCloud)
|
||||
self.nameButton=Action(self,18,312,144,'',self.ToggleName)
|
||||
self.damageButton=Action(self,170,312,144,'',self.ToggleDamage)
|
||||
self.status=Text(self,18,376,'',0xffc3b7a1)
|
||||
self.rangeButton=Action(self,18,364,144,'',self.NextRange)
|
||||
self.npcButton=Action(self,170,364,144,'',self.ToggleNPC)
|
||||
self.status=Text(self,18,428,'',0xffc3b7a1)
|
||||
self.Refresh();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton]+self.levelButtons
|
||||
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton,self.rangeButton,self.npcButton]+self.levelButtons
|
||||
|
||||
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
|
||||
|
||||
@@ -80,6 +86,10 @@ class DisplayWindow(ui.Window):
|
||||
|
||||
def ToggleCloud(self):self.options.cloud=not self.options.cloud;self.Changed()
|
||||
|
||||
def NextRange(self):self.options.shopRange=(self.options.shopRange+1)%5;self.Changed()
|
||||
|
||||
def ToggleNPC(self):self.options.npcNames=not self.options.npcNames;self.Changed()
|
||||
|
||||
# Names and damage numbers are the original game options (saved by the client config on exit).
|
||||
def ToggleName(self):systemSetting.SetAlwaysShowNameFlag(not systemSetting.IsAlwaysShowName());self.Refresh()
|
||||
|
||||
@@ -91,6 +101,8 @@ class DisplayWindow(ui.Window):
|
||||
self.treeButton.SetText(Mark(u'显示树木',o.tree));self.cloudButton.SetText(Mark(u'显示云',o.cloud))
|
||||
self.nameButton.SetText(Mark(u'总是显示名字',systemSetting.IsAlwaysShowName()))
|
||||
self.damageButton.SetText(Mark(u'显示伤害数字',systemSetting.IsShowDamage()))
|
||||
self.rangeButton.SetText(L(B(u'摊位范围 %d 米'%((100,60,40,20,10)[o.shopRange]))))
|
||||
self.npcButton.SetText(Mark(u'显示NPC名称',o.npcNames))
|
||||
self.status.SetText(L(LEVEL_HINTS[o.effect]))
|
||||
|
||||
def OnRender(self):
|
||||
|
||||
@@ -33,6 +33,7 @@ class DungeonWindow(ui.Window):
|
||||
self.rows=[Text(self,24,142+32*i,'',0xffefdfc3) for i in range(6)]
|
||||
self.remindButton=Action(self,18,0,146,'到期提醒:关',self.Remind)
|
||||
self.entryButton=Action(self,180,0,146,'查看入口',self.Entry)
|
||||
self.travelButton=Action(self,342,0,146,'传送到入口',self.Travel)
|
||||
self.note=Text(self,18,0,'当前仅接入已核实的龙穴及相关周任务。',0xffb2aa9a)
|
||||
self.Reflow();self.Hide()
|
||||
|
||||
@@ -92,6 +93,15 @@ class DungeonWindow(ui.Window):
|
||||
self.remindButton.SetText('到期提醒:'+('开' if self.reminder is not None and self.reminder[0]==self.tab else '关'))
|
||||
self.remindButton.SetEnabled(v is not None and not self.stale and (self.tab==0 or 'weekly_end' in v))
|
||||
self.entryButton.SetEnabled(v is not None and not self.stale and (self.tab==0 or 'weekly_npc' in v))
|
||||
service=mt_feature_service.g_service
|
||||
if self.tab==0 and service and service.mask is not None and service.mask&512:self.travelButton.Show()
|
||||
else:self.travelButton.Hide()
|
||||
self.travelButton.SetEnabled(v is not None and not self.stale)
|
||||
|
||||
def Travel(self):
|
||||
if self.values is None or self.stale or self.tab!=0:return
|
||||
import mt_boss
|
||||
mt_boss.Travel(2493)
|
||||
|
||||
def Entry(self):
|
||||
if self.values is None or self.stale:return
|
||||
@@ -124,6 +134,7 @@ class DungeonWindow(ui.Window):
|
||||
if dims==self.dimensions:return
|
||||
self.dimensions=dims;width=min(660,max(500,dims[0]-16));height=min(450,max(300,dims[1]-16));self.SetSize(width,height)
|
||||
self.closeButton.SetPosition(width-76,6)
|
||||
self.travelButton.SetPosition(342,height-74)
|
||||
spacing=min(32,max(16,(height-250)//5))
|
||||
for i,row in enumerate(self.rows):row.SetPosition(24,132+i*spacing)
|
||||
self.remindButton.SetPosition(18,height-74);self.entryButton.SetPosition(180,height-74);self.note.SetPosition(18,height-18)
|
||||
@@ -148,7 +159,7 @@ class DungeonWindow(ui.Window):
|
||||
|
||||
def Destroy(self):
|
||||
self.generation+=1;self.reminder=None;self.values=None;self.Hide()
|
||||
for b in (self.closeButton,self.lairButton,self.weeklyButton,self.refreshButton,self.remindButton,self.entryButton):b.event=None
|
||||
for b in (self.closeButton,self.lairButton,self.weeklyButton,self.refreshButton,self.remindButton,self.entryButton,self.travelButton):b.event=None
|
||||
|
||||
|
||||
class ReminderTick(ui.Window):
|
||||
|
||||
@@ -6,7 +6,7 @@ import net
|
||||
import ui
|
||||
from mt_wiki_data import Number
|
||||
|
||||
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256}
|
||||
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256,'travel':512}
|
||||
WHOLE=('stats','dungeons','bosses') # one reply with every row; no subject or page
|
||||
g_service=None
|
||||
g_tick=None
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// PORT: touch equivalents of AVA2's inventory preview / chest shortcuts.
|
||||
// Native touch selection invokes ShowInventory; no synthetic modifier keys.
|
||||
static const char c_szItemActionsScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import game
|
||||
import grp
|
||||
import player
|
||||
import ui
|
||||
import uiInventory
|
||||
import weakref
|
||||
import wndMgr
|
||||
from mt_biolog import Action
|
||||
|
||||
g_window=None
|
||||
|
||||
|
||||
class ItemActions(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self);self.AddFlag('float');self.SetWindowName('TouchItemActions')
|
||||
self.snapshot=None;self.buttons=[];self.Hide()
|
||||
|
||||
def Clear(self):
|
||||
self.Hide();self.snapshot=None
|
||||
for button in self.buttons:button.Hide();button.event=None
|
||||
self.buttons=[]
|
||||
|
||||
def Valid(self):
|
||||
if not self.snapshot:return False
|
||||
try:
|
||||
owner,page,cell,vnum,count=self.snapshot
|
||||
return (owner.IsShow() and owner.inventoryPageIndex==page and
|
||||
player.GetItemIndex(cell)==vnum and player.GetItemCount(cell)==count)
|
||||
except ReferenceError:return False
|
||||
|
||||
def Select(self,owner,cell):
|
||||
self.Clear()
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if not vnum:return
|
||||
self.snapshot=(weakref.proxy(owner),owner.inventoryPageIndex,cell,vnum,player.GetItemCount(cell))
|
||||
import mt_preview
|
||||
import mt_chest
|
||||
import mt_wiki
|
||||
choices=[('百科',lambda:mt_wiki.OpenItem(vnum))]
|
||||
if mt_preview.ItemSpec(vnum):choices.append(('模型预览',lambda:mt_preview.Preview('item',vnum)))
|
||||
if mt_chest.g_window and mt_chest.Batchable(vnum):
|
||||
choices.append(('批量开箱',lambda:mt_chest.g_window.Select(cell,vnum)))
|
||||
choices.append(('关闭',self.Clear))
|
||||
for i,(label,action) in enumerate(choices):
|
||||
self.buttons.append(Action(self,8+i*108,6,100,label,lambda action=action:self.Run(action)))
|
||||
self.SetSize(16+len(choices)*108,60)
|
||||
x,y=owner.GetGlobalPosition()
|
||||
self.SetPosition(max(0,min(x,wndMgr.GetScreenWidth()-self.GetWidth())),
|
||||
max(0,min(y+owner.GetHeight(),wndMgr.GetScreenHeight()-self.GetHeight())))
|
||||
self.Show();self.SetTop()
|
||||
|
||||
def Run(self,action):
|
||||
valid=self.Valid();self.Clear()
|
||||
if valid:action()
|
||||
|
||||
def OnUpdate(self):
|
||||
if self.IsShow() and not self.Valid():self.Clear()
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnPressEscapeKey(self):self.Clear();return True
|
||||
|
||||
|
||||
def ShowInventory(owner,cell):
|
||||
if g_window:g_window.Select(owner,cell)
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
|
||||
def Open(self):
|
||||
global g_window
|
||||
_open(self);g_window=ItemActions()
|
||||
|
||||
def Close(self):
|
||||
global g_window
|
||||
if g_window:g_window.Clear();g_window=None
|
||||
_close(self)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
|
||||
_use=uiInventory.InventoryWindow.UseItemSlot
|
||||
|
||||
def UseItemSlot(self,slot):
|
||||
cell=self._InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos(slot)
|
||||
vnum=player.GetItemIndex(cell)
|
||||
if 25150<=vnum<=25161:
|
||||
import mt_battlepass
|
||||
if mt_battlepass.g_window:mt_battlepass.g_window.OfferTicket(cell,vnum)
|
||||
return
|
||||
if vnum in (50348,50349):
|
||||
import mt_switchbot
|
||||
if mt_switchbot.g_window:mt_switchbot.g_window.Open()
|
||||
return
|
||||
return _use(self,slot)
|
||||
|
||||
uiInventory.InventoryWindow.UseItemSlot=UseItemSlot
|
||||
)PY";
|
||||
@@ -0,0 +1,30 @@
|
||||
// PORT: networking is prepared by the native transport, independently of the login UI.
|
||||
#include <Python.h>
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h"
|
||||
#include "MeshPortConfig.h"
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
namespace {
|
||||
PyObject* event(PyObject*,PyObject*) { return PyInt_FromLong(mt::meshport::take_event()); }
|
||||
PyObject* local(PyObject*,PyObject* args) {
|
||||
const char* ip;if(!PyArg_ParseTuple(args,"s",&ip))return nullptr;
|
||||
return PyBool_FromLong(mt::meshport::same_subnet(ip));
|
||||
}
|
||||
PyMethodDef methods[]={
|
||||
{"event",event,METH_NOARGS,nullptr},{"same_subnet",local,METH_VARARGS,nullptr},
|
||||
{nullptr,nullptr,0,nullptr}
|
||||
};
|
||||
}
|
||||
void initMeshPort() {
|
||||
std::string config=kMeshPortConfig;
|
||||
if(const char* path=std::getenv("MT_MESHPORT_CONFIG")) {
|
||||
std::ifstream input(path,std::ios::binary);
|
||||
config.assign(std::istreambuf_iterator<char>(input),{});
|
||||
}
|
||||
if(config.size()>65536)config.clear();
|
||||
mt::meshport::configure(config);
|
||||
Py_InitModule("_mt_meshport",methods);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
// PORT: native transport owns routing; Python displays status and handles pending-login cancellation.
|
||||
static const char* c_szMeshPortScript = R"PY(# -*- coding: utf-8 -*-
|
||||
import app
|
||||
import ui
|
||||
import wndMgr
|
||||
import player
|
||||
import introLogin
|
||||
import net
|
||||
import _mt_meshport as native
|
||||
|
||||
|
||||
class NetworkNotice(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self)
|
||||
self.label = ui.TextLine()
|
||||
self.label.SetHorizontalAlignCenter()
|
||||
self.hideAt = 0
|
||||
self.Show()
|
||||
|
||||
def OnUpdate(self):
|
||||
event = native.event()
|
||||
if event:
|
||||
messages = {1: '正在组网,等待动态分配 IP...',
|
||||
2: '组网成功', 3: '组网连接失败,请检查网络后重试'}
|
||||
self.label.SetText(player.AutoHuntLocalize(messages[event]))
|
||||
self.label.SetPackedFontColor(0xff66ee88 if event == 2 else 0xffffdd77)
|
||||
self.label.SetPosition(wndMgr.GetScreenWidth() / 2, 32)
|
||||
self.label.Show()
|
||||
self.label.SetTop()
|
||||
self.hideAt = app.GetTime() + (65 if event == 1 else 6)
|
||||
if self.hideAt and app.GetTime() >= self.hideAt:
|
||||
self.label.Hide()
|
||||
self.hideAt = 0
|
||||
|
||||
|
||||
notice = NetworkNotice()
|
||||
|
||||
# Original login popup uses the focus callback for its Cancel button. Stop only
|
||||
# the account/game transports still preparing; leave established sessions and
|
||||
# background channel queries alone. No credentials or Connect methods are wrapped.
|
||||
def _wrap_cancel(method):
|
||||
def Cancel(self, *args):
|
||||
if net.CancelPendingLogin():
|
||||
notice.label.Hide()
|
||||
notice.hideAt = 0
|
||||
return method(self, *args)
|
||||
return Cancel
|
||||
|
||||
introLogin.LoginWindow.SetPasswordEditLineFocus = _wrap_cancel(introLogin.LoginWindow.SetPasswordEditLineFocus)
|
||||
introLogin.LoginWindow.OnPressExitKey = _wrap_cancel(introLogin.LoginWindow.OnPressExitKey)
|
||||
introLogin.LoginWindow.Close = _wrap_cancel(introLogin.LoginWindow.Close)
|
||||
)PY";
|
||||
@@ -56,6 +56,9 @@ def _Select(self, slot):
|
||||
_last_time = app.GetTime()
|
||||
if _last[3]:
|
||||
self.ShowToolTip(_last[2])
|
||||
import sys
|
||||
actions = sys.modules.get('mt_item_actions')
|
||||
if actions:actions.ShowInventory(self, _last[2])
|
||||
return
|
||||
snapshot = _Snapshot(self, slot) if dragging and not mouse.isAttached() else None
|
||||
result = _OriginalSelect(self, slot)
|
||||
|
||||
@@ -47,6 +47,9 @@
|
||||
#include "UserInterface/CRenderTargetManager.h"
|
||||
#include "EterBase/Timer.h"
|
||||
#include "PythonBoot.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h"
|
||||
#endif
|
||||
#include "../UserInterface/UserInterface.h"
|
||||
#include "PythonHost.h"
|
||||
#include "../EterLib/UIRenderCommands.h"
|
||||
@@ -250,6 +253,10 @@ void* fiber_main(void*)
|
||||
}
|
||||
|
||||
void init_2v0_gameplay_stubs();
|
||||
void StopAccountRegistration(); // PORT: drain registration before networking teardown.
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
void initMeshPort();
|
||||
#endif
|
||||
|
||||
namespace PythonBoot
|
||||
{
|
||||
@@ -899,6 +906,9 @@ bool run_main_script_body(const char* lpCmdLine, std::string* error)
|
||||
initChat();
|
||||
initTextTail();
|
||||
initnet();
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
initMeshPort();
|
||||
#endif
|
||||
initMiniMap();
|
||||
initEvent();
|
||||
initeffect();
|
||||
@@ -1011,6 +1021,10 @@ namespace PythonBoot
|
||||
#include "VipScript.inc"
|
||||
#include "ModelPreviewScript.inc"
|
||||
#include "BattlePassScript.inc"
|
||||
#include "ItemActionsScript.inc"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "MeshPortScript.inc"
|
||||
#endif
|
||||
|
||||
static void install_script_module(const char* c_szModule, const char* c_szScript)
|
||||
{
|
||||
@@ -1066,6 +1080,9 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
|
||||
{
|
||||
install_script_module("mt_autohunt", c_szAutoHuntScript);
|
||||
install_script_module("mt_register", c_szRegisterScript);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
install_script_module("mt_meshport", c_szMeshPortScript);
|
||||
#endif
|
||||
install_script_module("mt_framerate", c_szFrameRateOptionScript);
|
||||
install_script_module("mt_uiscale", c_szUIScaleOptionScript);
|
||||
install_script_module("mt_inventory", c_szInventoryPagesScript);
|
||||
@@ -1093,6 +1110,7 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
|
||||
install_script_module("mt_vip", c_szVipScript);
|
||||
install_script_module("mt_preview", c_szModelPreviewScript);
|
||||
install_script_module("mt_battlepass", c_szBattlePassScript);
|
||||
install_script_module("mt_item_actions", c_szItemActionsScript);
|
||||
if (g_touch_input)
|
||||
install_script_module("mt_mobile_hud", c_szMobileHUDScript);
|
||||
}
|
||||
@@ -1197,6 +1215,10 @@ void Stop()
|
||||
" getattr(_mm.mouseController, 'cursorDict', {}).clear()\n");
|
||||
PyGILState_Release(gil);
|
||||
}
|
||||
StopAccountRegistration();
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::shutdown(); // PORT: join SDK worker and stop mesh before Python/platform teardown.
|
||||
#endif
|
||||
g_launcher->Clear();
|
||||
g_game_singletons.reset();
|
||||
g_game_application.reset();
|
||||
|
||||
@@ -159,6 +159,8 @@ class RegisterDialog(ui.BoardWithTitleBar):
|
||||
ui.__mem_func__(self.Close))
|
||||
|
||||
def Destroy(self):
|
||||
if self.pending:
|
||||
net.CancelRegisterAccount()
|
||||
self.Hide()
|
||||
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
|
||||
row.Destroy()
|
||||
@@ -178,6 +180,11 @@ class RegisterDialog(ui.BoardWithTitleBar):
|
||||
self.loginRow.edit.SetFocus()
|
||||
|
||||
def Close(self):
|
||||
if self.pending:
|
||||
net.CancelRegisterAccount()
|
||||
self.pending = False
|
||||
self.pendingPassword = ""
|
||||
self.registerButton.Enable()
|
||||
for row in (self.loginRow, self.passwordRow, self.confirmRow, self.socialRow):
|
||||
row.edit.KillFocus()
|
||||
self.Hide()
|
||||
|
||||
@@ -31,7 +31,7 @@ REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达
|
||||
ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练',
|
||||
'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练',
|
||||
'unsupported':'服务器尚未启用自动洗练','slot':'该条属性不能锁定','max':'最多锁定 2 条,且至少留 1 条可洗',
|
||||
'db':'锁定保存失败,请稍后再试'}
|
||||
'db':'锁定保存失败,请稍后再试','five_attr':'装备需要 5 条普通属性才能锁定','material':'锁定需要道具 50348,解锁需要道具 50349'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=4294967295):
|
||||
@@ -188,7 +188,7 @@ class SwitchbotWindow(ui.Window):
|
||||
vnum=player.GetItemIndex(player.INVENTORY,cell)
|
||||
if not vnum:continue
|
||||
item.SelectItem(vnum);kind=item.GetItemType()
|
||||
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE:
|
||||
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE and vnum not in (50348,50349):
|
||||
scrolls[vnum]=scrolls.get(vnum,0)+player.GetItemCount(player.INVENTORY,cell)
|
||||
elif kind in (item.ITEM_TYPE_WEAPON,item.ITEM_TYPE_ARMOR) and any(player.GetItemAttribute(player.INVENTORY,cell,i)[0] for i in range(5)):
|
||||
items.append((cell,vnum))
|
||||
|
||||
@@ -19,6 +19,9 @@ if(NOT TARGET mtpython)
|
||||
endif()
|
||||
|
||||
add_library(port_logic STATIC ${MT_PORT_SOURCES})
|
||||
if(TARGET mt_meshport)
|
||||
target_link_libraries(port_logic PUBLIC mt_meshport)
|
||||
endif()
|
||||
target_include_directories(port_logic PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
# 40250 system headers the ported sources keep including verbatim: D3D8/D3DX/Miles SDK types everywhere,
|
||||
# Windows/CRT ones only where the platform has none.
|
||||
@@ -326,6 +329,12 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_channel.py)
|
||||
add_test(NAME port.boss
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_boss.py)
|
||||
add_test(NAME port.battlepass
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_battlepass.py)
|
||||
add_test(NAME port.model_preview
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_model_preview.py)
|
||||
add_test(NAME port.item_actions
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_item_actions.py)
|
||||
add_test(NAME port.chest
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_chest.py)
|
||||
add_test(NAME port.ava2_items
|
||||
|
||||
@@ -32,9 +32,15 @@ void CNetworkAddress::Clear()
|
||||
|
||||
bool CNetworkAddress::IsIP(const char* c_szAddr)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
// PORT: digit-prefixed hostnames must resolve before the common subnet decision.
|
||||
in_addr parsed{};
|
||||
return c_szAddr && inet_pton(AF_INET,c_szAddr,&parsed) == 1;
|
||||
#else
|
||||
if (c_szAddr[0]<'0' || c_szAddr[0]>'9')
|
||||
return false;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool CNetworkAddress::Set(const char* c_szAddr, int port)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagram.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: preserve datagram payload/source/peek semantics over application-only mesh.
|
||||
#endif
|
||||
|
||||
CNetworkDatagram::CNetworkDatagram()
|
||||
{
|
||||
@@ -16,6 +19,9 @@ void CNetworkDatagram::Destroy()
|
||||
if (INVALID_SOCKET==m_sock)
|
||||
return;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_sock);
|
||||
#endif
|
||||
closesocket(m_sock);
|
||||
|
||||
__Initialize();
|
||||
@@ -68,6 +74,9 @@ void CNetworkDatagram::Update()
|
||||
|
||||
bool CNetworkDatagram::CanRecv()
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (mt::meshport::datagram_ready(m_sock)) return true;
|
||||
#endif
|
||||
if (FD_ISSET(m_sock, &m_fdsRecv))
|
||||
return true;
|
||||
|
||||
@@ -77,19 +86,31 @@ bool CNetworkDatagram::CanRecv()
|
||||
|
||||
int CNetworkDatagram::PeekRecvFrom(UINT uBufLen, void* pvBuf, SOCKADDR_IN* pkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::recv_datagram(m_sock,pvBuf,uBufLen,MSG_PEEK,pkSockAddrIn);
|
||||
#else
|
||||
int nSockAddrInLen=sizeof(SOCKADDR_IN);
|
||||
return recvfrom(m_sock, (char*)pvBuf, uBufLen, MSG_PEEK, (PSOCKADDR)pkSockAddrIn, &nSockAddrInLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNetworkDatagram::RecvFrom(UINT uBufLen, void* pvBuf, SOCKADDR_IN* pkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::recv_datagram(m_sock,pvBuf,uBufLen,0,pkSockAddrIn);
|
||||
#else
|
||||
int nSockAddrInLen=sizeof(SOCKADDR_IN);
|
||||
return recvfrom(m_sock, (char*)pvBuf, uBufLen, 0, (PSOCKADDR)pkSockAddrIn, &nSockAddrInLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
int CNetworkDatagram::SendTo(UINT uBufLen, const void* c_pvBuf, const SOCKADDR_IN& c_rkSockAddrIn)
|
||||
{
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
return mt::meshport::send_datagram(m_sock,c_pvBuf,uBufLen,0,c_rkSockAddrIn);
|
||||
#else
|
||||
return sendto(m_sock, (const char *)c_pvBuf, uBufLen, 0, (PSOCKADDR)&c_rkSockAddrIn, sizeof(SOCKADDR_IN));
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagramReceiver.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: shared datagram receive and relay lifetime.
|
||||
#endif
|
||||
|
||||
BOOL CNetDatagramReceiver::Process()
|
||||
{
|
||||
m_recvBufCurrentPos = 0;
|
||||
m_recvBufCurrentSize = 0;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
m_recvBufCurrentSize = mt::meshport::recv_datagram(m_Socket,m_recvBuf,m_recvBufSize,0,&m_SockAddr);
|
||||
#else
|
||||
int irecvAddrLength = sizeof(SOCKADDR_IN);
|
||||
m_recvBufCurrentSize = recvfrom(m_Socket, (char *)m_recvBuf, m_recvBufSize, 0, (PSOCKADDR)&m_SockAddr, &irecvAddrLength);
|
||||
#endif
|
||||
|
||||
if (m_recvBufCurrentSize <= 0)
|
||||
{
|
||||
@@ -42,7 +49,9 @@ BOOL CNetDatagramReceiver::isBind()
|
||||
|
||||
BOOL CNetDatagramReceiver::Bind(DWORD /*dwAddress*/, WORD wPortIndex)
|
||||
{
|
||||
Clear(); // PORT: rebinding releases any previous UDP/mesh association.
|
||||
m_Socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (m_Socket == INVALID_SOCKET) return FALSE;
|
||||
|
||||
DWORD arg = 1;
|
||||
ioctlsocket(m_Socket, FIONBIO, &arg); // Non-blocking mode
|
||||
@@ -56,6 +65,8 @@ BOOL CNetDatagramReceiver::Bind(DWORD /*dwAddress*/, WORD wPortIndex)
|
||||
if (bind(m_Socket, (PSOCKADDR)&m_SockAddr, sizeof(SOCKADDR_IN)) < 0)
|
||||
{
|
||||
Tracef("Failed binding socket\n");
|
||||
closesocket(m_Socket);
|
||||
m_Socket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
@@ -79,6 +90,12 @@ void CNetDatagramReceiver::SetRecvBufferSize(int recvBufSize)
|
||||
|
||||
void CNetDatagramReceiver::Clear()
|
||||
{
|
||||
if (m_isBind) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket); // PORT: close UDP and any mesh association before resetting state.
|
||||
}
|
||||
|
||||
m_isBind = FALSE;
|
||||
|
||||
@@ -93,6 +110,7 @@ void CNetDatagramReceiver::Clear()
|
||||
|
||||
CNetDatagramReceiver::CNetDatagramReceiver()
|
||||
{
|
||||
m_isBind = FALSE;
|
||||
m_recvBuf = NULL;
|
||||
m_recvBufSize = 0;
|
||||
|
||||
@@ -100,6 +118,7 @@ CNetDatagramReceiver::CNetDatagramReceiver()
|
||||
}
|
||||
CNetDatagramReceiver::~CNetDatagramReceiver()
|
||||
{
|
||||
Clear();
|
||||
if (m_recvBuf)
|
||||
delete [] m_recvBuf;
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetDatagramSender.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: common LAN/mesh policy and relay lifetime.
|
||||
#endif
|
||||
|
||||
BOOL CNetDatagramSender::SetSocket(const char * c_szIP, WORD wPortIndex)
|
||||
{
|
||||
@@ -8,12 +11,19 @@ BOOL CNetDatagramSender::SetSocket(const char * c_szIP, WORD wPortIndex)
|
||||
|
||||
BOOL CNetDatagramSender::SetSocket(DWORD dwAddress, WORD wPortIndex)
|
||||
{
|
||||
if (m_isSocket) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket);
|
||||
}
|
||||
m_isSocket = TRUE;
|
||||
|
||||
m_dwAddress = dwAddress;
|
||||
m_wPortIndex = wPortIndex;
|
||||
|
||||
m_Socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (m_Socket == INVALID_SOCKET) { m_isSocket = FALSE; return FALSE; }
|
||||
|
||||
memset(&m_SockAddr, 0, sizeof(SOCKADDR_IN));
|
||||
m_SockAddr.sin_family = AF_INET;
|
||||
@@ -27,7 +37,11 @@ BOOL CNetDatagramSender::Send(const void * pBuffer, int iSize)
|
||||
{
|
||||
assert(isSocket());
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
int iSendingLength = mt::meshport::send_datagram(m_Socket,pBuffer,iSize,0,m_SockAddr);
|
||||
#else
|
||||
int iSendingLength = sendto(m_Socket, (const char *)pBuffer, iSize, 0, (PSOCKADDR)&m_SockAddr, sizeof(SOCKADDR_IN));
|
||||
#endif
|
||||
if (iSendingLength < 0)
|
||||
{
|
||||
Tracef("Failed sending packet\n");
|
||||
@@ -55,4 +69,10 @@ CNetDatagramSender::CNetDatagramSender()
|
||||
|
||||
CNetDatagramSender::~CNetDatagramSender()
|
||||
{
|
||||
if (m_isSocket) {
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_Socket);
|
||||
#endif
|
||||
closesocket(m_Socket); // PORT: release the UDP socket and its mesh association together.
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
#include "StdAfx.h"
|
||||
#include "NetStream.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: application-only mesh transport, including account/warp/mark sockets.
|
||||
#endif
|
||||
//#include "eterCrypt.h"
|
||||
|
||||
#ifndef _IMPROVED_PACKET_ENCRYPTION_
|
||||
@@ -288,6 +291,19 @@ void CNetworkStream::Process()
|
||||
if (m_sock == INVALID_SOCKET)
|
||||
return;
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (!m_isOnline && mt::meshport::pending(m_sock))
|
||||
{
|
||||
const int state = mt::meshport::poll_socket(m_sock);
|
||||
if (state < 0 || time(NULL) > m_connectLimitTime)
|
||||
{
|
||||
Clear();
|
||||
OnConnectFailure();
|
||||
return;
|
||||
}
|
||||
if (state == 0) return;
|
||||
}
|
||||
#endif
|
||||
fd_set fdsRecv;
|
||||
fd_set fdsSend;
|
||||
|
||||
@@ -373,6 +389,9 @@ void CNetworkStream::Clear()
|
||||
m_cipher.CleanUp();
|
||||
#endif
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(m_sock); // PORT: discard partial SOCKS negotiation before fd reuse.
|
||||
#endif
|
||||
closesocket(m_sock);
|
||||
m_sock = INVALID_SOCKET;
|
||||
|
||||
@@ -416,7 +435,12 @@ bool CNetworkStream::Connect(const CNetworkAddress& c_rkNetAddr, int limitSec)
|
||||
DWORD arg = 1;
|
||||
ioctlsocket(m_sock, FIONBIO, &arg); // Non-blocking mode
|
||||
|
||||
if (connect(m_sock, (PSOCKADDR)&m_addr, m_addr.GetSize()) == SOCKET_ERROR)
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
const int connectResult = mt::meshport::connect_socket(m_sock, static_cast<const SOCKADDR_IN&>(m_addr), this);
|
||||
#else
|
||||
const int connectResult = connect(m_sock, (PSOCKADDR)&m_addr, m_addr.GetSize());
|
||||
#endif
|
||||
if (connectResult == SOCKET_ERROR)
|
||||
{
|
||||
int error = WSAGetLastError();
|
||||
|
||||
@@ -430,6 +454,9 @@ bool CNetworkStream::Connect(const CNetworkAddress& c_rkNetAddr, int limitSec)
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
if (mt::meshport::pending(m_sock) && limitSec < 75) limitSec = 75; // PORT: DHCP/routes plus remote SOCKS connect.
|
||||
#endif
|
||||
m_connectLimitTime = time(NULL) + limitSec;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2472,11 +2472,24 @@ void CInstanceBase::__UpdateEffectShown()
|
||||
else
|
||||
isShown = false;
|
||||
}
|
||||
m_GraphicThingInstance.SetAttachingEffectShown(isShown);
|
||||
m_GraphicThingInstance.SetAttachingEffectShown(isShown && PORT_IsDisplayVisible());
|
||||
}
|
||||
|
||||
bool CInstanceBase::PORT_IsDisplayVisible()
|
||||
{
|
||||
// AVA2 CActorInstance::IsShop and InstanceBase::__CanRender, including
|
||||
// the original 100/60/40/20/10 metre range presets. Never hide the main actor.
|
||||
CInstanceBase* main = __GetMainInstancePtr();
|
||||
if (!main || main == this || GetRace() < 30000 || GetRace() > 30020)
|
||||
return true;
|
||||
static const unsigned ranges[] = {10000, 6000, 4000, 2000, 1000};
|
||||
return NEW_GetDistanceFromDestInstance(*main) <= ranges[CPythonSystem::Instance().GetShopNamesRange()];
|
||||
}
|
||||
|
||||
bool CInstanceBase::__CanRender()
|
||||
{
|
||||
if (!PORT_IsDisplayVisible())
|
||||
return false;
|
||||
if (!__IsInViewFrustum())
|
||||
return false;
|
||||
if (IsAffect(AFFECT_INVISIBILITY))
|
||||
|
||||
@@ -398,6 +398,7 @@ class CInstanceBase
|
||||
|
||||
public:
|
||||
void SetMainInstance();
|
||||
bool PORT_IsDisplayVisible();
|
||||
|
||||
void OnSelected();
|
||||
void OnUnselected();
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: registration shares the same LAN/mesh policy as every game socket.
|
||||
#endif
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <fcntl.h>
|
||||
@@ -35,6 +39,11 @@ const int c_iRegisterTimeoutMs = 8000;
|
||||
std::mutex gs_kRegisterMutex;
|
||||
std::atomic<int> gs_iRegisterState(REGISTER_IDLE);
|
||||
std::string gs_strRegisterResult;
|
||||
// PORT: registration must stop on dialog cancellation and before the mesh runtime is torn down.
|
||||
std::thread gs_registerWorker;
|
||||
std::atomic<bool> gs_registerCancelled(false);
|
||||
std::mutex gs_registerSocketMutex;
|
||||
int gs_registerSocket = -1;
|
||||
|
||||
std::string __UrlEncode(const std::string& c_rstText)
|
||||
{
|
||||
@@ -58,8 +67,14 @@ std::string __UrlEncode(const std::string& c_rstText)
|
||||
|
||||
bool __WaitFor(int iSocket, short sEvents)
|
||||
{
|
||||
pollfd kPoll = { iSocket, sEvents, 0 };
|
||||
return poll(&kPoll, 1, c_iRegisterTimeoutMs) == 1 && (kPoll.revents & sEvents);
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(c_iRegisterTimeoutMs);
|
||||
while (!gs_registerCancelled && std::chrono::steady_clock::now() < deadline) {
|
||||
pollfd kPoll = {iSocket,sEvents,0};
|
||||
int result = poll(&kPoll,1,100);
|
||||
if (result > 0) return (kPoll.revents & sEvents) != 0;
|
||||
if (result < 0 && errno != EINTR) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c_rstBody)
|
||||
@@ -72,6 +87,7 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
if (getaddrinfo(c_rstHost.c_str(), std::to_string(iPort).c_str(), &kHints, &pkAddr) != 0 || !pkAddr)
|
||||
return "ERR CONNECT";
|
||||
|
||||
if (gs_registerCancelled) { freeaddrinfo(pkAddr); return "ERR CANCELLED"; }
|
||||
const int iSocket = socket(pkAddr->ai_family, pkAddr->ai_socktype, pkAddr->ai_protocol);
|
||||
if (iSocket < 0)
|
||||
{
|
||||
@@ -82,14 +98,37 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
const int iOne = 1;
|
||||
setsockopt(iSocket, SOL_SOCKET, SO_NOSIGPIPE, &iOne, sizeof(iOne));
|
||||
#endif
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
gs_registerSocket = iSocket;
|
||||
}
|
||||
fcntl(iSocket, F_SETFL, fcntl(iSocket, F_GETFL, 0) | O_NONBLOCK);
|
||||
|
||||
std::string stResult = "ERR CONNECT";
|
||||
int iError = 0;
|
||||
socklen_t iErrorLen = sizeof(iError);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
const int connected = mt::meshport::connect_socket(iSocket, *reinterpret_cast<sockaddr_in*>(pkAddr->ai_addr));
|
||||
const bool throughMesh = mt::meshport::pending(iSocket);
|
||||
bool meshReady = true;
|
||||
if (mt::meshport::pending(iSocket)) {
|
||||
int state = 0;
|
||||
while (state == 0 && !gs_registerCancelled) {
|
||||
state = mt::meshport::poll_socket(iSocket);
|
||||
if (!state) std::this_thread::sleep_for(std::chrono::milliseconds(2));
|
||||
}
|
||||
meshReady = state == 1;
|
||||
}
|
||||
if (!gs_registerCancelled && meshReady && (throughMesh || connected == 0 ||
|
||||
#else
|
||||
if (connect(iSocket, pkAddr->ai_addr, pkAddr->ai_addrlen) == 0 ||
|
||||
#endif
|
||||
(errno == EINPROGRESS && __WaitFor(iSocket, POLLOUT) &&
|
||||
getsockopt(iSocket, SOL_SOCKET, SO_ERROR, &iError, &iErrorLen) == 0 && iError == 0))
|
||||
getsockopt(iSocket, SOL_SOCKET, SO_ERROR, &iError, &iErrorLen) == 0 && iError == 0)
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
)
|
||||
#endif
|
||||
)
|
||||
{
|
||||
const std::string stRequest =
|
||||
"POST /register HTTP/1.0\r\n"
|
||||
@@ -140,9 +179,16 @@ std::string __Post(const std::string& c_rstHost, int iPort, const std::string& c
|
||||
}
|
||||
}
|
||||
|
||||
close(iSocket);
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
mt::meshport::forget_socket(iSocket);
|
||||
#endif
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
gs_registerSocket = -1;
|
||||
close(iSocket);
|
||||
}
|
||||
freeaddrinfo(pkAddr);
|
||||
return stResult;
|
||||
return gs_registerCancelled ? "ERR CANCELLED" : stResult;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,10 +218,12 @@ PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs)
|
||||
return Py_BuildValue("i", 0); // one request at a time
|
||||
}
|
||||
|
||||
if (gs_registerWorker.joinable()) gs_registerWorker.join();
|
||||
gs_registerCancelled = false;
|
||||
const std::string stHost = szHost;
|
||||
const std::string stBody = "login=" + __UrlEncode(szLogin) + "&password=" + __UrlEncode(szPassword) +
|
||||
"&social_id=" + __UrlEncode(szSocialID);
|
||||
std::thread([stHost, iPort, stBody]()
|
||||
gs_registerWorker = std::thread([stHost, iPort, stBody]()
|
||||
{
|
||||
const std::string stResult = __Post(stHost, iPort, stBody);
|
||||
{
|
||||
@@ -183,7 +231,7 @@ PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs)
|
||||
gs_strRegisterResult = stResult;
|
||||
}
|
||||
gs_iRegisterState = REGISTER_DONE;
|
||||
}).detach();
|
||||
});
|
||||
return Py_BuildValue("i", 1);
|
||||
}
|
||||
|
||||
@@ -196,3 +244,22 @@ PyObject* netGetRegisterAccountResult(PyObject* poSelf, PyObject* poArgs)
|
||||
std::lock_guard<std::mutex> kLock(gs_kRegisterMutex);
|
||||
return Py_BuildValue("s", gs_strRegisterResult.c_str());
|
||||
}
|
||||
|
||||
// PORT: cancellation interrupts both route preparation and HTTP I/O; the worker owns close().
|
||||
void CancelAccountRegistration()
|
||||
{
|
||||
gs_registerCancelled = true;
|
||||
std::lock_guard<std::mutex> lock(gs_registerSocketMutex);
|
||||
if (gs_registerSocket >= 0) ::shutdown(gs_registerSocket,SHUT_RDWR);
|
||||
}
|
||||
void StopAccountRegistration()
|
||||
{
|
||||
CancelAccountRegistration();
|
||||
if (gs_registerWorker.joinable()) gs_registerWorker.join();
|
||||
gs_iRegisterState = REGISTER_IDLE;
|
||||
}
|
||||
PyObject* netCancelRegisterAccount(PyObject*,PyObject*)
|
||||
{
|
||||
CancelAccountRegistration();
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#include "StdAfx.h"
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
#include "transport.h" // PORT: cancel only this login's pending mesh transports.
|
||||
#endif
|
||||
#include "PythonNetworkStream.h"
|
||||
//#include "PythonNetworkDatagram.h"
|
||||
#include "AccountConnector.h"
|
||||
@@ -14,6 +17,7 @@ std::list<std::string> g_kList_strCommand;
|
||||
// PORT: PythonAccountRegister.cpp
|
||||
PyObject* netRegisterAccount(PyObject* poSelf, PyObject* poArgs);
|
||||
PyObject* netGetRegisterAccountResult(PyObject* poSelf, PyObject* poArgs);
|
||||
PyObject* netCancelRegisterAccount(PyObject*,PyObject*); // PORT: cancel pending HTTP/mesh work.
|
||||
|
||||
PyObject* netGetBettingGuildWarValue(PyObject* poSelf, PyObject* poArgs)
|
||||
{
|
||||
@@ -1014,6 +1018,22 @@ PyObject* netLogOutGame(PyObject* poSelf, PyObject* poArgs)
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
PyObject* netCancelPendingLogin(PyObject*,PyObject*)
|
||||
{
|
||||
bool cancelled = false;
|
||||
auto& account = CAccountConnector::Instance();
|
||||
auto& game = CPythonNetworkStream::Instance();
|
||||
if (mt::meshport::pending_owner(static_cast<CNetworkStream*>(&account))) {
|
||||
account.Disconnect(); cancelled = true;
|
||||
}
|
||||
if (mt::meshport::pending_owner(static_cast<CNetworkStream*>(&game))) {
|
||||
game.Disconnect(); cancelled = true;
|
||||
}
|
||||
return PyBool_FromLong(cancelled);
|
||||
}
|
||||
#endif
|
||||
|
||||
PyObject* netDisconnect(PyObject* poSelf, PyObject* poArgs)
|
||||
{
|
||||
CPythonNetworkStream& rkNetStream=CPythonNetworkStream::Instance();
|
||||
@@ -1774,6 +1794,10 @@ void initnet()
|
||||
{ "SendChangeNamePacket", netSendChangeNamePacket, METH_VARARGS },
|
||||
{ "SendCreateCharacterPacket", netSendCreateCharacterPacket, METH_VARARGS },
|
||||
{ "RegisterAccount", netRegisterAccount, METH_VARARGS },
|
||||
{ "CancelRegisterAccount", netCancelRegisterAccount, METH_NOARGS },
|
||||
#ifdef MT_HAS_MESHPORT
|
||||
{ "CancelPendingLogin", netCancelPendingLogin, METH_NOARGS },
|
||||
#endif
|
||||
{ "GetRegisterAccountResult", netGetRegisterAccountResult, METH_VARARGS },
|
||||
{ "SendDestroyCharacterPacket", netSendDestroyCharacterPacket, METH_VARARGS },
|
||||
{ "SendEnterGamePacket", netSendEnterGamePacket, METH_VARARGS },
|
||||
|
||||
@@ -113,6 +113,10 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
// PORT: AVA2 effect_level (0 all, 1 hide players/NPCs, 2 hide monsters/NPCs, 3 hide others, 4 hide all).
|
||||
int GetEffectLevel() { return m_iPortEffectLevel; }
|
||||
void SetEffectLevel(int iLevel) { m_iPortEffectLevel = iLevel < 0 || iLevel > 4 ? 0 : iLevel; }
|
||||
int GetShopNamesRange() { return m_iPortShopRange; }
|
||||
void SetShopNamesRange(int index) { m_iPortShopRange = index < 0 || index > 4 ? 0 : index; }
|
||||
bool GetShopNameStatus() { return m_bPortNPCNames; }
|
||||
void SetShopNameStatus(bool shown) { m_bPortNPCNames = shown; }
|
||||
bool IsUseDefaultIME();
|
||||
bool IsNoSoundCard();
|
||||
bool IsAutoTiling();
|
||||
@@ -163,4 +167,6 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
PyObject * m_poInterfaceHandler;
|
||||
TWindowStatus m_WindowStatus[WINDOW_MAX_NUM];
|
||||
int m_iPortEffectLevel = 0;
|
||||
};
|
||||
int m_iPortShopRange = 0;
|
||||
bool m_bPortNPCNames = true;
|
||||
};
|
||||
|
||||
@@ -227,6 +227,29 @@ PyObject * systemGetEffectLevel(PyObject * poSelf, PyObject * poArgs)
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetEffectLevel());
|
||||
}
|
||||
|
||||
PyObject* systemSetShopNamesRange(PyObject*, PyObject* args)
|
||||
{
|
||||
int index;
|
||||
if (!PyTuple_GetInteger(args, 0, &index)) return Py_BadArgument();
|
||||
CPythonSystem::Instance().SetShopNamesRange(index);
|
||||
return Py_BuildNone();
|
||||
}
|
||||
PyObject* systemGetShopNamesRange(PyObject*, PyObject*)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetShopNamesRange());
|
||||
}
|
||||
PyObject* systemSetShopNameStatus(PyObject*, PyObject* args)
|
||||
{
|
||||
int shown;
|
||||
if (!PyTuple_GetInteger(args, 0, &shown)) return Py_BadArgument();
|
||||
CPythonSystem::Instance().SetShopNameStatus(shown != 0);
|
||||
return Py_BuildNone();
|
||||
}
|
||||
PyObject* systemGetShopNameStatus(PyObject*, PyObject*)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetShopNameStatus());
|
||||
}
|
||||
|
||||
PyObject * systemIsAlwaysShowName(PyObject * poSelf, PyObject * poArgs)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName());
|
||||
@@ -440,6 +463,10 @@ void initsystem()
|
||||
{ "IsShowSalesText", systemIsShowSalesText, METH_VARARGS },
|
||||
{ "SetEffectLevel", systemSetEffectLevel, METH_VARARGS }, // PORT: AVA2
|
||||
{ "GetEffectLevel", systemGetEffectLevel, METH_VARARGS },
|
||||
{ "SetShopNamesRange", systemSetShopNamesRange, METH_VARARGS },
|
||||
{ "GetShopNamesRange", systemGetShopNamesRange, METH_VARARGS },
|
||||
{ "SetShopNameStatus", systemSetShopNameStatus, METH_VARARGS },
|
||||
{ "GetShopNameStatus", systemGetShopNameStatus, METH_VARARGS },
|
||||
|
||||
{ "GetShadowLevel", systemGetShadowLevel, METH_VARARGS },
|
||||
{ "SetShadowLevel", systemSetShadowLevel, METH_VARARGS },
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include "resource.h"
|
||||
#include "PythonTextTail.h"
|
||||
#include "PythonCharacterManager.h"
|
||||
#include "PythonSystem.h"
|
||||
#include "PythonGuild.h"
|
||||
#include "Locale.h"
|
||||
#include "MarkManager.h"
|
||||
@@ -463,6 +464,11 @@ void CPythonTextTail::ShowCharacterTextTail(DWORD VirtualID)
|
||||
|
||||
if (pInstance->IsGuildWall())
|
||||
return;
|
||||
if (!pInstance->PORT_IsDisplayVisible())
|
||||
return;
|
||||
if (pInstance->IsNPC() && (pInstance->GetRace() < 30000 || pInstance->GetRace() > 30020) &&
|
||||
!CPythonSystem::Instance().GetShopNameStatus())
|
||||
return;
|
||||
|
||||
if (pInstance->CanPickInstance())
|
||||
m_CharacterTextTailList.push_back(pTextTail);
|
||||
|
||||
Reference in New Issue
Block a user