1
0
mirror of https://github.com/Anuken/Mindustry.git synced 2024-09-11 08:15:35 +03:00

Source reformat

This commit is contained in:
Anuken 2019-04-08 09:03:18 -04:00
parent 4a96b9bb00
commit b40beb0d1d
331 changed files with 2822 additions and 3274 deletions

View File

@ -1,11 +1,10 @@
jdk:
- openjdk8
- openjdk8
script:
- "git clone --depth=1 --branch=master https://github.com/Anuken/Arc ../Arc"
- "./gradlew test"
- "./gradlew desktop:dist -Pbuildversion=${TRAVIS_TAG:1}"
- "./gradlew server:dist -Pbuildversion=${TRAVIS_TAG:1}"
- "git clone --depth=1 --branch=master https://github.com/Anuken/Arc ../Arc"
- "./gradlew test"
- "./gradlew desktop:dist -Pbuildversion=${TRAVIS_TAG:1}"
- "./gradlew server:dist -Pbuildversion=${TRAVIS_TAG:1}"
deploy:
provider: releases
@ -14,8 +13,8 @@ deploy:
api_key:
secure: Cv5wFtWt62/A24EvSEQvMow7gKPbZ3oATEFPuSghhB2TQz1dA40Zee3Qvk4LFlpLrhYo4K0ZSczCZRGpR+hCd8+Dpww52bheYEvWuh3ZQfvu/fXtEx2j5PwP1qMpmIgSxETV/gkD7l9FImdh0VzktYiAvQfmi0bEocG9/D4QwjFpNat7iwBdcMiw1MvAygpdIWRsjiw0RKlB2mWarmoHhQ7Gu7qlU3j50uaEvcrtmU0pBUPggNQwQRv32i9NPvNFxrqqlUjDLIS8JFea99zCkp8BwYqbEvBIMzd+Qip1/stLJJA3+cDUClbsDtg8rAVetzpOrdLEEBmqShFe5MDl2yEHcsgpN9CFsyTaUfvB3P3rVjizvycMm42IsUkXQiarm5xTQ/TIA8Rd8AHiSKuweNCg1Fd5SFaRtKy8JVLXuxyfUccmyje6hhz2L4lS2Wfj3mAG7sqZUCXhWP79EKdGkiPOjKv4CwXEKmuH3BMVqPlNUZJr9Eg3sV1FG0h2l+MVOOnR635qdUbb49sYojYxVruMLX0BH1c4ZCu230m8CUoWA1Em1QNI75ya7+9Y5T6AsgWDVpBvdUo9fWNbdp+VQ0GskFQsJD5wtnxbcbHeFiERAgGBm7z6qt9u9LrQpBH+dsW52ADvYsu3L4nQEa+sdMHwTTwmGY+iUvsxu0DqxGg=
file:
- "desktop/build/libs/desktop-release.jar"
- "server/build/libs/server-release.jar"
- "desktop/build/libs/desktop-release.jar"
- "server/build/libs/server-release.jar"
on:
repo: Anuken/Mindustry
tags: true

View File

@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.anuke.mindustry">
package="io.anuke.mindustry">
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:glEsVersion="0x00020000" android:required="true"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:resizeableActivity="false"
@ -16,16 +16,16 @@
android:appCategory="game"
android:label="@string/app_name"
android:theme="@style/GdxTheme" android:fullBackupContent="@xml/backup_rules">
<meta-data android:name="android.max_aspect" android:value="2.1" />
<meta-data android:name="android.max_aspect" android:value="2.1"/>
<activity
android:name="io.anuke.mindustry.AndroidLauncher"
android:label="@string/app_name"
android:screenOrientation="user"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout">
android:name="io.anuke.mindustry.AndroidLauncher"
android:label="@string/app_name"
android:screenOrientation="user"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
@ -33,7 +33,7 @@
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:mimeType="application/octet-stream"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" />
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap"/>
</intent-filter>
<intent-filter>
@ -41,28 +41,28 @@
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:mimeType="application/octet-stream"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" />
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav"/>
</intent-filter>
<intent-filter android:icon="@mipmap/ic_launcher"
android:label="Mindustry Map"
android:priority="1">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" android:mimeType="*/*" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.mmap" android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" android:mimeType="*/*" />
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:scheme="file" android:host="*" android:pathPattern=".*\\.msav" android:mimeType="*/*"/>
</intent-filter>
</activity>
<activity android:name=".DonationsActivity"
android:theme="@style/GdxTheme" />
android:theme="@style/GdxTheme"/>
</application>

View File

