-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Initial concepts of type safe API #2
Open
0x7CFE
wants to merge
31
commits into
master
Choose a base branch
from
bwapi-c
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
34167a7
Adds draft implementation of the BwString wrapper
0x7CFE 6fbf0f0
Initial concept of lifetime-safe iterator wrappers
0x7CFE ac6887c
Fixes lifetimes of BwIterator
0x7CFE b3cc14c
Fixes identifiers to reflect changes in bwapi-c
0x7CFE a70ad92
Minor fixes
0x7CFE 67858c6
Adds prototype implementation of AIModule
0x7CFE 4e046a5
Adds handler wrappers, fixes link issues
0x7CFE e65c6fa
Adds more handler wrappers
0x7CFE b134f03
Adds UnitType, basic unit methods, HasPosition
0x7CFE b872ca2
Adds more methods, polymorphism to Unit::right_click()
0x7CFE ebd89c4
Renames methods according to Rust convention
0x7CFE 5f4b7f1
Adds Region, more Game methods
0x7CFE 867fa16
Refactors AIHandler to game::EventHandler, fixes imports
0x7CFE 52cf040
Adds prototype of session lifetimes
0x7CFE b9e0a79
Adds .cargo/config
kpp 36c17e0
Ports to bwapi-sys
kpp 06a052a
Adds examples
kpp 8337400
Adds implementation for position
kpp a964f63
Fixes tests
kpp 45ba8e5
Implements on_nuke_detect
kpp c677da8
Fixes Region::center
kpp 9ff5fce
Fixes unused import + variable
kpp e3b4c2c
Reintroduces lifetime 'g as global invariant
0x7CFE 6d5c26c
Adds handler factory stuff
0x7CFE 48a7065
Fixes game singleton and events
0x7CFE bbfbdb6
Refactors code to reflect new API
0x7CFE 4a0596f
Adds handler startup and shutdown
0x7CFE ec8c266
Add Game::average_fps
kpp 6dcb93a
Uses bwapi-sys from crates.io
kpp 85d099b
Updates TravisCI config to use g++-7
kpp 0ff36e6
Fixes tests for Position
kpp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,159 @@ | ||
|
||
use bwapi_sys::bridge as sys; | ||
use unit::Unit; | ||
use player::Player; | ||
use iterator::FromRaw; | ||
|
||
use std::ptr; | ||
use std::mem; | ||
use std::ffi::CStr; | ||
use std::os::raw::c_void as void; | ||
|
||
pub trait AIHandler { | ||
fn on_start(&self); | ||
fn on_end(&mut self, isWinner: bool); | ||
fn on_frame(&mut self); | ||
fn on_send_text(&mut self, text: &str); | ||
fn on_receive_text(&mut self, player: &mut Player, text: &str); | ||
fn on_player_left(&mut self, player: &mut Player); | ||
// TODO fn on_nuke_detect(&mut self, target: Position); | ||
fn on_unit_discover(&mut self, unit: &mut Unit); | ||
fn on_unit_evade(&mut self, unit: &mut Unit); | ||
fn on_unit_show(&mut self, unit: &mut Unit); | ||
fn on_unit_hide(&mut self, unit: &mut Unit); | ||
fn on_unit_create(&mut self, unit: &mut Unit); | ||
fn on_unit_destroy(&mut self, unit: &mut Unit); | ||
fn on_unit_morph(&mut self, unit: &mut Unit); | ||
fn on_unit_renegade(&mut self, unit: &mut Unit); | ||
fn on_save_game(&mut self, game_name: &str); | ||
fn on_unit_complete(&mut self, unit: &mut Unit); | ||
} | ||
|
||
#[repr(C)] | ||
pub struct AIModule { | ||
vtable: Box<sys::AIModule_vtable>, | ||
handler: Box<AIHandler>, | ||
} | ||
|
||
impl AIModule { | ||
pub fn new(handler: Box<AIHandler>) -> AIModule { | ||
AIModule { | ||
vtable: Box::new(sys::AIModule_vtable { | ||
onStart: Some(AIModule::on_start), | ||
onEnd: Some(AIModule::on_end), | ||
onFrame: Some(AIModule::on_frame), | ||
onSendText: Some(AIModule::on_send_text), | ||
onReceiveText: Some(AIModule::on_receive_text), | ||
onPlayerLeft: Some(AIModule::on_player_left), | ||
onNukeDetect: Some(AIModule::on_nuke_detect), | ||
onUnitDiscover: Some(AIModule::on_unit_discover), | ||
onUnitEvade: Some(AIModule::on_unit_evade), | ||
onUnitShow: Some(AIModule::on_unit_show), | ||
onUnitHide: Some(AIModule::on_unit_hide), | ||
onUnitCreate: Some(AIModule::on_unit_create), | ||
onUnitDestroy: Some(AIModule::on_unit_destroy), | ||
onUnitMorph: Some(AIModule::on_unit_morph), | ||
onUnitRenegade: Some(AIModule::on_unit_renegade), | ||
onSaveGame: Some(AIModule::on_save_game), | ||
onUnitComplete: Some(AIModule::on_unit_complete), | ||
}), | ||
|
||
handler | ||
} | ||
} | ||
|
||
unsafe fn get_handler<'a>(sys_module: *mut sys::AIModule) -> &'a mut AIHandler { | ||
let module = sys_module as *mut AIModule; | ||
&mut * (*module).handler | ||
} | ||
|
||
unsafe extern fn on_start(sys_module: *mut sys::AIModule) { | ||
Self::get_handler(sys_module).on_start(); | ||
} | ||
|
||
unsafe extern fn on_end(sys_module: *mut sys::AIModule, is_winner: bool) { | ||
Self::get_handler(sys_module).on_end(is_winner); | ||
} | ||
|
||
unsafe extern fn on_frame(sys_module: *mut sys::AIModule) { | ||
Self::get_handler(sys_module).on_frame(); | ||
} | ||
|
||
unsafe extern fn on_send_text(sys_module: *mut sys::AIModule, text: *const ::std::os::raw::c_char) { | ||
let text = CStr::from_ptr(text).to_str().unwrap(); | ||
Self::get_handler(sys_module).on_send_text(&text); | ||
} | ||
|
||
unsafe extern fn on_receive_text(sys_module: *mut sys::AIModule, player: *mut sys::Player, text: *const ::std::os::raw::c_char) { | ||
let mut player = Player::from_raw(player as *mut void); | ||
let text = CStr::from_ptr(text).to_str().unwrap(); | ||
Self::get_handler(sys_module).on_receive_text(&mut player, &text); | ||
} | ||
|
||
unsafe extern fn on_player_left(sys_module: *mut sys::AIModule, player: *mut sys::Player) { | ||
let mut player = Player::from_raw(player as *mut void); | ||
Self::get_handler(sys_module).on_player_left(&mut player); | ||
} | ||
|
||
unsafe extern fn on_nuke_detect(sys_module: *mut sys::AIModule, target: sys::Position) { | ||
// TODO | ||
} | ||
|
||
unsafe extern fn on_unit_discover(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_discover(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_evade(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_evade(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_show(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_show(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_hide(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_hide(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_create(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_create(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_destroy(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_destroy(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_morph(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_morph(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_unit_renegade(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_renegade(&mut unit); | ||
} | ||
|
||
unsafe extern fn on_save_game(sys_module: *mut sys::AIModule, game_name: *const ::std::os::raw::c_char) { | ||
let game_name = CStr::from_ptr(game_name).to_str().unwrap(); | ||
Self::get_handler(sys_module).on_save_game(game_name); | ||
} | ||
|
||
unsafe extern fn on_unit_complete(sys_module: *mut sys::AIModule, unit: *mut sys::Unit) { | ||
let mut unit = Unit::from_raw(unit as *mut void); | ||
Self::get_handler(sys_module).on_unit_complete(&mut unit); | ||
} | ||
|
||
} | ||
|
||
pub unsafe fn wrap_handler(handler: Box<AIHandler>) -> *mut ::std::os::raw::c_void { | ||
let module = Box::new(AIModule::new(handler)); | ||
let module_ptr = Box::into_raw(module) as *mut sys::AIModule; | ||
|
||
sys::createAIModuleWrapper(module_ptr) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
|
||
use bwapi_sys::bridge as sys; | ||
use std::ffi::{CString, CStr}; | ||
use iterator::{BwIterator, FromRaw}; | ||
|
||
use unit::Unit; | ||
use player::*; | ||
|
||
use std::os::raw::c_void as void; | ||
|
||
pub struct Game(*mut sys::Game); | ||
|
||
impl FromRaw for Game { | ||
unsafe fn from_raw(raw: *mut void) -> Game { | ||
assert!(!raw.is_null()); | ||
Game(raw as *mut sys::Game) | ||
} | ||
} | ||
|
||
pub enum CoordinateType { | ||
None = 0, | ||
Screen = 1, | ||
Map = 2, | ||
Mouse = 3 | ||
} | ||
|
||
impl Game { | ||
pub fn send_text(&self, text: &str) { | ||
unsafe { | ||
let data = CString::new(text).unwrap(); | ||
sys::Game_sendText(self.0, data.as_ptr()); | ||
} | ||
} | ||
|
||
pub fn get_frame_count(&self) -> i32 { | ||
unsafe { | ||
sys::Game_getFrameCount(self.0) | ||
} | ||
} | ||
|
||
pub fn draw_text(&self, ctype: CoordinateType, coords: (i32, i32), text: &str) { | ||
unsafe { | ||
let data = CString::new(text).unwrap(); | ||
let ctype = sys::CoordinateType{ id: ctype as i32 }; | ||
sys::Game_drawText(self.0, ctype, coords.0, coords.1, data.as_ptr()); | ||
} | ||
} | ||
|
||
pub fn get_self(&self) -> Player { | ||
unsafe { | ||
Player::from_raw(sys::Game_self(self.0) as *mut void) | ||
} | ||
} | ||
|
||
pub fn get_minerals(&self) -> Box<Iterator<Item=Unit>> { | ||
unsafe { | ||
let iter = sys::Game_getMinerals(self.0) as *mut sys::Iterator; | ||
Box::new(BwIterator::from(iter)) | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
|
||
use bwapi_sys::bridge as sys; | ||
use std::marker::PhantomData; | ||
use std::os::raw::c_void as void; | ||
|
||
/// `FromRaw` is a trait for entities that | ||
/// are typically created outside of Rust code. | ||
/// TODO Move to a proper place | ||
pub trait FromRaw { | ||
/// Construct entity from raw data. Unsafe. | ||
/// Please be 100% sure that you pass correct pointer. | ||
unsafe fn from_raw(raw: *mut void) -> Self; | ||
} | ||
|
||
/// Iterator is a wrapper over API iterator. | ||
/// To ensure safety it's lifetime is bound | ||
/// to the lifetime of the referenced data. | ||
pub struct BwIterator<'i, 'g: 'i, T: FromRaw + 'g> { | ||
raw: &'i mut sys::Iterator, | ||
phantom: PhantomData<&'g T>, | ||
} | ||
|
||
impl<'i, 'g: 'i, T: FromRaw + 'g> BwIterator<'i, 'g, T> { | ||
pub unsafe fn from(raw: *mut sys::Iterator) -> BwIterator<'i, 'g, T> { | ||
assert!(!raw.is_null()); | ||
BwIterator { raw: &mut *raw, phantom: PhantomData } | ||
} | ||
} | ||
|
||
impl<'i,'g: 'i, T: FromRaw + 'g> Iterator for BwIterator<'i, 'g, T> { | ||
type Item = T; | ||
|
||
fn next(&mut self) -> Option<Self::Item> { | ||
unsafe { | ||
if sys::Iterator_valid(self.raw) { | ||
let item = sys::Iterator_get(self.raw); | ||
sys::Iterator_next(self.raw); | ||
|
||
Some(T::from_raw(item)) | ||
} else { | ||
None | ||
} | ||
} | ||
} | ||
} | ||
|
||
impl<'i, 'g: 'i, T: FromRaw + 'g> Drop for BwIterator<'i, 'g, T> { | ||
fn drop(&mut self) { | ||
unsafe { | ||
sys::Iterator_release(self.raw); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
|
||
use bwapi_sys::bridge as sys; | ||
use string::BwString; | ||
use iterator::{BwIterator, FromRaw}; | ||
use std::os::raw::c_void as void; | ||
use unit::Unit; | ||
|
||
pub struct Player(*mut sys::Player); | ||
|
||
impl FromRaw for Player { | ||
unsafe fn from_raw(raw: *mut void) -> Player { | ||
assert!(!raw.is_null()); | ||
Player(raw as *mut sys::Player) | ||
} | ||
} | ||
|
||
impl Player { | ||
pub fn get_name(&self) -> BwString { | ||
unsafe { | ||
let name = sys::Player_getName(self.0); | ||
BwString::from_raw(name as *mut void) | ||
} | ||
} | ||
|
||
pub fn get_units(&self) -> Box<Iterator<Item=Unit>> { | ||
unsafe { | ||
let iter = sys::Player_getUnits(self.0) as *mut sys::Iterator; | ||
Box::new(BwIterator::from(iter)) | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Зачем BwString?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пока не могу внятно ответить, разбираюсь с интерфейсами и пытаюсь осознать, какие контракты нам будут нужны.
Если сходу конвертировать в String будет еще одна аллокация. Вообще можно использовать OsString который является промежуточным звеном между сырыми строками и строками Rust, и может быть дешево преобразован в обе стороны при условии, что внутри лежит UTF-8.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Дим, наверно пофиг на доп аллокацию? get_name не должны спрашивать чаще 16 раз за такт
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не то что бы это было критично. Просто зачем?
Я реализовал
Deref<Target=str>
иAsRef<str>
для этого типа, то есть его можно спокойно подставлять в те функции, где ожидается&str
. Если же потребуется владение, то илиx.to_owned()
илиString::from(x)
.