remove BWAPI3 support

This commit is contained in:
Gered 2017-04-11 10:48:21 -04:00
parent bf0cd16696
commit c106d4b22b
102 changed files with 116 additions and 1242 deletions

View file

@ -31,20 +31,29 @@ import java.util.*;
@SuppressWarnings("ConstantConditions")
public class CJavaPipeline {
public static final int BWAPI_V3 = 3;
public static final int BWAPI_V4 = 4;
public static int BWAPI_VERSION = BWAPI_V4;
/**
* Classes from BWAPI 4 that don't need mirroring
* Not used in mirroring BWAPI 3
*/
private static final List<String> ignoredClasses = new ArrayList<>(Arrays.asList("Client", "Vectorset", "ConstVectorset", "VSetIterator", "GameWrapper",
"Interface", "RectangleArray", "UnitImpl", "PlayerImpl", "GameImpl", "BulletImpl", "ForceImpl", "TournamentModule", "RegionImpl", "SetContainer", "InterfaceEvent", "PositionOrUnit", "Point"));
private static final List<String> ignoredClasses = new ArrayList<>(Arrays.asList(
"Client",
"Vectorset",
"ConstVectorset",
"VSetIterator",
"GameWrapper",
"Interface",
"RectangleArray",
"UnitImpl",
"PlayerImpl",
"GameImpl",
"BulletImpl",
"ForceImpl",
"TournamentModule",
"RegionImpl",
"SetContainer",
"InterfaceEvent",
"PositionOrUnit",
"Point"
));
private static final HashMap<String, String> superClasses = new HashMap<>();
@ -303,53 +312,27 @@ public class CJavaPipeline {
System.out.println();
try {
if (BWAPI_VERSION == BWAPI_V3) {
ignoredClasses.add("Position");
PackageProcessOptions bwapiOptions = new PackageProcessOptions();
bwapiOptions.packageName = "bwapi";
bwapiOptions.cHeadersDir = new File(basePath.getPath() + "/bwapi-master");
bwapiOptions.manualCopyClassesDir = new File(basePath.getPath() + "/manual-bwapi");
PackageProcessOptions bwapiOptions = new PackageProcessOptions();
bwapiOptions.packageName = "bwapi";
bwapiOptions.cHeadersDir = new File(basePath.getPath() + "/bwapi-includes");
bwapiOptions.manualCopyClassesDir = new File(basePath.getPath() + "/manual-bwapi");
PackageProcessOptions bwtaOptions = new PackageProcessOptions();
bwtaOptions.packageName = "bwta";
bwtaOptions.cHeadersDir = new File(basePath.getPath() + "/bwta-c");
bwtaOptions.additionalImportClasses = Arrays.asList("bwapi.Position", "bwapi.TilePosition", "bwapi.Player");
bwtaOptions.globalClassName = "BWTA";
PackageProcessOptions bwtaOptions = new PackageProcessOptions();
bwtaOptions.packageName = "bwta";
bwtaOptions.cHeadersDir = new File(basePath.getPath() + "/bwta2-c");
bwtaOptions.additionalImportClasses = Arrays.asList("bwapi.Position", "bwapi.TilePosition", "bwapi.Player", "bwapi.Unit", "bwapi.Pair");
bwtaOptions.globalClassName = "BWTA";
Properties props = new Properties();
props.put(COMPILE_DIR_PROPERTY, basePath.getPath() + "/output/compiled");
props.put(HEADERS_DIR_PROPERTY, basePath.getPath() + "/output/headers");
props.put(HEADER_FILE_PROPERTY, basePath.getPath() + "/output/concat_header.h");
props.put(C_IMPLEMENTATION_FILE_PROPERTY, basePath.getPath() + "/output/c/impl.cpp");
props.put(GENERATE_TO_DIR, basePath.getPath() + "/output");
Properties props = new Properties();
props.put(COMPILE_DIR_PROPERTY, basePath.getPath() + "/output/compiled");
props.put(HEADERS_DIR_PROPERTY, basePath.getPath() + "/output/headers");
props.put(HEADER_FILE_PROPERTY, basePath.getPath() + "/output/concat_header.h");
props.put(C_IMPLEMENTATION_FILE_PROPERTY, basePath.getPath() + "/output/c/impl.cpp");
props.put(GENERATE_TO_DIR, basePath.getPath() + "/output/generated");
new CJavaPipeline().run(new PackageProcessOptions[]{bwapiOptions, bwtaOptions}, props);
}
if (BWAPI_VERSION == BWAPI_V4) {
ignoredClasses.add("Position");
PackageProcessOptions bwapiOptions = new PackageProcessOptions();
bwapiOptions.packageName = "bwapi";
bwapiOptions.cHeadersDir = new File(basePath.getPath() + "/bwapi4-includes");
bwapiOptions.manualCopyClassesDir = new File(basePath.getPath() + "/manual-bwapi4");
PackageProcessOptions bwtaOptions = new PackageProcessOptions();
bwtaOptions.packageName = "bwta";
bwtaOptions.cHeadersDir = new File(basePath.getPath() + "/bwta2-c");
bwtaOptions.additionalImportClasses = Arrays.asList("bwapi.Position", "bwapi.TilePosition", "bwapi.Player", "bwapi.Unit", "bwapi.Pair");
bwtaOptions.globalClassName = "BWTA";
Properties props = new Properties();
props.put(COMPILE_DIR_PROPERTY, basePath.getPath() + "/output/compiled4");
props.put(HEADERS_DIR_PROPERTY, basePath.getPath() + "/output/headers4");
props.put(HEADER_FILE_PROPERTY, basePath.getPath() + "/output/concat_header4.h");
props.put(C_IMPLEMENTATION_FILE_PROPERTY, basePath.getPath() + "/output/c4/impl.cpp");
props.put(GENERATE_TO_DIR, basePath.getPath() + "/output/generated");
new CJavaPipeline().run(new PackageProcessOptions[]{bwapiOptions, bwtaOptions}, props);
}
new CJavaPipeline().run(new PackageProcessOptions[]{bwapiOptions, bwtaOptions}, props);
} catch (Exception ex) {
ex.printStackTrace();
}
@ -360,9 +343,4 @@ public class CJavaPipeline {
private static final String C_IMPLEMENTATION_FILE_PROPERTY = "impl_file";
private static final String HEADER_FILE_PROPERTY = "header_file";
private static final String GENERATE_TO_DIR = "generate_to_dir";
public static boolean isBWAPI3() {
return BWAPI_VERSION == BWAPI_V3;
}
}

View file

@ -212,13 +212,6 @@ public class JavaContext {
return implementCopyReturn(javaType, "cresult");
}
public static String checkBWAPI3brackets() {
if (CJavaPipeline.isBWAPI3()) {
return "()";
}
return "";
}
public String implementCopyReturn(String javaType, String fieldName) {
switch (javaType) {
case "Integer":
@ -237,8 +230,8 @@ public class JavaContext {
case "Position":
case "WalkPosition":
case "Point":
return ", " + fieldName + ".x" + checkBWAPI3brackets() +
", " + fieldName + ".y" + checkBWAPI3brackets();
return ", " + fieldName + ".x" +
", " + fieldName + ".y";
case "Color":
return ", " + fieldName + ".red()" +
", " + fieldName + ".green()" +

View file

@ -4,15 +4,12 @@ import bwmirror.c.CClass;
import bwmirror.c.CDeclaration;
import bwmirror.c.DeclarationType;
import bwmirror.c.Field;
import bwmirror.generator.CJavaPipeline;
import bwmirror.generator.JavaContext;
import bwmirror.impl.ClassVariable;
import java.io.PrintStream;
import java.util.List;
import static bwmirror.generator.JavaContext.checkBWAPI3brackets;
/**
* User: PC
* Date: 18. 6. 2014
@ -33,38 +30,17 @@ public class Bind {
this.context = context;
}
private void implementBWAPIInit() {
out.println("println(\"Attempting to init BWAPI...\");");
out.println("\t\tBWAPI_init();");
out.println("\t\tprintln(\"BWAPI ready.\");");
}
private void implementConnectionRoutine() {
if (CJavaPipeline.isBWAPI3()) {
out.println(" if (Broodwar != NULL) {\n" +
"\t\t\t\tprintln(\"Waiting...\");\n" +
" while (!Broodwar->isInGame()) {\n" +
" BWAPIClient.update();\n" +
"\t\t\t\t\tif (Broodwar == NULL) {\n" +
" println(\"Match ended.\");\n" +
" return;\n" +
" }\n" +
" }\n" +
" }\n" +
"\n");
} else {
out.println("\t\t\t\tprintln(\"Waiting...\");\n" +
"while ( !Broodwar->isInGame() )\n" +
" {\n" +
" BWAPI::BWAPIClient.update();\n" +
" if (!BWAPI::BWAPIClient.isConnected())\n" +
" {\n" +
" println(\"Reconnecting...\");\n" +
" reconnect();\n" +
" }\n" +
" }");
}
out.println("\t\t\t\tprintln(\"Waiting...\");\n" +
"while ( !Broodwar->isInGame() )\n" +
" {\n" +
" BWAPI::BWAPIClient.update();\n" +
" if (!BWAPI::BWAPIClient.isConnected())\n" +
" {\n" +
" println(\"Reconnecting...\");\n" +
" reconnect();\n" +
" }\n" +
" }");
}
@ -81,7 +57,7 @@ public class Bind {
"\t\tjobject moduleObj = env->GetObjectField(obj, env->GetFieldID(cls, \"module\", \"L" + context.getPackageName() + "/AIModule;\"));\n" +
"\t\tjclass moduleCls = env->GetObjectClass(moduleObj);\n" +
"\t\tenv->SetObjectField(obj, env->GetFieldID(cls, \"game\", \"L" + context.getPackageName() + "/Game;\"), " +
"env->CallStaticObjectMethod(gamecls, env->GetStaticMethodID(gamecls, \"get\", \"(J)L" + context.getPackageName() + "/Game;\"), (long)Broodwar" + (CJavaPipeline.isBWAPI3() ? "" : "Ptr")+"));\n" +
"env->CallStaticObjectMethod(gamecls, env->GetStaticMethodID(gamecls, \"get\", \"(J)L" + context.getPackageName() + "/Game;\"), (long)BroodwarPtr));\n" +
"\n" +
"\t\tjmethodID updateMethodID = env->GetMethodID(env->GetObjectClass(obj), \"update\", \"()V\");");
@ -117,12 +93,6 @@ public class Bind {
"\t\t\t\t\t switch (it->getType()) {\n" +
"\t\t\t\t\t\t case EventType::MatchStart:\n" +
(CJavaPipeline.isBWAPI3() ?
"\t\t\t\t\t\t\t BWTA::BWTA_Result::regions.clear();\n" +
"\t\t\t\t\t\t\t BWTA::BWTA_Result::baselocations.clear();\n" +
"\t\t\t\t\t\t\t BWTA::BWTA_Result::startlocations.clear();\n" +
"\t\t\t\t\t\t\t BWTA::BWTA_Result::chokepoints.clear();\n" +
"\t\t\t\t\t\t\t BWTA::BWTA_Result::unwalkablePolygons.clear();\n" : "") +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, matchStartCallback);\n" +
"\t\t\t\t\t\t break;\n" +
"\t\t\t\t\t\t case EventType::MatchEnd:\n" +
@ -141,7 +111,7 @@ public class Bind {
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, playerLeftCallback, env->CallStaticObjectMethod(playerCls, env->GetStaticMethodID(playerCls, \"get\", \"(J)L" + context.getPackageName() + "/Player;\"), (jlong)it->getPlayer()));\n" +
"\t\t\t\t\t\t break;\n" +
"\t\t\t\t\t\t case EventType::NukeDetect:\n" +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, nukeDetectCallback, env->NewObject(posCls, env->GetMethodID(posCls,\"<init>\", \"(II)V\"), it->getPosition().x" + checkBWAPI3brackets() + ", it->getPosition().y" + checkBWAPI3brackets() + "));\n" +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, nukeDetectCallback, env->NewObject(posCls, env->GetMethodID(posCls,\"<init>\", \"(II)V\"), it->getPosition().x, it->getPosition().y));\n" +
"\t\t\t\t\t\t break;\n" +
"\t\t\t\t\t\t case EventType::UnitDiscover:\n" +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, unitDiscoverCallback, env->CallStaticObjectMethod(unitCls, env->GetStaticMethodID(unitCls, \"get\", \"(J)L" + context.getPackageName() + "/Unit;\"), (jlong)it->getUnit()));\n" +
@ -173,11 +143,6 @@ public class Bind {
"\t\t\t\t\t\t case EventType::UnitComplete:\n" +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, unitCompleteCallback, env->CallStaticObjectMethod(unitCls, env->GetStaticMethodID(unitCls, \"get\", \"(J)L" + context.getPackageName() + "/Unit;\"), (jlong)it->getUnit()));\n" +
"\t\t\t\t\t\t break;\n" +
(CJavaPipeline.isBWAPI3() ?
"\t\t\t\t\t\t case EventType::PlayerDropped:\n" +
"\t\t\t\t\t\t\t env->CallVoidMethod(moduleObj, playerDroppedCallback, env->CallStaticObjectMethod(playerCls, env->GetStaticMethodID(playerCls, \"get\", \"(J)L" + context.getPackageName() + "/Player;\")));\n" +
"\t\t\t\t\t\t break;\n"
: "") +
"\n" +
"\t\t\t\t\t }\n" +
"\t\t\t\t }");
@ -188,30 +153,19 @@ public class Bind {
"\t\t\t\t\t\treconnect();\n" +
"\t\t\t\t}\n" +
"\t\t\t}\n" +
(CJavaPipeline.isBWAPI3() ? "" : "println(\"Match ended.\");") +
"println(\"Match ended.\");" +
"\t\t}");
}
private void implementHelpers() {
if (CJavaPipeline.isBWAPI3()) {
out.println("void reconnect()\n" +
"{\n" +
"\twhile (!BWAPIClient.connect()) {\n" +
" Sleep(1000);\n" +
" }\n" +
"}\n" +
"\n" +
"\n");
} else {
out.println("void reconnect()\n" +
"{\n" +
"\twhile (!BWAPIClient.connect()) {\n" +
" std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });\n" +
" }\n" +
"}\n" +
"\n" +
"\n");
}
out.println("void reconnect()\n" +
"{\n" +
"\twhile (!BWAPIClient.connect()) {\n" +
" std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });\n" +
" }\n" +
"}\n" +
"\n" +
"\n");
out.println(
"void flushPrint(const char * text){\n" +
@ -229,9 +183,6 @@ public class Bind {
private void implementMirrorInit(List<CDeclaration> declarationList) {
implementHelpers();
out.println("JNIEXPORT void JNICALL Java_" + context.getPackageName() + "_Mirror_startGame(JNIEnv * env, jobject obj){");
if (CJavaPipeline.isBWAPI3()) {
implementBWAPIInit();
}
implementVariablesBind(declarationList);
implementGameStart();
out.println("}");

View file

@ -1,7 +1,6 @@
package bwmirror.generator.ccalls;
import bwmirror.c.Param;
import bwmirror.generator.CJavaPipeline;
import bwmirror.generator.JavaContext;
import bwmirror.util.Generic;
import bwmirror.util.PointerTest;
@ -52,14 +51,14 @@ public class CallImplementer {
public void setOut(PrintStream out) {
this.out = out;
out.print("#include \"../concat_header" + (CJavaPipeline.isBWAPI3() ? "" : "4") + ".h\"\n" +
out.print("#include \"../concat_header.h\"\n" +
"#include <BWAPI.h>\n" +
"#include <BWAPI/Client.h>\n" +
"#include <BWTA.h>\n" +
(CJavaPipeline.isBWAPI3() ? "" : "#include <thread>\n" + "#include <chrono>\n") +
"#include <thread>\n" +
"#include <chrono>\n" +
"#include <jni.h>\n" +
"#include <cstring>\n" +
(CJavaPipeline.isBWAPI3() ? "#include \"../BWTA_Result.h\"" : "") +
"\n" +
"using namespace BWAPI;\n\n");
}
@ -85,7 +84,7 @@ public class CallImplementer {
if (javaContext.isCollection(param.third)) {
String genericType = Generic.extractGeneric(param.third);
if (CJavaPipeline.isBWAPI3() || javaContext.isValueType(genericType)) {
if (javaContext.isValueType(genericType)) {
out.println("std::set<" + PointerTest.test(genericType) + "> " + param.second + SEMICOLON);
} else {
out.println(genericType + "set " + param.second + SEMICOLON);
@ -186,7 +185,7 @@ public class CallImplementer {
private String wrapInCCollection(String genericType, String javaMethodName) {
String buffer = "";
boolean isBWAPI4Collection = !CJavaPipeline.isBWAPI3() && !genericType.startsWith("BWTA::");
boolean isBWAPI4Collection = !genericType.startsWith("BWTA::");
if (!isBWAPI4Collection) {
if (javaMethodName.equals("getHoles")) {
buffer += "std::vector<";
@ -207,7 +206,7 @@ public class CallImplementer {
buffer += "set";
}
if (buffer.equals("set") && !CJavaPipeline.isBWAPI3()) {
if (buffer.equals("set")) {
if (javaContext.getPackageName().equals("bwta")) {
return "std::vector<" + genericType + ">";
}

View file

@ -2,9 +2,7 @@ package bwmirror.generator.java;
import bwmirror.c.CClass;
import bwmirror.c.CDeclaration;
import bwmirror.generator.CJavaPipeline;
import bwmirror.generator.MirrorContext;
import bwmirror.javadoc.Crawler;
import bwmirror.javadoc.CrawlerBWAPI4;
import bwmirror.javadoc.Documentation;
import bwmirror.javadoc.DocumentedField;
@ -56,27 +54,14 @@ public abstract class Mirror {
}
} else {
if (field instanceof CClass) {
if (CJavaPipeline.isBWAPI3() /*|| context.getPackage().equals("bwta")*/) {
Crawler cl = new Crawler();
if (context.getPackage().equals("bwta")) {
cl.setBaseUrl("https://code.google.com/p/bwta/wiki/");
}
documentation = cl.request(getDecl().getName());
if (documentation != null) {
printJavadoc(documentation.header);
}
} else {
CrawlerBWAPI4 cl = new CrawlerBWAPI4();
if (context.getPackage().equals("bwta")) {
cl.setBaseUrl("https://code.google.com/p/bwta/wiki/");
}
documentation = cl.request(getDecl().getName());
if (documentation != null) {
printJavadoc(documentation.header);
}
CrawlerBWAPI4 cl = new CrawlerBWAPI4();
if (context.getPackage().equals("bwta")) {
cl.setBaseUrl("https://code.google.com/p/bwta/wiki/");
}
documentation = cl.request(getDecl().getName());
if (documentation != null) {
printJavadoc(documentation.header);
}
}
if (documentation == null) {
return;

View file

@ -1,7 +1,6 @@
package bwmirror.impl;
import bwmirror.c.*;
import bwmirror.generator.CJavaPipeline;
import java.io.BufferedReader;
import java.io.File;
@ -113,14 +112,6 @@ public class CApiParser {
return LineState.END;
}
if(CJavaPipeline.isBWAPI3()) {
if (line.endsWith("Types")) {
return LineState.END;
}
if (line.equals("Races")) {
return LineState.END;
}
}
return LineState.SKIP;
}
@ -256,10 +247,6 @@ public class CApiParser {
System.err.println("function skipped - GameData* return (" + function.name + ")");
return null;
}
if (CJavaPipeline.isBWAPI3() && function.returnType.equals("UnitCommand")) {
System.err.println("function skipped - UnitCommand return (" + function.name + ")");
return null;
}
if (function.returnType.equals("Event")) {
System.err.println("function skipped - Event return (" + function.name + ")");
return null;
@ -513,13 +500,11 @@ public class CApiParser {
}
Clazz clz = new Clazz(clazzName);
if(!CJavaPipeline.isBWAPI3()){
if(clazzName.endsWith("Type") || clazzName.equals("Error") || clazzName.equals("Race") || clazzName.equals("Order")){
Function function = new Function();
function.name = "toString";
function.returnType = "string";
clz.fields.add(function);
}
if(clazzName.endsWith("Type") || clazzName.equals("Error") || clazzName.equals("Race") || clazzName.equals("Order")){
Function function = new Function();
function.name = "toString";
function.returnType = "string";
clz.fields.add(function);
}
if (javadoc != null) {

View file

@ -1,7 +1,5 @@
package bwmirror.util;
import bwmirror.generator.CJavaPipeline;
import java.util.Arrays;
import java.util.List;
@ -24,9 +22,6 @@ public class PointerTest {
public static String test(String cls, boolean print) {
if (CJavaPipeline.isBWAPI3()) {
return (print ? cls : "" )+ "*";
}
return (print ? cls : "" ) + (testCls(cls) ? "*" : "");
}

View file

@ -4,9 +4,9 @@ import bwapi.BWEventListener;
/**
* This class receives all events from Broodwar.
* To process them, receive an AIModule's instance from {@link bwapi.Mirror} and call {@link #setEventListener(BWEventListener)}
* to set you own {@link bwapi.BWEventListener listener}.
* There's also a stub class ({@link bwapi.DefaultBWListener}) provided, so you don't have to implement all of the methods.
* To process them, receive an AIModule's instance from {@link Mirror} and call {@link #setEventListener(bwapi.BWEventListener)}
* to set you own {@link BWEventListener listener}.
* There's also a stub class ({@link DefaultBWListener}) provided, so you don't have to implement all of the methods.
*/
public class AIModule {

View file

@ -18,11 +18,11 @@ public abstract class AbstractPoint<T extends AbstractPoint> {
return getPoint().getY();
}
public double distanceTo(AbstractPoint<T> otherPosition) {
return distanceTo(otherPosition.getX(), otherPosition.getY());
public double getDistance(AbstractPoint<T> otherPosition) {
return getDistance(otherPosition.getX(), otherPosition.getY());
}
public double distanceTo(int x, int y) {
public double getDistance(int x, int y) {
double dx = x - getX();
double dy = y - getY();
return Math.sqrt(dx * dx + dy * dy);

View file

@ -8,7 +8,7 @@ import java.util.Collection;
import java.util.List;
/**
* Implement this interface and call {@link bwapi.AIModule#setEventListener(bwapi.BWEventListener)} to receive all of the in game events.
* Implement this interface and call {@link AIModule#setEventListener(bwapi.BWEventListener)} to receive all of the in game events.
*/
public interface BWEventListener {

View file

@ -6,7 +6,7 @@ import bwapi.Position;
import bwapi.Unit;
/**
* A utility stub class providing a default implementation of {@link bwapi.BWEventListener},
* A utility stub class providing a default implementation of {@link BWEventListener},
* override it's methods if you want to handle only some events.
*/
public class DefaultBWListener implements BWEventListener {

View file

@ -1,100 +0,0 @@
package bwapi;
import java.util.HashMap;
import java.util.Map;
/**
* Functions in BWAPI may set an error code. To retrieve the error code, call Game::getLastError.
*/
public class Error {
private int id;
private Error(int id) {
this.id = id;
}
public static Error Unit_Does_Not_Exist;
public static Error Unit_Not_Visible;
public static Error Unit_Not_Owned;
public static Error Unit_Busy;
public static Error Incompatible_UnitType;
public static Error Incompatible_TechType;
public static Error Incompatible_State;
public static Error Already_Researched;
public static Error Fully_Upgraded;
public static Error Currently_Researching;
public static Error Currently_Upgrading;
public static Error Insufficient_Minerals;
public static Error Insufficient_Gas;
public static Error Insufficient_Supply;
public static Error Insufficient_Energy;
public static Error Insufficient_Tech;
public static Error Insufficient_Ammo;
public static Error Insufficient_Space;
public static Error Invalid_Tile_Position;
public static Error Unbuildable_Location;
public static Error Unreachable_Location;
public static Error Out_Of_Range;
public static Error Unable_To_Hit;
public static Error Access_Denied;
public static Error File_Not_Found;
public static Error Invalid_Parameter;
public static Error None;
public static Error Unknown;
private static Map<Long, Error> instances = new HashMap<Long, Error>();
private Error(long pointer) {
this.pointer = pointer;
}
private static Error get(long pointer) {
Error instance = instances.get(pointer);
if (instance == null) {
instance = new Error(pointer);
instances.put(pointer, instance);
}
return instance;
}
private long pointer;
public String c_str() {
return c_str_native(pointer);
}
public String toString(){
return c_str();
}
private native String c_str_native(long pointer);
}

View file

@ -13,9 +13,9 @@ import java.util.zip.*;
/**
* <p>The API entry point. Standard use case:</p>
* <ul>
* <li>Create a Mirror object and use {@link #getModule()} and then set an {@link bwapi.AIModule}'s {@link bwapi.BWEventListener}<br/>
* <li>Create a Mirror object and use {@link #getModule()} and then set an {@link AIModule}'s {@link BWEventListener}<br/>
* <li>Call {@link #startGame()} to init the API and connect to Broodwar, then launch Broodwar from ChaosLauncher.</li>
* <li>In you {@link bwapi.BWEventListener#onStart()} method, receive the Game object by calling {@link #getGame()}</li>
* <li>In you {@link BWEventListener#onStart()} method, receive the Game object by calling {@link #getGame()}</li>
* </ul>
* <br/>
* <b>Example</b>
@ -56,11 +56,11 @@ public class Mirror {
private static final boolean EXTRACT_JAR = true;
private static final String VERSION = "1_2";
private static final String VERSION = "2_5";
static {
String arch = System.getProperty("os.arch");
String dllNames[] = {"bwapi_bridge" + VERSION, "gmp-vc90-mt", "mpfr-vc90-mt"};
String dllNames[] = {"bwapi_bridge" + VERSION, "libgmp-10", "libmpfr-4"};
if(!arch.equals("x86")){
throw new UnsupportedOperationException("BWMirror API supports only x86 architecture.");
}
@ -74,14 +74,20 @@ public class Mirror {
String path = Mirror.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = java.net.URLDecoder.decode(path, "UTF-8");
JarResources jar = null;
for (String dllName : dllNames) {
String dllNameExt = dllName + ".dll";
if (!new File(dllNameExt).exists()) {
JarResources jar = new JarResources(path);
if (null == jar) {
jar = new JarResources(decodedPath);
}
byte[] correctDllData = jar.getResource(dllNameExt);
FileOutputStream funnyStream = new FileOutputStream(dllNameExt);
funnyStream.write(correctDllData);
funnyStream.close();
// prevents the creation of zero byte files
if (null != correctDllData) {
FileOutputStream funnyStream = new FileOutputStream(dllNameExt);
funnyStream.write(correctDllData);
funnyStream.close();
}
}
}
}
@ -110,7 +116,7 @@ public class Mirror {
}
/**
* Starts the API, initializes all constants ( {@link bwapi.UnitType}, {@link bwapi.WeaponType} ) and the {@link bwapi.Game} object.
* Starts the API, initializes all constants ( {@link UnitType}, {@link WeaponType} ) and the {@link Game} object.
* This method blocks until the end of game.
*/
public native void startGame();
@ -127,7 +133,7 @@ public class Mirror {
/**
* The simplest interface to receive update event from Broodwar. The {@link #update()} method is called once each frame.
* For a simple bot and implementation of this interface is enough, to receive all in game events, implement {@link bwapi.BWEventListener}.
* For a simple bot and implementation of this interface is enough, to receive all in game events, implement {@link BWEventListener}.
*/
/*public*/ private interface FrameCallback {
public void update();

View file

@ -1,5 +1,7 @@
package bwapi;
import bwapi.TilePosition;
import java.lang.Override;
import java.util.HashMap;
import java.util.Map;
@ -24,14 +26,10 @@ public class Position extends AbstractPoint<Position>{
public native Position makeValid();
public native double getDistance(Position position);
public native int getApproxDistance(Position position);
public native double getLength();
public native boolean hasPath(Position position);
public int getX() {
return x;
}
@ -87,4 +85,8 @@ public class Position extends AbstractPoint<Position>{
public Position getPoint(){
return this;
}
public TilePosition toTilePosition(){
return new TilePosition(x / TilePosition.SIZE_IN_PIXELS, y / TilePosition.SIZE_IN_PIXELS);
}
}

View file

@ -1,5 +1,7 @@
package bwapi;
import bwapi.Position;
import java.lang.Override;
import java.util.HashMap;
import java.util.Map;
@ -12,6 +14,8 @@ import java.util.Map;
public class TilePosition extends AbstractPoint<TilePosition>{
private int x, y;
public static final int SIZE_IN_PIXELS = 32;
public TilePosition(int x, int y) {
this.x = x;
this.y = y;
@ -21,14 +25,10 @@ public class TilePosition extends AbstractPoint<TilePosition>{
return "[" + x + ", " + y + "]";
}
public native boolean hasPath(TilePosition position);
public native boolean isValid();
public native TilePosition makeValid();
public native double getDistance(TilePosition position);
public native double getLength();
public int getX() {
@ -86,4 +86,8 @@ public class TilePosition extends AbstractPoint<TilePosition>{
public TilePosition getPoint(){
return this;
}
public Position toPosition(){
return new Position(x * SIZE_IN_PIXELS, y * SIZE_IN_PIXELS);
}
}

View file

@ -1,130 +0,0 @@
package bwapi;
import bwapi.BWEventListener;
/**
* This class receives all events from Broodwar.
* To process them, receive an AIModule's instance from {@link Mirror} and call {@link #setEventListener(bwapi.BWEventListener)}
* to set you own {@link BWEventListener listener}.
* There's also a stub class ({@link DefaultBWListener}) provided, so you don't have to implement all of the methods.
*/
public class AIModule {
AIModule(){}
private BWEventListener eventListener;
public void setEventListener(BWEventListener eventListener) {
this.eventListener = eventListener;
}
public void onStart() {
if (eventListener != null) {
eventListener.onStart();
}
}
public void onEnd(boolean isWinner) {
if (eventListener != null) {
eventListener.onEnd(isWinner);
}
}
public void onFrame() {
if (eventListener != null) {
eventListener.onFrame();
}
}
public void onSendText(String text) {
if (eventListener != null)
{
eventListener.onSendText(text);
}
}
public void onReceiveText(Player player, String text) {
if (eventListener != null) {
eventListener.onReceiveText(player, text);
}
}
public void onPlayerLeft(Player player) {
if (eventListener != null) {
eventListener.onPlayerLeft(player);
}
}
public void onNukeDetect(Position target) {
if (eventListener != null) {
eventListener.onNukeDetect(target);
}
}
public void onUnitDiscover(Unit unit) {
if (eventListener != null) {
eventListener.onUnitDiscover(unit);
}
}
public void onUnitEvade(Unit unit) {
if (eventListener != null) {
eventListener.onUnitEvade(unit);
}
}
public void onUnitShow(Unit unit) {
if (eventListener != null) {
eventListener.onUnitShow(unit);
}
}
public void onUnitHide(Unit unit) {
if (eventListener != null) {
eventListener.onUnitHide(unit);
}
}
public void onUnitCreate(Unit unit) {
if (eventListener != null) {
eventListener.onUnitCreate(unit);
}
}
public void onUnitDestroy(Unit unit) {
if (eventListener != null) {
eventListener.onUnitDestroy(unit);
}
}
public void onUnitMorph(Unit unit) {
if (eventListener != null) {
eventListener.onUnitMorph(unit);
}
}
public void onUnitRenegade(Unit unit) {
if (eventListener != null) {
eventListener.onUnitRenegade(unit);
}
}
public void onSaveGame(String gameName) {
if (eventListener != null) {
eventListener.onSaveGame(gameName);
}
}
public void onUnitComplete(Unit unit) {
if (eventListener != null) {
eventListener.onUnitComplete(unit);
}
}
public void onPlayerDropped(Player player) {
if (eventListener != null) {
eventListener.onPlayerDropped(player);
}
}
}

View file

@ -1,30 +0,0 @@
package bwapi;
/**
* Common ancestor for location based objects to simplify distance computation.
* This will be refactored into interface with default methods when java 8 becomes widely used.
*
* Idea by Rafa³ Poniatowski
*/
public abstract class AbstractPoint<T extends AbstractPoint> {
public abstract T getPoint();
public int getX(){
return getPoint().getX();
}
public int getY(){
return getPoint().getY();
}
public double getDistance(AbstractPoint<T> otherPosition) {
return getDistance(otherPosition.getX(), otherPosition.getY());
}
public double getDistance(int x, int y) {
double dx = x - getX();
double dy = y - getY();
return Math.sqrt(dx * dx + dy * dy);
}
}

View file

@ -1,53 +0,0 @@
package bwapi;
import bwapi.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Collection;
import java.util.List;
/**
* Implement this interface and call {@link AIModule#setEventListener(bwapi.BWEventListener)} to receive all of the in game events.
*/
public interface BWEventListener {
public void onStart();
public void onEnd(boolean isWinner);
public void onFrame();
public void onSendText(String text);
public void onReceiveText(Player player, String text);
public void onPlayerLeft(Player player);
public void onNukeDetect(Position target);
public void onUnitDiscover(Unit unit);
public void onUnitEvade(Unit unit);
public void onUnitShow(Unit unit);
public void onUnitHide(Unit unit);
public void onUnitCreate(Unit unit);
public void onUnitDestroy(Unit unit);
public void onUnitMorph(Unit unit);
public void onUnitRenegade(Unit unit);
public void onSaveGame(String gameName);
public void onUnitComplete(Unit unit);
public void onPlayerDropped(Player player);
}

View file

@ -1,15 +0,0 @@
package bwapi;
import bwapi.Position;
/**
* Interrmediate class used to translate getPoint() calls to getCenter() calls.
*/
public abstract class CenteredObject extends AbstractPoint<Position> {
public Position getPoint(){
return getCenter();
}
public abstract Position getCenter();
}

View file

@ -1,73 +0,0 @@
package bwapi;
import java.lang.Override;
import java.util.HashMap;
import java.util.Map;
/**
* Starcraft uses a 256 color palette to render everything,
* so the colors available for draw shapes using BWAPI is limited to the colors available in the <a href="http://bwapi.googlecode.com/svn/wiki/colorPalette.gif" target="_blank">Pallete</a>.
* Several predefined colors from the pallete are provided.
*/
public class Color {
private int r, g, b;
/**
* Create a color using the color in the palette that is closest to the RGB color specified. This will check a number of colors in the pallet to see which is closest to the specified color so this function is relatively slow.
* @param r
* @param g
* @param b
*/
public Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
public static Color Red;
public static Color Blue;
public static Color Teal;
public static Color Purple;
public static Color Orange;
public static Color Brown;
public static Color White;
public static Color Yellow;
public static Color Green;
public static Color Cyan;
public static Color Black;
public static Color Grey;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Color)) return false;
Color color = (Color) o;
if (b != color.b) return false;
if (g != color.g) return false;
if (r != color.r) return false;
return true;
}
@Override
public int hashCode() {
int result = r;
result = 31 * result + g;
result = 31 * result + b;
return result;
}
}

View file

@ -1,103 +0,0 @@
package bwapi;
import bwapi.BWEventListener;
import bwapi.Player;
import bwapi.Position;
import bwapi.Unit;
/**
* A utility stub class providing a default implementation of {@link BWEventListener},
* override it's methods if you want to handle only some events.
*/
public class DefaultBWListener implements BWEventListener {
@Override
public void onStart() {
}
@Override
public void onEnd(boolean b) {
}
@Override
public void onFrame() {
}
@Override
public void onSendText(String s) {
}
@Override
public void onReceiveText(Player player, String s) {
}
@Override
public void onPlayerLeft(Player player) {
}
@Override
public void onNukeDetect(Position position) {
}
@Override
public void onUnitDiscover(Unit unit) {
}
@Override
public void onUnitEvade(Unit unit) {
}
@Override
public void onUnitShow(Unit unit) {
}
@Override
public void onUnitHide(Unit unit) {
}
@Override
public void onUnitCreate(Unit unit) {
}
@Override
public void onUnitDestroy(Unit unit) {
}
@Override
public void onUnitMorph(Unit unit) {
}
@Override
public void onUnitRenegade(Unit unit) {
}
@Override
public void onSaveGame(String s) {
}
@Override
public void onUnitComplete(Unit unit) {
}
@Override
public void onPlayerDropped(Player player) {
}
}

View file

@ -1,268 +0,0 @@
package bwapi;
import bwapi.AIModule;
import bwapi.BWEventListener;
import java.io.*;
import java.io.File;
import java.lang.Exception;
import java.lang.UnsupportedOperationException;
import java.util.*;
import java.util.zip.*;
/**
* <p>The API entry point. Standard use case:</p>
* <ul>
* <li>Create a Mirror object and use {@link #getModule()} and then set an {@link AIModule}'s {@link BWEventListener}<br/>
* <li>Call {@link #startGame()} to init the API and connect to Broodwar, then launch Broodwar from ChaosLauncher.</li>
* <li>In you {@link BWEventListener#onStart()} method, receive the Game object by calling {@link #getGame()}</li>
* </ul>
* <br/>
* <b>Example</b>
* <pre>
* {@code
*
* mirror.getModule().setEventListener(new DefaultBWListener()
* {
* public void onStart() {
* game = mirror.getGame();
* self = game.self();
* //initialization
* ....
* }
*
* public void onUpdate() {
* for (Unit myUnit : self.getUnits()) {
* //give orders to unit
* ...
* }
* }
* });
* }
* mirror.startGame();
* </pre>
* <p><b>Note:</b> The Game object is initialized during the {@link #startGame()} as well as other BWMirror API's constants.
* Do not use any API releated methods/fields prior to {@link #startGame()}.</p>
*/
public class Mirror {
private Game game;
private AIModule module = new AIModule();
private FrameCallback frameCallback;
private static final boolean EXTRACT_JAR = true;
private static final String VERSION = "2_5";
static {
String arch = System.getProperty("os.arch");
String dllNames[] = {"bwapi_bridge" + VERSION, "libgmp-10", "libmpfr-4"};
if(!arch.equals("x86")){
throw new UnsupportedOperationException("BWMirror API supports only x86 architecture.");
}
try {
if (EXTRACT_JAR) {
System.setProperty("java.library.path", ".");
java.lang.reflect.Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
String path = Mirror.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = java.net.URLDecoder.decode(path, "UTF-8");
JarResources jar = null;
for (String dllName : dllNames) {
String dllNameExt = dllName + ".dll";
if (!new File(dllNameExt).exists()) {
if (null == jar) {
jar = new JarResources(decodedPath);
}
byte[] correctDllData = jar.getResource(dllNameExt);
// prevents the creation of zero byte files
if (null != correctDllData) {
FileOutputStream funnyStream = new FileOutputStream(dllNameExt);
funnyStream.write(correctDllData);
funnyStream.close();
}
}
}
}
} catch (Exception e) {
System.err.println("Failed to extract native libraries.\n" + e);
}
System.loadLibrary(dllNames[0]);
File dataDir = new File("bwapi-data/BWTA");
if(!dataDir.exists()){
try {
dataDir.mkdirs();
} catch (Exception e) {
System.err.println("Unable to create /bwapi-data/BWTA folder, BWTA analysis will not be saved.");
}
}
}
public Game getGame() {
return game;
}
public AIModule getModule() {
return module;
}
/**
* Starts the API, initializes all constants ( {@link UnitType}, {@link WeaponType} ) and the {@link Game} object.
* This method blocks until the end of game.
*/
public native void startGame();
private void update() {
if (frameCallback != null) {
frameCallback.update();
}
}
/*public void setFrameCallback(bwapi.Mirror.FrameCallback frameCallback) {
this.frameCallback = frameCallback;
} */
/**
* The simplest interface to receive update event from Broodwar. The {@link #update()} method is called once each frame.
* For a simple bot and implementation of this interface is enough, to receive all in game events, implement {@link BWEventListener}.
*/
/*public*/ private interface FrameCallback {
public void update();
}
@SuppressWarnings({"unchecked"})
private static class JarResources {
// external debug flag
public boolean debugOn = false;
// jar resource mapping tables
private Hashtable htSizes = new Hashtable();
private Hashtable htJarContents = new Hashtable();
// a jar file
private String jarFileName;
/**
* creates a javabot.JarResources. It extracts all resources from a Jar
* into an internal hashtable, keyed by resource names.
*
* @param jarFileName a jar or zip file
*/
public JarResources(String jarFileName) {
this.jarFileName = jarFileName;
init();
}
/**
* Extracts a jar resource as a blob.
*
* @param name a resource name.
*/
public byte[] getResource(String name) {
return (byte[]) htJarContents.get(name);
}
/**
* initializes internal hash tables with Jar file resources.
*/
private void init() {
try {
// extracts just sizes only.
ZipFile zf = new ZipFile(jarFileName);
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
if (debugOn) {
System.out.println(dumpZipEntry(ze));
}
htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
}
zf.close();
// extract resources and put them into the hashtable.
FileInputStream fis = new FileInputStream(jarFileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis);
ZipEntry ze = null;
while ((ze = zis.getNextEntry()) != null) {
if (ze.isDirectory()) {
continue;
}
if (debugOn) {
System.out.println(
"ze.getName()=" + ze.getName() + "," + "getSize()=" + ze.getSize()
);
}
int size = (int) ze.getSize();
// -1 means unknown size.
if (size == -1) {
size = ((Integer) htSizes.get(ze.getName())).intValue();
}
byte[] b = new byte[(int) size];
int rb = 0;
int chunk = 0;
while (((int) size - rb) > 0) {
chunk = zis.read(b, rb, (int) size - rb);
if (chunk == -1) {
break;
}
rb += chunk;
}
// add to internal resource hashtable
htJarContents.put(ze.getName(), b);
if (debugOn) {
System.out.println(
ze.getName() + " rb=" + rb +
",size=" + size +
",csize=" + ze.getCompressedSize()
);
}
}
} catch (NullPointerException e) {
System.out.println("done.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Dumps a zip entry into a string.
*
* @param ze a ZipEntry
*/
private String dumpZipEntry(ZipEntry ze) {
StringBuffer sb = new StringBuffer();
if (ze.isDirectory()) {
sb.append("d ");
} else {
sb.append("f ");
}
if (ze.getMethod() == ZipEntry.STORED) {
sb.append("stored ");
} else {
sb.append("defalted ");
}
sb.append(ze.getName());
sb.append("\t");
sb.append("" + ze.getSize());
if (ze.getMethod() == ZipEntry.DEFLATED) {
sb.append("/" + ze.getCompressedSize());
}
return (sb.toString());
}
}
}

View file

@ -1,92 +0,0 @@
package bwapi;
import bwapi.TilePosition;
import java.lang.Override;
import java.util.HashMap;
import java.util.Map;
/**
* Positions are measured in pixels and are the highest resolution.
*/
public class Position extends AbstractPoint<Position>{
private int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return "[" + x + ", " + y + "]";
}
public native boolean isValid();
public native Position makeValid();
public native int getApproxDistance(Position position);
public native double getLength();
public int getX() {
return x;
}
public int getY() {
return y;
}
public static Position Invalid;
public static Position None;
public static Position Unknown;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Position)) return false;
Position position = (Position) o;
if (x != position.x) return false;
if (y != position.y) return false;
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
private static Map<Long, Position> instances = new HashMap<Long, Position>();
private Position(long pointer) {
this.pointer = pointer;
}
private static Position get(long pointer) {
Position instance = instances.get(pointer);
if (instance == null) {
instance = new Position(pointer);
instances.put(pointer, instance);
}
return instance;
}
private long pointer;
public Position getPoint(){
return this;
}
public TilePosition toTilePosition(){
return new TilePosition(x / TilePosition.SIZE_IN_PIXELS, y / TilePosition.SIZE_IN_PIXELS);
}
}

View file

@ -1,15 +0,0 @@
package bwapi;
import bwapi.Position;
/**
* Interrmediate class used to translate getPoint() calls to getPosition() calls.
*/
public abstract class PositionedObject extends AbstractPoint<Position> {
public Position getPoint(){
return getPosition();
}
public abstract Position getPosition();
}

Some files were not shown because too many files have changed in this diff Show more