@ -1,30 +1,30 @@
buildscript {
repositories {
buildscript{
repositories{
mavenLocal()
mavenCentral()
google()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven{ url "https://oss.sonatype.org/content/repositories/snapshots/" }
jcenter()
}
dependencies {
dependencies{
classpath 'com.android.tools.build:gradle:3.3.2'
}
}
apply plugin: "com.android.application"
configurations { natives }
configurations{ natives }
repositories {
mavenCentral()
repositories{
mavenCentral()
jcenter()
maven {
url "https://maven.google.com"
maven{
url "https://maven.google.com"
}
}
dependencies {
dependencies{
implementation project(":core")
implementation project(":net")
@ -46,14 +46,14 @@ task deploy(type: Copy){
from "build/outputs/apk/release/android-release.apk"
into "../deploy/"
rename ("android-release.apk", appName + "-android-" + getVersionString() + ".apk")
rename("android-release.apk", appName + "-android-" + getVersionString() + ".apk")
}
android {
android{
buildToolsVersion '28.0.3'
compileSdkVersion 28
sourceSets {
main {
sourceSets{
main{
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
aidl.srcDirs = ['src']
@ -65,11 +65,11 @@ android {
androidTest.setRoot('tests')
}
packagingOptions {
packagingOptions{
exclude 'META-INF/robovm/ios/robovm.xml'
}
defaultConfig {
defaultConfig{
def vfile = file('../core/assets/version.properties')
def code = 0
@ -93,16 +93,16 @@ android {
versionName versionNameResult
}
compileOptions {
compileOptions{
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
flavorDimensions "google"
signingConfigs {
release {
if(project.hasProperty("RELEASE_STORE_FILE")) {
signingConfigs{
release{
if(project.hasProperty("RELEASE_STORE_FILE")){
storeFile file(RELEASE_STORE_FILE)
storePassword RELEASE_STORE_PASSWORD
keyAlias RELEASE_KEY_ALIAS
@ -113,8 +113,8 @@ android {
}
}
buildTypes {
release {
buildTypes{
release{
signingConfig signingConfigs.release
}
}
@ -122,22 +122,22 @@ android {
// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
task copyAndroidNatives(){
file("libs/armeabi/").mkdirs()
file("libs/armeabi-v7a/").mkdirs()
file("libs/arm64-v8a/").mkdirs()
file("libs/x86_64/").mkdirs()
file("libs/x86/").mkdirs()
configurations.natives.files.each { jar ->
configurations.natives.files.each{ jar ->
def outputDir = null
if (jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if (jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if (jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
if (jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if (jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if (outputDir != null) {
copy {
if(jar.name.endsWith("natives-arm64-v8a.jar")) outputDir = file("libs/arm64-v8a")
if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
if(jar.name.endsWith("natives-x86_64.jar")) outputDir = file("libs/x86_64")
if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
if(outputDir != null){
copy{
from zipTree(jar)
into outputDir
include "*.so"
@ -146,21 +146,21 @@ task copyAndroidNatives() {
}
}
task run(type: Exec) {
task run(type: Exec){
def path
def localProperties = project.file("../local.properties")
if (localProperties.exists()) {
if(localProperties.exists()){
Properties properties = new Properties()
localProperties.withInputStream { instr ->
localProperties.withInputStream{ instr ->
properties.load(instr)
}
def sdkDir = properties.getProperty('sdk.dir')
if (sdkDir) {
if(sdkDir){
path = sdkDir
} else {
}else{
path = "$System.env.ANDROID_HOME"
}
} else {
}else{
path = "$System.env.ANDROID_HOME"
}
@ -169,19 +169,19 @@ task run(type: Exec) {
}
// sets up the Android Idea project, using the old Ant based build.
idea {
module {
idea{
module{
sourceDirs += file("src")
scopes = [COMPILE: [plus: [project.configurations.compile]]]
iml {
withXml {
iml{
withXml{
def node = it.asNode()
def builder = NodeBuilder.newInstance()
builder.current = node
builder.component(name: "FacetManager") {
facet(type: "android", name: "Android") {
configuration {
builder.component(name: "FacetManager"){
facet(type: "android", name: "Android"){
configuration{
option(name: "UPDATE_PROPERTY_FILES", value: "true")
}
}

View File

@ -9,6 +9,5 @@
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-19

View File

@ -18,18 +18,15 @@ import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Strings;
import io.anuke.arc.util.serialization.Base64Coder;
import io.anuke.net.KryoClient;
import io.anuke.net.KryoServer;
import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.game.Saves.SaveSlot;
import io.anuke.mindustry.io.SaveIO;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.ui.dialogs.FileChooser;
import io.anuke.net.KryoClient;
import io.anuke.net.KryoServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import java.util.ArrayList;
import static io.anuke.mindustry.Vars.*;
@ -59,7 +56,7 @@ public class AndroidLauncher extends AndroidApplication{
int len = s.length();
byte[] data = new byte[len / 2];
for(int i = 0; i < len; i += 2){
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
data[i / 2] = (byte)((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
String result = new String(Base64Coder.encode(data));
@ -184,7 +181,7 @@ public class AndroidLauncher extends AndroidApplication{
}
private boolean isTablet(Context context){
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
return manager != null && manager.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE;
}
}

View File

@ -1,6 +1,6 @@
apply plugin: "java"
sourceCompatibility = 1.8
sourceSets.main.java.srcDirs = [ "src/main/java/" ]
sourceSets.main.resources.srcDirs = [ "src/main/resources/" ]
sourceSets.main.java.srcDirs = ["src/main/java/"]
sourceSets.main.resources.srcDirs = ["src/main/resources/"]

View File

@ -1,9 +1,6 @@
package io.anuke.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
public class Annotations{
@ -19,25 +16,25 @@ public class Annotations{
}
/** Marks a class as serializable.*/
/** Marks a class as serializable. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Serialize{
}
/** Marks a class as a special value type struct. Class name must end in 'Struct'.*/
/** Marks a class as a special value type struct. Class name must end in 'Struct'. */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Struct{
}
/**Marks a field of a struct. Optional.*/
/** Marks a field of a struct. Optional. */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface StructField{
/**Size of a struct field in bits. Not valid on booleans or floating point numbers.*/
/** Size of a struct field in bits. Not valid on booleans or floating point numbers. */
int value();
}

View File

@ -1,7 +1,5 @@
package io.anuke.annotations;
import io.anuke.annotations.MethodEntry;
import java.util.ArrayList;
/** Represents a class witha list method entries to include in it. */

View File

@ -1,8 +1,6 @@
package io.anuke.annotations;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.PacketPriority;
import io.anuke.annotations.Annotations.Variant;
import io.anuke.annotations.Annotations.*;
import javax.lang.model.element.ExecutableElement;

View File

@ -1,18 +1,13 @@
package io.anuke.annotations;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.*;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.*;
import javax.tools.Diagnostic.Kind;
import java.util.*;
import java.util.stream.Collectors;
@ -21,14 +16,14 @@ import java.util.stream.Collectors;
/** 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 static final int maxPacketSize = 4096;
/** Warning on top of each autogenerated file.*/
/** Warning on top of each autogenerated file. */
public static final String autogenWarning = "Autogenerated file. Do not modify!\n";
/** Name of the base package to put all the generated classes. */
private static final String packageName = "io.anuke.mindustry.gen";
@ -37,7 +32,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
private static final String readServerName = "RemoteReadServer";
/** Name of class that handles reading and invoking packets on the client. */
private static final String readClientName = "RemoteReadClient";
/**Simple class name of generated class name.*/
/** Simple class name of generated class name. */
private static final String callLocation = "Call";
/** Processing round number. */
@ -115,7 +110,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
//create and add entry
MethodEntry method = new MethodEntry(entry.name, Utils.getMethodName(element), annotation.targets(), annotation.variants(),
annotation.called(), annotation.unreliable(), annotation.forward(), lastMethodID++, (ExecutableElement) element, annotation.priority());
annotation.called(), annotation.unreliable(), annotation.forward(), lastMethodID++, (ExecutableElement)element, annotation.priority());
entry.methods.add(method);
methods.add(method);
@ -140,7 +135,7 @@ public class RemoteMethodAnnotationProcessor extends AbstractProcessor{
TypeSpec.Builder hashBuilder = TypeSpec.classBuilder("MethodHash").addModifiers(Modifier.PUBLIC);
hashBuilder.addJavadoc(autogenWarning);
hashBuilder.addField(FieldSpec.builder(int.class, "HASH", Modifier.STATIC, Modifier.PUBLIC, Modifier.FINAL)
.initializer("$1L", Objects.hash(methods)).build());
.initializer("$1L", Objects.hash(methods)).build());
//build and write resulting hash class
TypeSpec spec = hashBuilder.build();

View File

@ -3,9 +3,7 @@ package io.anuke.annotations;
import com.squareup.javapoet.*;
import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.element.*;
import javax.tools.Diagnostic.Kind;
import java.io.IOException;
import java.lang.reflect.Constructor;
@ -25,24 +23,23 @@ public class RemoteReadGenerator{
/**
* 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.
*/
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);
classBuilder.addJavadoc(RemoteMethodAnnotationProcessor.autogenWarning);
//create main method builder
MethodSpec.Builder readMethod = MethodSpec.methodBuilder("readPacket")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(ByteBuffer.class, "buffer") //buffer to read form
.addParameter(int.class, "id") //ID of method type to read
.returns(void.class);
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(ByteBuffer.class, "buffer") //buffer to read form
.addParameter(int.class, "id") //ID of method type to read
.returns(void.class);
if(needsPlayer){
//since the player type isn't loaded yet, creating a type def is necessary
@ -115,13 +112,13 @@ public class RemoteReadGenerator{
//execute the relevant method before the forward
//if it throws a ValidateException, the method won't be forwarded
readBlock.addStatement("$N." + entry.element.getSimpleName() + "(" + varResult.toString() + ")", ((TypeElement) entry.element.getEnclosingElement()).getQualifiedName().toString());
readBlock.addStatement("$N." + entry.element.getSimpleName() + "(" + varResult.toString() + ")", ((TypeElement)entry.element.getEnclosingElement()).getQualifiedName().toString());
//call forwarded method, don't forward on the client reader
if(entry.forward && entry.where.isServer && needsPlayer){
//call forwarded method
readBlock.addStatement(packageName + "." + entry.className + "." + entry.element.getSimpleName() +
"__forward(player.con.id" + (varResult.length() == 0 ? "" : ", ") + varResult.toString() + ")");
"__forward(player.con.id" + (varResult.length() == 0 ? "" : ", ") + varResult.toString() + ")");
}
readBlock.nextControlFlow("catch (java.lang.Exception e)");

View File

@ -4,10 +4,7 @@ import com.squareup.javapoet.*;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.IOFinder.ClassSerializer;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.element.*;
import javax.tools.Diagnostic.Kind;
import java.io.IOException;
import java.nio.ByteBuffer;
@ -33,7 +30,7 @@ public class RemoteWriteGenerator{
//add temporary write buffer
classBuilder.addField(FieldSpec.builder(ByteBuffer.class, "TEMP_BUFFER", Modifier.STATIC, Modifier.PRIVATE, Modifier.FINAL)
.initializer("ByteBuffer.allocate($1L)", RemoteMethodAnnotationProcessor.maxPacketSize).build());
.initializer("ByteBuffer.allocate($1L)", RemoteMethodAnnotationProcessor.maxPacketSize).build());
//go through each method entry in this class
for(MethodEntry methodEntry : entry.methods){
@ -65,8 +62,8 @@ public class RemoteWriteGenerator{
//create builder
MethodSpec.Builder method = MethodSpec.methodBuilder(elem.getSimpleName().toString() + (forwarded ? "__forward" : "")) //add except suffix when forwarding
.addModifiers(Modifier.STATIC, Modifier.SYNCHRONIZED)
.returns(void.class);
.addModifiers(Modifier.STATIC, Modifier.SYNCHRONIZED)
.returns(void.class);
//forwarded methods aren't intended for use, and are not public
if(!forwarded){
@ -119,7 +116,7 @@ public class RemoteWriteGenerator{
//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();
@ -170,7 +167,7 @@ public class RemoteWriteGenerator{
method.addStatement("TEMP_BUFFER.put(" + varName + " ? (byte)1 : 0)");
}else{
method.addStatement("TEMP_BUFFER.put" +
capName + "(" + varName + ")");
capName + "(" + varName + ")");
}
}else{
//else, try and find a serializer
@ -209,7 +206,7 @@ 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") + ")");
(methodEntry.unreliable ? "io.anuke.mindustry.net.Net.SendMode.udp" : "io.anuke.mindustry.net.Net.SendMode.tcp") + ")");
//end check for server/client
@ -221,7 +218,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

@ -5,13 +5,9 @@ import io.anuke.annotations.Annotations.Serialize;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.element.*;
import javax.lang.model.util.ElementFilter;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Set;
@ -21,7 +17,7 @@ import java.util.Set;
"io.anuke.annotations.Annotations.Serialize"
})
public class SerializeAnnotationProcessor extends AbstractProcessor{
/**Target class name.*/
/** Target class name. */
private static final String className = "Serialization";
/** Name of the base package to put all the generated classes. */
private static final String packageName = "io.anuke.mindustry.gen";
@ -58,8 +54,8 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
classBuilder.addField(jsonType, "bjson", Modifier.STATIC, Modifier.PRIVATE);
classBuilder.addField(ubJsonReaderType, "bjsonReader", Modifier.STATIC, Modifier.PRIVATE);
classBuilder.addStaticBlock(CodeBlock.builder()
.addStatement("bjson = new " + jsonType + "()")
.addStatement("bjsonReader = new " + ubJsonReaderType + "()")
.addStatement("bjson = new " + jsonType + "()")
.addStatement("bjsonReader = new " + ubJsonReaderType + "()")
.build());
for(TypeElement elem : elements){
@ -99,7 +95,8 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
List<VariableElement> fields = ElementFilter.fieldsIn(Utils.elementUtils.getAllMembers(elem));
for(VariableElement field : fields){
if(field.getModifiers().contains(Modifier.STATIC) || field.getModifiers().contains(Modifier.TRANSIENT) || field.getModifiers().contains(Modifier.PRIVATE)) continue;
if(field.getModifiers().contains(Modifier.STATIC) || field.getModifiers().contains(Modifier.TRANSIENT) || field.getModifiers().contains(Modifier.PRIVATE))
continue;
String name = field.getSimpleName().toString();
String typeName = Utils.typeUtils.erasure(field.asType()).toString().replace('$', '.');
@ -109,11 +106,11 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
writeMethod.addStatement("stream.write" + capName + "(object." + name + ")");
readMethod.addStatement("object." + name + "= stream.read" + capName + "()");
jsonWriteMethod.addStatement("json.writeValue(\"" + name + "\", object." + name +")");
jsonWriteMethod.addStatement("json.writeValue(\"" + name + "\", object." + name + ")");
jsonReadMethod.addStatement("if(value.has(\"" + name + "\")) object." + name + "= value.get" + capName + "(\"" + name + "\")");
}else{
writeMethod.addStatement("io.anuke.arc.Core.settings.getSerializer(" + typeName+ ".class).write(stream, object." + name + ")");
readMethod.addStatement("object." + name + " = (" +typeName+")io.anuke.arc.Core.settings.getSerializer(" + typeName+ ".class).read(stream)");
writeMethod.addStatement("io.anuke.arc.Core.settings.getSerializer(" + typeName + ".class).write(stream, object." + name + ")");
readMethod.addStatement("object." + name + " = (" + typeName + ")io.anuke.arc.Core.settings.getSerializer(" + typeName + ".class).read(stream)");
}
}
@ -123,7 +120,7 @@ public class SerializeAnnotationProcessor extends AbstractProcessor{
serializer.addMethod(writeMethod.build());
serializer.addMethod(readMethod.build());
method.addStatement("io.anuke.arc.Core.settings.setSerializer($N, $L)", Utils.elementUtils.getBinaryName(elem).toString().replace('$', '.') + ".class", serializer.build());
method.addStatement("io.anuke.arc.Core.settings.setSerializer($N, $L)", Utils.elementUtils.getBinaryName(elem).toString().replace('$', '.') + ".class", serializer.build());
name(writeMethod, "write" + simpleTypeName);
name(readMethod, "read" + simpleTypeName);

View File

@ -1,28 +1,25 @@
package io.anuke.annotations;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import com.squareup.javapoet.*;
import io.anuke.annotations.Annotations.Struct;
import io.anuke.annotations.Annotations.StructField;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.element.*;
import javax.lang.model.type.TypeKind;
import javax.lang.model.util.ElementFilter;
import javax.tools.Diagnostic.Kind;
import java.util.List;
import java.util.Set;
/**Generates ""value types"" classes that are packed into integer primitives of the most aproppriate size.
* It would be nice if Java didn't make crazy hacks like this necessary.*/
/**
* Generates ""value types"" classes that are packed into integer primitives of the most aproppriate size.
* It would be nice if Java didn't make crazy hacks like this necessary.
*/
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({
"io.anuke.annotations.Annotations.Struct"
"io.anuke.annotations.Annotations.Struct"
})
public class StructAnnotationProcessor extends AbstractProcessor{
/** Name of the base package to put all the generated classes. */
@ -57,7 +54,7 @@ public class StructAnnotationProcessor extends AbstractProcessor{
String structParam = structName.toLowerCase();
TypeSpec.Builder classBuilder = TypeSpec.classBuilder(structName)
.addModifiers(Modifier.FINAL, Modifier.PUBLIC);
.addModifiers(Modifier.FINAL, Modifier.PUBLIC);
try{
List<VariableElement> variables = ElementFilter.fieldsIn(elem.getEnclosedElements());
@ -92,14 +89,14 @@ public class StructAnnotationProcessor extends AbstractProcessor{
//[get] field(structType) : fieldType
MethodSpec.Builder getter = MethodSpec.methodBuilder(var.getSimpleName().toString())
.addModifiers(Modifier.STATIC, Modifier.PUBLIC)
.returns(varType)
.addParameter(structType, structParam);
.addModifiers(Modifier.STATIC, Modifier.PUBLIC)
.returns(varType)
.addParameter(structType, structParam);
//[set] field(structType, fieldType) : structType
MethodSpec.Builder setter = MethodSpec.methodBuilder(var.getSimpleName().toString())
.addModifiers(Modifier.STATIC, Modifier.PUBLIC)
.returns(structType)
.addParameter(structType, structParam).addParameter(varType, "value");
.addModifiers(Modifier.STATIC, Modifier.PUBLIC)
.returns(structType)
.addParameter(structType, structParam).addParameter(varType, "value");
//[getter]
if(varType == TypeName.BOOLEAN){
@ -209,7 +206,7 @@ public class StructAnnotationProcessor extends AbstractProcessor{
throw new IllegalArgumentException("Too many fields, must fit in 64 bits. Curent size: " + size);
}
/**returns a type's element size in bits.*/
/** returns a type's element size in bits. */
static int typeSize(TypeKind kind) throws IllegalArgumentException{
switch(kind){
case BOOLEAN:

View File

@ -14,11 +14,11 @@ public class Utils{
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){
return type.equals("boolean") || type.equals("byte") || type.equals("short") || type.equals("int")
|| type.equals("long") || type.equals("float") || type.equals("double") || type.equals("char");
|| type.equals("long") || type.equals("float") || type.equals("double") || type.equals("char");
}
}

View File

@ -27,7 +27,7 @@ allprojects{
gdxVersion = '1.9.9'
roboVMVersion = '2.3.6'
arcHash = null
debugged = {
return new File(projectDir.parent, '../debug').exists() && !project.hasProperty("release")
}
@ -89,7 +89,8 @@ allprojects{
try{
pfile.createNewFile()
}catch(Exception ignored){}
}catch(Exception ignored){
}
if(pfile.exists()){
props.load(new FileInputStream(pfile))
@ -121,7 +122,7 @@ project(":desktop"){
dependencies{
compile project(":core")
compile project(":net")
if(debugged()) compile project(":debug")
compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
@ -157,9 +158,9 @@ project(":ios"){
compile project(":core")
compile project(":net")
compileOnly project(":annotations")
compile arcModule("backends:backend-robovm")
compile "com.mobidevelop.robovm:robovm-rt:$roboVMVersion"
compile "com.mobidevelop.robovm:robovm-cocoatouch:$roboVMVersion"
compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"

View File

@ -1,8 +1,8 @@
{
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true,
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true
}

View File

@ -1,8 +1,8 @@
{
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 1024,
maxHeight: 1024,
fast: true,
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 1024,
maxHeight: 1024,
fast: true
}

View File

@ -1,8 +1,8 @@
{
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true,
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true
}

View File

@ -1,8 +1,8 @@
{
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 1024,
maxHeight: 1024,
fast: true,
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 1024,
maxHeight: 1024,
fast: true
}

View File

@ -1,8 +1,8 @@
{
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true,
duplicatePadding: true,
combineSubdirectories: true,
flattenPaths: true,
maxWidth: 2048,
maxHeight: 2048,
fast: true
}

View File

@ -615,8 +615,8 @@ block.moss.name = Moss
block.spore-moss.name = Spore Moss
block.shalerocks.name = Shale Rocks
block.scrap-wall.name = Scrap Wall
block.scrap-wall-large.name = Large Scrap Wall
block.scrap-wall-huge.name = Huge Scrap Wall
block.scrap-wall-large.name = Large Scrap Wall
block.scrap-wall-huge.name = Huge Scrap Wall
block.scrap-wall-gigantic.name = Gigantic Scrap Wall
block.thruster.name = Thruster
block.kiln.name = Kiln

View File

@ -14,7 +14,6 @@ screenshot = 화면 캡쳐가 {0} 경로에 저장되었습니다.
gameover = 게임 오버
gameover.pvp = [accent]{0}[] 팀이 승리했습니다!
highscore = [accent]최고점수 달성!
stat.wave = 웨이브 성공:[accent]{0}
stat.enemiesDestroyed = 파괴한 적 수:[accent]{0}
stat.built = 건설한 건물 수:[accent]{0}
@ -22,10 +21,8 @@ stat.destroyed = 파괴된 건물 수:[accent]{0}
stat.deconstructed = 파괴한 건물 수:[accent]{0}
stat.delivered = 획득한 자원:
stat.rank = 최종 기록: [accent]{0}
placeline = 블록을 선택하셨습니다.\n][accent]몇초간 설치 시작지점을 누르고[] 원하는 방향을 향해 드래그 하면 [accent]일렬로[] 설치할 수 있습니다.\n한번 해 보세요.
removearea = 블록 제거모드를 선택하셨습니다.\n[accent]몇초간 제거 시작지점을 누르고[] 원하는 구역 끝을 향해 드래그 하면 [accent]직사각형[] 안에 있는 모든 건물을 제거할 수 있습니다.\n한번 해 보세요.
launcheditems = [accent]출격 아이템
map.delete = 정말로 "[accent]{0}[]" 맵을 삭제하시겠습니까?\n
level.highscore = 최고 점수: [accent]{0}
@ -284,7 +281,6 @@ tutorial = 게임 방법
editor = 편집기
mapeditor = 맵 편집기
donate = 기부
abandon = 포기
abandon.text = 이 구역과 모든 자원이 적에게 빼앗길 것입니다.
locked = 잠김
@ -306,7 +302,6 @@ zone.config.complete = 웨이브 {0} 달성:\n로드아웃 설정 잠금 해제
zone.resources = 자원 감지됨:
add = 추가...
boss.health = 보스 체력
connectfail = [crimson]{0}[accent] 서버에 연결하지 못했습니다.[]
error.unreachable = 서버에 연결하지 못했습니다.\n서버 주소가 정확히 입력되었나요?
error.invalidaddress = 잘못된 주소입니다.
@ -316,7 +311,6 @@ error.alreadyconnected = 이미 접속중입니다.
error.mapnotfound = 맵 파일을 찾을 수 없습니다!
error.io = 네트워크 I/O 오류.
error.any = 알 수 없는 네트워크 오류.
zone.groundZero.name = 그라운드 제로
zone.craters.name = 분화구
zone.frozenForest.name = 얼어붙은 숲
@ -324,7 +318,6 @@ zone.ruinousShores.name = 파멸의 기슭
zone.stainedMountains.name = 얼룩진 산맥
zone.desolateRift.name = 황량한 강
zone.nuclearComplex.name = 핵 생산 단지
settings.language = 언어
settings.reset = 설정 초기화
settings.rebind = 키 재설정
@ -384,7 +377,6 @@ bar.heat = 발열
bar.power = 전력
bar.progress = 건설 진행
bar.spawned = 유닛: {0}/{1}
bullet.damage = [stat]{0}[lightgray] 데미지
bullet.splashdamage = [stat]{0}[lightgray] area 데미지 ~[stat] {1}[lightgray] 타일
bullet.incendiary = [stat]방화
@ -396,7 +388,6 @@ bullet.freezing = [stat]동결
bullet.tarred = [stat]타르
bullet.multiplier = [stat]{0}[lightgray]x 탄약 배율
bullet.reload = [stat]{0}[lightgray]x 사격 속도
unit.blocks = 블록
unit.powersecond = 전력/초
unit.liquidsecond = 액체/초
@ -497,7 +488,6 @@ mode.pvp.description = 실제 플레이어와 PvP를 합니다.
mode.attack.name = 공격
mode.attack.description = 일정 시간마다 적이 오는 단계가 없으며, 적의 기지를 파괴하는 것을 목표로 합니다.
mode.custom = 커스텀 규칙
rules.infiniteresources = 무한 자원
rules.wavetimer = 웨이브 타이머
rules.waves = 웨이브
@ -512,7 +502,6 @@ rules.respawntime = 리스폰 시간:[LIGHT_GRAY] (초)
rules.wavespacing = 웨이브 간격:[LIGHT_GRAY] (초)
rules.buildcostmultiplier = 건설 소모 배율
rules.buildspeedmultiplier = 건설 속도 배율
content.item.name = 아이템
content.liquid.name = 액체
content.unit.name = 유닛
@ -597,7 +586,6 @@ mech.buildspeed = [LIGHT_GRAY]건설 속도: {0}%
liquid.heatcapacity = [LIGHT_GRAY]발열 용량: {0}
liquid.viscosity = [LIGHT_GRAY]점도: {0}
liquid.temperature = [LIGHT_GRAY]온도: {0}
block.grass.name = 잔디
block.salt.name = 소금
block.sandrocks.name = 모래 바위
@ -896,7 +884,6 @@ block.wraith-factory.description = 빠른 뺑소니 요격기 유닛을 생산
block.ghoul-factory.description = 중탄두 폭격기를 생산합니다.
block.dagger-factory.description = 기본 지상 유닛을 생산합니다.
block.titan-factory.description = 첨단 장갑 지상부대를 생산합니다.
block.fortress-factory.description = 중대포 지상부대를 생산합니다.
block.revenant-factory.description = 중량의 레이저 포대를 가진 공중부대를 생산합니다.
block.repair-point.description = 주변에서 가장 가까운 손상된 유닛을 지속적으로 치료합니다.

View File

@ -1,8 +1,6 @@
package io.anuke.mindustry;
import io.anuke.arc.ApplicationCore;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.*;
import io.anuke.arc.util.Log;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.core.*;
@ -55,7 +53,7 @@ public class Mindustry extends ApplicationCore{
int fpsCap = Core.settings.getInt("fpscap", 125);
if(fpsCap <= 120){
long target = (1000 * 1000000)/fpsCap; //target in nanos
long target = (1000 * 1000000) / fpsCap; //target in nanos
long elapsed = Time.timeSinceNanos(lastFrameTime);
if(elapsed < target){
try{

View File

@ -14,12 +14,8 @@ import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.game.GlobalData;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.gen.Serialization;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity;
@ -30,95 +26,95 @@ import java.util.Locale;
@SuppressWarnings("unchecked")
public class Vars{
/**IO buffer size.*/
/** IO buffer size. */
public static final int bufferSize = 8192;
/**global charset*/
/** global charset */
public static final Charset charset = Charset.forName("UTF-8");
/**main application name, capitalized*/
/** main application name, capitalized */
public static final String appName = "Mindustry";
/**URL for itch.io donations.*/
/** URL for itch.io donations. */
public static final String donationURL = "https://anuke.itch.io/mindustry/purchase";
/**URL for discord invite.*/
/** URL for discord invite. */
public static final String discordURL = "https://discord.gg/mindustry";
/**URL for Github API for releases*/
/** URL for Github API for releases */
public static final String releasesURL = "https://api.github.com/repos/Anuken/Mindustry/releases";
/**URL for Github API for contributors*/
/** URL for Github API for contributors */
public static final String contributorsURL = "https://api.github.com/repos/Anuken/Mindustry/contributors";
/**URL for sending crash reports to*/
/** URL for sending crash reports to */
public static final String crashReportURL = "http://mindustry.us.to/report";
/**maximum distance between mine and core that supports automatic transferring*/
/** maximum distance between mine and core that supports automatic transferring */
public static final float mineTransferRange = 220f;
/**team of the player by default*/
/** team of the player by default */
public static final Team defaultTeam = Team.blue;
/**team of the enemy in waves/sectors*/
/** team of the enemy in waves/sectors */
public static final Team waveTeam = Team.red;
/**how many times longer a boss wave takes*/
/** how many times longer a boss wave takes */
public static final float bossWaveMultiplier = 3f;
/**how many times longer a launch wave takes*/
/** how many times longer a launch wave takes */
public static final float launchWaveMultiplier = 2f;
/**max chat message length*/
/** max chat message length */
public static final int maxTextLength = 150;
/**max player name length in bytes*/
/** max player name length in bytes */
public static final int maxNameLength = 40;
/**displayed item size when ingame, TODO remove.*/
/** displayed item size when ingame, TODO remove. */
public static final float itemSize = 5f;
/**extra padding around the world; units outside this bound will begin to self-destruct.*/
/** extra padding around the world; units outside this bound will begin to self-destruct. */
public static final float worldBounds = 100f;
/**units outside of this bound will simply die instantly*/
/** units outside of this bound will simply die instantly */
public static final float finalWorldBounds = worldBounds + 500;
/**ticks spent out of bound until self destruct.*/
public static final float boundsCountdown = 60*7;
/**for map generator dialog*/
/** ticks spent out of bound until self destruct. */
public static final float boundsCountdown = 60 * 7;
/** for map generator dialog */
public static boolean updateEditorOnChange = false;
/**size of tiles in units*/
/** size of tiles in units */
public static final int tilesize = 8;
/**all choosable player colors in join/host dialog*/
/** all choosable player colors in join/host dialog */
public static final Color[] playerColors = {
Color.valueOf("82759a"),
Color.valueOf("c0c1c5"),
Color.valueOf("fff0e7"),
Color.valueOf("7d2953"),
Color.valueOf("ff074e"),
Color.valueOf("ff072a"),
Color.valueOf("ff76a6"),
Color.valueOf("a95238"),
Color.valueOf("ffa108"),
Color.valueOf("feeb2c"),
Color.valueOf("ffcaa8"),
Color.valueOf("008551"),
Color.valueOf("00e339"),
Color.valueOf("423c7b"),
Color.valueOf("4b5ef1"),
Color.valueOf("2cabfe"),
Color.valueOf("82759a"),
Color.valueOf("c0c1c5"),
Color.valueOf("fff0e7"),
Color.valueOf("7d2953"),
Color.valueOf("ff074e"),
Color.valueOf("ff072a"),
Color.valueOf("ff76a6"),
Color.valueOf("a95238"),
Color.valueOf("ffa108"),
Color.valueOf("feeb2c"),
Color.valueOf("ffcaa8"),
Color.valueOf("008551"),
Color.valueOf("00e339"),
Color.valueOf("423c7b"),
Color.valueOf("4b5ef1"),
Color.valueOf("2cabfe"),
};
/**default server port*/
/** default server port */
public static final int port = 6567;
/**if true, UI is not drawn*/
/** if true, UI is not drawn */
public static boolean disableUI;
/**if true, game is set up in mobile mode, even on desktop. used for debugging*/
/** if true, game is set up in mobile mode, even on desktop. used for debugging */
public static boolean testMobile;
/**whether the game is running on a mobile device*/
/** whether the game is running on a mobile device */
public static boolean mobile;
/**whether the game is running on an iOS device*/
/** whether the game is running on an iOS device */
public static boolean ios;
/**whether the game is running on an Android device*/
/** whether the game is running on an Android device */
public static boolean android;
/**whether the game is running on a headless server*/
/** whether the game is running on a headless server */
public static boolean headless;
/**application data directory, equivalent to {@link io.anuke.arc.Settings#getDataDirectory()}*/
/** application data directory, equivalent to {@link io.anuke.arc.Settings#getDataDirectory()} */
public static FileHandle dataDirectory;
/**data subdirectory used for screenshots*/
/** data subdirectory used for screenshots */
public static FileHandle screenshotDirectory;
/**data subdirectory used for custom mmaps*/
/** data subdirectory used for custom mmaps */
public static FileHandle customMapDirectory;
/**data subdirectory used for saves*/
/** data subdirectory used for saves */
public static FileHandle saveDirectory;
/**map file extension*/
/** map file extension */
public static final String mapExtension = "mmap";
/**save file extension*/
/** save file extension */
public static final String saveExtension = "msav";
/**list of all locales that can be switched to*/
/** list of all locales that can be switched to */
public static Locale[] locales;
public static ContentLoader content;
@ -143,7 +139,7 @@ public class Vars{
public static EntityGroup<Fire> fireGroup;
public static EntityGroup<BaseUnit>[] unitGroups;
/**all local players, currently only has one player. may be used for local co-op in the future*/
/** all local players, currently only has one player. may be used for local co-op in the future */
public static Player player;
public static void init(){

View File

@ -17,31 +17,31 @@ import io.anuke.mindustry.world.meta.BlockFlag;
import static io.anuke.mindustry.Vars.*;
/**Class used for indexing special target blocks for AI.*/
/** Class used for indexing special target blocks for AI. */
@SuppressWarnings("unchecked")
public class BlockIndexer{
/**Size of one ore quadrant.*/
/** Size of one ore quadrant. */
private final static int oreQuadrantSize = 20;
/**Size of one structure quadrant.*/
/** Size of one structure quadrant. */
private final static int structQuadrantSize = 12;
/**Set of all ores that are being scanned.*/
/** Set of all ores that are being scanned. */
private final ObjectSet<Item> scanOres = ObjectSet.with(Item.getAllOres().toArray(Item.class));
private final ObjectSet<Item> itemSet = new ObjectSet<>();
/**Stores all ore quadtrants on the map.*/
/** Stores all ore quadtrants on the map. */
private ObjectMap<Item, ObjectSet<Tile>> ores;
/**Tags all quadrants.*/
/** Tags all quadrants. */
private Bits[] structQuadrants;
/**Stores all damaged tile entities by team.*/
/** Stores all damaged tile entities by team. */
private ObjectSet<Tile>[] damagedTiles = new ObjectSet[Team.all.length];
/**Maps teams to a map of flagged tiles by type.*/
/** Maps teams to a map of flagged tiles by type. */
private ObjectSet<Tile>[][] flagMap = new ObjectSet[Team.all.length][BlockFlag.all.length];
/**Maps tile positions to their last known tile index data.*/
/** Maps tile positions to their last known tile index data. */
private IntMap<TileIndex> typeMap = new IntMap<>();
/**Empty set used for returning.*/
/** Empty set used for returning. */
private ObjectSet<Tile> emptySet = new ObjectSet<>();
/**Array used for returning and reusing.*/
/** Array used for returning and reusing. */
private Array<Tile> returnArray = new Array<>();
public BlockIndexer(){
@ -72,7 +72,7 @@ public class BlockIndexer{
//create bitset for each team type that contains each quadrant
structQuadrants = new Bits[Team.all.length];
for(int i = 0; i < Team.all.length; i++){
structQuadrants[i] = new Bits(Mathf.ceil(world.width() / (float) structQuadrantSize) * Mathf.ceil(world.height() / (float) structQuadrantSize));
structQuadrants[i] = new Bits(Mathf.ceil(world.width() / (float)structQuadrantSize) * Mathf.ceil(world.height() / (float)structQuadrantSize));
}
for(int x = 0; x < world.width(); x++){
@ -101,7 +101,7 @@ public class BlockIndexer{
return flagMap[team.ordinal()];
}
/**Returns all damaged tiles by team.*/
/** Returns all damaged tiles by team. */
public ObjectSet<Tile> getDamaged(Team team){
returnArray.clear();
@ -123,12 +123,12 @@ public class BlockIndexer{
return set;
}
/**Get all allied blocks with a flag.*/
/** Get all allied blocks with a flag. */
public ObjectSet<Tile> getAllied(Team team, BlockFlag type){
return flagMap[team.ordinal()][type.ordinal()];
}
/**Get all enemy blocks with a flag.*/
/** Get all enemy blocks with a flag. */
public Array<Tile> getEnemy(Team team, BlockFlag type){
returnArray.clear();
for(Team enemy : state.teams.enemiesOf(team)){
@ -154,8 +154,8 @@ public class BlockIndexer{
TileEntity closest = null;
float dst = 0;
for(int rx = Math.max((int) ((x - range) / tilesize / structQuadrantSize), 0); rx <= (int) ((x + range) / tilesize / structQuadrantSize) && rx < quadWidth(); rx++){
for(int ry = Math.max((int) ((y - range) / tilesize / structQuadrantSize), 0); ry <= (int) ((y + range) / tilesize / structQuadrantSize) && ry < quadHeight(); ry++){
for(int rx = Math.max((int)((x - range) / tilesize / structQuadrantSize), 0); rx <= (int)((x + range) / tilesize / structQuadrantSize) && rx < quadWidth(); rx++){
for(int ry = Math.max((int)((y - range) / tilesize / structQuadrantSize), 0); ry <= (int)((y + range) / tilesize / structQuadrantSize) && ry < quadHeight(); ry++){
if(!getQuad(team, rx, ry)) continue;
@ -167,7 +167,8 @@ public class BlockIndexer{
other = other.target();
if(other.entity == null || other.getTeam() != team || !pred.test(other) || !other.block().targetable) continue;
if(other.entity == null || other.getTeam() != team || !pred.test(other) || !other.block().targetable)
continue;
TileEntity e = other.entity;
@ -194,7 +195,7 @@ public class BlockIndexer{
return ores.get(item, emptySet);
}
/**Find the closest ore block relative to a position.*/
/** Find the closest ore block relative to a position. */
public Tile findClosestOre(float xp, float yp, Item item){
Tile tile = Geometry.findClosest(xp, yp, world.indexer.getOrePositions(item));
@ -214,7 +215,7 @@ public class BlockIndexer{
private void process(Tile tile){
if(tile.block().flags.size() > 0 &&
tile.getTeam() != Team.none){
tile.getTeam() != Team.none){
ObjectSet<Tile>[] map = getFlagged(tile.getTeam());
for(BlockFlag flag : tile.block().flags){
@ -235,13 +236,13 @@ public class BlockIndexer{
itemSet.clear();
Tile rounded = world.tile(Mathf.clamp(quadrantX * oreQuadrantSize + oreQuadrantSize / 2, 0, world.width() - 1),
Mathf.clamp(quadrantY * oreQuadrantSize + oreQuadrantSize / 2, 0, world.height() - 1));
Mathf.clamp(quadrantY * oreQuadrantSize + oreQuadrantSize / 2, 0, world.height() - 1));
//find all items that this quadrant contains
for(int x = quadrantX * structQuadrantSize; x < world.width() && x < (quadrantX + 1) * structQuadrantSize; x++){
for(int y = quadrantY * structQuadrantSize; y < world.height() && y < (quadrantY + 1) * structQuadrantSize; y++){
Tile result = world.tile(x, y);
if( result == null || result.drop() == null || !scanOres.contains(result.drop())) continue;
if(result == null || result.drop() == null || !scanOres.contains(result.drop())) continue;
itemSet.add(result.drop());
}
@ -294,16 +295,16 @@ public class BlockIndexer{
}
private boolean getQuad(Team team, int quadrantX, int quadrantY){
int index = quadrantX + quadrantY * Mathf.ceil(world.width() / (float) structQuadrantSize);
int index = quadrantX + quadrantY * Mathf.ceil(world.width() / (float)structQuadrantSize);
return structQuadrants[team.ordinal()].get(index);
}
private int quadWidth(){
return Mathf.ceil(world.width() / (float) structQuadrantSize);
return Mathf.ceil(world.width() / (float)structQuadrantSize);
}
private int quadHeight(){
return Mathf.ceil(world.height() / (float) structQuadrantSize);
return Mathf.ceil(world.height() / (float)structQuadrantSize);
}
private void scanOres(){
@ -324,9 +325,9 @@ public class BlockIndexer{
//add position of quadrant to list when an ore is found
if(tile.drop() != null && scanOres.contains(tile.drop()) && tile.block() == Blocks.air){
ores.get(tile.drop()).add(world.tile(
//make sure to clamp quadrant middle position, since it might go off bounds
Mathf.clamp(qx * oreQuadrantSize + oreQuadrantSize / 2, 0, world.width() - 1),
Mathf.clamp(qy * oreQuadrantSize + oreQuadrantSize / 2, 0, world.height() - 1)));
//make sure to clamp quadrant middle position, since it might go off bounds
Mathf.clamp(qx * oreQuadrantSize + oreQuadrantSize / 2, 0, world.width() - 1),
Mathf.clamp(qy * oreQuadrantSize + oreQuadrantSize / 2, 0, world.height() - 1)));
}
}
}

View File

@ -65,9 +65,9 @@ public class Pathfinder{
Tile other = world.tile(dx, dy);
if(other == null) continue;
if(values[dx][dy] < value && (target == null || values[dx][dy]< tl) &&
!other.solid() &&
!(point.x != 0 && point.y != 0 && (world.solid(tile.x + point.x, tile.y) || world.solid(tile.x, tile.y + point.y)))){ //diagonal corner trap
if(values[dx][dy] < value && (target == null || values[dx][dy] < tl) &&
!other.solid() &&
!(point.x != 0 && point.y != 0 && (world.solid(tile.x + point.x, tile.y) || world.solid(tile.x, tile.y + point.y)))){ //diagonal corner trap
target = other;
tl = values[dx][dy];
}
@ -86,8 +86,10 @@ public class Pathfinder{
return (!tile.solid()) || (tile.breakable() && (tile.target().getTeam() != team));
}
/**Clears the frontier, increments the search and sets up all flow sources.
* This only occurs for active teams.*/
/**
* Clears the frontier, increments the search and sets up all flow sources.
* This only occurs for active teams.
*/
private void update(Tile tile, Team team){
//make sure team exists
if(paths != null && paths[team.ordinal()] != null && paths[team.ordinal()].weights != null){
@ -126,7 +128,7 @@ public class Pathfinder{
Tile tile = world.tile(x, y);
if(state.teams.areEnemies(tile.getTeam(), team)
&& tile.block().flags.contains(BlockFlag.target)){
&& tile.block().flags.contains(BlockFlag.target)){
path.frontier.addFirst(tile.pos());
path.weights[x][y] = 0;
path.searches[x][y] = (short)path.search;
@ -162,7 +164,7 @@ public class Pathfinder{
Tile other = world.tile(dx, dy);
if(other != null && (path.weights[dx][dy] > cost + other.cost || path.searches[dx][dy] < path.search)
&& passable(other, team)){
&& passable(other, team)){
if(other.cost < 0) throw new IllegalArgumentException("Tile cost cannot be negative! " + other);
path.frontier.addFirst(Pos.get(dx, dy));
path.weights[dx][dy] = cost + other.cost;

View File

@ -16,9 +16,7 @@ import io.anuke.mindustry.game.SpawnGroup;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.Pos;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.*;
@ -56,7 +54,7 @@ public class WaveSpawner{
return groundSpawns.size;
}
/**@return true if the player is near a ground spawn point.*/
/** @return true if the player is near a ground spawn point. */
public boolean playerNear(){
return groundSpawns.count(g -> Mathf.dst(g.x * tilesize, g.y * tilesize, player.x, player.y) < maxShockwaveDst) > 0;
}
@ -88,7 +86,7 @@ public class WaveSpawner{
for(GroundSpawn spawn : groundSpawns){
spawnX = spawn.x * tilesize;
spawnY = spawn.y * tilesize;
spread = tilesize*2;
spread = tilesize * 2;
for(int i = 0; i < spawned; i++){
Tmp.v1.rnd(spread);
@ -96,7 +94,7 @@ public class WaveSpawner{
BaseUnit unit = group.createUnit(waveTeam);
unit.set(spawnX + Tmp.v1.x, spawnY + Tmp.v1.y);
Time.run(Math.min(i*5, 60*2), () -> shockwave(unit));
Time.run(Math.min(i * 5, 60 * 2), () -> shockwave(unit));
}
Time.run(20f, () -> Effects.effect(Fx.spawnShockwave, spawn.x * tilesize, spawn.y * tilesize));
//would be interesting to see player structures survive this without hacks
@ -125,7 +123,7 @@ public class WaveSpawner{
//hide spawnpoints, they have served their purpose
world.tile(x, y).setBlock(Blocks.air);
Log.info("Add spawn "+ x + " " + y);
Log.info("Add spawn " + x + " " + y);
}
}
}
@ -145,7 +143,7 @@ public class WaveSpawner{
groundSpawns.add(spawn);
FlyerSpawn fspawn = new FlyerSpawn();
fspawn.angle = Angles.angle(world.width()/2f, world.height()/2f, x, y);
fspawn.angle = Angles.angle(world.width() / 2f, world.height() / 2f, x, y);
flySpawns.add(fspawn);
}

View File

@ -2,18 +2,12 @@ package io.anuke.mindustry.content;
import io.anuke.arc.Core;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.TextureRegion;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.graphics.CacheLayer;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.graphics.Shaders;
import io.anuke.mindustry.type.Category;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.LiquidStack;
import io.anuke.mindustry.graphics.*;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.*;
@ -23,13 +17,8 @@ import io.anuke.mindustry.world.blocks.distribution.*;
import io.anuke.mindustry.world.blocks.power.*;
import io.anuke.mindustry.world.blocks.production.*;
import io.anuke.mindustry.world.blocks.sandbox.*;
import io.anuke.mindustry.world.blocks.storage.CoreBlock;
import io.anuke.mindustry.world.blocks.storage.LaunchPad;
import io.anuke.mindustry.world.blocks.storage.Unloader;
import io.anuke.mindustry.world.blocks.storage.Vault;
import io.anuke.mindustry.world.blocks.units.MechPad;
import io.anuke.mindustry.world.blocks.units.RepairPoint;
import io.anuke.mindustry.world.blocks.units.UnitFactory;
import io.anuke.mindustry.world.blocks.storage.*;
import io.anuke.mindustry.world.blocks.units.*;
import io.anuke.mindustry.world.consumers.ConsumeLiquidFilter;
import io.anuke.mindustry.world.meta.Attribute;
import io.anuke.mindustry.world.modules.LiquidModule;
@ -91,15 +80,25 @@ public class Blocks implements ContentList{
public void load(){
//region environment
air = new Floor("air"){{
air = new Floor("air"){
{
alwaysReplace = true;
hasShadow = false;
}
public void draw(Tile tile){}
public void load(){}
public void init(){}
public boolean isHidden(){ return true; }
public void draw(Tile tile){
}
public void load(){
}
public void init(){
}
public boolean isHidden(){
return true;
}
public TextureRegion[] variantRegions(){
if(variantRegions == null){
variantRegions = new TextureRegion[]{Core.atlas.find("clear")};
@ -111,7 +110,8 @@ public class Blocks implements ContentList{
part = new BlockPart();
spawn = new Block("spawn"){
public void drawShadow(Tile tile){}
public void drawShadow(Tile tile){
}
};
//Registers build blocks from size 1-6
@ -593,10 +593,10 @@ public class Blocks implements ContentList{
separator = new Separator("separator"){{
requirements(Category.crafting, ItemStack.with(Items.copper, 60, Items.titanium, 50));
results = ItemStack.with(
Items.copper, 5,
Items.lead, 3,
Items.graphite, 2,
Items.titanium, 2
Items.copper, 5,
Items.lead, 3,
Items.graphite, 2,
Items.titanium, 2
);
hasPower = true;
craftTime = 35f;
@ -630,7 +630,7 @@ public class Blocks implements ContentList{
}
int liquidRegion = reg("-liquid");
int topRegion =reg("-top");
int topRegion = reg("-top");
drawIcons = () -> new TextureRegion[]{Core.atlas.find(name), Core.atlas.find(name + "-top")};
@ -638,7 +638,7 @@ public class Blocks implements ContentList{
GenericCrafterEntity entity = tile.entity();
Draw.rect(region, tile.drawx(), tile.drawy());
Draw.rect(reg(frameRegions[(int) Mathf.absin(entity.totalProgress, 5f, 2.999f)]), tile.drawx(), tile.drawy());
Draw.rect(reg(frameRegions[(int)Mathf.absin(entity.totalProgress, 5f, 2.999f)]), tile.drawx(), tile.drawy());
Draw.color(Color.CLEAR, tile.entity.liquids.current().color, tile.entity.liquids.total() / liquidCapacity);
Draw.rect(reg(liquidRegion), tile.drawx(), tile.drawy());
Draw.color();
@ -1244,10 +1244,10 @@ public class Blocks implements ContentList{
duo = new DoubleTurret("duo"){{
requirements(Category.turret, ItemStack.with(Items.copper, 70), true);
ammo(
Items.copper, Bullets.standardCopper,
Items.graphite, Bullets.standardDense,
Items.pyratite, Bullets.standardIncendiary,
Items.silicon, Bullets.standardHoming
Items.copper, Bullets.standardCopper,
Items.graphite, Bullets.standardDense,
Items.pyratite, Bullets.standardIncendiary,
Items.silicon, Bullets.standardHoming
);
reload = 20f;
restitution = 0.03f;
@ -1262,8 +1262,8 @@ public class Blocks implements ContentList{
scatter = new BurstTurret("scatter"){{
requirements(Category.turret, ItemStack.with(Items.copper, 170, Items.lead, 90));
ammo(
Items.scrap, Bullets.flakScrap,
Items.lead, Bullets.flakLead
Items.scrap, Bullets.flakScrap,
Items.lead, Bullets.flakLead
);
reload = 15f;
range = 180f;
@ -1277,14 +1277,14 @@ public class Blocks implements ContentList{
inaccuracy = 17f;
shootCone = 35f;
health = 260*size*size;
health = 260 * size * size;
}};
scorch = new ItemTurret("scorch"){{
requirements(Category.turret, ItemStack.with(Items.copper, 50, Items.graphite, 45));
ammo(
Items.coal, Bullets.basicFlame,
Items.pyratite, Bullets.pyraFlame
Items.coal, Bullets.basicFlame,
Items.pyratite, Bullets.pyraFlame
);
recoil = 0f;
reload = 4f;
@ -1298,9 +1298,9 @@ public class Blocks implements ContentList{
hail = new ArtilleryTurret("hail"){{
requirements(Category.turret, ItemStack.with(Items.copper, 80, Items.graphite, 35));
ammo(
Items.graphite, Bullets.artilleryDense,
Items.silicon, Bullets.artilleryHoming,
Items.pyratite, Bullets.artlleryIncendiary
Items.graphite, Bullets.artilleryDense,
Items.silicon, Bullets.artilleryHoming,
Items.pyratite, Bullets.artlleryIncendiary
);
reload = 60f;
recoil = 2f;
@ -1313,10 +1313,10 @@ public class Blocks implements ContentList{
wave = new LiquidTurret("wave"){{
requirements(Category.turret, ItemStack.with(Items.metaglass, 90, Items.lead, 150));
ammo(
Liquids.water, Bullets.waterShot,
Liquids.slag, Bullets.slagShot,
Liquids.cryofluid, Bullets.cryoShot,
Liquids.oil, Bullets.oilShot
Liquids.water, Bullets.waterShot,
Liquids.slag, Bullets.slagShot,
Liquids.cryofluid, Bullets.cryoShot,
Liquids.oil, Bullets.oilShot
);
size = 2;
recoil = 0f;
@ -1325,7 +1325,7 @@ public class Blocks implements ContentList{
shootCone = 50f;
shootEffect = Fx.shootLiquid;
range = 110f;
health = 250*size*size;
health = 250 * size * size;
drawer = (tile, entity) -> {
Draw.rect(region, tile.drawx() + tr2.x, tile.drawy() + tr2.y, entity.rotation - 90);
@ -1356,7 +1356,7 @@ public class Blocks implements ContentList{
chargeBeginEffect = Fx.lancerLaserChargeBegin;
heatColor = Color.RED;
size = 2;
health = 280*size*size;
health = 280 * size * size;
targetAir = false;
}};
@ -1380,9 +1380,9 @@ public class Blocks implements ContentList{
swarmer = new BurstTurret("swarmer"){{
requirements(Category.turret, ItemStack.with(Items.graphite, 70, Items.titanium, 70, Items.plastanium, 90, Items.silicon, 60));
ammo(
Items.blastCompound, Bullets.missileExplosive,
Items.pyratite, Bullets.missileIncendiary,
Items.surgealloy, Bullets.missileSurge
Items.blastCompound, Bullets.missileExplosive,
Items.pyratite, Bullets.missileIncendiary,
Items.surgealloy, Bullets.missileSurge
);
reload = 50f;
shots = 4;
@ -1391,17 +1391,17 @@ public class Blocks implements ContentList{
range = 140f;
xRand = 6f;
size = 2;
health = 300*size*size;
health = 300 * size * size;
}};
salvo = new BurstTurret("salvo"){{
requirements(Category.turret, ItemStack.with(Items.copper, 210, Items.graphite, 190, Items.titanium, 120));
ammo(
Items.copper, Bullets.standardCopper,
Items.graphite, Bullets.standardDense,
Items.pyratite, Bullets.standardIncendiary,
Items.silicon, Bullets.standardHoming,
Items.thorium, Bullets.standardThorium
Items.copper, Bullets.standardCopper,
Items.graphite, Bullets.standardDense,
Items.pyratite, Bullets.standardIncendiary,
Items.silicon, Bullets.standardHoming,
Items.thorium, Bullets.standardThorium
);
size = 2;
@ -1421,11 +1421,11 @@ public class Blocks implements ContentList{
ripple = new ArtilleryTurret("ripple"){{
requirements(Category.turret, ItemStack.with(Items.copper, 300, Items.graphite, 270, Items.titanium, 120));
ammo(
Items.graphite, Bullets.artilleryDense,
Items.silicon, Bullets.artilleryHoming,
Items.pyratite, Bullets.artlleryIncendiary,
Items.blastCompound, Bullets.artilleryExplosive,
Items.plastanium, Bullets.arilleryPlastic
Items.graphite, Bullets.artilleryDense,
Items.silicon, Bullets.artilleryHoming,
Items.pyratite, Bullets.artlleryIncendiary,
Items.blastCompound, Bullets.artilleryExplosive,
Items.plastanium, Bullets.arilleryPlastic
);
size = 3;
shots = 4;
@ -1446,9 +1446,9 @@ public class Blocks implements ContentList{
cyclone = new ItemTurret("cyclone"){{
requirements(Category.turret, ItemStack.with(Items.copper, 400, Items.titanium, 250, Items.plastanium, 160));
ammo(
Items.blastCompound, Bullets.flakExplosive,
Items.plastanium, Bullets.flakPlastic,
Items.surgealloy, Bullets.flakSurge
Items.blastCompound, Bullets.flakExplosive,
Items.plastanium, Bullets.flakPlastic,
Items.surgealloy, Bullets.flakSurge
);
xRand = 4f;
reload = 6f;
@ -1478,9 +1478,9 @@ public class Blocks implements ContentList{
spectre = new DoubleTurret("spectre"){{
requirements(Category.turret, ItemStack.with(Items.copper, 700, Items.graphite, 600, Items.surgealloy, 500, Items.plastanium, 350, Items.thorium, 500));
ammo(
Items.graphite, Bullets.standardDenseBig,
Items.pyratite, Bullets.standardIncendiaryBig,
Items.thorium, Bullets.standardThoriumBig
Items.graphite, Bullets.standardDenseBig,
Items.pyratite, Bullets.standardIncendiaryBig,
Items.thorium, Bullets.standardThoriumBig
);
reload = 6f;
coolantMultiplier = 0.5f;

View File

@ -1,20 +1,15 @@
package io.anuke.mindustry.content;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.CapStyle;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.entities.Damage;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.bullet.*;
import io.anuke.mindustry.entities.effect.Fire;
import io.anuke.mindustry.entities.effect.Lightning;
import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.entities.effect.*;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.graphics.Shapes;
@ -37,7 +32,7 @@ public class Bullets implements ContentList{
//standard
standardCopper, standardDense, standardThorium, standardHoming, standardIncendiary, standardMechSmall,
standardGlaive, standardDenseBig, standardThoriumBig, standardIncendiaryBig,
standardGlaive, standardDenseBig, standardThoriumBig, standardIncendiaryBig,
//electric
lancerLaser, meltdownLaser, lightning, arc, damageLightning,
@ -562,7 +557,7 @@ public class Bullets implements ContentList{
public void hit(Bullet b, float hitx, float hity){
Effects.effect(hitEffect, colors[2], hitx, hity);
if(Mathf.chance(0.4)){
Fire.create(world.tileWorld(hitx+Mathf.range(5f), hity+Mathf.range(5f)));
Fire.create(world.tileWorld(hitx + Mathf.range(5f), hity + Mathf.range(5f)));
}
}
@ -586,6 +581,7 @@ public class Bullets implements ContentList{
fuseShot = new BulletType(0.01f, 70){
int rays = 3;
float rayLength = 80f;
{
hitEffect = Fx.hitFuse;
lifetime = 13f;
@ -594,23 +590,23 @@ public class Bullets implements ContentList{
}
@Override
public void init(Bullet b) {
for (int i = 0; i < rays; i++) {
Damage.collideLine(b, b.getTeam(), hitEffect, b.x, b.y, b.rot(), rayLength - Math.abs(i - (rays/2))*20f);
public void init(Bullet b){
for(int i = 0; i < rays; i++){
Damage.collideLine(b, b.getTeam(), hitEffect, b.x, b.y, b.rot(), rayLength - Math.abs(i - (rays / 2)) * 20f);
}
}
@Override
public void draw(Bullet b) {
public void draw(Bullet b){
super.draw(b);
Draw.color(Color.WHITE, Pal.surge, b.fin());
for(int i = 0; i < 7; i++){
Tmp.v1.trns(b.rot(), i * 8f);
float sl = Mathf.clamp(b.fout()-0.5f) * (80f - i *10);
float sl = Mathf.clamp(b.fout() - 0.5f) * (80f - i * 10);
Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() + 90);
Shapes.tri(b.x + Tmp.v1.x, b.y + Tmp.v1.y, 4f, sl, b.rot() - 90);
}
Shapes.tri(b.x, b.y, 13f, (rayLength+50) * b.fout(), b.rot());
Shapes.tri(b.x, b.y, 13f, (rayLength + 50) * b.fout(), b.rot());
Shapes.tri(b.x, b.y, 13f, 10f * b.fout(), b.rot() + 180f);
Draw.reset();
}
@ -665,14 +661,16 @@ public class Bullets implements ContentList{
}
};
arc = new BulletType(0.001f, 25){{
arc = new BulletType(0.001f, 25){
{
lifetime = 1;
despawnEffect = Fx.none;
hitEffect = Fx.hitLancer;
}
@Override
public void draw(Bullet b){}
public void draw(Bullet b){
}
@Override
public void init(Bullet b){
@ -709,7 +707,8 @@ public class Bullets implements ContentList{
incendSpread = 10f;
}};
bombOil = new BombBulletType(2f, 3f, "shell"){{
bombOil = new BombBulletType(2f, 3f, "shell"){
{
bulletWidth = 8f;
bulletHeight = 12f;
hitEffect = Fx.pulverize;
@ -728,7 +727,8 @@ public class Bullets implements ContentList{
}
};
explode = new BombBulletType(2f, 3f, "clear"){{
explode = new BombBulletType(2f, 3f, "clear"){
{
hitEffect = Fx.pulverize;
lifetime = 23f;
speed = 1f;

View File

@ -2,9 +2,7 @@ package io.anuke.mindustry.content;
import io.anuke.arc.Core;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Tmp;
@ -39,18 +37,19 @@ public class Fx implements ContentList{
@Override
public void load(){
none = new Effect(0, 0f, e -> {});
none = new Effect(0, 0f, e -> {
});
unitSpawn = new Effect(30f, e -> {
if(!(e.data instanceof BaseUnit)) return;
Draw.alpha(e.fin());
float scl = 1f + e.fout()*2f;
float scl = 1f + e.fout() * 2f;
BaseUnit unit = (BaseUnit)e.data;
Draw.rect(unit.getIconRegion(), e.x, e.y,
unit.getIconRegion().getWidth() * Draw.scl * scl, unit.getIconRegion().getWidth() * Draw.scl * scl, 180f);
unit.getIconRegion().getWidth() * Draw.scl * scl, unit.getIconRegion().getWidth() * Draw.scl * scl, 180f);
Draw.reset();
});
@ -74,7 +73,7 @@ public class Fx implements ContentList{
Lines.stroke(3f - e.fin() * 2f);
Lines.square(e.x, e.y, tilesize / 2f * e.rotation + e.fin() * 3f);
Angles.randLenVectors(e.id, 3 + (int) (e.rotation * 3), e.rotation * 2f + (tilesize * e.rotation) * e.finpow(), (x, y) -> {
Angles.randLenVectors(e.id, 3 + (int)(e.rotation * 3), e.rotation * 2f + (tilesize * e.rotation) * e.finpow(), (x, y) -> {
Fill.square(e.x + x, e.y + y, 1f + e.fout() * (3f + e.rotation));
});
Draw.reset();
@ -113,7 +112,7 @@ public class Fx implements ContentList{
Lines.poly(e.x, e.y, 4, 5f + e.fin() * 60f);
Draw.reset();
});
vtolHover = new Effect(40f, e -> {
float len = e.finpow() * 10f;
float ang = e.rotation + Mathf.randomSeedRange(e.id, 30f);
@ -179,7 +178,7 @@ public class Fx implements ContentList{
e.scaled(7f, s -> {
Lines.stroke(0.5f + s.fout());
Lines.circle(e.x, e.y, s.fin()*5f);
Lines.circle(e.x, e.y, s.fin() * 5f);
});
@ -198,7 +197,7 @@ public class Fx implements ContentList{
e.scaled(7f, s -> {
Lines.stroke(0.5f + s.fout());
Lines.circle(e.x, e.y, s.fin()*7f);
Lines.circle(e.x, e.y, s.fin() * 7f);
});
@ -273,7 +272,7 @@ public class Fx implements ContentList{
hitLaser = new Effect(8, e -> {
Draw.color(Color.WHITE, Pal.heal, e.fin());
Lines.stroke(0.5f + e.fout());
Lines.circle(e.x, e.y, e.fin()*5f);
Lines.circle(e.x, e.y, e.fin() * 5f);
Draw.reset();
});
@ -539,7 +538,7 @@ public class Fx implements ContentList{
Draw.color(Pal.accent);
Angles.randLenVectors(e.id, 2, 1f + e.fin() * 2f, (x, y) -> {
Fill.square(e.x + x, e.y + y, e.fout() * 2.3f+0.5f);
Fill.square(e.x + x, e.y + y, e.fout() * 2.3f + 0.5f);
});
Draw.color();
@ -549,7 +548,7 @@ public class Fx implements ContentList{
float length = 20f * e.finpow();
float size = 7f * e.fout();
Draw.rect(((Item) e.data).icon(Icon.large), e.x + Angles.trnsx(e.rotation, length), e.y + Angles.trnsy(e.rotation, length), size, size);
Draw.rect(((Item)e.data).icon(Icon.large), e.x + Angles.trnsx(e.rotation, length), e.y + Angles.trnsy(e.rotation, length), size, size);
});
@ -614,23 +613,23 @@ public class Fx implements ContentList{
dynamicExplosion = new Effect(30, e -> {
float intensity = e.rotation;
e.scaled(5 + intensity*2, i -> {
e.scaled(5 + intensity * 2, i -> {
Lines.stroke(3.1f * i.fout());
Lines.poly(e.x, e.y, (int)(20 * intensity), (3f + i.fin() * 14f) * intensity);
});
Draw.color(Color.GRAY);
Angles.randLenVectors(e.id, e.finpow(), (int)(6 * intensity), 21f*intensity, (x, y, in, out) -> {
Fill.circle(e.x + x, e.y + y, out * (2f+intensity) * 3 + 0.5f);
Angles.randLenVectors(e.id, e.finpow(), (int)(6 * intensity), 21f * intensity, (x, y, in, out) -> {
Fill.circle(e.x + x, e.y + y, out * (2f + intensity) * 3 + 0.5f);
Fill.circle(e.x + x / 2f, e.y + y / 2f, out * (intensity) * 3);
});
Draw.color(Pal.lighterOrange, Pal.lightOrange, Color.GRAY, e.fin());
Lines.stroke((1.7f * e.fout()) * (1f + (intensity - 1f) / 2f));
Angles.randLenVectors(e.id + 1, e.finpow(), (int)(9*intensity), 40f*intensity, (x, y, in, out) -> {
Lines.lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (3f+intensity));
Angles.randLenVectors(e.id + 1, e.finpow(), (int)(9 * intensity), 40f * intensity, (x, y, in, out) -> {
Lines.lineAngle(e.x + x, e.y + y, Mathf.angle(x, y), 1f + out * 4 * (3f + intensity));
});
Draw.reset();
@ -772,8 +771,8 @@ public class Fx implements ContentList{
float len = (2f + e.finpow() * 6f) * i;
float lr = rot + e.fin() * 30f * i;
Fill.rect(e.x + Angles.trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()),
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
1f, 2f, rot + e.fin() * 50f * i);
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
1f, 2f, rot + e.fin() * 50f * i);
Draw.color();
});
@ -785,9 +784,9 @@ public class Fx implements ContentList{
float len = (2f + e.finpow() * 10f) * i;
float lr = rot + e.fin() * 20f * i;
Draw.rect(Core.atlas.find("casing"),
e.x + Angles.trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()),
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
2f, 3f, rot);
e.x + Angles.trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()),
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
2f, 3f, rot);
}
Draw.color(Color.LIGHT_GRAY, Color.GRAY, e.fin());
@ -808,10 +807,10 @@ public class Fx implements ContentList{
float len = (4f + e.finpow() * 8f) * i;
float lr = rot + Mathf.randomSeedRange(e.id + i + 6, 20f * e.fin()) * i;
Draw.rect(Core.atlas.find("casing"),
e.x + Angles.trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()),
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
2.5f, 4f,
rot + e.fin() * 30f * i + Mathf.randomSeedRange(e.id + i + 9, 40f * e.fin()));
e.x + Angles.trnsx(lr, len) + Mathf.randomSeedRange(e.id + i + 7, 3f * e.fin()),
e.y + Angles.trnsy(lr, len) + Mathf.randomSeedRange(e.id + i + 8, 3f * e.fin()),
2.5f, 4f,
rot + e.fin() * 30f * i + Mathf.randomSeedRange(e.id + i + 9, 40f * e.fin()));
}
Draw.color(Color.LIGHT_GRAY);
@ -1178,7 +1177,7 @@ public class Fx implements ContentList{
healBlock = new Effect(20, e -> {
Draw.color(Pal.heal);
Lines.stroke(2f * e.fout() + 0.5f);
Lines.square(e.x, e.y, 1f + (e.fin() * e.rotation * tilesize/2f-1f));
Lines.square(e.x, e.y, 1f + (e.fin() * e.rotation * tilesize / 2f - 1f));
Draw.color();
});

View File

@ -21,7 +21,7 @@ import io.anuke.mindustry.type.Weapon;
public class Mechs implements ContentList{
public static Mech alpha, delta, tau, omega, dart, javelin, trident, glaive;
/**These are not new mechs, just re-assignments for convenience.*/
/** These are not new mechs, just re-assignments for convenience. */
public static Mech starterDesktop, starterMobile;
@Override
@ -137,7 +137,7 @@ public class Mechs implements ContentList{
if(player.timer.get(Player.timerAbility, healReload)){
wasHealed = false;
rect.setSize(healRange*2f).setCenter(player.x, player.y);
rect.setSize(healRange * 2f).setCenter(player.x, player.y);
Units.getNearby(player.getTeam(), rect, unit -> {
if(unit.dst(player) <= healRange){
if(unit.health < unit.maxHealth()){
@ -192,7 +192,7 @@ public class Mechs implements ContentList{
@Override
public float spreadX(Player player){
return player.shootHeat*2f;
return player.shootHeat * 2f;
}
@Override
@ -203,7 +203,7 @@ public class Mechs implements ContentList{
@Override
public void updateAlt(Player player){
float scl = 1f - player.shootHeat/2f;
float scl = 1f - player.shootHeat / 2f;
player.velocity().scl(scl);
}
@ -257,6 +257,7 @@ public class Mechs implements ContentList{
float minV = 3.6f;
float maxV = 6f;
TextureRegion shield;
{
drillPower = -1;
speed = 0.11f;
@ -292,7 +293,7 @@ public class Mechs implements ContentList{
@Override
public void updateAlt(Player player){
float scl = scld(player);
if(Mathf.chance(Time.delta() * (0.15*scl))){
if(Mathf.chance(Time.delta() * (0.15 * scl))){
Effects.effect(Fx.hitLancer, Pal.lancerLaser, player.x, player.y);
Lightning.create(player.getTeam(), Pal.lancerLaser, 10f,
player.x + player.velocity().x, player.y + player.velocity().y, player.rotation, 14);
@ -304,9 +305,9 @@ public class Mechs implements ContentList{
float scl = scld(player);
if(scl < 0.01f) return;
Draw.color(Pal.lancerLaser);
Draw.alpha(scl/2f);
Draw.alpha(scl / 2f);
Draw.blend(Blending.additive);
Draw.rect(shield, player.x + Mathf.range(scl/2f), player.y + Mathf.range(scl/2f), player.rotation - 90);
Draw.rect(shield, player.x + Mathf.range(scl / 2f), player.y + Mathf.range(scl / 2f), player.rotation - 90);
Draw.blend();
}

View File

@ -1,7 +1,7 @@
package io.anuke.mindustry.content;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.type.StatusEffect;

View File

@ -88,7 +88,6 @@ public class TechTree implements ContentList{
});
node(copperWall, () -> {
node(copperWallLarge);
node(titaniumWall, () -> {
@ -172,7 +171,6 @@ public class TechTree implements ContentList{
});
node(mechanicalPump, () -> {
node(conduit, () -> {
node(liquidJunction, () -> {
@ -275,12 +273,13 @@ public class TechTree implements ContentList{
for(int i = 0; i < requirements.length; i++){
requirements[i] = new ItemStack(block.buildRequirements[i].item, block.buildRequirements[i].amount * 5);
}
return new TechNode(block, requirements, children);
}
private TechNode node(Block block){
return node(block, () -> {});
return node(block, () -> {
});
}
public static class TechNode{

View File

@ -8,9 +8,9 @@ import io.anuke.mindustry.type.Weapon;
public class UnitTypes implements ContentList{
public static UnitType
spirit, phantom,
wraith, ghoul, revenant, lich, reaper,
dagger, crawler, titan, fortress, eruptor, chaosArray, eradicator;
spirit, phantom,
wraith, ghoul, revenant, lich, reaper,
dagger, crawler, titan, fortress, eruptor, chaosArray, eradicator;
@Override
public void load(){

View File

@ -4,9 +4,7 @@ import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.game.Rules;
import io.anuke.mindustry.maps.generators.MapGenerator;
import io.anuke.mindustry.maps.generators.MapGenerator.Decoration;
import io.anuke.mindustry.type.Item;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.Zone;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.Block;
public class Zones implements ContentList{
@ -44,7 +42,7 @@ public class Zones implements ContentList{
}};
frozenForest = new Zone("frozenForest", new MapGenerator("frozenForest", 1)
.decor(new Decoration(Blocks.snow, Blocks.sporeCluster, 0.02))){{
.decor(new Decoration(Blocks.snow, Blocks.sporeCluster, 0.02))){{
loadout = Loadouts.basicFoundation;
baseLaunchCost = ItemStack.with();
startingItems = ItemStack.list(Items.copper, 400);
@ -89,8 +87,8 @@ public class Zones implements ContentList{
}};*/
stainedMountains = new Zone("stainedMountains", new MapGenerator("stainedMountains", 2)
.dist(0f, false)
.decor(new Decoration(Blocks.moss, Blocks.shaleBoulder, 0.02))){{
.dist(0f, false)
.decor(new Decoration(Blocks.moss, Blocks.shaleBoulder, 0.02))){{
loadout = Loadouts.basicFoundation;
baseLaunchCost = ItemStack.with();
startingItems = ItemStack.list(Items.copper, 400, Items.lead, 100);

View File

@ -1,8 +1,6 @@
package io.anuke.mindustry.core;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.ObjectMap;
import io.anuke.arc.collection.ObjectSet;
import io.anuke.arc.collection.*;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.Pixmap;
@ -10,14 +8,10 @@ import io.anuke.arc.util.Log;
import io.anuke.mindustry.content.*;
import io.anuke.mindustry.entities.bullet.Bullet;
import io.anuke.mindustry.entities.bullet.BulletType;
import io.anuke.mindustry.entities.effect.Fire;
import io.anuke.mindustry.entities.effect.Lightning;
import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.entities.effect.*;
import io.anuke.mindustry.entities.traits.TypeTrait;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Content;
import io.anuke.mindustry.game.ContentList;
import io.anuke.mindustry.game.MappableContent;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.LegacyColorMapper;
@ -58,7 +52,7 @@ public class ContentLoader{
verbose = true;
}
/**Creates all content types.*/
/** Creates all content types. */
public void load(){
if(loaded){
Log.info("Content already loaded, skipping.");
@ -69,7 +63,7 @@ public class ContentLoader{
for(ContentType type : ContentType.values()){
contentMap[type.ordinal()] = new Array<>();
contentNameMap[type.ordinal()] = new ObjectMap<>();
contentNameMap[type.ordinal()] = new ObjectMap<>();
}
for(ContentList list : content){
@ -82,13 +76,13 @@ public class ContentLoader{
for(Content c : contentMap[type.ordinal()]){
if(c instanceof MappableContent){
String name = ((MappableContent) c).name;
String name = ((MappableContent)c).name;
if(contentNameMap[type.ordinal()].containsKey(name)){
throw new IllegalArgumentException("Two content objects cannot have the same name! (issue: '" + name + "')");
}
contentNameMap[type.ordinal()].put(name, (MappableContent) c);
contentNameMap[type.ordinal()].put(name, (MappableContent)c);
}
total ++;
total++;
}
}
@ -119,7 +113,7 @@ public class ContentLoader{
loaded = true;
}
/**Initializes all content with the specified function.*/
/** Initializes all content with the specified function. */
public void initialize(Consumer<Content> callable){
if(initialization.contains(callable)) return;
@ -132,7 +126,7 @@ public class ContentLoader{
initialization.add(callable);
}
/**Loads block colors.*/
/** Loads block colors. */
public void loadColors(){
Pixmap pixmap = new Pixmap(files.internal("sprites/block_colors.png"));
for(int i = 0; i < 256; i++){
@ -193,7 +187,7 @@ public class ContentLoader{
}
public <T extends Content> Array<T> getBy(ContentType type){
return (Array<T>) contentMap[type.ordinal()];
return (Array<T>)contentMap[type.ordinal()];
}
//utility methods, just makes things a bit shorter
@ -203,7 +197,7 @@ public class ContentLoader{
}
public Block block(int id){
return (Block) getByID(ContentType.block, id);
return (Block)getByID(ContentType.block, id);
}
public Array<Item> items(){
@ -211,7 +205,7 @@ public class ContentLoader{
}
public Item item(int id){
return (Item) getByID(ContentType.item, id);
return (Item)getByID(ContentType.item, id);
}
public Array<Liquid> liquids(){
@ -219,7 +213,7 @@ public class ContentLoader{
}
public Liquid liquid(int id){
return (Liquid) getByID(ContentType.liquid, id);
return (Liquid)getByID(ContentType.liquid, id);
}
public Array<BulletType> bullets(){
@ -227,7 +221,7 @@ public class ContentLoader{
}
public BulletType bullet(int id){
return (BulletType) getByID(ContentType.bullet, id);
return (BulletType)getByID(ContentType.bullet, id);
}
public Array<Zone> zones(){
@ -250,5 +244,9 @@ public class ContentLoader{
TypeTrait.registerType(Lightning.class, Lightning::new);
}
private class ImpendingDoomException extends RuntimeException{ ImpendingDoomException(String s){ super(s); }}
private class ImpendingDoomException extends RuntimeException{
ImpendingDoomException(String s){
super(s);
}
}
}

View File

@ -1,8 +1,6 @@
package io.anuke.mindustry.core;
import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.*;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.GL20;
import io.anuke.arc.graphics.g2d.Draw;
@ -16,16 +14,10 @@ import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Content;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.game.EventType.*;
import io.anuke.mindustry.game.GlobalData;
import io.anuke.mindustry.game.Rules;
import io.anuke.mindustry.game.Saves;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.input.Binding;
import io.anuke.mindustry.input.DesktopInput;
import io.anuke.mindustry.input.InputHandler;
import io.anuke.mindustry.input.MobileInput;
import io.anuke.mindustry.input.*;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item;
@ -152,20 +144,20 @@ public class Control implements ApplicationListener{
if(e.breaking){
state.stats.buildingsDeconstructed++;
}else{
state.stats.buildingsBuilt ++;
state.stats.buildingsBuilt++;
}
}
});
Events.on(BlockDestroyEvent.class, e -> {
if(e.tile.getTeam() == player.getTeam()){
state.stats.buildingsDestroyed ++;
state.stats.buildingsDestroyed++;
}
});
Events.on(UnitDestroyEvent.class, e -> {
if(e.unit.getTeam() != player.getTeam()){
state.stats.enemyUnitsDestroyed ++;
state.stats.enemyUnitsDestroyed++;
}
});
@ -252,9 +244,9 @@ public class Control implements ApplicationListener{
Core.settings.save();
}).size(100f, 60f);
dialog.cont.add("Reminder: The alpha version you are about to play is very unstable, and is [accent]not representative of the final v4 release.[]\n\n " +
"\nThere is currently[scarlet] no sound implemented[]; this is intentional.\n" +
"All current art and UI is unfinished, and will be changed before release. " +
"\n\n[accent]Saves may be corrupted without warning between updates.").wrap().width(400f);
"\nThere is currently[scarlet] no sound implemented[]; this is intentional.\n" +
"All current art and UI is unfinished, and will be changed before release. " +
"\n\n[accent]Saves may be corrupted without warning between updates.").wrap().width(400f);
dialog.show();
});
}
@ -309,7 +301,7 @@ public class Control implements ApplicationListener{
Time.update();
}
if(!scene.hasDialog() && !(scene.root.getChildren().peek() instanceof Dialog) &&Core.input.keyTap(KeyCode.BACK)){
if(!scene.hasDialog() && !(scene.root.getChildren().peek() instanceof Dialog) && Core.input.keyTap(KeyCode.BACK)){
Platform.instance.hide();
}
}

View File

@ -3,30 +3,28 @@ package io.anuke.mindustry.core;
import io.anuke.arc.Events;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.game.EventType.StateChangeEvent;
import io.anuke.mindustry.game.Rules;
import io.anuke.mindustry.game.Stats;
import io.anuke.mindustry.game.Teams;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.net.Net;
import static io.anuke.mindustry.Vars.unitGroups;
import static io.anuke.mindustry.Vars.waveTeam;
public class GameState{
/**Current wave number, can be anything in non-wave modes.*/
/** Current wave number, can be anything in non-wave modes. */
public int wave = 1;
/**Wave countdown in ticks.*/
/** Wave countdown in ticks. */
public float wavetime;
/**Whether the game is in game over state.*/
/** Whether the game is in game over state. */
public boolean gameOver = false, launched = false;
/**The current game rules.*/
/** The current game rules. */
public Rules rules = new Rules();
/**Statistics for this save/game. Displayed after game over.*/
/** Statistics for this save/game. Displayed after game over. */
public Stats stats = new Stats();
/**Team data. Gets reset every new game.*/
/** Team data. Gets reset every new game. */
public Teams teams = new Teams();
/**Number of enemies in the game; only used clientside in servers.*/
/** Number of enemies in the game; only used clientside in servers. */
public int enemies;
/**Current game state.*/
/** Current game state. */
private State state = State.menu;
public int enemies(){

View File

@ -8,15 +8,9 @@ import io.anuke.arc.collection.ObjectSet.ObjectSetIterator;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Entities;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.game.EventType.GameOverEvent;
import io.anuke.mindustry.game.EventType.PlayEvent;
import io.anuke.mindustry.game.EventType.ResetEvent;
import io.anuke.mindustry.game.EventType.WaveEvent;
import io.anuke.mindustry.game.EventType.*;
import io.anuke.mindustry.game.*;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item;
@ -51,7 +45,7 @@ public class Logic implements ApplicationListener{
});
}
/**Handles the event of content being used by either the player or some block.*/
/** Handles the event of content being used by either the player or some block. */
public void handleContent(UnlockableContent content){
if(!headless){
data.unlockContent(content);
@ -85,7 +79,7 @@ public class Logic implements ApplicationListener{
world.spawner.spawnEnemies();
state.wave++;
state.wavetime = world.isZone() && world.getZone().isBossWave(state.wave) ? state.rules.waveSpacing * bossWaveMultiplier :
world.isZone() && world.getZone().isLaunchWave(state.wave) ? state.rules.waveSpacing * launchWaveMultiplier : state.rules.waveSpacing;
world.isZone() && world.getZone().isLaunchWave(state.wave) ? state.rules.waveSpacing * launchWaveMultiplier : state.rules.waveSpacing;
Events.fire(new WaveEvent());
}

View File

@ -1,17 +1,12 @@
package io.anuke.mindustry.core;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.PacketPriority;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.annotations.Annotations.Variant;
import io.anuke.annotations.Annotations.*;
import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Core;
import io.anuke.arc.collection.IntSet;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.math.RandomXS128;
import io.anuke.arc.util.Interval;
import io.anuke.arc.util.Log;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.*;
import io.anuke.arc.util.io.ReusableByteArrayInputStream;
import io.anuke.arc.util.serialization.Base64Coder;
import io.anuke.mindustry.Vars;
@ -25,11 +20,9 @@ import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.gen.RemoteReadClient;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.net.*;
import io.anuke.mindustry.net.Net.SendMode;
import io.anuke.mindustry.net.NetworkIO;
import io.anuke.mindustry.net.Packets.*;
import io.anuke.mindustry.net.ValidateException;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.modules.ItemModule;
@ -45,18 +38,18 @@ public class NetClient implements ApplicationListener{
public final static float viewScale = 2f;
private Interval timer = new Interval(5);
/**Whether the client is currently connecting.*/
/** Whether the client is currently connecting. */
private boolean connecting = false;
/**If true, no message will be shown on disconnect.*/
/** If true, no message will be shown on disconnect. */
private boolean quiet = false;
/**Counter for data timeout.*/
/** Counter for data timeout. */
private float timeoutTime = 0f;
/**Last sent client snapshot ID.*/
/** Last sent client snapshot ID. */
private int lastSent;
/**List of entities that were removed, and need not be added while syncing.*/
/** List of entities that were removed, and need not be added while syncing. */
private IntSet removed = new IntSet();
/**Byte stream for reading in snapshots.*/
/** Byte stream for reading in snapshots. */
private ReusableByteArrayInputStream byteStream = new ReusableByteArrayInputStream();
private DataInputStream dataStream = new DataInputStream(byteStream);
@ -210,7 +203,7 @@ public class NetClient implements ApplicationListener{
int id = input.readInt();
byte typeID = input.readByte();
SyncTrait entity = (SyncTrait) group.getByID(id);
SyncTrait entity = (SyncTrait)group.getByID(id);
boolean add = false;
if(entity == null && id == player.id){
@ -220,7 +213,7 @@ public class NetClient implements ApplicationListener{
//entity must not be added yet, so create it
if(entity == null){
entity = (SyncTrait) TypeTrait.getTypeByID(typeID).get(); //create entity from supplier
entity = (SyncTrait)TypeTrait.getTypeByID(typeID).get(); //create entity from supplier
entity.resetID(id);
if(!netClient.isEntityUsed(entity.getID())){
add = true;
@ -323,7 +316,7 @@ public class NetClient implements ApplicationListener{
Net.disconnect();
}
/**When set, any disconnects will be ignored and no dialogs will be shown.*/
/** When set, any disconnects will be ignored and no dialogs will be shown. */
public void setQuiet(){
quiet = true;
}
@ -349,13 +342,13 @@ public class NetClient implements ApplicationListener{
}
Call.onClientShapshot(lastSent++, player.x, player.y,
player.pointerX, player.pointerY, player.rotation, player.baseRotation,
player.velocity().x, player.velocity().y,
player.getMineTile(),
player.isBoosting, player.isShooting, ui.chatfrag.chatOpen(),
requests,
Core.camera.position.x, Core.camera.position.y,
Core.camera.width * viewScale, Core.camera.height * viewScale);
player.pointerX, player.pointerY, player.rotation, player.baseRotation,
player.velocity().x, player.velocity().y,
player.getMineTile(),
player.isBoosting, player.isShooting, ui.chatfrag.chatOpen(),
requests,
Core.camera.position.x, Core.camera.position.y,
Core.camera.width * viewScale, Core.camera.height * viewScale);
}
if(timer.get(1, 60)){

View File

@ -4,26 +4,19 @@ import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Events;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntMap;
import io.anuke.arc.collection.ObjectSet;
import io.anuke.arc.collection.*;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.Colors;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Log;
import io.anuke.arc.util.Structs;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.*;
import io.anuke.arc.util.io.ByteBufferOutput;
import io.anuke.arc.util.io.CountableByteArrayOutputStream;
import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.content.Mechs;
import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Entities;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.traits.BuilderTrait.BuildRequest;
import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.traits.SyncTrait;
@ -33,44 +26,40 @@ import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.game.Version;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.gen.RemoteReadServer;
import io.anuke.mindustry.net.Administration;
import io.anuke.mindustry.net.*;
import io.anuke.mindustry.net.Administration.PlayerInfo;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.net.NetConnection;
import io.anuke.mindustry.net.NetworkIO;
import io.anuke.mindustry.net.Packets.*;
import io.anuke.mindustry.world.Tile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.zip.DeflaterOutputStream;
import static io.anuke.mindustry.Vars.*;
import java.lang.StringBuilder;
public class NetServer implements ApplicationListener{
public final static int maxSnapshotSize = 430;
private final static float serverSyncTime = 30, kickDuration = 30 * 1000;
private final static Vector2 vector = new Vector2();
private final static Rectangle viewport = new Rectangle();
private final static Array<Entity> returnArray = new Array<>();
/**If a player goes away of their server-side coordinates by this distance, they get teleported back.*/
/** If a player goes away of their server-side coordinates by this distance, they get teleported back. */
private final static float correctDist = 16f;
public final Administration admins = new Administration();
/**Maps connection IDs to players.*/
/** Maps connection IDs to players. */
private IntMap<Player> connections = new IntMap<>();
private boolean closing = false;
private ByteBuffer writeBuffer = ByteBuffer.allocate(127);
private ByteBufferOutput outputBuffer = new ByteBufferOutput(writeBuffer);
/**Stream for writing player sync data to.*/
/** Stream for writing player sync data to. */
private CountableByteArrayOutputStream syncStream = new CountableByteArrayOutputStream();
/**Data stream for writing player sync data to.*/
/** Data stream for writing player sync data to. */
private DataOutputStream dataStream = new DataOutputStream(syncStream);
public NetServer(){
@ -100,7 +89,7 @@ public class NetServer implements ApplicationListener{
NetConnection connection = Net.getConnection(id);
if(connection == null ||
admins.isIPBanned(connection.address)) return;
admins.isIPBanned(connection.address)) return;
if(connection.hasBegunConnecting){
kick(id, KickReason.idInUse);
@ -215,7 +204,7 @@ public class NetServer implements ApplicationListener{
int count = 0;
for(Player other : players){
if(other.getTeam() == team){
count ++;
count++;
}
}
return count;
@ -262,16 +251,16 @@ public class NetServer implements ApplicationListener{
@Remote(targets = Loc.client, unreliable = true)
public static void onClientShapshot(
Player player,
int snapshotID,
float x, float y,
float pointerX, float pointerY,
float rotation, float baseRotation,
float xVelocity, float yVelocity,
Tile mining,
boolean boosting, boolean shooting, boolean chatting,
BuildRequest[] requests,
float viewX, float viewY, float viewWidth, float viewHeight
Player player,
int snapshotID,
float x, float y,
float pointerX, float pointerY,
float rotation, float baseRotation,
float xVelocity, float yVelocity,
Tile mining,
boolean boosting, boolean shooting, boolean chatting,
BuildRequest[] requests,
float viewX, float viewY, float viewWidth, float viewHeight
){
NetConnection connection = player.con;
if(connection == null || snapshotID < connection.lastRecievedClientSnapshot) return;
@ -348,7 +337,7 @@ public class NetServer implements ApplicationListener{
if(!player.isAdmin){
Log.warn("ACCESS DENIED: Player {0} / {1} attempted to perform admin action without proper security access.",
player.name, player.con.address);
player.name, player.con.address);
return;
}
@ -394,7 +383,7 @@ public class NetServer implements ApplicationListener{
int used = 0;
for(Team t : Team.all){
if(playerGroup.count(p -> p.getTeam() == t) > 0){
used ++;
used++;
}
}
return used < 2;
@ -472,7 +461,7 @@ public class NetServer implements ApplicationListener{
for(EntityGroup<?> group : Entities.getAllGroups()){
if(group.isEmpty() || !(group.all().get(0) instanceof SyncTrait)) continue;
//clipping is done by representatives
SyncTrait represent = (SyncTrait) group.all().get(0);
SyncTrait represent = (SyncTrait)group.all().get(0);
//make sure mapping is enabled for this group
if(!group.mappingEnabled()){
@ -482,13 +471,13 @@ public class NetServer implements ApplicationListener{
returnArray.clear();
if(represent.isClipped()){
EntityQuery.getNearby(group, viewport, entity -> {
if(((SyncTrait) entity).isSyncing() && viewport.overlaps(Tmp.r3.setSize(((SyncTrait)entity).clipSize(), ((SyncTrait)entity).clipSize()).setCenter(entity.getX(), entity.getY()))){
if(((SyncTrait)entity).isSyncing() && viewport.overlaps(Tmp.r3.setSize(((SyncTrait)entity).clipSize(), ((SyncTrait)entity).clipSize()).setCenter(entity.getX(), entity.getY()))){
returnArray.add(entity);
}
});
}else{
for(Entity entity : group.all()){
if(((SyncTrait) entity).isSyncing()){
if(((SyncTrait)entity).isSyncing()){
returnArray.add(entity);
}
}
@ -501,10 +490,10 @@ public class NetServer implements ApplicationListener{
for(Entity entity : returnArray){
//write all entities now
dataStream.writeInt(entity.getID()); //write id
dataStream.writeByte(((SyncTrait) entity).getTypeID()); //write type ID
((SyncTrait) entity).write(dataStream); //write entity
dataStream.writeByte(((SyncTrait)entity).getTypeID()); //write type ID
((SyncTrait)entity).write(dataStream); //write entity
sent ++;
sent++;
if(syncStream.position() > maxSnapshotSize){
dataStream.close();
@ -579,7 +568,7 @@ public class NetServer implements ApplicationListener{
try{
//iterate through each player
for(int i = 0; i < playerGroup.size(); i ++){
for(int i = 0; i < playerGroup.size(); i++){
Player player = playerGroup.all().get(i);
if(player.isLocal) continue;

View File

@ -10,15 +10,17 @@ import io.anuke.arc.util.serialization.Base64Coder;
import static io.anuke.mindustry.Vars.mobile;
public abstract class Platform {
/**Each separate game platform should set this instance to their own implementation.*/
public static Platform instance = new Platform() {};
public abstract class Platform{
/** Each separate game platform should set this instance to their own implementation. */
public static Platform instance = new Platform(){
};
/**Add a text input dialog that should show up after the field is tapped.*/
/** Add a text input dialog that should show up after the field is tapped. */
public void addDialog(TextField field){
addDialog(field, 16);
}
/**See addDialog().*/
/** See addDialog(). */
public void addDialog(TextField field, int maxLength){
if(!mobile) return; //this is mobile only, desktop doesn't need dialogs
@ -35,13 +37,17 @@ public abstract class Platform {
Core.input.getTextInput(input);
});
}
/**Update discord RPC.*/
public void updateRPC(){}
/**Whether donating is supported.*/
/** Update discord RPC. */
public void updateRPC(){
}
/** Whether donating is supported. */
public boolean canDonate(){
return false;
}
/**Must be a base64 string 8 bytes in length.*/
/** Must be a base64 string 8 bytes in length. */
public String getUUID(){
String uuid = Core.settings.getString("uuid", "");
if(uuid.isEmpty()){
@ -54,25 +60,31 @@ public abstract class Platform {
}
return uuid;
}
/**Only used for iOS or android: open the share menu for a map or save.*/
public void shareFile(FileHandle file){}
/**Show a file chooser. Desktop only.
*
/** Only used for iOS or android: open the share menu for a map or save. */
public void shareFile(FileHandle file){
}
/**
* Show a file chooser. Desktop only.
* @param text File chooser title text
* @param content Description of the type of files to be loaded
* @param cons Selection listener
* @param open Whether to open or save files
* @param filetype File extension to filter
*/
public void showFileChooser(String text, String content, Consumer<FileHandle> cons, boolean open, String filetype){}
public void showFileChooser(String text, String content, Consumer<FileHandle> cons, boolean open, String filetype){
}
/**Hide the app. Android only.*/
public void hide(){}
/** Hide the app. Android only. */
public void hide(){
}
/**Forces the app into landscape mode. Currently Android only.*/
public void beginForceLandscape(){}
/** Forces the app into landscape mode. Currently Android only. */
public void beginForceLandscape(){
}
/**Stops forcing the app into landscape orientation. Currently Android only.*/
public void endForceLandscape(){}
/** Stops forcing the app into landscape orientation. Currently Android only. */
public void endForceLandscape(){
}
}

View File

@ -5,37 +5,22 @@ import io.anuke.arc.Core;
import io.anuke.arc.files.FileHandle;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.function.Predicate;
import io.anuke.arc.graphics.Camera;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.Pixmap;
import io.anuke.arc.graphics.PixmapIO;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.SpriteBatch;
import io.anuke.arc.graphics.*;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.graphics.glutils.FrameBuffer;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.BufferUtils;
import io.anuke.arc.util.ScreenUtils;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.*;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityDraw;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.effect.GroundEffectEntity;
import io.anuke.mindustry.entities.effect.GroundEffectEntity.GroundEffect;
import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.graphics.*;
import io.anuke.mindustry.world.blocks.defense.ForceProjector.ShieldEntity;
@ -84,7 +69,7 @@ public class Renderer implements ApplicationListener{
entity.id++;
entity.set(x, y);
if(data instanceof Entity){
entity.setParent((Entity) data);
entity.setParent((Entity)data);
}
effectGroup.add(entity);
}else{
@ -96,7 +81,7 @@ public class Renderer implements ApplicationListener{
entity.data = data;
entity.set(x, y);
if(data instanceof Entity){
entity.setParent((Entity) data);
entity.setParent((Entity)data);
}
groundEffectGroup.add(entity);
}
@ -281,7 +266,7 @@ public class Renderer implements ApplicationListener{
EntityGroup<BaseUnit> group = unitGroups[team.ordinal()];
if(group.count(p -> p.isFlying() == flying) +
playerGroup.count(p -> p.isFlying() == flying && p.getTeam() == team) == 0 && flying) continue;
playerGroup.count(p -> p.isFlying() == flying && p.getTeam() == team) == 0 && flying) continue;
drawAndInterpolate(unitGroups[team.ordinal()], u -> u.isFlying() == flying && !u.isDead(), Unit::drawUnder);
drawAndInterpolate(playerGroup, p -> p.isFlying() == flying && p.getTeam() == team && !p.isDead(), Unit::drawUnder);
@ -329,7 +314,7 @@ public class Renderer implements ApplicationListener{
public void takeMapScreenshot(){
drawGroundShadows();
int w = world.width()*tilesize, h = world.height()*tilesize;
int w = world.width() * tilesize, h = world.height() * tilesize;
int memory = w * h * 4 / 1024 / 1024;
if(memory >= 65){
@ -348,8 +333,8 @@ public class Renderer implements ApplicationListener{
disableUI = true;
camera.width = w;
camera.height = h;
camera.position.x = w/2f + tilesize/2f;
camera.position.y = h/2f + tilesize/2f;
camera.position.x = w / 2f + tilesize / 2f;
camera.position.y = h / 2f + tilesize / 2f;
Draw.flush();
buffer.begin();
draw();
@ -361,7 +346,7 @@ public class Renderer implements ApplicationListener{
camera.position.set(px, py);
buffer.begin();
byte[] lines = ScreenUtils.getFrameBufferPixels(0, 0, w, h, true);
for(int i = 0; i < lines.length; i+= 4){
for(int i = 0; i < lines.length; i += 4){
lines[i + 3] = (byte)255;
}
buffer.end();

View File

@ -1,8 +1,6 @@
package io.anuke.mindustry.core;
import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.*;
import io.anuke.arc.Graphics.Cursor;
import io.anuke.arc.Graphics.Cursor.SystemCursor;
import io.anuke.arc.freetype.FreeTypeFontGenerator;
@ -13,19 +11,13 @@ import io.anuke.arc.graphics.Colors;
import io.anuke.arc.graphics.g2d.BitmapFont;
import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Interpolation;
import io.anuke.arc.scene.Group;
import io.anuke.arc.scene.Scene;
import io.anuke.arc.scene.Skin;
import io.anuke.arc.scene.*;
import io.anuke.arc.scene.actions.Actions;
import io.anuke.arc.scene.ui.Dialog;
import io.anuke.arc.scene.ui.TextField;
import io.anuke.arc.scene.ui.*;
import io.anuke.arc.scene.ui.TextField.TextFieldFilter;
import io.anuke.arc.scene.ui.TooltipManager;
import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Align;
import io.anuke.arc.util.Strings;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.*;
import io.anuke.mindustry.editor.MapEditorDialog;
import io.anuke.mindustry.game.EventType.ResizeEvent;
import io.anuke.mindustry.graphics.Pal;
@ -84,21 +76,21 @@ public class UI implements ApplicationListener{
Core.input.addProcessor(Core.scene);
Dialog.setShowAction(() -> sequence(
alpha(0f),
originCenter(),
moveToAligned(Core.graphics.getWidth() / 2f, Core.graphics.getHeight() / 2f, Align.center),
scaleTo(0.0f, 1f),
parallel(
scaleTo(1f, 1f, 0.1f, Interpolation.fade),
fadeIn(0.1f, Interpolation.fade)
)
alpha(0f),
originCenter(),
moveToAligned(Core.graphics.getWidth() / 2f, Core.graphics.getHeight() / 2f, Align.center),
scaleTo(0.0f, 1f),
parallel(
scaleTo(1f, 1f, 0.1f, Interpolation.fade),
fadeIn(0.1f, Interpolation.fade)
)
));
Dialog.setHideAction(() -> sequence(
parallel(
scaleTo(0.01f, 0.01f, 0.1f, Interpolation.fade),
fadeOut(0.1f, Interpolation.fade)
)
parallel(
scaleTo(0.01f, 0.01f, 0.1f, Interpolation.fade),
fadeOut(0.1f, Interpolation.fade)
)
));
TooltipManager.getInstance().animations = false;
@ -126,11 +118,11 @@ public class UI implements ApplicationListener{
Core.graphics.restoreCursor();
}
void generateFonts(Skin skin){
generator = new FreeTypeFontGenerator(Core.files.internal("fonts/font.ttf"));
FreeTypeFontParameter param = new FreeTypeFontParameter();
param.size = (int)(9*2 * Math.max(Unit.dp.scl(1f), 0.5f));
param.size = (int)(9 * 2 * Math.max(Unit.dp.scl(1f), 0.5f));
param.shadowColor = Color.DARK_GRAY;
param.shadowOffsetY = 2;
param.incremental = true;

View File

@ -1,20 +1,14 @@
package io.anuke.mindustry.core;
import io.anuke.annotations.Annotations.Nullable;
import io.anuke.arc.ApplicationListener;
import io.anuke.arc.Core;
import io.anuke.arc.Events;
import io.anuke.arc.*;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntArray;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.util.Log;
import io.anuke.arc.util.Structs;
import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.ai.BlockIndexer;
import io.anuke.mindustry.ai.Pathfinder;
import io.anuke.mindustry.ai.WaveSpawner;
import io.anuke.arc.util.*;
import io.anuke.mindustry.ai.*;
import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.core.GameState.State;
import io.anuke.mindustry.entities.EntityQuery;
@ -22,16 +16,10 @@ import io.anuke.mindustry.game.EventType.TileChangeEvent;
import io.anuke.mindustry.game.EventType.WorldLoadEvent;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.io.MapIO;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.maps.MapException;
import io.anuke.mindustry.maps.Maps;
import io.anuke.mindustry.maps.*;
import io.anuke.mindustry.maps.generators.Generator;
import io.anuke.mindustry.type.ContentType;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.Zone;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.*;
import static io.anuke.mindustry.Vars.*;
@ -97,11 +85,13 @@ public class World implements ApplicationListener{
return tiles == null ? 0 : tiles[0].length;
}
public @Nullable Tile tile(int pos){
public @Nullable
Tile tile(int pos){
return tiles == null ? null : tile(Pos.x(pos), Pos.y(pos));
}
public @Nullable Tile tile(int x, int y){
public @Nullable
Tile tile(int x, int y){
if(tiles == null){
return null;
}
@ -113,7 +103,8 @@ public class World implements ApplicationListener{
return tiles[x][y];
}
public @Nullable Tile tileWorld(float x, float y){
public @Nullable
Tile tileWorld(float x, float y){
return tile(Math.round(x / tilesize), Math.round(y / tilesize));
}
@ -161,7 +152,7 @@ public class World implements ApplicationListener{
generating = true;
}
/**Call to signal the beginning of loading the map with a custom set of tiles.*/
/** Call to signal the beginning of loading the map with a custom set of tiles. */
public void beginMapLoad(Tile[][] tiles){
this.tiles = tiles;
generating = true;
@ -185,7 +176,7 @@ public class World implements ApplicationListener{
addDarkness(tiles);
EntityQuery.resizeTree(-finalWorldBounds, -finalWorldBounds, tiles.length * tilesize + finalWorldBounds*2, tiles[0].length * tilesize + finalWorldBounds*2);
EntityQuery.resizeTree(-finalWorldBounds, -finalWorldBounds, tiles.length * tilesize + finalWorldBounds * 2, tiles[0].length * tilesize + finalWorldBounds * 2);
generating = false;
Events.fire(new WorldLoadEvent());
@ -326,7 +317,7 @@ public class World implements ApplicationListener{
if(!(worldx == tile.x && worldy == tile.y)){
Tile toplace = world.tile(worldx, worldy);
if(toplace != null){
toplace.setLinked((byte) (dx + offsetx), (byte) (dy + offsety));
toplace.setLinked((byte)(dx + offsetx), (byte)(dy + offsety));
toplace.setTeam(team);
}
}
@ -341,7 +332,7 @@ public class World implements ApplicationListener{
if(!Structs.inBounds(x, y, oldWidth, oldHeight)) return -1;
x += shiftX;
y += shiftY;
return y*newWidth + x;
return y * newWidth + x;
}
/**
@ -349,12 +340,11 @@ public class World implements ApplicationListener{
*/
public Point2 raycastWorld(float x, float y, float x2, float y2){
return raycast(Math.round(x / tilesize), Math.round(y / tilesize),
Math.round(x2 / tilesize), Math.round(y2 / tilesize));
Math.round(x2 / tilesize), Math.round(y2 / tilesize));
}
/**
* Input is in block coordinates, not world coordinates.
*
* @return null if no collisions found, block position otherwise.
*/
public Point2 raycast(int x0f, int y0f, int x1, int y1){
@ -422,7 +412,7 @@ public class World implements ApplicationListener{
}
}
/**Loads raw map tile data into a Tile[][] array, setting up multiblocks, cliffs and ores. */
/** Loads raw map tile data into a Tile[][] array, setting up multiblocks, cliffs and ores. */
void loadTileData(Tile[][] tiles){
prepareTiles(tiles);
}
@ -471,10 +461,12 @@ public class World implements ApplicationListener{
}
}
/**'Prepares' a tile array by:<br>
/**
* 'Prepares' a tile array by:<br>
* - setting up multiblocks<br>
* - updating occlusion<br>
* Usually used before placing structures on a tile array.*/
* Usually used before placing structures on a tile array.
*/
public void prepareTiles(Tile[][] tiles){
//find multiblocks
@ -510,7 +502,7 @@ public class World implements ApplicationListener{
if(!(worldx == x && worldy == y)){
Tile toplace = world.tile(worldx, worldy);
if(toplace != null){
toplace.setLinked((byte) (dx + offsetx), (byte) (dy + offsety));
toplace.setLinked((byte)(dx + offsetx), (byte)(dy + offsety));
toplace.setTeam(team);
}
}

View File

@ -8,10 +8,7 @@ import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.Floor;
import io.anuke.mindustry.world.blocks.OreBlock;
import io.anuke.mindustry.world.modules.ConsumeModule;
import io.anuke.mindustry.world.modules.ItemModule;
import io.anuke.mindustry.world.modules.LiquidModule;
import io.anuke.mindustry.world.modules.PowerModule;
import io.anuke.mindustry.world.modules.*;
import static io.anuke.mindustry.Vars.ui;
@ -49,7 +46,7 @@ public class EditorTile extends Tile{
@Override
public void setBlock(Block type){
Block previous =wall;
Block previous = wall;
if(previous == type) return;
super.setBlock(type);
op(TileOp.get(x, y, (byte)OpType.block.ordinal(), previous.id, type.id));

View File

@ -7,12 +7,8 @@ import io.anuke.arc.input.KeyCode;
import io.anuke.arc.util.Pack;
import io.anuke.arc.util.Structs;
import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.BlockPart;
import io.anuke.mindustry.world.blocks.Floor;
import io.anuke.mindustry.world.blocks.OreBlock;
import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.blocks.*;
public enum EditorTool{
pick{

View File

@ -68,7 +68,7 @@ public class MapEditor{
//adds missing blockparts
public void checkLinkedTiles(){
//clear block parts first
for(int x = 0; x < width(); x ++){
for(int x = 0; x < width(); x++){
for(int y = 0; y < height(); y++){
if(tiles[x][y].block() == Blocks.part){
tiles[x][y].setBlock(Blocks.air);
@ -78,8 +78,8 @@ public class MapEditor{
}
//set up missing blockparts
for(int x = 0; x < width(); x ++){
for(int y = 0; y < height(); y ++){
for(int x = 0; x < width(); x++){
for(int y = 0; y < height(); y++){
Block drawBlock = tiles[x][y].block();
if(drawBlock.isMultiblock()){
int offsetx = -(drawBlock.size - 1) / 2;
@ -92,7 +92,7 @@ public class MapEditor{
if(Structs.inBounds(worldx, worldy, width(), height()) && !(dx + offsetx == 0 && dy + offsety == 0)){
Tile tile = tiles[worldx][worldy];
tile.setBlock(Blocks.part);
tile.setLinkByte(Pack.byteByte((byte) (dx + offsetx + 8), (byte) (dy + offsety + 8)));
tile.setLinkByte(Pack.byteByte((byte)(dx + offsetx + 8), (byte)(dy + offsety + 8)));
}
}
}
@ -107,7 +107,7 @@ public class MapEditor{
loading = false;
}
/**Creates a 2-D array of EditorTiles with stone as the floor block.*/
/** Creates a 2-D array of EditorTiles with stone as the floor block. */
public Tile[][] createTiles(int width, int height){
tiles = new Tile[width][height];
@ -179,9 +179,9 @@ public class MapEditor{
boolean isfloor = drawBlock instanceof Floor && drawBlock != Blocks.air;
if(drawBlock.isMultiblock()){
x = Mathf.clamp(x, (drawBlock.size-1)/2, width() - drawBlock.size/2 - 1);
y = Mathf.clamp(y, (drawBlock.size-1)/2, height() - drawBlock.size/2 - 1);
x = Mathf.clamp(x, (drawBlock.size - 1) / 2, width() - drawBlock.size / 2 - 1);
y = Mathf.clamp(y, (drawBlock.size - 1) / 2, height() - drawBlock.size / 2 - 1);
int offsetx = -(drawBlock.size - 1) / 2;
int offsety = -(drawBlock.size - 1) / 2;
@ -197,7 +197,7 @@ public class MapEditor{
if(i == 1){
tile.setBlock(Blocks.part);
tile.setLinkByte(Pack.byteByte((byte) (dx + offsetx + 8), (byte) (dy + offsety + 8)));
tile.setLinkByte(Pack.byteByte((byte)(dx + offsetx + 8), (byte)(dy + offsety + 8)));
}else{
byte link = tile.getLinkByte();
Block block = tile.block();
@ -279,7 +279,7 @@ public class MapEditor{
clearOp();
Tile[][] previous = tiles;
int offsetX = -(width - width())/2, offsetY = -(height - height())/2;
int offsetX = -(width - width()) / 2, offsetY = -(height - height()) / 2;
loading = true;
tiles = new Tile[width][height];

View File

@ -85,49 +85,49 @@ public class MapEditorDialog extends Dialog implements Disposable{
t.row();
t.addImageTextButton("$editor.import", "icon-load-map", isize, () ->
createDialog("$editor.import",
"$editor.importmap", "$editor.importmap.description", "icon-load-map", (Runnable) loadDialog::show,
"$editor.importfile", "$editor.importfile.description", "icon-file", (Runnable) () ->
Platform.instance.showFileChooser("$editor.loadmap", "Map Files", file -> ui.loadAnd(() -> {
try{
//TODO what if it's an image? users should be warned for their stupidity
editor.beginEdit(MapIO.readMap(file, true));
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}), true, mapExtension),
createDialog("$editor.import",
"$editor.importmap", "$editor.importmap.description", "icon-load-map", (Runnable)loadDialog::show,
"$editor.importfile", "$editor.importfile.description", "icon-file", (Runnable)() ->
Platform.instance.showFileChooser("$editor.loadmap", "Map Files", file -> ui.loadAnd(() -> {
try{
//TODO what if it's an image? users should be warned for their stupidity
editor.beginEdit(MapIO.readMap(file, true));
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}), true, mapExtension),
"$editor.importimage", "$editor.importimage.description", "icon-file-image", (Runnable)() ->
Platform.instance.showFileChooser("$loadimage", "Image Files", file ->
ui.loadAnd(() -> {
try{
Pixmap pixmap = new Pixmap(file);
Tile[][] tiles = editor.createTiles(pixmap.getWidth(), pixmap.getHeight());
editor.load(() -> MapIO.readLegacyPixmap(pixmap, tiles));
editor.beginEdit(tiles);
}catch (Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}), true, "png")));
"$editor.importimage", "$editor.importimage.description", "icon-file-image", (Runnable)() ->
Platform.instance.showFileChooser("$loadimage", "Image Files", file ->
ui.loadAnd(() -> {
try{
Pixmap pixmap = new Pixmap(file);
Tile[][] tiles = editor.createTiles(pixmap.getWidth(), pixmap.getHeight());
editor.load(() -> MapIO.readLegacyPixmap(pixmap, tiles));
editor.beginEdit(tiles);
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}), true, "png")));
t.addImageTextButton("$editor.export", "icon-save-map", isize, () ->
Platform.instance.showFileChooser("$editor.savemap", "Map Files", file -> {
file = file.parent().child(file.nameWithoutExtension() + "." + mapExtension);
FileHandle result = file;
ui.loadAnd(() -> {
try{
if(!editor.getTags().containsKey("name")){
editor.getTags().put("name", result.nameWithoutExtension());
}
MapIO.writeMap(result, editor.createMap(result), editor.tiles());
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorsave", Strings.parseException(e, false)));
Log.err(e);
}
});
}, false, mapExtension));
Platform.instance.showFileChooser("$editor.savemap", "Map Files", file -> {
file = file.parent().child(file.nameWithoutExtension() + "." + mapExtension);
FileHandle result = file;
ui.loadAnd(() -> {
try{
if(!editor.getTags().containsKey("name")){
editor.getTags().put("name", result.nameWithoutExtension());
}
MapIO.writeMap(result, editor.createMap(result), editor.tiles());
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorsave", Strings.parseException(e, false)));
Log.err(e);
}
});
}, false, mapExtension));
});
menu.cont.row();
@ -146,14 +146,14 @@ public class MapEditorDialog extends Dialog implements Disposable{
});
loadDialog = new MapLoadDialog(map ->
ui.loadAnd(() -> {
try{
editor.beginEdit(map);
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}));
ui.loadAnd(() -> {
try{
editor.beginEdit(map);
}catch(Exception e){
ui.showError(Core.bundle.format("editor.errorload", Strings.parseException(e, false)));
Log.err(e);
}
}));
setFillParent(true);
@ -239,10 +239,10 @@ public class MapEditorDialog extends Dialog implements Disposable{
dialog.cont.defaults().size(360f, h).padBottom(5).padRight(5).padLeft(5);
for(int i = 0; i < arguments.length; i += 4){
String name = (String) arguments[i];
String description = (String) arguments[i + 1];
String iconname = (String) arguments[i + 2];
Runnable listenable = (Runnable) arguments[i + 3];
String name = (String)arguments[i];
String description = (String)arguments[i + 1];
String iconname = (String)arguments[i + 2];
Runnable listenable = (Runnable)arguments[i + 3];
TextButton button = dialog.cont.addButton(name, () -> {
listenable.run();
@ -306,8 +306,8 @@ public class MapEditorDialog extends Dialog implements Disposable{
public void build(){
float amount = 10f, baseSize = 60f;
float size = mobile ? (int) (Math.min(Core.graphics.getHeight(), Core.graphics.getWidth()) / amount / Unit.dp.scl(1f)) :
Math.min(Core.graphics.getDisplayMode().height / amount, baseSize);
float size = mobile ? (int)(Math.min(Core.graphics.getHeight(), Core.graphics.getWidth()) / amount / Unit.dp.scl(1f)) :
Math.min(Core.graphics.getDisplayMode().height / amount, baseSize);
clearChildren();
table(cont -> {
@ -374,7 +374,7 @@ public class MapEditorDialog extends Dialog implements Disposable{
tools.row();
tools.table("underline", t -> t.add("$editor.teams"))
.colspan(3).height(40).width(size * 3f + 3f).padBottom(3);
.colspan(3).height(40).width(size * 3f + 3f).padBottom(3);
tools.row();
@ -401,7 +401,7 @@ public class MapEditorDialog extends Dialog implements Disposable{
mid.table("underline", t -> {
Slider slider = new Slider(0, MapEditor.brushSizes.length - 1, 1, false);
slider.moved(f -> editor.brushSize = MapEditor.brushSizes[(int) (float) f]);
slider.moved(f -> editor.brushSize = MapEditor.brushSizes[(int)(float)f]);
t.top();
t.add("$editor.brush");

View File

@ -62,7 +62,7 @@ public class MapGenerateDialog extends FloatingDialog{
update();
}).size(160f, 64f);
buttons.addImageTextButton("$add", "icon-add", 14*2, this::showAdd).height(64f).width(140f);
buttons.addImageTextButton("$add", "icon-add", 14 * 2, this::showAdd).height(64f).width(140f);
}
void setup(){
@ -120,24 +120,24 @@ public class MapGenerateDialog extends FloatingDialog{
t.table(b -> {
b.left();
b.defaults().size(50f);
b.addImageButton("icon-refresh", 14*2, () -> {
b.addImageButton("icon-refresh", 14 * 2, () -> {
filter.randomize();
update();
});
b.addImageButton("icon-arrow-up", 10*2, () -> {
b.addImageButton("icon-arrow-up", 10 * 2, () -> {
int idx = filters.indexOf(filter);
filters.swap(idx, Math.max(0, idx - 1));
rebuildFilters();
update();
});
b.addImageButton("icon-arrow-down", 10*2, () -> {
b.addImageButton("icon-arrow-down", 10 * 2, () -> {
int idx = filters.indexOf(filter);
filters.swap(idx, Math.min(filters.size-1, idx + 1));
filters.swap(idx, Math.min(filters.size - 1, idx + 1));
rebuildFilters();
update();
});
b.addImageButton("icon-trash", 14*2, () -> {
b.addImageButton("icon-trash", 14 * 2, () -> {
filters.remove(filter);
rebuildFilters();
update();

View File

@ -1,14 +1,12 @@
package io.anuke.mindustry.editor;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.*;
import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.util.Scaling;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.BorderImage;
import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.ButtonGroup;
import io.anuke.arc.scene.ui.ScrollPane;
import io.anuke.arc.scene.ui.TextButton;
import io.anuke.arc.scene.ui.layout.Table;
import static io.anuke.mindustry.Vars.world;

View File

@ -40,7 +40,7 @@ public class MapRenderer implements Disposable{
}
}
chunks = new IndexedRenderer[(int) Math.ceil((float) width / chunksize)][(int) Math.ceil((float) height / chunksize)];
chunks = new IndexedRenderer[(int)Math.ceil((float)width / chunksize)][(int)Math.ceil((float)height / chunksize)];
for(int x = 0; x < chunks.length; x++){
for(int y = 0; y < chunks[0].length; y++){
@ -115,38 +115,38 @@ public class MapRenderer implements Disposable{
if(wall.rotate){
mesh.draw(idxWall, region,
wx * tilesize + wall.offset(), wy * tilesize + wall.offset(),
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl, tile.getRotation() * 90 - 90);
wx * tilesize + wall.offset(), wy * tilesize + wall.offset(),
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl, tile.getRotation() * 90 - 90);
}else{
mesh.draw(idxWall, region,
wx * tilesize + wall.offset() + (tilesize - region.getWidth() * Draw.scl)/2f,
wy * tilesize + wall.offset() + (tilesize - region.getHeight() * Draw.scl)/2f,
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl);
wx * tilesize + wall.offset() + (tilesize - region.getWidth() * Draw.scl) / 2f,
wy * tilesize + wall.offset() + (tilesize - region.getHeight() * Draw.scl) / 2f,
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl);
}
}else{
region = floor.editorVariantRegions()[Mathf.randomSeed(idxWall, 0, floor.editorVariantRegions().length-1)];
region = floor.editorVariantRegions()[Mathf.randomSeed(idxWall, 0, floor.editorVariantRegions().length - 1)];
mesh.draw(idxWall, region, wx * tilesize, wy * tilesize, 8, 8);
}
float offsetX = -(wall.size/3)*tilesize, offsetY = -(wall.size/3) * tilesize;
float offsetX = -(wall.size / 3) * tilesize, offsetY = -(wall.size / 3) * tilesize;
if(wall.update || wall.destructible){
mesh.setColor(team.color);
region = Core.atlas.find("block-border-editor");
}else if(!wall.synthetic() && wall != Blocks.air){
region = !Core.atlas.isFound(wall.editorIcon()) ? Core.atlas.find("clear-editor") : wall.editorIcon();
offsetX = tilesize/2f - region.getWidth()/2f * Draw.scl;
offsetY = tilesize/2f - region.getHeight()/2f * Draw.scl;
offsetX = tilesize / 2f - region.getWidth() / 2f * Draw.scl;
offsetY = tilesize / 2f - region.getHeight() / 2f * Draw.scl;
}else if(wall == Blocks.air && tile.ore() != null){
region = tile.ore().editorVariantRegions()[Mathf.randomSeed(idxWall, 0, tile.ore().editorVariantRegions().length-1)];
region = tile.ore().editorVariantRegions()[Mathf.randomSeed(idxWall, 0, tile.ore().editorVariantRegions().length - 1)];
}else{
region = Core.atlas.find("clear-editor");
}
mesh.draw(idxDecal, region,
wx * tilesize + offsetX, wy * tilesize + offsetY,
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl);
wx * tilesize + offsetX, wy * tilesize + offsetY,
region.getWidth() * Draw.scl, region.getHeight() * Draw.scl);
mesh.setColor(Color.WHITE);
}

View File

@ -1,11 +1,11 @@
package io.anuke.mindustry.editor;
import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import io.anuke.arc.function.Consumer;
import io.anuke.arc.scene.ui.TextButton;
import io.anuke.arc.scene.ui.TextField;
import io.anuke.mindustry.core.Platform;
import io.anuke.mindustry.maps.Map;
import io.anuke.mindustry.ui.dialogs.FloatingDialog;
import static io.anuke.mindustry.Vars.ui;
import static io.anuke.mindustry.Vars.world;

View File

@ -3,18 +3,14 @@ package io.anuke.mindustry.editor;
import io.anuke.arc.Core;
import io.anuke.arc.collection.Array;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.ScissorStack;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.input.GestureDetector;
import io.anuke.arc.input.GestureDetector.GestureListener;
import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.*;
import io.anuke.arc.scene.Element;
import io.anuke.arc.scene.event.InputEvent;
import io.anuke.arc.scene.event.InputListener;
import io.anuke.arc.scene.event.Touchable;
import io.anuke.arc.scene.event.*;
import io.anuke.arc.scene.ui.TextField;
import io.anuke.arc.scene.ui.layout.Unit;
import io.anuke.arc.util.Tmp;
@ -69,6 +65,7 @@ public class MapView extends Element implements GestureListener{
return false;
}
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, KeyCode button){
if(pointer != 0){
@ -196,7 +193,7 @@ public class MapView extends Element implements GestureListener{
super.act(delta);
if(Core.scene.getKeyboardFocus() == null || !(Core.scene.getKeyboardFocus() instanceof TextField) &&
!Core.input.keyDown(KeyCode.CONTROL_LEFT)){
!Core.input.keyDown(KeyCode.CONTROL_LEFT)){
float ax = Core.input.axis(Binding.move_x);
float ay = Core.input.axis(Binding.move_y);
offsetx -= ax * 15f / zoom;
@ -224,7 +221,7 @@ public class MapView extends Element implements GestureListener{
}
private Point2 project(float x, float y){
float ratio = 1f / ((float) editor.width() / editor.height());
float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height);
float sclwidth = size * zoom;
float sclheight = size * zoom * ratio;
@ -232,26 +229,26 @@ public class MapView extends Element implements GestureListener{
y = (y - getHeight() / 2 + sclheight / 2 - offsety * zoom) / sclheight * editor.height();
if(editor.drawBlock.size % 2 == 0 && tool != EditorTool.eraser){
return Tmp.g1.set((int) (x - 0.5f), (int) (y - 0.5f));
return Tmp.g1.set((int)(x - 0.5f), (int)(y - 0.5f));
}else{
return Tmp.g1.set((int) x, (int) y);
return Tmp.g1.set((int)x, (int)y);
}
}
private Vector2 unproject(int x, int y){
float ratio = 1f / ((float) editor.width() / editor.height());
float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height);
float sclwidth = size * zoom;
float sclheight = size * zoom * ratio;
float px = ((float) x / editor.width()) * sclwidth + offsetx * zoom - sclwidth / 2 + getWidth() / 2;
float py = ((float) (y) / editor.height()) * sclheight
+ offsety * zoom - sclheight / 2 + getHeight() / 2;
float px = ((float)x / editor.width()) * sclwidth + offsetx * zoom - sclwidth / 2 + getWidth() / 2;
float py = ((float)(y) / editor.height()) * sclheight
+ offsety * zoom - sclheight / 2 + getHeight() / 2;
return vec.set(px, py);
}
@Override
public void draw(){
float ratio = 1f / ((float) editor.width() / editor.height());
float ratio = 1f / ((float)editor.width() / editor.height());
float size = Math.min(width, height);
float sclwidth = size * zoom;
float sclheight = size * zoom * ratio;
@ -317,9 +314,9 @@ public class MapView extends Element implements GestureListener{
Vector2 v = unproject(p.x, p.y).add(x, y);
float offset = (editor.drawBlock.size % 2 == 0 ? scaling / 2f : 0f);
Lines.square(
v.x + scaling / 2f + offset,
v.y + scaling / 2f + offset,
scaling * editor.drawBlock.size / 2f);
v.x + scaling / 2f + offset,
v.y + scaling / 2f + offset,
scaling * editor.drawBlock.size / 2f);
}
}
@ -334,9 +331,9 @@ public class MapView extends Element implements GestureListener{
private boolean active(){
return Core.scene.getKeyboardFocus() != null
&& Core.scene.getKeyboardFocus().isDescendantOf(ui.editor)
&& ui.editor.isShown() && tool == EditorTool.zoom &&
Core.scene.hit(Core.input.mouse().x, Core.input.mouse().y, true) == this;
&& Core.scene.getKeyboardFocus().isDescendantOf(ui.editor)
&& ui.editor.isShown() && tool == EditorTool.zoom &&
Core.scene.hit(Core.input.mouse().x, Core.input.mouse().y, true) == this;
}
@Override

View File

@ -7,9 +7,7 @@ import io.anuke.arc.input.KeyCode;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.scene.ui.TextField.TextFieldFilter;
import io.anuke.arc.scene.ui.layout.Table;
import io.anuke.arc.util.Align;
import io.anuke.arc.util.Strings;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.*;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.content.StatusEffects;
import io.anuke.mindustry.content.UnitTypes;
@ -47,7 +45,7 @@ public class WaveInfoDialog extends FloatingDialog{
});
keyDown(key -> {
if(key == KeyCode.ESCAPE || key == KeyCode.BACK) {
if(key == KeyCode.ESCAPE || key == KeyCode.BACK){
Core.app.post(this::hide);
}
});
@ -74,7 +72,7 @@ public class WaveInfoDialog extends FloatingDialog{
dialog.hide();
}).disabled(b -> Core.app.getClipboard().getContents() == null || Core.app.getClipboard().getContents().isEmpty());
dialog.cont.row();
dialog.cont.addButton("$settings.reset", () -> ui.showConfirm("$confirm", "$settings.clear.confirm", () ->{
dialog.cont.addButton("$settings.reset", () -> ui.showConfirm("$confirm", "$settings.clear.confirm", () -> {
groups = null;
buildGroups();
dialog.hide();
@ -100,7 +98,8 @@ public class WaveInfoDialog extends FloatingDialog{
cont.table("clear", m -> {
m.add("$waves.preview").color(Color.LIGHT_GRAY).growX().center().get().setAlignment(Align.center, Align.center);
m.row();
m.addButton("-", () -> {}).update(t -> {
m.addButton("-", () -> {
}).update(t -> {
if(t.getClickListener().isPressed()){
updateTimer += Time.delta();
if(updateTimer >= updatePeriod){
@ -113,11 +112,12 @@ public class WaveInfoDialog extends FloatingDialog{
m.row();
m.pane(t -> preview = t).grow().get().setScrollingDisabled(true, false);
m.row();
m.addButton("+", () -> {}).update(t -> {
m.addButton("+", () -> {
}).update(t -> {
if(t.getClickListener().isPressed()){
updateTimer += Time.delta();
if(updateTimer >= updatePeriod){
start ++;
start++;
updateTimer = 0f;
updateWaves();
}
@ -146,10 +146,10 @@ public class WaveInfoDialog extends FloatingDialog{
t.row();
t.table(spawns -> {
spawns.addField("" + (group.begin + 1), TextFieldFilter.digitsOnly, text -> {
if(Strings.canParsePostiveInt(text)){
group.begin = Strings.parseInt(text) - 1;
updateWaves();
}
if(Strings.canParsePostiveInt(text)){
group.begin = Strings.parseInt(text) - 1;
updateWaves();
}
}).width(100f);
spawns.add("$waves.to").padLeft(4).padRight(4);
spawns.addField(group.end == never ? "" : (group.end + 1) + "", TextFieldFilter.digitsOnly, text -> {
@ -184,7 +184,7 @@ public class WaveInfoDialog extends FloatingDialog{
}).width(80f);
a.add(" + ");
a.addField(Strings.fixed(Math.max((Mathf.isZero(group.unitScaling) ? 0 : 1f/group.unitScaling), 0), 2), TextFieldFilter.floatsOnly, text -> {
a.addField(Strings.fixed(Math.max((Mathf.isZero(group.unitScaling) ? 0 : 1f / group.unitScaling), 0), 2), TextFieldFilter.floatsOnly, text -> {
if(Strings.canParsePositiveFloat(text)){
group.unitScaling = 1f / Strings.parseFloat(text);
updateWaves();
@ -228,7 +228,7 @@ public class WaveInfoDialog extends FloatingDialog{
dialog.hide();
buildGroups();
}).pad(2).margin(12f).fillX();
if(++i % 3 == 0)dialog.cont.row();
if(++i % 3 == 0) dialog.cont.row();
}
dialog.show();
}
@ -239,10 +239,10 @@ public class WaveInfoDialog extends FloatingDialog{
Array<SpawnGroup> groups = (this.groups == null ? DefaultWaves.get() : this.groups);
for(int i = start; i < displayed + start; i ++){
for(int i = start; i < displayed + start; i++){
int wave = i;
preview.table("underline", table -> {
table.add((wave+1) + "").color(Pal.accent).center().colspan(2).get().setAlignment(Align.center, Align.center);
table.add((wave + 1) + "").color(Pal.accent).center().colspan(2).get().setAlignment(Align.center, Align.center);
table.row();
int[] spawned = new int[Vars.content.getBy(ContentType.unit).size];

View File

@ -11,14 +11,14 @@ public class DistortFilter extends GenerateFilter{
{
options(
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 400f),
new SliderOption("mag", () -> mag, f -> mag = f, 0.5f, 100f)
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 400f),
new SliderOption("mag", () -> mag, f -> mag = f, 0.5f, 100f)
);
}
@Override
public void apply(){
DummyTile tile = in.tile(in.x / (in.scaling) + (noise(in.x, in.y, scl, mag)-mag/2f)/in.scaling, in.y / (in.scaling) + (noise(in.x, in.y+o, scl, mag)-mag/2f)/in.scaling);
DummyTile tile = in.tile(in.x / (in.scaling) + (noise(in.x, in.y, scl, mag) - mag / 2f) / in.scaling, in.y / (in.scaling) + (noise(in.x, in.y + o, scl, mag) - mag / 2f) / in.scaling);
in.floor = content.block(tile.floor);
if(!content.block(tile.block).synthetic() && !in.block.synthetic()) in.block = content.block(tile.block);

View File

@ -20,7 +20,9 @@ public abstract class FilterOption{
public static final Predicate<Block> oresOnly = b -> b instanceof OreBlock && Core.atlas.isFound(b.icon(Icon.full));
public abstract void build(Table table);
public Runnable changed = () -> {};
public Runnable changed = () -> {
};
static class SliderOption extends FilterOption{
final String name;
@ -40,7 +42,7 @@ public abstract class FilterOption{
public void build(Table table){
table.add("$filter.option." + name);
table.row();
Slider slider = table.addSlider(min, max, (max-min)/200f, setter).growX().get();
Slider slider = table.addSlider(min, max, (max - min) / 200f, setter).growX().get();
slider.setValue(getter.get());
if(updateEditorOnChange){
slider.changed(changed);
@ -65,14 +67,14 @@ public abstract class FilterOption{
@Override
public void build(Table table){
table.addButton(b -> b.addImage(supplier.get().icon(Icon.small)).update(i -> ((TextureRegionDrawable)i.getDrawable()).setRegion(supplier.get().icon(Icon.small))).size(8*3), () -> {
table.addButton(b -> b.addImage(supplier.get().icon(Icon.small)).update(i -> ((TextureRegionDrawable)i.getDrawable()).setRegion(supplier.get().icon(Icon.small))).size(8 * 3), () -> {
FloatingDialog dialog = new FloatingDialog("");
dialog.setFillParent(false);
int i = 0;
for(Block block : Vars.content.blocks()){
if(!filter.test(block)) continue;
dialog.cont.addImage(block.icon(Icon.medium)).size(8*4).pad(3).get().clicked(() -> {
dialog.cont.addImage(block.icon(Icon.medium)).size(8 * 4).pad(3).get().clicked(() -> {
consumer.accept(block);
dialog.hide();
changed.run();

View File

@ -11,7 +11,7 @@ import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.blocks.Floor;
public abstract class GenerateFilter{
protected float o = (float)(Math.random()*10000000.0);
protected float o = (float)(Math.random() * 10000000.0);
protected long seed;
protected GenerateInput in;
@ -20,15 +20,15 @@ public abstract class GenerateFilter{
protected abstract void apply();
protected float noise(float x, float y, float scl, float mag){
return (float)in.noise.octaveNoise2D(1f, 0f, 1f/scl, x + o, y + o)*mag;
return (float)in.noise.octaveNoise2D(1f, 0f, 1f / scl, x + o, y + o) * mag;
}
protected float noise(float x, float y, float scl, float mag, float octaves, float persistence){
return (float)in.noise.octaveNoise2D(octaves, persistence, 1f/scl, x + o, y + o)*mag;
return (float)in.noise.octaveNoise2D(octaves, persistence, 1f / scl, x + o, y + o) * mag;
}
protected float rnoise(float x, float y, float scl, float mag){
return in.pnoise.getValue((int)(x + o), (int)(y + o), 1f/scl)*mag;
return in.pnoise.getValue((int)(x + o), (int)(y + o), 1f / scl) * mag;
}
public void randomize(){

View File

@ -14,12 +14,12 @@ public class NoiseFilter extends GenerateFilter{
{
options(
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("wall", () -> block, b -> block = b, wallsOnly)
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("wall", () -> block, b -> block = b, wallsOnly)
);
}

View File

@ -4,7 +4,8 @@ import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.editor.generation.FilterOption.SliderOption;
import io.anuke.mindustry.world.Block;
import static io.anuke.mindustry.editor.generation.FilterOption.*;
import static io.anuke.mindustry.editor.generation.FilterOption.BlockOption;
import static io.anuke.mindustry.editor.generation.FilterOption.oresOnly;
public class OreFilter extends GenerateFilter{
float scl = 40, threshold = 0.8f, octaves = 3f, falloff = 0.5f;
@ -12,11 +13,11 @@ public class OreFilter extends GenerateFilter{
{
options(
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("ore", () -> ore, b -> ore = b, oresOnly)
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("ore", () -> ore, b -> ore = b, oresOnly)
);
}

View File

@ -14,12 +14,12 @@ public class RiverNoiseFilter extends GenerateFilter{
{
options(
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("threshold2", () -> threshold2, f -> threshold2 = f, 0f, 1f),
new BlockOption("block", () -> block, b -> block = b, wallsOnly),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("floor2", () -> floor2, b -> floor2 = b, floorsOnly)
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("threshold2", () -> threshold2, f -> threshold2 = f, 0f, 1f),
new BlockOption("block", () -> block, b -> block = b, wallsOnly),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("floor2", () -> floor2, b -> floor2 = b, floorsOnly)
);
}

View File

@ -14,16 +14,16 @@ public class ScatterFilter extends GenerateFilter{
{
options(
new SliderOption("chance", () -> chance, f -> chance = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("block", () -> block, b -> block = b, wallsOnly)
new SliderOption("chance", () -> chance, f -> chance = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("block", () -> block, b -> block = b, wallsOnly)
);
}
@Override
public void apply(){
if(in.srcfloor == floor && in.srcblock == Blocks.air && chance() <= chance){
if(in.srcfloor == floor && in.srcblock == Blocks.air && chance() <= chance){
in.block = block;
}
}

View File

@ -15,20 +15,20 @@ public class TerrainFilter extends GenerateFilter{
{
options(
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("mag", () -> magnitude, f -> magnitude = f, 0f, 2f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("circle-scale", () -> circleScl, f -> circleScl = f, 0f, 3f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("wall", () -> block, b -> block = b, wallsOnly)
new SliderOption("scale", () -> scl, f -> scl = f, 1f, 500f),
new SliderOption("mag", () -> magnitude, f -> magnitude = f, 0f, 2f),
new SliderOption("threshold", () -> threshold, f -> threshold = f, 0f, 1f),
new SliderOption("circle-scale", () -> circleScl, f -> circleScl = f, 0f, 3f),
new SliderOption("octaves", () -> octaves, f -> octaves = f, 1f, 10f),
new SliderOption("falloff", () -> falloff, f -> falloff = f, 0f, 1f),
new BlockOption("floor", () -> floor, b -> floor = b, floorsOnly),
new BlockOption("wall", () -> block, b -> block = b, wallsOnly)
);
}
@Override
public void apply(){
float noise = noise(in.x, in.y, scl, magnitude, octaves, falloff) + Mathf.dst((float) in.x / in.editor.width(), (float) in.y / in.editor.height(), 0.5f, 0.5f) * circleScl;
float noise = noise(in.x, in.y, scl, magnitude, octaves, falloff) + Mathf.dst((float)in.x / in.editor.width(), (float)in.y / in.editor.height(), 0.5f, 0.5f) * circleScl;
in.floor = floor;
in.ore = Blocks.air;

View File

@ -7,10 +7,7 @@ import io.anuke.arc.function.Consumer;
import io.anuke.arc.function.Predicate;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.math.geom.*;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.content.Fx;
@ -27,7 +24,7 @@ import io.anuke.mindustry.world.Tile;
import static io.anuke.mindustry.Vars.*;
/**Utility class for damaging in an area.*/
/** Utility class for damaging in an area. */
public class Damage{
private static Rectangle rect = new Rectangle();
private static Rectangle hitrect = new Rectangle();
@ -35,19 +32,19 @@ public class Damage{
private static GridBits bits = new GridBits(30, 30);
private static IntQueue propagation = new IntQueue();
/**Creates a dynamic explosion based on specified parameters.*/
/** Creates a dynamic explosion based on specified parameters. */
public static void dynamicExplosion(float x, float y, float flammability, float explosiveness, float power, float radius, Color color){
for(int i = 0; i < Mathf.clamp(power / 20, 0, 6); i++){
int branches = 5 + Mathf.clamp((int) (power / 30), 1, 20);
int branches = 5 + Mathf.clamp((int)(power / 30), 1, 20);
Time.run(i * 2f + Mathf.random(4f), () -> Lightning.create(Team.none, Pal.power, 3,
x, y, Mathf.random(360f), branches + Mathf.range(2)));
x, y, Mathf.random(360f), branches + Mathf.range(2)));
}
for(int i = 0; i < Mathf.clamp(flammability / 4, 0, 30); i++){
Time.run(i / 2f, () -> Call.createBullet(Bullets.fireball, x, y, Mathf.random(360f)));
}
int waves = Mathf.clamp((int) (explosiveness / 4), 0, 30);
int waves = Mathf.clamp((int)(explosiveness / 4), 0, 30);
for(int i = 0; i < waves; i++){
int f = i;
@ -67,7 +64,7 @@ public class Damage{
float shake = Math.min(explosiveness / 4f + 3f, 9f);
Effects.shake(shake, shake, x, y);
Effects.effect(Fx.dynamicExplosion, x, y, radius/8f);
Effects.effect(Fx.dynamicExplosion, x, y, radius / 8f);
}
public static void createIncend(float x, float y, float range, int amount){
@ -136,7 +133,7 @@ public class Damage{
Units.getNearbyEnemies(team, rect, cons);
}
/**Damages all entities and blocks in a radius that are enemies of the team.*/
/** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damageUnits(Team team, float x, float y, float size, float damage, Predicate<io.anuke.mindustry.entities.type.Unit> predicate, Consumer<io.anuke.mindustry.entities.type.Unit> acceptor){
Consumer<io.anuke.mindustry.entities.type.Unit> cons = entity -> {
if(!predicate.test(entity)) return;
@ -157,17 +154,17 @@ public class Damage{
}
}
/**Damages everything in a radius.*/
/** Damages everything in a radius. */
public static void damage(float x, float y, float radius, float damage){
damage(null, x, y, radius, damage, false);
}
/**Damages all entities and blocks in a radius that are enemies of the team.*/
/** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damage(Team team, float x, float y, float radius, float damage){
damage(team, x, y, radius, damage, false);
}
/**Damages all entities and blocks in a radius that are enemies of the team.*/
/** Damages all entities and blocks in a radius that are enemies of the team. */
public static void damage(Team team, float x, float y, float radius, float damage, boolean complete){
Consumer<Unit> cons = entity -> {
if(entity.getTeam() == team || entity.dst(x, y) > radius){
@ -201,11 +198,11 @@ public class Damage{
public static void tileDamage(Team team, int startx, int starty, int radius, float baseDamage){
bits.clear();
propagation.clear();
int bitOffset = bits.width()/2;
int bitOffset = bits.width() / 2;
propagation.addFirst(PropCell.get((byte)0, (byte)0, (short)baseDamage));
//clamp radius to fit bits
radius = Math.min(radius, bits.width()/2);
radius = Math.min(radius, bits.width() / 2);
while(!propagation.isEmpty()){
int prop = propagation.removeLast();
@ -242,7 +239,7 @@ public class Damage{
}
private static void completeDamage(Team team, float x, float y, float radius, float damage){
int trad = (int) (radius / tilesize);
int trad = (int)(radius / tilesize);
for(int dx = -trad; dx <= trad; dx++){
for(int dy = -trad; dy <= trad; dy++){
Tile tile = world.tile(Math.round(x / tilesize) + dx, Math.round(y / tilesize) + dy);

View File

@ -3,10 +3,7 @@ package io.anuke.mindustry.entities;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntSet;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.QuadTree;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.math.geom.*;
import io.anuke.mindustry.entities.traits.Entity;
import io.anuke.mindustry.entities.traits.SolidTrait;
@ -135,7 +132,7 @@ public class EntityCollisions{
for(Entity entity : group.all()){
if(entity instanceof SolidTrait){
SolidTrait s = (SolidTrait) entity;
SolidTrait s = (SolidTrait)entity;
s.lastPosition().set(s.getX(), s.getY());
tree.insert(s);
}
@ -144,8 +141,8 @@ public class EntityCollisions{
private void checkCollide(Entity entity, Entity other){
SolidTrait a = (SolidTrait) entity;
SolidTrait b = (SolidTrait) other;
SolidTrait a = (SolidTrait)entity;
SolidTrait b = (SolidTrait)other;
a.hitbox(this.r1);
b.hitbox(this.r2);
@ -228,7 +225,7 @@ public class EntityCollisions{
if(!(entity instanceof SolidTrait) || collided.contains(entity.getID()))
continue;
SolidTrait solid = (SolidTrait) entity;
SolidTrait solid = (SolidTrait)entity;
solid.hitbox(r1);
r1.x += (solid.lastPosition().x - solid.getX());

View File

@ -46,7 +46,7 @@ public class EntityDraw{
for(Entity e : group.all()){
if(!(e instanceof DrawTrait) || !toDraw.test((T)e) || !e.isAdded()) continue;
if(!clip || rect.setSize(((DrawTrait) e).drawSize()).setCenter(e.getX(), e.getY()).overlaps(viewport)){
if(!clip || rect.setSize(((DrawTrait)e).drawSize()).setCenter(e.getX(), e.getY()).overlaps(viewport)){
cons.accept((T)e);
}
}

View File

@ -180,7 +180,7 @@ public class EntityGroup<T extends Entity>{
return null;
}
/**Returns the logic-only array for iteration.*/
/** Returns the logic-only array for iteration. */
public Array<T> all(){
return entityArray;
}

View File

@ -74,7 +74,7 @@ public class EntityQuery{
float cdist = 0f;
Array<SolidTrait> entities = getNearby(group, x, y, range * 2f);
for(int i = 0; i < entities.size; i++){
T e = (T) entities.get(i);
T e = (T)entities.get(i);
if(!pred.test(e))
continue;

View File

@ -14,7 +14,6 @@ public class Predict{
/**
* Calculates of intercept of a stationary and moving target. Do not call from multiple threads!
*
* @param srcx X of shooter
* @param srcy Y of shooter
* @param dstx X of target
@ -28,7 +27,7 @@ public class Predict{
dstvx /= Time.delta();
dstvy /= Time.delta();
float tx = dstx - srcx,
ty = dsty - srcy;
ty = dsty - srcy;
// Get quadratic equation components
float a = dstvx * dstvx + dstvy * dstvy - v * v;
@ -57,8 +56,8 @@ public class Predict{
*/
public static Vector2 intercept(TargetTrait src, TargetTrait dst, float v){
return intercept(src.getX(), src.getY(), dst.getX(), dst.getY(),
dst.getTargetVelocityX() - src.getTargetVelocityX(),
dst.getTargetVelocityY() - src.getTargetVelocityY(), v);
dst.getTargetVelocityX() - src.getTargetVelocityX(),
dst.getTargetVelocityY() - src.getTargetVelocityY(), v);
}
private static Vector2 quad(float a, float b, float c){

View File

@ -7,10 +7,7 @@ import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.BaseUnit;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Tile;
@ -29,7 +26,6 @@ public class Units{
/**
* Validates a target.
*
* @param target The target to validate
* @param team The team of the thing doing tha targeting
* @param x The X position of the thing doign the targeting
@ -41,17 +37,17 @@ public class Units{
return target == null || (range != Float.MAX_VALUE && target.dst(x, y) > range) || target.getTeam() == team || !target.isValid();
}
/**See {@link #invalidateTarget(TargetTrait, Team, float, float, float)}*/
/** See {@link #invalidateTarget(TargetTrait, Team, float, float, float)} */
public static boolean invalidateTarget(TargetTrait target, Team team, float x, float y){
return invalidateTarget(target, team, x, y, Float.MAX_VALUE);
}
/**See {@link #invalidateTarget(TargetTrait, Team, float, float, float)}*/
/** See {@link #invalidateTarget(TargetTrait, Team, float, float, float)} */
public static boolean invalidateTarget(TargetTrait target, Unit targeter){
return invalidateTarget(target, targeter.getTeam(), targeter.x, targeter.y, targeter.getWeapon().bullet.range());
}
/**Returns whether there are any entities on this tile.*/
/** Returns whether there are any entities on this tile. */
public static boolean anyEntities(Tile tile){
Block type = tile.block();
rect.setSize(type.size * tilesize, type.size * tilesize);
@ -60,7 +56,7 @@ public class Units{
return anyEntities(rect);
}
/**Can be called from any thread.*/
/** Can be called from any thread. */
public static boolean anyEntities(Rectangle rect){
boolResult = false;
@ -78,7 +74,7 @@ public class Units{
return boolResult;
}
/**Returns whether there are any entities on this tile, with the hitbox expanded.*/
/** Returns whether there are any entities on this tile, with the hitbox expanded. */
public static boolean anyEntities(Tile tile, float expansion, Predicate<Unit> pred){
Block type = tile.block();
rect.setSize(type.size * tilesize + expansion, type.size * tilesize + expansion);
@ -100,18 +96,18 @@ public class Units{
return value[0];
}
/**Returns the neareset damaged tile.*/
/** Returns the neareset damaged tile. */
public static TileEntity findDamagedTile(Team team, float x, float y){
Tile tile = Geometry.findClosest(x, y, world.indexer.getDamaged(team));
return tile == null ? null : tile.entity;
}
/**Returns the neareset ally tile in a range.*/
/** Returns the neareset ally tile in a range. */
public static TileEntity findAllyTile(Team team, float x, float y, float range, Predicate<Tile> pred){
return world.indexer.findTile(team, x, y, range, pred);
}
/**Returns the neareset enemy tile in a range.*/
/** Returns the neareset enemy tile in a range. */
public static TileEntity findEnemyTile(Team team, float x, float y, float range, Predicate<Tile> pred){
if(team == Team.none) return null;
@ -124,7 +120,7 @@ public class Units{
return null;
}
/**Iterates over all units on all teams, including players.*/
/** Iterates over all units on all teams, including players. */
public static void allUnits(Consumer<Unit> cons){
//check all unit groups first
for(EntityGroup<BaseUnit> group : unitGroups){
@ -141,17 +137,17 @@ public class Units{
}
}
/**Returns the closest target enemy. First, units are checked, then tile entities.*/
/** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range){
return getClosestTarget(team, x, y, range, Unit::isValid);
}
/**Returns the closest target enemy. First, units are checked, then tile entities.*/
/** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred){
return getClosestTarget(team, x, y, range, unitPred, t -> true);
}
/**Returns the closest target enemy. First, units are checked, then tile entities.*/
/** Returns the closest target enemy. First, units are checked, then tile entities. */
public static TargetTrait getClosestTarget(Team team, float x, float y, float range, Predicate<Unit> unitPred, Predicate<Tile> tilePred){
Unit unit = getClosestEnemy(team, x, y, range, unitPred);
if(unit != null){
@ -161,7 +157,7 @@ public class Units{
}
}
/**Returns the closest enemy of this team. Filter by predicate.*/
/** Returns the closest enemy of this team. Filter by predicate. */
public static Unit getClosestEnemy(Team team, float x, float y, float range, Predicate<Unit> predicate){
if(team == Team.none) return null;
@ -186,7 +182,7 @@ public class Units{
return result;
}
/**Returns the closest ally of this team. Filter by predicate.*/
/** Returns the closest ally of this team. Filter by predicate. */
public static Unit getClosest(Team team, float x, float y, float range, Predicate<Unit> predicate){
result = null;
cdist = 0f;
@ -209,21 +205,21 @@ public class Units{
return result;
}
/**Iterates over all units in a rectangle.*/
/** Iterates over all units in a rectangle. */
public static void getNearby(Team team, Rectangle rect, Consumer<Unit> cons){
EntityGroup<BaseUnit> group = unitGroups[team.ordinal()];
if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity));
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
}
//now check all players
EntityQuery.getNearby(playerGroup, rect, player -> {
if(((Unit) player).getTeam() == team) cons.accept((Unit) player);
if(((Unit)player).getTeam() == team) cons.accept((Unit)player);
});
}
/**Iterates over all units in a circle around this position.*/
/** Iterates over all units in a circle around this position. */
public static void getNearby(Team team, float x, float y, float radius, Consumer<Unit> cons){
rect.setSize(radius * 2).setCenter(x, y);
@ -231,53 +227,53 @@ public class Units{
if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> {
if(entity.dst(x, y) <= radius){
cons.accept((Unit) entity);
cons.accept((Unit)entity);
}
});
}
//now check all players
EntityQuery.getNearby(playerGroup, rect, player -> {
if(((Unit) player).getTeam() == team && player.dst(x, y) <= radius){
cons.accept((Unit) player);
if(((Unit)player).getTeam() == team && player.dst(x, y) <= radius){
cons.accept((Unit)player);
}
});
}
/**Iterates over all units in a rectangle.*/
/** Iterates over all units in a rectangle. */
public static void getNearby(Rectangle rect, Consumer<Unit> cons){
for(Team team : Team.all){
EntityGroup<BaseUnit> group = unitGroups[team.ordinal()];
if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity));
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
}
}
//now check all enemy players
EntityQuery.getNearby(playerGroup, rect, player -> cons.accept((Unit) player));
EntityQuery.getNearby(playerGroup, rect, player -> cons.accept((Unit)player));
}
/**Iterates over all units that are enemies of this team.*/
/** Iterates over all units that are enemies of this team. */
public static void getNearbyEnemies(Team team, Rectangle rect, Consumer<Unit> cons){
EnumSet<Team> targets = state.teams.enemiesOf(team);
for(Team other : targets){
EntityGroup<BaseUnit> group = unitGroups[other.ordinal()];
if(!group.isEmpty()){
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit) entity));
EntityQuery.getNearby(group, rect, entity -> cons.accept((Unit)entity));
}
}
//now check all enemy players
EntityQuery.getNearby(playerGroup, rect, player -> {
if(targets.contains(((Player) player).getTeam())){
cons.accept((Unit) player);
if(targets.contains(((Player)player).getTeam())){
cons.accept((Unit)player);
}
});
}
/**Iterates over all units.*/
/** Iterates over all units. */
public static void getAllUnits(Consumer<Unit> cons){
for(Team team : Team.all){

View File

@ -1,9 +1,9 @@
package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect;
//TODO scale velocity depending on fslope()
public class ArtilleryBulletType extends BasicBulletType{

View File

@ -6,7 +6,7 @@ import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.TextureRegion;
import io.anuke.mindustry.graphics.Pal;
/**An extended BulletType for most ammo-based bullets shot from turrets and units.*/
/** An extended BulletType for most ammo-based bullets shot from turrets and units. */
public class BasicBulletType extends BulletType{
public Color backColor = Pal.bulletYellowBack, frontColor = Pal.bulletYellow;
public float bulletWidth = 5f, bulletHeight = 7f;

View File

@ -5,9 +5,7 @@ import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Interval;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.Tmp;
import io.anuke.arc.util.*;
import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.entities.EntityGroup;
@ -18,9 +16,7 @@ import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.world.Tile;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.*;
@ -36,7 +32,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
protected Entity owner;
protected float time;
/**Internal use only!*/
/** Internal use only! */
public Bullet(){
}
@ -64,7 +60,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
bullet.velocity.set(0, type.speed).setAngle(angle).scl(velocityScl);
if(type.keepVelocity){
bullet.velocity.add(owner instanceof VelocityTrait ? ((VelocityTrait) owner).velocity() : Vector2.ZERO);
bullet.velocity.add(owner instanceof VelocityTrait ? ((VelocityTrait)owner).velocity() : Vector2.ZERO);
}
bullet.team = team;
@ -85,13 +81,13 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
return create(type, parent.owner, parent.team, x, y, angle, velocityScl);
}
/**Internal use only.*/
/** Internal use only. */
@Remote(called = Loc.server, unreliable = true)
public static void createBullet(BulletType type, float x, float y, float angle){
create(type, null, Team.none, x, y, angle);
}
/**ok*/
/** ok */
@Remote(called = Loc.server, unreliable = true)
public static void createBullet(BulletType type, Team team, float x, float y, float angle){
create(type, null, team, x, y, angle);
@ -133,7 +129,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
public float damageMultiplier(){
if(owner instanceof Unit){
return ((Unit) owner).getDamageMultipler();
return ((Unit)owner).getDamageMultipler();
}
return 1f;
}
@ -194,7 +190,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
@Override
public boolean collides(SolidTrait other){
return type.collides && (other != owner && !(other instanceof DamageTrait)) && !supressCollision && !(other instanceof Unit && ((Unit) other).isFlying() && !type.collidesAir);
return type.collides && (other != owner && !(other instanceof DamageTrait)) && !supressCollision && !(other instanceof Unit && ((Unit)other).isFlying() && !type.collidesAir);
}
@Override
@ -203,7 +199,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
type.hit(this, x, y);
if(other instanceof Unit){
Unit unit = (Unit) other;
Unit unit = (Unit)other;
unit.velocity().add(Tmp.v3.set(other.getX(), other.getY()).sub(x, y).setLength(type.knockback / unit.mass()));
unit.applyEffect(type.status, type.statusDuration);
}
@ -218,7 +214,7 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
velocity.scl(Mathf.clamp(1f - type.drag * Time.delta()));
time += Time.delta() * 1f/(lifeScl);
time += Time.delta() * 1f / (lifeScl);
time = Mathf.clamp(time, 0, type.lifetime);
if(time >= type.lifetime){
@ -336,12 +332,12 @@ public class Bullet extends SolidEntity implements DamageTrait, ScaleTrait, Pool
velocity.limit(f);
}
/** Sets the bullet's rotation in degrees.*/
/** Sets the bullet's rotation in degrees. */
public void rot(float angle){
velocity.setAngle(angle);
}
/** @return the bullet's rotation.*/
/** @return the bullet's rotation. */
public float rot(){
float angle = Mathf.atan2(velocity.x, velocity.y) * Mathf.radiansToDegrees;
if(angle < 0) angle += 360;

View File

@ -4,10 +4,8 @@ import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.content.StatusEffects;
import io.anuke.mindustry.entities.Damage;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.effect.Lightning;
import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.game.Content;
@ -26,39 +24,39 @@ public abstract class BulletType extends Content{
public boolean pierce;
public Effect hitEffect, despawnEffect;
/**Effect created when shooting.*/
/** Effect created when shooting. */
public Effect shootEffect = Fx.shootSmall;
/**Extra smoke effect created when shooting.*/
/** Extra smoke effect created when shooting. */
public Effect smokeEffect = Fx.shootSmallSmoke;
/**Extra inaccuracy when firing.*/
/** Extra inaccuracy when firing. */
public float inaccuracy = 0f;
/**How many bullets get created per ammo item/liquid.*/
/** How many bullets get created per ammo item/liquid. */
public float ammoMultiplier = 1f;
/**Multiplied by turret reload speed to get final shoot speed.*/
/** Multiplied by turret reload speed to get final shoot speed. */
public float reloadMultiplier = 1f;
/**Recoil from shooter entities.*/
/** Recoil from shooter entities. */
public float recoil;
public float splashDamage = 0f;
/**Knockback in velocity.*/
/** Knockback in velocity. */
public float knockback;
/**Whether this bullet hits tiles.*/
/** Whether this bullet hits tiles. */
public boolean hitTiles = true;
/**Status effect applied on hit.*/
/** Status effect applied on hit. */
public StatusEffect status = StatusEffects.none;
/**Intensity of applied status effect in terms of duration.*/
/** Intensity of applied status effect in terms of duration. */
public float statusDuration = 60 * 1f;
/**Whether to sync this bullet to clients.*/
/** Whether to sync this bullet to clients. */
public boolean syncable;
/**Whether this bullet type collides with tiles.*/
/** Whether this bullet type collides with tiles. */
public boolean collidesTiles = true;
/**Whether this bullet type collides with tiles that are of the same team.*/
/** Whether this bullet type collides with tiles that are of the same team. */
public boolean collidesTeam = false;
/**Whether this bullet type collides with air units.*/
/** Whether this bullet type collides with air units. */
public boolean collidesAir = true;
/**Whether this bullet types collides with anything at all.*/
/** Whether this bullet types collides with anything at all. */
public boolean collides = true;
/**Whether velocity is inherited from the shooter.*/
/** Whether velocity is inherited from the shooter. */
public boolean keepVelocity = true;
//additional effects
@ -67,7 +65,7 @@ public abstract class BulletType extends Content{
public float fragVelocityMin = 0.2f, fragVelocityMax = 1f;
public BulletType fragBullet = null;
/**Use a negative value to disable splash damage.*/
/** Use a negative value to disable splash damage. */
public float splashDamageRadius = -1f;
public int incendAmount = 0;
@ -90,7 +88,7 @@ public abstract class BulletType extends Content{
despawnEffect = Fx.hitBulletSmall;
}
/**Returns maximum distance the bullet this bullet type has can travel.*/
/** Returns maximum distance the bullet this bullet type has can travel. */
public float range(){
return speed * lifetime * (1f - drag);
}
@ -136,7 +134,7 @@ public abstract class BulletType extends Content{
hit(b);
}
for (int i = 0; i < lightining; i++) {
for(int i = 0; i < lightining; i++){
Lightning.create(b.getTeam(), Pal.surge, damage, b.x, b.y, Mathf.random(360f), lightningLength);
}
}

View File

@ -1,9 +1,9 @@
package io.anuke.mindustry.entities.bullet;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Units;
import io.anuke.arc.util.Time;
public abstract class FlakBulletType extends BasicBulletType{
protected static Rectangle rect = new Rectangle();
@ -24,7 +24,7 @@ public abstract class FlakBulletType extends BasicBulletType{
if(b.getData() instanceof Integer) return;
if(b.timer.get(2, 6)){
Units.getNearbyEnemies(b.getTeam(), rect.setSize(explodeRange*2f).setCenter(b.x, b.y), unit -> {
Units.getNearbyEnemies(b.getTeam(), rect.setSize(explodeRange * 2f).setCenter(b.x, b.y), unit -> {
if(b.getData() instanceof Float) return;
if(unit.dst(b) < explodeRange){

View File

@ -1,6 +1,5 @@
package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
@ -8,6 +7,7 @@ import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.effect.Fire;
import io.anuke.mindustry.entities.effect.Puddle;
import io.anuke.mindustry.type.Liquid;
@ -35,11 +35,11 @@ public class LiquidBulletType extends BulletType{
@Override
public float range(){
return speed * lifetime /2f;
return speed * lifetime / 2f;
}
@Override
public void update(Bullet b) {
public void update(Bullet b){
super.update(b);
if(liquid.canExtinguish()){

View File

@ -1,11 +1,11 @@
package io.anuke.mindustry.entities.bullet;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.world.blocks.distribution.MassDriver.DriverBulletData;
@ -45,7 +45,7 @@ public class MassDriverBolt extends BulletType{
float hitDst = 7f;
DriverBulletData data = (DriverBulletData) b.getData();
DriverBulletData data = (DriverBulletData)b.getData();
//if the target is dead, just keep flying until the bullet explodes
if(data.to.isDead()){
@ -87,7 +87,7 @@ public class MassDriverBolt extends BulletType{
if(!(b.getData() instanceof DriverBulletData)) return;
DriverBulletData data = (DriverBulletData) b.getData();
DriverBulletData data = (DriverBulletData)b.getData();
data.to.isRecieving = false;
for(int i = 0; i < data.items.length; i++){

View File

@ -1,11 +1,11 @@
package io.anuke.mindustry.entities.bullet;
import io.anuke.arc.graphics.Color;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.entities.Effects;
import io.anuke.arc.util.Time;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.graphics.Pal;
public class MissileBulletType extends BasicBulletType{
protected Color trailColor = Pal.missileYellowBack;

View File

@ -1,12 +1,12 @@
package io.anuke.mindustry.entities.effect;
import io.anuke.arc.graphics.Color;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.math.Mathf;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.BelowLiquidTrait;
import io.anuke.mindustry.entities.traits.DrawTrait;
import static io.anuke.mindustry.Vars.groundEffectGroup;

View File

@ -3,9 +3,6 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.IntMap;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2;
@ -13,22 +10,17 @@ import io.anuke.arc.util.Structs;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.content.StatusEffects;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Damage;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.content.*;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.SaveTrait;
import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.*;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.*;
@ -42,10 +34,11 @@ public class Fire extends TimedEntity implements SaveTrait, SyncTrait, Poolable{
private float baseFlammability = -1, puddleFlammability;
private float lifetime;
/**Deserialization use only!*/
public Fire(){}
/** Deserialization use only! */
public Fire(){
}
/**Start a fire on the tile. If there already is a file there, refreshes its lifetime.*/
/** Start a fire on the tile. If there already is a file there, refreshes its lifetime. */
public static void create(Tile tile){
if(Net.client() || tile == null) return; //not clientside.
@ -153,8 +146,8 @@ public class Fire extends TimedEntity implements SaveTrait, SyncTrait, Poolable{
entity.damage(0.4f);
}
Damage.damageUnits(null, tile.worldx(), tile.worldy(), tilesize, 3f,
unit -> !unit.isFlying() && !unit.isImmune(StatusEffects.burning),
unit -> unit.applyEffect(StatusEffects.burning, 60 * 5));
unit -> !unit.isFlying() && !unit.isImmune(StatusEffects.burning),
unit -> unit.applyEffect(StatusEffects.burning, 60 * 5));
}
}

View File

@ -1,12 +1,12 @@
package io.anuke.mindustry.entities.effect;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.Effects.Effect;
import io.anuke.mindustry.entities.Effects.EffectRenderer;
import io.anuke.mindustry.entities.impl.EffectEntity;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.util.Time;
import io.anuke.mindustry.Vars;
import io.anuke.mindustry.world.Tile;
/**
@ -17,7 +17,7 @@ public class GroundEffectEntity extends EffectEntity{
@Override
public void update(){
GroundEffect effect = (GroundEffect) this.effect;
GroundEffect effect = (GroundEffect)this.effect;
if(effect.isStatic){
time += Time.delta();
@ -41,7 +41,7 @@ public class GroundEffectEntity extends EffectEntity{
@Override
public void draw(){
GroundEffect effect = (GroundEffect) this.effect;
GroundEffect effect = (GroundEffect)this.effect;
if(once && effect.isStatic)
Effects.renderEffect(id, effect, color, lifetime(), rotation, x, y, data);

View File

@ -2,18 +2,16 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Interpolation;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.type.Item;

View File

@ -4,27 +4,18 @@ import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.IntSet;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.mindustry.entities.traits.TimeTrait;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.RandomXS128;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.*;
import io.anuke.arc.math.geom.*;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.bullet.Bullet;
import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.entities.impl.TimedEntity;
import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.graphics.Pal;
@ -48,16 +39,16 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
private Array<Position> lines = new Array<>();
private Color color = Pal.lancerLaser;
/**For pooling use only. Do not call directly!*/
/** For pooling use only. Do not call directly! */
public Lightning(){
}
/**Create a lighting branch at a location. Use Team.none to damage everyone.*/
/** Create a lighting branch at a location. Use Team.none to damage everyone. */
public static void create(Team team, Color color, float damage, float x, float y, float targetAngle, int length){
Call.createLighting(lastSeed++, team, color, damage, x, y, targetAngle, length);
}
/**Do not invoke!*/
/** Do not invoke! */
@Remote(called = Loc.server)
public static void createLighting(int seed, Team team, Color color, float damage, float x, float y, float rotation, int length){
@ -72,7 +63,7 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
random.setSeed(seed);
hit.clear();
for (int i = 0; i < length/2; i++) {
for(int i = 0; i < length / 2; i++){
Bullet.create(Bullets.damageLightning, l, team, x, y, 0f, 1f, 1f, dmg);
l.lines.add(new Vector2(x + Mathf.range(3f), y + Mathf.range(3f)));
@ -94,8 +85,8 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
y = furthest.y;
}else{
rotation += random.range(20f);
x += Angles.trnsx(rotation, hitRange/2f);
y += Angles.trnsy(rotation, hitRange/2f);
x += Angles.trnsx(rotation, hitRange / 2f);
y += Angles.trnsy(rotation, hitRange / 2f);
}
}
}
@ -106,10 +97,12 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
}
@Override
public void write(DataOutput data){}
public void write(DataOutput data){
}
@Override
public void read(DataInput data){}
public void read(DataInput data){
}
@Override
public float lifetime(){
@ -144,7 +137,7 @@ public class Lightning extends TimedEntity implements DrawTrait, SyncTrait, Time
int i = 0;
for(Position p : lines){
Fill.square(p.getX(), p.getY(), (5f - (float)i++/lines.size*2f) * fout(), 45);
Fill.square(p.getX(), p.getY(), (5f - (float)i++ / lines.size * 2f) * fout(), 45);
}
Draw.reset();
}

View File

@ -3,36 +3,25 @@ package io.anuke.mindustry.entities.effect;
import io.anuke.annotations.Annotations.Loc;
import io.anuke.annotations.Annotations.Remote;
import io.anuke.arc.collection.IntMap;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.EntityGroup;
import io.anuke.mindustry.entities.impl.SolidEntity;
import io.anuke.mindustry.entities.traits.DrawTrait;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Geometry;
import io.anuke.arc.math.geom.Point2;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.*;
import io.anuke.arc.util.Time;
import io.anuke.arc.util.pooling.Pool.Poolable;
import io.anuke.arc.util.pooling.Pools;
import io.anuke.mindustry.content.Liquids;
import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.content.Bullets;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Units;
import io.anuke.mindustry.entities.traits.SaveTrait;
import io.anuke.mindustry.entities.traits.SyncTrait;
import io.anuke.mindustry.content.*;
import io.anuke.mindustry.entities.*;
import io.anuke.mindustry.entities.impl.SolidEntity;
import io.anuke.mindustry.entities.traits.*;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Liquid;
import io.anuke.mindustry.world.Tile;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.*;
@ -55,21 +44,21 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
private float accepting;
private byte generation;
/**Deserialization use only!*/
/** Deserialization use only! */
public Puddle(){
}
/**Deposists a puddle between tile and source.*/
/** Deposists a puddle between tile and source. */
public static void deposit(Tile tile, Tile source, Liquid liquid, float amount){
deposit(tile, source, liquid, amount, 0);
}
/**Deposists a puddle at a tile.*/
/** Deposists a puddle at a tile. */
public static void deposit(Tile tile, Liquid liquid, float amount){
deposit(tile, tile, liquid, amount, 0);
}
/**Returns the puddle on the specified tile. May return null.*/
/** Returns the puddle on the specified tile. May return null. */
public static Puddle getPuddle(Tile tile){
return map.get(tile.pos());
}
@ -79,13 +68,13 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
if(tile.floor().isLiquid && !canStayOn(liquid, tile.floor().liquidDrop)){
reactPuddle(tile.floor().liquidDrop, liquid, amount, tile,
(tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
(tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
Puddle p = map.get(tile.pos());
if(generation == 0 && p != null && p.lastRipple <= Time.time() - 40f){
Effects.effect(Fx.ripple, tile.floor().liquidDrop.color,
(tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
(tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
p.lastRipple = Time.time();
}
return;
@ -99,14 +88,14 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
puddle.tile = tile;
puddle.liquid = liquid;
puddle.amount = amount;
puddle.generation = (byte) generation;
puddle.generation = (byte)generation;
puddle.set((tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
puddle.add();
map.put(tile.pos(), puddle);
}else if(p.liquid == liquid){
p.accepting = Math.max(amount, p.accepting);
if(generation == 0 && p.lastRipple <= Time.time() - 40f && p.amount >= maxLiquid / 2f){
if(generation == 0 && p.lastRipple <= Time.time() - 40f && p.amount >= maxLiquid / 2f){
Effects.effect(Fx.ripple, p.liquid.color, (tile.worldx() + source.worldx()) / 2f, (tile.worldy() + source.worldy()) / 2f);
p.lastRipple = Time.time();
}
@ -123,10 +112,10 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
return liquid == Liquids.oil && other == Liquids.water;
}
/**Reacts two liquids together at a location.*/
/** Reacts two liquids together at a location. */
private static float reactPuddle(Liquid dest, Liquid liquid, float amount, Tile tile, float x, float y){
if((dest.flammability > 0.3f && liquid.temperature > 0.7f) ||
(liquid.flammability > 0.3f && dest.temperature > 0.7f)){ //flammable liquid + hot liquid
(liquid.flammability > 0.3f && dest.temperature > 0.7f)){ //flammable liquid + hot liquid
Fire.create(tile);
if(Mathf.chance(0.006 * amount)){
Call.createBullet(Bullets.fireball, x, y, Mathf.random(360f));
@ -234,7 +223,7 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
Fill.circle(x + Mathf.sin(Time.time() + seeds * 532, sscl, smag), y + Mathf.sin(Time.time() + seeds * 53, sscl, smag), f * 8f);
Angles.randLenVectors(id, 3, f * 6f, (ex, ey) -> {
Fill.circle(x + ex + Mathf.sin(Time.time() + seeds * 532, sscl, smag),
y + ey + Mathf.sin(Time.time() + seeds * 53, sscl, smag), f * 5f);
y + ey + Mathf.sin(Time.time() + seeds * 53, sscl, smag), f * 5f);
seeds++;
});
Draw.color();
@ -295,7 +284,7 @@ public class Puddle extends SolidEntity implements SaveTrait, Poolable, DrawTrai
data.writeFloat(x);
data.writeFloat(y);
data.writeByte(liquid.id);
data.writeShort((short) (amount * 4));
data.writeShort((short)(amount * 4));
data.writeInt(tile.pos());
}

View File

@ -11,7 +11,7 @@ public class RubbleDecal extends Decal{
private static final TextureRegion[][] regions = new TextureRegion[16][0];
private TextureRegion region;
/**Creates a rubble effect at a position. Provide a block size to use.*/
/** Creates a rubble effect at a position. Provide a block size to use. */
public static void create(float x, float y, int size){
if(headless) return;

View File

@ -40,10 +40,10 @@ public class ScorchDecal extends Decal{
float space = 1.5f + Mathf.randomSeed(id + i + 1, 0, 20) / 10f;
Draw.rect(region,
x + Angles.trnsx(rotation, space),
y + Angles.trnsy(rotation, space) + region.getHeight()/2f*Draw.scl,
y + Angles.trnsy(rotation, space) + region.getHeight() / 2f * Draw.scl,
region.getWidth() * Draw.scl,
region.getHeight() * Draw.scl,
region.getWidth()/2f*Draw.scl, 0, rotation - 90);
region.getWidth() / 2f * Draw.scl, 0, rotation - 90);
}
}
}

View File

@ -1,9 +1,7 @@
package io.anuke.mindustry.entities.impl;
import io.anuke.mindustry.entities.traits.DamageTrait;
import io.anuke.mindustry.entities.traits.HealthTrait;
import io.anuke.mindustry.entities.traits.SolidTrait;
import io.anuke.mindustry.entities.traits.*;
public abstract class DestructibleEntity extends SolidEntity implements HealthTrait{
public transient boolean dead;
@ -18,7 +16,7 @@ public abstract class DestructibleEntity extends SolidEntity implements HealthTr
public void collision(SolidTrait other, float x, float y){
if(other instanceof DamageTrait){
onHit(other);
damage(((DamageTrait) other).damage());
damage(((DamageTrait)other).damage());
}
}

View File

@ -5,9 +5,7 @@ import io.anuke.arc.Events;
import io.anuke.arc.collection.Array;
import io.anuke.arc.collection.Queue;
import io.anuke.arc.graphics.Color;
import io.anuke.arc.graphics.g2d.Draw;
import io.anuke.arc.graphics.g2d.Fill;
import io.anuke.arc.graphics.g2d.Lines;
import io.anuke.arc.graphics.g2d.*;
import io.anuke.arc.math.Angles;
import io.anuke.arc.math.Mathf;
import io.anuke.arc.math.geom.Vector2;
@ -16,29 +14,23 @@ import io.anuke.mindustry.Vars;
import io.anuke.mindustry.content.Blocks;
import io.anuke.mindustry.content.Fx;
import io.anuke.mindustry.entities.Effects;
import io.anuke.mindustry.entities.type.Player;
import io.anuke.mindustry.entities.type.TileEntity;
import io.anuke.mindustry.entities.type.Unit;
import io.anuke.mindustry.entities.type.*;
import io.anuke.mindustry.game.EventType.BuildSelectEvent;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.graphics.Shapes;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Build;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.blocks.BuildBlock;
import io.anuke.mindustry.world.blocks.BuildBlock.BuildEntity;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import java.util.Arrays;
import static io.anuke.mindustry.Vars.*;
import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.*;
import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.removal;
import static io.anuke.mindustry.entities.traits.BuilderTrait.BuildDataStatic.tmptr;
/**
* Interface for units that build, break or mine things.
@ -54,25 +46,25 @@ public interface BuilderTrait extends Entity, TeamTrait{
static Vector2[] tmptr = new Vector2[]{new Vector2(), new Vector2(), new Vector2(), new Vector2()};
}
/**Returns the queue for storing build requests.*/
/** Returns the queue for storing build requests. */
Queue<BuildRequest> getPlaceQueue();
/**Returns the tile this builder is currently mining.*/
/** Returns the tile this builder is currently mining. */
Tile getMineTile();
/**Sets the tile this builder is currently mining.*/
/** Sets the tile this builder is currently mining. */
void setMineTile(Tile tile);
/**Returns the minining speed of this miner. 1 = standard, 0.5 = half speed, 2 = double speed, etc.*/
/** Returns the minining speed of this miner. 1 = standard, 0.5 = half speed, 2 = double speed, etc. */
float getMinePower();
/**Build power, can be any float. 1 = builds recipes in normal time, 0 = doesn't build at all.*/
/** Build power, can be any float. 1 = builds recipes in normal time, 0 = doesn't build at all. */
float getBuildPower(Tile tile);
/**Returns whether or not this builder can mine a specific item type.*/
/** Returns whether or not this builder can mine a specific item type. */
boolean canMine(Item item);
/**Whether this type of builder can begin creating new blocks.*/
/** Whether this type of builder can begin creating new blocks. */
default boolean canCreateBlocks(){
return true;
}
@ -106,13 +98,13 @@ public interface BuilderTrait extends Entity, TeamTrait{
float progress = input.readFloat();
BuildRequest request;
if(type == 1){ //remove
request = new BuildRequest(Pos.x(position), Pos.y(position));
}else{ //place
byte block = input.readByte();
byte rotation = input.readByte();
request = new BuildRequest(Pos.x(position), Pos.y(position), rotation, content.block(block));
}
if(type == 1){ //remove
request = new BuildRequest(Pos.x(position), Pos.y(position));
}else{ //place
byte block = input.readByte();
byte rotation = input.readByte();
request = new BuildRequest(Pos.x(position), Pos.y(position), rotation, content.block(block));
}
request.progress = progress;
@ -124,17 +116,17 @@ public interface BuilderTrait extends Entity, TeamTrait{
}
}
/**Return whether this builder's place queue contains items.*/
/** Return whether this builder's place queue contains items. */
default boolean isBuilding(){
return getPlaceQueue().size != 0;
}
/**Clears the placement queue.*/
/** Clears the placement queue. */
default void clearBuilding(){
getPlaceQueue().clear();
}
/**Add another build requests to the tail of the queue, if it doesn't exist there yet.*/
/** Add another build requests to the tail of the queue, if it doesn't exist there yet. */
default void addBuildRequest(BuildRequest place){
for(BuildRequest request : getPlaceQueue()){
if(request.x == place.x && request.y == place.y){
@ -172,8 +164,8 @@ public interface BuilderTrait extends Entity, TeamTrait{
for(BuildRequest request : removal){
if(!((request.breaking && world.tile(request.x, request.y).block() == Blocks.air) ||
(!request.breaking && (world.tile(request.x, request.y).getRotation() == request.rotation || !request.block.rotate)
&& world.tile(request.x, request.y).block() == request.block))){
(!request.breaking && (world.tile(request.x, request.y).getRotation() == request.rotation || !request.block.rotate)
&& world.tile(request.x, request.y).block() == request.block))){
getPlaceQueue().addLast(request);
}
}
@ -249,14 +241,14 @@ public interface BuilderTrait extends Entity, TeamTrait{
}
}
/**Do not call directly.*/
/** Do not call directly. */
default void updateMining(){
Unit unit = (Unit)this;
Tile tile = getMineTile();
TileEntity core = unit.getClosestCore();
if(core == null || tile.block() != Blocks.air || dst(tile.worldx(), tile.worldy()) > mineDistance
|| tile.drop() == null || !unit.acceptsItem(tile.drop()) || !canMine(tile.drop())){
|| tile.drop() == null || !unit.acceptsItem(tile.drop()) || !canMine(tile.drop())){
setMineTile(null);
}else{
Item item = tile.drop();
@ -266,25 +258,25 @@ public interface BuilderTrait extends Entity, TeamTrait{
if(unit.dst(core) < mineTransferRange && core.tile.block().acceptStack(item, 1, core.tile, unit) == 1){
Call.transferItemTo(item, 1,
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f), core.tile);
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f), core.tile);
}else if(unit.acceptsItem(item)){
Call.transferItemToUnit(item,
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f),
unit);
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f),
unit);
}
}
if(Mathf.chance(0.06 * Time.delta())){
Effects.effect(Fx.pulverizeSmall,
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f), 0f, item.color);
tile.worldx() + Mathf.range(tilesize / 2f),
tile.worldy() + Mathf.range(tilesize / 2f), 0f, item.color);
}
}
}
/**Draw placement effects for an entity. This includes mining*/
/** Draw placement effects for an entity. This includes mining */
default void drawBuilding(){
Unit unit = (Unit)this;
BuildRequest request;
@ -317,10 +309,10 @@ public interface BuilderTrait extends Entity, TeamTrait{
tmptr[3].set(tile.drawx() + sz, tile.drawy() + sz);
Arrays.sort(tmptr, (a, b) -> -Float.compare(Angles.angleDist(Angles.angle(unit.x, unit.y, a.x, a.y), ang),
Angles.angleDist(Angles.angle(unit.x, unit.y, b.x, b.y), ang)));
Angles.angleDist(Angles.angle(unit.x, unit.y, b.x, b.y), ang)));
float x1 = tmptr[0].x, y1 = tmptr[0].y,
x3 = tmptr[1].x, y3 = tmptr[1].y;
x3 = tmptr[1].x, y3 = tmptr[1].y;
Draw.alpha(1f);
@ -332,7 +324,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Draw.color();
}
/**Internal use only.*/
/** Internal use only. */
default void drawMining(){
Unit unit = (Unit)this;
Tile tile = getMineTile();
@ -353,7 +345,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Shapes.laser("minelaser", "minelaser-end", px, py, ex, ey, 0.75f);
if(unit instanceof Player && ((Player) unit).isLocal){
if(unit instanceof Player && ((Player)unit).isLocal){
Lines.stroke(1f, Pal.accent);
Lines.poly(tile.worldx(), tile.worldy(), 4, tilesize / 2f * Mathf.sqrt2, Time.time());
}
@ -361,7 +353,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
Draw.color();
}
/**Class for storing build requests. Can be either a place or remove request.*/
/** Class for storing build requests. Can be either a place or remove request. */
class BuildRequest{
public final int x, y, rotation;
public final Block block;
@ -370,7 +362,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
public float progress;
public boolean initialized;
/**This creates a build request.*/
/** This creates a build request. */
public BuildRequest(int x, int y, int rotation, Block block){
this.x = x;
this.y = y;
@ -379,7 +371,7 @@ public interface BuilderTrait extends Entity, TeamTrait{
this.breaking = false;
}
/**This creates a remove request.*/
/** This creates a remove request. */
public BuildRequest(int x, int y){
this.x = x;
this.y = y;

View File

@ -1,8 +1,6 @@
package io.anuke.mindustry.entities.traits;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
public interface Saveable{
void writeSave(DataOutput stream) throws IOException;

View File

@ -1,11 +1,9 @@
package io.anuke.mindustry.entities.traits;
import io.anuke.mindustry.entities.EntityQuery;
import io.anuke.arc.math.geom.Position;
import io.anuke.arc.math.geom.*;
import io.anuke.arc.math.geom.QuadTree.QuadTreeObject;
import io.anuke.arc.math.geom.Rectangle;
import io.anuke.arc.math.geom.Vector2;
import io.anuke.mindustry.entities.EntityQuery;
public interface SolidTrait extends QuadTreeObject, MoveTrait, VelocityTrait, Entity, Position{
@ -35,7 +33,8 @@ public interface SolidTrait extends QuadTreeObject, MoveTrait, VelocityTrait, En
return true;
}
default void collision(SolidTrait other, float x, float y){}
default void collision(SolidTrait other, float x, float y){
}
default void move(float x, float y){
EntityQuery.collisions().move(this, x, y);

View File

@ -1,17 +1,15 @@
package io.anuke.mindustry.entities.traits;
import io.anuke.mindustry.core.NetClient;
import io.anuke.mindustry.net.Interpolator;
import io.anuke.arc.Core;
import io.anuke.arc.util.Tmp;
import io.anuke.mindustry.core.NetClient;
import io.anuke.mindustry.net.Interpolator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
public interface SyncTrait extends Entity, TypeTrait{
/**Sets the position of this entity and updated the interpolator.*/
/** Sets the position of this entity and updated the interpolator. */
default void setNet(float x, float y){
set(x, y);
@ -24,7 +22,7 @@ public interface SyncTrait extends Entity, TypeTrait{
}
}
/**Interpolate entity position only. Override if you need to interpolate rotations or other values.*/
/** Interpolate entity position only. Override if you need to interpolate rotations or other values. */
default void interpolate(){
if(getInterpolator() == null){
throw new RuntimeException("This entity must have an interpolator to interpolate()!");
@ -47,17 +45,17 @@ public interface SyncTrait extends Entity, TypeTrait{
setY(getInterpolator().pos.y);
}
/**Return the interpolator used for smoothing the position. Optional.*/
/** Return the interpolator used for smoothing the position. Optional. */
default Interpolator getInterpolator(){
return null;
}
/**Whether syncing is enabled for this entity; true by default.*/
/** Whether syncing is enabled for this entity; true by default. */
default boolean isSyncing(){
return true;
}
/**Whether this entity is clipped and not synced when out of viewport.*/
/** Whether this entity is clipped and not synced when out of viewport. */
default boolean isClipped(){
return true;
}

View File

@ -14,14 +14,14 @@ public interface TargetTrait extends Position, VelocityTrait{
default float getTargetVelocityX(){
if(this instanceof SolidTrait){
return ((SolidTrait) this).getDeltaX();
return ((SolidTrait)this).getDeltaX();
}
return velocity().x;
}
default float getTargetVelocityY(){
if(this instanceof SolidTrait){
return ((SolidTrait) this).getDeltaY();
return ((SolidTrait)this).getDeltaY();
}
return velocity().y;
}

View File

@ -28,7 +28,7 @@ public interface VelocityTrait extends MoveTrait{
velocity().scl(1f - drag() * Time.delta());
if(this instanceof SolidTrait){
((SolidTrait) this).move(velocity().x * Time.delta(), velocity().y * Time.delta());
((SolidTrait)this).move(velocity().x * Time.delta(), velocity().y * Time.delta());
}else{
moveBy(velocity().x * Time.delta(), velocity().y * Time.delta());
}

View File

@ -29,7 +29,7 @@ import java.io.*;
import static io.anuke.mindustry.Vars.*;
/**Base class for AI units.*/
/** Base class for AI units. */
public abstract class BaseUnit extends Unit implements ShooterTrait{
protected static int timerIndex = 0;
@ -45,7 +45,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
protected int spawner = noSpawner;
/**internal constructor used for deserialization, DO NOT USE*/
/** internal constructor used for deserialization, DO NOT USE */
public BaseUnit(){
}
@ -78,7 +78,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
return type.drag;
}
/**Initialize the type and team of this unit. Only call once!*/
/** Initialize the type and team of this unit. Only call once! */
public void init(UnitType type, Team team){
if(this.type != null) throw new RuntimeException("This unit is already initialized!");
@ -99,7 +99,7 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
}
public boolean targetHasFlag(BlockFlag flag){
return target instanceof TileEntity && ((TileEntity) target).tile.block().flags.contains(flag);
return target instanceof TileEntity && ((TileEntity)target).tile.block().flags.contains(flag);
}
public void setState(UnitState state){
@ -112,14 +112,14 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
}
}
/**Only runs when the unit has a target.*/
/** Only runs when the unit has a target. */
public void behavior(){
}
public void updateTargeting(){
if(target == null || (target instanceof Unit && (target.isDead() || target.getTeam() == team))
|| (target instanceof TileEntity && ((TileEntity) target).tile.entity == null)){
|| (target instanceof TileEntity && ((TileEntity)target).tile.entity == null)){
target = null;
}
}
@ -166,9 +166,9 @@ public abstract class BaseUnit extends Unit implements ShooterTrait{
float angT = i == 0 ? 0 : Mathf.randomSeedRange(i + 2, 60f);
float lenT = i == 0 ? 0 : Mathf.randomSeedRange(i + 3, 1f) - 1f;
Draw.rect(item.item.icon(Item.Icon.large),
x + Angles.trnsx(rotation + 180f + angT, backTrns + lenT),
y + Angles.trnsy(rotation + 180f + angT, backTrns + lenT),
itemSize, itemSize, rotation);
x + Angles.trnsx(rotation + 180f + angT, backTrns + lenT),
y + Angles.trnsy(rotation + 180f + angT, backTrns + lenT),
itemSize, itemSize, rotation);
}
}
}

View File

@ -127,11 +127,11 @@ public abstract class FlyingUnit extends BaseUnit{
public void drawEngine(){
Draw.color(Pal.engine);
Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset), y + Angles.trnsy(rotation + 180, type.engineOffset),
type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize/4f));
type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize / 4f));
Draw.color(Color.WHITE);
Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset-1f), y + Angles.trnsy(rotation + 180, type.engineOffset-1f),
(type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize/4f)) / 2f);
Fill.circle(x + Angles.trnsx(rotation + 180, type.engineOffset - 1f), y + Angles.trnsy(rotation + 180, type.engineOffset - 1f),
(type.engineSize + Mathf.absin(Time.time(), 2f, type.engineSize / 4f)) / 2f);
Draw.color();
}
@ -141,7 +141,7 @@ public abstract class FlyingUnit extends BaseUnit{
if(Units.invalidateTarget(target, this)){
for(boolean left : Mathf.booleans){
int wi = Mathf.num(left);
weaponAngles[wi] = Mathf.slerpDelta(weaponAngles[wi],rotation, 0.1f);
weaponAngles[wi] = Mathf.slerpDelta(weaponAngles[wi], rotation, 0.1f);
}
}
}
@ -154,8 +154,8 @@ public abstract class FlyingUnit extends BaseUnit{
protected void wobble(){
if(Net.client()) return;
x += Mathf.sin(Time.time() + id * 999, 25f, 0.05f)*Time.delta();
y += Mathf.cos(Time.time() + id * 999, 25f, 0.05f)*Time.delta();
x += Mathf.sin(Time.time() + id * 999, 25f, 0.05f) * Time.delta();
y += Mathf.cos(Time.time() + id * 999, 25f, 0.05f) * Time.delta();
if(velocity.len() <= 0.05f){
//rotation += Mathf.sin(Time.time() + id * 99, 10f, 2f * type.speed)*Time.delta();

View File

@ -111,7 +111,7 @@ public abstract class GroundUnit extends BaseUnit{
public void draw(){
Draw.mixcol(Color.WHITE, hitTime / hitDuration);
float ft = Mathf.sin(walkTime * type.speed*5f, 6f, 2f + type.hitsize/15f);
float ft = Mathf.sin(walkTime * type.speed * 5f, 6f, 2f + type.hitsize / 15f);
Floor floor = getFloorOn();
@ -121,9 +121,9 @@ public abstract class GroundUnit extends BaseUnit{
for(int i : Mathf.signs){
Draw.rect(type.legRegion,
x + Angles.trnsx(baseRotation, ft * i),
y + Angles.trnsy(baseRotation, ft * i),
type.legRegion.getWidth() * i * Draw.scl, type.legRegion.getHeight() * Draw.scl - Mathf.clamp(ft * i, 0, 2), baseRotation - 90);
x + Angles.trnsx(baseRotation, ft * i),
y + Angles.trnsy(baseRotation, ft * i),
type.legRegion.getWidth() * i * Draw.scl, type.legRegion.getHeight() * Draw.scl - Mathf.clamp(ft * i, 0, 2), baseRotation - 90);
}
if(floor.isLiquid){
@ -138,10 +138,10 @@ public abstract class GroundUnit extends BaseUnit{
for(int i : Mathf.signs){
float tra = rotation - 90, trY = -type.weapon.getRecoil(this, i > 0) + type.weaponOffsetY;
float w = - i * type.weapon.region.getWidth() * Draw.scl;
float w = -i * type.weapon.region.getWidth() * Draw.scl;
Draw.rect(type.weapon.region,
x + Angles.trnsx(tra, getWeapon().width * i, trY),
y + Angles.trnsy(tra, getWeapon().width * i, trY), w, type.weapon.region.getHeight() * Draw.scl, rotation - 90);
x + Angles.trnsx(tra, getWeapon().width * i, trY),
y + Angles.trnsy(tra, getWeapon().width * i, trY), w, type.weapon.region.getHeight() * Draw.scl, rotation - 90);
}
drawItems();
@ -211,7 +211,7 @@ public abstract class GroundUnit extends BaseUnit{
if(tile == targetTile) return;
velocity.add(vec.trns(angleTo(targetTile), type.speed*Time.delta()));
velocity.add(vec.trns(angleTo(targetTile), type.speed * Time.delta()));
if(Units.invalidateTarget(target, this)){
rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed);
}
@ -235,7 +235,7 @@ public abstract class GroundUnit extends BaseUnit{
if(tile == targetTile || core == null || dst(core) < 90f) return;
velocity.add(vec.trns(angleTo(targetTile), type.speed*Time.delta()));
velocity.add(vec.trns(angleTo(targetTile), type.speed * Time.delta()));
rotation = Mathf.slerpDelta(rotation, baseRotation, type.rotatespeed);
}
}

View File

@ -365,11 +365,11 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
float size = mech.engineSize * (mech.flying ? 1f : boostHeat);
Draw.color(mech.engineColor);
Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset), y + Angles.trnsy(rotation + 180, mech.engineOffset),
size + Mathf.absin(Time.time(), 2f, size/4f));
size + Mathf.absin(Time.time(), 2f, size / 4f));
Draw.color(Color.WHITE);
Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset-1f), y + Angles.trnsy(rotation + 180, mech.engineOffset-1f),
(size + Mathf.absin(Time.time(), 2f, size/4f)) / 2f);
Fill.circle(x + Angles.trnsx(rotation + 180, mech.engineOffset - 1f), y + Angles.trnsy(rotation + 180, mech.engineOffset - 1f),
(size + Mathf.absin(Time.time(), 2f, size / 4f)) / 2f);
Draw.color();
}
@ -443,15 +443,16 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
TextureRegion region = draw.region;
Draw.rect(region,
request.x * tilesize + request.block.offset(), request.y * tilesize + request.block.offset(),
region.getWidth() * 1f * Draw.scl * draw.scalex,
region.getHeight() * 1f * Draw.scl * draw.scaley, request.block.rotate ? draw.rotation * 90 : 0);
request.x * tilesize + request.block.offset(), request.y * tilesize + request.block.offset(),
region.getWidth() * 1f * Draw.scl * draw.scalex,
region.getHeight() * 1f * Draw.scl * draw.scaley, request.block.rotate ? draw.rotation * 90 : 0);
Draw.color(Pal.accent);
for(int i = 0; i < 4; i++){
Point2 p = Geometry.d8edge[i];
float offset = -Math.max(request.block.size-1, 0)/2f * tilesize;
if(i % 2 == 0) Draw.rect("block-select", request.x * tilesize + request.block.offset() + offset * p.x, request.y * tilesize + request.block.offset() + offset * p.y, i * 90);
float offset = -Math.max(request.block.size - 1, 0) / 2f * tilesize;
if(i % 2 == 0)
Draw.rect("block-select", request.x * tilesize + request.block.offset() + offset * p.x, request.y * tilesize + request.block.offset() + offset * p.y, i * 90);
}
Draw.color();
@ -615,7 +616,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
}
protected void updateFlying(){
if(Units.invalidateTarget(target, this) && !(target instanceof TileEntity && ((TileEntity) target).damaged() && target.getTeam() == team &&
if(Units.invalidateTarget(target, this) && !(target instanceof TileEntity && ((TileEntity)target).damaged() && target.getTeam() == team &&
mech.canHeal && dst(target) < getWeapon().bullet.range())){
target = null;
}
@ -635,7 +636,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
if(dst(moveTarget) < 2f){
if(tapping){
Tile tile = ((TileEntity) moveTarget).tile;
Tile tile = ((TileEntity)moveTarget).tile;
tile.block().tapped(tile, this);
}
@ -695,7 +696,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
if(target != null && dst(target) > getWeapon().bullet.range()){
target = null;
}else if(target != null){
target = ((Tile) target).entity;
target = ((Tile)target).entity;
}
}
@ -703,7 +704,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
setMineTile(null);
}
}
}else if(target.isValid() || (target instanceof TileEntity && ((TileEntity) target).damaged() && target.getTeam() == team &&
}else if(target.isValid() || (target instanceof TileEntity && ((TileEntity)target).damaged() && target.getTeam() == team &&
mech.canHeal && dst(target) < getWeapon().bullet.range())){
//rotate toward and shoot the target
if(mech.turnCursor){
@ -840,7 +841,7 @@ public class Player extends Unit implements BuilderTrait, ShooterTrait{
buffer.writeByte(mech.id);
buffer.writeInt(mining == null ? noSpawner : mining.pos());
buffer.writeInt(spawner == null ? noSpawner : spawner.getTile().pos());
buffer.writeShort((short) (baseRotation * 2));
buffer.writeShort((short)(baseRotation * 2));
writeBuilding(buffer);
}

View File

@ -20,18 +20,11 @@ import io.anuke.mindustry.entities.traits.TargetTrait;
import io.anuke.mindustry.game.EventType.BlockDestroyEvent;
import io.anuke.mindustry.game.Team;
import io.anuke.mindustry.gen.Call;
import io.anuke.mindustry.world.Block;
import io.anuke.mindustry.world.Edges;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.*;
import io.anuke.mindustry.world.blocks.defense.Wall;
import io.anuke.mindustry.world.modules.ConsumeModule;
import io.anuke.mindustry.world.modules.ItemModule;
import io.anuke.mindustry.world.modules.LiquidModule;
import io.anuke.mindustry.world.modules.PowerModule;
import io.anuke.mindustry.world.modules.*;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.tileGroup;
import static io.anuke.mindustry.Vars.world;
@ -39,7 +32,7 @@ import static io.anuke.mindustry.Vars.world;
public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
public static final float timeToSleep = 60f * 4; //4 seconds to fall asleep
private static final ObjectSet<Tile> tmpTiles = new ObjectSet<>();
/**This value is only used for debugging.*/
/** This value is only used for debugging. */
public static int sleepingEntities = 0;
public Tile tile;
@ -53,7 +46,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
public LiquidModule liquids;
public ConsumeModule cons;
/**List of (cached) tiles with entities in proximity, used for outputting to*/
/** List of (cached) tiles with entities in proximity, used for outputting to */
private Array<Tile> proximity = new Array<>(8);
private boolean dead = false;
private boolean sleeping;
@ -76,7 +69,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
tile.entity.onDeath();
}
/**Sets this tile entity data to this tile, and adds it if necessary.*/
/** Sets this tile entity data to this tile, and adds it if necessary. */
public TileEntity init(Tile tile, boolean shouldAdd){
this.tile = tile;
x = tile.drawx();
@ -93,12 +86,12 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
return this;
}
/**Scaled delta.*/
/** Scaled delta. */
public float delta(){
return Time.delta() * timeScale;
}
/**Call when nothing is happening to the entity. This increments the internal sleep timer.*/
/** Call when nothing is happening to the entity. This increments the internal sleep timer. */
public void sleep(){
sleepTime += Time.delta();
if(!sleeping && sleepTime >= timeToSleep){
@ -108,7 +101,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
}
}
/**Call when this entity is updating. This wakes it up.*/
/** Call when this entity is updating. This wakes it up. */
public void noSleep(){
sleepTime = 0f;
if(sleeping){
@ -126,13 +119,17 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
return dead || tile.entity != this;
}
public void write(DataOutput stream) throws IOException{}
public void write(DataOutput stream) throws IOException{
}
public void writeConfig(DataOutput stream) throws IOException{}
public void writeConfig(DataOutput stream) throws IOException{
}
public void read(DataInput stream) throws IOException{}
public void read(DataInput stream) throws IOException{
}
public void readConfig(DataInput stream) throws IOException{}
public void readConfig(DataInput stream) throws IOException{
}
public boolean collide(Bullet other){
return true;
@ -269,7 +266,7 @@ public class TileEntity extends BaseEntity implements TargetTrait, HealthTrait{
public void update(){
//TODO better smoke effect, this one is awful
if(health != 0 && health < block.health && !(block instanceof Wall) &&
Mathf.chance(0.009f * Time.delta() * (1f - health / block.health))){
Mathf.chance(0.009f * Time.delta() * (1f - health / block.health))){
Effects.effect(Fx.smoke, x + Mathf.range(4), y + Mathf.range(4));
}

View File

@ -24,26 +24,21 @@ import io.anuke.mindustry.game.Teams.TeamData;
import io.anuke.mindustry.graphics.Pal;
import io.anuke.mindustry.net.Interpolator;
import io.anuke.mindustry.net.Net;
import io.anuke.mindustry.type.Item;
import io.anuke.mindustry.type.ItemStack;
import io.anuke.mindustry.type.StatusEffect;
import io.anuke.mindustry.type.Weapon;
import io.anuke.mindustry.type.*;
import io.anuke.mindustry.world.Pos;
import io.anuke.mindustry.world.Tile;
import io.anuke.mindustry.world.blocks.Floor;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.*;
import static io.anuke.mindustry.Vars.*;
public abstract class Unit extends DestructibleEntity implements SaveTrait, TargetTrait, SyncTrait, DrawTrait, TeamTrait{
/**Total duration of hit flash effect*/
/** Total duration of hit flash effect */
public static final float hitDuration = 9f;
/**Percision divisor of velocity, used when writing. For example a value of '2' would mean the percision is 1/2 = 0.5-size chunks.*/
/** Percision divisor of velocity, used when writing. For example a value of '2' would mean the percision is 1/2 = 0.5-size chunks. */
public static final float velocityPercision = 8f;
/**Maximum absolute value of a velocity vector component.*/
/** Maximum absolute value of a velocity vector component. */
public static final float maxAbsVelocity = 127f / velocityPercision;
public static final int noSpawner = Pos.get(-1, 1);
@ -106,9 +101,9 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
if(isDead()) return false;
if(other instanceof DamageTrait){
return other instanceof TeamTrait && state.teams.areEnemies((((TeamTrait) other).getTeam()), team);
return other instanceof TeamTrait && state.teams.areEnemies((((TeamTrait)other).getTeam()), team);
}else{
return other instanceof Unit && ((Unit) other).isFlying() == isFlying();
return other instanceof Unit && ((Unit)other).isFlying() == isFlying();
}
}
@ -198,10 +193,10 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
stream.writeBoolean(isDead());
stream.writeFloat(net ? interpolator.target.x : x);
stream.writeFloat(net ? interpolator.target.y : y);
stream.writeByte((byte) (Mathf.clamp(velocity.x, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeByte((byte) (Mathf.clamp(velocity.y, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeShort((short) (rotation * 2));
stream.writeShort((short) health);
stream.writeByte((byte)(Mathf.clamp(velocity.x, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeByte((byte)(Mathf.clamp(velocity.y, -maxAbsVelocity, maxAbsVelocity) * velocityPercision));
stream.writeShort((short)(rotation * 2));
stream.writeShort((short)health);
stream.writeByte(item.item.id);
stream.writeShort((short)item.amount);
status.writeSave(stream);
@ -258,10 +253,10 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
moveVector.setZero();
for(int cx = -rad; cx <= rad; cx++){
for(int cy = -rad; cy <= rad; cy++){
Tile tile = world.tileWorld(x + cx*tilesize, y + cy*tilesize);
Tile tile = world.tileWorld(x + cx * tilesize, y + cy * tilesize);
if(tile == null) continue;
int weight = flying ? tile.airWeight : tile.weight;
float scl = (rad - Mathf.dst(tile.worldx(), tile.worldy(), x, y)/(8f * 1.2f * Mathf.sqrt2)) * 0.1f;
float scl = (rad - Mathf.dst(tile.worldx(), tile.worldy(), x, y) / (8f * 1.2f * Mathf.sqrt2)) * 0.1f;
moveVector.add(Mathf.sign(x - tile.worldx()) * scaling * weight * scl, Mathf.sign(y - tile.worldy()) * scaling * weight * scl);
}
@ -301,12 +296,13 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
public Floor getFloorOn(){
Tile tile = world.tileWorld(x, y);
return tile == null ? (Floor) Blocks.air : tile.floor();
return tile == null ? (Floor)Blocks.air : tile.floor();
}
public void onRespawn(Tile tile){}
public void onRespawn(Tile tile){
}
/**Updates velocity and status effects.*/
/** Updates velocity and status effects. */
public void updateVelocityStatus(){
Floor floor = getFloorOn();
@ -314,7 +310,7 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
status.update(this);
velocity.limit(maxVelocity()).scl(1f + (status.getSpeedMultiplier()-1f) * Time.delta());
velocity.limit(maxVelocity()).scl(1f + (status.getSpeedMultiplier() - 1f) * Time.delta());
if(x < -finalWorldBounds || y < -finalWorldBounds || x >= world.width() * tilesize + finalWorldBounds || y >= world.height() * tilesize + finalWorldBounds){
kill();
@ -420,7 +416,7 @@ public abstract class Unit extends DestructibleEntity implements SaveTrait, Targ
}
public void drawStats(){
Draw.color(Color.BLACK, team.color, healthf() + Mathf.absin(Time.time(), healthf()*5f, 1f - healthf()));
Draw.color(Color.BLACK, team.color, healthf() + Mathf.absin(Time.time(), healthf() * 5f, 1f - healthf()));
Draw.rect(getPowerCellRegion(), x, y, rotation - 90);
Draw.color();
}

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