Formatting

This commit is contained in:
Anuken
2018-07-12 20:37:14 -04:00
parent a3bda3a941
commit baaeb229cf
379 changed files with 17470 additions and 16215 deletions

View File

@@ -9,70 +9,31 @@ import java.lang.annotation.Target;
* Goal: To create a system to send events to the server from the client and vice versa, without creating a new packet type each time.<br>
* These events may optionally also trigger on the caller client/server as well.<br>
*/
public class Annotations {
public class Annotations{
/**Marks a method as invokable remotely across a server/client connection.*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface Remote {
/**Specifies the locations from which this method can be invoked.*/
Loc targets() default Loc.server;
/**Specifies which methods are generated. Only affects server-to-client methods.*/
Variant variants() default Variant.all;
/**The local locations where this method is called locally, when invoked.*/
Loc called() default Loc.none;
/**Whether to forward this packet to all other clients upon recieval. Client only.*/
boolean forward() default false;
/**Whether the packet for this method is sent with UDP instead of TCP.
* UDP is faster, but is prone to packet loss and duplication.*/
boolean unreliable() default false;
/**The simple class name where this method is placed.*/
String in() default "Call";
/**Priority of this event.*/
PacketPriority priority() default PacketPriority.normal;
}
/**Specifies that this method will be used to write classes of the type returned by {@link #value()}.<br>
* This method must return void and have two parameters, the first being of type {@link java.nio.ByteBuffer} and the second
* being the type returned by {@link #value()}.*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface WriteClass {
Class<?> value();
}
/**Specifies that this method will be used to read classes of the type returned by {@link #value()}. <br>
* This method must return the type returned by {@link #value()},
* and have one parameter, being of type {@link java.nio.ByteBuffer}.*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface ReadClass {
Class<?> value();
}
public enum PacketPriority {
/**Gets put in a queue and processed if not connected.*/
public enum PacketPriority{
/** Gets put in a queue and processed if not connected. */
normal,
/**Gets handled immediately, regardless of connection status.*/
/** Gets handled immediately, regardless of connection status. */
high,
/**Does not get handled unless client is connected.*/
/** Does not get handled unless client is connected. */
low
}
/**A set of two booleans, one specifying server and one specifying client.*/
public enum Loc {
/**Method can only be invoked on the client from the server.*/
/** A set of two booleans, one specifying server and one specifying client. */
public enum Loc{
/** Method can only be invoked on the client from the server. */
server(true, false),
/**Method can only be invoked on the server from the client.*/
/** Method can only be invoked on the server from the client. */
client(false, true),
/**Method can be invoked from anywhere*/
/** Method can be invoked from anywhere */
both(true, true),
/**Neither server nor client.*/
/** Neither server nor client. */
none(false, false);
/**If true, this method can be invoked ON clients FROM servers.*/
/** If true, this method can be invoked ON clients FROM servers. */
public final boolean isServer;
/**If true, this method can be invoked ON servers FROM clients.*/
/** If true, this method can be invoked ON servers FROM clients. */
public final boolean isClient;
Loc(boolean server, boolean client){
@@ -81,12 +42,12 @@ public class Annotations {
}
}
public enum Variant {
/**Method can only be invoked targeting one player.*/
public enum Variant{
/** Method can only be invoked targeting one player. */
one(true, false),
/**Method can only be invoked targeting all players.*/
/** Method can only be invoked targeting all players. */
all(false, true),
/**Method targets both one player and all players.*/
/** Method targets both one player and all players. */
both(true, true);
public final boolean isOne, isAll;
@@ -96,4 +57,55 @@ public class Annotations {
this.isAll = isAll;
}
}
/** Marks a method as invokable remotely across a server/client connection. */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface Remote{
/** Specifies the locations from which this method can be invoked. */
Loc targets() default Loc.server;
/** Specifies which methods are generated. Only affects server-to-client methods. */
Variant variants() default Variant.all;
/** The local locations where this method is called locally, when invoked. */
Loc called() default Loc.none;
/** Whether to forward this packet to all other clients upon recieval. Client only. */
boolean forward() default false;
/**
* Whether the packet for this method is sent with UDP instead of TCP.
* UDP is faster, but is prone to packet loss and duplication.
*/
boolean unreliable() default false;
/** The simple class name where this method is placed. */
String in() default "Call";
/** Priority of this event. */
PacketPriority priority() default PacketPriority.normal;
}
/**
* Specifies that this method will be used to write classes of the type returned by {@link #value()}.<br>
* This method must return void and have two parameters, the first being of type {@link java.nio.ByteBuffer} and the second
* being the type returned by {@link #value()}.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface WriteClass{
Class<?> value();
}
/**
* Specifies that this method will be used to read classes of the type returned by {@link #value()}. <br>
* This method must return the type returned by {@link #value()},
* and have one parameter, being of type {@link java.nio.ByteBuffer}.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface ReadClass{
Class<?> value();
}
}

View File

@@ -2,14 +2,14 @@ package io.anuke.annotations;
import java.util.ArrayList;
/**Represents a class witha list method entries to include in it.*/
public class ClassEntry {
/**All methods in this generated class.*/
/** Represents a class witha list method entries to include in it. */
public class ClassEntry{
/** All methods in this generated class. */
public final ArrayList<MethodEntry> methods = new ArrayList<>();
/**Simple class name.*/
/** Simple class name. */
public final String name;
public ClassEntry(String name) {
public ClassEntry(String name){
this.name = name;
}
}

View File

@@ -10,12 +10,16 @@ import javax.tools.Diagnostic.Kind;
import java.util.HashMap;
import java.util.Set;
/**This class finds reader and writer methods annotated by the {@link io.anuke.annotations.Annotations.WriteClass}
* and {@link io.anuke.annotations.Annotations.ReadClass} annotations.*/
public class IOFinder {
/**
* This class finds reader and writer methods annotated by the {@link io.anuke.annotations.Annotations.WriteClass}
* and {@link io.anuke.annotations.Annotations.ReadClass} annotations.
*/
public class IOFinder{
/**Finds all class serializers for all types and returns them. Logs errors when necessary.
* Maps fully qualified class names to their serializers.*/
/**
* Finds all class serializers for all types and returns them. Logs errors when necessary.
* Maps fully qualified class names to their serializers.
*/
public HashMap<String, ClassSerializer> findSerializers(RoundEnvironment env){
HashMap<String, ClassSerializer> result = new HashMap<>();
@@ -51,33 +55,33 @@ public class IOFinder {
}
private String getValue(WriteClass write){
try {
try{
Class<?> type = write.value();
return type.getName();
}catch (MirroredTypeException e){
}catch(MirroredTypeException e){
return e.getTypeMirror().toString();
}
}
private String getValue(ReadClass read){
try {
try{
Class<?> type = read.value();
return type.getName();
}catch (MirroredTypeException e){
}catch(MirroredTypeException e){
return e.getTypeMirror().toString();
}
}
/**Information about read/write methods for a specific class type.*/
/** Information about read/write methods for a specific class type. */
public static class ClassSerializer{
/**Fully qualified method name of the reader.*/
/** Fully qualified method name of the reader. */
public final String readMethod;
/**Fully qualified method name of the writer.*/
/** Fully qualified method name of the writer. */
public final String writeMethod;
/**Fully qualified class type name.*/
/** Fully qualified class type name. */
public final String classType;
public ClassSerializer(String readMethod, String writeMethod, String classType) {
public ClassSerializer(String readMethod, String writeMethod, String classType){
this.readMethod = readMethod;
this.writeMethod = writeMethod;
this.classType = classType;

View File

@@ -6,32 +6,34 @@ import io.anuke.annotations.Annotations.Variant;
import javax.lang.model.element.ExecutableElement;
/**Class that repesents a remote method to be constructed and put into a class.*/
public class MethodEntry {
/**Simple target class name.*/
/** Class that repesents a remote method to be constructed and put into a class. */
public class MethodEntry{
/** Simple target class name. */
public final String className;
/**Fully qualified target method to call.*/
/** Fully qualified target method to call. */
public final String targetMethod;
/**Whether this method can be called on a client/server.*/
/** Whether this method can be called on a client/server. */
public final Loc where;
/**Whether an additional 'one' and 'all' method variant is generated. At least one of these must be true.
* Only applicable to client (server-invoked) methods.*/
/**
* Whether an additional 'one' and 'all' method variant is generated. At least one of these must be true.
* Only applicable to client (server-invoked) methods.
*/
public final Variant target;
/**Whether this method is called locally as well as remotely.*/
/** Whether this method is called locally as well as remotely. */
public final Loc local;
/**Whether this method is unreliable and uses UDP.*/
/** Whether this method is unreliable and uses UDP. */
public final boolean unreliable;
/**Whether to forward this method call to all other clients when a client invokes it. Server only.*/
/** Whether to forward this method call to all other clients when a client invokes it. Server only. */
public final boolean forward;
/**Unique method ID.*/
/** Unique method ID. */
public final int id;
/**The element method associated with this entry.*/
/** The element method associated with this entry. */
public final ExecutableElement element;
/**The assigned packet priority. Only used in clients.*/
/** The assigned packet priority. Only used in clients. */
public final PacketPriority priority;
public MethodEntry(String className, String targetMethod, Loc where, Variant target,
Loc local, boolean unreliable, boolean forward, int id, ExecutableElement element, PacketPriority priority) {
Loc local, boolean unreliable, boolean forward, int id, ExecutableElement element, PacketPriority priority){
this.className = className;
this.forward = forward;
this.targetMethod = targetMethod;
@@ -45,7 +47,7 @@ public class MethodEntry {
}
@Override
public int hashCode() {
public int hashCode(){
return targetMethod.hashCode();
}
}

View File

@@ -18,25 +18,25 @@ import java.util.*;
import java.util.stream.Collectors;
/**The annotation processor for generating remote method call code.*/
/** The annotation processor for generating remote method call code. */
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({
"io.anuke.annotations.Annotations.Remote",
"io.anuke.annotations.Annotations.WriteClass",
"io.anuke.annotations.Annotations.ReadClass",
"io.anuke.annotations.Annotations.Remote",
"io.anuke.annotations.Annotations.WriteClass",
"io.anuke.annotations.Annotations.ReadClass",
})
public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
/**Maximum size of each event packet.*/
public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
/** Maximum size of each event packet. */
public static final int maxPacketSize = 4096;
/**Name of the base package to put all the generated classes.*/
/** Name of the base package to put all the generated classes. */
private static final String packageName = "io.anuke.mindustry.gen";
/**Name of class that handles reading and invoking packets on the server.*/
/** Name of class that handles reading and invoking packets on the server. */
private static final String readServerName = "RemoteReadServer";
/**Name of class that handles reading and invoking packets on the client.*/
/** Name of class that handles reading and invoking packets on the client. */
private static final String readClientName = "RemoteReadClient";
/**Processing round number.*/
/** Processing round number. */
private int round;
//class serializers
@@ -51,7 +51,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
private ArrayList<ClassEntry> classes;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
public synchronized void init(ProcessingEnvironment processingEnv){
super.init(processingEnv);
//put all relevant utils into utils class
Utils.typeUtils = processingEnv.getTypeUtils();
@@ -61,15 +61,15 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv){
if(round > 1) return false; //only process 2 rounds
round ++;
round++;
try {
try{
//round 1: find all annotations, generate *writers*
if(round == 1) {
if(round == 1){
//get serializers
serializers = new IOFinder().findSerializers(roundEnv);
@@ -88,21 +88,21 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
orderedElements.sort(Comparator.comparing(Object::toString));
//create methods
for (Element element : orderedElements) {
for(Element element : orderedElements){
Remote annotation = element.getAnnotation(Remote.class);
//check for static
if (!element.getModifiers().contains(Modifier.STATIC) || !element.getModifiers().contains(Modifier.PUBLIC)) {
if(!element.getModifiers().contains(Modifier.STATIC) || !element.getModifiers().contains(Modifier.PUBLIC)){
Utils.messager.printMessage(Kind.ERROR, "All @Remote methods must be public and static: ", element);
}
//can't generate none methods
if (annotation.targets() == Loc.none) {
if(annotation.targets() == Loc.none){
Utils.messager.printMessage(Kind.ERROR, "A @Remote method's targets() cannot be equal to 'none':", element);
}
//get and create class entry if needed
if (!classMap.containsKey(annotation.in())) {
if(!classMap.containsKey(annotation.in())){
ClassEntry clas = new ClassEntry(annotation.in());
classMap.put(annotation.in(), clas);
classes.add(clas);
@@ -127,7 +127,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
writegen.generateFor(classes, packageName);
return true;
}else if(round == 2) { //round 2: generate all *readers*
}else if(round == 2){ //round 2: generate all *readers*
RemoteReadGenerator readgen = new RemoteReadGenerator(serializers);
//generate server readers
@@ -147,7 +147,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor {
return true;
}
}catch (Exception e){
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}

View File

@@ -14,22 +14,25 @@ import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
/**Generates code for reading remote invoke packets on the client and server.*/
public class RemoteReadGenerator {
/** Generates code for reading remote invoke packets on the client and server. */
public class RemoteReadGenerator{
private final HashMap<String, ClassSerializer> serializers;
/**Creates a read generator that uses the supplied serializer setup.*/
public RemoteReadGenerator(HashMap<String, ClassSerializer> serializers) {
/** Creates a read generator that uses the supplied serializer setup. */
public RemoteReadGenerator(HashMap<String, ClassSerializer> serializers){
this.serializers = serializers;
}
/**Generates a class for reading remote invoke packets.
/**
* Generates a class for reading remote invoke packets.
*
* @param entries List of methods to use/
* @param className Simple target class name.
* @param packageName Full target package name.
* @param needsPlayer Whether this read method requires a reference to the player sender.*/
* @param needsPlayer Whether this read method requires a reference to the player sender.
*/
public void generateFor(List<MethodEntry> entries, String className, String packageName, boolean needsPlayer)
throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IOException {
throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException, IOException{
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC);
@@ -69,10 +72,10 @@ public class RemoteReadGenerator {
StringBuilder varResult = new StringBuilder();
//go through each parameter
for(int i = 0; i < entry.element.getParameters().size(); i ++){
for(int i = 0; i < entry.element.getParameters().size(); i++){
VariableElement var = entry.element.getParameters().get(i);
if(!needsPlayer || i != 0) { //if client, skip first parameter since it's always of type player and doesn't need to be read
if(!needsPlayer || i != 0){ //if client, skip first parameter since it's always of type player and doesn't need to be read
//full type name of parameter
String typeName = var.asType().toString();
//name of parameter
@@ -81,17 +84,17 @@ public class RemoteReadGenerator {
String capName = typeName.equals("byte") ? "" : Character.toUpperCase(typeName.charAt(0)) + typeName.substring(1);
//write primitives automatically
if (Utils.isPrimitive(typeName)) {
if (typeName.equals("boolean")) {
if(Utils.isPrimitive(typeName)){
if(typeName.equals("boolean")){
readBlock.addStatement("boolean " + varName + " = buffer.get() == 1");
} else {
}else{
readBlock.addStatement(typeName + " " + varName + " = buffer.get" + capName + "()");
}
} else {
}else{
//else, try and find a serializer
ClassSerializer ser = serializers.get(typeName);
if (ser == null) { //make sure a serializer exists!
if(ser == null){ //make sure a serializer exists!
Utils.messager.printMessage(Kind.ERROR, "No @ReadClass method to read class type: '" + typeName + "'", var);
return;
}
@@ -121,7 +124,7 @@ public class RemoteReadGenerator {
}
readBlock.nextControlFlow("catch (java.lang.Exception e)");
readBlock.addStatement("throw new java.lang.RuntimeException(\"Failed to to read remote method '"+entry.element.getSimpleName() +"'!\", e)");
readBlock.addStatement("throw new java.lang.RuntimeException(\"Failed to to read remote method '" + entry.element.getSimpleName() + "'!\", e)");
readBlock.endControlFlow();
}

View File

@@ -14,17 +14,17 @@ import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
/**Generates code for writing remote invoke packets on the client and server.*/
public class RemoteWriteGenerator {
/** Generates code for writing remote invoke packets on the client and server. */
public class RemoteWriteGenerator{
private final HashMap<String, ClassSerializer> serializers;
/**Creates a write generator that uses the supplied serializer setup.*/
public RemoteWriteGenerator(HashMap<String, ClassSerializer> serializers) {
/** Creates a write generator that uses the supplied serializer setup. */
public RemoteWriteGenerator(HashMap<String, ClassSerializer> serializers){
this.serializers = serializers;
}
/**Generates all classes in this list.*/
public void generateFor(List<ClassEntry> entries, String packageName) throws IOException {
/** Generates all classes in this list. */
public void generateFor(List<ClassEntry> entries, String packageName) throws IOException{
for(ClassEntry entry : entries){
//create builder
@@ -58,7 +58,7 @@ public class RemoteWriteGenerator {
}
}
/**Creates a specific variant for a method entry.*/
/** Creates a specific variant for a method entry. */
private void writeMethodVariant(TypeSpec.Builder classBuilder, MethodEntry methodEntry, boolean toAll, boolean forwarded){
ExecutableElement elem = methodEntry.element;
@@ -99,7 +99,7 @@ public class RemoteWriteGenerator {
if(!forwarded && methodEntry.local != Loc.none){
//add in local checks
if(methodEntry.local != Loc.both){
method.beginControlFlow("if("+getCheckString(methodEntry.local) + " || !io.anuke.mindustry.net.Net.active())");
method.beginControlFlow("if(" + getCheckString(methodEntry.local) + " || !io.anuke.mindustry.net.Net.active())");
}
//concatenate parameters
@@ -109,16 +109,16 @@ public class RemoteWriteGenerator {
//special case: calling local-only methods uses the local player
if(index == 0 && methodEntry.where == Loc.client){
results.append("io.anuke.mindustry.Vars.players[0]");
}else {
}else{
results.append(var.getSimpleName());
}
if(index != elem.getParameters().size() - 1) results.append(", ");
index ++;
index++;
}
//add the statement to call it
method.addStatement("$N." + elem.getSimpleName() + "(" + results.toString() + ")",
((TypeElement)elem.getEnclosingElement()).getQualifiedName().toString());
((TypeElement) elem.getEnclosingElement()).getQualifiedName().toString());
if(methodEntry.local != Loc.both){
method.endControlFlow();
@@ -126,7 +126,7 @@ public class RemoteWriteGenerator {
}
//start control flow to check if it's actually client/server so no netcode is called
method.beginControlFlow("if("+getCheckString(methodEntry.where)+")");
method.beginControlFlow("if(" + getCheckString(methodEntry.where) + ")");
//add statement to create packet from pool
method.addStatement("$1N packet = $2N.obtain($1N.class)", "io.anuke.mindustry.net.Packets.InvokePacket", "io.anuke.ucore.util.Pooling");
@@ -139,7 +139,7 @@ public class RemoteWriteGenerator {
//rewind buffer
method.addStatement("TEMP_BUFFER.position(0)");
for(int i = 0; i < elem.getParameters().size(); i ++){
for(int i = 0; i < elem.getParameters().size(); i++){
//first argument is skipped as it is always the player caller
if((!methodEntry.where.isServer/* || methodEntry.mode == Loc.both*/) && i == 0){
continue;
@@ -164,7 +164,7 @@ public class RemoteWriteGenerator {
method.beginControlFlow("if(io.anuke.mindustry.net.Net.server())");
}
if(Utils.isPrimitive(typeName)) { //check if it's a primitive, and if so write it
if(Utils.isPrimitive(typeName)){ //check if it's a primitive, and if so write it
if(typeName.equals("boolean")){ //booleans are special
method.addStatement("TEMP_BUFFER.put(" + varName + " ? (byte)1 : 0)");
}else{
@@ -181,7 +181,7 @@ public class RemoteWriteGenerator {
}
//add statement for writing it
method.addStatement(ser.writeMethod + "(TEMP_BUFFER, " + varName +")");
method.addStatement(ser.writeMethod + "(TEMP_BUFFER, " + varName + ")");
}
if(writePlayerSkipCheck){ //write end check
@@ -197,7 +197,7 @@ public class RemoteWriteGenerator {
if(forwarded){ //forward packet
if(!methodEntry.local.isClient){ //if the client doesn't get it called locally, forward it back after validation
sendString = "send(";
}else {
}else{
sendString = "sendExcept(exceptSenderID, ";
}
}else if(toAll){ //send to all players / to server
@@ -207,8 +207,8 @@ public class RemoteWriteGenerator {
}
//send the actual packet
method.addStatement("io.anuke.mindustry.net.Net." + sendString + "packet, "+
(methodEntry.unreliable ? "io.anuke.mindustry.net.Net.SendMode.udp" : "io.anuke.mindustry.net.Net.SendMode.tcp")+")");
method.addStatement("io.anuke.mindustry.net.Net." + sendString + "packet, " +
(methodEntry.unreliable ? "io.anuke.mindustry.net.Net.SendMode.udp" : "io.anuke.mindustry.net.Net.SendMode.tcp") + ")");
//end check for server/client
@@ -220,7 +220,7 @@ public class RemoteWriteGenerator {
private String getCheckString(Loc loc){
return loc.isClient && loc.isServer ? "io.anuke.mindustry.net.Net.server() || io.anuke.mindustry.net.Net.client()" :
loc.isClient ? "io.anuke.mindustry.net.Net.client()" :
loc.isServer ? "io.anuke.mindustry.net.Net.server()" : "false";
loc.isClient ? "io.anuke.mindustry.net.Net.client()" :
loc.isServer ? "io.anuke.mindustry.net.Net.server()" : "false";
}
}

View File

@@ -7,14 +7,14 @@ import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
public class Utils {
public class Utils{
public static Types typeUtils;
public static Elements elementUtils;
public static Filer filer;
public static Messager messager;
public static String getMethodName(Element element){
return ((TypeElement)element.getEnclosingElement()).getQualifiedName().toString() + "." + element.getSimpleName();
return ((TypeElement) element.getEnclosingElement()).getQualifiedName().toString() + "." + element.getSimpleName();
}
public static boolean isPrimitive(String type){