file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
BitArrayTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/BitArrayTest.java | package test.shared;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import harenet.BitArray;
public class BitArrayTest {
/*
* purpose : test BitArray function coverage in BitArray class.
* input : integer 33
* output : the variable data[0]==0
*/
@Test
public void testBitArray() {
BitArray test = new BitArray(33);
assertTrue(test.getData()[0]==0);
}
/*
* purpose : test setDataElement coverage in BitArray class.
* input : integer 0 ,integer 0 each for i, data
* expected output : data[0]==0 in BitArray class
*/
@Test
public void testsetDataElement(){
BitArray test = new BitArray(33);
test.setDataElement(0, (byte)0);
assertTrue(test.getData()[0]==0);
}
/*
* purpose : test getData function coverage in BitArray class.
* input : integer 33
* expected output : data[0]==0 in BitArray class
*
*/
@Test
public void testgetData(){
BitArray test = new BitArray(33);
assertTrue(test.getData()[0]==0);
}
/*
* purpose : test clear function coverage in BitArray class.
* input : integer 33 and play the function clear.
* expected output : data[0]==0 in BitArray class.
*/
@Test
public void testclear(){
BitArray test = new BitArray(33);
test.clear();
assertTrue(test.getData()[0]==0);
}
/*
* purpose : test setAll function coverage in BitArray class.
* input : integer 33 and play the function setAll.
* expected output : data[0]==0xFFffFFff in BitArray class.
*/
@Test
public void testsetAll(){
BitArray test = new BitArray(33);
test.setAll();
assertTrue(test.getData()[0]==0xFFffFFff);
}
/*
* purpose : test numberOfBytes function coverage in BitArray class.
* input : integer 32 on class creation.
* output : data.length == 8
*/
@Test
public void testnumberOfBytes(){
BitArray test = new BitArray(32);
assertTrue(test.numberOfBytes()==4);
}
/*
* purpose : test size function coverage in BitArray class.
* input : integer 32 on class creation.
* output : return value is 2*32 when call size function.
*/
@Test
public void testsize(){
BitArray test = new BitArray(32);
assertTrue(test.size()==32);
}
/*
* purpose : test testtoString override function in BitArray class.
* input : integer 32 on class creation and call toString().
* expected output: test.getData()[0]==0 cause Integer.toBinaryString(0)==0.
*
*/
@Test
public void testtoString(){
BitArray test = new BitArray(32);
test.toString();
assertTrue(test.getData()[0]==0);
System.out.println(Integer.toBinaryString(0));
}
/*
* purpose : test setBit function in BitArray class.
* input : integer 32 on class creation and setBit function each.
* expected output: test.getData()[0]==0 cause data[bitIndex(32)] = 0(00000000) and bitOffset(32) = 0(00000000).
*
*/
@Test
public void testsetBit(){
BitArray test = new BitArray(32);
test.setBit(31);
assertTrue(test.getData()[0]==0);
}
/*
* purpose : test getBit function in BitArray class.
* input : integer 32 on class creation.
* expected output : getbit(32)=false cause data[bitIndex(32)]=0 and bitOffset(32)=0.
* so result is false.
* getbit(0)=true cause getData()[0]=1, so data[bitIndex(0)]=1 and bitOffset(0)=0
*/
@Test
public void testgetBit(){
BitArray test = new BitArray(32);
test.getData()[0]=1;
assertTrue(test.getBit(31)==false);
assertTrue(test.getBit(0)==true);
}
@Test
public void testSetBit() {
BitArray test = new BitArray(32);
assertFalse(test.getBit(4));
test.setBit(4, true);
assertTrue(test.getBit(4));
test.setBit(4, false);
assertFalse(test.getBit(4));
for(int i = 0; i < test.size(); i++) {
assertFalse(test.getBit(i));
}
test.setBit(4, true);
assertTrue(test.getBit(4));
for(int i = 0; i < test.size(); i++) {
if(i!=4) {
assertFalse(test.getBit(i));
}
}
}
@Test
public void testSize() {
BitArray array = new BitArray(33);
assertEquals(5, array.numberOfBytes());
array = new BitArray(31);
assertEquals(4, array.numberOfBytes());
array = new BitArray(1500);
assertEquals(188, array.numberOfBytes());
array = new BitArray(255);
assertEquals(32, array.numberOfBytes());
array = new BitArray(256);
assertEquals(32, array.numberOfBytes());
array = new BitArray(64);
assertEquals(8, array.numberOfBytes());
}
}
| 5,204 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BroadcastListenerTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/BroadcastListenerTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.BroadcastListener;
public class BroadcastListenerTest {
/*
* purpose : test BroadcastListener function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testBroadcastListener() {
BroadcastListener test = new BroadcastListener(20,"192.168.25.53",80);
}
/*
* purpose : test AddOnMessageReceivedListener function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80, null for OnMessageREceivedListener
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testAddOnMessageReceivedListener() {
BroadcastListener test = new BroadcastListener(20,"192.168.25.53",80);
test.addOnMessageReceivedListener(null);
}
/*
* purpose : test start function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80.
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testStart() {
BroadcastListener test = new BroadcastListener(20,"192.168.25.53",80);
try {
test.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* purpose : test close function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80.
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testClose() {
BroadcastListener test = new BroadcastListener(20,"192.168.25.53",80);
try {
test.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,974 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MapListFileNameTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/MapListFileNameTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.MapList;
/*
* Purpose: Test stripFileExtension function whether it return correct String
* maplist.stripFileExtension(String fileName);
* FileName = "abc.json"
* Return = "abc"
*/
public class MapListFileNameTest {
private MapList maplist;
/*
* Purpose: Test String Filename is correctly changed
* Input: fileName = "abc.json"
*
* Expected: "abc"
*/
@Test
public void testStringFileName() {
final String fileName = "abc.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "abc";
assertEquals(actual, expected);
}
/*
* Purpose: Test Integer Filename is correctly changed
* Input: fileName = "123.json"
*
* Expected: "123"
*/
@Test
public void testIntegerFileName() {
final String fileName = "123.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "123";
assertEquals(actual, expected);
}
/*
* Purpose: Test Mixed Filename is correctly changed
* Input: fileName = "abc123.json"
*
* Expected: "abc123"
*/
@Test
public void testMixedFileName() {
final String fileName = "abc123.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "abc123";
assertEquals(actual, expected);
}
/*
* Purpose: Test other type Filename is correctly changed
* Input: fileName = "abc123.exe"
*
* Expected: "abc.exe"
*/
@Test
public void testOtherTypeFileName() {
final String fileName = "abc.exe";
String actual = maplist.stripFileExtension(fileName);
String expected = "abc.exe";
assertEquals(actual, expected);
}
/*
* Purpose: Test long Filename is correctly changed
* Input: fileName = "aaabbbbcccddddeeeffffqqqqwerrrrr.json"
*
* Expected: "aaabbbbcccddddeeeffffqqqqwerrrrr"
*/
@Test
public void testLongFileName() {
final String fileName = "aaabbbbcccddddeeeffffqqqqwerrrrr.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "aaabbbbcccddddeeeffffqqqqwerrrrr";
assertEquals(actual, expected);
}
/*
* Purpose: Test Single Character Filename is correctly changed
* Input: fileName = "a.json"
*
* Expected: "a"
*/
@Test
public void testSingleFileName() {
final String fileName = "a.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "a";
assertEquals(actual, expected);
}
/*
* Purpose: Test Single integer Filename is correctly changed
* Input: fileName = "1.json"
*
* Expected: "1"
*/
@Test
public void testSingleIntegerFileName() {
final String fileName = "1.json";
String actual = maplist.stripFileExtension(fileName);
String expected = "1";
assertEquals(actual, expected);
}
}
| 3,307 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ArrayMapTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/ArrayMapTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.ArrayMap;
public class ArrayMapTest {
/*
* purpose : test ArrayMap and Presize function in ArrayMaptest class.
* input : default, value 0, value 1 for class creation.
* expected output : assertNotNull for all creation is true.
*/
@Test
public <K,V> void testArrayMapAndPresize() {
ArrayMap<K,V> testNone = new ArrayMap<K,V>();
ArrayMap<K,V> testZero = new ArrayMap<K,V>(0);
ArrayMap<K,V> testOne = new ArrayMap<K,V>(1);
assertNotNull(testNone);
assertNotNull(testZero);
assertNotNull(testOne);
}
/*
* purpose : test set and rawset function in ArrayMap class.
* input : K for "key", V for "value"
* expected output : none. cause two function invoke another.
*/
@Test
public <K,V> void testSetAndrawSet() {
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"key";
V Value = (V)"value";
test.set(Key, Value);
assertNotNull(test);
}
/*
* purpose : test length function in ArrayMap class.
* input : class creation.
* expected output : return value is 0. cause nothing in hashEntries.
*/
@Test
public <K,V> void testLength(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
assertTrue(test.length()==0);
}
/*
* purpose : test Size function in ArrayMap class.
* input : class creation.
* expected output : return value is 0. cause nothing in hashEntries.
*/
@Test
public <K,V> void testSize(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
assertTrue(test.size()==0);
}
/*
* purpose : test IsEmpty function in ArrayMap class.
* input : class creation.
* expected output : return value is true at first. cause nothing in hashEntries.
* after put one hashset, then isEmpty is false.
*/
@Test
public <K,V> void testIsEmpty(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
assertTrue(test.isEmpty()==true);
test.hashset(Key, Value);
assertTrue(test.isEmpty()==false);
}
/*
* purpose : test Put function in ArrayMap class.
* input : K Key for "Key", V Value for "Value".
* expected output : the return value of calling put function is null.
*
*/
@Test
public <K,V> void testPut(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
assertEquals(test.put(Key, Value),null);
}
/*
* purpose : test remove and hashRemove function in ArrayMap class.
* input : class ArrayMap.
* expected output : the return value of calling remove(ArrayMap) is null.
*
*/
@Test
public <K,V> void testRemove(){
ArrayMap<K,V> test = new ArrayMap<K,V>(0);
assertEquals(test.remove(test),null);
}
/*
* purpose : test ContainsKey function in ArrayMap class.
* input : K Key for "Key", V Value for "Value". and class ArrayMap.
* expected output : return value is false.
* after calling set function, then return value is true.
* but, never true in this case. cause, when erase, set and
* initialize, hashKeys always has value by minimum 1.
*/
@Test
public <K,V> void testContainsKey(){
ArrayMap<K,V> test = new ArrayMap<K,V>(0);
K Key = (K)"Key";
V Value = (V)"Value";
assertTrue(test.containsKey(test)==false);
// test.set(Key, Value);
// assertTrue(test.containsKey(test)==true);
//
}
/*
* purpose : test Equal function in ArrayMap class.
* input : two classes named ArrayMap.
* expected output : true, false for each class.
* can't reach getClass()!= val.getClass() sentence.
*
*/
@Test
public <K,V> void testEqual(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
ArrayMap<K,V> tests = new ArrayMap<K,V>(0);
ArrayMap<K,V> nullTest = null;
assertTrue(test.equal(test));
assertTrue(test.equal(tests)==false);
assertTrue(test.equal(nullTest)==false);
}
/*
* purpose : test containsValue function in ArrayMap class.
* input : K Key for "Key", V Value for "Value" and V Values for "Values".
* expected output : return value of containsValue is false.
*/
@Test
public <K,V> void testContainsValue(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
V Values = (V)"Values";
assertTrue(test.containsValue(Value)==false);
test.set(Key, Value);
test.containsValue(Value);
test.containsValue(Values);
}
/*
* purpose : test Get function in ArrayMap class.
* input : K Key for "Key", V Value for "Value". and then call set function.
* expected output: when calls get function for Key, then return value is "Value".
*
*/
@Test
public <K,V> void testGet(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
assertEquals(test.get(Key),"Value");
}
/*
* purpose : test getKey function in ArrayMap class.
* input : ArrayMap class.
* expected output : return value of getKey(0) is null.
*/
@Test
public <K,V> void testGetKey(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
assertEquals(test.getKey(0),null);
}
/*
* purpose : test getValue function in ArrayMap class.
* input : ArrayMap class.
* expected output: return value of getValue(0) is null.
*/
@Test
public <K,V> void testgetValue(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
assertEquals(test.getValue(0),null);
}
/*
* purpose : test nextKey function in ArrayMap class.
* input : K Key for "Key", V Value for "Value", and call set function.
* expected output : return value of nextKey(Key) is "Key".
*/
@Test
public <K,V> void testNextKey(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
assertEquals(test.nextKey(Key),"Key");
}
/*
* purpose : test nextValue function in ArrayMap class.
* input : K Key for "Key", V Value for "Value", and call set function.
* expected output : return value of nextKey(Value) is "Value".
*/
@Test
public <K,V> void testNextValue(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
assertEquals(test.nextValue(Key),"Value");
}
/*
* purpose : test clear function in ArrayMap class.
* input : K key for "Key", V Value for "Value".
* expected output : after calling clear(), the size value is 0.
*/
@Test
public <K,V> void testClear(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
assertEquals(test.nextValue(Key),"Value");
test.clear();
assertEquals(test.size(),0);
}
/*
* purpose : test KeySet function in ArrayMap class.
* input : Key, Value and call set function.
* output : X
*/
@Test
public <K,V> void testKeySet(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
test.keySet();
}
/*
* purpose : test values function in ArrayMap class.
* input : Key,Value and call set, values function.
* expected output : X
*/
@Test
public <K,V> void testValues(){
ArrayMap<K,V> test = new ArrayMap<K,V>();
test.values();
K Key = (K)"Key";
V Value = (V)"Value";
test.set(Key, Value);
test.values();
}
/*
* purpose : test nexti function in ArrayMap class.
* input : Key, Value for each "Key", "Value".
* expected output : ** do not complete for testing **
*/
// @Test
// public <K,V> void testNexti(){
// ArrayMap<K,V> test = new ArrayMap<K,V>();
// K Key = (K)"Key";
// V Value = (V)"Value";
// test.set(Key, Value);
// assertTrue(test.nexti(Key)==0);
//
// }
/*
* purpose : test Hashset function in ArrayMap class.
* input : Key,Value
* expected output : ** do not complete for testing **
*/
// @Test
// public <K,V> void testHashset() {
// ArrayMap<K,V> test = new ArrayMap<K,V>(0);
// K Key = (K)"Key";
// V Value = (V)"Value";
// test.set(Key, Value);
// test.hashset(Key, Value);
// test.hashset(Key, null);
//
//
// }
}
| 9,225 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BroadcasterTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/BroadcasterTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.Broadcaster;
public class BroadcasterTest {
/*
* purpose : test Broadcaster function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testBroadcaster() {
try {
Broadcaster test = new Broadcaster(20,"192.168.25.53",80);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* purpose : test BroadcastMessage function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80
* expected output : X, cause the function is only made for creation.
*/
@Test
public void testBroadcastMessage() {
try {
Broadcaster test = new Broadcaster(5,"192.168.25.53",80);
test.broadcastMessage("Hello");
test.broadcastMessage("HelloHello");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* purpose : test close function in Broadcaster class.
* input : mtu:20, groupAddress:192.168.25.53, port:80
* expected output : X, cause the function is only made for close socket.
*/
@Test
public void testClose() {
try {
Broadcaster test = new Broadcaster(5,"192.168.25.53",80);
test.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 1,762 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PrintStreamLoggerTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/PrintStreamLoggerTest.java | package test.shared;
import static org.junit.Assert.*;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.PrintStreamLogger;
/*
* Purpose: test PrintStreamLogger constructor
* Input: PrintStream stream
* Expected:
*/
public class PrintStreamLoggerTest {
private PrintStreamLogger printlogger;
private PrintStream stream;
@Before
public void setUp() throws Exception {
printlogger = new PrintStreamLogger(stream);
}
@Test
public void ConstructTest(){
printlogger = new PrintStreamLogger(stream);
}
}
| 651 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ExecCommandTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/ExecCommandTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.Logger;
import seventh.shared.Command;
import seventh.shared.Console;
import seventh.shared.DefaultConsole;
import seventh.shared.ExecCommand;
public class ExecCommandTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
/**
* Test case for ExecCommand
*/
@Test
public void testExecute() {
ExecCommand EC = new ExecCommand();
Console console = new DefaultConsole();
EC.execute(console, "new file");
EC.execute(console, "/Users/hyeongjukim/Desktop/new.txt");
}
}
| 758 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RconHashTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/RconHashTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.RconHash;
public class RconHashTest {
/*
* Purpose: Rconhash hashing
* Input: RconHash token 10, hash hello world
* Expected:
* hashing string = 52uLz5GE4rvH/QG44Mjaseol6L3l7eMpWLcIT/58zds=
*/
@Test
public void testMinMaxScope(){
final String expected = "52uLz5GE4rvH/QG44Mjaseol6L3l7eMpWLcIT/58zds=";
RconHash rconhash = new RconHash(10);
assertEquals(expected,rconhash.hash("hello world"));
}
}
| 580 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EaseInInterpolationTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/EaseInInterpolationTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;
import seventh.shared.EaseInInterpolation;
import seventh.shared.TimeStep;
public class EaseInInterpolationTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testEaseInInterpolation() {
}
@Test
public void testEaseInInterpolationFloatFloatLong() {
}
/**
* Reset EaseInInterpolation object
* @Inputs float from, float to, long time
* @throws Exception
* @ExpectedOutput set the EaseInInterpolation
*/
@Test
public void testReset() throws Exception {
EaseInInterpolation EI = new EaseInInterpolation();
EaseInInterpolation EI2 = new EaseInInterpolation(100f,0f,8);
EI.reset(30f,20f,5);
EI2.reset(30f, 20f, 0);
float expected = 30f;
System.out.println(EI.getValue());
Assert.assertEquals(expected, EI.getValue(),0.0001);
Assert.assertNotSame(expected, EI.getValue());
}
/** * Test the update function
* @Input TimeStep(GameClock : 80, DeltaTime : 40)
* @ExpectedOutput EI's properties, RemainingTime is decreased by 40 every calling update()
*/
@Test
public void testUpdate() {
EaseInInterpolation EI = new EaseInInterpolation(100f,0f,60);
System.out.println(EI.getRemainingTime());
TimeStep TS = new TimeStep();
TS.setGameClock(80);
TS.setDeltaTime(40);
EI.update(TS);
System.out.println(EI.getRemainingTime());
}
/**
* Test whether time Expired or not
* Input TimeStep(GameClock : 60, DeltaTime : 30)
* ExpectedOutput True
*/
@Test
public void testIsExpired() {
EaseInInterpolation EI = new EaseInInterpolation(60f,0f,60);
System.out.println(EI.getRemainingTime());
TimeStep TS = new TimeStep();
TS.setGameClock(60);
TS.setDeltaTime(30);
EI.update(TS);
System.out.println(EI.getRemainingTime());
Assert.assertTrue(!EI.isExpired());
EI.update(TS);
System.out.println(EI.getRemainingTime());
Assert.assertTrue(EI.isExpired());
}
@Test
public void testGetRemainingTime() {
}
@Test
public void testGetValue() {
}
/**
* Test getTarget
* @ExpectedOutput EI.target set 0f
*/
@Test
public void testGetTarget() {
EaseInInterpolation EI = new EaseInInterpolation(60f,0f,60);
final float expected = 0f;
Assert.assertEquals(expected, EI.getTarget(), 0.001);
}
}
| 2,830 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
StateMachineTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/StateMachineTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.server.GameServer;
import seventh.server.InGameState;
import seventh.server.ServerStartState;
import seventh.shared.State;
import seventh.shared.StateMachine;
import seventh.shared.StateMachine.StateMachineListener;
import seventh.shared.TimeStep;
public class StateMachineTest {
/*
* Purpose: current state of stateMachine is NULL after calling constructor
* Input: nothing
* Expected:
* currentState of statemachine is NULL
*/
@Test
public void testCurrentStateAfterConstruct() {
assertNull(new StateMachine<>().getCurrentState());
}
/*
* Purpose: change the current state to enter with no Listener
* Input: test state => ServerStartState
* Expected:
* currentState is enter
* listener is NULL
*/
@Test
public void testChangeCurrentStateEnter(){
StateMachine<State> statemachine = new StateMachine<State>();
ServerStartState expectedState = new ServerStartState();
statemachine.changeState(expectedState);
assertEquals(expectedState,statemachine.getCurrentState());
assertNull(statemachine.getListener());
}
/*
* Purpose: change the state and listener to new state
* Input: test state => ServerStartState(Enter) -> ServerStartState(new state)
* test Listener => StateMachine<state>(Enter) -> StateMachineLister<State>(new listener)
* Expected:
* first state exit. next state enter.
* first listener is exit. next listener enter
*/
@Test
public void testChangeStateAndListener(){
StateMachine<State> statemachine = new StateMachine<State>();
ServerStartState stateEnter = new ServerStartState();
StateMachineListener<State> ListenerEnter = new StateMachineListener<State>(){
@Override
public void onEnterState(State state) {}
@Override
public void onExitState(State state) {}
};
ServerStartState expectedState = new ServerStartState();
StateMachineListener<State> expectedListener = new StateMachineListener<State>(){
@Override
public void onEnterState(State state) {}
@Override
public void onExitState(State state) {}
};
statemachine.setListener(ListenerEnter);
statemachine.changeState(stateEnter);
statemachine.setListener(expectedListener);
statemachine.changeState(expectedState);
assertEquals(expectedState,statemachine.getCurrentState());
assertEquals(expectedListener,statemachine.getListener());
}
/*
* Purpose: change the Listener to enterState
* Input: test state => ServerStartState, test Listener => StateMachineLister<State>
* Expected:
* currentState is enter
* listener is onEnterState
*/
@Test
public void testChangeListenerOnEnterState(){
StateMachine<State> statemachine = new StateMachine<State>();
ServerStartState expectedState = new ServerStartState();
StateMachineListener<State> expectedListener = new StateMachineListener<State>(){
@Override
public void onEnterState(State state) {}
@Override
public void onExitState(State state) {}
};
statemachine.setListener(expectedListener);
statemachine.changeState(expectedState);
assertEquals(expectedState,statemachine.getCurrentState());
assertEquals(expectedListener,statemachine.getListener());
}
/*
* Purpose: update the state along with time step
* Input: new TimeStep
* Expected:
* Current state is updated to time step
* Listener is NULL
*/
@Test
public void testUpdateState(){
StateMachine<State> statemachine = new StateMachine<State>();
statemachine.changeState(new ServerStartState());
statemachine.update(new TimeStep());
assertNotNull(statemachine.getCurrentState());
assertNull(statemachine.getListener());
}
}
| 4,272 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ArraysTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/ArraysTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.Arrays;
public class ArraysTest {
/*
* purpose : test UsedLength function in Arrays class.
* input : generic type [T] array.
* zeroStuff for testing overall sentence,
* incaseStuff for testing "if sentence" on second,
* nullStuff for testing "if sentence" on first.
* expected output : assertEquals 0 for zeroStuff,
* assertEquals 1 for incaseStuff,
* assertEquals 0 for nullStuff.
*/
@SuppressWarnings("unchecked")
@Test
public <T> void testUsedLength() {
T[] zeroStuff = (T[])new Object[3];
T[] incaseStuff = (T[])new Object[1];
T[] nullStuff = null;
assertNull(nullStuff);
incaseStuff[0] = (T) "A";
assertEquals(Arrays.usedLength(zeroStuff),0);
assertEquals(Arrays.usedLength(incaseStuff),1);
assertEquals(Arrays.usedLength(nullStuff),0);
}
/*
* purpose : test clear function in Arrays class.
* input : generic type [T] array.
* incaseStuff for "if sentence not null",
* nullStuff for "if sentence null"
* output : assertNull for incaseStuff is true.
* ***but in this case, an error about JavaDoc is poped up.**
*/
@SuppressWarnings("unchecked")
@Test
public <T> void testClear() {
T[] incaseStuff = (T[])new Object[1];
incaseStuff[0] = (T) "A";
assertNotNull(incaseStuff);
T[] nullStuff = null;
assertNull(nullStuff);
Arrays.clear(incaseStuff);
Arrays.clear(nullStuff);
// assertNull(incaseStuff);
}
}
| 1,846 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefaultConsoleTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/DefaultConsoleTest.java | package test.shared;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.Test;
import seventh.shared.Command;
import seventh.shared.Console;
import seventh.shared.DefaultConsole;
import seventh.shared.Logger;
import seventh.shared.SysOutLogger;
import seventh.shared.TimeStep;
public class DefaultConsoleTest{
/*
* Purpose: add command to the Command's map
* Input: null
* Expected:
* IllegalArgumentException
*/
@Test(expected=IllegalArgumentException.class)
public void addCommandTest1() throws IllegalArgumentException {
DefaultConsole test = new DefaultConsole();
test.addCommand(null);
}
/*
* Purpose: add command to the Command's map
* Input: Command(null)
* Expected:
* IllegalArgumentException
*/
@Test(expected=IllegalArgumentException.class)
public void addCommandTest2() throws IllegalArgumentException {
DefaultConsole test = new DefaultConsole();
test.addCommand(new Command(null) {
@Override
public void execute(Console console, String... args) {
}
});
}
/*
* Purpose: add command to the Command's map
* Input: String and null
* Expected:
* IllegalArgumentException
*/
@Test(expected=IllegalArgumentException.class)
public void addCommandTest3() throws IllegalArgumentException {
DefaultConsole test = new DefaultConsole();
test.addCommand("test",null);
}
/*
* Purpose: add command to the Command's map
* Input: Command
* Expected:
* the added Command's map
*/
@Test
public void addCommandTest4(){
DefaultConsole test = new DefaultConsole();
test.addCommand(new Command("test") {
@Override
public void execute(Console console, String... args) {
}
});
Command cmd = test.getCommand("test");
assertEquals("test",cmd.getName());
}
/*
* Purpose: get command in the Command's map by Command's name
* Input: String
* Expected:
* the Command having the name
*/
@Test
public void getCommandTest() {
DefaultConsole test = new DefaultConsole();
Command DefaultCmd = test.getCommand("cmdlist");
assertEquals("cmdlist",DefaultCmd.getName());
DefaultCmd = test.getCommand("sleep");
assertEquals("sleep",DefaultCmd.getName());
test.addCommand(new Command("test") {
@Override
public void execute(Console console, String... args) {
}
});
Command cmd = test.getCommand("test");
assertEquals("test",cmd.getName());
}
/*
* Purpose: remove command in the Command's map by Command's name
* Input: String
* Expected:
* the removed Command's map
*/
@Test(expected=NullPointerException.class)
public void removeCommandTest() throws NullPointerException {
DefaultConsole test = new DefaultConsole();
test.addCommand(new Command("test") {
@Override
public void execute(Console console, String... args) {
}
});
Command cmd = test.getCommand("test");
assertEquals("test",cmd.getName());
test.removeCommand("test");
cmd = test.getCommand("test");
assertEquals(null,cmd.getName());
}
/*
* Purpose: remove command in the Command's map by Command
* Input: Command
* Expected:
* the removed Command's map
*/
@Test(expected=NullPointerException.class)
public void removeCommandTest2() throws NullPointerException {
DefaultConsole test = new DefaultConsole();
test.addCommand(new Command("test") {
@Override
public void execute(Console console, String... args) {
}
});
Command cmd = test.getCommand("test");
assertEquals("test",cmd.getName());
test.removeCommand((Command)null);
test.removeCommand(cmd);
cmd = test.getCommand("test");
assertEquals(null,cmd.getName());
}
/*
* Purpose: find command in the Command's map by partial Command's name
* Input: String
* Expected:
* the command
*/
@Test
public void findTest() {
DefaultConsole test = new DefaultConsole();
List<String> expected = new ArrayList<String>();
expected.addAll(test.find("cmd"));
Iterator<String> index = expected.iterator();
assertEquals("cmdlist",index.next());
}
/*
* Purpose: find command in the Command's map by partial Command's name
* Input: null
* Expected:
* NoSuchElementException
*/
@Test(expected=NoSuchElementException.class)
public void findTest2() throws NoSuchElementException {
DefaultConsole test = new DefaultConsole();
List<String> expected = new ArrayList<String>();
expected.addAll(test.find(null));
Iterator<String> index = expected.iterator();
index.next();
}
}
| 5,516 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MapListaddFileExtensionTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/MapListaddFileExtensionTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.MapList;
public class MapListaddFileExtensionTest {
private MapList maplist;
/*
* Purpose: test addFileExtension(mapName).
* if it is not end with ".json"
* this function needs to add ".json" at the end of filename
* Input: fileName = "abc.json"
* Expected: "abc.json"
*/
@Test
public void addFileTest() {
String mapName = "abc.json";
String actual = maplist.addFileExtension(mapName);
String expected = "abc.json";
assertEquals(actual, expected);
}
/*
* Purpose: test other file name
* Input: fileName = "abc.exe"
* Expected: "abc.exe.json"
*/
@Test
public void differentTypeTest() {
String mapName = "abc.exe";
String actual = maplist.addFileExtension(mapName);
String expected = "abc.exe.json";
assertEquals(actual, expected);
}
/*
* Purpose: test integer file name
* Input: fileName = "123"
* Expected: "123.json"
*/
@Test
public void integerFileNameTest() {
String mapName = "123";
String actual = maplist.addFileExtension(mapName);
String expected = "123.json";
assertEquals(actual, expected);
}
/*
* Purpose: test other file name
* Input: fileName = "123abc.exe"
* Expected: "123abc.exe.json"
*/
@Test
public void mixedFileNameTest() {
String mapName = "123abc";
String actual = maplist.addFileExtension(mapName);
String expected = "123abc.json";
assertEquals(actual, expected);
}
/*
* Purpose: test other type's file name
* Input: fileName = "abc.exe"
* Expected: "abc.exe.json"
*/
@Test
public void otherFileNameTest() {
String mapName = "#43.";
String actual = maplist.addFileExtension(mapName);
String expected = "#43..json";
assertEquals(actual, expected);
}
/*
* Purpose: test long type's file name
* Input: fileName = "aaabbbcccdddeeeeffffttttttttqewrqerqe"
* Expected: "aaabbbcccdddeeeeffffttttttttqewrqerqe.json"
*/
@Test
public void longFileNameTest() {
String mapName = "aaabbbcccdddeeeeffffttttttttqewrqerqe";
String actual = maplist.addFileExtension(mapName);
String expected = "aaabbbcccdddeeeeffffttttttttqewrqerqe.json";
assertEquals(actual, expected);
}
/*
* Purpose: test single file name
* Input: fileName = "aaabbbcccdddeeeeffffttttttttqewrqerqe"
* Expected: "aaabbbcccdddeeeeffffttttttttqewrqerqe.json"
*/
@Test
public void singleFileNameTest() {
String mapName = "a";
String actual = maplist.addFileExtension(mapName);
String expected = "a.json";
assertEquals(actual, expected);
}
}
| 3,093 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SeventhConfigTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/SeventhConfigTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.SeventhConfig;
public class SeventhConfigTest {
final String validPath = "./assets/client_config.leola";
final String inValidPath = "invalid";
final String validRootNode = "client_config";
final String invalidRootNode = "invalid";
/*
* Purpose: invalid Path
* Input: SeventhConfig ("invalid", "client_config")
* Expected:
* throw Exception
*/
@Test(expected=Exception.class)
public void testInvalidPath() throws Exception {
SeventhConfig seventhconfig = new SeventhConfig(inValidPath,validRootNode);
}
/*
* Purpose: invalid Root node
* Input: SeventhConfig ("./assets/client_config.leola","invalid")
* Expected:
* throw Exception
*/
@Test(expected=Exception.class)
public void testInvalidRootNode() throws Exception {
SeventhConfig seventhconfig = new SeventhConfig(validPath,invalidRootNode);
}
/*
* Purpose: valid seventhConfig construct
* Input: SeventhConfig ("./assets/client_config.leola","client_config")
* Expected:
* new SeventhConfig
*/
@Test
public void testSeventhConfigConstructor() throws Exception{
SeventhConfig seventhconfig = new SeventhConfig(validPath,validRootNode);
assertTrue(seventhconfig instanceof SeventhConfig);
}
}
| 1,470 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RandomizerTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/RandomizerTest.java | package test.shared;
import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;
import seventh.shared.Randomizer;
public class RandomizerTest {
/*
* Purpose: specify a minimum scope
* Input: getRandomRangeMin minimum scope 0.5
* Expected:
* 0.5 < random number
* random number < 1.0
*/
@Test
public void testMinScope() {
final double rangeMin = 0.5;
final double rangeMax = 1.0;
Randomizer randomizer = new Randomizer(new Random());
assertTrue(rangeMin < randomizer.getRandomRangeMin(rangeMin));
assertTrue(rangeMax > randomizer.getRandomRangeMin(rangeMin));
}
/*
* Purpose: specify a maximum scope
* Input: getRandomRangeMax maximum scope 0.8
* Expected:
* 0.0 < random number
* random number < 0.8
*
*/
@Test
public void testMaxScope(){
final double rangeMin = 0.0;
final double rangeMax = 0.8;
Randomizer randomizer = new Randomizer(new Random());
assertTrue(rangeMin < randomizer.getRandomRangeMax(rangeMax));
assertTrue(rangeMax > randomizer.getRandomRangeMax(rangeMax));
}
/*
* Purpose: specify minumun & maximum scope
* Input: getRandomRange min 0.3, max 0.8
* Expected:
* 0.3 < random number
* random number < 0.8
*/
@Test
public void testMinMaxScope(){
final double rangeMin = 0.3;
final double rangeMax = 0.8;
Randomizer randomizer = new Randomizer(new Random());
assertTrue(rangeMin < randomizer.getRandomRange(rangeMin,rangeMax));
assertTrue(rangeMax > randomizer.getRandomRange(rangeMin,rangeMax));
}
}
| 1,804 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BitsTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/BitsTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.Bits;
public class BitsTest {
/*
* purpose : test IsSignBitSet function in Bits class.
* input : ((byte)-1), ((byte)0), ((byte)1)
* expected output : true, false, false each.
*/
@Test
public void testIsSignBitSet() {
assertTrue(Bits.isSignBitSet((byte)-1)==true);
assertTrue(Bits.isSignBitSet((byte)0)==false);
assertTrue(Bits.isSignBitSet((byte)1)==false);
}
/*
* purpose : test SetSignBit function in Bits class.
* input : ((byte)-1)
* expected output : -1
*/
@Test
public void testSetSignBit() {
assertTrue(Bits.setSignBit((byte)-1)==-1);
}
/*
* purpose : test GetWithoutSignBit function in Bits class.
* input : ((byte)0)
* expected output : 0
*/
@Test
public void testGetWithoutSignBit() {
assertTrue(Bits.getWithoutSignBit((byte)0)==0);
}
}
| 1,004 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LANServerConfigTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/LANServerConfigTest.java | package test.shared;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.Config;
import seventh.shared.LANServerConfig;
public class LANServerConfigTest {
private LANServerConfig lanconfig;
private Config config;
@Before
public void setUp() throws Exception{
config = EasyMock.createMock(Config.class);
lanconfig = new LANServerConfig(config);
}
@After
public void tearDown() throws Exception{
config = null;
lanconfig = null;
}
/*
* Purpose: check the broadcast address by checking getBroadcastAddress()
* Input: defaultValue = "224.0.0.44"
* keys = "lan"
* key2 = "broadcast_address"
* Expected:
* "224.0.0.44"
*
*/
@Test
public void testBroadcastAddress() {
config.getStr("224.0.0.44", "lan", "broadcast_address");
EasyMock.expect(config.getStr("224.0.0.44", "lan", "broadcast_address")).andReturn("224.0.0.44");
EasyMock.replay(config);
LANServerConfig lanconfig = new LANServerConfig(config);
String expected = "224.0.0.44";
String actual = lanconfig.getBroadcastAddress();
assertEquals(expected, actual);
EasyMock.verify(config);
}
}
| 1,413 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FileSystemAssetWatcherTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/FileSystemAssetWatcherTest.java | package test.shared;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.AssetLoader;
import seventh.shared.Cons;
import seventh.shared.FileSystemAssetWatcher;
public class FileSystemAssetWatcherTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
/**
* test the FileSystemAssetWatcher
* @throws IOException
*/
@Test
public void testFileSystemAssetWatcher() throws IOException {
File file = new File("/Users/hyeongjukim/Desktop/");
FileSystemAssetWatcher FSA = new FileSystemAssetWatcher(file);
FSA.startWatching();
FSA.loadAsset("new.txt", new AssetLoader<File>(){
@Override
public File loadAsset(String filename) throws IOException {
try {
Cons.println("Evaluating: " + filename);
Cons.println("Successfully evaluated: " + filename);
}
catch (Exception e) {
Cons.println("*** Error evaluating: " + filename);
Cons.println("*** " + e);
}
return null;
}
});
FSA.stopWatching();
FSA.clearWatched();
FSA.removeWatchedAsset("new.txt");
}
}
| 1,496 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MasterServerConfigTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/MasterServerConfigTest.java | package test.shared;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.Config;
import seventh.shared.MasterServerConfig;
public class MasterServerConfigTest {
private MasterServerConfig msconfig;
private Config config;
@Before
public void setUp() throws Exception {
config = EasyMock.createMock(Config.class);
msconfig = new MasterServerConfig(config);
}
@After
public void tearDown() throws Exception {
config = null;
msconfig = null;
}
/*
* Purpose: Test URL
* Input: "master_server", "url"
*
* Expected: "master_server + url"
*/
@Test
public void getUrlTest() {
EasyMock.expect(config.getString("mater_server", "url")).andReturn("master_server url");
EasyMock.replay(config);
String expected = "master_server url";
String actual = msconfig.getUrl();
assertEquals(expected, actual);
EasyMock.verify(config);
}
}
| 1,119 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FpsCounterTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/FpsCounterTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.FpsCounter;
public class FpsCounterTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
/**
* Test initialization
* @input null / integer
* @ExpectedOutput set FpsCounter.simplesize as default(100) / as 30
*/
@Test
public void testFpsCounterInt() {
FpsCounter fps = new FpsCounter();
FpsCounter fps2 = new FpsCounter(30);
final int expected = 100;
final int expected2 = 30;
assertEquals(expected,fps.getSampleSize());
assertEquals(expected2,fps2.getSampleSize());
}
/**
* Testcase for update
* @Input long
* @ExpectedOutput set all figures except simplesize
*/
@Test
public void testUpdate() {
long expectedAvg= 0;
long expectedTally = 0;
long expectedCS = 0;
long expectedFps = 0;
FpsCounter fps = new FpsCounter();
for(int i = 300;i >=0; i--){
fps.update(i);
if(i>0){
expectedFps = 1000/i;
}
expectedCS++;
if(expectedCS > fps.getSampleSize()) {
expectedAvg = expectedTally / fps.getSampleSize();
expectedTally = 0;
expectedCS = 0;
}
else{
expectedTally += expectedFps;
}
System.out.println(fps.getAvgFPS());
System.out.println(fps.getFps());
assertEquals(expectedAvg,fps.getAvgFPS());
assertEquals(expectedFps,fps.getFps());
}
}
}
| 1,818 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TimerTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/TimerTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
public class TimerTest {
/*
* Purpose: get remaining time when endTime is invalid time
* Input: endTime -> endTime -10
* Expected:
* return failure
* remain time < 0
*/
@Test
public void testConstructMinusEndTime() {
Timer timer = new Timer(true,-10);
TimeStep timestep = new TimeStep();
timestep.setDeltaTime(10);
timer.update(timestep);
assertTrue(0 < timer.getRemainingTime());
assertTrue(0 < timer.getEndTime());
}
/*
* Purpose: get remaining time when endTime is valid time
* Input: endTime -> 10
* Expected:
* 0 < remain time
*/
@Test
public void testConstructValidTime() {
Timer timer = new Timer(true,10);
TimeStep timestep = new TimeStep();
timestep.setDeltaTime(10);
timer.update(timestep);
assertTrue(0 < timer.getRemainingTime());
assertTrue(0 < timer.getEndTime());
}
}
| 1,153 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CommandTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/CommandTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.*;
public class CommandTest extends Command {
public CommandTest() {
super("expected");
// TODO Auto-generated constructor stub
}
@Override
public void execute(Console console, String... args) {
// TODO Auto-generated method stub
}
/*
* Purpose: get the Command's name
* Input:
* Expected:
* the Command's name
*/
@Test
public void getNameTest() {
CommandTest test = new CommandTest();
assertEquals("expected",test.getName());
}
/*
* Purpose: Merges the arguments into one string by index and delimiter
* Input: delimiter, index, Strings
* Expected:
* the coalesced string
*/
@Test
public void mergeArgsDelimAtTest() {
CommandTest test = new CommandTest();
assertEquals("expected",test.mergeArgsDelimAt("@",0,"expected"));
assertEquals("expected@test",test.mergeArgsDelimAt("@",0,"expected","test"));
assertEquals("test@item",test.mergeArgsDelimAt("@",1,"expected","test","item"));
assertEquals("test/item/great",test.mergeArgsDelimAt("/",1,"expected","test","item","great"));
}
/*
* Purpose: Merges the arguments into one string by delimiter
* Input: delimiter, Strings
* Expected:
* the coalesced string
*/
@Test
public void mergeArgsDelimTest() {
CommandTest test = new CommandTest();
assertEquals("expected",test.mergeArgsDelim("@","expected"));
assertEquals("expected@test",test.mergeArgsDelim("@","expected","test"));
assertEquals("expected@test@item",test.mergeArgsDelim("@","expected","test","item"));
assertEquals("expected/test/item/great",test.mergeArgsDelim("/","expected","test","item","great"));
}
/*
* Purpose: Merges the arguments into one string
* Input: Strings
* Expected:
* the coalesced string
*/
@Test
public void mergeArgsTest() {
CommandTest test = new CommandTest();
assertEquals("expected",test.mergeArgs("expected"));
assertEquals("expectedtest",test.mergeArgs("expected","test"));
assertEquals("expectedtestitem",test.mergeArgs("expected","test","item"));
}
}
| 2,403 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MasterServerClientTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/MasterServerClientTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.MasterServerClient;
import seventh.shared.MasterServerConfig;
public class MasterServerClientTest {
private MasterServerClient msclient;
private MasterServerConfig config;
/*
* Purpose: Test MasterServerClient constructor
* Input: MasterServerConfig config
*/
@Test
public void MasterServerClientTest(){
msclient = new MasterServerClient(config);
}
}
| 562 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SoundTypeTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/SoundTypeTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.shared.SoundType;
import seventh.shared.SoundType.SoundSourceType;
public class SoundTypeTest {
/*
* Purpose: check M1_GARAND_LAST_FIRE SoundType value number(valid)
* Input: SoundType.fromNet (byte)9
* Expected:
* M1_GARAND_LAST_FIRE is 10th value (starting number 0)
*/
@Test
public void testValidSoundType() {
final SoundType expectedSoundType = SoundType.M1_GARAND_LAST_FIRE;
assertEquals(expectedSoundType,SoundType.fromNet((byte) 9));
}
/*
* Purpose: check M1_GARAND_LAST_FIRE SoundType value number(invalid)
* Input: SoundType.fromNet (byte)14
* Expected:
* M1_GARAND_LAST_FIRE SoundType is (byte)9
* (byte)14 is SPRINGFIELD_RECHAMBER
*/
@Test
public void testInvalidSoundType() {
final SoundType expectedSoundType = SoundType.M1_GARAND_LAST_FIRE;
assertNotEquals(expectedSoundType,SoundType.fromNet((byte) 14));
}
/*
* Purpose: MUTE Sound Source Type value when number over length of value
* Input: SoundType.fromNet (byte)127 > SoundType value count
* Expected:
* Sound Source Type is MUTE
*/
@Test
public void testMuteOverValueLength() {
final SoundType expected = SoundType.MUTE;
byte typeSize = (byte) 127;
assertTrue(typeSize > SoundType.values().length);
assertEquals(expected,SoundType.fromNet(typeSize));
}
/*
* Purpose: MUTE Sound Source Type value when number under 0
* Input: SoundType.fromNet (byte)240 < 0
* Expected:
* Sound Source Type is MUTE
*/
@Test
public void testMuteUnderZero() {
final SoundType expected = SoundType.MUTE;
byte typeSize = (byte) 240;
assertTrue(typeSize < 0);
assertEquals(expected,SoundType.fromNet(typeSize));
}
}
| 2,005 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GeomTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/GeomTest.java | package test.shared;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.map.Map;
import seventh.shared.Geom;
public class GeomTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
Geom geom = new Geom();
}
}
| 411 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LANServerConstructorTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/shared/LANServerConstructorTest.java | package test.shared;
import static org.junit.Assert.*;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.shared.Config;
import seventh.shared.LANServerConfig;
public class LANServerConstructorTest {
private Config config;
private LANServerConfig lanconfig;
@Test
public void testLANServerConfig(){
lanconfig = new LANServerConfig(config);
}
}
| 454 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fZeroTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fZeroTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fZeroTest {
/*
* Purpose: To test zeroOut() which make x =0 and y = 0
* Input: Vector2f(2,3), vector.zeroOut();
* Expected: vector.x = 0, vector.y = 0;
*/
@Test
public void Vector2fzeroOutTest() {
Vector2f vector = new Vector2f(2,3);
vector.zeroOut();
assertTrue(vector.x == 0);
assertTrue(vector.y == 0);
}
/*
* Purpose: To test isZero(). it returns True when x ==0 && y == 0, False otherwise
* Input: Vector2f(2,3), vector.isZero(), vector.set(0,0), vector.isZero();
* Expected: false , true
*/
@Test
public void Vector2fisZeroTest() {
Vector2f vector = new Vector2f(2,3);
assertTrue(vector.isZero() == false);
vector.set(0,0);
assertTrue(vector.isZero() == true);
}
}
| 997 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fEqualTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fEqualTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fEqualTest {
/*
* Purpose: test equals(Object 0)
* if(o instanceof Vector2f) check v.x == x && v.y == y
* if it is correct, return true, false otherwise
* Input: 1) vector(2.0f, 3.0f), vector.equals(3)
* 2) vector(2.0f, 3.0f), another(2.0f, 3.0f), vector.equals(another)
* Expected: 1) false
* 2) true
*/
@Test
public void EqualsTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
boolean expected = false;
boolean actual = vector.equals(3);
assertEquals(expected, actual);
Vector2f another = new Vector2f(2.0f, 3.0f);
expected = true;
actual = vector.equals(another);
assertEquals(expected, actual);
}
/*
* Purpose: test hashCode()
* it returns x.hashCode() + y.hashCode();
* Input: vector(2.0f, 3.0f)
* Expected: x.hashCode() + y.hashCode();
*/
@Test
public void HashCodeTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
Float x = 2.0f;
Float y = 3.0f;
int expected = x.hashCode() + y.hashCode();
int actual = vector.hashCode();
assertEquals(expected, actual);
}
}
| 1,438 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PairTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/PairTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.Pair;
public class PairTest {
/*
* Purpose: check that the null values stored
* Input: Pair default constructor
* pairD()
* Expected:
* pairD.first == null, pairD.second = null
*/
@Test
public void testPairDefaultConstructor() {
Pair pairD = new Pair();
assertNull(pairD.getFirst() );
assertNull(pairD.getSecond());
}
/*
* Purpose: check that the correct integer values stored
* Input: Pair<int, int> using positive, zero, negative
* pairP(3, 5), pairZ(0, 0), pairN(-7, -4)
* Expected:
* pairP.fisrt == 3, pairP.second == 5
* pairZ.fisrt == 0, pairZ.second == 0
* pairN.first == -7, pairN.second == -4
*/
@Test
public void testPairIntConstructor() {
Pair pairA = new Pair( 3, 5);
assertEquals( 3, pairA.getFirst() );
assertEquals( 5, pairA.getSecond());
Pair pairZ = new Pair( 0, 0);
assertEquals( 0, pairZ.getFirst() );
assertEquals( 0, pairZ.getSecond());
Pair pairN = new Pair(-7, -4);
assertEquals(-7, pairN.getFirst() );
assertEquals(-4, pairN.getSecond());
}
/*
* Purpose: check that the correct double values stored
* Input: Pair<double, double> using positive, zero, negative
* pairP(3.14, 5.26), pairZ(0.0, 0.0), pairN(-1.414, -4.19)
* Expected:
* pairP.fisrt == 3.14, pairP.second == 5.26
* pairZ.fisrt == 0.0, pairZ.second == 0.0
* pairN.first == -1.414, pairN.second == -4.19
*/
@Test
public void testPairDoubleConstructor() {
Pair pairA = new Pair( 3.14, 5.26);
assertEquals( 3.14, pairA.getFirst() );
assertEquals( 5.26, pairA.getSecond());
Pair pairZ = new Pair( 0.0, 0.0 );
assertEquals( 0.0 , pairZ.getFirst() );
assertEquals( 0.0 , pairZ.getSecond());
Pair pairN = new Pair(-1.414, -4.19);
assertEquals(-1.414, pairN.getFirst() );
assertEquals(-4.19, pairN.getSecond());
}
/*
* Purpose: check that the correct integer values stored
* Input: Pair<int, int> set positive, zero, negative
* set pairP( 25, 10),
* set pairZ( 0, 0),
* set pairN(-10, -20)
* Expected:
* pairP.fisrt == 25, pairP.second == 10
* pairZ.fisrt == 0, pairZ.second == 0
* pairN.first == -10, pairN.second == -20
* */
@Test
public void testPairSetInt() {
Pair pairA = new Pair(-3, 5);
pairA.setFirst( 25);
assertEquals( 25, pairA.getFirst() );
pairA.setSecond( 10);
assertEquals( 10, pairA.getSecond());
Pair pairZ = new Pair(22, 22);
pairZ.setFirst( 0);
assertEquals( 0, pairZ.getFirst() );
pairZ.setSecond( 0);
assertEquals( 0, pairZ.getSecond());
Pair pairN = new Pair( 0, 0);
pairN.setFirst( -10);
assertEquals( -10, pairN.getFirst() );
pairN.setSecond(-20);
assertEquals( -20, pairN.getSecond());
}
/*
* Purpose: check that the correct double values stored
* Input: Pair<double, double> set positive, zero, negative
* set pairP( 26.56, 1069.639),
* set pairZ( 0.0, 00.0000),
* set pairN(-148.14, -41.149)
* Expected:
* pairP.fisrt == 26.56, pairP.second == 1069.639
* pairZ.fisrt == 0.0, pairZ.second == 00.0000
* pairN.first == -148.14, pairN.second == -41.149
*/
@Test
public void testPairSetDouble() {
Pair pairA = new Pair( 45.5, 268.157);
pairA.setFirst( 26.56);
assertEquals( 26.56, pairA.getFirst() );
pairA.setSecond(1069.639);
assertEquals( 1069.639, pairA.getSecond());
Pair pairZ = new Pair(-479.369, 2308.2);
pairZ.setFirst( 0.0);
assertEquals( 0.0, pairZ.getFirst() );
pairZ.setSecond( 00.0000);
assertEquals( 00.0000, pairZ.getSecond());
Pair pairN = new Pair( 29.2, 175.17);
pairN.setFirst( -148.14);
assertEquals( -148.14, pairN.getFirst() );
pairN.setSecond( -41.149);
assertEquals( -41.149, pairN.getSecond());
}
}
| 4,859 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fCoverageTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fCoverageTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.FloatUtil;
import seventh.math.Vector2f;
public class Vector2fCoverageTest {
/*
* Purpose: Test Vector2f Constructor.
* Vector2f's x and y value will be initialized in 0.
* Input: new Vector2f()
* Expected: x = 0, y = 0
*/
@Test
public void testConstructor() {
Vector2f vector = new Vector2f();
}
/*
* Purpose: Test Vector2f Float Constructor.
* Vector2f's x and y value will be initialized in 0.
* Input: new Vector2f()
* Expected: x = 0, y = 0
*/
@Test
public void testFloatConstructor() {
Vector2f vector = new Vector2f();
float x = vector.x;
float y = vector.y;
assertTrue(x == 0);
assertTrue(y == 0);
}
/*
* Purpose: Test Vector2f Float Array Constructor.
* Vector2f's x and y value will be initialized in v[0], v[1].
* Input: float[] v = {1,2};
* Expected: x = 1, y = 2
*/
@Test
public void testFloatArrConstructor() {
float []v = {1, 2};
Vector2f vector = new Vector2f(v);
float x = vector.x;
float y = vector.y;
assertTrue(x == 1);
assertTrue(y == 2);
}
/*
* Purpose: Test Vector2f Vector2f Constructor.
* Vector2f's x and y value will be initialized in vectorOne's x and y.
* Input: VectorOne x = 2; y = 3;
* Expected: VectorTwo x = 2; y = 3;
*/
@Test
public void testVector2fConstructor() {
float x = 2;
float y = 3;
Vector2f vectorOne = new Vector2f(2, 3);
Vector2f vectorTwo = new Vector2f(vectorOne);
assertTrue(vectorTwo.x == 2);
assertTrue(vectorTwo.y == 3);
}
/*
* Purpose: To test Vector2f.get(int i). it returns x when the i is 0, y otherwise.
* Input: Vector2f(2,3), get(0), get(1);
* Expected: get(0) = 2, get(1) = 3
*/
@Test
public void Vector2fGetTest() {
Vector2f vector = new Vector2f(2,3);
int i = 0;
int j = 1;
float actualX = vector.get(i);
float actualY = vector.get(j);
assertTrue(actualX == 2);
assertTrue(actualY == 3);
}
/*
* Purpose: To test set(float x, float y). this.x = x, this.y = y
* Input: Vector2f(), set(2,3)
* Expected: Vector2f.x = 2, Vector2f.y = 3
*/
@Test
public void Vector2fFloatSetTest() {
Vector2f vector = new Vector2f();
vector.set(2,3);
assertTrue(vector.x == 2);
assertTrue(vector.y == 3);
}
/*
* Purpose: To test set(Vector2f v). this.x = v.x, this.y = c.y
* Input: vectorOne(2,3), vectorTwo.set(vectorOne)
* Expected: vectorTwo.x = 2, vectorTwo.y = 3
*/
@Test
public void Vector2fVector2fSetTest() {
Vector2f vectorOne = new Vector2f(2,3);
Vector2f vectorTwo = new Vector2f();
vectorTwo.set(vectorOne);
assertTrue(vectorTwo.x == 2);
assertTrue(vectorTwo.y == 3);
}
/*
* Purpose: To test set(float[] v)
* Input: vector(), set(float[] v), v = {1, 2, 3}
* Expected: vector.x = 1, vector.y = 2
*/
@Test
public void Vector2fFloatArrSetTest() {
float[] v = {1, 2, 3};
Vector2f vector = new Vector2f();
vector.set(v);
assertTrue(vector.x == 1);
assertTrue(vector.y == 2);
}
/*
* Purpose: To test zeroOut() which make x =0 and y = 0
* Input: Vector2f(2,3), vector.zeroOut();
* Expected: vector.x = 0, vector.y = 0;
*/
@Test
public void Vector2fzeroOutTest() {
Vector2f vector = new Vector2f(2,3);
vector.zeroOut();
assertTrue(vector.x == 0);
assertTrue(vector.y == 0);
}
/*
* Purpose: To test isZero(). it returns True when x ==0 && y == 0, False otherwise
* Input: Vector2f(2,3), vector.isZero(), vector.set(0,0), vector.isZero();
* Expected: false , true
*/
@Test
public void Vector2fisZeroTest() {
Vector2f vector = new Vector2f(2,3);
assertTrue(vector.isZero() == false);
vector.set(0,0);
assertTrue(vector.isZero() == true);
}
/*
* Purpose: To test round(). x = Math.round(x), y = Math.round(y)
* Input: Vector2f(2.6f, 3.2f), vector.round()
* Expected: vector.x = 3, vector.y = 3
*/
@Test
public void RoundTest() {
Vector2f vector = new Vector2f(2.6f, 3.2f);
vector.round();
assertTrue(vector.x == 3);
assertTrue(vector.y == 3);
}
/*
* Purpose: To test subtract(Vector2f v), it returns Vector2f(this.x-v.x, this.y - v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 2, dest.y = 2
*/
@Test
public void SubtractTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.subtract(v);
assertTrue(dest.x == 2);
assertTrue(dest.y == 2);
}
/*
* Purpose: To test addition(Vector2f v), it returns Vector2f(this.x+v.x, this.y + v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 8, dest.y = 8
*/
@Test
public void AdditionTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.addition(v);
assertTrue(dest.x == 8);
assertTrue(dest.y == 8);
}
/*
* Purpose: To test mult(Vector2f v), it returns Vector2f(this.x*v.x, this.y*v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 15, dest.y = 15
*/
@Test
public void MultiplyVectorTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.mult(v);
assertTrue(dest.x == 15);
assertTrue(dest.y == 15);
}
/*
* Purpose: To test mult(float scalar), it returns Vector2f(this.x*scalar, this.y*scalar)
* Input: vector(5,5), scalar = 3
* Expected: dest.x = 15, dest.y = 15
*/
@Test
public void MultiplyFloatTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f dest = new Vector2f();
dest = vector.mult(3);
assertTrue(dest.x == 15);
assertTrue(dest.y == 15);
}
/*
* Purpose: To test div(Vector2f v), it returns Vector2f(this.x/v.x, this.y/v.y)
* Input: vector(10, 10), v(2, 5)
* Expected: dest.x = 5, dest.y = 2
*/
@Test
public void DivideVectorTest() {
Vector2f vector = new Vector2f(10, 10);
Vector2f v = new Vector2f(2, 5);
Vector2f dest = new Vector2f();
dest = vector.div(v);
assertTrue(dest.x == 5);
assertTrue(dest.y == 2);
}
/*
* Purpose: To test div(float v), it returns Vector2f(this.x/scalar, this.y/scalar)
* Input: vector(10, 10), scalar = 5
* Expected: dest.x = 2, dest.y = 2
*/
@Test
public void DivideFloatTest() {
Vector2f vector = new Vector2f(10, 10);
Vector2f dest = new Vector2f();
dest = vector.div(5);
assertTrue(dest.x == 2);
assertTrue(dest.y == 2);
}
/*
* Purpose: test normalize(), returns normalized x and y
* Input: vector.normalize(), x=3, y =4
* Expected: x = 3.0f * FlLen, y = 4.0f * FlLen;
*/
@Test
public void NormalizeTest() {
Vector2f vector = new Vector2f();
vector.normalize();
vector.set(3,4);
vector.normalize();
float FlLen = 1.0f/5.0f;
float expectedX = 3.0f * FlLen;
float expectedY = 4.0f * FlLen;
assertTrue(vector.x == expectedX );
assertTrue(vector.y == expectedY );
}
/*
* Purpose: test lengthSquared(), returns x*x + y*y
* Input: Vector2f(3,4)
* Expected: 25.0f
*/
@Test
public void lenthSquaredTest() {
Vector2f vector = new Vector2f(3, 4);
float actual = vector.lengthSquared();
float expected = 25.0f;
assertTrue(actual == expected);
}
/*
* Purpose: test length(), returns Math.sqrt(x*x + y*y)
* Input: Vector2f(3,4)
* Expected: 5.0f
*/
@Test
public void lenthTest() {
Vector2f vector = new Vector2f(3, 4);
float actual = vector.length();
float expected = 5.0f;
assertTrue(actual == expected);
}
/*
* Purpose: test rotate(double radians)
* x1 = x * cos(radians) - y * sin(radians)
* y1 = x * sin(radians) + y * cos(radians)
* return Vector2f((float)x1, (float)y1)
* Input: vector(3,4), radians = 30
* Expected: x = (float)x1, y = (float)y1
*/
@Test
public void RotateTest() {
Vector2f vector = new Vector2f(3, 4);
Vector2f dest = new Vector2f();
double radians = 30;
double x1 = 3 * Math.cos(radians) - 4 * Math.sin(radians);
double y1 = 3 * Math.sin(radians) + 4 * Math.cos(radians);
float expectedX = (float)x1;
float expectedY = (float)y1;
dest = vector.rotate(30.0d);
assertTrue(dest.x == expectedX);
assertTrue(dest.y == expectedY);
}
/*
* Purpose: test equals(Object 0)
* if(o instanceof Vector2f) check v.x == x && v.y == y
* if it is correct, return true, false otherwise
* Input: 1) vector(2.0f, 3.0f), vector.equals(3)
* 2) vector(2.0f, 3.0f), another(2.0f, 3.0f), vector.equals(another)
* Expected: 1) false
* 2) true
*/
@Test
public void EqualsTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
boolean expected = false;
boolean actual = vector.equals(3);
assertEquals(expected, actual);
Vector2f another = new Vector2f(2.0f, 3.0f);
expected = true;
actual = vector.equals(another);
assertEquals(expected, actual);
}
/*
* Purpose: test hashCode()
* it returns x.hashCode() + y.hashCode();
* Input: vector(2.0f, 3.0f)
* Expected: x.hashCode() + y.hashCode();
*/
@Test
public void HashCodeTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
Float x = 2.0f;
Float y = 3.0f;
int expected = x.hashCode() + y.hashCode();
int actual = vector.hashCode();
assertEquals(expected, actual);
}
/*
* Purpose: test toString()
*
* Input: vector(2.0f, 3.0f), vector.toString()
* Expected: {"x": 2.0, "y": 3.0}
*/
@Test
public void toStringTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
String actual = vector.toString();
String expected = "{ \"x\": 2.0, \"y\": 3.0}";
assertEquals(expected, actual);
}
/*
* Purpose: test createClone()
* it returns clone of Vector2f
* Input: vector(2.0f, 3.0f), vector.toString()
* Expected: {"x": 2.0, "y": 3.0}
*/
@Test
public void CloneTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
Vector2f clone = vector.createClone();
assertEquals(vector, clone);
}
/*
* Purpose: test toArray()
* it returns float array {x, y}
* Input: vector(2.0f, 3.0f), vector.toArray();
* Expected: float{2.0f, 3.0f}
*/
@Test
public void toArrayTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
float[] expected = {2.0f, 3.0f};
float[] actual = vector.toArray();
assertTrue(expected[0] == actual[0]);
assertTrue(expected[1] == actual[1]);
}
/*
* Purpose: test Vector2fCrossProduct()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: -2
*/
@Test
public void CrossProductTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fCrossProduct(vectorOne, vectorTwo);
float expected = -2;
assertTrue(actual == expected);
}
/*
* Purpose: test Vector2fDotProduct()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: 26
*/
@Test
public void DotProductTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fDotProduct(vectorOne, vectorTwo);
float expected = 26;
assertTrue(actual == expected);
}
/*
* Purpose: test Vector2fDet()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: -2
*/
@Test
public void DetTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fDet(vectorOne, vectorTwo);
float expected = -2;
assertTrue(actual == expected);
}
/*
* Purpose: test AddTest()
* check the return value
*
* Input: a(2,4), b(3,5), dest(a, b, dest)
* Expected: dest.x = 5, dest.y = 9
*/
@Test
public void AddTest() {
Vector2f a = new Vector2f(2,4);
Vector2f b = new Vector2f(3,5);
Vector2f dest = new Vector2f();
dest.Vector2fAdd(a, b, dest);
assertTrue(dest.x == 5);
assertTrue(dest.y == 9);
}
/*
* Purpose: test AddScalarTest()
* check the return value
*
* Input: a(2,4), b(3,5), dest(a, b, dest)
* Expected: dest.x = 5, dest.y = 9
*/
@Test
public void AddScalarTest() {
Vector2f a = new Vector2f(2,4);
Vector2f dest = new Vector2f();
dest.Vector2fAdd(a, 5, dest);
assertTrue(dest.x == 7);
assertTrue(dest.y == 9);
}
/*
* Purpose: test Vector2fSubtract(a, b, dest)
* check the return value
*
* Input: a(2,4), b(1,1), dest.subtract(a, b, dest)
* Expected: dest.x = 1, dest.y = 3
*/
@Test
public void VetorSubTest() {
Vector2f a = new Vector2f(2,4);
Vector2f b = new Vector2f(1,1);
Vector2f dest = new Vector2f();
dest.Vector2fSubtract(a, b, dest);
assertTrue(dest.x == 1);
assertTrue(dest.y == 3);
}
/*
* Purpose: test Vector2fSubtract(a, scalar, dest)
* check the return value
*
* Input: a(8,6), Scalar = 2, subtract(a, 2, dest)
* Expected: dest.x = 6, dest.y = 4
*/
@Test
public void ScalarSubTest() {
Vector2f a = new Vector2f(8,6);
Vector2f dest = new Vector2f();
dest.Vector2fSubtract(a, 2, dest);
assertTrue(dest.x == 6);
assertTrue(dest.y == 4);
}
/*
* Purpose: test Vector2fMult(a,b, dest)
* check the return value
*
* Input: a(8,6), b(3,5), Vector2fMult(a, 2, dest)
* Expected: dest.x = 24, dest.y = 30
*/
@Test
public void VectorMulTest() {
Vector2f a = new Vector2f(8,6);
Vector2f b = new Vector2f(3,5);
Vector2f dest = new Vector2f();
dest.Vector2fMult(a, b, dest);
assertTrue(dest.x == 24);
assertTrue(dest.y == 30);
}
/*
* Purpose: test Vector2fMult(a,scalar, dest)
* check the return value
*
* Input: a(8,6), scalar = 3, Vector2fMult(a, 3, dest)
* Expected: dest.x = 24, dest.y = 30
*/
@Test
public void ScalarMulTest() {
Vector2f a = new Vector2f(8,6);
float scalar = 3;
Vector2f dest = new Vector2f();
dest.Vector2fMult(a, scalar, dest);
assertTrue(dest.x == 24);
assertTrue(dest.y == 18);
}
/*
* Purpose: test Vector2fDiv(a,b, dest)
* check the return value
*
* Input: a(8,6), b(2,3), Vector2fMult(a, b, dest)
* Expected: dest.x = 4, dest.y = 2
*/
@Test
public void VectorDivTest() {
Vector2f a = new Vector2f(8,6);
Vector2f b = new Vector2f(2,3);
Vector2f dest = new Vector2f();
dest.Vector2fDiv(a, b, dest);
assertTrue(dest.x == 4);
assertTrue(dest.y == 2);
}
/*
* Purpose: test Scalar2fDiv(a,scalar, dest)
* check the return value
*
* Input: a(8,6), scalar = 2, Vector2fMult(a, scalar, dest)
* Expected: dest.x = 4, dest.y = 3
*/
@Test
public void ScalarDivTest() {
Vector2f a = new Vector2f(8,6);
float scalar = 2;
Vector2f dest = new Vector2f();
dest.Vector2fDiv(a, 2, dest);
assertTrue(dest.x == 4);
assertTrue(dest.y == 3);
}
/*
* Purpose: test Vector2fRotate(a, radians, dest)
* check the return value
*
* Input: a(8,6), radians = 30, dest()
* Expected: dest.x = (float)(a.x * Math.cos(radians) - a.y * Math.sin(radians))
* dest.y = (float)(a.x * Math.sin(radians) + a.y * Math.cos(radians))
*/
@Test
public void VectorRotateTest () {
Vector2f a = new Vector2f(8,6);
double radians = 30;
Vector2f dest = new Vector2f();
float expectedX = (float)(a.x * Math.cos(radians) - a.y * Math.sin(radians));
float expectedY = (float)(a.x * Math.sin(radians) + a.y * Math.cos(radians));
dest.Vector2fRotate(a, radians, dest);
float actualX = dest.x;
float actualY = dest.y;
assertTrue(actualX == expectedX);
assertTrue(actualY == expectedY);
}
/*
* Purpose: test Vector2fAngle(a,b)
* check the return value
*
* Input: a(5,4), b(3,2), dest()
* Expected: dest.x = (float)(a.x * Math.cos(radians) - a.y * Math.sin(radians))
* dest.y = (float)(a.x * Math.sin(radians) + a.y * Math.cos(radians))
*/
@Test
public void AngleTest () {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(3,2);
Vector2f dest = new Vector2f();
double expectedAngle = Math.atan2(2.0f, 3.0f) - Math.atan2(4.0f,5.0f);
double actualAngle = dest.Vector2fAngle(a, b);
assertTrue(expectedAngle == actualAngle);
}
/*
* Purpose: test Vector2fMA(a, b, scalar, dest)
* check the return value
*
* Input: a(5,4), b(3,2), scalar = 5, dest();
* Expected: dest.x = 20, dest.y = 14
*/
@Test
public void Vector2fMATest () {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(3,2);
float scalar = 5;
Vector2f dest = new Vector2f();
dest.Vector2fMA(a, b, scalar, dest);
assertTrue(dest.x == 20);
assertTrue(dest.y == 14);
}
/*
* Purpose: test Vector2fMS(a, b, scalar, dest)
* check the return value
*
* Input: a(5,4), b(3,2), scalar = 5, dest();
* Expected: dest.x = -10, dest.y = -6
*/
@Test
public void Vector2fMSTest () {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(3,2);
float scalar = 5;
Vector2f dest = new Vector2f();
dest.Vector2fMS(a, b, scalar, dest);
assertTrue(dest.x == -10);
assertTrue(dest.y == -6);
}
/*
* Purpose: test Vector2fCopy(a, dest)
* check the return value
*
* Input: a(5,4), dest();
* Expected: dest.x = 5, dest.y = 4
*/
@Test
public void Vector2fCopyTest() {
Vector2f a = new Vector2f(5,4);
Vector2f dest = new Vector2f();
dest.Vector2fCopy(a, dest);
assertTrue(dest.x == 5);
assertTrue(dest.y == 4);
}
/*
* Purpose: test Vector2fEquals(a, b)
* check the return value
*
* Input: 1) a(5,4), b(5,4)
* 2) a(3,3), b(2,2)
* Expected: 1) true
* 2) false
*/
@Test
public void VectorEqualsTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(5,4);
boolean expected = true;
boolean actual = a.Vector2fEquals(a, b);
assertTrue(actual == expected);
b.set(2,2);
expected = false;
actual = a.Vector2fEquals(a,b);
assertTrue(actual == expected);
}
/*
* Purpose: test Vector2fEquals(a, b)
* check the return value
* test when a.x == b.x , a.y != b.y
*
* Input: 1) a(5,4), b(5,2)
* Expected: 1) false
*/
@Test
public void VectorEqualsFalseTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(5,2);
boolean expected = false;
boolean actual = a.Vector2fEquals(a, b);
assertTrue(actual == expected);
}
/*
* Purpose: test ApproxEquals(a, b)
* check the return value
*
* Input: a(5,4), b(5,4)
* Expected: true
*/
@Test
public void ApproxEqualsTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(5,4);
boolean expected = FloatUtil.eq(5, 5) && FloatUtil.eq(4, 4);
boolean actual = a.Vector2fApproxEquals(a,b);
assertTrue(expected == actual);
}
/*
* Purpose: test ApproxEquals(a, b)
* check the return value
*
* Input: a(5,4), b(5,4)
* Expected: true
*/
@Test
public void ApproxEqualsFalseFirTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(4,4);
boolean expected = FloatUtil.eq(5, 4) && FloatUtil.eq(4, 4);
boolean actual = a.Vector2fApproxEquals(a,b);
assertTrue(expected == actual);
}
/*
* Purpose: test ApproxEquals(a, b)
* check the return value
* a.x != b.x && a.y != b.y
*
* Input: a(5,4), b(4,3)
* Expected: false
*/
@Test
public void ApproxEqualsFalseSecTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(4,3);
boolean expected = FloatUtil.eq(5, 4) && FloatUtil.eq(4, 3);
boolean actual = a.Vector2fApproxEquals(a,b);
assertTrue(expected == actual);
}
/*
* Purpose: test ApproxEquals(a, b)
* check the return value
* a.x == b.x but a.y != b.y
*
* Input: a(5,4), b(5,3)
* Expected: false
*/
@Test
public void ApproxEqualsFalseThrTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(5,3);
boolean expected = FloatUtil.eq(5, 5) && FloatUtil.eq(4, 3);
boolean actual = a.Vector2fApproxEquals(a,b);
assertTrue(expected == actual);
}
/*
* Purpose: test ApproxEquals(a, b, epsilon)
* check the return value
*
* Input: a(5,4), b(5,4) epsilon = 5
* Expected: true(FloatUtil.eq(4, 4) && FloatUtil.eq(5, 5))
*/
@Test
public void ApproxEqualsEpsTest() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(5,4);
float epsilon = 5;
float temp = FloatUtil.epsilon;
FloatUtil.epsilon = epsilon;
boolean expectedResult = FloatUtil.eq(5, 5) && FloatUtil.eq(4, 4);
boolean actualResult = a.Vector2fApproxEquals(a, b, epsilon);
assertTrue(expectedResult == actualResult);
}
/*
* Purpose: test ApproxEquals(a, b, epsilon)
* check the return value
* a.x != b.x && a.y == b.y
*
* Input: a(5,4), b(4,4) epsilon = 5
* Expected: false
*/
@Test
public void ApproxEqualsEpsTestSec() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(4,4);
float epsilon = 5;
float temp = FloatUtil.epsilon;
FloatUtil.epsilon = epsilon;
boolean expectedResult = FloatUtil.eq(5, 4) && FloatUtil.eq(4, 4);
boolean actualResult = a.Vector2fApproxEquals(a, b, epsilon);
assertTrue(expectedResult == actualResult);
}
/*
* Purpose: test ApproxEquals(a, b, epsilon)
* check the return value
* a.x != b.x && a.y != b.y
*
* Input: a(5,4), b(4,3) epsilon = 5
* Expected: false
*/
@Test
public void ApproxEqualsEpsTestThr() {
Vector2f a = new Vector2f(5,4);
Vector2f b = new Vector2f(4,3);
float epsilon = 5;
float temp = FloatUtil.epsilon;
FloatUtil.epsilon = epsilon;
boolean expectedResult = FloatUtil.eq(5, 4) && FloatUtil.eq(4, 3);
boolean actualResult = a.Vector2fApproxEquals(a, b, epsilon);
assertTrue(expectedResult == actualResult);
}
/*
* Purpose: test Vector2fLength(Vector2f a)
* check the return value
*
* Input: Vector2f a(3,4)
* Expected: 5
*/
@Test
public void Vector2fLengthTest() {
Vector2f a = new Vector2f(3,4);
float expected = 5;
float actual = a.Vector2fLength(a);
assertTrue(expected == actual);
}
/*
* Purpose: test Vector2fLengthSq(Vector2f a)
* check the return value
*
* Input: Vector2f a(3,4)
* Expected: 25
*/
@Test
public void Vector2fLengthSqTest() {
Vector2f a = new Vector2f(3,4);
float expected = 25;
float actual = a.Vector2fLengthSq(a);
assertTrue(expected == actual);
}
/*
* Purpose: test Vector2fDistanceSq(Vector2f a, Vector2f b)
* check the return value
*
* Input: Vector2f a(6,4) b(5,3)
* Expected: 2
*/
@Test
public void Vector2fDistanceSqTest() {
Vector2f a = new Vector2f(6,4);
Vector2f b = new Vector2f(5,3);
float expected = (5 - 6) * (5 - 6) + (3 - 4) * (3 - 4);
float actual = Vector2f.Vector2fDistanceSq(a, b);
assertTrue(expected == actual);
}
/*
* Purpose: test Vector2fDistance(Vector2f a, Vector2f b)
* check the return value
*
* Input: Vector2f a(6,4) b(5,3)
* Expected: (float)Math.sqrt(2);
*/
@Test
public void Vector2fDistanceTest() {
Vector2f a = new Vector2f(6,4);
Vector2f b = new Vector2f(5,3);
float expected = (float)Math.sqrt((5 - 6) * (5 - 6) + (3 - 4) * (3 - 4));
float actual = Vector2f.Vector2fDistance(a, b);
assertTrue(expected == actual);
}
/*
* Purpose: test Vector2fNormalize(Vector2f a, Vector2f dest)
* check the return value
*
* Input: Vector2f a(6,4) dest(2,2))
* Expected: x = 6.0f/fLen, y = 4.0f/fLen
*/
@Test
public void Vector2fNormalizeTest() {
Vector2f a = new Vector2f(6,4);
Vector2f dest = new Vector2f(2, 2);
float fLen = (float)Math.sqrt(52);
float expectedX = 6.0f/fLen;
float expectedY = 4.0f/fLen;
a.Vector2fNormalize(a, dest);
float actualX = dest.x;
float actualY = dest.y;
assertTrue(expectedX == actualX);
assertTrue(expectedY == actualY);
}
/*
* Purpose: test Vector2fNormalize(Vector2f a, Vector2f dest)
* fLen = (float)Math.sqrt(x^2 + y^2)
* check when fLen == 0
*
* Input: Vector2f a(0,0) b(2,2)
* Expected: return
*/
@Test
public void Vector2fNormalizeZeroTest() {
Vector2f a = new Vector2f(0,0);
Vector2f dest = new Vector2f(2, 2);
a.Vector2fNormalize(a, dest);
}
/*
* Purpose: test Vector2fPerpendicular(Vector2f a, Vector2f dest)
* dest.x = a.y, dest.y = -a.x
* Input: Vector2f a(5,4) dest()
* Expected: dest.x = 4, dest.y = -5
*/
@Test
public void Vector2fPerpendicularTest() {
Vector2f a = new Vector2f(5,4);
Vector2f dest = new Vector2f();
a.Vector2fPerpendicular(a, dest);
float actualX = dest.x;
float actualY = dest.y;
float expectedX = 4;
float expectedY = -5;
assertTrue(actualX == expectedX);
assertTrue(actualY == expectedY);
}
/*
* Purpose: test Vector2fZeroOut(Vector2f a)
* a.x = a.y = 0
* Input: Vector2f a(5,4)
* Expected: a.x = a.y = 0
*/
@Test
public void Vector2fZeroOutTest() {
Vector2f a = new Vector2f(5,4);
a.Vector2fZeroOut(a);
assertTrue(a.x == 0);
assertTrue(a.y == 0);
}
/*
* Purpose: test Vector2fIsZero(Vector2f a), True case test
* Input: Vector2f a(0, 0)
* Expected: true
*/
@Test
public void Vector2fIsZeroTrueTest() {
Vector2f a = new Vector2f(0, 0);
boolean expected = true;
boolean actual = a.Vector2fIsZero(a);
assertEquals(expected, actual);
}
/*
* Purpose: test Vector2fIsZero(Vector2f a), False case test
* Input: Vector2f a(2, 0)
* Expected: false
*/
@Test
public void Vector2fIsZeroFalseTest() {
Vector2f a = new Vector2f(2, 0);
boolean expected = false;
boolean actual = a.Vector2fIsZero(a);
assertEquals(expected, actual);
}
/*
* Purpose: test Vector2fIsZero(Vector2f a), False case test
* Input: Vector2f a(2,4)
* Expected: false
*/
@Test
public void Vector2fIsZeroFalseTestTwo() {
Vector2f a = new Vector2f(2, 4);
boolean expected = false;
boolean actual = a.Vector2fIsZero(a);
assertEquals(expected, actual);
}
/*
* Purpose: test Vector2fIsZero(Vector2f a), False case test
* Input: Vector2f a(0, 4)
* Expected: false
*/
@Test
public void Vector2fIsZeroFalseTestThr() {
Vector2f a = new Vector2f(0, 4);
boolean expected = false;
boolean actual = a.Vector2fIsZero(a);
assertEquals(expected, actual);
}
/*
* Purpose: test GreaterOrEq(Vector2f a, Vector2f b)
* Input: Vector2f a(5, 4), b(8, 9)
* Expected: false
*/
@Test
public void GreaterOrEqFalseTest() {
Vector2f a = new Vector2f(5, 4);
Vector2f b = new Vector2f(8, 9);
boolean expected = false;
boolean actual = a.Vector2fGreaterOrEq(a, b);
assertEquals(expected, actual);
}
/*
* Purpose: test GreaterOrEq(Vector2f a, Vector2f b)
* Input: Vector2f a(10, 12), b(8, 9)
* Expected: true
*/
@Test
public void GreaterOrEqTrueTest() {
Vector2f a = new Vector2f(10, 12);
Vector2f b = new Vector2f(8, 9);
boolean expected = true;
boolean actual = a.Vector2fGreaterOrEq(a, b);
assertEquals(expected, actual);
}
/*
* Purpose: test Vector2fRound(Vector2f a, Vector2f dest)
* Input: Vector2f a(10, 12), dest()
* Expected: dest.x = Math.round(10), dest.y = Math.round(12)
*/
@Test
public void Vector2fRoundTest() {
Vector2f a = new Vector2f(10, 12);
Vector2f dest = new Vector2f();
a.Vector2fRound(a, dest);
float expectedX = Math.round(10);
float expectedY = Math.round(12);
assertTrue(dest.x == expectedX);
assertTrue(dest.y == expectedY);
}
/*
* Purpose: test Vector2fSnap(Vector2f a, Vector2f dest)
* Input: Vector2f a(10, 12), dest()
* Expected: dest.x = 10, dest.y = 12
*/
@Test
public void Vector2fSnapTest() {
Vector2f a = new Vector2f(10, 12);
Vector2f dest = new Vector2f();
a.Vector2fSnap(a, dest);
assertTrue(dest.x == 10);
assertTrue(dest.y == 12);
}
/*
* Purpose: test Vector2fSet(Vector2f a, float x, float y)
* Input: Vector2f a.Vector2fSet(a, 5, 5)
* Expected: a.x = 5, a.y = 5
*/
@Test
public void Vector2fSetTest() {
Vector2f a = new Vector2f(10, 12);
a.Vector2fSet(a, 5, 5);
assertTrue(a.x == 5);
assertTrue(a.y == 5);
}
/*
* Purpose: test Vector2fNegate(Vector2f a, Vector2f dest)
* Input: Vector2f a(3,4), dest();
* Expected: dest.x = -3, dest.y = -4
*/
@Test
public void Vector2fNegateTest() {
Vector2f a = new Vector2f(3, 4);
Vector2f dest = new Vector2f();
a.Vector2fNegate(a, dest);
assertTrue(dest.x == -3);
assertTrue(dest.y == -4);
}
/*
* Purpose: test Vector2fWholeNumber(Vector2f a, Vector2f dest)
* Input: Vector2f a(3.5f, 4.5f), dest(1.5f, 2.5f);
* Expected: dest.x = 4, dest.y = 5
*/
@Test
public void WholeNumberTest() {
Vector2f a = new Vector2f(3.5f, 4.5f);
Vector2f dest = new Vector2f(1.5f,2.5f);
int t = 3;
float delta = 3.5f - (float)t;
float expectedX = 4;
t = 4;
delta = 4.5f - (float)t;
float expectedY = 5;
a.Vector2fWholeNumber(a, dest);
float actualX = dest.x;
float actualY = dest.y;
assertTrue(actualX == expectedX);
assertTrue(actualY == expectedY);
}
/*
* Purpose: test Vector2fWholeNumber(Vector2f a, Vector2f dest)
* test coverage
* Input: Vector2f a(3,4), dest(1,2)
* Expected: dest.x = 3, dest.y = 4
*/
@Test
public void WholeNumberTestTwo() {
Vector2f a = new Vector2f(3, 4);
Vector2f dest = new Vector2f(1,2);
a.Vector2fWholeNumber(a, dest);
}
/*
* Purpose: test Vector2fWholeNumber(Vector2f a, Vector2f dest)
* test coverage
* Input: Vector2f a(-3.2f,-4.4f), dest(-2.2f, -1.8f)
* Expected: dest.x = -3, dest.y = -4
*/
@Test
public void WholeNumberTestThr() {
Vector2f a = new Vector2f(-3.2f, -4.4f);
Vector2f dest = new Vector2f(-2.2f, -1.8f);
a.Vector2fWholeNumber(a, dest);
}
/*
* Purpose: test Vector2fInterpolate(Vector2f a, Vector2f b, float alpha, Vector2f dest)
*
* Input: Vector2f a(3,4), b(4,5), alpha = 2, dest()
* Expected: dest.x = 5, dest.y = 6
*/
@Test
public void Vector2fInterpolateTest() {
Vector2f a = new Vector2f(3,4);
Vector2f b = new Vector2f(4,5);
float alpha = 2;
Vector2f dest = new Vector2f();
a.Vector2fInterpolate(a, b, alpha, dest);
assertTrue(dest.x == 5);
assertTrue(dest.y == 6);
}
/*
* Purpose: test Vector2fLerp(Vector2f a, Vector2f b, float alpha, Vector2f dest)
*
* Input: Vector2f a(3.0f,4.0f), b(4.0f,5.0f), alpha = 2.0f, dest()
* Expected: dest.x = 5, dest.y = 6
*/
@Test
public void Vector2fLerpTest() {
Vector2f a = new Vector2f(3.0f,4.0f);
Vector2f b = new Vector2f(4.0f,5.0f);
float alpha = 2.0f;
Vector2f dest = new Vector2f();
float invAlpha = 1.0f - alpha;
float expectedX = (3.0f * invAlpha) + (4.0f * alpha);
float expectedY = (4.0f * invAlpha) + (5.0f * alpha);
a.Vector2fLerp(a, b, alpha, dest);
assertTrue(dest.x == expectedX);
assertTrue(dest.y == expectedY);
}
}
| 37,506 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fVariousConstructorTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fVariousConstructorTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fVariousConstructorTest {
/*
* Purpose: Test Vector2f Constructor.
* Vector2f's x and y value will be initialized in 0.
* Input: new Vector2f()
* Expected: x = 0, y = 0
*/
@Test
public void testConstructor() {
Vector2f vector = new Vector2f();
}
/*
* Purpose: Test Vector2f Float Constructor.
* Vector2f's x and y value will be initialized in 0.
* Input: new Vector2f()
* Expected: x = 0, y = 0
*/
@Test
public void testFloatConstructor() {
Vector2f vector = new Vector2f();
float x = vector.x;
float y = vector.y;
assertTrue(x == 0);
assertTrue(y == 0);
}
/*
* Purpose: Test Vector2f Float Array Constructor.
* Vector2f's x and y value will be initialized in v[0], v[1].
* Input: float[] v = {1,2};
* Expected: x = 1, y = 2
*/
@Test
public void testFloatArrConstructor() {
float []v = {1, 2};
Vector2f vector = new Vector2f(v);
float x = vector.x;
float y = vector.y;
assertTrue(x == 1);
assertTrue(y == 2);
}
/*
* Purpose: Test Vector2f Vector2f Constructor.
* Vector2f's x and y value will be initialized in vectorOne's x and y.
* Input: VectorOne x = 2; y = 3;
* Expected: VectorTwo x = 2; y = 3;
*/
@Test
public void testVector2fConstructor() {
float x = 2;
float y = 3;
Vector2f vectorOne = new Vector2f(2, 3);
Vector2f vectorTwo = new Vector2f(vectorOne);
assertTrue(vectorTwo.x == 2);
assertTrue(vectorTwo.y == 3);
}
}
| 1,920 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LineTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/LineTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.FloatUtil;
import seventh.math.Line;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
public class LineTest {
/*
* Purpose: constructor stores right value
* Input: Line : (a, b) = (Vector2f, Vector2f)
*
* lineA = ((-1.0f,-1.0f), (1.0f,1.0f))
* lineB = ((1.0f,1.0f), (-1.0f,-1.0f))
* lineC = ((0.0f,0.0f), (0.0f,0.0f))
* Expected:
* lineA.a.x == -1.0f
* lineA.a.y == -1.0f
* lineA.b.x == 1.0f
* lineA.b.y == 1.0f
*
* lineB.a.x == 1.0f
* lineB.a.y == 1.0f
* lineB.b.x == -1.0f
* lineB.b.y == 1.0f
*
* lineC.a.x == 0.0f
* lineC.a.y == 0.0f
* lineC.b.x == 0.0f
* lineC.b.y == 0.0f
*/
@Test
public void testLineConstructor() {
// lineA : from (-1,-1) to (1,1)
final float lineAStartPointX = -1.0f, lineAStartPointY = -1.0f;
final float lineAEndPointX = 1.0f, lineAEndPointY = 1.0f;
// lineB : from (1,1) to (-1,-1)
final float lineBStartPointX = 1.0f, lineBStartPointY = 1.0f;
final float lineBEndPointX = -1.0f, lineBEndPointY = -1.0f;
// lineC : from (0,0) to (0,0)
// actually, not line, point
final float lineCStartPointX = 0.0f, lineCStartPointY = 0.0f;
final float lineCEndPointX = 0.0f, lineCEndPointY = 0.0f;
Line lineA = new Line(new Vector2f(lineAStartPointX, lineAStartPointY),
new Vector2f(lineAEndPointX, lineAEndPointY));
Line lineB = new Line(new Vector2f(lineBStartPointX, lineBStartPointY),
new Vector2f(lineBEndPointX, lineBEndPointY));
Line lineC = new Line(new Vector2f(lineCStartPointX, lineCStartPointY),
new Vector2f(lineCEndPointX, lineCEndPointY));
assertTrue(FloatUtil.eq(lineAStartPointX, lineA.a.x));
assertTrue(FloatUtil.eq(lineAStartPointY, lineA.a.y));
assertTrue(FloatUtil.eq(lineAEndPointX, lineA.b.x));
assertTrue(FloatUtil.eq(lineAEndPointY, lineA.b.y));
assertTrue(FloatUtil.eq(lineBStartPointX, lineB.a.x));
assertTrue(FloatUtil.eq(lineBStartPointY, lineB.a.y));
assertTrue(FloatUtil.eq(lineBEndPointX, lineB.b.x));
assertTrue(FloatUtil.eq(lineBEndPointY, lineB.b.y));
assertTrue(FloatUtil.eq(lineCStartPointX, lineC.a.x));
assertTrue(FloatUtil.eq(lineCStartPointY, lineC.a.y));
assertTrue(FloatUtil.eq(lineCEndPointX, lineC.b.x));
assertTrue(FloatUtil.eq(lineCEndPointY, lineC.b.y));
}
// ----------------------------------------------------
// line and line
/*
* to test method lineIntersectLine()
*/
private void assertLineIntersectLine(Line firstLine, Line secondLine, boolean expectedResult) {
assertEquals(expectedResult, Line.lineIntersectLine(firstLine, secondLine));
assertEquals(expectedResult, Line.lineIntersectLine(firstLine.a, firstLine.b, secondLine.a, secondLine.b));
assertEquals(expectedResult, Line.lineIntersectLine(
firstLine.a.x, firstLine.a.y,
firstLine.b.x, firstLine.b.y,
secondLine.a.x, secondLine.a.y,
secondLine.b.x, secondLine.b.y));
}
/*
* Purpose: two lines intersect
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f,0.0f))
* lineB = ((0.0f, -1.0f), (0.0f, 1.0f))
* Expected:
* return true
*/
@Test
public void testLineIntersectLine() {
// lineA and lineB intersect
// intersection point is (0.0f, 0.0f)
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineB = new Line(new Vector2f(0.0f, -1.0f), new Vector2f(0.0f, 1.0f));
assertLineIntersectLine(lineA, lineB, true);
}
/*
* Purpose: intersection point of two lines is the end of one of them
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f, 0.0f))
* lineC = ((1.0f, -1.0f), (1.0f, 1.0f))
* Expected:
* return true
*/
@Test
public void testLineIntersectEndOfLine() {
// lineA and lineC intersect
// intersection point is (1.0f, 0.0f)
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineC = new Line(new Vector2f(1.0f, -1.0f), new Vector2f(1.0f, 1.0f));
assertLineIntersectLine(lineA, lineC, true);
}
/*
* Purpose: two lines don't intersect
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f, 0.0f))
* lineD = ((2.0f, -1.0f), (2.0f, 1.0f))
* Expected:
* return false
*/
@Test
public void testLineNotIntersectLine() {
// lineA and lineD do not intersect
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineD = new Line(new Vector2f(2.0f, -1.0f), new Vector2f(2.0f, 1.0f));
assertLineIntersectLine(lineA, lineD, false);
}
/*
* Purpose: two lines (one of them is actually a point) intersect
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f, 0.0f))
* lineE = ((0.0f, 0.0f), (0.0f, 0.0f))
* Expected:
* return true
*/
@Test
public void testLineIntersectLineWhichIsPoint() {
// lineA and lineE(point) intersect
// intersection point is (0.0f, 0.0f)
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineE = new Line(new Vector2f(0.0f, 0.0f), new Vector2f(0.0f, 0.0f));
assertLineIntersectLine(lineA, lineE, true);
}
/*
* Purpose: intersection point of two lines(one of them is a point)
* is the end of line
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f, 0.0f))
* lineF = ((1.0f, 0.0f), (1.0f, 0.0f))
* Expected:
* return true
*/
@Test
public void testEndOfLineIntersectLineWhichIsPoint() {
// lineA and lineF(point) intersect
// intersection point is (1.0f, 0.0f)
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineF = new Line(new Vector2f(1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
assertLineIntersectLine(lineA, lineF, true);
}
/*
* Purpose: two lines(one of them is a point) don't intersect
* Input: lineIntersectLine
*
* lineA = ((-1.0f, 0.0f), (1.0f, 0.0f))
* lineG = ((2.0f, 0.0f), (2.0f, 0.0f))
* Expected:
* return false
*/
@Test
public void testLineNotIntersectLineWhichIsPoint() {
// lineA and lineG(point) do not intersect
Line lineA = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
Line lineG = new Line(new Vector2f(2.0f, 0.0f), new Vector2f(2.0f, 0.0f));
assertLineIntersectLine(lineA, lineG, false);
}
/*
* Purpose: two lines (both are actually points) intersect
* Input: lineIntersectLine
*
* lineE = ((0.0f, 0.0f), (0.0f, 0.0f))
* lineH = ((0.0f, 0.0f), (0.0f, 0.0f))
* Expected:
* return true
*/
@Test
public void testLinesWhichArePointIntersect() {
// lineE(point) and lineH(point) intersect
// intersection point is (0.0f, 0.0f)
Line lineE = new Line(new Vector2f(0.0f, 0.0f), new Vector2f(0.0f, 0.0f));
Line lineH = new Line(new Vector2f(0.0f, 0.0f), new Vector2f(0.0f, 0.0f));
assertLineIntersectLine(lineE, lineH, true);
}
/*
* Purpose: two lines(both are actually points) don't intersect
* Input: lineIntersectLine
*
* lineE = ((0.0f, 0.0f), (0.0f, 0.0f))
* lineF = ((1.0f, 0.0f), (1.0f, 0.0f))
* Expected:
* return false
*************** Error ******************
*/
@Test
public void testLinesWhichArePointNotIntersect() {
// lineE(point) and lineF(point) do not intersect
Line lineE = new Line(new Vector2f(0.0f, 0.0f), new Vector2f(0.0f, 0.0f));
Line lineF = new Line(new Vector2f(1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
assertLineIntersectLine(lineE, lineF, false);
}
// -------------------------------------------------------------
// line and rectangle
// determine - test near collision point and far collision point
// I do not test the near/far collision points
// because the result value (collision points) is so much different from the value I expected,
// I think I don't understand the collision points.
private final static boolean NEARFARCHECK = false;
// to test method lineIntersectsRectangle()
private void assertLineIntersectsRectangle(
Line line,
Rectangle rectangle,
boolean expectedResult,
boolean testCollisionPoint,
Vector2f expectedNear,
Vector2f expectedFar)
{
Vector2f nearA = new Vector2f();
Vector2f farA = new Vector2f();
Vector2f nearB = new Vector2f();
Vector2f farB = new Vector2f();
assertEquals(expectedResult, Line.lineIntersectsRectangle(line, rectangle));
assertEquals(expectedResult, Line.lineIntersectsRectangle(line.a, line.b, rectangle));
assertEquals(expectedResult, Line.lineIntersectsRectangle(line, rectangle, nearA, farA));
assertEquals(expectedResult, Line.lineIntersectsRectangle(line.a, line.b, rectangle, nearB, farB));
if (testCollisionPoint)
{
if (NEARFARCHECK) {
// near, far collision point check
// expected
final float nearCollisionX = expectedNear.x;
final float nearCollisionY = expectedNear.y;
final float farCollisionX = expectedFar.x;
final float farCollisionY = expectedFar.y;
assertTrue(FloatUtil.eq(nearCollisionX, nearA.x));
assertTrue(FloatUtil.eq(nearCollisionY, nearA.y));
assertTrue(FloatUtil.eq(farCollisionX, farA.x));
assertTrue(FloatUtil.eq(farCollisionY, farA.y));
assertTrue(FloatUtil.eq(nearCollisionX, nearB.x));
assertTrue(FloatUtil.eq(nearCollisionY, nearB.y));
assertTrue(FloatUtil.eq(farCollisionX, farB.x));
assertTrue(FloatUtil.eq(farCollisionY, farB.y));
Vector2f nearCollisionPoint = Line.nearCollisionPoint(line, rectangle);
Vector2f farCollisionPoint = Line.farCollisionPoint(line, rectangle);
assertTrue(FloatUtil.eq(nearCollisionX, nearCollisionPoint.x));
assertTrue(FloatUtil.eq(nearCollisionY, nearCollisionPoint.y));
assertTrue(FloatUtil.eq(farCollisionX, farCollisionPoint.x));
assertTrue(FloatUtil.eq(farCollisionY, farCollisionPoint.y));
}
}
}
/*
* Purpose: line intersects with a rectangle. the start, end points of line are not in the rectangle.
* Input: lineIntersectsRectangle
* nearCollisionPoint
* farCollisionPoint
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineG = ((-1.0f, 1.0f), (4.0f, 1.0f))
* Expected:
* return true
* (0, 1) = near
* (3, 1) = far
*/
@Test
public void testLineIntersectsThroughRect() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineG = new Line(new Vector2f(-1.0f, 1.0f), new Vector2f(4.0f, 1.0f));
// expected near,far collision point
final float nearCollisionX = 0.0f;
final float nearCollisionY = 1.0f;
final float farCollisionX = 3.0f;
final float farCollisionY = 1.0f;
assertLineIntersectsRectangle(
lineG,
rectangle,
true,
true,
new Vector2f(nearCollisionX, nearCollisionY),
new Vector2f(farCollisionX, farCollisionY));
}
/*
* Purpose: line intersects with a rectangle, the line is on the edge of rectangle, parallel
* Input: lineIntersectsRectangle
* nearCollisionPoint
* farCollisionPoint
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineH = ((-1.0f, 0.0f), (4.0f, 0.0f))
* Expected:
* return true
* (0, 0) = near
* (3, 0) = far
*/
@Test
public void testLineIntersectsRectLineOnEdge() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineH = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(4.0f, 0.0f));
// expected near,far collision point
final float nearCollisionX = 0.0f;
final float nearCollisionY = 0.0f;
final float farCollisionX = 3.0f;
final float farCollisionY = 0.0f;
assertLineIntersectsRectangle(
lineH,
rectangle,
true,
true,
new Vector2f(nearCollisionX, nearCollisionY),
new Vector2f(farCollisionX, farCollisionY));
}
/*
* Purpose: line intersects with a rectangle. start point of the line is in the rectangle, end point of the line is not.
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineI = ((2.0f, 2.0f), (4.0f, 2.0f))
* Expected:
* return true
*/
@Test
public void testHalfLineIntersectsRect() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineI = new Line(new Vector2f(2.0f, 2.0f), new Vector2f(4.0f, 2.0f));
assertLineIntersectsRectangle(
lineI,
rectangle,
true,
false,
null,
null);
}
/*
* Purpose: line doesn't intersects with a rectangle
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineJ = ((-1.0f, 4.0f), (4.0f, 4.0f))
* Expected:
* return false
*/
@Test
public void testLineNotIntersectsRectangle() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineJ = new Line(new Vector2f(-1.0f, 4.0f), new Vector2f(4.0f, 4.0f));
assertLineIntersectsRectangle(
lineJ,
rectangle,
false,
false,
null,
null);
}
/*
* Purpose: The line is inside the rectangle.
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineK = ((1.0f, 1.0f), (2.0f, 2.0f))
* Expected:
* return true
*/
@Test
public void testLineIsInsideRectangle() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineK = new Line(new Vector2f(1.0f, 1.0f), new Vector2f(2.0f, 2.0f));
assertLineIntersectsRectangle(
lineK,
rectangle,
true,
false,
null,
null);
}
/*
* Purpose: the line is a point. the line is on the edge of the rectangle.
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineL = ((1.0f, 0.0f), (1.0f, 0.0f))
* Expected:
* return true
*/
@Test
public void testLineWhichIsPointOnEdge() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineL = new Line(new Vector2f(1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
// expected near,far collision point
final float nearCollisionX = 1.0f;
final float nearCollisionY = 0.0f;
final float farCollisionX = 1.0f;
final float farCollisionY = 0.0f;
assertLineIntersectsRectangle(
lineL,
rectangle,
true,
true,
new Vector2f(nearCollisionX, nearCollisionY),
new Vector2f(farCollisionX, farCollisionY));
}
/*
* Purpose: the line is a point. the line is inside the rectangle.
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineM = ((1.0f, 1.0f), (1.0f, 1.0f))
* Expected:
* return true
*/
@Test
public void testLineWhichIsPointInRect() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineM = new Line(new Vector2f(1.0f, 1.0f), new Vector2f(1.0f, 1.0f));
assertLineIntersectsRectangle(
lineM,
rectangle,
true,
false,
null,
null);
}
/*
* Purpose: the line is a point. the line is outside the rectangle.
* Input: lineIntersectsRectangle
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* lineN = ((4.0f, 4.0f), (4.0f, 4.0f))
* Expected:
* return false
* ************************ Error ****************
*/
@Test
public void testLineWhichIsPointOutRect() {
Rectangle rectangle = new Rectangle(0,0,3,3);
Line lineN = new Line(new Vector2f(4.0f, 4.0f), new Vector2f(4.0f, 4.0f));
assertLineIntersectsRectangle(
lineN,
rectangle,
false,
false,
null,
null);
}
/*
* Purpose: satisfy coverage - function : Line.outcode()
* width of rectangle <= 0
* height of rectangle <= 0
* Input: lineIntersectsRectangle calls intersectsLine that calls outcode
*
* rectangle : x = 0, y = 0, width = -2, height = -2
* line = ((-1.0f, 0.0f), (1.0f, 0.0f))
* Expected:
* return false
*/
@Test
public void testOutcodeNegRectWH() {
// rectangle.width <= 0, rectangle.height <=0
Rectangle rectangle = new Rectangle(0, 0, -2, -2);
Line line = new Line(new Vector2f(-1.0f, 0.0f), new Vector2f(1.0f, 0.0f));
assertEquals(false, Line.lineIntersectsRectangle(line, rectangle));
}
/*
* Purpose: satisfy coverage - function : Line.outcode()
* y of start or end point of line is lower than y of rectangle
* Input: lineIntersectsRectangle calls intersectsLine that calls outcode
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* line = ((-1.0f, -3.0f), (1.0f, -1.0f))
* Expected:
* return false
*/
@Test
public void testOutcodeLineYltRectY() {
Rectangle rectangle = new Rectangle(0, 0, 3, 3);
Line line = new Line(new Vector2f(-1.0f, -3.0f), new Vector2f(1.0f, -1.0f));
assertEquals(false, Line.lineIntersectsRectangle(line, rectangle));
}
/*
* Purpose: satisfy coverage - function : Line.intersectsLine(Rectangle,float,float,float,float)
* the right of the rectangle is to the start point of line.
* Input: lineIntersectsRectangle calls intersectsLine
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* line = ((5.0f, 1.0f), (-1.0f, 1.0f))
* Expected:
* return true
*/
@Test
public void testRectIsOUT_RIGHT() {
Rectangle rectangle = new Rectangle(0, 0, 3, 3);
Line line = new Line(new Vector2f(5.0f, 1.0f), new Vector2f(-1.0f, 1.0f));
assertEquals(true, Line.lineIntersectsRectangle(line, rectangle));
}
/*
* Purpose: satisfy coverage - function : Line.intersectsLine(Rectangle,float,float,float,float)
* rectangle is OUT_BOTTOM, but is not OUT_LEFT | OUT_RIGHT
* Input: lineIntersectsRectangle calls intersectsLine
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* line = ((1.0f, 4.0f), (1.0f, -1.0f))
* Expected:
* return true
*/
@Test
public void testRectIsBNotLR() {
Rectangle rectangle = new Rectangle(0, 0, 3, 3);
Line line = new Line(new Vector2f(1.0f, 4.0f), new Vector2f(1.0f, -1.0f));
assertEquals(true, Line.lineIntersectsRectangle(line, rectangle));
}
/*
* Purpose: satisfy coverage - function : Line.intersectsLine(Rectangle,float,float,float,float)
* rectangle is OUT_TOP, but is not OUT_LEFT | OUT_RIGHT
* Input: lineIntersectsRectangle calls intersectsLine
*
* rectangle : x = 0, y = 0, width = 3, height = 3
* line = ((1.0f, -1.0f), (1.0f, 4.0f))
* Expected:
* return true
*/
@Test
public void testRectIsTNotLR() {
Rectangle rectangle = new Rectangle(0, 0, 3, 3);
Line line = new Line(new Vector2f(1.0f, -1.0f), new Vector2f(1.0f, 4.0f));
assertEquals(true, Line.lineIntersectsRectangle(line, rectangle));
}
}
| 23,122 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fGetSetTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fGetSetTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fGetSetTest {
/*
* Purpose: To test Vector2f.get(int i). it returns x when the i is 0, y otherwise.
* Input: Vector2f(2,3), get(0), get(1);
* Expected: get(0) = 2, get(1) = 3
*/
@Test
public void Vector2fGetTest() {
Vector2f vector = new Vector2f(2,3);
int i = 0;
int j = 1;
float actualX = vector.get(i);
float actualY = vector.get(j);
assertTrue(actualX == 2);
assertTrue(actualY == 3);
}
/*
* Purpose: To test set(float x, float y). this.x = x, this.y = y
* Input: Vector2f(), set(2,3)
* Expected: Vector2f.x = 2, Vector2f.y = 3
*/
@Test
public void Vector2fFloatSetTest() {
Vector2f vector = new Vector2f();
vector.set(2,3);
assertTrue(vector.x == 2);
assertTrue(vector.y == 3);
}
/*
* Purpose: To test set(Vector2f v). this.x = v.x, this.y = c.y
* Input: vectorOne(2,3), vectorTwo.set(vectorOne)
* Expected: vectorTwo.x = 2, vectorTwo.y = 3
*/
@Test
public void Vector2fVector2fSetTest() {
Vector2f vectorOne = new Vector2f(2,3);
Vector2f vectorTwo = new Vector2f();
vectorTwo.set(vectorOne);
assertTrue(vectorTwo.x == 2);
assertTrue(vectorTwo.y == 3);
}
/*
* Purpose: To test set(float[] v)
* Input: vector(), set(float[] v), v = {1, 2, 3}
* Expected: vector.x = 1, vector.y = 2
*/
@Test
public void Vector2fFloatArrSetTest() {
float[] v = {1, 2, 3};
Vector2f vector = new Vector2f();
vector.set(v);
assertTrue(vector.x == 1);
assertTrue(vector.y == 2);
}
}
| 1,888 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TriTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/TriTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.Tri;
public class TriTest {
/*
* Purpose: check that the correct integer values stored
* Input: Tri<int, int, int> using positive, zero, negative
* TriP(43, 36, 88), TriZ(00000, 000, 00000), TriN(-55, -38, -25)
* Expected:
* TriP.fisrt == 43, TriP.second == 36, TriP.second == 88
* TriZ.fisrt == 00000, TriZ.second == 000, TriZ.second == 00000
* TriN.first == -55, TriN.second == -38, TriN.second == -25
*/
@Test
public void testTriIntConstructor() {
Tri TriA = new Tri( 43, 36, 88);
assertEquals( 43, TriA.getFirst() );
assertEquals( 36, TriA.getSecond());
assertEquals( 88, TriA.getThird() );
Tri TriZ = new Tri(00000, 000, 0000);
assertEquals(00000, TriZ.getFirst() );
assertEquals( 000, TriZ.getSecond());
assertEquals(00000, TriZ.getThird() );
Tri TriN = new Tri( -55, -38, -25);
assertEquals( -55, TriN.getFirst() );
assertEquals( -38, TriN.getSecond());
assertEquals( -25, TriN.getThird() );
}
/*
* Purpose: check that the correct double values stored
* Input: Tri<double, double, double> using positive, zero, negative
* TriP(6.32, 64.72, 39.4), TriZ(0000.0, 00.0, 0.0), TriN(-93.59, -60.13, -1.78)
* Expected:
* TriP.fisrt == 6.32, TriP.second == 64.72, TriP.second == 39.4
* TriZ.fisrt == 0000.0, TriZ.second == 00.0, TriZ.second == 0.0
* TriN.first == -93.59, TriN.second == -60.13, TriN.second == -1.78
*/
@Test
public void testTriDoubleConstructor() {
Tri TriA = new Tri( 6.32, 64.72, 39.4);
assertEquals( 6.32, TriA.getFirst() );
assertEquals( 64.72, TriA.getSecond());
assertEquals( 39.4, TriA.getThird() );
Tri TriZ = new Tri( 0000.0, 00.0, 0.0 );
assertEquals(0000.0, TriZ.getFirst() );
assertEquals( 00.0, TriZ.getSecond());
assertEquals( 0.0, TriZ.getThird() );
Tri TriN = new Tri(-93.59, -60.13, -1.78);
assertEquals( -93.59, TriN.getFirst() );
assertEquals( -60.13, TriN.getSecond());
assertEquals( -1.78, TriN.getThird() );
}
/*
* Purpose: check that the correct integer values stored
* Input: Tri<int, int, int> set positive, zero, negative
* set TriP( 25, 10, 41),
* set TriZ( 0, 0, 00),
* set TriN(-10, -20, -3)
* Expected:
* TriP.fisrt == 25, TriP.second == 10, TriP.third == 41
* TriZ.fisrt == 0, TriZ.second == 0, TriZ.third == 00
* TriN.first == -10, TriN.second == -20, TriN.third == -3
* */
@Test
public void testTriSetInt() {
Tri TriA = new Tri(-3, 5, 34);
TriA.setFirst( 25);
assertEquals( 25, TriA.getFirst() );
TriA.setSecond( 10);
assertEquals( 10, TriA.getSecond());
TriA.setThird( 41);
assertEquals( 41, TriA.getThird() );
Tri TriZ = new Tri(22, 22, 3);
TriZ.setFirst( 0);
assertEquals( 0, TriZ.getFirst() );
TriZ.setSecond( 0);
assertEquals( 0, TriZ.getSecond());
TriZ.setThird( 00);
assertEquals( 00, TriZ.getThird() );
Tri TriN = new Tri( 0, 0, 8);
TriN.setFirst( -10);
assertEquals( -10, TriN.getFirst() );
TriN.setSecond(-20);
assertEquals( -20, TriN.getSecond());
TriN.setThird( -3);
assertEquals( -3, TriN.getThird() );
}
/*
* Purpose: check that the correct double values stored
* Input: Tri<double, double, double> set positive, zero, negative
* set TriP( 26.56, 1069.639, 28.6 ),
* set TriZ( 0.0, 00.0000, 00.00),
* set TriN(-148.14, -41.149, -30.24)
* Expected:
* TriP.fisrt == 26.56, TriP.second == 1069.639, TriP.third == 28.6
* TriZ.fisrt == 0.0, TriZ.second == 00.0000, TriZ.third == 00.00
* TriN.first == -148.14, TriN.second == -41.149, TriN.third == -30.24
*/
@Test
public void testTriSetDouble() {
Tri TriA = new Tri( 45.5, 268.157, 45.5);
TriA.setFirst( 26.56);
assertEquals( 26.56, TriA.getFirst() );
TriA.setSecond(1069.639);
assertEquals( 1069.639, TriA.getSecond());
TriA.setThird( 28.6);
assertEquals( 28.6, TriA.getThird() );
Tri TriZ = new Tri(-479.369, 2308.2, 37.27);
TriZ.setFirst( 0.0);
assertEquals( 0.0, TriZ.getFirst() );
TriZ.setSecond( 00.0000);
assertEquals( 00.0000, TriZ.getSecond());
TriZ.setThird( 00.00);
assertEquals( 00.00, TriZ.getThird() );
Tri TriN = new Tri( 29.2, 175.17, 42.14);
TriN.setFirst( -148.14);
assertEquals( -148.14, TriN.getFirst() );
TriN.setSecond( -41.149);
assertEquals( -41.149, TriN.getSecond());
TriN.setThird( -30.24);
assertEquals( -30.24, TriN.getThird() );
}
}
| 5,599 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fNormalizeTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fNormalizeTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
import static java.lang.Math.atan2;
public class Vector2fNormalizeTest {
/*
* Purpose: test normalize(), returns normalized x and y
* Input: vector.normalize(), x=3, y =4
* Expected: x = 3.0f * FlLen, y = 4.0f * FlLen;
*/
@Test
public void NormalizeTest() {
Vector2f vector = new Vector2f();
vector.normalize();
vector.set(3,4);
vector.normalize();
float FlLen = 1.0f/5.0f;
float expectedX = 3.0f * FlLen;
float expectedY = 4.0f * FlLen;
assertTrue(vector.x == expectedX );
assertTrue(vector.y == expectedY );
}
/*
* Purpose: test lengthSquared(), returns x*x + y*y
* Input: Vector2f(3,4)
* Expected: 25.0f
*/
@Test
public void lenthSquaredTest() {
Vector2f vector = new Vector2f(3, 4);
float actual = vector.lengthSquared();
float expected = 25.0f;
assertTrue(actual == expected);
}
/*
* Purpose: test length(), returns Math.sqrt(x*x + y*y)
* Input: Vector2f(3,4)
* Expected: 5.0f
*/
@Test
public void lenthTest() {
Vector2f vector = new Vector2f(3, 4);
float actual = vector.length();
float expected = 5.0f;
assertTrue(actual == expected);
}
/*
* Purpose: test rotate(double radians)
* x1 = x * cos(radians) - y * sin(radians)
* y1 = x * sin(radians) + y * cos(radians)
* return Vector2f((float)x1, (float)y1)
* Input: vector(3,4), radians = 30
* Expected: x = (float)x1, y = (float)y1
*/
@Test
public void RotateTest() {
Vector2f vector = new Vector2f(3, 4);
Vector2f dest = new Vector2f();
double radians = 30;
double x1 = 3 * Math.cos(radians) - 4 * Math.sin(radians);
double y1 = 3 * Math.sin(radians) + 4 * Math.cos(radians);
float expectedX = (float)x1;
float expectedY = (float)y1;
dest = vector.rotate(30.0d);
assertTrue(dest.x == expectedX);
assertTrue(dest.y == expectedY);
}
}
| 2,302 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FloatUtilTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/FloatUtilTest.java | package test.math;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.FloatUtil;
import seventh.math.Vector2f;
public class FloatUtilTest {
/*
* Purpose: Determine if two floats are equal by a given Epsilon.
* Input: float, float // float,float,float
* Expected:
* if two float variables are Equal, return true
* if two float variables aren't Equal, return false
*/
@Test
public void eqTest() {
float x = 1.234f;
float y = 1.2345f;
float z = 1.24f;
assertTrue(FloatUtil.eq(x,y));
assertFalse(FloatUtil.eq(x,z));
assertFalse(FloatUtil.eq(x,y,0.0001f));
assertTrue(FloatUtil.eq(x,z,0.01f));
}
/*
* Purpose: Determine if one float is greater than another
* Input: float, float
* Expected:
* if one float is greater than another, return true
* if one float isn't greater than another, return false
*/
@Test
public void gtTest() {
float x = 1.234f;
float y = 1.2450f;
float z = 1.24501f;
assertTrue(FloatUtil.gt(y,x));
assertFalse(FloatUtil.gt(x,y));
assertFalse(FloatUtil.gt(y,z));
}
/*
* Purpose: Determine if one float is less than another
* Input: float, float
* Expected:
* if one float is less than another, return true
* if one float isn't less than another, return false
*/
@Test
public void ltTest() {
float x = 1.234f;
float y = 1.2450f;
float z = 1.24501f;
assertFalse(FloatUtil.lt(y,x));
assertTrue(FloatUtil.lt(x,y));
assertFalse(FloatUtil.lt(y,z));
}
/*
* Purpose: Determine if one float is greater than another or equal
* Input: float, float
* Expected:
* if one float is greater than another or equal, return true
* if one float isn't greater than another or equal, return false
*/
@Test
public void gteTest() {
float x = 1.234f;
float y = 1.2450f;
float z = 1.24501f;
assertTrue(FloatUtil.gte(y,x));
assertFalse(FloatUtil.gte(x,y));
assertTrue(FloatUtil.gte(y,z));
}
/*
* Purpose: Determine if one float is less than another or equal
* Input: float, float
* Expected:
* if one float is less than another or equal, return true
* if one float isn't less than another or equal, return false
*/
@Test
public void lteTest() {
float x = 1.234f;
float y = 1.2450f;
float z = 1.24501f;
assertFalse(FloatUtil.lte(y,x));
assertTrue(FloatUtil.lte(x,y));
assertTrue(FloatUtil.lte(y,z));
}
/*
* Purpose: add two float array's element in same index
* Input: float[], float[], float[]
* Expected:
* the added float array
*/
@Test
public void Vector2fAddTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
float[] dest={0,0};
float expectd1 =1.234f+3.432f;
float expectd2 =2.323f+7.544f;
FloatUtil.Vector2fAdd(a, b, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: subtract two float array's element in same index
* Input: float[], float[], float[]
* Expected:
* the subtracted float array
*/
@Test
public void Vector2fSubtractTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
float[] dest={0,0};
float expectd1 =1.234f-3.432f;
float expectd2 =2.323f-7.544f;
FloatUtil.Vector2fSubtract(a, b, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: multiply two float array's element in same index
* Input: float[], float[], float[]
* Expected:
* the multiplied float array
*/
@Test
public void Vector2fMultTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
float[] dest={0,0};
float expectd1 =1.234f*3.432f;
float expectd2 =2.323f*7.544f;
float expectd3 =1.234f*4.123f;
float expectd4 =2.323f*4.123f;
FloatUtil.Vector2fMult(a, b, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
FloatUtil.Vector2fMult(a, 4.123f, dest);
assertEquals(expectd3,dest[0],0.00001f);
assertEquals(expectd4,dest[1],0.00001f);
}
/*
* Purpose: divide two float array's element in same index
* Input: float[], float[], float[]
* Expected:
* the divided float array
*/
@Test
public void Vector2fDivTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
float[] dest={0,0};
float expectd1 =1.234f/3.432f;
float expectd2 =2.323f/7.544f;
FloatUtil.Vector2fDiv(a, b, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: add two float array's element in different index(0 and 1, 1 and 0)
* Input: float[], float[]
* Expected:
* the cross added float
*/
@Test
public void Vector2fCrossTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
float expectd1 =1.234f*7.544f-2.323f*3.432f;
assertEquals(expectd1,FloatUtil.Vector2fCross(a, b),0.00001f);
}
/*
* Purpose: Determine if two float arrays are equal
* Input: float[], float[]
* Expected:
* if two float arrays are Equal, return true
* if two float arrays aren't Equal, return false
*/
@Test
public void Vector2fEqualsTest() {
float[] a={1.234f,2.323f};
float[] b={1.234f,2.323f};
float[] c={3.432f, 7.544f};
float[] d={1.234f, 7.544f};
assertTrue(FloatUtil.Vector2fEquals(a, b));
assertFalse(FloatUtil.Vector2fEquals(a, c));
assertFalse(FloatUtil.Vector2fEquals(a, d));
}
/*
* Purpose: Determine if two float arrays are equal by a giving Epsilon
* Input: float[], float[]
* Expected:
* if two float arrays are Equal, return true
* if two float arrays aren't Equal, return false
*/
@Test
public void Vector2fApproxEqualsTest() {
float[] a={1.234f,2.323f};
float[] b={1.234f,2.323f};
float[] c={3.432f, 7.544f};
float[] d={1.234f, 7.544f};
assertTrue(FloatUtil.Vector2fApproxEquals(a, b));
assertFalse(FloatUtil.Vector2fApproxEquals(a, c));
assertFalse(FloatUtil.Vector2fApproxEquals(a, d));
}
/*
* Purpose: rotate one float point(x,y) by radians
* Input: float[],float, float[]
* Expected:
* the float array having rotated float point(x,y)
*/
@Test
public void Vector2fRotateTest() {
float[] a={1.234f,2.323f};
float[] dest={0,0};
float radians = 30.0f;
float expectd1 =(float)(1.234f * cos(radians) - 2.323f * sin(radians));
float expectd2 =(float)(1.234f * sin(radians) + 2.323f * cos(radians));
FloatUtil.Vector2fRotate(a, radians, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: get the length from zero point(0,0) to one float point(x,y)
* Input: float[]
* Expected:
* the length from zero point(0,0) to one float point(x,y)
*/
@Test
public void Vector2fLengthTest() {
float[] a={1.234f,2.323f};
float expectd1 =(float)Math.sqrt( 1.234f * 1.234f + 2.323f * 2.323f) ;
assertEquals(expectd1,FloatUtil.Vector2fLength(a),0.00001f);
}
/*
* Purpose: get the length'square from zero point(0,0) to one float point(x,y)
* Input: float[]
* Expected:
* the length'square from zero point(0,0) to one float point(x,y)
*/
@Test
public void Vector2fLengthSqTest() {
float[] a={1.234f,2.323f};
float expectd1 =1.234f * 1.234f + 2.323f * 2.323f ;
assertEquals(expectd1,FloatUtil.Vector2fLengthSq(a),0.00001f);
}
/*
* Purpose: get the normalized point(x,y) from one float point(x,y)
* Input: float[], float[]
* Expected:
* the normalized point(x,y) from one float point(x,y)
*/
@Test
public void Vector2fNormalizeTest() {
float[] a={1.234f,2.323f};
float[] b={0.0f,0.0f};
float[] dest={0,0};
float fLen = 1.0f / ( (float)Math.sqrt( (1.234f * 1.234f + 2.323f * 2.323f) ));
float expectd1 = 1.234f * fLen;
float expectd2 = 2.323f * fLen;
FloatUtil.Vector2fNormalize(b, dest);
FloatUtil.Vector2fNormalize(a, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: copy one float array to another
* Input: float[], float[]
* Expected:
* copied float array
*/
@Test
public void Vector2fCopyTest() {
float[] a={1.234f,2.323f};
float[] dest={0,0};
float expectd1 = 1.234f;
float expectd2 = 2.323f;
FloatUtil.Vector2fCopy(a, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: change each float array's element to zero
* Input: float[]
* Expected:
* the array having zero element
*/
@Test
public void Vector2fZeroOutTest() {
float[] a={1.234f,2.323f};
float expectd1 = 0;
float expectd2 = 0;
FloatUtil.Vector2fZeroOut(a);
assertEquals(expectd1,a[0],0.00001f);
assertEquals(expectd2,a[1],0.00001f);
}
/*
* Purpose: check whether each float array's element is zero
* Input: float[]
* Expected:
* if all array's elements are zero, return true
* unless, return false
*/
@Test
public void Vector2fIsZeroTest() {
float[] a={1.234f,2.323f};
float[] b={0,0};
float[] c={0,0.3232f};
assertFalse(FloatUtil.Vector2fIsZero(a));
assertTrue(FloatUtil.Vector2fIsZero(b));
assertFalse(FloatUtil.Vector2fIsZero(c));
}
/*
* Purpose: make one vector2f object with one float array
* Input: float[]
* Expected:
* the one vector2f object
*/
@Test
public void Vector2fToVector2fTest() {
float[] a={1.234f,2.323f};
Vector2f b = FloatUtil.Vector2fToVector2f(a);
assertEquals(a[0],b.get(0),0.00001f);
assertEquals(a[1],b.get(1),0.00001f);
}
/*
* Purpose: make one array having zero elements
* Input:
* Expected:
* the array having zero elements
*/
@Test
public void Vector2fNewTest() {
float[] a = FloatUtil.Vector2fNew();
assertEquals(0,a[0],0.00001f);
assertEquals(0,a[1],0.00001f);
}
/*
* Purpose:Determine if each array'element in same index is greater than another or equal
* Input: float[], float[]
* Expected:
* one array's all element is greater than another or equal, return true
* unless return false
*/
@Test
public void Vector2fGreaterOrEqTest() {
float[] a={1.234f,2.323f};
float[] b={3.432f, 7.544f};
assertFalse(FloatUtil.Vector2fGreaterOrEq(a,b));
assertTrue(FloatUtil.Vector2fGreaterOrEq(b,a));
}
/*
* Purpose: round off one float array's each element
* Input: float[], float[]
* Expected:
* the rounded array
*/
@Test
public void Vector2fRoundTest() {
float[] a={1.234f,2.323f};
float[] dest={0,0};
float expectd1 = Math.round(a[0]);
float expectd2 = Math.round(a[1]);
FloatUtil.Vector2fRound(a, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: make one float array with two floats
* Input: float[], float, float
* Expected:
* the float array with two floats
*/
@Test
public void Vector2fSetTest() {
float[] dest={0,0};
float expectd1 = 1.234f;
float expectd2 = 2.323f;
FloatUtil.Vector2fSet(dest, expectd1, expectd2);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
/*
* Purpose: make negated float array with one float array
* Input: float[], float[]
* Expected:
* the negated float array
*/
@Test
public void Vector2fNegateTest() {
float[] a={1.234f,2.323f};
float[] dest={0,0};
float expectd1 = -1.234f;
float expectd2 = -2.323f;
FloatUtil.Vector2fNegate(a, dest);
assertEquals(expectd1,dest[0],0.00001f);
assertEquals(expectd2,dest[1],0.00001f);
}
}
| 13,671 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
OBBTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/OBBTest.java | package test.math;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.OBB;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
public class OBBTest {
public float width;
public float height;
public float orientation;
public Vector2f center;
public Vector2f topLeft, topRight, bottomLeft, bottomRight;
/*
* Purpose: Test Defaults Constructor
* Input: obb default
* Expected:
* All Entities of Constructor are 0
*/
@Test
public void DefaultConstructorTest() {
OBB obb = new OBB();
assertTrue(0 == obb.getOrientation());
assertTrue(0 == obb.getWidth());
assertTrue(0 == obb.getHeight());
assertTrue(0 == obb.length());
}
/*
* Purpose: Test Constructor of a default rectangle as input
* Input: obb default Rectangle
* Expected:
* All Entities of Constructor are 0
*/
@Test
public void DefaultRectangleConstructorTest() {
Rectangle r = new Rectangle();
OBB obb = new OBB(r);
assertTrue(0 == obb.getOrientation());
assertTrue(0 == obb.getWidth());
assertTrue(0 == obb.getHeight());
assertTrue(0 == obb.length());
assertEquals(new Vector2f(0, 0), obb.getCenter());
}
/*
* Purpose: Test Constructor of a rectangle as input
* Input: obb Rectangle
* Expected:
* All Entities of Constructor are same as rectangle's
* width : 3
* height : 4
* length : 5
* center : (2, 3)
*/
@Test
public void RectangleConstructorTest() {
Rectangle r = new Rectangle(1, 1, 3, 4); // r.x + r.width/2, r.y + r.height/2
OBB obb = new OBB(r);
assertTrue(0 == obb.getOrientation());
assertTrue(3 == obb.getWidth());
assertTrue(4 == obb.getHeight());
assertTrue(5 == obb.length());
assertEquals(new Vector2f(2, 3), obb.getCenter());
}
/*
* Purpose: Test Constructor of a rectangle, an orientation as input
* Input: obb Orientation, Rectangle
* Expected:
* All Entities of Constructor are same as rectangle's
* width : 3
* height : 4
* center : (2, 3)
*
* orientation : 3
*/
@Test
public void OrientationRectangleConstructorTest() {
Rectangle r = new Rectangle(1, 1, 3, 4);
OBB obb = new OBB(3, r);
assertTrue(3 == obb.getOrientation());
assertTrue(3 == obb.getWidth());
assertTrue(4 == obb.getHeight());
assertEquals(new Vector2f(2, 3), obb.getCenter());
}
/*
* Purpose: Test Constructor of an default OBB as input
* Input: obb default OBB
* Expected:
* All Entities of Constructor are same as origin OBB's
*/
@Test
public void DefaultOBBConstructorTest() {
OBB obb = new OBB();
OBB obb_param = new OBB(obb);
assertTrue(obb_param.getOrientation() == obb.getOrientation());
assertTrue(obb_param.getWidth() == obb.getWidth());
assertTrue(obb_param.getHeight() == obb.getHeight());
assertEquals(obb_param.getCenter(), obb.getCenter());
assertTrue(obb_param.length() == obb.length());
}
/*
* Purpose: Test Constructor of an OBB as input
* Input: obb OBB
* Expected:
* All Entities of Constructor are same as origin OBB's
*/
@Test
public void OBBConstructorTest() {
Rectangle r = new Rectangle(1, 1, 3, 4);
OBB obb = new OBB(3, r);
OBB obb_param = new OBB(obb);
assertTrue(obb_param.getOrientation() == obb.getOrientation());
assertTrue(obb_param.getWidth() == obb.getWidth());
assertTrue(obb_param.getHeight() == obb.getHeight());
assertEquals(obb_param.getCenter(), obb.getCenter());
assertTrue(obb_param.length() == obb.length());
}
/*
* Purpose: Test Constructor of orientation, center x,y , width, height as input
* Input: obb orientation = 1, center x = 1, center y = 1, width = 3, height = 4
* Expected:
* orientation : 1
* width : 3
* height : 4
* center : (1, 1)
*/
@Test
public void AllParamConstructorTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
assertTrue(1 == obb.getOrientation());
assertTrue(3 == obb.getWidth());
assertTrue(4 == obb.getHeight());
assertEquals(new Vector2f(1, 1), obb.getCenter());
}
/*
* Purpose: Test Constructor of orientation, center vector, width, height as input
* Input: obb orientation = 1, center vector (1, 1), width = 3, height = 4
* Expected:
* orientation : 1
* width : 3
* height : 4
* center : (1, 1)
*/
@Test
public void AllParamWithVectorConstructorTest() {
OBB obb = new OBB(1, new Vector2f(2, 3), 3, 4);
assertTrue(1 == obb.getOrientation());
assertTrue(3 == obb.getWidth());
assertTrue(4 == obb.getHeight());
assertEquals(new Vector2f(2, 3), obb.getCenter());
}
/*
* Purpose: Test update of orientation, center vector as input
* Input: update orientation = 2, center vector(4, 4)
* Expected:
* orientation : 1 -> 2
* center : (4, 4)
*/
@Test
public void OriCenterVectorUpdateTest() {
OBB obb = new OBB();
obb.update(2, new Vector2f(4, 4));
assertTrue(2 == obb.getOrientation());
assertEquals(new Vector2f(4, 4), obb.getCenter());
}
/*
* Purpose: Test update of orientation, center as input
* Input: update orientation = 2, center x = 4, y = 4
* Expected:
* orientation : 1 -> 2
* center : (4, 4)
*/
@Test
public void OriCenterUpdateTest() {
OBB obb = new OBB();
obb.update(2, 4, 4);
assertTrue(2 == obb.getOrientation());
assertEquals(new Vector2f(4, 4), obb.getCenter());
}
/*
* Purpose: Test rotateAround of center vector as input
* Input: rotateAround position vector(4, 4) newOrientation = 2
* Expected:
* orientation : 2
* center : (7.9763327, 2.5205483)
*/
@Test
public void RotateAroundTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
float x = obb.center.x;
float y = obb.center.y;
obb.rotateAround(new Vector2f(4, 4), 2);
assertTrue(2 == obb.getOrientation());
x -= 4;
y -= 4;
float x2 = (float)(x * cos(2) - y * sin(2));
float y2 = (float)(x * sin(2) + y * cos(2));
x2 += 4;
y2 += 4;
assertEquals(new Vector2f(x2, y2), obb.getCenter());
}
/*
* Purpose: Test rotateTo of new Orientation as input
* Input: rotateTo newOrientation = 2
* Expected:
* orientation : 2
*/
@Test
public void RotateToTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.rotateTo(2);
assertTrue(2 == obb.getOrientation());
}
/*
* Purpose: Test rotate of adjustBy as input
* Input: rotate adjustBy = 2, orientation += adjustBy
* Expected:
* orientation : 3
*/
@Test
public void rotateTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.rotate(2);
assertTrue(3 == obb.getOrientation());
}
/*
* Purpose: Test translate of move position x, y as input
* Input: translate move x = 2, y = 2 center x += move x, center y += move y
* Expected:
* center = (3, 3)
*/
@Test
public void TranslateVectorTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.translate(new Vector2f(2, 2));
assertEquals(new Vector2f(1+2, 1+2), obb.getCenter());
}
/*
* Purpose: Test translate of move position vector as input
* Input: translate move vector (2, 2) center (x+2, y+2)
* Expected:
* center = (3, 3)
*/
@Test
public void TranslateTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.translate(2, 2);
assertEquals(new Vector2f(1+2, 1+2), obb.getCenter());
}
/*
* Purpose: Test setLocation of center position as input
* Input: setLocation new center x, new center y
* Expected:
* center = (3, 3)
*/
@Test
public void SetLocationTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.setLocation(3, 3);
assertEquals(new Vector2f(3, 3), obb.getCenter());
}
/*
* Purpose: Test setLocation of center position vector as input
* Input: setLocation vector(new center x, new center y)
* Expected:
* center = (3, 3)
*/
@Test
public void SetLocationVectorTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.setLocation(new Vector2f(3, 3));
assertEquals(new Vector2f(3, 3), obb.getCenter());
}
/*
* Purpose: Test setBound of new width, height as input
* Input: setBound width = 4, height = 5
* Expected:
* width = 4
* height = 5
*/
@Test
public void SetBoundTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
obb.setBounds(4, 5);
assertTrue(4 == obb.getWidth());
assertTrue(5 == obb.getHeight());
}
/*
* Purpose: Test contains of inner point as input
* Input: contains point(0, 0) which in OBB
* Expected:
* return true
*/
@Test
public void InnerPointContainsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
assertEquals(true, obb.contains(0, 0));
}
/*
* Purpose: Test contains of external point as input
* Input: contains point(6, 6) which out of OBB
* Expected:
* return false
*/
@Test
public void ExternPointContainsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
assertEquals(false, obb.contains(6, 6));
}
/*
* Purpose: Test contains of inner vector point as input
* Input: contains point(0, 0) which in OBB
* Expected:
* return true
*/
@Test
public void InnerVectorContainsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
assertEquals(true, obb.contains(new Vector2f(0, 0)));
}
/*
* Purpose: Test contains of external vector point as input
* Input: contains point(6, 6) which out of OBB
* Expected:
* return false
*/
@Test
public void ExternVectorContainsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
assertEquals(false, obb.contains(new Vector2f(6, 6)));
}
/*
* Purpose: Test intersects of intersect rectangle as input
* Input: intersects intersect rectangle
* Expected:
* return true
*/
@Test
public void InnerRectangleIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
Rectangle inter_r = new Rectangle(1, 1, 3, 4);
Rectangle extern_r = new Rectangle(10, 10, 3, 4);
assertEquals(true, obb.intersects(inter_r));
assertEquals(false, obb.intersects(extern_r));
}
/*
* Purpose: Test intersects of extern rectangle as input
* Input: intersects extern rectangle
* Expected:
* return false
*/
@Test
public void ExternRectangleIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
Rectangle extern_r = new Rectangle(10, 10, 3, 4);
assertEquals(false, obb.intersects(extern_r));
}
/*
* Purpose: Test expensiveIntersects of inner rectangle as input
* Input: expensiveIntersects intersect rectangle
* Expected:
* return true
*/
@Test
public void InnerRectangleExpensiveIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
Rectangle inner_r = new Rectangle(1, 1, 2, 2);
Rectangle extern_r = new Rectangle(10, 10, 3, 4);
assertEquals(true, obb.expensiveIntersects(inner_r));
assertEquals(false, obb.expensiveIntersects(extern_r));
}
/*
* Purpose: Test expensiveIntersects of extern rectangle as input
* Input: expensiveIntersects extern rectangle
* Expected:
* return false
*/
@Test
public void ExternRectangleExpensiveIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
Rectangle extern_r = new Rectangle(10, 10, 3, 4);
assertEquals(false, obb.expensiveIntersects(extern_r));
}
/*
* Purpose: Test intersects of inter obb as input
* Input: intersects inter obb
* Expected:
* return true
*/
@Test
public void InnerOBBIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
OBB inter_obb = new OBB(1, 2, 2, 3, 4);
assertEquals(true, obb.intersects(inter_obb));
}
/*
* Purpose: Test intersects of extern obb as input
* Input: intersects extern obb
* Expected:
* return false
*/
@Test
public void ExternOBBIntersectsTest() {
OBB obb = new OBB(1, 1, 1, 3, 4);
OBB extern_obb = new OBB(5, 5, 2, 3, 3);
assertEquals(false, obb.intersects(extern_obb));
}
}
| 14,354 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fOperationTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fOperationTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fOperationTest {
/*
* Purpose: To test round(). x = Math.round(x), y = Math.round(y)
* Input: Vector2f(2.6f, 3.2f), vector.round()
* Expected: vector.x = 3, vector.y = 3
*/
@Test
public void RoundTest() {
Vector2f vector = new Vector2f(2.6f, 3.2f);
vector.round();
assertTrue(vector.x == 3);
assertTrue(vector.y == 3);
}
/*
* Purpose: To test subtract(Vector2f v), it returns Vector2f(this.x-v.x, this.y - v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 2, dest.y = 2
*/
@Test
public void SubtractTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.subtract(v);
assertTrue(dest.x == 2);
assertTrue(dest.y == 2);
}
/*
* Purpose: To test addition(Vector2f v), it returns Vector2f(this.x+v.x, this.y + v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 8, dest.y = 8
*/
@Test
public void AdditionTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.addition(v);
assertTrue(dest.x == 8);
assertTrue(dest.y == 8);
}
/*
* Purpose: To test mult(Vector2f v), it returns Vector2f(this.x*v.x, this.y*v.y)
* Input: vector(5,5), v = (3,3)
* Expected: dest.x = 15, dest.y = 15
*/
@Test
public void MultiplyVectorTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f v = new Vector2f(3, 3);
Vector2f dest = new Vector2f();
dest = vector.mult(v);
assertTrue(dest.x == 15);
assertTrue(dest.y == 15);
}
/*
* Purpose: To test mult(float scalar), it returns Vector2f(this.x*scalar, this.y*scalar)
* Input: vector(5,5), scalar = 3
* Expected: dest.x = 15, dest.y = 15
*/
@Test
public void MultiplyFloatTest() {
Vector2f vector = new Vector2f(5, 5);
Vector2f dest = new Vector2f();
dest = vector.mult(3);
assertTrue(dest.x == 15);
assertTrue(dest.y == 15);
}
/*
* Purpose: To test div(Vector2f v), it returns Vector2f(this.x/v.x, this.y/v.y)
* Input: vector(10, 10), v(2, 5)
* Expected: dest.x = 5, dest.y = 2
*/
@Test
public void DivideVectorTest() {
Vector2f vector = new Vector2f(10, 10);
Vector2f v = new Vector2f(2, 5);
Vector2f dest = new Vector2f();
dest = vector.div(v);
assertTrue(dest.x == 5);
assertTrue(dest.y == 2);
}
/*
* Purpose: To test div(float v), it returns Vector2f(this.x/scalar, this.y/scalar)
* Input: vector(10, 10), scalar = 5
* Expected: dest.x = 2, dest.y = 2
*/
@Test
public void DivideFloatTest() {
Vector2f vector = new Vector2f(10, 10);
Vector2f dest = new Vector2f();
dest = vector.div(5);
assertTrue(dest.x == 2);
assertTrue(dest.y == 2);
}
}
| 3,324 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fProductTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fProductTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fProductTest {
/*
* Purpose: test Vector2fCrossProduct()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: -2
*/
@Test
public void CrossProductTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fCrossProduct(vectorOne, vectorTwo);
float expected = -2;
assertTrue(actual == expected);
}
/*
* Purpose: test Vector2fDotProduct()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: 26
*/
@Test
public void DotProductTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fDotProduct(vectorOne, vectorTwo);
float expected = 26;
assertTrue(actual == expected);
}
/*
* Purpose: test Vector2fDet()
* check the return value
*
* Input: v1(2,4), v2(3,5), vector(v1, v2)
* Expected: -2
*/
@Test
public void DetTest() {
Vector2f vectorOne = new Vector2f(2,4);
Vector2f vectorTwo = new Vector2f(3,5);
Vector2f vector = new Vector2f();
float actual = vector.Vector2fDet(vectorOne, vectorTwo);
float expected = -2;
assertTrue(actual == expected);
}
/*
* Purpose: test AddTest()
* check the return value
*
* Input: a(2,4), b(3,5), dest(a, b, dest)
* Expected: dest.x = 5, dest.y = 9
*/
@Test
public void AddTest() {
Vector2f a = new Vector2f(2,4);
Vector2f b = new Vector2f(3,5);
Vector2f dest = new Vector2f();
dest.Vector2fAdd(a, b, dest);
assertTrue(dest.x == 5);
assertTrue(dest.y == 9);
}
/*
* Purpose: test AddScalarTest()
* check the return value
*
* Input: a(2,4), b(3,5), dest(a, b, dest)
* Expected: dest.x = 5, dest.y = 9
*/
@Test
public void AddScalarTest() {
Vector2f a = new Vector2f(2,4);
Vector2f dest = new Vector2f();
dest.Vector2fAdd(a, 5, dest);
assertTrue(dest.x == 7);
assertTrue(dest.y == 9);
}
/*
* Purpose: test Vector2fSubtract(a, b, dest)
* check the return value
*
* Input: a(2,4), b(1,1), dest.subtract(a, b, dest)
* Expected: dest.x = 1, dest.y = 3
*/
@Test
public void VetorSubTest() {
Vector2f a = new Vector2f(2,4);
Vector2f b = new Vector2f(1,1);
Vector2f dest = new Vector2f();
dest.Vector2fSubtract(a, b, dest);
assertTrue(dest.x == 1);
assertTrue(dest.y == 3);
}
/*
* Purpose: test Vector2fSubtract(a, scalar, dest)
* check the return value
*
* Input: a(8,6), Scalar = 2, subtract(a, 2, dest)
* Expected: dest.x = 6, dest.y = 4
*/
@Test
public void ScalarSubTest() {
Vector2f a = new Vector2f(8,6);
Vector2f dest = new Vector2f();
dest.Vector2fSubtract(a, 2, dest);
assertTrue(dest.x == 6);
assertTrue(dest.y == 4);
}
/*
* Purpose: test Vector2fMult(a,b, dest)
* check the return value
*
* Input: a(8,6), b(3,5), Vector2fMult(a, 2, dest)
* Expected: dest.x = 24, dest.y = 30
*/
@Test
public void VectorMulTest() {
Vector2f a = new Vector2f(8,6);
Vector2f b = new Vector2f(3,5);
Vector2f dest = new Vector2f();
dest.Vector2fMult(a, b, dest);
assertTrue(dest.x == 24);
assertTrue(dest.y == 30);
}
/*
* Purpose: test Vector2fMult(a,scalar, dest)
* check the return value
*
* Input: a(8,6), scalar = 3, Vector2fMult(a, 3, dest)
* Expected: dest.x = 24, dest.y = 30
*/
@Test
public void ScalarMulTest() {
Vector2f a = new Vector2f(8,6);
float scalar = 3;
Vector2f dest = new Vector2f();
dest.Vector2fMult(a, scalar, dest);
assertTrue(dest.x == 24);
assertTrue(dest.y == 18);
}
/*
* Purpose: test Vector2fDiv(a,b, dest)
* check the return value
*
* Input: a(8,6), b(2,3), Vector2fMult(a, b, dest)
* Expected: dest.x = 4, dest.y = 2
*/
@Test
public void VectorDivTest() {
Vector2f a = new Vector2f(8,6);
Vector2f b = new Vector2f(2,3);
Vector2f dest = new Vector2f();
dest.Vector2fDiv(a, b, dest);
assertTrue(dest.x == 4);
assertTrue(dest.y == 2);
}
/*
* Purpose: test Scalar2fDiv(a,scalar, dest)
* check the return value
*
* Input: a(8,6), scalar = 2, Vector2fMult(a, scalar, dest)
* Expected: dest.x = 4, dest.y = 3
*/
@Test
public void ScalarDivTest() {
Vector2f a = new Vector2f(8,6);
float scalar = 2;
Vector2f dest = new Vector2f();
dest.Vector2fDiv(a, 2, dest);
assertTrue(dest.x == 4);
assertTrue(dest.y == 3);
}
}
| 5,667 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TriangleTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/TriangleTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.badlogic.gdx.math.Rectangle;
import seventh.client.gfx.ReticleCursor;
import seventh.math.Line;
import seventh.math.Triangle;
import seventh.math.Vector2f;
public class TriangleTest {
Triangle tri;
/*
* Purpose: Test Triangle Construcor Test. Input:
* Triangle((1,2),(4,5),(10,11)) Expected: Triangle.a.x = 1 , Triangle.a.y =
* 2, Triangle.b.x = 4 , Triangle.b.y = 5, Triagle.c.x = 10 , Triangle.c.y =
* 11
*/
@Test
public void ConstructTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
assertTrue(tri.a.x == 1);
assertTrue(tri.a.y == 2);
assertTrue(tri.b.x == 4);
assertTrue(tri.b.y == 5);
assertTrue(tri.c.x == 10);
assertTrue(tri.c.y == 11);
}
/*
* Purpose: Test Triangle add all x + input.x , y + input.y. Input:
* Vector2f(1,1) Expected: Triangle.a.x = 2 , Triangle.a.y = 3, Triangle.b.x
* = 5 , Triangle.b.y = 6, Triangle.c.x = 11 , Triangle.c.y = 12
*
*/
@Test
public void TranslateAddTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
Vector2f tmp = new Vector2f(1, 1);
tri.translate(tmp);
assertTrue(tri.a.x == 2);
assertTrue(tri.a.y == 3);
assertTrue(tri.b.x == 5);
assertTrue(tri.b.y == 6);
assertTrue(tri.c.x == 11);
assertTrue(tri.c.y == 12);
}
/*
* Purpose: Test Triangle sub all x - input.x , y - input.y. Input:
* Vector2f(-1,-1) Expected: Triangle.a.x = 0 , Triangle.a.y = 1,
* Triangle.b.x = 3 , Triangle.b.y = 4, Triangle.c.x = 9 , Triangle.c.y = 10
*
*/
@Test
public void TranslatesubTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
Vector2f tmp = new Vector2f(-1, -1);
tri.translate(tmp);
assertTrue(tri.a.x == 0);
assertTrue(tri.a.y == 1);
assertTrue(tri.b.x == 3);
assertTrue(tri.b.y == 4);
assertTrue(tri.c.x == 9);
assertTrue(tri.c.y == 10);
}
/*
* Purpose: Test Triangle add all x + inputFloatValue , y + inputFloatValue
* Input: Float 11 Expected: Triangle.a.x = 2 , Triangle.a.y = 3,
* Triangle.b.x = 5 , Triangle.b.y = 6, Triangle.c.x = 11 , Triangle.c.y =
* 12
*
*/
@Test
public void TranslateFloatAddTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
float tmp = 1;
tri.translate(tmp);
assertTrue(tri.a.x == 2);
assertTrue(tri.a.y == 3);
assertTrue(tri.b.x == 5);
assertTrue(tri.b.y == 6);
assertTrue(tri.c.x == 11);
assertTrue(tri.c.y == 12);
}
/*
* Purpose: Test Triangle sub all x - inputFloatValue , y - inputFloatValue.
* Input: -1
* Expected: Triangle.a.x = 0 , Triangle.a.y = 1, Triangle.b.x = 3, Triangle.b.y = 4, Triangle.c.x = 9 , Triangle.c.y = 10
*
*/
@Test
public void TranslateFloatsubTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
// Construct Float value
float tmp = -1;
tri.translate(tmp);
assertTrue(tri.a.x == 0);
assertTrue(tri.a.y == 1);
assertTrue(tri.b.x == 3);
assertTrue(tri.b.y == 4);
assertTrue(tri.c.x == 9);
assertTrue(tri.c.y == 10);
}
/*
* Purpose: Test Translates the link Triangle to a new location.
* Input: Triangle, vector2f, dest Expected: TransFormed Dest -> Triangle
*/
@Test
public void TriangleTranslateFloatTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
Triangle dest = new Triangle(new Vector2f(3, 3), new Vector2f(7, 3), new Vector2f(5, 10));
float value =1;
tri.TriangleTranslate(tri, value, dest);
assertTrue(dest.a.x == 2);
assertTrue(dest.a.y == 3);
assertTrue(dest.b.x == 5);
assertTrue(dest.b.y == 6);
assertTrue(dest.c.x == 11);
assertTrue(dest.c.y == 12);
}
/*
* Purpose: Test Translates the link Triangle to a new location.
* Input:Triangle, vector2f, dest
* Expected: TransFormed Dest's Value is same with inputTriangle
*/
@Test
public void TriangleTranslateVector2fTest() {
tri = new Triangle(new Vector2f(1, 2),new Vector2f(4, 5),new Vector2f(10, 11));
Triangle dest = new Triangle(new Vector2f(3, 3), new Vector2f(7, 3), new Vector2f(5, 10));
dest.TriangleTranslate(tri, new Vector2f(1, 1), dest);
assertTrue(dest.a.x == 2);
assertTrue(dest.a.y == 3);
assertTrue(dest.b.x == 5);
assertTrue(dest.b.y == 6);
assertTrue(dest.c.x == 11);
assertTrue(dest.c.y == 12);
}
/*
* Purpose: Test to determine if the supplied Point intersects with the supplied Triangle
* Input: 3 3, triangle(2,2 ,2 15, 10,2)
* Expected: true
*/
@Test
public void pointIntersectsTriangleTrueTest() {
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
Vector2f point= new Vector2f(3,3);
assertTrue(true == tri.pointIntersectsTriangle(point, tri));
}
/*
* Purpose: Test to determine if the supplied Point intersects with the supplied Triangle}
* Input: -1 -1, triangle(2,2 ,2 15, 10,2)
* Expected: flase
*/
@Test
public void pointIntersectsTriangleFalseTest() {
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
Vector2f point= new Vector2f(-1,-1);
//Out Of triangle
assertTrue(false == tri.pointIntersectsTriangle(point, tri));
}
/*
* PurPose: Test Determine if the supplied link Line intersects with the supplied link Triangle.
* Input: Line((1,1),(3,3)),Line((3,3),(1,2)),Line((3,3),(2,1)),Line((3,3),(10,10)),Line((3,3),(10,1)),Line((3,3),(2,15))
* Expected: true
*
*/
@Test
public void lineIntersectsTriangleLineTrueTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
Line line1 = new Line(new Vector2f(3,3),new Vector2f(1,2));
Line line2 = new Line(new Vector2f(3,3),new Vector2f(2,1));
Line line3 = new Line(new Vector2f(3,3),new Vector2f(10,10));
assertTrue(true == tri.lineIntersectsTriangle(line1, tri));
assertTrue(true == tri.lineIntersectsTriangle(line2, tri));
assertTrue(true == tri.lineIntersectsTriangle(line3, tri));
}
/*
* PurPose: Test Determine if the supplied link Line intersects with the supplied link Triangle.
* Input: Line((0,0),(1,1))
* Expected: false
*
*/
@Test
public void lineIntersectsTriangleLineFalseTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
Line line1 = new Line(new Vector2f(0,0),new Vector2f(1,1));
assertTrue(false == tri.lineIntersectsTriangle(line1, tri));
}
/*
* PurPose: Test Determine if the supplied link Line intersects with the supplied link Triangle
* Input: Point((1,1) and (3,3)),Point((3,3) and (1,2)),Point((3,3) and(2,1)),Point((3,3) and (10,10)),Point ((3,3)and (10,1)),point((3,3) and (2,15))
* Expected: true
*
*/
@Test
public void lineIntersectsTrianglePointTrueTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
assertTrue(true == tri.lineIntersectsTriangle(new Vector2f(3,3),new Vector2f(1,2), tri));
assertTrue(true == tri.lineIntersectsTriangle(new Vector2f(3,3),new Vector2f(2,1), tri));
assertTrue(true == tri.lineIntersectsTriangle(new Vector2f(3,3),new Vector2f(10,10), tri));
}
/*
* PurPose: Test Determine if the supplied link Line intersects with the supplied link Triangle
* Input: Point((0,0) and (1,1))
* Expected: false
*
*/
@Test
public void lineIntersectsTrianglePointFalseTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
assertTrue(false == tri.lineIntersectsTriangle(new Vector2f(1,1),new Vector2f(0,0), tri));
}
/*
* PurPose: Test Determine if the supplied link Rectangle and link Triangle intersect. -> Not Intersect
* Input: Rectangle((2,2),8,3), Triangle((2,2),(2,15),(10,2)) //inside
* Input: Rectangle((0,2),0,3), Triangle((2,2),(2,15),(10,2)) //width = 0
* Input: Rectangle((1,0),3,0), Triangle((2,2),(2,15),(10,2)) //height =0
* Input: Rectangle((0,0),20,20), Triangle((2,2),(2,15),(10,2)) //outside
* Expected: false
*
*/
@Test //Inside
public void rectangleIntersectsTriangleFalseTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(2, 2),(int)8,(int)13);
assertTrue(false == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //width =0
public void rectangleIntersectsTriangleFalseHeighZeroTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(0, 2),(int)0,(int)13);
assertTrue(false == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //height =0
public void rectangleIntersectsTriangleFalseWidthZeroTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(1, 0),(int)3,(int)0);
assertTrue(false == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //OutSide
public void rectangleIntersectsTriangleFalseOutsideUnderTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(2, 0),(int)8,(int)0);
assertTrue(false == tri.rectangleIntersectsTriangle(rectangle,tri));
}
/*
* PurPose: Test Determine if the supplied link Rectangle and link Triangle intersect. -> Intersect
* Input: Rectangle((1,1),10,6), Triangle((2,2),(2,15),(10,2)) - All direction Line intersect
* Input: Rectangle((3,1),2,3), Triangle((2,2),(2,15),(10,2)) -Under Line intersect
* Input: Rectangle((1,3),4,4), Triangle((2,2),(2,15),(10,2)) -Height Line intersect
* Input: Rectangle((3,3),15,15), Triangle((2,2),(2,15),(10,2)) -Hypotenuse Line intersect
* Input: Rectangle((1,3),15,0), Triangle((2,2),(2,15),(10,2)) -Rectangle Height = 0
* Input: Rectangle((3,1),0,15), Triangle((2,2),(2,15),(10,2)) -Rectangle width = 0
* Input: Rectangle((-5,-5),50,50), Triangle((2,2),(2,15),(10,2)) - Triangle Located In Rectangle
* Expected: True
*
*/
@Test //All Direction Intersect
public void rectangleIntersectsTriangleTrueAllLineTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(1, 1),(int)10,(int)6);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Under Line Intersect
public void rectangleIntersectsTriangleTrueUnderLineTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(3, 1),(int)2,(int)3);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Height Line Intersect
public void rectangleIntersectsTriangleTrueHeightLineTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(1, 3),6,4);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Hypotenuse Line InterSect
public void rectangleIntersectsTriangleTrueHypotenuseLineTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(3, 3),15,15);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Width Zero Rectangle InterSect
public void rectangleIntersectsTriangleTrueWidthZeroTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(1, 3),15,0);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Height Zero Rectangle InterSect
public void rectangleIntersectsTriangleTrueHeigthZeroTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(3, 1),0,15);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
@Test //Height Zero Rectangle InterSect
public void rectangleIntersectsTriangleTrueRectangleInsideTest(){
tri = new Triangle(new Vector2f(2, 2), new Vector2f(2, 15), new Vector2f(10, 2));
seventh.math.Rectangle rectangle = new seventh.math.Rectangle(new Vector2f(-5, -5),50,50);
assertTrue(true == tri.rectangleIntersectsTriangle(rectangle,tri));
}
}
| 14,545 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector2fToStringTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/Vector2fToStringTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import seventh.math.Vector2f;
public class Vector2fToStringTest {
/*
* Purpose: test toString()
*
* Input: vector(2.0f, 3.0f), vector.toString()
* Expected: {"x": 2.0, "y": 3.0}
*/
@Test
public void toStringTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
String actual = vector.toString();
String expected = "{ \"x\": 2.0, \"y\": 3.0}";
assertEquals(expected, actual);
}
/*
* Purpose: test createClone()
* it returns clone of Vector2f
* Input: vector(2.0f, 3.0f), vector.toString()
* Expected: {"x": 2.0, "y": 3.0}
*/
@Test
public void CloneTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
Vector2f clone = vector.createClone();
assertEquals(vector, clone);
}
/*
* Purpose: test toArray()
* it returns float array {x, y}
* Input: vector(2.0f, 3.0f), vector.toArray();
* Expected: float{2.0f, 3.0f}
*/
@Test
public void toArrayTest() {
Vector2f vector = new Vector2f(2.0f,3.0f);
float[] expected = {2.0f, 3.0f};
float[] actual = vector.toArray();
assertTrue(expected[0] == actual[0]);
assertTrue(expected[1] == actual[1]);
}
}
| 1,457 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RectangleTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/RectangleTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.Circle;
import seventh.math.OBB;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
public class RectangleTest {
/*
* Purpose: rectangleA intersect rectangleB
* Input:
* rectangleA => (0,0) width 4 height 4
* rectangleB => (3,3) width 6 height 5
* Expected:
* the rectangleA intersect rectangleB
*/
@Test
public void testRectangleIntersectRectangle() {
final boolean intersect = true;
final boolean noIntersect = false;
Rectangle rectangleA = new Rectangle(0,0,4,4);
Rectangle rectangleB = new Rectangle(3,3,6,5);
assertEquals(intersect,rectangleA.intersects(rectangleB));
assertNotEquals(noIntersect,rectangleA.intersects(rectangleB));
}
/*
* Purpose: rectangleA don't intersect rectangleB
* Input:
* rectangleA => (0,0) width 1 height 1
* rectangleB => (10,10) width 5 height 5
* Expected:
* the rectangleA don't intersect rectangleB
*/
@Test
public void testRectangleNoIntersectRectangle() {
final boolean intersect = true;
final boolean noIntersect = false;
Rectangle rectangleA = new Rectangle(0,0,1,1);
Rectangle rectangleB = new Rectangle(10,10,5,5);
assertEquals(noIntersect,rectangleA.intersects(rectangleB));
assertNotEquals(intersect,rectangleA.intersects(rectangleB));
}
/*
* Purpose: rectangleA contains rectangleB
* Input:
* rectangleA => (0,0) width 10 height 10
* rectangleB => (0,0) width 2 height 2
* Expected:
* the rectangleA contains rectangleB
*/
@Test
public void testRectangleContainRectangle() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangleA = new Rectangle(0,0,10,10);
Rectangle rectangleB = new Rectangle(0,0,2,2);
assertEquals(contain,rectangleA.contains(rectangleB));
assertNotEquals(noContain,rectangleA.contains(rectangleB));
}
/*
* Purpose: rectangleA is same rectangleB
* Input:
* rectangleA => (0,0) width 10 height 10
* rectangleB => (0,0) width 10 height 10
* Expected:
* the rectangleA contains same rectangle rectangleB
*/
@Test
public void testRectangleContainSameRectangle() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangleA = new Rectangle(0,0,10,10);
Rectangle rectangleB = new Rectangle(0,0,10,10);
assertEquals(contain,rectangleA.contains(rectangleB));
assertNotEquals(noContain,rectangleA.contains(rectangleB));
}
/*
* Purpose: rectangleA don't contain rectangleB
* Input:
* rectangleA => (0,0) width 2 height 2
* rectangleB => (10,10) width 2 height 2
* Expected:
* the rectangleA don't contain rectangleB
*/
@Test
public void testRectangleNoContainRectangle() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangleA = new Rectangle(0,0,2,2);
Rectangle rectangleB = new Rectangle(10,10,2,2);
assertEquals(noContain,rectangleA.contains(rectangleB));
assertNotEquals(contain,rectangleA.contains(rectangleB));
}
/*
* Purpose: rectangle contain point
* Input:
* rectangleA => (0,0) width 4 height 4
* point => (1,1)
* Expected:
* the rectangleA contains the point
*/
@Test
public void testRectangleContainPoint() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangle = new Rectangle(0,0,4,4);
assertEquals(contain,rectangle.contains(1,1));
assertNotEquals(noContain,rectangle.contains(1,1));
assertEquals(contain,rectangle.contains(new Vector2f(1,1)));
assertNotEquals(noContain,rectangle.contains(new Vector2f(1,1)));
}
/*
* Purpose: rectangle don't contain point
* Input:
* rectangleA => (0,0) width 4 height 4
* point => (10,10)
* Expected:
* the rectangleA contains the point
*/
@Test
public void testRectangleNoContainPoint() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangle = new Rectangle(0,0,4,4);
assertEquals(noContain,rectangle.contains(10,10));
assertNotEquals(contain,rectangle.contains(10,10));
assertEquals(noContain,rectangle.contains(new Vector2f(10,10)));
assertNotEquals(contain,rectangle.contains(new Vector2f(10,10)));
}
/*
* Purpose: make rectangle that is intersection of two rectangle
* Input:
* rectangleA => (0,0) width 10 height 10
* rectangleB => (5,5) width 10 height 10
* Expected:
* the rectangleA contains intersectedRectangle
* the rectangleB contains intersectedRectangle
* intersectedRectangle => (5,5) width 10 height 10
*/
@Test
public void testIntersectionRectangle() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangleA = new Rectangle(0,0,10,10);
Rectangle rectangleB = new Rectangle(5,5,10,10);
Rectangle expectedRectangle = new Rectangle(5,5,5,5);
Rectangle intersectedRectangle = rectangleA.intersection(rectangleB);
assertEquals(contain,rectangleA.contains(intersectedRectangle));
assertEquals(contain,rectangleB.contains(intersectedRectangle));
assertTrue(expectedRectangle.equals(intersectedRectangle));
}
/*
* Purpose: there is no rectangle that is intersection of two rectangle
* Input:
* rectangleA => (0,0) width 10 height 10
* rectangleB => (20,20) width 10 height 10
* Expected:
* the rectangleA contains intersectedRectangle
* the rectangleB contains intersectedRectangle
* intersectedRectangle => (5,5) width 10 height 10
*/
@Test
public void testNoIntersectionRectangle() {
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangleA = new Rectangle(0,0,10,10);
Rectangle rectangleB = new Rectangle(20,20,10,10);
Rectangle intersectedRectangle = rectangleA.intersection(rectangleB);
assertEquals(noContain,rectangleA.contains(intersectedRectangle));
assertEquals(noContain,rectangleB.contains(intersectedRectangle));
}
/*
* Purpose: rectangle contain OBB
* Input:
* rectangle => (0,0) width 20 height 20
* obb => center (5,5) width 10 height 10
* Expected:
* the rectangle contains obb
*/
@Test
public void testContainOBB(){
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangle = new Rectangle(0,0,20,20);
OBB oob = new OBB(0,5,5,10,10);
assertEquals(contain,rectangle.contains(oob));
assertNotEquals(noContain,rectangle.contains(oob));
}
/*
* Purpose: rectangle don't contain OBB
* Input:
* rectangle => (0,0) width 20 height 20
* obb => center (30,30) width 5 height 5
* Expected:
* the rectangle don't contains obb
*/
@Test
public void testContainNoOBB(){
final boolean contain = true;
final boolean noContain = false;
Rectangle rectangle = new Rectangle(0,0,20,20);
OBB oob = new OBB(0,30,30,5,5);
assertEquals(noContain,rectangle.contains(oob));
assertNotEquals(contain,rectangle.contains(oob));
}
/*
* Purpose: construct same rectangle each constructor
* Input:
* A => (0,0) width 0 height 0
* B => vector2f(0,0) width 0 height 0
* C => width 0 height 0
* D => nothing
* Expected:
* all rectangle are same (0,0) width 0 height 0
*/
@Test
public void testConstructRectangle(){
final boolean same = true;
Rectangle rectangleA = new Rectangle(0,0,0,0);
Rectangle rectangleB = new Rectangle(new Vector2f(0,0),0,0);
Rectangle rectangleC = new Rectangle(0,0);
Rectangle rectangleD = new Rectangle();
Rectangle rectangleE = new Rectangle(rectangleA);
assertEquals(same,rectangleA.equals(rectangleB));
assertEquals(same,rectangleA.equals(rectangleC));
assertEquals(same,rectangleA.equals(rectangleD));
assertEquals(same,rectangleA.equals(rectangleE));
assertEquals(same,rectangleB.equals(rectangleA));
assertEquals(same,rectangleB.equals(rectangleC));
assertEquals(same,rectangleB.equals(rectangleD));
assertEquals(same,rectangleB.equals(rectangleE));
assertEquals(same,rectangleC.equals(rectangleA));
assertEquals(same,rectangleC.equals(rectangleB));
assertEquals(same,rectangleC.equals(rectangleD));
assertEquals(same,rectangleC.equals(rectangleE));
assertEquals(same,rectangleD.equals(rectangleA));
assertEquals(same,rectangleD.equals(rectangleB));
assertEquals(same,rectangleD.equals(rectangleC));
assertEquals(same,rectangleD.equals(rectangleE));
assertEquals(same,rectangleE.equals(rectangleA));
assertEquals(same,rectangleE.equals(rectangleB));
assertEquals(same,rectangleE.equals(rectangleC));
assertEquals(same,rectangleE.equals(rectangleD));
assertEquals(0,rectangleA.getX());
assertEquals(0,rectangleA.getY());
assertEquals(0,rectangleA.getWidth());
assertEquals(0,rectangleA.getHeight());
}
/*
* Purpose: rectangle add x,y
* Input:
* all rectangles => (1,1) width 2 height 2
* add (2,2)
* Expected:
* x,y of rectangles are (3,3)
*/
@Test
public void testRectangleAdd(){
Rectangle rectangleA = new Rectangle(1,1,2,2);
Rectangle rectangleB = new Rectangle(1,1,2,2);
Rectangle rectangleC = new Rectangle(1,1,2,2);
rectangleA.add(2, 2);
assertEquals(3,rectangleA.getX());
assertEquals(3,rectangleA.getY());
assertEquals(2,rectangleA.getWidth());
assertEquals(2,rectangleA.getHeight());
rectangleB.add(new Vector2f(2,2));
assertEquals(3,rectangleB.getX());
assertEquals(3,rectangleB.getY());
assertEquals(2,rectangleB.getWidth());
assertEquals(2,rectangleB.getHeight());
rectangleC.add(new Rectangle(2,2,0,0));
assertEquals(3,rectangleC.getX());
assertEquals(3,rectangleC.getY());
assertEquals(2,rectangleC.getWidth());
assertEquals(2,rectangleC.getHeight());
}
/*
* Purpose: make (0,0,0,0)rectangle to (1,2,3,4)rectangle
* Input:
* rectangle => (x,y) (0,0) width 0 height 0
* setBounds : (x,y) (1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (1,2) width 3 height 4
*/
@Test
public void testSetBoundintValue(){
final int expectedX = 1;
final int expectedY = 2;
final int expectedWidth = 3;
final int expectedheight = 4;
Rectangle rectangle = new Rectangle(0,0,0,0);
rectangle.setBounds(1,2,3,4);
assertEquals(expectedX,rectangle.getX());
assertEquals(expectedY,rectangle.getY());
assertEquals(expectedWidth,rectangle.getWidth());
assertEquals(expectedheight,rectangle.getHeight());
}
/*
* Purpose: make (0,0,0,0)rectangle to (1,2,3,4)rectangle
* Input:
* rectangle => (x,y) (0,0) width 0 height 0
* set : Vector2f(1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (1,2) width 3 height 4
*/
@Test
public void testSetVector2f(){
final int expectedX = 1;
final int expectedY = 2;
final int expectedWidth = 3;
final int expectedheight = 4;
Rectangle rectangle = new Rectangle(0,0,0,0);
rectangle.set(new Vector2f(1,2),3,4);
assertEquals(expectedX,rectangle.getX());
assertEquals(expectedY,rectangle.getY());
assertEquals(expectedWidth,rectangle.getWidth());
assertEquals(expectedheight,rectangle.getHeight());
}
/*
* Purpose: make (0,0,0,0)rectangle to (1,2,3,4)rectangle
* Input:
* rectangle => (x,y) (0,0) width 0 height 0
* setBounds : Vector2f(1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (1,2) width 3 height 4
*/
@Test
public void testSetBoundVector2f(){
final int expectedX = 1;
final int expectedY = 2;
final int expectedWidth = 3;
final int expectedheight = 4;
Rectangle rectangle = new Rectangle(0,0,0,0);
rectangle.setBounds(new Vector2f(1,2),3,4);
assertEquals(expectedX,rectangle.getX());
assertEquals(expectedY,rectangle.getY());
assertEquals(expectedWidth,rectangle.getWidth());
assertEquals(expectedheight,rectangle.getHeight());
}
/*
* Purpose: make (0,0,0,0)rectangle to (1,2,3,4)rectangle
* Input:
* rectangle => (x,y) (0,0) width 0 height 0
* setBounds : Rectangle -> (x,y) (1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (1,2) width 3 height 4
*/
@Test
public void testSetBoundRectangle(){
final int expectedX = 1;
final int expectedY = 2;
final int expectedWidth = 3;
final int expectedheight = 4;
Rectangle rectangle = new Rectangle(0,0,0,0);
rectangle.setBounds(new Rectangle(1,2,3,4));
assertEquals(expectedX,rectangle.getX());
assertEquals(expectedY,rectangle.getY());
assertEquals(expectedWidth,rectangle.getWidth());
assertEquals(expectedheight,rectangle.getHeight());
}
/*
* Purpose: make (0,0,0,0)rectangle to (1,2,3,4)rectangle
* Input:
* rectangle => (x,y) (0,0) width 0 height 0
* set : Rectangle -> (x,y) (1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (1,2) width 3 height 4
*/
@Test
public void testSetRectangle(){
final int expectedX = 1;
final int expectedY = 2;
final int expectedWidth = 3;
final int expectedheight = 4;
Rectangle rectangle = new Rectangle(0,0,0,0);
rectangle.set(new Rectangle(1,2,3,4));
assertEquals(expectedX,rectangle.getX());
assertEquals(expectedY,rectangle.getY());
assertEquals(expectedWidth,rectangle.getWidth());
assertEquals(expectedheight,rectangle.getHeight());
}
/*
* Purpose: make (1,2,3,4)rectangle to (0,0,0,0)rectangle
* Input:
* rectangle => (x,y) (1,2) width 3 height 4
* Expected:
* rectangle => (x,y) (0,0) width 0 height 0
*/
@Test
public void testZeroOut(){
final int expected = 0;
Rectangle rectangle = new Rectangle(1,2,3,4);
rectangle.zeroOut();
assertEquals(expected,rectangle.getX());
assertEquals(expected,rectangle.getY());
assertEquals(expected,rectangle.getWidth());
assertEquals(expected,rectangle.getHeight());
}
}
| 15,748 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FastMathTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/FastMathTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.FastMath;
public class FastMathTest {
/*
* Purpose: test intMax in FastMath class
* Input: int, int
* Expected: Bigger one
* example (2147483647, 0) = 2147483647
*
*/
@Test
public void intMaxTest() {
assertEquals(FastMath.max(2147483647, 0),2147483647);
assertEquals(FastMath.max(0, -2147483648),0);
assertEquals(FastMath.max(-2147483648, 2147483647),2147483647);
}
/*
* Purpose: test doubleMax in FastMath class
* Input: double, double
* Expected: bigger one
* example (2147483647, 0) = 2147483647
*/
@Test
public void doubleMaxTest()
{
assertTrue(FastMath.max(Double.MAX_VALUE, 0)== Double.MAX_VALUE);
assertTrue(FastMath.max(0, Double.MIN_VALUE) == Double.MIN_VALUE); //it must be false but true
assertTrue(FastMath.max(Double.MAX_VALUE, Double.MIN_VALUE) == Double.MAX_VALUE);
}
/*
* Purpose: test floatMax in FastMath class
* Input: float, float
* Expected: bigger one
* example FastMath.max(Float.MAX_VALUE, 0)= Float.MAX_VALUE;
*/
@Test
public void floatMaxTest()
{
assertTrue(FastMath.max(Float.MAX_VALUE, 0)== Float.MAX_VALUE);
assertTrue(FastMath.max(0,Float.MIN_VALUE)==Float.MIN_VALUE); // it must be false, but true
assertTrue(FastMath.max(Float.MAX_VALUE, Float.MIN_VALUE)== Float.MAX_VALUE);
}
/*
* Purpose: test doubleMax in FastMath class
* Input: long, long
* Expected: bigger one
* example (2147483647,Long.MAX_VALUE) = Long.MAX_VALUE
*/
@Test
public void longMaxTest()
{
assertEquals(FastMath.max(Long.MIN_VALUE,Long.MAX_VALUE), Long.MAX_VALUE);
assertEquals(FastMath.max(0,Long.MAX_VALUE), Long.MAX_VALUE);
assertEquals(FastMath.max(Long.MIN_VALUE,0), 0);
}
/*
* Purpose: test intMin in FastMath class
* Input: int, int
* Expected: smaller one
* example (-2147483648, 0) = -2147483648
*/
@Test
public void intMinTest()
{
assertEquals(FastMath.min(-2147483648, 0),-2147483648);
assertEquals(FastMath.min(-2147483648, 2147483647),-2147483648);
assertEquals(FastMath.min(2147483647, 0),0);
}
/*
* Purpose: test floatMin in FastMath class
* Input: float, float
* Expected: smaller one
* example (Float.MIN_VALUE, Float.MAX_VALUE) = Float.MIN_VALUE
*/
@Test
public void floatMinTest()
{
assertTrue(FastMath.min(Float.MIN_VALUE, Float.MAX_VALUE) == Float.MIN_VALUE);
assertTrue(FastMath.min(Float.MIN_VALUE, 0) == 0); //it must be false, but true
assertTrue(FastMath.min(0, Float.MAX_VALUE) == 0);
}
/*
* Purpose: test longMin in FastMath class
* Input: long,long
* Expected: smaller one
* example (Long.MAX_VALUE, Long.MIN_VALUE) = Long.MIN_VALUE
*/
@Test
public void longMinTest()
{
assertEquals(FastMath.min(Long.MAX_VALUE, Long.MIN_VALUE), Long.MIN_VALUE);
assertEquals(FastMath.min(Long.MIN_VALUE, 0), Long.MIN_VALUE);
assertEquals(FastMath.min(0, Long.MAX_VALUE), 0);
}
/*
* Purpose: test doubleMin in FastMath class
* Input: double, double
* Expected: smaller one
* example (Double.MAX_VALUE, Double.MIN_VALUE) = Double.MIN_VALUE
*/
@Test
public void doubleMinTest()
{
assertTrue(FastMath.min(Double.MAX_VALUE, Double.MIN_VALUE) == Double.MIN_VALUE);
assertTrue(FastMath.min(0, Double.MIN_VALUE) == 0); //it must be false, but true
assertTrue(FastMath.min(Double.MAX_VALUE, 0) == 0);
}
/*
* Purpose: test sin in FastMath class
* Input: float
* Expected: result = sin(float)
* example sin(PI/6) should be 0.5 but, it's a FastMath, so i gave 0.01 error range
* 0.49<sin(PI/6)<0.51
*/
@Test
public void sinTest()
{
assertTrue(FastMath.sin(FastMath.PI/6) > 0.49);
assertTrue(FastMath.sin(FastMath.PI/6) < 0.51);
assertTrue(FastMath.sin(0) >= 0);
assertTrue(FastMath.sin(0) < 0.01);
assertTrue(FastMath.sin(FastMath.PI/2)>0.9);
assertTrue(FastMath.sin(FastMath.PI/2)<=1);
}
/*
* Purpose: test cosin in FastMath class
* Input: float
* Expected: result = cosin(float)
* example cos(PI/3) should be 0.5 but, it's a FastMath, so i gave 0.01 error range
* 0.49<sin(PI/6)<0.51
*/
@Test
public void cosTest()
{
assertTrue(FastMath.cos(FastMath.PI/3) > 0.49);
assertTrue(FastMath.cos(FastMath.PI/3) < 0.51);
assertTrue(FastMath.cos(0) <= 1);
assertTrue(FastMath.cos(0) > 0.9);
assertTrue(FastMath.cos(FastMath.PI/2) > -0.01);
assertTrue(FastMath.cos(FastMath.PI/2) < 0.01);
}
}
| 5,297 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CircleTest.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/test/math/CircleTest.java | package test.math;
import static org.junit.Assert.*;
import org.junit.Test;
import seventh.math.Circle;
import seventh.math.Line;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
public class CircleTest {
/*
* Purpose: a point is in Circle
* Input: Circle => (0,0) radius 3, point => (0,0)
* Expected:
* the point is in the circle
*/
@Test
public void testPointInCircle() {
final boolean contain = true;
final boolean noContain = false;
Vector2f vector2f = new Vector2f(0,0);
Vector2f point = new Vector2f(0,0);
Circle circle = new Circle(vector2f,3);
assertEquals(contain,Circle.circleContainsPoint(circle, point));
assertNotEquals(noContain,Circle.circleContainsPoint(circle, point));
}
/*
* Purpose: a point is on Circle line
* Input: Circle => (0,0) radius 3, point => (4,0)
* Expected:
* the point is on the circle line
*/
@Test
public void testPointOnCircleLine() {
final boolean contain = true;
final boolean noContain = false;
Vector2f point = new Vector2f(3,0);
Circle circle = new Circle(new Vector2f(0,0),3);
assertEquals(contain,Circle.circleContainsPoint(circle, point));
assertNotEquals(noContain,Circle.circleContainsPoint(circle, point));
}
/*
* Purpose: a point is out of Circle
* Input: Circle => (0,0) radius 3, point => (100,0)
* Expected:
* return fail
* the point is out of the circle line.
* but it is error that calculating distance
*/
@Test
public void testPointOutCircle() {
final boolean contain = true;
final boolean noContain = false;
Vector2f point = new Vector2f(100,0);
Circle circle = new Circle(new Vector2f(0,0),3);
assertEquals(noContain,Circle.circleContainsPoint(circle, point));
assertNotEquals(contain,Circle.circleContainsPoint(circle, point));
}
/*
* Purpose: a circle is in Rectangle
* Input: Circle => (3,3) radius 1, rectangle => (0,0) width 4 height 4
* Expected:
* the circle is in the rectangle
*/
@Test
public void testCircleInRectangle() {
final boolean contain = true;
final boolean noContain = false;
Circle circle = new Circle(new Vector2f(3,3),1);
Rectangle rectangle = new Rectangle(new Vector2f(0,0),4,4);
assertEquals(contain,Circle.circleContainsRect(circle, rectangle));
assertNotEquals(noContain,Circle.circleContainsRect(circle, rectangle));
}
/*
* Purpose: a circle is out of Rectangle
* Input: Circle => (10,10) radius 1, rectangle => (0,0) width 4 height 4
* Expected:
* the circle is out of the rectangle
*/
@Test
public void testCircleOutRectangle() {
final boolean contain = true;
final boolean noContain = false;
Circle circle = new Circle(new Vector2f(10,10),1);
Rectangle rectangle = new Rectangle(new Vector2f(0,0),4,4);
assertEquals(noContain,Circle.circleContainsRect(circle, rectangle));
assertNotEquals(contain,Circle.circleContainsRect(circle, rectangle));
}
/*
* Purpose: a circle intersect Rectangle
* Input: Circle => (0,0) radius 3, rectangle => (2,2) width 4 height 4
* Expected:
* the circle intersect the rectangle
*/
@Test
public void testCircleIntersectRectangle() {
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),3);
Rectangle rectangle = new Rectangle(new Vector2f(2,2),4,4);
assertEquals(intersect,Circle.circleIntersectsRect(circle, rectangle));
assertNotEquals(noIntersect,Circle.circleIntersectsRect(circle, rectangle));
}
/*
* Purpose: a circle intersect Rectangle in Rectangle
* Input: Circle => (0,0) radius 10, rectangle => (3,3) width 2 height 2
* Expected:
* the circle intersect the rectangle
*/
@Test
public void testCircleIntersectInRectangle() {
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),10);
Rectangle rectangle = new Rectangle(new Vector2f(3,3),2,2);
assertEquals(intersect,Circle.circleIntersectsRect(circle, rectangle));
assertNotEquals(noIntersect,Circle.circleIntersectsRect(circle, rectangle));
}
/*
* Purpose: a circle don't intersect Rectangle on same Y axis
* Input: Circle => (0,0) radius 3, rectangle => (10,0) width 5 height 5
* Expected:
* the circle don't intersect the rectangle
*/
@Test
public void testCircleNoIntersectRectangleSameYaxis() {
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),3);
Rectangle rectangle = new Rectangle(new Vector2f(10,0),5,5);
assertEquals(noIntersect,Circle.circleIntersectsRect(circle, rectangle));
assertNotEquals(intersect,Circle.circleIntersectsRect(circle, rectangle));
}
/*
* Purpose: a circle don't intersect Rectangle on same X axis
* Input: Circle => (0,0) radius 3, rectangle => (0,10) width 5 height 5
* Expected:
* the circle don't intersect the rectangle
*/
@Test
public void testCircleNoIntersectRectangleSameXaxis() {
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),3);
Rectangle rectangle = new Rectangle(new Vector2f(0,10),5,5);
assertEquals(noIntersect,Circle.circleIntersectsRect(circle, rectangle));
assertNotEquals(intersect,Circle.circleIntersectsRect(circle, rectangle));
}
/*
* Purpose: a line intersect Circle
* Input: Circle => (0,0) radius 3, line => line(0,0)~(0,10)
* Expected:
* the line intersect the circle
*/
@Test
public void testCircleIntersectLine(){
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),3);
Line line = new Line(new Vector2f(0,0),new Vector2f(0,10));
assertEquals(intersect,Circle.circleIntersectsLine(circle, line));
assertNotEquals(noIntersect,Circle.circleIntersectsLine(circle, line));
}
/*
* Purpose: a line don't intersect Circle
* Input: Circle => (0,0) radius 3, line => line(9,9)~(10,10)
* Expected:
* return FAILURE
* line shouldn't have intersected the circle
* However, the line intersect the circle
*/
@Test
public void testCircleNoIntersectLine(){
final boolean intersect = true;
final boolean noIntersect = false;
Circle circle = new Circle(new Vector2f(0,0),3);
Line line = new Line(new Vector2f(9,9),new Vector2f(10,10));
assertNotEquals(intersect,Circle.circleIntersectsLine(circle, line));
assertEquals(noIntersect,Circle.circleIntersectsLine(circle, line));
}
}
| 7,382 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Protocol.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Protocol.java | /*
* see license.txt
*/
package harenet;
import harenet.messages.NetMessageFactory;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* Simple base Harenet protocol header. Each UDP packet will contain
* this protocol header information. This hold information such as
* the protocol ID, version, peerId and sequencing mechanisms.
*
* @author Tony
*
*/
public class Protocol implements Transmittable {
/**
* Protocol Id -- helps filter out garbage packets
*/
public static final byte PROTOCOL_ID = 0x1e;
private static final int FLAG_COMPRESSED = 0x0001;
/* serves as a quick filter and version# */
private byte protocolId;
/* packet flags */
private byte flags;
/* what peer this belongs to */
private byte peerId;
/* number of messages in this packet */
private byte numberOfMessages;
/* time the packet was sent */
// private int sentTime;
/* the packet number */
private int sendSequence;
/* the last acknowledged packet number */
private int acknowledge;
/* the last 32 acknowledges */
private int ackHistory;
/* the number of bytes we have compressed from
* the original message
*/
private int numberOfBytesCompressed;
private Deflater deflater;
private Inflater inflater;
private IOBuffer compressionBuffer;
private int compressionThreshold;
/**
* @param compressionThreshold
* @param mtu
*/
public Protocol(int compressionThreshold, int mtu) {
this.compressionThreshold = compressionThreshold;
this.deflater = new Deflater(Deflater.BEST_COMPRESSION);
this.deflater.setStrategy(Deflater.HUFFMAN_ONLY);
this.inflater = new Inflater();
this.compressionBuffer = IOBuffer.Factory.allocate(mtu);
reset();
}
/**
* @return true if the protocol ID matches
*/
public boolean isValid() {
return this.protocolId == PROTOCOL_ID;
}
/**
* Makes the protocol Id valid
*/
public void makeValid() {
this.protocolId = PROTOCOL_ID;
}
/**
* Resets to initial state
*/
public void reset() {
this.protocolId = 0;
this.flags = 0;
this.peerId = Host.INVALID_PEER_ID;
this.numberOfMessages = 0;
// this.sentTime = 0;
this.sendSequence = 0;
this.acknowledge = 0;
this.ackHistory = 0;
this.numberOfBytesCompressed = 0;
this.compressionBuffer.clear();
this.deflater.reset();
this.inflater.reset();
}
/**
* @return the number of bytes the protocol header takes
*/
public int size() {
return 1 + // protocolId
1 + // flags
1 + // peerdId
1 + // numberOf messages
// 4 + // send time
4 + // send Sequence
4 + // acknowledge
4 // ackHistory
;
}
/**
* @param sendSequence the sendSequence to set
*/
public void setSendSequence(int sendSequence) {
this.sendSequence = sendSequence;
}
/**
* @param acknowledge the acknowledge to set
*/
public void setAcknowledge(int acknowledge) {
this.acknowledge = acknowledge;
}
/**
* @param ackHistory the ackHistory to set
*/
public void setAckHistory(int ackHistory) {
this.ackHistory = ackHistory;
}
/**
* @param numberOfMessages the numberOfMessages to set
*/
public void setNumberOfMessages(byte numberOfMessages) {
this.numberOfMessages = numberOfMessages;
}
/**
* @param sentTime the sentTime to set
*/
// public void setSentTime(int sentTime) {
// this.sentTime = sentTime;
// }
/**
* @param peerId the peerId to set
*/
public void setPeerId(byte peerId) {
this.peerId = peerId;
}
/**
* @return the peerId
*/
public byte getPeerId() {
return peerId;
}
/**
* @return the sentTime
*/
// public int getSentTime() {
// return sentTime;
// }
/**
* @return the numberOfMessages
*/
public byte getNumberOfMessages() {
return numberOfMessages;
}
/**
* @return the ackHistory
*/
public int getAckHistory() {
return ackHistory;
}
/**
* @return the acknowledge
*/
public int getAcknowledge() {
return acknowledge;
}
/**
* @return the sendSequence
*/
public int getSendSequence() {
return sendSequence;
}
/**
* @return the numberOfBytesCompressed
*/
public int getNumberOfBytesCompressed() {
return numberOfBytesCompressed;
}
/*
* (non-Javadoc)
* @see harenet.Transmittable#readFrom(harenet.IOBuffer, harenet.messages.NetMessageFactory)
*/
@Override
public void readFrom(IOBuffer buffer, NetMessageFactory messageFactory) {
this.protocolId = buffer.getByte();
this.flags = buffer.getByte();
uncompress(buffer);
this.peerId = buffer.getByte();
this.numberOfMessages = buffer.getByte();
// this.sentTime = buffer.getInt();
this.sendSequence = buffer.getInt();
this.acknowledge = buffer.getInt();
this.ackHistory = buffer.getInt();
}
/* (non-Javadoc)
* @see netspark.Transmittable#writeTo(java.nio.ByteBuffer)
*/
@Override
public void writeTo(IOBuffer buffer) {
int endPosition = buffer.position();
buffer.position(0);
buffer.putByte(PROTOCOL_ID);
buffer.putByte(this.flags); // just a place holder
buffer.putByte(this.peerId);
buffer.putByte(this.numberOfMessages);
// buffer.putInt(this.sentTime);
buffer.putInt(this.sendSequence);
buffer.putInt(this.acknowledge);
buffer.putInt(this.ackHistory);
buffer.position(endPosition);
compress(buffer);
/* if we compressed things, mark the
* flags header
*/
buffer.putByte(1, this.flags);
}
/**
* Compress the supplied {@link IOBuffer}
*
* @param buffer
*/
private void compress(IOBuffer buffer) {
int size = buffer.position();
if(buffer.hasArray() && this.compressionThreshold > 0 && size > this.compressionThreshold) {
int numberOfBytesToSkip = 2; /* Skip the Protocol and Flags bytes */
this.deflater.setInput(buffer.array(), numberOfBytesToSkip, buffer.position()-numberOfBytesToSkip );
this.deflater.finish();
int len = deflater.deflate(this.compressionBuffer.array(), numberOfBytesToSkip, this.compressionBuffer.capacity()-numberOfBytesToSkip, Deflater.FULL_FLUSH);
if(!deflater.finished()) {
return; /* not able to compress with the amount of space given */
}
this.numberOfBytesCompressed = (size-numberOfBytesToSkip)-len;
this.compressionBuffer.position(numberOfBytesToSkip);
this.compressionBuffer.limit(len);
buffer.limit(len+numberOfBytesToSkip);
buffer.position(numberOfBytesToSkip);
buffer.put(this.compressionBuffer);
this.flags |= FLAG_COMPRESSED;
}
}
/**
* Uncompress the supplied {@link IOBuffer}
*
* @param buffer
*/
private void uncompress(IOBuffer buffer) {
if((this.flags & FLAG_COMPRESSED) != 0) {
int numberOfBytesToSkip = 2; /* Skip the Protocol and Flags bytes */
this.inflater.setInput(buffer.array(), numberOfBytesToSkip, buffer.limit()-numberOfBytesToSkip);
int len = 0;
try {
len = this.inflater.inflate(this.compressionBuffer.array(), numberOfBytesToSkip, this.compressionBuffer.capacity()-numberOfBytesToSkip);
}
catch(DataFormatException e) {
throw new RuntimeException(e);
}
this.numberOfBytesCompressed = len-(buffer.limit()-numberOfBytesToSkip);
this.compressionBuffer.position(2);
this.compressionBuffer.limit(len);
buffer.limit(len+numberOfBytesToSkip);
buffer.position(numberOfBytesToSkip);
buffer.put(this.compressionBuffer);
buffer.position(numberOfBytesToSkip);
}
}
}
| 8,926 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
NetConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/NetConfig.java | /*
* see license.txt
*/
package harenet;
import harenet.messages.NetMessageFactory;
/**
* The Harenet configuration. This allows for tweaking
* a number of parameters to better suit your needs.
*
* @author Tony
*
*/
public class NetConfig {
private long timeout;
private int mtu;
private int maxConnections;
private long reliableMessageTimeout;
private long heartbeatTime;
private int pollRate;
private long pingRate;
private int compressionThreshold;
private boolean useDirectBuffers;
private Log log;
private NetMessageFactory messageFactory;
/**
* @param messageFactory
*/
public NetConfig(NetMessageFactory messageFactory) {
this(15_000 // timeout
, 5_000 // reliable timeout
, 150 // heartbeat
, 10_000 // ping rate
, 33 // poll the network
, 1500 // mtu
, 16 // max connections
, 500 // compressionThreshold
, false // useDirectBuffers
, new SysoutLog()
, messageFactory);
}
/**
* @param timeout
* @param reliableMessageTimeout
* @param heartbeat
* @param pingRate
* @param pollRate
* @param mtu
* @param maxConnections
* @param compressionThreshold
* @param useDirectBuffers
* @param log
* @param messageFactory
*/
public NetConfig(long timeout
, long reliableMessageTimeout
, long heartbeat
, long pingRate
, int pollRate
, int mtu, int maxConnections
, int compressionThreshold
, boolean useDirectBuffers
, Log log
, NetMessageFactory messageFactory) {
super();
this.timeout = timeout;
this.reliableMessageTimeout = reliableMessageTimeout;
this.heartbeatTime = heartbeat;
this.pingRate = pingRate;
this.pollRate = pollRate;
this.mtu = mtu;
this.maxConnections = maxConnections;
this.compressionThreshold = compressionThreshold;
this.useDirectBuffers = useDirectBuffers;
this.log = log;
this.messageFactory = messageFactory;
}
/**
* Turn logging on/off
* @param b
*/
public void enableLog(boolean b) {
log.setEnabled(b);
}
/**
* @return the messageFactory
*/
public NetMessageFactory getMessageFactory() {
return messageFactory;
}
/**
* @param messageFactory the messageFactory to set
*/
public void setMessageFactory(NetMessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
/**
* @return the pollRate
*/
public int getPollRate() {
return pollRate;
}
/**
* @return the pingRate
*/
public long getPingRate() {
return pingRate;
}
/**
* @return the heartbeatTime
*/
public long getHeartbeatTime() {
return heartbeatTime;
}
/**
* @param heartbeatTime the heartbeatTime to set
*/
public void setHeartbeatTime(long heartbeatTime) {
this.heartbeatTime = heartbeatTime;
}
/**
* @param pingRate the pingRate to set
*/
public void setPingRate(long pingRate) {
this.pingRate = pingRate;
}
/**
* @param reliableMessageTimeout the reliableMessageTimeout to set
*/
public void setReliableMessageTimeout(long reliableMessageTimeout) {
this.reliableMessageTimeout = reliableMessageTimeout;
}
/**
* @return the reliableMessageTimeout
*/
public long getReliableMessageTimeout() {
return reliableMessageTimeout;
}
/**
* @param pollRate the pollRate to set
*/
public void setPollRate(int pollRate) {
this.pollRate = pollRate;
}
/**
* @param timeout the timeout to set
*/
public void setTimeout(long timeout) {
this.timeout = timeout;
}
/**
* @param mtu the mtu to set
*/
public void setMtu(int mtu) {
this.mtu = mtu;
}
/**
* @param maxConnections the maxConnections to set
*/
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* @param log the log to set
*/
public void setLog(Log log) {
this.log = log;
}
/**
* @return the log
*/
public Log getLog() {
return log;
}
/**
* @return the maxConnections
*/
public int getMaxConnections() {
return maxConnections;
}
/**
* @return the mtu
*/
public int getMtu() {
return mtu;
}
/**
* @return the timeout
*/
public long getTimeout() {
return timeout;
}
/**
* @return the compressionThreshold
*/
public int getCompressionThreshold() {
return compressionThreshold;
}
/**
* @param compressionThreshold the compressionThreshold to set
*/
public void setCompressionThreshold(int compressionThreshold) {
this.compressionThreshold = compressionThreshold;
}
/**
* @return if native buffers are to be used for reading/writing from
* the network sockets
*/
public boolean useDirectBuffers() {
return this.useDirectBuffers;
}
/**
* @param useDirectBuffers the useDirectBuffers to set
*/
public void setUseDirectBuffers(boolean useDirectBuffers) {
this.useDirectBuffers = useDirectBuffers;
}
}
| 5,782 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Time.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Time.java | /*
* see license.txt
*/
package harenet;
/**
* Utility class for calculating delta times
*
* @author Tony
*
*/
public class Time {
private static long timeBase = System.currentTimeMillis() - (365 * 24 * 60 * 60 * 1000);
/**
* The time based off of some arbitrary offset. This should not be
* used to calculate the current epoch time, but rather should be used
* for taking delta time calculations
*
* @return the current time based off of some some arbitrary offset
*/
public static int time() {
return (int) (System.currentTimeMillis() - timeBase);
}
}
| 638 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Host.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Host.java | /*
* see license.txt
*/
package harenet;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Queue;
import harenet.Peer.State;
import harenet.messages.ConnectionRequestMessage;
import harenet.messages.DisconnectMessage;
import harenet.messages.HeartbeatMessage;
import harenet.messages.Message;
import harenet.messages.NetMessageFactory;
import harenet.messages.PingMessage;
import harenet.messages.PongMessage;
import harenet.messages.ServerFullMessage;
/**
* Represents a {@link Host} machine. This is able to send and receive
* messages from remote {@link Peer}s
*
* @author Tony
*
*/
public class Host {
public static final byte INVALID_PEER_ID = -1;
private static final int SOCKET_ERROR = -1;
private static final int SOCKET_WAIT = 0;
private static final int SOCKET_READ = 1;
private static final int SOCKET_WRITE = 2;
private Selector selector;
private DatagramChannel datagramChannel;
private InetSocketAddress receivedAddress;
private NetConfig config;
private IOBuffer readBuffer, writeBuffer;
private Peer[] peers;
private int maxConnections;
private int numberOfConnections;
private Protocol protocol;
private Log log;
private NetMessageFactory messageFactory;
private boolean isServer;
private Peer localPeer;
/**
* Listens for messages and {@link Peer} connection state events.
*
* @author Tony
*
*/
public static interface MessageListener {
/**
* The {@link Peer} has connected to the {@link Host}
*
* @param peer
*/
public void onConnected(Peer peer);
/**
* The {@link Peer} has disconnected from the {@link Host}
*
* @param peer
*/
public void onDisconnected(Peer peer);
/**
* The server is full and is denying the peer from
* connecting.
*
* @param peer
*/
public void onServerFull(Peer peer);
/**
* A message has been received
*
* @param peer
* @param message
*/
public void onMessage(Peer peer, Message message);
}
/**
* @param config
* @param address
* @throws IOException
*/
public Host(NetConfig config, InetSocketAddress address) throws IOException {
this.config = config;
log = config.getLog();
messageFactory = config.getMessageFactory();
isServer = address != null;
maxConnections = this.config.getMaxConnections();
datagramChannel = DatagramChannel.open();
datagramChannel.configureBlocking(false);
datagramChannel.bind(address);
selector = Selector.open();
datagramChannel.register(selector, SelectionKey.OP_READ);
readBuffer = config.useDirectBuffers() ? IOBuffer.Factory.allocateDirect(config.getMtu()) :
IOBuffer.Factory.allocate(config.getMtu());
readBuffer.clear();
writeBuffer = config.useDirectBuffers() ? IOBuffer.Factory.allocateDirect(config.getMtu()) :
IOBuffer.Factory.allocate(config.getMtu());
writeBuffer.clear();
peers = new Peer[config.getMaxConnections()];
protocol = new Protocol(config.getCompressionThreshold(), config.getMtu());
}
/**
* @return the config
*/
public NetConfig getConfig() {
return config;
}
/**
* @return the {@link Log} instance
*/
public Log getLogger() {
return config.getLog();
}
/**
* Reserves the next available ID slot.
*
* @param id the ID which is reserved.
*/
public int reserveId() {
synchronized (this) {
byte id = findOpenId();
if(isValidPeerId(id)) {
if(peers[id] == null) {
peers[id] = new DummyPeer(this, (byte)id);
numberOfConnections++;
}
}
return id;
}
}
/**
* Destroy this host, releasing any resources and closing down connections
*/
public void destroy() {
for(int i = 0; i < this.maxConnections; i++) {
Peer peer = peers[i];
if(peer != null && peer.isConnected()) {
peer.disconnectNow();
}
peers[i] = null;
}
this.numberOfConnections = 0;
if(datagramChannel.isOpen()) {
try {datagramChannel.close(); } catch (IOException e) {}
}
if(this.selector.isOpen()) {
try { this.selector.close(); } catch (IOException e) {}
}
}
/**
* Initiates a connection to the remote address
* @param address
* @return the {@link Peer}
* @throws IOException
*/
public Peer connect(InetSocketAddress address) throws IOException {
// Peer peer = allocatePeer(address);
if(localPeer != null) {
localPeer.disconnectNow();
}
if(datagramChannel.isConnected()) {
datagramChannel.disconnect();
}
datagramChannel.connect(address);
localPeer = new Peer(this, address, INVALID_PEER_ID);
localPeer.send(new ConnectionRequestMessage());
return localPeer;
}
/**
* Allocates the {@link Peer} which doesn't actually make the connection
* @param address
* @return the Peer
* @throws IOException
*/
protected Peer allocatePeer(InetSocketAddress address) throws IOException {
synchronized (this) {
if (this.numberOfConnections >= this.maxConnections) {
sendOutOfBandMessage(writeBuffer, address, ServerFullMessage.INSTANCE);
throw new IOException("Max number of connections has been met.");
}
Peer peer = isClientAlreadyConnected(address);
if(peer==null) {
byte id = findOpenId();
if (id == INVALID_PEER_ID) {
throw new IOException("Unable to allocate a valid id.");
}
this.numberOfConnections++;
peer = new Peer(this, address, id);
peer.setState(State.CONNECTED);
peers[id] = peer;
}
return peer;
}
}
private Peer isClientAlreadyConnected(InetSocketAddress address) {
for (int i = 0; i < this.maxConnections; i++) {
if (peers[i] != null) {
if(peers[i].getAddress().equals(address)) {
return peers[i];
}
}
}
return null;
}
/**
* @return an open available id
*/
private byte findOpenId() {
for (int i = 0; i < this.maxConnections; i++) {
if (peers[i] == null) {
return (byte) i;
}
}
return INVALID_PEER_ID;
}
/**
* @param peerId
* @return true if the supplied ID is valid
*/
private boolean isValidPeerId(byte peerId) {
return peerId > INVALID_PEER_ID && peerId < this.maxConnections;
}
void disconnect(Peer peer) {
byte id = peer.getId();
if (isValidPeerId(id)) {
if(peers[id] != null) {
peers[id].send(new DisconnectMessage());
/* remove the peer if they are disconnected */
if(peers[id].isDisconnected()) {
synchronized (this) {
peers[id] = null;
this.numberOfConnections--;
if(this.numberOfConnections < 0) {
this.numberOfConnections = 0;
}
}
}
}
}
}
/**
* Sends a {@link Message} to the peer
* @param message
* @param peerId
*/
public void sendTo(Message message, byte peerId) {
if(isValidPeerId(peerId)) {
Peer peer = peers[peerId];
if(peer != null) {
peer.send(message);
}
}
}
/**
* Sends the message to all Peers
* @param message
*/
public void sendToAll(Message message) {
for(int i = 0; i < peers.length; i++) {
Peer peer = peers[i];
if(peer != null) {
peer.send(message);
}
}
}
/**
* Sends the message to all Peers with the exception of the supplied peerId
* @param message
* @param peerId
*/
public void sendToAllExcept(Message message, byte peerId) {
for(int i = 0; i < peers.length; i++) {
Peer peer = peers[i];
if(peer != null && i != peerId) {
peer.send(message);
}
}
}
/**
* Sends out any pending packets to all connected clients
*
* @throws IOException
*/
public void sendClientPackets() throws IOException {
if(isServer) {
for (int i = 0; i < maxConnections; i++) {
Peer peer = peers[i];
sendPacket(peer);
}
}
else {
sendPacket(localPeer);
}
}
/**
* Checks to see if any bytes are received
*
* @return true if packets have been received
* @throws IOException
*/
public boolean receiveClientPackets() throws IOException {
boolean bytesReceived = false;
/* now lets receive any messages */
int numberOfBytesRecv = receive(readBuffer);
if(numberOfBytesRecv > 0) {
/* the received address is updated as
* we receive bytes from a peer (it is updated
* to the address that send us the bytes
*/
if(this.receivedAddress != null) {
parsePacket(readBuffer);
bytesReceived = true;
}
}
return bytesReceived;
}
/**
* Updates the network state
*
* @param listener
* @param timeout
* @throws IOException
*/
public void update(MessageListener listener, int timeout) throws IOException {
// algorithm:
// For each Client:
// 1) send out Packet
// 2) read in queued up Messages from clients
// 3) receive Packet
// 4) parse Packet
// 5) place Message in client Queue
int startTime = Time.time();
/* send any pending packets */
sendClientPackets();
int socketState = SOCKET_WAIT;
do {
/* if we received a packet from the client
* we can break out
*/
if(receiveClientPackets()) {
break;
}
int endTime = Time.time();
if( (endTime-startTime) > timeout) {
break;
}
socketState = socketWait(timeout - (endTime-startTime) );
if(socketState == SOCKET_ERROR) {
if(log.enabled()) {
log.error("Error selecting from datagram channel!");
}
}
} while (socketState == SOCKET_READ);
dispatchMessages(listener);
checkTimeouts(listener);
}
/**
* Packs and sends out the packet for the peer.
*
* @param peer
*/
private void sendPacket(Peer peer) {
if (peer != null) {
writeBuffer.clear();
protocol.reset();
/* do we need to send a ping? */
if( this.isServer ) {
long currentTime = System.currentTimeMillis();
if ( currentTime - peer.getLastPingTime() >= config.getPingRate() ) {
peer.setLastPingTime(currentTime);
peer.send(PingMessage.INSTANCE);
}
}
/* move the header to start writing messages,
* we will write out the protocol header once
* we have all the information we need
*/
writeBuffer.position(protocol.size());
if(peer.isConnecting()) {
protocol.setPeerId(INVALID_PEER_ID);
}
else {
protocol.setPeerId(peer.getId());
}
byte numberOfMessages = 0;
/* always give priority to the reliable packets */
numberOfMessages += packReliableMessages(writeBuffer, protocol, peer);
/* if there is space, go ahead and put in the unreliable packets */
numberOfMessages += packUnreliableMessages(writeBuffer, protocol, peer);
protocol.setNumberOfMessages(numberOfMessages);
/* if we had any messages, lets send it out */
if(numberOfMessages > 0) {
// protocol.setSentTime(Time.time());
protocol.setSendSequence(peer.nextSequenceNumber());
protocol.setAcknowledge(peer.getRemoteSequence());
protocol.setAckHistory(peer.getAckHistory());
protocol.writeTo(writeBuffer);
peer.addNumberOfBytesCompressed(protocol.getNumberOfBytesCompressed());
send(writeBuffer, peer);
}
else {
long amountOfTimeSinceLastPacket = System.currentTimeMillis() - peer.getLastSendTime();
if(amountOfTimeSinceLastPacket >= config.getHeartbeatTime()) {
peer.send(HeartbeatMessage.INSTANCE);
}
}
}
}
/**
* Empties the unreliable queue
* @param writeBuffer
* @param protocol
* @param peer
* @return the number of messages packed
*/
private int packUnreliableMessages(IOBuffer writeBuffer, Protocol protocol, Peer peer) {
int numberOfMessagesSent = 0;
if (peer != null) {
Queue<Message> messages = peer.getOutgoingMessages();
int numberOfMessages = messages.size();
if((numberOfMessages+protocol.getNumberOfMessages()) > Byte.MAX_VALUE) {
numberOfMessages = Byte.MAX_VALUE - protocol.getNumberOfMessages();
}
if (!messages.isEmpty()) {
while (numberOfMessages > 0) {
numberOfMessages--;
Message msg = messages.peek();
/*
* check and see if the message can fit
*/
if (!fitsInPacket(msg)) {
msg.delay();
break;
}
messages.poll();
if(log.enabled()) {
log.debug("Sending unreliable message: "
+ (peer.getSendSequence()+1)
+ " with Ack: " + peer.getRemoteSequence());
}
msg.writeTo(writeBuffer);
numberOfMessagesSent++;
}
}
}
return (numberOfMessagesSent);
}
/**
* Packs as many reliable messages as possible
* @param writeBuffer
* @param protocol
* @param peer
* @return the number of packed messages
*/
private int packReliableMessages(IOBuffer writeBuffer, Protocol protocol, Peer peer) {
int numberOfMessagesSent = 0;
if (peer != null) {
Queue<Message> reliableMessages = peer.getReliableOutgoingMessages();
if(!reliableMessages.isEmpty()) {
for (Message msg : reliableMessages) {
/* check and see if the message can
* fit
*/
if(! fitsInPacket(msg)) {
msg.delay();
break;
}
/* note when it was sent out, so we can time it out */
if(!msg.hasBeenSent()) {
/* mark which packet number this reliable message
* was sent out
*/
int seq = peer.getSendSequence()+1;
msg.setSequenceNumberSent(seq);
msg.setMessageId(peer.nextMessageId());
msg.setTimeSent(System.currentTimeMillis());
}
msg.addSequenceNumberSent();
msg.writeTo(writeBuffer);
if(log.enabled()) {
log.debug("Sending reliable message: " + msg.getClass().getSimpleName()
+ " Sequence: " + msg.getSequenceNumberSent()
+ " with Ack: " + peer.getRemoteSequence());
}
numberOfMessagesSent++;
}
}
}
return (numberOfMessagesSent);
}
/**
* Dispatches any queued up messages
* @param listener
*/
private void dispatchMessages(MessageListener listener) {
for (int i = 0; i < maxConnections; i++) {
Peer peer = peers[i];
if (peer != null) {
peer.receiveMessages(listener);
// peer.checkReliableMessages();
}
}
}
/**
* Writes an out of band message to the remote address. This is one way communication
*
* @param ioBuffer
* @param remoteAddress
* @param msg
* @return the number of bytes written out
*/
private int sendOutOfBandMessage(IOBuffer ioBuffer, InetSocketAddress remoteAddress, Message msg) {
protocol.reset();
protocol.setNumberOfMessages( (byte)1 );
protocol.writeTo(ioBuffer);
msg.writeTo(ioBuffer);
ByteBuffer buffer = ioBuffer.sendSync().asByteBuffer();
buffer.flip();
try {
return datagramChannel.send(buffer, remoteAddress);
}
catch (Exception e) {
if(log.enabled()) log.error("Error sending bytes to peer: " + e);
return -1;
}
}
/**
* Sends the bytes to the remote Peer.
* @param buffer
* @param peer
* @return the number of bytes transfered
*/
private int send(IOBuffer ioBuffer, Peer peer) {
ByteBuffer buffer = ioBuffer.sendSync().asByteBuffer();
buffer.flip();
try {
peer.setLastSendTime(System.currentTimeMillis());
peer.addNumberOfBytesSent(buffer.limit());
return datagramChannel.send(buffer, peer.getAddress());
}
catch (Exception e) {
if(log.enabled()) log.error("Error sending bytes to peer: " + e);
return -1;
}
}
/**
* Receives bytes from a remote peer. If bytes are received the "receivedAddress"
* will be updated to the address that send the bytes.
*
* @param buffer
* @return the number of bytes received
*/
private int receive(IOBuffer ioBuffer) {
ByteBuffer buffer = ioBuffer.clear().asByteBuffer();
buffer.clear();
try {
this.receivedAddress = (InetSocketAddress) datagramChannel.receive(buffer);
buffer.flip();
ioBuffer.receiveSync();
return buffer.limit();
}
catch(Exception e) {
if(log.enabled()) log.error("Error receiving bytes: " + e);
return -1;
}
}
/**
* Parses the packet; reads in the protocol headers and queuing up Messages
* for the Peer.
*
* @param buffer
* @throws IOException
*/
private void parsePacket(IOBuffer buffer) throws IOException {
if(log.enabled()) {
log.debug("Receiving " + buffer.limit() + " of bytes from " + receivedAddress);
}
protocol.reset();
protocol.readFrom(buffer, messageFactory);
/* if this packet isn't from our
* network protocol ignore it
*/
if(protocol.isValid()) {
byte peerId = protocol.getPeerId();
/* this is the first time this client
* is connecting to our server
*/
if(peerId == INVALID_PEER_ID) {
peerId = handleConnectionRequest(buffer, protocol);
}
/* lets read in the messages */
if(isValidPeerId(peerId)) {
/* if this isn't a server we reassign the peer
* to the correct id (since it was assigned from
* the server
*/
if(!isServer && peers[peerId] == null) {
peers[peerId] = localPeer;
peers[peerId].setState(State.CONNECTED);
peers[peerId].receive(new ConnectionRequestMessage());
}
Peer peer = peers[peerId];
if(peer == null) {
if(log.enabled()) {
log.error("The PeerId: " + peerId + " is no longer valid, ignoring packet.");
}
}
else {
/* there are times were the remote address will
* change, so we just always update the address to
* keep in sync
*/
peer.setId(peerId);
peer.setAddress(receivedAddress);
peer.setLastReceivedTime(System.currentTimeMillis());
peer.addNumberOfBytesRecv(buffer.limit());
peer.addNumberOfBytesCompressed(protocol.getNumberOfBytesCompressed());
int seqNumber = protocol.getSendSequence();
/* if this is a newer packet, lets go ahead
* and process it
*/
if(peer.isSequenceMoreRecent(seqNumber)) {
int numberOfDroppedPackets = seqNumber - peer.getRemoteSequence();
if(numberOfDroppedPackets > 1) {
peer.addDroppedPacket(numberOfDroppedPackets-1);
}
peer.setRemoteSequence(seqNumber);
peer.setRemoteAck(protocol.getAckHistory(), protocol.getAcknowledge());
parseMessages(peer, buffer, protocol);
}
else {
peer.addDroppedPacket();
if(log.enabled()) {
log.error("Out of order packet:" + seqNumber + " should be: " + peer.getRemoteSequence());
}
}
}
}
else {
if(log.enabled()) {
log.error("Invalid PeerId: " + peerId + " ignoring the rest of the packet.");
}
}
}
}
/**
* Handles a new connection request
*
* @param buffer
* @param protocol
* @return the PeerId
*/
private byte handleConnectionRequest(IOBuffer buffer, Protocol protocol) throws IOException {
Peer peer = allocatePeer(receivedAddress);
if(peer ==null) {
if(log.enabled()) {
log.error("Unable to allocate peer for: " + receivedAddress);
}
return INVALID_PEER_ID;
}
// else {
// peer.send(new ConnectionAcceptedMessage());
// }
return peer.getId();
}
/**
* Parses the messages
*
* @param peer
* @param buffer
* @param protocol
*/
private void parseMessages(Peer peer, IOBuffer buffer, Protocol protocol) {
byte numberOfMessages = protocol.getNumberOfMessages();
while(numberOfMessages > 0 && buffer.hasRemaining()) {
numberOfMessages--;
Message message = MessageHeader.readMessageHeader(buffer, messageFactory);
if(message == null) {
if(log.enabled()) {
log.error("Error reading the message header from: " + receivedAddress);
}
}
else if(message.isReliable()) {
// if(log.enabled()) {
// log.debug("Receiving message: " + protocol.getSendSequence() + " with Ack: " + protocol.getAcknowledge());
// }
if(!peer.isDuplicateMessage(message)) {
peer.receive(message);
}
}
else {
if(message instanceof PingMessage) {
peer.send(PongMessage.INSTANCE);
}
else if(message instanceof PongMessage) {
peer.pongMessageReceived();
}
else {
peer.receive(message);
}
}
}
}
/**
* @param msg
* @return true if the Message fits in the Packet
*/
private boolean fitsInPacket(Message msg) {
return this.writeBuffer.remaining() > msg.getSize();
}
/**
* Does multiplex on the Datagram channel
* @param timeout
* @return what state the socket is in
* @throws IOException
*/
private int socketWait(int timeout) {
int result = SOCKET_WAIT;
int numKeys = 0;
try {
numKeys = (timeout > 0) ? selector.select(timeout) : selector.selectNow();
}
catch (IOException e) {
if(log.enabled()) {
log.error("*** Error in select : " + e);
}
result = SOCKET_ERROR;
}
if (numKeys > 0) {
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey key = selectedKeys.next();
selectedKeys.remove();
if (!key.isValid()) {
continue;
}
if (key.isReadable()) {
result = SOCKET_READ;
break;
} else if (key.isWritable()) {
result = SOCKET_WRITE;
break;
}
}
}
return result;
}
/**
* Checks for client time outs
* @param listener
*/
private void checkTimeouts(MessageListener listener) {
long currentTime = System.currentTimeMillis();
long messageTimeout = config.getReliableMessageTimeout() + 500;
for(int i = 0; i < peers.length; i++) {
Peer peer = peers[i];
if(peer != null && peer.isConnected()) {
if(peer.checkIfTimedOut(currentTime, config.getTimeout())) {
listener.onDisconnected(peer);
peer.disconnectNow();
}
else {
peer.timeoutDuplicates(currentTime, messageTimeout);
}
}
else if(peer!=null && peer.isDisconnecting()) {
peer.disconnectNow();
}
}
}
}
| 29,595 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ByteBufferIOBuffer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/ByteBufferIOBuffer.java | /*
* see license.txt
*/
package harenet;
import java.nio.ByteBuffer;
/**
* An IOBuffer backed by a {@link ByteBuffer}
*
* @author Tony
*
*/
public class ByteBufferIOBuffer implements IOBuffer {
private ByteBuffer buffer;
private BitPacker packer;
/**
*/
public ByteBufferIOBuffer(ByteBuffer buffer) {
this.buffer = buffer;
this.packer = new BitPacker(this.buffer.capacity() * 8, buffer.limit() * 8);
// syncs what's in the ByteBuffer to the BitPacker
syncBuffer();
}
/**
* @param size
*/
public ByteBufferIOBuffer(int size) {
this.buffer = ByteBuffer.allocate(size);
this.packer = new BitPacker(this.buffer.capacity() * 8, size * 8);
}
private void syncBuffer() {
buffer.clear();
int oldPosition = packer.position(0);
packer.writeTo(buffer);
packer.position(oldPosition);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#receiveSync()
*/
@Override
public IOBuffer receiveSync() {
buffer.mark();
{
packer.clear();
packer.readFrom(buffer);
packer.flip();
}
buffer.reset();
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#sync()
*/
@Override
public IOBuffer sendSync() {
syncBuffer();
return this;
}
/*
* (non-Javadoc)
* @see harenet.IOBuffer#asByteBuffer()
*/
@Override
public ByteBuffer asByteBuffer() {
return buffer;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#slice()
*/
@Override
public IOBuffer slice() {
syncBuffer();
return new ByteBufferIOBuffer(buffer.slice());
}
/* (non-Javadoc)
* @see netspark.IOBuffer#duplicate()
*/
@Override
public IOBuffer duplicate() {
syncBuffer();
return new ByteBufferIOBuffer(buffer.duplicate());
}
/* (non-Javadoc)
* @see netspark.IOBuffer#asReadOnlyBuffer()
*/
@Override
public IOBuffer asReadOnlyBuffer() {
syncBuffer();
return new ByteBufferIOBuffer(buffer.asReadOnlyBuffer());
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getUnsignedByte()
*/
@Override
public int getUnsignedByte() {
return packer.getByte() & 0xFF;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get()
*/
@Override
public byte getByte() {
return packer.getByte();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putUnsignedByte(int)
*/
@Override
public IOBuffer putUnsignedByte(int b) {
packer.putByte( (byte) b);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte)
*/
@Override
public IOBuffer putByte(byte b) {
packer.putByte(b);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(int)
*/
@Override
public byte getByte(int index) {
packer.mark();
packer.position(index * 8);
byte result = packer.getByte();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(int, byte)
*/
@Override
public IOBuffer putByte(int index, byte b) {
packer.putBits(index * 8, b, Byte.SIZE);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(byte[], int, int)
*/
@Override
public IOBuffer getBytes(byte[] dst, int offset, int length) {
packer.getBytes(dst, offset, length);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(byte[])
*/
@Override
public IOBuffer getBytes(byte[] dst) {
packer.getBytes(dst, 0, dst.length);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(netspark.IOBuffer)
*/
@Override
public IOBuffer put(IOBuffer src) {
//buffer.put(src.array(), src.arrayOffset(), src.capacity());
//buffer.put(src.asByteBuffer());
//ByteBuffer buffer = src.asByteBuffer();
// TODO: Think about this more
packer.putBytes(buffer.array(), buffer.arrayOffset(), buffer.capacity());
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte[], int, int)
*/
@Override
public IOBuffer putBytes(byte[] src, int offset, int length) {
//buffer.put(src, offset, length);
packer.putBytes(src, offset, length);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte[])
*/
@Override
public IOBuffer putBytes(byte[] src) {
packer.putBytes(src);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#hasArray()
*/
@Override
public boolean hasArray() {
return buffer.hasArray();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#array()
*/
@Override
public byte[] array() {
syncBuffer();
return buffer.array();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#arrayOffset()
*/
@Override
public int arrayOffset() {
return buffer.arrayOffset();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#compact()
*/
@Override
public IOBuffer compact() {
syncBuffer();
buffer.compact();
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#isDirect()
*/
@Override
public boolean isDirect() {
return buffer.isDirect();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#capacity()
*/
@Override
public int capacity() {
return buffer.capacity();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#position()
*/
@Override
public int position() {
int leftOver = packer.position() % 8;
if(leftOver>0) {
return (packer.position() / 8) + 1;
}
return (packer.position() / 8);
}
/* (non-Javadoc)
* @see netspark.IOBuffer#position(int)
*/
@Override
public IOBuffer position(int newPosition) {
packer.position(newPosition * 8);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#limit()
*/
@Override
public int limit() {
int leftOver = packer.limit() % 8;
if(leftOver>0) {
return (packer.limit() / 8) + 1;
}
return (packer.limit() / 8);
}
/* (non-Javadoc)
* @see netspark.IOBuffer#limit(int)
*/
@Override
public IOBuffer limit(int newLimit) {
packer.limit(newLimit * 8);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#mark()
*/
@Override
public IOBuffer mark() {
packer.mark();
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#reset()
*/
@Override
public IOBuffer reset() {
packer.reset();
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#clear()
*/
@Override
public IOBuffer clear() {
packer.clear();
packer.limit(buffer.capacity() * 8);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#flip()
*/
@Override
public IOBuffer flip() {
packer.flip();
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#rewind()
*/
@Override
public IOBuffer rewind() {
packer.rewind();
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#remaining()
*/
@Override
public int remaining() {
int leftOver = packer.remaining() % 8;
if(leftOver>0) {
return (packer.remaining() / 8) + 1;
}
return (packer.remaining() / 8);
}
/* (non-Javadoc)
* @see netspark.IOBuffer#hasRemaining()
*/
@Override
public boolean hasRemaining() {
return packer.hasRemaining();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#isReadOnly()
*/
@Override
public boolean isReadOnly() {
return buffer.isReadOnly();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getShort()
*/
@Override
public short getShort() {
return packer.getShort();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putShort(short)
*/
@Override
public IOBuffer putShort(short value) {
packer.putShort(value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getShort(int)
*/
@Override
public short getShort(int index) {
packer.mark();
packer.position(index * 8);
short result = packer.getShort();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putShort(int, short)
*/
@Override
public IOBuffer putShort(int index, short value) {
packer.putShort(index, value, Short.SIZE);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getInt()
*/
@Override
public int getInt() {
return packer.getInteger();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putInt(int)
*/
@Override
public IOBuffer putInt(int value) {
packer.putInteger(value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getInt(int)
*/
@Override
public int getInt(int index) {
packer.mark();
packer.position(index * 8);
int result = packer.getInteger();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putInt(int, int)
*/
@Override
public IOBuffer putInt(int index, int value) {
packer.putInteger(index, value, Integer.SIZE);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getLong()
*/
@Override
public long getLong() {
return packer.getLong();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putLong(long)
*/
@Override
public IOBuffer putLong(long value) {
packer.putLong(value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getLong(int)
*/
@Override
public long getLong(int index) {
packer.mark();
packer.position(index * 8);
long result = packer.getLong();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putLong(int, long)
*/
@Override
public IOBuffer putLong(int index, long value) {
packer.putLong(index, value, Long.SIZE);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getFloat()
*/
@Override
public float getFloat() {
return packer.getFloat();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putFloat(float)
*/
@Override
public IOBuffer putFloat(float value) {
packer.putFloat(value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getFloat(int)
*/
@Override
public float getFloat(int index) {
packer.mark();
packer.position(index * 8);
float result = packer.getFloat();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putFloat(int, float)
*/
@Override
public IOBuffer putFloat(int index, float value) {
packer.putFloat(index, value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getDouble()
*/
@Override
public double getDouble() {
return packer.getDouble();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putDouble(double)
*/
@Override
public IOBuffer putDouble(double value) {
packer.putDouble(value);
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getDouble(int)
*/
@Override
public double getDouble(int index) {
packer.mark();
packer.position(index * 8);
double result = packer.getDouble();
packer.reset();
return result;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putDouble(int, double)
*/
@Override
public IOBuffer putDouble(int index, double value) {
packer.putDouble(index, value);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putBooleanBit(boolean)
*/
@Override
public IOBuffer putBooleanBit(boolean value) {
packer.putBoolean(value);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putLongBits(long, int)
*/
@Override
public IOBuffer putLongBits(long value, int numberOfBits) {
packer.putLong(value, numberOfBits);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putByteBits(byte, int)
*/
@Override
public IOBuffer putByteBits(byte value, int numberOfBits) {
packer.putByte(value, numberOfBits);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putShortBits(short, int)
*/
@Override
public IOBuffer putShortBits(short value, int numberOfBits) {
packer.putShort(value, numberOfBits);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putIntBits(int, int)
*/
@Override
public IOBuffer putIntBits(int value, int numberOfBits) {
packer.putInteger(value, numberOfBits);
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getBooleanBit()
*/
@Override
public boolean getBooleanBit() {
return packer.getBoolean();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getByteBits()
*/
@Override
public byte getByteBits() {
return packer.getByte();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getByteBits(int)
*/
@Override
public byte getByteBits(int numberOfBits) {
return packer.getByte(numberOfBits);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getShortBits()
*/
@Override
public short getShortBits() {
return packer.getShort();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getShortBits(int)
*/
@Override
public short getShortBits(int numberOfBits) {
return packer.getShort(numberOfBits);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getIntBits()
*/
@Override
public int getIntBits() {
return packer.getInteger();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getIntBits(int)
*/
@Override
public int getIntBits(int numberOfBits) {
return packer.getInteger(numberOfBits);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getLongBits()
*/
@Override
public long getLongBits() {
return packer.getLong();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getLongBits(int)
*/
@Override
public long getLongBits(int numberOfBits) {
return packer.getLong(numberOfBits);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitPosition(int)
*/
@Override
public int bitPosition(int position) {
return packer.position(position);
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitPosition()
*/
@Override
public int bitPosition() {
return packer.position();
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitCapacity()
*/
@Override
public int bitCapacity() {
return packer.getNumberOfBits();
}
}
| 15,833 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MessageHeader.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/MessageHeader.java | /*
* see license.txt
*/
package harenet;
import harenet.messages.ConnectionAcceptedMessage;
import harenet.messages.ConnectionRequestMessage;
import harenet.messages.DisconnectMessage;
import harenet.messages.HeartbeatMessage;
import harenet.messages.Message;
import harenet.messages.NetMessageFactory;
import harenet.messages.PingMessage;
import harenet.messages.PongMessage;
import harenet.messages.ReliableNetMessage;
import harenet.messages.ServerFullMessage;
import harenet.messages.UnReliableNetMessage;
/**
* The Harenet protocol message headers. Serves as a means for
* creating Harenet messages.
*
* @author Tony
*
*/
public class MessageHeader {
public static final byte CONNECTION_REQUEST_MESSAGE = 1;
public static final byte CONNECTION_ACCEPTED_MESSAGE = 2;
public static final byte DISCONNECT_MESSAGE = 3;
public static final byte SERVER_FULL_MESSAGE = 4;
public static final byte HEARTBEAT_MESSAGE = 5;
public static final byte PING_MESSAGE = 6;
public static final byte PONG_MESSAGE = 7;
// messages past this must have a NetMessage Attached
public static final byte RELIABLE_NETMESSAGE = 8;
public static final byte UNRELIABLE_NETMESSAGE = 9;
/**
* Reads the buffer to determine what Message to allocate.
*
* @param buf
* @param messageFactory
* @return the Message;
*/
public static Message readMessageHeader(IOBuffer buf, NetMessageFactory messageFactory) {
Message message = null;
byte messageType = buf.getByte();
switch(messageType) {
case CONNECTION_REQUEST_MESSAGE: {
message = new ConnectionRequestMessage();
break;
}
case CONNECTION_ACCEPTED_MESSAGE: {
message = new ConnectionAcceptedMessage();
break;
}
case DISCONNECT_MESSAGE: {
message = new DisconnectMessage();
break;
}
case SERVER_FULL_MESSAGE: {
message = new ServerFullMessage();
break;
}
case RELIABLE_NETMESSAGE: {
message = new ReliableNetMessage();
break;
}
case UNRELIABLE_NETMESSAGE: {
message = new UnReliableNetMessage();
break;
}
case HEARTBEAT_MESSAGE: {
message = HeartbeatMessage.INSTANCE;
break;
}
case PING_MESSAGE: {
message = PingMessage.INSTANCE;
break;
}
case PONG_MESSAGE: {
message = PongMessage.INSTANCE;
break;
}
}
message.readFrom(buf, messageFactory);
return message;
}
}
| 2,891 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SysoutLog.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/SysoutLog.java | /*
* see license.txt
*/
package harenet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Simple <code>System.out</code> implementation of the {@link Log} interface.
*
* @author Tony
*
*/
public class SysoutLog implements Log {
private boolean enabled;
private static final DateFormat format = new SimpleDateFormat("HH:mm:ss SSSS");
/**
*
*/
public SysoutLog() {
this.enabled = false;
}
/* (non-Javadoc)
* @see netspark.Log#enabled()
*/
@Override
public boolean enabled() {
return this.enabled;
}
/* (non-Javadoc)
* @see netspark.Log#setEnabled(boolean)
*/
@Override
public void setEnabled(boolean enable) {
this.enabled = enable;
}
/* (non-Javadoc)
* @see netspark.Log#debug(java.lang.String)
*/
@Override
public void debug(String msg) {
if(this.enabled||true) {
System.out.println(format.format(new Date()) + ":" + msg);
}
}
/* (non-Javadoc)
* @see netspark.Log#error(java.lang.String)
*/
@Override
public void error(String msg) {
if(this.enabled) {
System.out.println(format.format(new Date()) + ": *** " + msg);
}
}
/* (non-Javadoc)
* @see netspark.Log#info(java.lang.String)
*/
@Override
public void info(String msg) {
if(this.enabled) {
System.out.println(format.format(new Date()) + ":" +msg);
}
}
}
| 1,539 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BitPacker.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/BitPacker.java | /*
* see license.txt
*/
package harenet;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
/**
* Special thanks to: http://www.shadebob.org/posts/bit-packing-in-java
* for the implementation https://gist.github.com/cobolfoo/0c4124308e7cc05d82b8
*
* @author Tony
*
*/
public class BitPacker {
private BitArray data;
private int numBits;
private int position;
private int mark;
private int limit;
/**
* @param initialSizeInBits the initial size of the bit set
*/
public BitPacker(int initialSizeInBits, int limit) {
this.data = new BitArray(initialSizeInBits);
this.numBits = 0;
this.position = 0;
this.mark = 0;
this.limit = limit;
}
/**
*/
public BitPacker() {
this(1500*8, 1500*8);
}
/**
* @return the limit
*/
public int limit() {
return limit;
}
public void limit(int limit) {
this.limit = limit;
}
/**
* The number of isRotated this {@link BitPacker} is currently using.
*
* @return The number of isRotated this {@link BitPacker} is currently using.
*/
public int getNumberOfBits() {
return this.numBits;
}
/**
* The number of bytes this {@link BitPacker} is currently using.
*
* @return The number of bytes this {@link BitPacker} is currently using.
*/
public int getNumberOfBytes() {
int remainder = (this.numBits % 8 > 0) ? 1 : 0;
return (this.numBits / 8) + remainder;
}
/**
* Clears the {@link BitPacker} so that it can be reused.
* @return this object for method chaining
*/
public BitPacker clear() {
this.data.clear();
this.numBits = 0;
this.position = 0;
this.mark = 0;
return this;
}
/**
* Rewinds the read position to the beginning
* @return this object for method chaining
*/
public BitPacker rewind() {
this.position = 0;
this.mark = 0;
return this;
}
public BitPacker flip() {
this.limit = this.position;
this.position = 0;
this.mark = 0;
return this;
}
/**
* @return the current read position
*/
public int position() {
return this.position;
}
public int remaining() {
return this.limit - this.position;
}
public boolean hasRemaining() {
return remaining() > 0;
}
/**
* Sets the new Read position
* @param newPosition
* @return the previous read position
*/
public int position(int newPosition) {
int previous = this.position;
this.position = newPosition;
if(newPosition>this.limit) {
throw new IndexOutOfBoundsException();
}
return previous;
}
/**
* Mark the current read position
* @return this object for method chaining
*/
public BitPacker mark() {
this.mark = this.position;
return this;
}
/**
* Resets the read position to the mark position
*
* @return this object for method chaining
*/
public BitPacker reset() {
this.position = this.mark;
return this;
}
/**
* Converts the {@link BitPacker} into a set of bytes that
* represent the {@link BitPacker}
*
* @return the bytes
*/
public byte[] toBytes() {
pad();
byte[] output = new byte[numBits / 8];
for (int i = 0; i < output.length; i++) {
output[i] = getByte();
}
return output;
}
/**
* Write the bytes from this {@link BitPacker} to the {@link ByteBuffer}
* @param buffer
* @return this object for method chaining
*/
public BitPacker writeTo(ByteBuffer buffer) {
pad();
int numberOfBytes = getNumberOfBytes();
for (int i = 0; i < numberOfBytes; i++) {
buffer.put(getByte());
}
/*
byte[] bytes = data.getData();
for (int i = 0; i < bytes.length; i++) {
buffer.put(bytes[i]);
}
this.position += bytes.length * 8;
*/
return this;
}
/**
* Read from the {@link ByteBuffer} and populate this {@link BitPacker}
*
* @param buffer
* @return this object for method chaining
*/
public BitPacker readFrom(ByteBuffer buffer) {
/*int remaining = buffer.remaining();
if(remaining < data.numberOfBytes()) {
for(int i = 0; i < remaining; i++) {
data.setDataElement(i, buffer.get());
}
}
this.position += remaining * 8;
*/
while(buffer.hasRemaining()) {
putByte(buffer.get());
}
return this;
}
public BitPacker putBits(int position, long value, int numberOfBits) {
if(position + numberOfBits > this.limit) {
throw new BufferOverflowException();
}
for (int i = 0; i < numberOfBits; i++) {
if (((value >> i) & 1) == 1) {
data.setBit(position++, true);
}
else {
data.setBit(position++, false);
}
}
// if we've expanded the buffer, make
// sure to update the numBits
if(position > numBits) {
numBits = position;
}
return this;
}
public BitPacker putBits(long value, int numberOfBits) {
putBits(this.position, value, numberOfBits);
this.position += numberOfBits;
return this;
}
public BitPacker putByte(byte value) {
putByte(value, Byte.SIZE);
return this;
}
public BitPacker putByte(byte value, int length) {
if (length > Byte.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putByte()");
}
return putBits(value, length);
}
public BitPacker putByte(int position, byte value, int length) {
if (length > Byte.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putByte()");
}
return putBits(position, value, length);
}
public BitPacker putShort(short value) {
return putShort(value, Short.SIZE);
}
public BitPacker putShort(short value, int length) {
if (length > Short.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putShort()");
}
return putBits(value, length);
}
public BitPacker putShort(int position, short value, int length) {
if (length > Short.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putShort()");
}
return putBits(position, value, length);
}
public BitPacker putInteger(int value) {
return putInteger(value, Integer.SIZE);
}
public BitPacker putInteger(int value, int length) {
if (length > Integer.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putInteger()");
}
return putBits(value, length);
}
public BitPacker putInteger(int position, int value, int length) {
if (length > Integer.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putInteger()");
}
return putBits(position, value, length);
}
public BitPacker putLong(long value) {
return putLong(value, Long.SIZE);
}
public BitPacker putLong(long value, int length) {
if (length > Long.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putLong()");
}
return putBits(value, length);
}
public BitPacker putLong(int position, long value, int length) {
if (length > Long.SIZE) {
throw new IllegalArgumentException("Invalid length (" + length + ") in putLong()");
}
return putBits(position, value, length);
}
public BitPacker putFloat(float value) {
int raw = Float.floatToRawIntBits(value);
return putBits(raw, Float.SIZE);
}
public BitPacker putFloat(int position, float value) {
int raw = Float.floatToRawIntBits(value);
return putBits(position, raw, Float.SIZE);
}
public BitPacker putDouble(double value) {
long raw = Double.doubleToRawLongBits(value);
return putBits(raw, Double.SIZE);
}
public BitPacker putDouble(int position, double value) {
long raw = Double.doubleToRawLongBits(value);
return putBits(position, raw, Double.SIZE);
}
public BitPacker putBoolean(boolean value) {
if(this.position + 1 > this.limit) {
throw new BufferOverflowException();
}
data.setBit(numBits++, value);
this.position++;
return this;
}
public BitPacker putBoolean(int position, boolean value) {
if(position + 1 > this.limit) {
throw new BufferOverflowException();
}
data.setBit(position, value);
if(position==numBits+1) {
numBits++;
}
return this;
}
public BitPacker putString(String value) {
byte[] payload = value.getBytes();
int length = payload.length;
if (length > 255) {
length = 255;
}
putInteger(length, 8);
putBytes(payload);
return this;
}
public BitPacker putBytes(byte[] value) {
return putBytes(value, 0, value.length);
}
public BitPacker putBytes(byte[] value, int offset, int length) {
for (int i = offset; i < length; i++) {
putByte(value[i]);
}
return this;
}
private void checkPosition() {
if (position > numBits - 1) {
throw new IllegalStateException("Out of bound error, read: " + position + ", numBits: " + numBits);
}
}
public byte getByte() {
return getByte(Byte.SIZE);
}
public byte getByte(int length) {
byte value = 0;
for (int i = 0; i < length; i++) {
value |= (data.getBit(position++) ? 1 : 0) << (i % Byte.SIZE);
}
return value;
}
public short getShort() {
return getShort(Short.SIZE);
}
public short getShort(int length) {
short value = 0;
for (int i = 0; i < length; i++) {
value |= (data.getBit(position++) ? 1 : 0) << (i % Short.SIZE);
}
return value;
}
public int getInteger() {
return getInteger(Integer.SIZE);
}
public int getInteger(int length) {
int value = 0;
for (int i = 0; i < length; i++) {
checkPosition();
value |= (data.getBit(position++) ? 1 : 0) << (i % Integer.SIZE);
}
return value;
}
public long getLong() {
return getLong(Long.SIZE);
}
public long getLong(int length) {
long value = 0;
for (int i = 0; i < length; i++) {
checkPosition();
value |= (data.getBit(position++) ? 1L : 0L) << (i % Long.SIZE);
}
return value;
}
public float getFloat() {
return getFloat(Float.SIZE);
}
public float getFloat(int length) {
int value = 0;
for (int i = 0; i < length; i++) {
checkPosition();
value |= (data.getBit(position++) ? 1 : 0) << (i % Float.SIZE);
}
return Float.intBitsToFloat(value);
}
public double getDouble() {
return getDouble(Double.SIZE);
}
public double getDouble(int length) {
long value = 0;
for (int i = 0; i < length; i++) {
checkPosition();
value |= (data.getBit(position++) ? 1L : 0L) << (i % Double.SIZE);
}
return Double.longBitsToDouble(value);
}
public boolean getBoolean() {
checkPosition();
return data.getBit(position++);
}
public byte[] getBytes(int length) {
byte[] output = new byte[length];
return getBytes(output, 0, length);
}
public byte[] getBytes(byte[] bytes, int offset, int length) {
for (int i = 0; i < length; i++) {
bytes[offset + i] = getByte();
}
return bytes;
}
public String getString() {
int length = getInteger(8);
byte[] payload = getBytes(length);
return new String(payload);
}
/**
* Fill out the remaining isRotated with 0
*
* @return
*/
public BitPacker pad() {
int leftOvers = (numBits % 8);
if(leftOvers > 0) {
int remaining = 8 - leftOvers;
for (int i = 0; i < remaining; i++) {
putBoolean(numBits, false);
}
}
return this;
}
public static void dumpBytes(byte[] value) {
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))");
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
int count = 0;
for (int j = 0; j < value.length; j++) {
byte v = value[j];
for (int i = 0; i < Byte.SIZE; i++) {
if (((v >> i) & 1) == 1) {
System.out.print("1");
}
else {
System.out.print("0");
}
}
System.out.print(" ");
count++;
if (count == 12) {
System.out.println();
count = 0;
}
}
System.out.println();
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
}
public void dump() {
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
System.out.println("| Dumping bitset, length: " + numBits);
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
int count = 0;
for (int i = 0; i < numBits; i++) {
System.out.print(data.getBit(i) ? "1" : "0");
if ((i != 0) && (i % 8 == 7)) {
System.out.print(" ");
count++;
if (count == 12) {
System.out.println();
count = 0;
}
}
}
System.out.println();
System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --");
}
} | 15,200 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
NetworkDisruptor.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/NetworkDisruptor.java | /*
* see license.txt
*/
package harenet;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Create network hooks to mimic a disrupted network connection (dropping packets, or delaying them)
*
* @author Tony
*
*/
public class NetworkDisruptor {
public static void main(String[] args) throws Exception {
int proxyPort = 9843;
int minLatency = 50;
int maxLatency = 100;
int dropPercentage = 5;
NetworkDisruptor proxy = new NetworkDisruptor(new InetSocketAddress("localhost", 9845),
proxyPort,
minLatency,
maxLatency,
dropPercentage);
proxy.run();
}
static class Packet {
DatagramPacket packet;
long receivedTime;
public Packet(DatagramPacket packet) {
this.packet = packet;
this.receivedTime = System.currentTimeMillis();
}
}
private DatagramChannel proxySocket;
private AtomicBoolean isRunning;
private ByteBuffer recvBuffer;
private ByteBuffer writeBuffer;
private InetSocketAddress proxiedServerAddress;
private SocketAddress proxiedClientAddress;
private List<Packet> pendingClientSendPackets;
private List<Packet> pendingServerSendPackets;
private int proxyPort;
private int minLatency, maxLatency;
private int dropPrecentage;
private int biggestPacketSize;
private Random random;
public NetworkDisruptor(InetSocketAddress proxiedServerAddress,
int proxyPort,
int minLatency,
int maxLatency,
int dropPercentage) {
this.proxyPort = proxyPort;
this.minLatency = minLatency / 2; // we delay both server and client
this.maxLatency = maxLatency / 2;
this.dropPrecentage = dropPercentage;
this.isRunning = new AtomicBoolean(false);
this.recvBuffer = ByteBuffer.allocate(1500);
this.writeBuffer = ByteBuffer.allocate(1500);
this.proxiedServerAddress = proxiedServerAddress;
this.pendingClientSendPackets = new LinkedList<>();
this.pendingServerSendPackets = new LinkedList<>();
this.random = new Random();
}
public void run() throws Exception {
if(this.isRunning.get()) {
return;
}
this.isRunning.set(true);
this.proxySocket = DatagramChannel.open();
this.proxySocket.configureBlocking(false);
this.proxySocket.bind(new InetSocketAddress("localhost", this.proxyPort));
System.out.println("Proxy server started on " + this.proxySocket.getLocalAddress());
while(this.isRunning.get()) {
this.recvBuffer.clear();
SocketAddress remoteAddr = this.proxySocket.receive(this.recvBuffer);
if(remoteAddr != null) {
System.out.println("Received message from: " + remoteAddr);
this.recvBuffer.flip();
byte[] buf = copy(this.recvBuffer);
DatagramPacket packet = new DatagramPacket(buf, buf.length, remoteAddr);
Packet p = new Packet(packet);
if(this.proxiedServerAddress.equals(remoteAddr)) {
this.pendingServerSendPackets.add(p);
}
else {
this.proxiedClientAddress = remoteAddr;
this.pendingClientSendPackets.add(p);
}
}
sendPackets(this.pendingServerSendPackets, this.proxiedClientAddress);
sendPackets(this.pendingClientSendPackets, this.proxiedServerAddress);
}
}
private byte[] copy(ByteBuffer buf) {
int limit = buf.limit();
byte[] cpy = new byte[limit];
buf.get(cpy, 0, limit);
return cpy;
}
private void sendPackets(List<Packet> pendingPackets, SocketAddress sendTo) throws Exception {
final long now = System.currentTimeMillis();
final int latencyFuzz = this.maxLatency - this.minLatency;
List<Packet> remove = new ArrayList<>();
for(int i = 0; i < pendingPackets.size(); i++) {
Packet packet = pendingPackets.get(i);
long timePassed = now - packet.receivedTime;
if( (timePassed - this.random.nextInt(latencyFuzz)) > this.minLatency) {
remove.add(packet);
int dropPacket = this.random.nextInt(100);
if(dropPacket < this.dropPrecentage) {
System.out.println("*** Dropping packet from: " + packet.packet.getSocketAddress() + " to " + sendTo);
continue;
}
System.out.print("Sending packet from: " + packet.packet.getSocketAddress() + " to " + sendTo);
this.writeBuffer.clear();
this.writeBuffer.put(packet.packet.getData(), packet.packet.getOffset(), packet.packet.getLength());
this.writeBuffer.flip();
int sentBytes = this.proxySocket.send(this.writeBuffer, sendTo);
System.out.println(" => " + sentBytes + " bytes");
if(sentBytes > this.biggestPacketSize) {
this.biggestPacketSize = sentBytes;
System.out.println("^^^ High water mark packet size => " + this.biggestPacketSize);
}
}
}
for(Packet p: remove) {
pendingPackets.remove(p);
}
}
}
| 6,209 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Transmittable.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Transmittable.java | /*
* see license.txt
*/
package harenet;
import harenet.messages.NetMessageFactory;
/**
* Internal interface for Harenet protocol level message transferring.
*
* @author Tony
*
*/
public interface Transmittable {
/**
* Writes the contents of this message to the buffer
* @param buffer
*/
public void writeTo(IOBuffer buffer);
/**
* Reads from the buffer
*
* @param buffer
* @param messageFactory
*/
public void readFrom(IOBuffer buffer, NetMessageFactory messageFactory);
}
| 554 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
IOBuffer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/IOBuffer.java | /*
* see license.txt
*/
package harenet;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.InvalidMarkException;
import java.nio.ReadOnlyBufferException;
/**
* A means for doing Input/Output on a buffer.
*
* @author Tony
*
*/
public interface IOBuffer {
/**
* Simple factory methods
*
* @author Tony
*
*/
public static class Factory {
public static IOBuffer allocateDirect(int size) {
return new ByteBufferIOBuffer(ByteBuffer.allocateDirect(size));
}
public static IOBuffer allocate(int size) {
return new ByteBufferIOBuffer(ByteBuffer.allocate(size));
}
public static IOBuffer wrap(byte[] buff) {
return new ByteBufferIOBuffer(ByteBuffer.wrap(buff));
}
public static IOBuffer wrap(byte[] buff, int offset, int len) {
return new ByteBufferIOBuffer(ByteBuffer.wrap(buff, offset, len));
}
}
public IOBuffer receiveSync();
public IOBuffer sendSync();
/**
* @return the underlying {@link ByteBuffer}
*/
public ByteBuffer asByteBuffer();
/**
* Creates a new byte buffer whose content is a shared subsequence of
* this buffer's content.
*
* <p> The content of the new buffer will start at this buffer's current
* position. Changes to this buffer's content will be visible in the new
* buffer, and vice versa; the two buffers' position, limit, and mark
* values will be independent.
*
* <p> The new buffer's position will be zero, its capacity and its limit
* will be the number of bytes remaining in this buffer, and its mark
* will be undefined. The new buffer will be direct if, and only if, this
* buffer is direct, and it will be read-only if, and only if, this buffer
* is read-only. </p>
*
* @return The new byte buffer
*/
public abstract IOBuffer slice();
/**
* Creates a new byte buffer that shares this buffer's content.
*
* <p> The content of the new buffer will be that of this buffer. Changes
* to this buffer's content will be visible in the new buffer, and vice
* versa; the two buffers' position, limit, and mark values will be
* independent.
*
* <p> The new buffer's capacity, limit, position, and mark values will be
* identical to those of this buffer. The new buffer will be direct if,
* and only if, this buffer is direct, and it will be read-only if, and
* only if, this buffer is read-only. </p>
*
* @return The new byte buffer
*/
public abstract IOBuffer duplicate();
/**
* Creates a new, read-only byte buffer that shares this buffer's
* content.
*
* <p> The content of the new buffer will be that of this buffer. Changes
* to this buffer's content will be visible in the new buffer; the new
* buffer itself, however, will be read-only and will not allow the shared
* content to be modified. The two buffers' position, limit, and mark
* values will be independent.
*
* <p> The new buffer's capacity, limit, position, and mark values will be
* identical to those of this buffer.
*
* <p> If this buffer is itself read-only then this method behaves in
* exactly the same way as the {@link #duplicate duplicate} method. </p>
*
* @return The new, read-only byte buffer
*/
public abstract IOBuffer asReadOnlyBuffer();
// -- Singleton get/put methods --
/**
* Relative <i>get</i> method. Reads the byte at this buffer's
* current position, and then increments the position. </p>
*
* @return The byte at the buffer's current position
*
* @throws BufferUnderflowException
* If the buffer's current position is not smaller than its limit
*/
public abstract byte getByte();
public abstract int getUnsignedByte();
public abstract IOBuffer putUnsignedByte(int b);
/**
* Relative <i>put</i> method <i>(optional operation)</i>.
*
* <p> Writes the given byte into this buffer at the current
* position, and then increments the position. </p>
*
* @param b
* The byte to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If this buffer's current position is not smaller than its limit
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putByte(byte b);
/**
* Absolute <i>get</i> method. Reads the byte at the given
* index. </p>
*
* @param index
* The index from which the byte will be read
*
* @return The byte at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit
*/
public abstract byte getByte(int index);
/**
* Absolute <i>put</i> method <i>(optional operation)</i>.
*
* <p> Writes the given byte into this buffer at the given
* index. </p>
*
* @param index
* The index at which the byte will be written
*
* @param b
* The byte value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putByte(int index, byte b);
// -- Bulk get operations --
/**
* Relative bulk <i>get</i> method.
*
* <p> This method transfers bytes from this buffer into the given
* destination array. If there are fewer bytes remaining in the
* buffer than are required to satisfy the request, that is, if
* <tt>length</tt> <tt>></tt> <tt>remaining()</tt>, then no
* bytes are transferred and a {@link BufferUnderflowException} is
* thrown.
*
* <p> Otherwise, this method copies <tt>length</tt> bytes from this
* buffer into the given array, starting at the current position of this
* buffer and at the given offset in the array. The position of this
* buffer is then incremented by <tt>length</tt>.
*
* <p> In other words, an invocation of this method of the form
* <tt>src.get(dst, off, len)</tt> has exactly the same effect as
* the loop
*
* <pre>
* for (int i = off; i < off + len; i++)
* dst[i] = src.get(); </pre>
*
* except that it first checks that there are sufficient bytes in
* this buffer and it is potentially much more efficient. </p>
*
* @param dst
* The array into which bytes are to be written
*
* @param offset
* The offset within the array of the first byte to be
* written; must be non-negative and no larger than
* <tt>dst.length</tt>
*
* @param length
* The maximum number of bytes to be written to the given
* array; must be non-negative and no larger than
* <tt>dst.length - offset</tt>
*
* @return This buffer
*
* @throws BufferUnderflowException
* If there are fewer than <tt>length</tt> bytes
* remaining in this buffer
*
* @throws IndexOutOfBoundsException
* If the preconditions on the <tt>offset</tt> and <tt>length</tt>
* parameters do not hold
*/
public IOBuffer getBytes(byte[] dst, int offset, int length);
/**
* Relative bulk <i>get</i> method.
*
* <p> This method transfers bytes from this buffer into the given
* destination array. An invocation of this method of the form
* <tt>src.get(a)</tt> behaves in exactly the same way as the invocation
*
* <pre>
* src.get(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferUnderflowException
* If there are fewer than <tt>length</tt> bytes
* remaining in this buffer
*/
public IOBuffer getBytes(byte[] dst);
// -- Bulk put operations --
/**
* Relative bulk <i>put</i> method <i>(optional operation)</i>.
*
* <p> This method transfers the bytes remaining in the given source
* buffer into this buffer. If there are more bytes remaining in the
* source buffer than in this buffer, that is, if
* <tt>src.remaining()</tt> <tt>></tt> <tt>remaining()</tt>,
* then no bytes are transferred and a {@link
* BufferOverflowException} is thrown.
*
* <p> Otherwise, this method copies
* <i>n</i> = <tt>src.remaining()</tt> bytes from the given
* buffer into this buffer, starting at each buffer's current position.
* The positions of both buffers are then incremented by <i>n</i>.
*
* <p> In other words, an invocation of this method of the form
* <tt>dst.put(src)</tt> has exactly the same effect as the loop
*
* <pre>
* while (src.hasRemaining())
* dst.put(src.get()); </pre>
*
* except that it first checks that there is sufficient space in this
* buffer and it is potentially much more efficient. </p>
*
* @param src
* The source buffer from which bytes are to be read;
* must not be this buffer
*
* @return This buffer
*
* @throws BufferOverflowException
* If there is insufficient space in this buffer
* for the remaining bytes in the source buffer
*
* @throws IllegalArgumentException
* If the source buffer is this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public IOBuffer put(IOBuffer src);
/**
* Relative bulk <i>put</i> method <i>(optional operation)</i>.
*
* <p> This method transfers bytes into this buffer from the given
* source array. If there are more bytes to be copied from the array
* than remain in this buffer, that is, if
* <tt>length</tt> <tt>></tt> <tt>remaining()</tt>, then no
* bytes are transferred and a {@link BufferOverflowException} is
* thrown.
*
* <p> Otherwise, this method copies <tt>length</tt> bytes from the
* given array into this buffer, starting at the given offset in the array
* and at the current position of this buffer. The position of this buffer
* is then incremented by <tt>length</tt>.
*
* <p> In other words, an invocation of this method of the form
* <tt>dst.put(src, off, len)</tt> has exactly the same effect as
* the loop
*
* <pre>
* for (int i = off; i < off + len; i++)
* dst.put(a[i]); </pre>
*
* except that it first checks that there is sufficient space in this
* buffer and it is potentially much more efficient. </p>
*
* @param src
* The array from which bytes are to be read
*
* @param offset
* The offset within the array of the first byte to be read;
* must be non-negative and no larger than <tt>array.length</tt>
*
* @param length
* The number of bytes to be read from the given array;
* must be non-negative and no larger than
* <tt>array.length - offset</tt>
*
* @return This buffer
*
* @throws BufferOverflowException
* If there is insufficient space in this buffer
*
* @throws IndexOutOfBoundsException
* If the preconditions on the <tt>offset</tt> and <tt>length</tt>
* parameters do not hold
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public IOBuffer putBytes(byte[] src, int offset, int length);
/**
* Relative bulk <i>put</i> method <i>(optional operation)</i>.
*
* <p> This method transfers the entire content of the given source
* byte array into this buffer. An invocation of this method of the
* form <tt>dst.put(a)</tt> behaves in exactly the same way as the
* invocation
*
* <pre>
* dst.put(a, 0, a.length) </pre>
*
* @return This buffer
*
* @throws BufferOverflowException
* If there is insufficient space in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public IOBuffer putBytes(byte[] src);
// -- Other stuff --
/**
* Tells whether or not this buffer is backed by an accessible byte
* array.
*
* <p> If this method returns <tt>true</tt> then the {@link #array() array}
* and {@link #arrayOffset() arrayOffset} methods may safely be invoked.
* </p>
*
* @return <tt>true</tt> if, and only if, this buffer
* is backed by an array and is not read-only
*/
public boolean hasArray();
/**
* Returns the byte array that backs this
* buffer <i>(optional operation)</i>.
*
* <p> Modifications to this buffer's content will cause the returned
* array's content to be modified, and vice versa.
*
* <p> Invoke the {@link #hasArray hasArray} method before invoking this
* method in order to ensure that this buffer has an accessible backing
* array. </p>
*
* @return The array that backs this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is backed by an array but is read-only
*
* @throws UnsupportedOperationException
* If this buffer is not backed by an accessible array
*/
public byte[] array() ;
/**
* Returns the offset within this buffer's backing array of the first
* element of the buffer <i>(optional operation)</i>.
*
* <p> If this buffer is backed by an array then buffer position <i>p</i>
* corresponds to array index <i>p</i> + <tt>arrayOffset()</tt>.
*
* <p> Invoke the {@link #hasArray hasArray} method before invoking this
* method in order to ensure that this buffer has an accessible backing
* array. </p>
*
* @return The offset within this buffer's array
* of the first element of the buffer
*
* @throws ReadOnlyBufferException
* If this buffer is backed by an array but is read-only
*
* @throws UnsupportedOperationException
* If this buffer is not backed by an accessible array
*/
public int arrayOffset();
/**
* Compacts this buffer <i>(optional operation)</i>.
*
* <p> The bytes between the buffer's current position and its limit,
* if any, are copied to the beginning of the buffer. That is, the
* byte at index <i>p</i> = <tt>position()</tt> is copied
* to index zero, the byte at index <i>p</i> + 1 is copied
* to index one, and so forth until the byte at index
* <tt>limit()</tt> - 1 is copied to index
* <i>n</i> = <tt>limit()</tt> - <tt>1</tt> - <i>p</i>.
* The buffer's position is then set to <i>n+1</i> and its limit is set to
* its capacity. The mark, if defined, is discarded.
*
* <p> The buffer's position is set to the number of bytes copied,
* rather than to zero, so that an invocation of this method can be
* followed immediately by an invocation of another relative <i>put</i>
* method. </p>
*
*
* <p> Invoke this method after writing data from a buffer in case the
* write was incomplete. The following loop, for example, copies bytes
* from one channel to another via the buffer <tt>buf</tt>:
*
* <blockquote><pre>
* buf.clear(); // Prepare buffer for use
* while (in.read(buf) >= 0 || buf.position != 0) {
* buf.flip();
* out.write(buf);
* buf.compact(); // In case of partial write
* }</pre></blockquote>
*
*
* @return This buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer compact();
/**
* Tells whether or not this byte buffer is direct. </p>
*
* @return <tt>true</tt> if, and only if, this buffer is direct
*/
public abstract boolean isDirect();
/**
* Returns this buffer's capacity. </p>
*
* @return The capacity of this buffer
*/
public int capacity();
/**
* Returns this buffer's position. </p>
*
* @return The position of this buffer
*/
public int position();
/**
* Sets this buffer's position. If the mark is defined and larger than the
* new position then it is discarded. </p>
*
* @param newPosition
* The new position value; must be non-negative
* and no larger than the current limit
*
* @return This buffer
*
* @throws IllegalArgumentException
* If the preconditions on <tt>newPosition</tt> do not hold
*/
public IOBuffer position(int newPosition);
/**
* Returns this buffer's limit. </p>
*
* @return The limit of this buffer
*/
public int limit();
/**
* Sets this buffer's limit. If the position is larger than the new limit
* then it is set to the new limit. If the mark is defined and larger than
* the new limit then it is discarded. </p>
*
* @param newLimit
* The new limit value; must be non-negative
* and no larger than this buffer's capacity
*
* @return This buffer
*
* @throws IllegalArgumentException
* If the preconditions on <tt>newLimit</tt> do not hold
*/
public IOBuffer limit(int newLimit) ;
/**
* Sets this buffer's mark at its position. </p>
*
* @return This buffer
*/
public IOBuffer mark();
/**
* Resets this buffer's position to the previously-marked position.
*
* <p> Invoking this method neither changes nor discards the mark's
* value. </p>
*
* @return This buffer
*
* @throws InvalidMarkException
* If the mark has not been set
*/
public IOBuffer reset();
/**
* Clears this buffer. The position is set to zero, the limit is set to
* the capacity, and the mark is discarded.
*
* <p> Invoke this method before using a sequence of channel-read or
* <i>put</i> operations to fill this buffer. For example:
*
* <blockquote><pre>
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data</pre></blockquote>
*
* <p> This method does not actually erase the data in the buffer, but it
* is named as if it did because it will most often be used in situations
* in which that might as well be the case. </p>
*
* @return This buffer
*/
public IOBuffer clear();
/**
* Flips this buffer. The limit is set to the current position and then
* the position is set to zero. If the mark is defined then it is
* discarded.
*
* <p> After a sequence of channel-read or <i>put</i> operations, invoke
* this method to prepare for a sequence of channel-write or relative
* <i>get</i> operations. For example:
*
* <blockquote><pre>
* buf.put(magic); // Prepend header
* in.read(buf); // Read data into rest of buffer
* buf.flip(); // Flip buffer
* out.write(buf); // Write header + data to channel</pre></blockquote>
*
* <p> This method is often used in conjunction with the {@link
* java.nio.IOBuffer#compact compact} method when transferring data from
* one place to another. </p>
*
* @return This buffer
*/
public IOBuffer flip();
/**
* Rewinds this buffer. The position is set to zero and the mark is
* discarded.
*
* <p> Invoke this method before a sequence of channel-write or <i>get</i>
* operations, assuming that the limit has already been set
* appropriately. For example:
*
* <blockquote><pre>
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array</pre></blockquote>
*
* @return This buffer
*/
public IOBuffer rewind();
/**
* Returns the number of elements between the current position and the
* limit. </p>
*
* @return The number of elements remaining in this buffer
*/
public int remaining();
/**
* Tells whether there are any elements between the current position and
* the limit. </p>
*
* @return <tt>true</tt> if, and only if, there is at least one element
* remaining in this buffer
*/
public boolean hasRemaining();
/**
* Tells whether or not this buffer is read-only. </p>
*
* @return <tt>true</tt> if, and only if, this buffer is read-only
*/
public abstract boolean isReadOnly();
/**
* Relative <i>get</i> method for reading a char value.
*
* <p> Reads the next two bytes at this buffer's current position,
* composing them into a char value according to the current byte order,
* and then increments the position by two. </p>
*
* @return The char value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than two bytes
* remaining in this buffer
*/
//public abstract char getChar();
/**
* Relative <i>put</i> method for writing a char
* value <i>(optional operation)</i>.
*
* <p> Writes two bytes containing the given char value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by two. </p>
*
* @param value
* The char value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than two bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
//public abstract IOBuffer putChar(char value);
/**
* Absolute <i>get</i> method for reading a char value.
*
* <p> Reads two bytes at the given index, composing them into a
* char value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The char value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus one
*/
//public abstract char getChar(int index);
/**
* Absolute <i>put</i> method for writing a char
* value <i>(optional operation)</i>.
*
* <p> Writes two bytes containing the given char value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The char value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus one
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
//public abstract IOBuffer putChar(int index, char value);
/**
* Relative <i>get</i> method for reading a short value.
*
* <p> Reads the next two bytes at this buffer's current position,
* composing them into a short value according to the current byte order,
* and then increments the position by two. </p>
*
* @return The short value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than two bytes
* remaining in this buffer
*/
public abstract short getShort();
/**
* Relative <i>put</i> method for writing a short
* value <i>(optional operation)</i>.
*
* <p> Writes two bytes containing the given short value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by two. </p>
*
* @param value
* The short value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than two bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putShort(short value);
/**
* Absolute <i>get</i> method for reading a short value.
*
* <p> Reads two bytes at the given index, composing them into a
* short value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The short value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus one
*/
public abstract short getShort(int index);
/**
* Absolute <i>put</i> method for writing a short
* value <i>(optional operation)</i>.
*
* <p> Writes two bytes containing the given short value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The short value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus one
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putShort(int index, short value);
/**
* Relative <i>get</i> method for reading an int value.
*
* <p> Reads the next four bytes at this buffer's current position,
* composing them into an int value according to the current byte order,
* and then increments the position by four. </p>
*
* @return The int value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than four bytes
* remaining in this buffer
*/
public abstract int getInt();
/**
* Relative <i>put</i> method for writing an int
* value <i>(optional operation)</i>.
*
* <p> Writes four bytes containing the given int value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by four. </p>
*
* @param value
* The int value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than four bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putInt(int value);
/**
* Absolute <i>get</i> method for reading an int value.
*
* <p> Reads four bytes at the given index, composing them into a
* int value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The int value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus three
*/
public abstract int getInt(int index);
/**
* Absolute <i>put</i> method for writing an int
* value <i>(optional operation)</i>.
*
* <p> Writes four bytes containing the given int value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The int value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus three
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putInt(int index, int value);
/**
* Relative <i>get</i> method for reading a long value.
*
* <p> Reads the next eight bytes at this buffer's current position,
* composing them into a long value according to the current byte order,
* and then increments the position by eight. </p>
*
* @return The long value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than eight bytes
* remaining in this buffer
*/
public abstract long getLong();
/**
* Relative <i>put</i> method for writing a long
* value <i>(optional operation)</i>.
*
* <p> Writes eight bytes containing the given long value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by eight. </p>
*
* @param value
* The long value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than eight bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putLong(long value);
/**
* Absolute <i>get</i> method for reading a long value.
*
* <p> Reads eight bytes at the given index, composing them into a
* long value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The long value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus seven
*/
public abstract long getLong(int index);
/**
* Absolute <i>put</i> method for writing a long
* value <i>(optional operation)</i>.
*
* <p> Writes eight bytes containing the given long value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The long value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus seven
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putLong(int index, long value);
/**
* Relative <i>get</i> method for reading a float value.
*
* <p> Reads the next four bytes at this buffer's current position,
* composing them into a float value according to the current byte order,
* and then increments the position by four. </p>
*
* @return The float value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than four bytes
* remaining in this buffer
*/
public abstract float getFloat();
/**
* Relative <i>put</i> method for writing a float
* value <i>(optional operation)</i>.
*
* <p> Writes four bytes containing the given float value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by four. </p>
*
* @param value
* The float value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than four bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putFloat(float value);
/**
* Absolute <i>get</i> method for reading a float value.
*
* <p> Reads four bytes at the given index, composing them into a
* float value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The float value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus three
*/
public abstract float getFloat(int index);
/**
* Absolute <i>put</i> method for writing a float
* value <i>(optional operation)</i>.
*
* <p> Writes four bytes containing the given float value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The float value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus three
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putFloat(int index, float value);
/**
* Relative <i>get</i> method for reading a double value.
*
* <p> Reads the next eight bytes at this buffer's current position,
* composing them into a double value according to the current byte order,
* and then increments the position by eight. </p>
*
* @return The double value at the buffer's current position
*
* @throws BufferUnderflowException
* If there are fewer than eight bytes
* remaining in this buffer
*/
public abstract double getDouble();
/**
* Relative <i>put</i> method for writing a double
* value <i>(optional operation)</i>.
*
* <p> Writes eight bytes containing the given double value, in the
* current byte order, into this buffer at the current position, and then
* increments the position by eight. </p>
*
* @param value
* The double value to be written
*
* @return This buffer
*
* @throws BufferOverflowException
* If there are fewer than eight bytes
* remaining in this buffer
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putDouble(double value);
/**
* Absolute <i>get</i> method for reading a double value.
*
* <p> Reads eight bytes at the given index, composing them into a
* double value according to the current byte order. </p>
*
* @param index
* The index from which the bytes will be read
*
* @return The double value at the given index
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus seven
*/
public abstract double getDouble(int index);
/**
* Absolute <i>put</i> method for writing a double
* value <i>(optional operation)</i>.
*
* <p> Writes eight bytes containing the given double value, in the
* current byte order, into this buffer at the given index. </p>
*
* @param index
* The index at which the bytes will be written
*
* @param value
* The double value to be written
*
* @return This buffer
*
* @throws IndexOutOfBoundsException
* If <tt>index</tt> is negative
* or not smaller than the buffer's limit,
* minus seven
*
* @throws ReadOnlyBufferException
* If this buffer is read-only
*/
public abstract IOBuffer putDouble(int index, double value);
/*
* Bit operations
*/
/**
* Places the number of isRotated into the buffer.
*
* @param value the value to store (must fit within the supplied number of isRotated)
* @param numberOfBits the number of isRotated to write out
* @return this buffer
*/
public abstract IOBuffer putBooleanBit(boolean value);
public abstract IOBuffer putLongBits(long value, int numberOfBits);
public abstract IOBuffer putByteBits(byte value, int numberOfBits);
public abstract IOBuffer putShortBits(short value, int numberOfBits);
public abstract IOBuffer putIntBits(int value, int numberOfBits);
public abstract boolean getBooleanBit();
public abstract byte getByteBits();
public abstract byte getByteBits(int numberOfBits);
public abstract short getShortBits();
public abstract short getShortBits(int numberOfBits);
public abstract int getIntBits();
public abstract int getIntBits(int numberOfBits);
public abstract long getLongBits();
public abstract long getLongBits(int numberOfBits);
public abstract int bitPosition(int position);
public abstract int bitPosition();
public abstract int bitCapacity();
}
| 38,764 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Log.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Log.java | /*
* see license.txt
*/
package harenet;
/**
* Simple logging interface
*
* @author Tony
*
*/
public interface Log {
public boolean enabled();
public void setEnabled(boolean enable);
public void debug(String msg);
public void error(String msg);
public void info(String msg);
}
| 313 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ByteCounterIOBuffer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/ByteCounterIOBuffer.java | /*
* see license.txt
*/
package harenet;
import java.nio.ByteBuffer;
/**
* Just counts the bytes
*
* @author Tony
*
*/
public class ByteCounterIOBuffer implements IOBuffer {
private int numberOfBits;
/**
*
*/
public ByteCounterIOBuffer() {
this.numberOfBits = 0;
}
public ByteCounterIOBuffer(int size) {
this.numberOfBits = size;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#receiveSync()
*/
@Override
public IOBuffer receiveSync() {
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#sync()
*/
@Override
public IOBuffer sendSync() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#asByteBuffer()
*/
@Override
public ByteBuffer asByteBuffer() {
return null;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#slice()
*/
@Override
public IOBuffer slice() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#duplicate()
*/
@Override
public IOBuffer duplicate() {
return new ByteCounterIOBuffer(this.numberOfBits);
}
/* (non-Javadoc)
* @see netspark.IOBuffer#asReadOnlyBuffer()
*/
@Override
public IOBuffer asReadOnlyBuffer() {
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getUnsignedByte()
*/
@Override
public int getUnsignedByte() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putUnsignedByte(int)
*/
@Override
public IOBuffer putUnsignedByte(int b) {
this.numberOfBits+=Byte.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get()
*/
@Override
public byte getByte() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte)
*/
@Override
public IOBuffer putByte(byte b) {
this.numberOfBits+=Byte.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(int)
*/
@Override
public byte getByte(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(int, byte)
*/
@Override
public IOBuffer putByte(int index, byte b) {
this.numberOfBits += Byte.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(byte[], int, int)
*/
@Override
public IOBuffer getBytes(byte[] dst, int offset, int length) {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#get(byte[])
*/
@Override
public IOBuffer getBytes(byte[] dst) {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(netspark.IOBuffer)
*/
@Override
public IOBuffer put(IOBuffer src) {
this.numberOfBits += src.remaining() * 8;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte[], int, int)
*/
@Override
public IOBuffer putBytes(byte[] src, int offset, int length) {
this.numberOfBits += length * 8;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#put(byte[])
*/
@Override
public IOBuffer putBytes(byte[] src) {
this.numberOfBits += src.length * 8;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#hasArray()
*/
@Override
public boolean hasArray() {
return false;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#array()
*/
@Override
public byte[] array() {
return null;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#arrayOffset()
*/
@Override
public int arrayOffset() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#compact()
*/
@Override
public IOBuffer compact() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#isDirect()
*/
@Override
public boolean isDirect() {
return false;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#capacity()
*/
@Override
public int capacity() {
int leftOver = this.numberOfBits % 8;
if(leftOver > 0) {
return (this.numberOfBits / 8) + 1;
}
return this.numberOfBits / 8;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#position()
*/
@Override
public int position() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#position(int)
*/
@Override
public IOBuffer position(int newPosition) {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#limit()
*/
@Override
public int limit() {
return capacity();
}
/* (non-Javadoc)
* @see netspark.IOBuffer#limit(int)
*/
@Override
public IOBuffer limit(int newLimit) {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#mark()
*/
@Override
public IOBuffer mark() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#reset()
*/
@Override
public IOBuffer reset() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#clear()
*/
@Override
public IOBuffer clear() {
this.numberOfBits = 0;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#flip()
*/
@Override
public IOBuffer flip() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#rewind()
*/
@Override
public IOBuffer rewind() {
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#remaining()
*/
@Override
public int remaining() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#hasRemaining()
*/
@Override
public boolean hasRemaining() {
return false;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#isReadOnly()
*/
@Override
public boolean isReadOnly() {
return false;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getShort()
*/
@Override
public short getShort() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putShort(short)
*/
@Override
public IOBuffer putShort(short value) {
this.numberOfBits += Short.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getShort(int)
*/
@Override
public short getShort(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putShort(int, short)
*/
@Override
public IOBuffer putShort(int index, short value) {
this.numberOfBits += Short.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getInt()
*/
@Override
public int getInt() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putInt(int)
*/
@Override
public IOBuffer putInt(int value) {
this.numberOfBits += Integer.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getInt(int)
*/
@Override
public int getInt(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putInt(int, int)
*/
@Override
public IOBuffer putInt(int index, int value) {
this.numberOfBits += Integer.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getLong()
*/
@Override
public long getLong() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putLong(long)
*/
@Override
public IOBuffer putLong(long value) {
this.numberOfBits += Long.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getLong(int)
*/
@Override
public long getLong(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putLong(int, long)
*/
@Override
public IOBuffer putLong(int index, long value) {
this.numberOfBits += Long.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getFloat()
*/
@Override
public float getFloat() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putFloat(float)
*/
@Override
public IOBuffer putFloat(float value) {
this.numberOfBits += Float.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getFloat(int)
*/
@Override
public float getFloat(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putFloat(int, float)
*/
@Override
public IOBuffer putFloat(int index, float value) {
this.numberOfBits += Float.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getDouble()
*/
@Override
public double getDouble() {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putDouble(double)
*/
@Override
public IOBuffer putDouble(double value) {
this.numberOfBits += Double.SIZE;
return this;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#getDouble(int)
*/
@Override
public double getDouble(int index) {
return 0;
}
/* (non-Javadoc)
* @see netspark.IOBuffer#putDouble(int, double)
*/
@Override
public IOBuffer putDouble(int index, double value) {
this.numberOfBits += Double.SIZE;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putBooleanBit(boolean)
*/
@Override
public IOBuffer putBooleanBit(boolean value) {
this.numberOfBits ++;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putLongBits(long, int)
*/
@Override
public IOBuffer putLongBits(long value, int numberOfBits) {
this.numberOfBits += numberOfBits;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putByteBits(byte, int)
*/
@Override
public IOBuffer putByteBits(byte value, int numberOfBits) {
this.numberOfBits += numberOfBits;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putShortBits(short, int)
*/
@Override
public IOBuffer putShortBits(short value, int numberOfBits) {
this.numberOfBits += numberOfBits;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#putIntBits(int, int)
*/
@Override
public IOBuffer putIntBits(int value, int numberOfBits) {
this.numberOfBits += numberOfBits;
return this;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getBooleanBit()
*/
@Override
public boolean getBooleanBit() {
return false;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getByteBits()
*/
@Override
public byte getByteBits() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getByteBits(int)
*/
@Override
public byte getByteBits(int numberOfBits) {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getShortBits()
*/
@Override
public short getShortBits() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getShortBits(int)
*/
@Override
public short getShortBits(int numberOfBits) {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getIntBits()
*/
@Override
public int getIntBits() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getIntBits(int)
*/
@Override
public int getIntBits(int numberOfBits) {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getLongBits()
*/
@Override
public long getLongBits() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#getLongBits(int)
*/
@Override
public long getLongBits(int numberOfBits) {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitPosition()
*/
@Override
public int bitPosition() {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitPosition(int)
*/
@Override
public int bitPosition(int position) {
return 0;
}
/* (non-Javadoc)
* @see harenet.IOBuffer#bitCapacity()
*/
@Override
public int bitCapacity() {
return capacity() * 8;
}
}
| 12,665 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BitArray.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/BitArray.java | /*
* see license.txt
*/
package harenet;
import seventh.shared.SeventhConstants;
/**
* Stores bits
*
* @author Tony
*
*/
public class BitArray {
private static final int WORD_SIZE = 8;
private byte[] data;
/**
* @param maxNumberOfBits
*/
public BitArray(int maxNumberOfBits) {
int leftOver = maxNumberOfBits % WORD_SIZE;
this.data = new byte[(maxNumberOfBits / WORD_SIZE) + ((leftOver>0) ? 1 : 0)];
}
private int bitIndex(int b) {
return b / WORD_SIZE;
}
private int bitOffset(int b) {
return b % WORD_SIZE;
}
/**
* Sets the bit (is zero based)
*
* @param b
* @param isSet
*/
public void setBit(int b, boolean isSet) {
if(isSet) {
data[bitIndex(b)] |= 1 << (bitOffset(b));
}
else {
data[bitIndex(b)] &= ~(1 << (bitOffset(b)));
}
}
/**
* Sets the bit (is zero based)
*
* @param b
*/
public void setBit(int b) {
data[bitIndex(b)] |= 1 << (bitOffset(b));
}
/**
* Zero based index
*
* @param b
* @return true if the bit is set
*/
public boolean getBit(int b) {
return (data[bitIndex(b)] & (1 << (bitOffset(b)))) != 0;
}
/**
* Set the data directly
*
* @param i
* @param data
*/
public void setDataElement(int i, byte data) {
this.data[i] = data;
}
/**
* @return the data
*/
public byte[] getData() {
return data;
}
public void clear() {
for(int i = 0; i < data.length; i++) {
data[i] = 0;
}
}
public void setAll() {
for(int i = 0; i < data.length; i++) {
data[i] = 0xFFFFFFFF;
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < data.length; i++) {
sb.append(Integer.toBinaryString(data[i]));
sb.append(" ");
}
return sb.toString();
}
/**
* The number of bytes to represent the number of bits
*
* @return The number of bytes to represent the number of bits
*/
public int numberOfBytes() {
return this.data.length;
}
/**
* The number of bits used in this bit array
*
* @return the number of bits
*/
public int size() {
return this.data.length * WORD_SIZE;
}
public static void main(String[] args) {
BitArray a = new BitArray(255);
// int[] ents = new int[256];
for(int i = 0; i < 255; i++) {
a.setBit(i);
}
System.out.println("NumberOfBytes:" + a.numberOfBytes() + " : " + a.size() + " : " + a);
BitArray b = new BitArray(SeventhConstants.MAX_PERSISTANT_ENTITIES - 1);
// int[] ents = new int[256];
for(int i = 2; i < b.size(); i++) {
b.setBit(i);
}
System.out.println("NumberOfBytes:" + b.numberOfBytes() + " : " + b.size() + " : " + b);
}
}
| 3,268 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Peer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/Peer.java | /*
* see license.txt
*/
package harenet;
import harenet.Host.MessageListener;
import harenet.messages.ConnectionRequestMessage;
import harenet.messages.DisconnectMessage;
import harenet.messages.Message;
import harenet.messages.ReliableNetMessage;
import harenet.messages.ServerFullMessage;
import harenet.messages.UnReliableNetMessage;
import java.net.InetSocketAddress;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* A {@link Peer} is a representation of a remote client. The {@link Host}
* can send and receive messages from a {@link Peer}.
*
* @author Tony
*
*/
public class Peer {
enum State {
CONNECTING,
CONNECTED,
DISCONNECTING,
DISCONNECTED,
DENIED,
ZOMBIE,
}
private byte id;
private InetSocketAddress address;
private Host host;
private State state;
private NetConfig config;
private Log log;
private Queue<Message> outgoingMessages;
private Queue<Message> reliableOutgoingMessages;
private Queue<Message> inboundMessages;
// private Queue<Message> outgoingMessagesCache;
private Map<Integer, Message> receivedReliableMessages;
private long roundTripTime;
/* the packet number */
private int sendSequence;
/* the remote packet sequence number */
private int remoteSequence;
/* what the other connection received from us */
private int remoteAck;
/* last time this peer received a message */
private long lastReceivedTime;
/* last time this peer sent a message */
private long lastSendTime;
/* last time we pinged this peer */
private long lastPingTime;
private long numberOfBytesSent;
private long numberOfBytesRecv;
private long numberOfDroppedPackets;
private long numberOfBytesCompressed;
private int[] ackBuffer;
private int ackBufferIndex;
private int messageIdGen;
private long timeConnected;
/**
* @param host
* @param address
* @param id
*/
public Peer(Host host, InetSocketAddress address, byte id) {
this.host = host;
this.address = address;
this.id = id;
this.config = host.getConfig();
this.log = config.getLog();
this.state = State.CONNECTING;
this.outgoingMessages = new ConcurrentLinkedQueue<Message>();
this.reliableOutgoingMessages = new ConcurrentLinkedQueue<Message>();
this.inboundMessages = new ConcurrentLinkedQueue<Message>();
// this.outgoingMessagesCache = new ConcurrentLinkedQueue<Message>();
this.receivedReliableMessages = new ConcurrentHashMap<>();
this.ackBuffer = new int[32];
this.ackBufferIndex = 0;
this.timeConnected = System.currentTimeMillis();
}
/**
* @param state the state to set
*/
void setState(State state) {
this.state = state;
}
/**
* @param id the id to set
*/
void setId(byte id) {
this.id = id;
}
/**
* @return the lastPingTime
*/
public long getLastPingTime() {
return lastPingTime;
}
/**
* @param lastPingTime the lastPingTime to set
*/
public void setLastPingTime(long lastPingTime) {
this.lastPingTime = lastPingTime;
}
public void pongMessageReceived() {
long ping = System.currentTimeMillis() - this.lastPingTime;
this.roundTripTime = (this.roundTripTime + ping) / 2;
}
/**
* @return the numberOfBytesCompressed
*/
public long getNumberOfBytesCompressed() {
return numberOfBytesCompressed;
}
/**
* @return the numberOfBytesRecv
*/
public long getNumberOfBytesRecv() {
return numberOfBytesRecv;
}
/**
* @return the numberOfBytesSent
*/
public long getNumberOfBytesSent() {
return numberOfBytesSent;
}
public void addNumberOfBytesRecv(int bytes) {
this.numberOfBytesRecv += bytes;
}
public void addNumberOfBytesSent(int bytes) {
this.numberOfBytesSent += bytes;
}
public void addNumberOfBytesCompressed(int bytes) {
this.numberOfBytesCompressed += bytes;
}
public void addDroppedPacket() {
this.numberOfDroppedPackets++;
}
public void addDroppedPacket(int numberOfPackets) {
this.numberOfDroppedPackets += numberOfPackets;
}
public long getAvgBitsPerSecRecv() {
long totalTimeConnected = (System.currentTimeMillis() - this.timeConnected)/1000;
if(totalTimeConnected > 0) {
return (long)( (numberOfBytesRecv*8) / totalTimeConnected );
}
return 0;
}
public long getAvgBitsPerSecSent() {
long totalTimeConnected = (System.currentTimeMillis() - this.timeConnected)/1000;
if(totalTimeConnected > 0) {
return (long)( (numberOfBytesSent*8) / totalTimeConnected );
}
return 0;
}
/**
* @return the numberOfDroppedPackets
*/
public long getNumberOfDroppedPackets() {
return numberOfDroppedPackets;
}
/**
* @return the next message id
*/
public int nextMessageId() {
return this.messageIdGen++;
}
/**
* @return the new Sequence number of this Peer next packet
*/
public int nextSequenceNumber() {
if( this.sendSequence >= Integer.MAX_VALUE ) {
this.sendSequence = 0;
}
return ++this.sendSequence;
}
/**
* @return the sendSequence
*/
public int getSendSequence() {
return sendSequence;
}
/**
* Checks the reliable message queue
*/
public void checkReliableMessages(int ackHistory) {
if(!this.reliableOutgoingMessages.isEmpty()) {
long currentTime = System.currentTimeMillis();
Iterator<Message> it = this.reliableOutgoingMessages.iterator();
while(it.hasNext()) {
Message msg = it.next();
/* if the sent packet has been acknowledged, we can
* go ahead and discard it.
*/
if(isAcknowledged(ackHistory, msg)) {
it.remove();
if(log.enabled()) {
log.debug("Reliable message received: "
+ msg.getClass().getSimpleName()
+ " Sequence: " + msg.getSequenceNumberSent()
+ " MessageId: " + msg.getMessageId()
+ " #Of Resends: " + msg.getSequencesSent());
}
}
else {
long timeSent = msg.getTimeSent();
if(timeSent > -1) {
long dt = currentTime - timeSent;
if(dt > config.getReliableMessageTimeout()) {
if(log.enabled()) {
log.debug("Reliable message timed out: " + msg.getClass().getSimpleName()
+ " Sequence: " + msg.getSequenceNumberSent()
+ " Number of Delays: " + msg.getNumberOfDelays()
+ " MessageId: " + msg.getMessageId()
+ " #Of Resends: " + msg.getSequencesSent());
}
it.remove();
}
}
}
}
}
}
/**
* @param remoteSequence the remoteSequence to set
*/
public void setRemoteSequence(int remoteSequence) {
this.remoteSequence = remoteSequence;
this.ackBuffer[this.ackBufferIndex] = remoteSequence;
this.ackBufferIndex = (this.ackBufferIndex + 1) % this.ackBuffer.length;
}
/**
* @param remoteAck the remoteAck to set
*/
public void setRemoteAck(int ackHistory, int remoteAck) {
this.remoteAck = remoteAck;
// this.ackBuffer[this.ackBufferIndex] = this.remoteAck;
// this.ackBufferIndex = (this.ackBufferIndex + 1) % this.ackBuffer.length;
checkReliableMessages(ackHistory);
}
/**
* @param sequenceNumber
* @return true if the sequence number was acknowledged
*/
public boolean isAcknowledged(int ackHistory, Message msg) {
// int ackHistory = getAckHistory();
int sequenceNumber = msg.getSequenceNumberSent();
int numberOfTimesSent = msg.getSequencesSent();
if(log.enabled()) {
log.debug("checking if acknowledged: Hist:" + Integer.toBinaryString(ackHistory)
+ " RemoteSeq: " + this.remoteSequence
+ " RemoteAck: " + this.remoteAck
+ " Seq:" + sequenceNumber);
}
boolean wasAck = false;
while(numberOfTimesSent > 0 && !wasAck) {
if(sequenceNumber == this.remoteAck) {
wasAck = true;
}
else if (sequenceNumber < this.remoteAck) {
int ackPosition = Math.max(this.remoteAck - sequenceNumber - 1, 0);
wasAck = ((ackHistory >>> ackPosition) & 1) != 0;
}
sequenceNumber--;
numberOfTimesSent--;
}
return wasAck;
}
/**
* @return the lastSendTime
*/
public long getLastSendTime() {
return lastSendTime;
}
/**
* @param lastSendTime the lastSendTime to set
*/
public void setLastSendTime(long lastSendTime) {
this.lastSendTime = lastSendTime;
}
/**
* @return the lastReceivedTime
*/
public long getLastReceivedTime() {
return lastReceivedTime;
}
/**
* @param lastReceivedTime the lastReceivedTime to set
*/
public void setLastReceivedTime(long lastReceivedTime) {
this.lastReceivedTime = lastReceivedTime;
}
/**
* @param currentTime the current time
* @param timeout time in msec to consider this connection timed out
* @return true if this Peer has timed out
*/
public boolean checkIfTimedOut(long currentTime, long timeout) {
long dt = currentTime - this.lastReceivedTime;
return dt > timeout;
}
/**
* @return the remoteSequence
*/
public int getRemoteSequence() {
return remoteSequence;
}
/**
* @return the ackHistory
*/
public int getAckHistory() {
int ackHistory = 0;
for(int i = 0; i < ackBuffer.length; i++) {
int previusSeq = ackBuffer[(ackBufferIndex + i) % ackBuffer.length];
if(previusSeq < remoteSequence) {
int newAckDelta = remoteSequence - previusSeq;
if(newAckDelta > 0 && newAckDelta < 32) {
ackHistory = ackHistory | (1<<newAckDelta);
}
}
}
// int ackHistory = 0;
// for(int i = 0; i < ackBuffer.length; i++) {
// int newAckDelta = this.remoteSequence - ackBuffer[(ackBufferIndex + i) % ackBuffer.length];
// ackHistory = ackHistory | (1<<newAckDelta);
// }
// if(log.enabled()) {
// log.debug("AckHistory: " + Integer.toBinaryString(ackHistory));
// }
return ackHistory;
}
/**
* @return the roundTripTime
*/
public long getRoundTripTime() {
return roundTripTime;
}
// /**
// * @return the outgoingMessagesCache
// */
// public Queue<Message> getOutgoingMessagesCache() {
// this.outgoingMessagesCache.clear();
//
// this.outgoingMessagesCache.addAll(this.reliableOutgoingMessages);
// this.outgoingMessagesCache.addAll(this.outgoingMessages);
//
// return outgoingMessagesCache;
// }
/**
* @return the reliableOutgoingMessages
*/
public Queue<Message> getReliableOutgoingMessages() {
return reliableOutgoingMessages;
}
/**
* @return the outgoingMessages
*/
public Queue<Message> getOutgoingMessages() {
return outgoingMessages;
}
/**
* @return the inboundMessages
*/
public Queue<Message> getInboundMessages() {
return inboundMessages;
}
/**
* @return the address
*/
public InetSocketAddress getAddress() {
return address;
}
/**
* @param address the address to set
*/
public void setAddress(InetSocketAddress address) {
this.address = address;
}
/**
* @return the id
*/
public byte getId() {
return id;
}
/**
* @return the state
*/
public State getState() {
return state;
}
/**
* @param seqNum - the sequence number to compare against
* @return true if seqNum is a newer sequence number than the stored sequence number
*/
public boolean isSequenceMoreRecent( int seqNum ) {
return (( seqNum >= this.remoteSequence ) && ( seqNum - this.remoteSequence <= Integer.MAX_VALUE/2 )) ||
(( this.remoteSequence >= seqNum ) && ( this.remoteSequence - seqNum > Integer.MAX_VALUE/2 ));
// return ( this.remoteSequence > seqNum ) && ( this.remoteSequence - seqNum <= Integer.MAX_VALUE/2 ) ||
// ( seqNum > this.remoteSequence ) && ( seqNum - this.remoteSequence > Integer.MAX_VALUE/2 );
}
/**
* The server can be full and deny this connection
*
* @return
*/
public boolean isDeniedConnection() {
return state==State.DENIED;
}
public boolean isConnected() {
return state==State.CONNECTED;
}
public boolean isConnecting() {
return state==State.CONNECTING;
}
public boolean isDisconnected() {
return state==State.DISCONNECTED;
}
public boolean isDisconnecting() {
return state == State.DISCONNECTING;
}
/**
* @return true if in zombie state
*/
public boolean isZombie() {
return state==State.ZOMBIE;
}
/**
* Denies the connection
*/
public void denyConnection() {
state = State.DENIED;
}
/**
* Signal a Disconnect message to
* the host.
*/
public void disconnect() {
this.state = State.DISCONNECTING;
this.host.disconnect(this);
}
public void disconnectNow() {
this.state = State.DISCONNECTED;
this.host.disconnect(this);
this.inboundMessages.clear();
this.outgoingMessages.clear();
this.receivedReliableMessages.clear();
this.reliableOutgoingMessages.clear();
}
/**
* Sends a Message
* @param message
*/
public void send(Message message) {
if(message.isReliable()) {
this.reliableOutgoingMessages.add(message.copy());
}
else {
this.outgoingMessages.add(message);
}
}
/**
* Removes stored reliable messages
* @param currentTime
*/
public void timeoutDuplicates(long currentTime, long timeout) {
for(Map.Entry<Integer, Message> e : this.receivedReliableMessages.entrySet()) {
if(currentTime - e.getValue().getTimeReceived() > timeout) {
this.receivedReliableMessages.remove(e.getKey());
}
}
}
/**
* Checks and temporarily stores the message to check for duplicates
* @param msg
* @return true if this message is a duplicate
*/
public boolean isDuplicateMessage(Message msg) {
boolean isDup = this.receivedReliableMessages.containsKey(msg.getMessageId());
if ( !isDup ) {
this.receivedReliableMessages.put(msg.getMessageId(), msg);
msg.setTimeReceived(System.currentTimeMillis());
}
return isDup;
}
/**
* Receives a message
* @param message
*/
public void receive(Message message) {
this.inboundMessages.add(message);
}
/**
* Receives messages
*
* @param listener
*/
public void receiveMessages(MessageListener listener) {
while(!this.inboundMessages.isEmpty()) {
Message message = this.inboundMessages.poll();
if(message instanceof UnReliableNetMessage) {
listener.onMessage(this, message);
}
else if(message instanceof ReliableNetMessage) {
listener.onMessage(this, message);
}
if(message instanceof ConnectionRequestMessage) {
listener.onConnected(this);
}
else if(message instanceof DisconnectMessage) {
listener.onDisconnected(this);
}
else if(message instanceof ServerFullMessage) {
denyConnection();
listener.onServerFull(this);
}
}
}
}
| 17,882 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DummyPeer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/DummyPeer.java | /*
* see license.txt
*/
package harenet;
import harenet.messages.Message;
import java.net.InetSocketAddress;
/**
* A {@link DummyPeer} simulates an connected {@link Peer}. This does not
* actually send or receive any data from a {@link Host}
*
* @author Tony
*
*/
public class DummyPeer extends Peer {
private static final InetSocketAddress DUMMY_ADDRESS = new InetSocketAddress(0);
/**
* @param host
* @param address
* @param id
*/
public DummyPeer(Host host, byte id) {
super(host, DUMMY_ADDRESS, id);
}
/* (non-Javadoc)
* @see harenet.Peer#isConnected()
*/
@Override
public boolean isConnected() {
return true;
}
/* (non-Javadoc)
* @see harenet.Peer#isConnecting()
*/
@Override
public boolean isConnecting() {
return false;
}
/* (non-Javadoc)
* @see harenet.Peer#checkIfTimedOut(long, long)
*/
@Override
public boolean checkIfTimedOut(long currentTime, long timeout) {
return false;
}
/* (non-Javadoc)
* @see harenet.Peer#send(harenet.messages.Message)
*/
@Override
public void send(Message message) {
}
/* (non-Javadoc)
* @see harenet.Peer#receive(harenet.messages.Message)
*/
@Override
public void receive(Message message) {
}
}
| 1,386 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LagConnectionListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/LagConnectionListener.java | /*
* see license.txt
*/
package harenet.api;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Used for debugging purposes. This will introduce a variable amount of lag.
*
* @author Tony
*
*/
public class LagConnectionListener implements ConnectionListener {
private Random random;
private ConnectionListener decorator;
private Queue<Msg> inbox;
private int minLag, maxLag;
private ScheduledExecutorService service;
class Msg {
Connection conn;
Object msg;
Msg(Connection conn, Object msg) {
this.conn = conn;
this.msg = msg;
}
}
/**
* @param minLag
* @param maxLag
* @param decorator
*/
public LagConnectionListener(final int minLag, final int maxLag, final ConnectionListener decorator) {
super();
this.minLag = minLag;
this.maxLag = maxLag;
this.decorator = decorator;
this.random = new Random();
this.inbox = new ConcurrentLinkedQueue<>();
this.service = Executors.newScheduledThreadPool(1);
}
/* (non-Javadoc)
* @see harenet.api.ConnectionListener#onConnected(harenet.api.Connection)
*/
@Override
public void onConnected(Connection conn) {
decorator.onConnected(conn);
}
/* (non-Javadoc)
* @see harenet.api.ConnectionListener#onDisconnected(harenet.api.Connection)
*/
@Override
public void onDisconnected(Connection conn) {
decorator.onDisconnected(conn);
}
/* (non-Javadoc)
* @see harenet.api.ConnectionListener#onServerFull(harenet.api.Connection)
*/
@Override
public void onServerFull(Connection conn) {
decorator.onServerFull(conn);
}
/* (non-Javadoc)
* @see harenet.api.ConnectionListener#onReceived(harenet.api.Connection, java.lang.Object)
*/
@Override
public void onReceived(Connection conn, Object msg) {
this.inbox.add(new Msg(conn,msg));
minLag = 150;
maxLag = 200;
long sleep = minLag + random.nextInt(maxLag-minLag);
if(sleep > maxLag) {
sleep = maxLag;
}
this.service.schedule(new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
Msg msg = inbox.poll();
if(msg != null) {
decorator.onReceived(msg.conn, msg.msg);
}
}
}, sleep, TimeUnit.MILLISECONDS);
}
}
| 2,904 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Client.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/Client.java | /*
* see license.txt
*/
package harenet.api;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* Represents a network connection to a server.
*
* @author Tony
*
*/
public interface Client extends Connection {
/**
* Attempts to connect to the remove host
*
* @param timeout
* @param host
* @throws IOException
* @return true if connected
*/
public boolean connect(int timeout, InetSocketAddress host) throws IOException;
/**
* Sets the keep alive time
*
* @param keepAliveMillis (msec)
*/
public void setKeepAlive(int keepAliveMillis);
}
| 648 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Server.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/Server.java | /*
* see license.txt
*/
package harenet.api;
import harenet.messages.NetMessage;
import java.io.IOException;
import java.util.List;
/**
* Manages remote connections from {@link Client}s
*
* @author Tony
*
*/
public interface Server extends Endpoint {
/**
* @return true if running, false otherwise
*/
public boolean isRunning();
/**
* Binds the server to a port
* @param port
* @throws IOException
*/
public void bind(int port) throws IOException;
/**
* Reserves the specified ID. If this ID is already claimed
* nothing happens.
*
* @return the reserved id
*/
public int reserveId();
/**
* @return a list of active {@link Connection} to this {@link Server}
*/
public List<Connection> getConnections();
/**
* Sends the message to all active connections
* @param protocolFlags
* @param msg
* @throws IOException
*/
public void sendToAll(int protocolFlags, NetMessage msg) throws IOException;
/**
* Sends the message to all active connections except the supplied connectionId
* @param protocolFlags
* @param msg
* @param connectionId
* @throws IOException
*/
public void sendToAllExcept(int protocolFlags, NetMessage msg, int connectionId) throws IOException;
/**
* Sends the message to the connection
* @param protocolFlags
* @param msg
* @param connectionId
* @throws IOException
*/
public void sendTo(int protocolFlags, NetMessage msg, int connectionId) throws IOException;
}
| 1,633 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Endpoint.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/Endpoint.java | /*
* see license.txt
*/
package harenet.api;
import java.io.IOException;
/**
* Connection endpoint
*
* @author Tony
*
*/
public interface Endpoint extends Runnable {
/**
* A flag for a reliable message, by default messages are
* unreliable
*/
public static final int FLAG_RELIABLE = (1<<0);
/**
* A flag for unsequenced, by default messages are
* sequenced
*/
public static final int FLAG_UNSEQUENCED = (1<<1);
/**
* A flag for sequenced but unreliable
*/
public static final int FLAG_UNRELIABLE = 0;
/**
* Close out the connection
*/
public void close();
/**
* Reads/writes any pending data
*
* @param timeout
*/
public void update(int timeout) throws IOException;
/**
* Starts a new thread, continually invoking {@link Client#run()}
*/
public void start();
/**
* closes the connection, and terminates the thread
*/
public void stop();
/**
* Adds a {@link ConnectionListener}
* @param listener
*/
public void addConnectionListener(ConnectionListener listener);
/**
* Removes a {@link ConnectionListener}
* @param listener
*/
public void removeConnectionListener(ConnectionListener listener);
/**
* Removes all {@link ConnectionListener}s
*/
// public void removeAllConnectionListeners();
}
| 1,466 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ConnectionListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/ConnectionListener.java | /*
* see license.txt
*/
package harenet.api;
/**
* Listens for events/messages
*
* @author Tony
*
*/
public interface ConnectionListener {
/**
* A connection has been made
* @param conn
*/
void onConnected(Connection conn);
/**
* The connection has been terminated
* @param conn
*/
void onDisconnected(Connection conn);
/**
* The server is full, and this client is not allowed
* to connect
*
* @param conn
*/
void onServerFull(Connection conn);
/**
* A message has been received
*
* @param conn
* @param msg
*/
void onReceived(Connection conn, Object msg);
}
| 702 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Connection.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/Connection.java | /*
* see license.txt
*/
package harenet.api;
import harenet.messages.NetMessage;
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* A connection between two computers
*
* @author Tony
*
*/
public interface Connection extends Endpoint {
/**
* @return this connections ID
*/
public int getId();
/**
* @return true if connected
*/
public boolean isConnected();
/**
* @return the return trip time in msec
*/
public int getReturnTripTime();
/**
* @return the number of bytes sent over the wire to the
* remote computer
*/
public long getNumberOfBytesSent();
/**
* @return the number of bytes received
*/
public long getNumberOfBytesReceived();
/**
* @return the average bit rate received
*/
public long getAvgBitsPerSecRecv();
/**
* @return the average bit rate sent
*/
public long getAvgBitsPerSecSent();
/**
* @return the number of dropped packets
*/
public long getNumberOfDroppedPackets();
/**
* @return the number of bytes compressed
*/
public long getNumberOfBytesCompressed();
/**
* Sends a message to the server
* @param protocolFlags
* @param msg
* @throws IOException
*/
public void send(int protocolFlags, NetMessage msg) throws IOException;
/**
* @return the remote address
*/
public InetSocketAddress getRemoteAddress();
}
| 1,536 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HareNetServer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/impl/HareNetServer.java | /*
* see license.txt
*/
package harenet.api.impl;
import harenet.Host;
import harenet.Host.MessageListener;
import harenet.NetConfig;
import harenet.Peer;
import harenet.api.Connection;
import harenet.api.Server;
import harenet.messages.Message;
import harenet.messages.NetMessage;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;
/**
* Harenet {@link Server} implementation
* @author Tony
*/
public class HareNetServer extends HareNetEndpoint implements Server {
private Host host;
private Connection[] connections;
private MessageListener listener;
private class ServerMessageListener implements MessageListener {
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onConnected(netspark.Peer)
*/
@Override
public void onConnected(Peer peer) {
byte peerId = peer.getId();
Connection conn = connections[peerId];
if(conn != null) {
if(conn.getId() != peerId) {
conn.close();
}
}
connections[peerId] = new HareNetClient(getNetConfig(), peerId, host, peer);
fireOnConnectionEvent(connections[peerId]);
}
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onDisconnected(netspark.Peer)
*/
@Override
public void onDisconnected(Peer peer) {
byte peerId = peer.getId();
Connection conn = connections[peerId];
if(conn != null) {
fireOnDisconnectionEvent(conn);
}
}
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onMessage(netspark.Peer, netspark.messages.Message)
*/
@Override
public void onMessage(Peer peer, Message message) {
byte peerId = peer.getId();
Connection conn = connections[peerId];
if(conn != null) {
fireOnReceivedEvent(conn, message);
}
}
/* (non-Javadoc)
* @see harenet.Host.MessageListener#onServerFull(harenet.Peer)
*/
@Override
public void onServerFull(Peer peer) {
byte peerId = peer.getId();
if(peerId > -1) {
Connection conn = connections[peerId];
if(conn != null) {
fireOnServerFullEvent(conn);
}
}
}
}
/**
*
*/
public HareNetServer(NetConfig netConfig) {
super(netConfig);
this.connections = new Connection[netConfig.getMaxConnections()];
this.listener = new ServerMessageListener();
}
/* (non-Javadoc)
* @see harenet.api.Server#reserveId(int)
*/
@Override
public int reserveId() {
if(host != null) {
return host.reserveId();
}
return -1;
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#close()
*/
@Override
public void close() {
try {
if(host!=null) {
host.destroy();
}
}
catch(Exception ignore) {
}
}
/* (non-Javadoc)
* @see net.jenet.api.Server#isRunning()
*/
@Override
public boolean isRunning() {
return ! this.isShutdown();
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#update(int)
*/
@Override
public void update(int timeout) {
try {
this.host.update(this.listener, timeout);
} catch (IOException e) {
this.host.getLogger().error(e.toString());
}
}
/* (non-Javadoc)
* @see net.jenet.api.Server#bind(int)
*/
@Override
public void bind(int port) throws IOException {
InetSocketAddress address=new InetSocketAddress(port);
this.host=new Host(getNetConfig(), address);
}
/* (non-Javadoc)
* @see net.jenet.api.Server#getConnections()
*/
@Override
public List<Connection> getConnections() {
return Arrays.asList(this.connections);
}
/* (non-Javadoc)
* @see net.jenet.api.Server#sendToAll(int, java.lang.Object)
*/
@Override
public void sendToAll(int protocolFlags, NetMessage msg) throws IOException {
if(this.host != null) {
Message message = writeMessage(protocolFlags, msg);
this.host.sendToAll(message);
}
}
/* (non-Javadoc)
* @see net.jenet.api.Server#sendToAllExcept(int, java.lang.Object, int)
*/
@Override
public void sendToAllExcept(int protocolFlags, NetMessage msg, int connectionId) throws IOException {
if(this.host != null) {
Message message = writeMessage(protocolFlags, msg);
this.host.sendToAllExcept(message, (byte) connectionId);
}
}
/* (non-Javadoc)
* @see net.jenet.api.Server#sendTo(int, java.lang.Object, int)
*/
@Override
public void sendTo(int protocolFlags, NetMessage msg, int connectionId) throws IOException {
if(this.host != null) {
Message message = writeMessage(protocolFlags, msg);
this.host.sendTo(message, (byte) connectionId);
}
}
}
| 5,570 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HareNetEndpoint.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/impl/HareNetEndpoint.java | /*
* see license.txt
*/
package harenet.api.impl;
import harenet.ByteCounterIOBuffer;
import harenet.NetConfig;
import harenet.api.Connection;
import harenet.api.ConnectionListener;
import harenet.api.Endpoint;
import harenet.messages.Message;
import harenet.messages.NetMessage;
import harenet.messages.ReliableNetMessage;
import harenet.messages.UnReliableNetMessage;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Harenet Endpoint implementation.
* @author Tony
*/
public abstract class HareNetEndpoint implements Endpoint {
private AtomicBoolean shutdown;
private Thread thread;
private Vector<ConnectionListener> listeners;
// private Output output;
private ByteCounterIOBuffer byteCounter;
private NetConfig netConfig;
private int pollRate;
/**
* @param netConfig
*/
public HareNetEndpoint(NetConfig netConfig) {
this.netConfig = netConfig;
this.shutdown = new AtomicBoolean(true);
this.listeners = new Vector<ConnectionListener>();
// this.output = new Output(1500, 4098);
this.byteCounter = new ByteCounterIOBuffer();
this.pollRate = netConfig.getPollRate();
}
/**
* @return the netConfig
*/
public NetConfig getNetConfig() {
return netConfig;
}
/**
* Writes out a {@link NetMessage}
*
* @param protocolFlags
* @param message
* @return the {@link Message} containing the {@link NetMessage} pay load
*/
protected Message writeMessage(int protocolFlags, NetMessage message) {
byteCounter.clear();
message.write(byteCounter);
Message msg = ((protocolFlags&Endpoint.FLAG_RELIABLE)!=0) ?
new ReliableNetMessage(message, (short)byteCounter.capacity()) :
new UnReliableNetMessage(message, (short)byteCounter.capacity()) ;
return msg;
}
/**
* Reads in the {@link Message} extracting out the {@link NetMessage} pay load
* @param message
* @return the {@link NetMessage}
*/
protected NetMessage readMessage(Message message) {
NetMessage obj = message.getMessage();
return obj;
}
/**
* @return the listeners
*/
public Vector<ConnectionListener> getListeners() {
return listeners;
}
protected boolean isShutdown() {
return this.shutdown.get();
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while(!this.shutdown.get()) {
try {
update(this.pollRate);
}
catch(Exception e) {
this.netConfig.getLog().error("*** Error updating network: " + e);
}
}
}
private void killNetworkThread() {
if(thread != null) {
this.shutdown.set(true);
try {
thread.join(5000);
} catch(InterruptedException ignore) {}
}
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#start()
*/
@Override
public void start() {
killNetworkThread();
shutdown.set(false);
thread = new Thread(this, "Network Thread");
thread.setDaemon(true);
thread.start();
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#stop()
*/
@Override
public void stop() {
if(this.shutdown.get()) {
return;
}
killNetworkThread();
close();
}
/**
* @param conn
* @param event
*/
protected void fireOnConnectionEvent(Connection conn) {
int size = this.listeners.size();
for(int i = 0; i < size; i++) {
this.listeners.get(i).onConnected(conn);
}
}
/**
* @param conn
* @param event
*/
protected void fireOnDisconnectionEvent(Connection conn) {
int size = this.listeners.size();
for(int i = 0; i < size; i++) {
this.listeners.get(i).onDisconnected(conn);
}
}
/**
* @param conn
*/
protected void fireOnReceivedEvent(Connection conn, Message msg) {
Object message = readMessage(msg);
int size = this.listeners.size();
for(int i = 0; i < size; i++) {
this.listeners.get(i).onReceived(conn, message);
}
}
/**
* @param conn
*/
protected void fireOnServerFullEvent(Connection conn) {
int size = this.listeners.size();
for(int i = 0; i < size; i++) {
this.listeners.get(i).onServerFull(conn);
}
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#addConnectionListener(net.jenet.api.ConnectionListener)
*/
@Override
public void addConnectionListener(ConnectionListener listener) {
this.listeners.add(listener);
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#removeConnectionListener(net.jenet.api.ConnectionListener)
*/
@Override
public void removeConnectionListener(ConnectionListener listener) {
this.listeners.remove(listener);
}
}
| 5,454 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HareNetClient.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/api/impl/HareNetClient.java | /*
* see license.txt
*/
package harenet.api.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import harenet.Host;
import harenet.Host.MessageListener;
import harenet.NetConfig;
import harenet.Peer;
import harenet.api.Client;
import harenet.messages.Message;
import harenet.messages.NetMessage;
/**
* Harenet Client implementation
*
* @author Tony
*/
public class HareNetClient extends HareNetEndpoint implements Client {
private int connectionId;
private Host host;
private Peer peer;
private class EndpointMessageListener implements MessageListener {
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onConnected(netspark.Peer)
*/
@Override
public void onConnected(Peer peer) {
fireOnConnectionEvent(HareNetClient.this);
}
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onDisconnected(netspark.Peer)
*/
@Override
public void onDisconnected(Peer peer) {
fireOnDisconnectionEvent(HareNetClient.this);
}
/* (non-Javadoc)
* @see netspark.Host.MessageListener#onMessage(netspark.Peer, netspark.messages.Message)
*/
@Override
public void onMessage(Peer peer, Message message) {
fireOnReceivedEvent(HareNetClient.this, message);
}
/* (non-Javadoc)
* @see harenet.Host.MessageListener#onServerFull(harenet.Peer)
*/
@Override
public void onServerFull(Peer peer) {
fireOnServerFullEvent(HareNetClient.this);
}
}
private MessageListener listener;
/**
*/
public HareNetClient(NetConfig netConfig) {
super(netConfig);
this.connectionId = -1;
this.listener = new EndpointMessageListener();
}
/**
* @param kryo
* @param connectionId
* @param host
* @param peer
*/
public HareNetClient(NetConfig netConfig, int connectionId, Host host, Peer peer) {
super(netConfig);
this.connectionId = connectionId;
this.host = host;
this.peer = peer;
}
/* (non-Javadoc)
* @see net.jenet.api.Connection#getId()
*/
@Override
public int getId() {
return this.connectionId;
}
/* (non-Javadoc)
* @see net.Connection#getReturnTripTime()
*/
@Override
public int getReturnTripTime() {
return (int)this.peer.getRoundTripTime();
}
/* (non-Javadoc)
* @see net.Connection#getNumberOfBytesReceived()
*/
@Override
public long getNumberOfBytesReceived() {
return this.peer.getNumberOfBytesRecv();
}
/* (non-Javadoc)
* @see net.Connection#getNumberOfBytesSent()
*/
@Override
public long getNumberOfBytesSent() {
return this.peer.getNumberOfBytesSent();
}
/* (non-Javadoc)
* @see net.Connection#getAvgBitsPerSecRecv()
*/
@Override
public long getAvgBitsPerSecRecv() {
return peer.getAvgBitsPerSecRecv();
}
/* (non-Javadoc)
* @see net.Connection#getAvgBitsPerSecSent()
*/
@Override
public long getAvgBitsPerSecSent() {
return peer.getAvgBitsPerSecSent();
}
/* (non-Javadoc)
* @see harenet.api.Connection#getNumberOfDroppedPackets()
*/
@Override
public long getNumberOfDroppedPackets() {
return peer.getNumberOfDroppedPackets();
}
/* (non-Javadoc)
* @see harenet.api.Connection#getNumberOfBytesCompressed()
*/
@Override
public long getNumberOfBytesCompressed() {
return peer.getNumberOfBytesCompressed();
}
/* (non-Javadoc)
* @see net.jenet.api.Connection#isConnected()
*/
@Override
public boolean isConnected() {
return (this.peer != null) && (this.peer.isConnected());
}
/* (non-Javadoc)
* @see net.jenet.api.Connection#send(net.jenet.api.Endpoint.ProtocolType, java.lang.Object)
*/
@Override
public void send(int protocolFlags, NetMessage msg) throws IOException {
if(isConnected()) {
Message packet = writeMessage(protocolFlags, msg);
peer.send(packet);
}
}
/* (non-Javadoc)
* @see net.jenet.api.Connection#getRemoteAddress()
*/
@Override
public InetSocketAddress getRemoteAddress() {
return (this.peer !=null) ? this.peer.getAddress() : null;
}
/*
* (non-Javadoc)
* @see harenet.api.Client#connect(int, java.net.InetSocketAddress)
*/
@Override
public boolean connect(int timeout, InetSocketAddress address)
throws IOException {
host = new Host(getNetConfig(), null);
peer=host.connect(address);
this.connectionId = peer.getId();
int attemptsRemaining = 5;
do {
update(timeout);
} while( !peer.isConnected() && peer.isDeniedConnection() && attemptsRemaining-- > 0);
return peer.isConnected();
}
/* (non-Javadoc)
* @see net.jenet.api.Client#setKeepAlive(int)
*/
@Override
public void setKeepAlive(int keepAliveMillis) {
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#close()
*/
@Override
public void close() {
try {
if(this.peer != null && this.peer.isConnected()) {
this.peer.disconnect();
update(100);
}
}
catch(Exception ignore) {
}
finally {
try {
if(host!=null) {
host.destroy();
}
}
catch(Exception ignore) {
}
}
}
/* (non-Javadoc)
* @see net.jenet.api.Endpoint#update(int)
*/
@Override
public void update(int timeout) {
if (host != null) {
synchronized(host) {
try {
host.update(this.listener, timeout);
}
catch (IOException e) {
host.getLogger().error(e.toString());
}
}
}
}
}
| 6,398 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PingMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/PingMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* Ping message. One side of the connection can initiate
* a {@link PingMessage} and the other side will respond back with
* a {@link PongMessage}. These messages are used to calculate the
* round trip time of a {@link Message}.
*
* @author Tony
*
*/
public class PingMessage extends AbstractMessage {
/**
* Cached instance to reduce GC load
*/
public static final PingMessage INSTANCE = new PingMessage();
/**
*/
public PingMessage() {
super(MessageHeader.PING_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return INSTANCE;
}
}
| 785 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ConnectionRequestMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/ConnectionRequestMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* A Client is requesting to connect to the server.
*
* @author Tony
*
*/
public class ConnectionRequestMessage extends AbstractReliableMessage {
/**
*/
public ConnectionRequestMessage() {
super(MessageHeader.CONNECTION_REQUEST_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return new ConnectionRequestMessage();
}
}
| 537 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
UnReliableNetMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/UnReliableNetMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* A network message that is <b>NOT</b> guaranteed to arrive at the peer. This message
* can contain a user defined {@link NetMessage} to transfer.
*
* @author Tony
*
*/
public class UnReliableNetMessage extends AbstractMessage {
/**
*/
public UnReliableNetMessage() {
super(MessageHeader.UNRELIABLE_NETMESSAGE);
}
public UnReliableNetMessage(NetMessage message, short length) {
super(MessageHeader.UNRELIABLE_NETMESSAGE, message, length);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return new UnReliableNetMessage(getMessage(), this.sizeInBytes);
}
}
| 789 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerFullMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/ServerFullMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* The server is full, no connection for you!
*
* @author Tony
*
*/
public class ServerFullMessage extends AbstractMessage {
public static final ServerFullMessage INSTANCE = new ServerFullMessage();
/**
*/
public ServerFullMessage() {
super(MessageHeader.SERVER_FULL_MESSAGE);
}
@Override
public Message copy() {
return new ServerFullMessage();
}
}
| 503 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HeartbeatMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/HeartbeatMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* Simple message to let the other side know we are still alive.
*
* @author Tony
*
*/
public class HeartbeatMessage extends AbstractMessage {
/**
* Cached instance to reduce GC load
*/
public static final HeartbeatMessage INSTANCE = new HeartbeatMessage();
/**
*/
public HeartbeatMessage() {
super(MessageHeader.HEARTBEAT_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return INSTANCE;
}
}
| 640 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
NetMessageFactory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/NetMessageFactory.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.IOBuffer;
/**
* Generates {@link NetMessage}'s based off network message.
*
* @author Tony
*
*/
public interface NetMessageFactory {
/**
* Reads the {@link IOBuffer} and creates the corresponding {@link NetMessage}.
*
* @param buffer
* @return the {@link NetMessage} object
*/
public NetMessage readNetMessage(IOBuffer buffer);
}
| 441 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AbstractMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/AbstractMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.IOBuffer;
import harenet.MessageHeader;
/**
* Basis for {@link Message}s. This holds all possible information and subclasses
* may or may not use some of the information. This strategy was chosen to simplify
* the rest of the code -- it can assume all Messages have NetMessages or are Reliable
* if need be.
*
* @author Tony
*
*/
public abstract class AbstractMessage implements Message {
/* the type is the only value sent over the wire for this class */
protected byte type;
protected short sizeInBytes;
protected int messageId;
protected NetMessage message;
private int numberOfDelays;
/** Tracking the Acknowledgement of the message */
private transient long timeSent = -1;
private transient int sequenceNumberSent = -1;
private transient int sequencesSent = 0;
private transient long timeReceived;
/**
* @param type
*/
public AbstractMessage(byte type) {
this.type = type;
}
/**
* @param data
* @param length
* @param flags
*/
public AbstractMessage(byte type, NetMessage message, short length) {
this.type = type;
this.sizeInBytes = length;
this.message = message;
this.numberOfDelays = 0;
}
/* (non-Javadoc)
* @see netspark.Transmittable#writeTo(java.nio.ByteBuffer)
*/
@Override
public void writeTo(IOBuffer buffer) {
buffer.putByte(type);
writeHeader(buffer);
if(type >= MessageHeader.RELIABLE_NETMESSAGE) {
message.write(buffer);
}
}
/**
* Write the header information
*
* @param buffer
*/
protected void writeHeader(IOBuffer buffer) {
}
/*
* (non-Javadoc)
* @see harenet.Transmittable#readFrom(harenet.IOBuffer, harenet.messages.NetMessageFactory)
*/
@Override
public void readFrom(IOBuffer buffer, NetMessageFactory messageFactory) {
// NOTE: the type is read from the MessageHeader
readHeader(buffer);
if(type >= MessageHeader.RELIABLE_NETMESSAGE) {
message = messageFactory.readNetMessage(buffer);
}
}
/**
* Reads the header information
*
* @param buffer
*/
protected void readHeader(IOBuffer buffer) {
}
/* (non-Javadoc)
* @see netspark.messages.Message#isReliable()
*/
@Override
public boolean isReliable() {
return false;
}
/* (non-Javadoc)
* @see netspark.messages.Message#getMessageId()
*/
@Override
public int getMessageId() {
return this.messageId;
}
/* (non-Javadoc)
* @see netspark.messages.Message#setMessageId(int)
*/
@Override
public void setMessageId(int messageId) {
this.messageId = messageId;
}
/**
* @return the timeSent
*/
public long getTimeSent() {
return timeSent;
}
/* (non-Javadoc)
* @see netspark.messages.Message#getTimeReceived()
*/
@Override
public long getTimeReceived() {
return this.timeReceived;
}
/* (non-Javadoc)
* @see netspark.messages.Message#setTimeReceived(long)
*/
@Override
public void setTimeReceived(long timeReceived) {
this.timeReceived = timeReceived;
}
/**
* @param timeSent the timeSent to set
*/
public void setTimeSent(long timeSent) {
this.timeSent = timeSent;
}
/**
* @return true if this message has been sent at least once
*/
public boolean hasBeenSent() {
return this.timeSent > -1;
}
/**
* @return the sequenceNumberSent
*/
public int getSequenceNumberSent() {
return sequenceNumberSent;
}
/**
* @param sequenceNumberSent the sequenceNumberSent to set
*/
public void setSequenceNumberSent(int sequenceNumberSent) {
this.sequenceNumberSent = sequenceNumberSent;
}
/**
* Adds the number attempts this was sent
*/
public void addSequenceNumberSent() {
this.sequencesSent++;
}
/**
* @return the sequencesSent
*/
public int getSequencesSent() {
return sequencesSent;
}
/* (non-Javadoc)
* @see netspark.messages.Message#getMessage()
*/
@Override
public NetMessage getMessage() {
return message;
}
/* (non-Javadoc)
* @see netspark.messages.Message#getSize()
*/
@Override
public short getSize() {
return (short)(this.sizeInBytes + 2);
}
/* (non-Javadoc)
* @see netspark.messages.Message#getNumberOfDelays()
*/
@Override
public int getNumberOfDelays() {
return this.numberOfDelays;
}
/* (non-Javadoc)
* @see netspark.messages.Message#delay()
*/
@Override
public void delay() {
this.numberOfDelays++;
}
}
| 5,087 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PongMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/PongMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* Pong message, this is a response from a {@link PingMessage}.
* This Ping/Pong is used to calculate round trip time (ping).
*
* @author Tony
*
*/
public class PongMessage extends AbstractMessage {
/**
* Cached instance to reduce GC load
*/
public static final PongMessage INSTANCE = new PongMessage();
/**
*/
public PongMessage() {
super(MessageHeader.PONG_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return INSTANCE;
}
}
| 685 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AbstractReliableMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/AbstractReliableMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.IOBuffer;
/**
* Represents a reliable message. These types of messages will be sent
* to until acknowledgment has been received.
*
* @author Tony
*
*/
public abstract class AbstractReliableMessage extends AbstractMessage {
/**
* @param type
*/
public AbstractReliableMessage(byte type) {
super(type);
}
/**
* @param type
* @param message
* @param length
*/
public AbstractReliableMessage(byte type, NetMessage message, short length) {
super(type, message, length);
}
/* (non-Javadoc)
* @see netspark.messages.AbstractMessage#getSize()
*/
@Override
public short getSize() {
return (short)(super.getSize() + 4);
}
/* (non-Javadoc)
* @see netspark.messages.AbstractMessage#isReliable()
*/
@Override
public boolean isReliable() {
return true;
}
/*
* (non-Javadoc)
* @see netspark.messages.AbstractMessage#readHeader(netspark.IOBuffer)
*/
protected void readHeader(IOBuffer buffer) {
this.messageId = buffer.getInt();
}
/*
* (non-Javadoc)
* @see netspark.messages.AbstractMessage#writeHeader(netspark.IOBuffer)
*/
protected void writeHeader(IOBuffer buffer) {
buffer.putInt(messageId);
}
}
| 1,407 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ReliableNetMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/ReliableNetMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* A Reliable message is one that is guaranteed to make it to the peer. This message
* can contain a user defined {@link NetMessage} to transfer.
*
* @author Tony
*
*/
public class ReliableNetMessage extends AbstractReliableMessage {
/**
*/
public ReliableNetMessage() {
super(MessageHeader.RELIABLE_NETMESSAGE);
}
public ReliableNetMessage(NetMessage message, short length) {
super(MessageHeader.RELIABLE_NETMESSAGE, message, length);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return new ReliableNetMessage(getMessage(), this.sizeInBytes);
}
}
| 797 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ConnectionAcceptedMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/ConnectionAcceptedMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* The connection has been accepted by the server
*
* @author Tony
*
*/
public class ConnectionAcceptedMessage extends AbstractReliableMessage {
/**
*/
public ConnectionAcceptedMessage() {
super(MessageHeader.CONNECTION_ACCEPTED_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return new ConnectionAcceptedMessage();
}
}
| 539 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
NetMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/NetMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.IOBuffer;
import java.nio.ByteBuffer;
/**
* A network message. Clients of the Harenet API can implement
* there own {@link NetMessage}'s to transmit.
*
* @author Tony
*
*/
public interface NetMessage {
/**
* Reads from the {@link ByteBuffer}
* @param buffer
*/
public void read(IOBuffer buffer);
/**
* Writes to the {@link ByteBuffer}
* @param buffer
*/
public void write(IOBuffer buffer);
}
| 532 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DisconnectMessage.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/DisconnectMessage.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.MessageHeader;
/**
* A client is requesting to disconnect
*
* @author Tony
*
*/
public class DisconnectMessage extends AbstractMessage {
/**
*/
public DisconnectMessage() {
super(MessageHeader.DISCONNECT_MESSAGE);
}
/* (non-Javadoc)
* @see netspark.messages.Message#copy()
*/
@Override
public Message copy() {
return new DisconnectMessage();
}
}
| 492 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Message.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/harenet/messages/Message.java | /*
* see license.txt
*/
package harenet.messages;
import harenet.Transmittable;
/**
* A message is a protocol level way is distributing isRotated of information from Host to Peer.
*
* Messages are packed into UDP datagram packets and sent to the Peer. Clients of the Harenet
* API should not use this interface to create custom messages, instead they should use the {@link NetMessage}.
*
* @see NetMessage
* @author Tony
*
*/
public interface Message extends Transmittable {
/**
* @return the timeSent
*/
public long getTimeSent();
/**
* @return the message id
*/
public int getMessageId();
/**
* @param messageId
*/
public void setMessageId(int messageId);
/**
* @param timeReceived
*/
public void setTimeReceived(long timeReceived);
/**
* @return the time this message was received
*/
public long getTimeReceived();
/**
* @param timeSent the timeSent to set
*/
public void setTimeSent(long timeSent);
/**
* @return true if this message has been sent at least once
*/
public boolean hasBeenSent();
/**
* @return the sequenceNumberSent
*/
public int getSequenceNumberSent();
/**
* @param sequenceNumberSent the sequenceNumberSent to set
*/
public void setSequenceNumberSent(int sequenceNumberSent);
/**
* Adds the number attempts this was sent
*/
public void addSequenceNumberSent();
/**
* @return the sequencesSent
*/
public int getSequencesSent();
/**
* @return true if a reliable message
*/
public boolean isReliable();
/**
* @return the messages data
*/
public NetMessage getMessage();
/**
* @return the size of this message
*/
public short getSize();
/**
* @return the number of times this message
* missed transporting because of its size
* (not fitting into the packet)
*/
public int getNumberOfDelays();
/**
* Delay this message from being sent
* out -- this is due to not fitting
* within the available Packet space.
*/
public void delay();
/**
* @return a copy of this message
*/
public Message copy();
}
| 2,343 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ClientMain.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ClientMain.java | /*
* See license
*/
package seventh;
import java.io.File;
import java.io.PrintStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics.DisplayMode;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.GL20;
import seventh.client.ClientSeventhConfig;
import seventh.client.SeventhGame;
import seventh.client.gfx.VideoConfig;
import seventh.shared.Config;
import seventh.shared.Logger;
import seventh.shared.PrintStreamLogger;
/**
* Main entry point for the client game
*
* @author Tony
*
*/
public class ClientMain {
/**
* Client configuration file location
*/
private static final String CLIENT_CFG_PATH = "./assets/client_config.leola";
/**
* Loads the client configuration file.
*
* @return the client configuration file
* @throws Exception
*/
private static ClientSeventhConfig loadConfig() throws Exception {
Config config = new Config(CLIENT_CFG_PATH, "client_config");
return new ClientSeventhConfig(config);
}
/**
* Attempts to find the best display mode
* @param config
* @return the best display mode
* @throws Exception
*/
private static DisplayMode findBestDimensions(VideoConfig config) throws Exception {
if(config.isPresent()) {
int width = config.getWidth();
int height = config.getHeight();
DisplayMode[] modes = LwjglApplicationConfiguration.getDisplayModes();
for(DisplayMode mode : modes) {
if(mode.width == width && mode.height == height) {
return mode;
}
}
}
return LwjglApplicationConfiguration.getDesktopDisplayMode();
}
/**
* Handle the exception -- piping out to a log file
* @param e
*/
private static void catchException(Throwable e) {
try {
PrintStream out = new PrintStream(new File("./seventh_error.log"));
try {
Logger logger = new PrintStreamLogger(out);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
logger.println("Date: " + formatter.format(new Date()));
logSystemSpecs(logger);
logVideoSpecs(logger);
e.printStackTrace(out);
}
finally {
out.close();
}
}
catch(Exception e1) {
e1.printStackTrace();
}
finally {
System.exit(1);
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
ClientSeventhConfig config = null;
try {
/*
* LibGDX spawns another thread which we don't have access
* to for catching its exceptions
*/
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
if(t.getName().equals("LWJGL Application")) {
catchException(e);
}
}
});
config = loadConfig();
VideoConfig vConfig = config.getVideo();
DisplayMode displayMode = findBestDimensions(vConfig);
LwjglApplicationConfiguration.disableAudio = true;
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
cfg.setFromDisplayMode(displayMode);
cfg.fullscreen = vConfig.isFullscreen();
cfg.title = "The Seventh " + SeventhGame.getVersion();
cfg.forceExit = true;
cfg.resizable = true;
cfg.useGL30 = vConfig.useGL30();
cfg.vSyncEnabled = vConfig.isVsync();
if(!cfg.fullscreen) {
cfg.width = 840;// 960;
cfg.height = 480; //600;
}
String startupScript = null;
if(args.length > 0) {
startupScript = args[0];
}
new LwjglApplication(new SeventhGame(config, startupScript), cfg);
}
catch(Exception e) {
catchException(e);
}
finally {
// System.exit(0);
if(config != null) {
//config.save(CLIENT_CFG_PATH);
}
}
}
public static void logVideoSpecs(Logger console) {
try {
if(Gdx.graphics != null) {
console.println("GL30: " + Gdx.graphics.isGL30Available());
console.println("OpenGL Version: " + Gdx.gl.glGetString(GL20.GL_VERSION));
console.println("OpenGL Vendor: " + Gdx.gl.glGetString(GL20.GL_VENDOR));
console.println("Renderer: " + Gdx.gl.glGetString(GL20.GL_RENDERER));
console.println("Gdx Version: " + Gdx.app.getVersion());
console.println("Is Fullscreen: " + Gdx.graphics.isFullscreen());
}
else {
console.println("OpenGL Version: " + Gdx.gl.glGetString(GL20.GL_VERSION));
console.println("OpenGL Vendor: " + Gdx.gl.glGetString(GL20.GL_VENDOR));
console.println("Renderer: " + Gdx.gl.glGetString(GL20.GL_RENDERER));
}
}
catch(Throwable t) {
console.println("Error retrieving video specifications: " + t);
}
}
/**
* Prints out system specifications
*
* @param console
*/
public static void logSystemSpecs(Logger console) {
Runtime runtime = Runtime.getRuntime();
final long MB = 1024 * 1024;
console.println("");
console.println("Seventh: " + SeventhGame.getVersion());
console.println("Available processors (cores): " + runtime.availableProcessors());
console.println("Free memory (MiB): " + runtime.freeMemory() / MB);
console.println("Max memory (MiB): " + (runtime.maxMemory() == Long.MAX_VALUE ? "no limit" : Long.toString(runtime.maxMemory() / MB)) );
console.println("Available for JVM (MiB): " + runtime.totalMemory() / MB);
/* Get a list of all filesystem roots on this system */
File[] roots = File.listRoots();
/* For each filesystem root, print some info */
for (File root : roots) {
console.println("File system root: " + root.getAbsolutePath());
console.println("\tTotal space (MiB): " + root.getTotalSpace() / MB);
console.println("\tFree space (MiB): " + root.getFreeSpace() / MB);
console.println("\tUsable space (MiB): " + root.getUsableSpace() / MB);
}
console.println("Java Version: " + System.getProperty("java.version"));
console.println("Java Vendor: " + System.getProperty("java.vendor"));
console.println("Java VM Version: " + System.getProperty("java.vm.version"));
console.println("Java VM Name: " + System.getProperty("java.vm.name"));
console.println("Java Class Version: " + System.getProperty("java.class.version"));
console.println("Java VM Spec. Version: " + System.getProperty("java.vm.specification.version"));
console.println("Java VM Spec. Vendor: " + System.getProperty("java.vm.specification.vendor"));
console.println("Java VM Spec. Name: " + System.getProperty("java.vm.specification.name"));
console.println("OS: " + System.getProperty("os.name"));
console.println("OS Arch: " + System.getProperty("os.arch"));
console.println("OS Version: " + System.getProperty("os.version"));
console.println("");
}
}
| 8,349 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerMain.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ServerMain.java | /*
* see license.txt
*/
package seventh;
import java.util.Scanner;
import leola.vm.Leola;
import seventh.server.GameServer;
import seventh.server.ServerSeventhConfig;
import seventh.shared.Config;
import seventh.shared.Cons;
import seventh.shared.Console;
import seventh.shared.ConsoleFrame;
import seventh.shared.DefaultConsole;
import seventh.shared.Scripting;
import seventh.shared.SeventhConstants;
/**
* Main entry point for the server
*
* @author Tony
*
*/
public class ServerMain {
private static final String BANNER =
"\n\n\n\t\t*** The Seventh Server ***\n" +
"\t\t 5d Studios (c)\n\n"
;
public static void main(final String [] args) {
final Console console = new DefaultConsole();
Cons.setImpl(console);
final Thread gameThread = new Thread(new Runnable() {
@Override
public void run() {
try {
int port = SeventhConstants.DEFAULT_PORT;
Leola runtime = Scripting.newRuntime();
ServerSeventhConfig config = new ServerSeventhConfig(new Config("./assets/server_config.leola", "server_config", runtime));
GameServer server = new GameServer(config, console, runtime);
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
}
catch(Exception e) {
port = config.getPort();
}
}
else {
port = config.getPort();
}
server.start(port);
}
catch (Exception e) {
console.println("An error occured with the server: " + e);
}
}
});
if (isCmdLineOnly(args)) {
gameThread.start();
setupCommandLine(console);
}
else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ConsoleFrame("The Seventh Server", BANNER, console);
gameThread.start();
}
});
}
}
private static boolean isCmdLineOnly(String [] args) {
for(int i = 0; i < args.length; i++) {
if(args[i].trim().equalsIgnoreCase("-c")) {
return true;
}
}
return false;
}
private static void setupCommandLine(Console console) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNext()) {
String in = scanner.nextLine();
if(in != null && in.length() > 0) {
console.execute(in.trim());
}
}
}
finally {
scanner.close();
}
}
}
| 3,127 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Controllable.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Controllable.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.entities.Entity;
/**
* Allows an {@link Entity} to be responsive to {@link UserCommand}'s
*
* @author Tony
*
*/
public interface Controllable {
/**
* Handles the users input commands
*
* @param keys
* @param orientation
*/
public void handleUserCommand(int keys, float orientation);
}
| 409 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PlayerClass.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/PlayerClass.java | /*
* see license.txt
*/
package seventh.game;
import static seventh.game.entities.Entity.Type.KAR98;
import static seventh.game.entities.Entity.Type.M1_GARAND;
import static seventh.game.entities.Entity.Type.MP40;
import static seventh.game.entities.Entity.Type.MP44;
import static seventh.game.entities.Entity.Type.SPRINGFIELD;
import static seventh.game.entities.Entity.Type.THOMPSON;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.PlayerEntity;
/**
* Represents a {@link PlayerEntity} class, which limits or enhancements
* their abilities.
*
* @author Tony
*
*/
public class PlayerClass {
public enum WeaponClass {
/* American version first, then German */
PISTOL(Type.PISTOL),
GRENADE(Type.GRENADE),
SMOKE_GRENADE(Type.SMOKE_GRENADE),
SMG(THOMPSON, MP40),
RIFLE(M1_GARAND, MP44),
RISKER(Type.RISKER),
SNIPER(SPRINGFIELD, KAR98),
SHOTGUN(Type.SHOTGUN),
FLAME_THROWER(Type.FLAME_THROWER),
ROCKET_LAUNCHER(Type.ROCKET_LAUNCHER),
HAMMER(Type.HAMMER)
;
private List<Type> weapons;
private WeaponClass(Type ...weapons) {
this.weapons = Arrays.asList(weapons);
}
/**
* @return the weapons
*/
public Collection<Type> getWeapons() {
return weapons;
}
/**
* If this class contains the weapon
*
* @param weapon
* @return
*/
public boolean hasWeapon(Type weapon) {
return weapons.contains(weapon);
}
public Type getTeamWeapon(Team team) {
if(team.getId() == Team.ALLIED_TEAM_ID) {
return getAlliedWeapon();
}
if(team.getId() == Team.AXIS_TEAM_ID) {
return getAxisWeapon();
}
return null;
}
public Type getAlliedWeapon() {
return weapons.get(0);
}
public Type getAxisWeapon() {
if(weapons.size() > 1) {
return weapons.get(1);
}
return weapons.get(0);
}
}
public static class WeaponEntry {
public WeaponClass type;
public int ammoBag;
public WeaponEntry(WeaponClass type, int ammoBag) {
this.type = type;
this.ammoBag = ammoBag;
}
}
private static WeaponEntry entry(WeaponClass type, int ammoBag) {
return new WeaponEntry(type, ammoBag);
}
private static WeaponEntry entry(WeaponClass type) {
return entry(type, -1);
}
public static PlayerClass fromNet(byte classId) {
switch(classId) {
case 1: return Engineer;
case 2: return Scout;
case 3: return Infantry;
case 4: return Demolition;
default: return Default;
}
}
public static byte toNet(PlayerClass playerClass) {
if(playerClass == Engineer) return 1;
if(playerClass == Scout) return 2;
if(playerClass == Infantry) return 3;
if(playerClass == Demolition) return 4;
return 4;
}
public static PlayerClass Engineer = new PlayerClass(100, 0, 20,
Arrays.asList(entry(WeaponClass.HAMMER, 1)),
Arrays.asList(entry(WeaponClass.HAMMER, 1), entry(WeaponClass.PISTOL), entry(WeaponClass.GRENADE, 2)),
WeaponClass.HAMMER);
public static PlayerClass Scout = new PlayerClass(0, 50, 0,
Arrays.asList(entry(WeaponClass.SMG),
entry(WeaponClass.SHOTGUN)),
Arrays.asList(entry(WeaponClass.PISTOL), entry(WeaponClass.GRENADE, 2)),
WeaponClass.SMG);
public static PlayerClass Infantry = new PlayerClass(0, 0, 0,
Arrays.asList(entry(WeaponClass.SMG),
entry(WeaponClass.RIFLE),
entry(WeaponClass.RISKER),
entry(WeaponClass.SNIPER),
entry(WeaponClass.SHOTGUN)),
Arrays.asList(entry(WeaponClass.PISTOL), entry(WeaponClass.GRENADE, 1)),
WeaponClass.SMG);
public static PlayerClass Demolition= new PlayerClass(0, -20, 20,
Arrays.asList(entry(WeaponClass.FLAME_THROWER),
entry(WeaponClass.ROCKET_LAUNCHER)),
Arrays.asList(entry(WeaponClass.SMG), entry(WeaponClass.PISTOL), entry(WeaponClass.GRENADE, 1)),
WeaponClass.ROCKET_LAUNCHER);
public static PlayerClass Default = new PlayerClass(0, 0, 0,
Arrays.asList(entry(WeaponClass.SMG),
entry(WeaponClass.RIFLE),
entry(WeaponClass.RISKER),
entry(WeaponClass.SNIPER),
entry(WeaponClass.SHOTGUN),
entry(WeaponClass.FLAME_THROWER),
entry(WeaponClass.ROCKET_LAUNCHER)),
Arrays.asList(entry(WeaponClass.PISTOL), entry(WeaponClass.GRENADE, 1)),
WeaponClass.SMG);
private int healthMultiplier;
private int speedMultiplier;
private int damageMultiplier;
private List<WeaponEntry> availableWeapons;
private List<WeaponEntry> defaultWeapons;
private WeaponClass defaultPrimaryWeapon;
/**
* @param healthMultiplier
* @param speedMultiplier
* @param damageMultiplier
* @param availableWeapons
* @param defaultWeapons
* @param defaultPrimaryWeapon
*/
public PlayerClass(int healthMultiplier,
int speedMultiplier,
int damageMultiplier,
List<WeaponEntry> availableWeapons,
List<WeaponEntry> defaultWeapons,
WeaponClass defaultPrimaryWeapon) {
this.healthMultiplier = healthMultiplier;
this.speedMultiplier = speedMultiplier;
this.damageMultiplier = damageMultiplier;
this.availableWeapons = availableWeapons;
this.defaultWeapons = defaultWeapons;
this.defaultPrimaryWeapon = defaultPrimaryWeapon;
}
/**
* @return the healthMultiplier
*/
public int getHealthMultiplier() {
return healthMultiplier;
}
/**
* @return the speedMultiplier
*/
public int getSpeedMultiplier() {
return speedMultiplier;
}
/**
* @return the damageMultiplier
*/
public int getDamageMultiplier() {
return damageMultiplier;
}
/**
* @return the availableWeapons
*/
public List<WeaponEntry> getAvailableWeapons() {
return availableWeapons;
}
/**
* @return the defaultWeapons
*/
public List<WeaponEntry> getDefaultWeapons() {
return defaultWeapons;
}
/**
* @return the defaultPrimaryWeapon
*/
public WeaponClass getDefaultPrimaryWeapon() {
return defaultPrimaryWeapon;
}
/**
* Determines if the supplied weapon type is an available option for this player class
*
* @param weaponType
* @return true if the weapon is available
*/
public boolean isAvailableWeapon(Type weaponType) {
return getAvailableWeaponEntry(weaponType) != null;
}
/**
* Get the {@link WeaponEntry} for the supplied weapontype
*
* @param weaponType
* @return the {@link WeaponEntry} or null if not an option
*/
public WeaponEntry getAvailableWeaponEntry(Type weaponType) {
for(int i = 0; i < availableWeapons.size(); i++) {
WeaponEntry entry = availableWeapons.get(i);
if(entry.type.hasWeapon(weaponType)) {
return entry;
}
}
return null;
}
}
| 9,851 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Inventory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Inventory.java | /*
* see license.txt
*/
package seventh.game;
import java.util.ArrayList;
import java.util.List;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.Flag;
import seventh.game.weapons.GrenadeBelt;
import seventh.game.weapons.Weapon;
/**
* A {@link Player}s current inventory of {@link Weapon}s.
*
* @author Tony
*
*/
public class Inventory {
private List<Weapon> weapons;
private final int maxPrimaryWeapons;
private int currentItem;
private GrenadeBelt grenades;
private Flag carriedFlag;
public Inventory(int maxPrimaryWeapons) {
this.maxPrimaryWeapons = maxPrimaryWeapons;
this.weapons = new ArrayList<Weapon>();
this.currentItem = 0;
}
/**
* Pickup a flag
*
* @param flag
*/
public void pickupFlag(Flag flag) {
this.carriedFlag = flag;
}
/**
* Drops the flag if carrying one
*/
public void dropFlag() {
if(this.carriedFlag!=null) {
Flag flag = this.carriedFlag;
this.carriedFlag = null;
flag.drop();
}
}
public boolean isCarryingFlag() {
return this.carriedFlag != null;
}
public boolean hasGrenades() {
return grenades != null && grenades.isLoaded();
}
/**
* @return the grenades
*/
public GrenadeBelt getGrenades() {
return grenades;
}
/**
* Adds a Weapon to the inventory
*
* @param item
* @return true if the weapon was picked up
*/
public boolean addItem(Weapon item) {
if(item instanceof GrenadeBelt) {
this.grenades = (GrenadeBelt)item;
return true;
}
else {
if(numberOfPrimaryItems() < this.maxPrimaryWeapons || !item.isPrimary()) {
this.weapons.add(item);
return true;
}
}
return false;
}
/**
* @param item
* @return true if the weapon type exists in this inventory
*/
public boolean hasItem(Type item) {
return getItem(item) != null;
}
/**
* @param item
* @return the Weapon of type 'item' or null if not in the inventory
*/
public Weapon getItem(Type item) {
for(Weapon w : weapons) {
if(w.getType().equals(item)) {
return w;
}
}
return null;
}
public void clear() {
this.grenades = null;
this.weapons.clear();
}
public void removeItem(Weapon item) {
this.weapons.remove(item);
}
public Weapon currentItem() {
return (this.weapons.isEmpty()) ? null :
this.weapons.get(this.currentItem);
}
public Weapon nextItem() {
currentItem += 1;
if(currentItem >= weapons.size()) {
currentItem = 0;
}
return currentItem();
}
public Weapon prevItem() {
currentItem -= 1;
if( currentItem < 0) {
currentItem = Math.max(weapons.size() - 1, 0);
}
return currentItem();
}
/**
* Equips the desired item
* @param item
* @return the Weapon
*/
public Weapon equipItem(Type item) {
for(int i = 0; i < weapons.size(); i++) {
if(weapons.get(i).getType().equals(item)) {
currentItem = i;
break;
}
}
return currentItem();
}
/**
* Number of weapons currently held
* @return Number of weapons currently held
*/
public int numberOfItems() {
return this.weapons.size();
}
public int numberOfPrimaryItems() {
int numberOfPrimary = 0;
for(int i = 0; i < weapons.size(); i++) {
if(weapons.get(i).isPrimary()) {
numberOfPrimary++;
}
}
return numberOfPrimary;
}
/**
* @return true if the primary weapon storage is full
*/
public boolean isPrimaryFull() {
return numberOfPrimaryItems() >= this.maxPrimaryWeapons;
}
/**
* @return the weapons
*/
public List<Weapon> getItems() {
return weapons;
}
}
| 4,333 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Triggers.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Triggers.java | /*
* see license.txt
*/
package seventh.game;
import java.util.ArrayList;
import java.util.List;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* Handles management of triggers
*
* @author Tony
*
*/
public class Triggers implements Updatable {
private List<Trigger> triggers, pendingTriggers;
private Game game;
/**
*
*/
public Triggers(Game game) {
this.game = game;
this.triggers = new ArrayList<>();
this.pendingTriggers = new ArrayList<>();
}
@Override
public void update(TimeStep timeStep) {
this.pendingTriggers.clear();
for(int i = 0; i < this.triggers.size(); i++) {
Trigger trigger = this.triggers.get(i);
if(!trigger.checkCondition(game)) {
this.pendingTriggers.add(trigger);
}
else {
trigger.execute(game);
}
}
this.triggers.clear();
this.triggers.addAll(pendingTriggers);
}
public Triggers addTrigger(Trigger trigger) {
this.triggers.add(trigger);
return this;
}
/**
* Removes all triggers
* @return
*/
public Triggers removeTriggers() {
this.triggers.clear();
return this;
}
}
| 1,335 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PlayerAwardSystem.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/PlayerAwardSystem.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.events.KillRollEvent;
import seventh.game.events.KillStreakEvent;
import seventh.game.events.PlayerAwardEvent;
import seventh.game.events.PlayerJoinedEvent;
import seventh.game.events.PlayerJoinedListener;
import seventh.game.events.PlayerKilledEvent;
import seventh.game.events.PlayerKilledListener;
import seventh.game.events.PlayerLeftEvent;
import seventh.game.events.PlayerLeftListener;
import seventh.game.events.RoundEndedEvent;
import seventh.game.events.RoundEndedListener;
import seventh.game.events.RoundStartedEvent;
import seventh.game.events.RoundStartedListener;
import seventh.shared.EventDispatcher;
import seventh.shared.SeventhConstants;
/**
* Keeps track of player stats for kill streaks and bonuses
*
* @author Tony
*
*/
public class PlayerAwardSystem {
/**
* Type of award
*
* @author Tony
*
*/
public static enum Award {
FirstBlood,
KillStreak,
KillRoll,
// death awards
Coward,
Excellence,
BeastMode,
FavreMode,
// kill awards
Participation,
Marksman,
BadMan,
Rodgers,
;
public byte netValue() {
return (byte)ordinal();
}
private static Award[] values = values();
public static Award fromNetValue(byte b) {
return values[b];
}
/**
* @return number of bits it takes to represent this
* enum
*/
public static int numOfBits() {
return 5;
}
}
private static class PlayerStats {
int kills;
int deaths;
int killStreak;
int highestKillStreak;
int killRoll;
long lastKillTime;
Player player;
EventDispatcher dispatcher;
public PlayerStats(Player player, EventDispatcher dispatcher) {
this.player = player;
this.dispatcher = dispatcher;
}
public void roundReset() {
this.killStreak = 0;
this.lastKillTime = 0;
}
public void roundEnded() {
if(deaths == 0) {
if(kills == 0) {
// send out coward award
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Coward));
}
else if(kills < 5) {
// send out
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Excellence));
}
else if(kills < 10) {
// send out
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BeastMode));
}
else {
// send out
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.FavreMode));
}
}
float ratio = 1.0f;
if(deaths>0) {
ratio = kills / deaths;
}
if(kills == 0) {
// send out worthless award
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Participation));
}
else {
if(ratio > .90f) {
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Rodgers));
}
else if(ratio > .70f) {
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BadMan));
}
else if(ratio > .60f) {
dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Marksman));
}
}
}
public void addKill() {
this.killStreak++;
if(this.killStreak > this.highestKillStreak) {
this.highestKillStreak = this.killStreak;
}
// if the kill streak is worthy, send out an event
switch(this.killStreak) {
case 3:
case 5:
case 10:
case 15:
dispatcher.queueEvent(new KillStreakEvent(this, player, this.killStreak));
break;
}
// TODO - use game time, instead of wall time
long killTime = System.currentTimeMillis();
if(killTime-this.lastKillTime < 3000) {
this.killRoll++;
// if we have multiple kills within the kill time frame,
// send out an event of this players awesomeness
if(this.killRoll>1) {
dispatcher.queueEvent(new KillRollEvent(this, player, this.killRoll));
}
}
else {
this.killRoll = 1;
}
this.lastKillTime = killTime;
this.kills++;
}
public void addDeath() {
this.killStreak = 0;
this.killRoll = 0;
this.deaths++;
}
}
private PlayerStats[] stats;
private boolean firstBlood;
/**
*
*/
public PlayerAwardSystem(Game game) {
this.stats = new PlayerStats[SeventhConstants.MAX_PLAYERS];
final EventDispatcher dispatcher = game.getDispatcher();
dispatcher.addEventListener(PlayerJoinedEvent.class, new PlayerJoinedListener() {
@Override
public void onPlayerJoined(PlayerJoinedEvent event) {
stats[event.getPlayer().getId()] = new PlayerStats(event.getPlayer(), dispatcher);
}
});
dispatcher.addEventListener(PlayerLeftEvent.class, new PlayerLeftListener() {
@Override
public void onPlayerLeft(PlayerLeftEvent event) {
//stats[event.getPlayer().getId()] = null; // Do we need to do this?
}
});
dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() {
@Override
public void onPlayerKilled(PlayerKilledEvent event) {
Player killed = event.getPlayer();
int killerId = event.getKillerId();
if(isValidPlayerId(killerId)) {
if(killed!=null && !killed.isTeammateWith(killerId)) {
stats[killerId].addKill();
if(firstBlood) {
dispatcher.queueEvent(new PlayerAwardEvent(this, stats[killerId].player, Award.FirstBlood));
}
}
}
if(killed!=null && isValidPlayerId(killed.getId())) {
stats[killed.getId()].addDeath();
}
firstBlood = false;
}
});
dispatcher.addEventListener(RoundStartedEvent.class, new RoundStartedListener() {
@Override
public void onRoundStarted(RoundStartedEvent event) {
firstBlood = true;
for(int i = 0; i < stats.length; i++) {
if(stats[i]!=null) {
stats[i].roundReset();
}
}
}
});
dispatcher.addEventListener(RoundEndedEvent.class, new RoundEndedListener() {
@Override
public void onRoundEnded(RoundEndedEvent event) {
for(int i = 0; i < stats.length; i++) {
if(stats[i]!=null) {
stats[i].roundEnded();
}
}
}
});
}
private boolean isValidPlayerId(int playerId) {
return playerId >= 0 && playerId < this.stats.length && this.stats[playerId] != null;
}
}
| 8,473 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Players.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Players.java | /*
* see license.txt
*/
package seventh.game;
import java.util.Random;
import seventh.shared.SeventhConstants;
/**
* Simple structure that holds the Players, this structure allows for
* mutable operations on the list of Players.
*
* @author Tony
*
*/
public class Players implements PlayerInfos {
public static interface PlayerIterator {
public void onPlayer(Player player);
}
private Player[] players;
private Random random;
/**
*
*/
public Players() {
this.players = new Player[SeventhConstants.MAX_PLAYERS];
this.random = new Random();
}
/**
* @param id
* @return true if the supplied ID is valid
*/
public boolean isValidId(int id) {
return (id >= 0 & id < this.players.length);
}
/**
* @param id
* @return true if the supplied ID is valid and if there is currently a player associated
* with the ID
*/
public boolean hasPlayer(int id) {
return isValidId(id) && this.players[id] != null;
}
/**
* @return the max number of players allowed
*/
public int maxNumberOfPlayers() {
return this.players.length;
}
/**
* @param id
* @return the {@link Player}
*/
public Player getPlayer(int id) {
if(isValidId(id)) {
return this.players[id];
}
return null;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getPlayerInfo(int)
*/
@Override
public PlayerInfo getPlayerInfo(int id) {
return getPlayer(id);
}
/**
* Adds a {@link Player}
* @param player
*/
public void addPlayer(Player player) {
if(isValidId(player.getId())) {
this.players[player.getId()] = player;
}
}
/**
* Removes a {@link Player}
* @param id
* @return the {@link Player} if found
*/
public Player removePlayer(int id) {
Player player = null;
if(isValidId(id)) {
player = this.players[id];
this.players[id] = null;
}
return player;
}
/**
* Removes a {@link Player}
* @param player
* @return the {@link Player} if found
*/
public Player removePlayer(Player player) {
return removePlayer(player.getId());
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getNumberOfPlayers()
*/
@Override
public int getNumberOfPlayers() {
int sum = 0;
for(int i = 0; i < this.players.length; i++) {
if(this.players[i] != null) {
sum++;
}
}
return sum;
}
/**
* Iterates through all the available players, invoking the
* {@link PlayerIterator} for each player.
* @param it
*/
public void forEachPlayer(PlayerIterator it) {
for(int i = 0; i < this.players.length; i++) {
Player player = this.players[i];
if(player != null) {
it.onPlayer(player);
}
}
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#forEachPlayerInfo(seventh.game.Players.PlayerInfoIterator)
*/
@Override
public void forEachPlayerInfo(PlayerInfoIterator it) {
for(int i = 0; i < this.players.length; i++) {
Player player = this.players[i];
if(player != null) {
it.onPlayerInfo(player);
}
}
}
/**
* @return the underlying list of players. For performance reasons
* this array may contain empty slots, it is up to the client
* to filter these.
*/
public Player[] getPlayers() {
return this.players;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getPlayerInfos()
*/
@Override
public PlayerInfo[] getPlayerInfos() {
return this.players;
}
/**
* Resets all of the players statistics
*/
public void resetStats() {
for(int i = 0; i < this.players.length; i++) {
Player player = this.players[i];
if(player != null) {
player.resetStats();
}
}
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getRandomAlivePlayer()
*/
@Override
public Player getRandomAlivePlayer() {
int size = players.length;
int startingIndex = random.nextInt(size);
for(int i = 0; i < size; i++) {
Player player = players[(startingIndex + i) % size];
if(player != null && player.isAlive()) {
return player;
}
}
return null;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getPrevAlivePlayerFrom(seventh.game.Player)
*/
@Override
public Player getPrevAlivePlayerFrom(Player oldPlayer) {
if(oldPlayer == null ) return getRandomAlivePlayer();
int nextPlayerIndex = (oldPlayer.getId() - 1) % players.length;
if(nextPlayerIndex < 0) {
nextPlayerIndex = Math.max(players.length - 1, 0);
}
for(int i = 0; i < this.players.length; i++) {
Player player = this.players[nextPlayerIndex];
if(player != null) {
if(player.isAlive() && player != oldPlayer) {
return player;
}
}
nextPlayerIndex = (nextPlayerIndex - 1) % players.length;
if(nextPlayerIndex < 0) {
nextPlayerIndex = Math.max(players.length - 1, 0);
}
}
return null;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfos#getNextAlivePlayerFrom(seventh.game.Player)
*/
@Override
public Player getNextAlivePlayerFrom(Player oldPlayer) {
if(oldPlayer == null ) return getRandomAlivePlayer();
int nextPlayerIndex = (oldPlayer.getId() + 1) % players.length;
for(int i = 0; i < this.players.length; i++) {
Player player = this.players[nextPlayerIndex];
if(player != null) {
if(player.isAlive() && player != oldPlayer) {
return player;
}
}
nextPlayerIndex = (nextPlayerIndex + 1) % players.length;
}
return null;
}
}
| 6,546 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PlayerStatSystem.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/PlayerStatSystem.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.entities.Entity;
import seventh.game.events.PlayerKilledEvent;
import seventh.game.weapons.Bullet;
import seventh.game.weapons.Explosion;
import seventh.game.weapons.Fire;
/**
* @author Tony
*
*/
public class PlayerStatSystem {
private class PlayerStat {
Players players;
/**
* List of players that have damaged
* this player
*/
private Player[] playersWhoCausedDamage;
/**
* This player that we are keeping track of
* who shot them (for tracking assists)
*/
private int playerId;
private int numberOfBulletsFired;
private int numberOfHits;
PlayerStat(Players players, int playerId) {
this.players = players;
this.playerId = playerId;
this.playersWhoCausedDamage = new Player[players.maxNumberOfPlayers()];
}
private Entity getPlayer(Entity damager) {
Entity player = null;
if(damager.isPlayer()) {
player = damager;
}
else if(damager instanceof Bullet) {
Bullet bullet = (Bullet) damager;
player = bullet.getOwner();
}
else if(damager instanceof Explosion) {
Explosion explosion = (Explosion)damager;
player = explosion.getOwner();
}
else if(damager instanceof Fire) {
Fire fire = (Fire)damager;
player = fire.getOwner();
}
return player;
}
public void onBulletFired() {
this.numberOfBulletsFired++;
}
public void onDamaged(Entity damager) {
Entity player = getPlayer(damager);
// mark that the damager dealt damage
if(player!=null) {
int damagerId = player.getId();
if(this.players.isValidId(damagerId)) {
PlayerStat stat = stats[damagerId];
Player damagerPlayer = this.players.getPlayer(damagerId);
if(!damagerPlayer.isTeammateWith(this.playerId)) {
// mark this damagers hit
stat.numberOfHits++;
// mark that the damager dealt damage to this player
if(this.playerId != damagerId) {
this.playersWhoCausedDamage[damagerId] = damagerPlayer;
}
}
if(stat.numberOfBulletsFired > 0) {
damagerPlayer.setHitPercentage( (float)stat.numberOfHits / (float)stat.numberOfBulletsFired);
}
}
}
}
public void onDeath(Entity killer) {
Entity player = getPlayer(killer);
// don't give an assist to the killer
if(player!=null && this.players.isValidId(player.getId())) {
this.playersWhoCausedDamage[player.getId()] = null;
}
for(int i = 0; i < this.playersWhoCausedDamage.length; i++) {
Player p = this.playersWhoCausedDamage[i];
if(p!=null) {
p.incrementAssists();
}
this.playersWhoCausedDamage[i] = null;
}
}
public void reset() {
for(int i = 0; i < this.playersWhoCausedDamage.length; i++) {
this.playersWhoCausedDamage[i] = null;
}
}
}
private Players players;
private PlayerStat[] stats;
/**
*
*/
public PlayerStatSystem(final Game game) {
this.players = game.getPlayers();
this.stats = new PlayerStat[players.maxNumberOfPlayers()];
for(int i = 0; i < stats.length; i++) {
this.stats[i] = new PlayerStat(players, i);
}
}
public void onRoundStarted() {
for(int i = 0; i < stats.length; i++) {
this.stats[i].reset();
}
}
public void onPlayerKilled(PlayerKilledEvent event) {
Player killed = event.getPlayer();
killed.incrementDeaths();
stats[killed.getId()].onDeath(event.getKilledBy());
Player killer = players.getPlayer(event.getKillerId());
if (killer != null) {
// lose a point for team kills
if (killed.getTeam().getId() == killer.getTeam().getId()) {
killer.loseKill();
}
// lose a point for suicide
else if (killed.getId() == killer.getId()) {
killer.loseKill();
} else {
killer.incrementKills();
}
}
}
public void onPlayerDamaged(Entity damaged, Entity damager, int damage) {
if(damaged.isPlayer()) {
this.stats[damaged.getId()].onDamaged(damager);
}
}
public void onBulletFired(Entity owner) {
if(owner.isPlayer()) {
this.stats[owner.getId()].onBulletFired();
}
}
}
| 5,489 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Trigger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Trigger.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.entities.Entity;
import seventh.map.Tile;
/**
* Bind to either a {@link Tile} or an {@link Entity} to cause something to happen when a condition is
* met.
*
* @author Tony
*
*/
public interface Trigger {
/**
* The condition in which a {@link Trigger} is triggered
*
* @param game
* @return true if the condition is met
*/
public boolean checkCondition(Game game);
/**
* Executes the {@link Trigger}
*
* @param game
*/
public void execute(Game game);
}
| 600 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SmoothOrientation.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/SmoothOrientation.java | /*
* see license.txt
*/
package seventh.game;
import seventh.math.FastMath;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* @author Tony
*
*/
public class SmoothOrientation implements Updatable {
private float desiredOrientation;
private float orientation;
private Vector2f facing;
private double movementSpeed;
private boolean moved;
public SmoothOrientation(double movementSpeed) {
this.facing = new Vector2f();
this.movementSpeed = movementSpeed;
this.moved = false;
}
/**
* @return the desiredOrientation
*/
public float getDesiredOrientation() {
return desiredOrientation;
}
/**
* @return the orientation
*/
public float getOrientation() {
return orientation;
}
/**
* @return the movementSpeed
*/
public double getMovementSpeed() {
return movementSpeed;
}
/**
* @param movementSpeed the movementSpeed to set
*/
public void setMovementSpeed(double movementSpeed) {
this.movementSpeed = movementSpeed;
}
/**
* @param desiredOrientation the desiredOrientation to set
*/
public void setDesiredOrientation(float desiredOrientation) {
final float fullCircle = FastMath.fullCircle;
if(desiredOrientation < 0) {
desiredOrientation += fullCircle;
}
this.desiredOrientation = desiredOrientation;
}
/**
* @param orientation the orientation to set
*/
public void setOrientation(float orientation) {
this.orientation = orientation;
this.facing.set(1, 0); // make right vector
Vector2f.Vector2fRotate(this.facing, this.orientation, this.facing);
}
/**
* @return the facing
*/
public Vector2f getFacing() {
return facing;
}
public boolean moved() {
return this.moved;
}
protected boolean updateOrientation(TimeStep timeStep) {
final float fullCircle = FastMath.fullCircle;
float deltaOrientation = (this.desiredOrientation-this.orientation);
float deltaOrientationAbs = Math.abs(deltaOrientation);
if(deltaOrientationAbs > 0.001f) {
if(deltaOrientationAbs > (fullCircle/2) ) {
deltaOrientation *= -1;
}
if(deltaOrientation != 0) {
float direction = deltaOrientation / deltaOrientationAbs;
this.orientation += (direction * Math.min(movementSpeed, deltaOrientationAbs));
if(this.orientation < 0) {
this.orientation = fullCircle + this.orientation;
}
this.orientation %= fullCircle;
}
this.facing.set(1, 0); // make right vector
Vector2f.Vector2fRotate(this.facing, this.orientation, this.facing);
return true;
}
return false;
}
@Override
public void update(TimeStep timeStep) {
this.moved = updateOrientation(timeStep);
}
}
| 3,218 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SoundEventPool.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/SoundEventPool.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.events.SoundEmittedEvent;
import seventh.math.Vector2f;
import seventh.shared.SoundType;
/**
* Pools the available sounds
*
* @author Tony
*
*/
public class SoundEventPool {
private SoundEmittedEvent[] events;
private int usedIndex = 0;
/**
*
*/
public SoundEventPool(int maxSounds) {
this.events = new SoundEmittedEvent[maxSounds];
for(int i = 0; i < this.events.length; i++) {
this.events[i] = new SoundEmittedEvent(events, i, SoundType.MUTE, new Vector2f());
this.events[i].setBufferIndex(i);
}
clear();
}
public void emitSoundFor(int id, SoundType sound, Vector2f pos, int forEntityId) {
emitSound(id, sound, pos, id, forEntityId);
}
/**
* Emits a sound
*
* @param id
* @param sound
* @param entityId
*/
public void emitSound(int id, SoundType sound, int entityId) {
emitSound(id, sound, null, entityId, -1);
}
/**
* Emits the sound
*
* @param id
* @param sound
* @param pos
*/
public void emitSound(int id, SoundType sound, Vector2f pos) {
emitSound(id, sound, pos, id, -1);
}
/**
* Emits the sound
*
* @param id
* @param sound
* @param pos
* @param entityId
*/
public void emitSound(int id, SoundType sound, Vector2f pos, int entityId, int forEntityId) {
if(usedIndex+1 < events.length) {
SoundEmittedEvent event = events[++usedIndex];
event.setId(id);
event.setSoundType(sound);
event.setPos(pos);
event.setEntityId(entityId);
event.setForEntityId(forEntityId);
}
}
/**
* Emits the sound
*
* @param event
*/
public void emitSound(SoundEmittedEvent event) {
emitSound(event.getId(), event.getSoundType(), event.getPos(), event.getEntityId(), event.getForEntityId());
}
/**
* @return the number of sounds in the pool
*/
public int numberOfSounds() {
return Math.max(0, this.usedIndex+1);
}
/**
* Clears out the used sounds
*/
public void clear() {
this.usedIndex = -1;
}
/**
* @return if this pool as available sounds
*/
public boolean hasSounds() {
return this.usedIndex >= 0;
}
/**
* The {@link SoundEmittedEvent} at the supplied index
* @param index
* @return the event
*/
public SoundEmittedEvent getSound(int index) {
return events[index];
}
/**
* Appends the supplied pools to this contents
* @param pool
*/
public void set(SoundEventPool pool) {
for(int i = 0; i < pool.numberOfSounds(); i++) {
emitSound(pool.events[i]);
}
}
}
| 2,963 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GameMap.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/GameMap.java | /*
* see license.txt
*/
package seventh.game;
import seventh.game.net.NetMap;
import seventh.map.Map;
/**
* The current game map information
*
* @author Tony
*
*/
public class GameMap {
private NetMap netMap;
private Map map;
/**
* @param path
* @param name
* @param map
*/
public GameMap(String path, String name, Map map) {
this.map = map;
this.netMap = new NetMap();
this.netMap.id = 0;
this.netMap.path = path;
this.netMap.name = name;
}
/**
* @return the file system name of the map
*/
public String getMapFileName() {
return this.netMap.path;
}
/**
* @return the map
*/
public Map getMap() {
return map;
}
/**
* @return the netMap
*/
public NetMap getNetMap() {
return netMap;
}
}
| 894 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Player.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Player.java | /*
* see license.txt
*/
package seventh.game;
import java.util.Date;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.PlayerEntity.Keys;
import seventh.game.net.NetPlayerPartialStat;
import seventh.game.net.NetPlayerStat;
import seventh.math.Vector2f;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
/**
* Represents a player in the game
*
* @author Tony
*
*/
public class Player implements PlayerInfo, Debugable {
/**
* Delay to next spawn
*/
public static final long SPAWN_DELAY = 3000;
public static final long LOOK_AT_DEATH_DELAY = 2000;
private int id;
private String name;
private int kills;
private int deaths;
private int assists;
private int ping;
private int hitPercentage;
private long joinTime;
private PlayerEntity entity;
private Player spectating;
private Team team;
private byte teamId;
private boolean isBot;
private boolean isDummy;
private boolean isCommander;
private long spawnTime;
private long lookAtDeathTime;
private boolean isLooking;
private NetPlayerStat stats;
private NetPlayerPartialStat partialStats;
private Vector2f killedAt;
private PlayerClass playerClass;
private Type weaponClass;
// For builders, their active tile
private int activeTile;
private int previousKeys;
/**
* @param id
*/
public Player(int id) {
this(id, false, false, "");
}
/**
* @param id
* @param isBot
* @param isDummy
* @param name
*/
public Player(int id, boolean isBot, boolean isDummy, String name) {
this.id = id;
this.isBot = isBot;
this.isDummy = isDummy;
this.name = name;
this.joinTime = System.currentTimeMillis();
this.stats = new NetPlayerStat();
this.stats.playerId = id;
this.partialStats = new NetPlayerPartialStat();
this.partialStats.playerId = id;
this.weaponClass = Type.UNKNOWN;
this.killedAt = new Vector2f();
this.activeTile = 0;
setPlayerClass(PlayerClass.Default);
setTeam(Team.SPECTATOR);
}
/**
* Resets the players statistics
*/
public void resetStats() {
this.deaths = 0;
this.kills = 0;
this.assists = 0;
this.hitPercentage = 0;
this.joinTime = System.currentTimeMillis();
this.team = Team.SPECTATOR;
// DO NOT RESET teamId, this is used for map_restarts to keep
// people on the same team
// this.teamId = this.team.getId();
this.entity = null;
this.killedAt.zeroOut();
this.isLooking = false;
this.lookAtDeathTime = 0;
}
/**
* Updates the counter so that we are ready to spawn this player
* @param timeStep
*/
public void updateSpawnTime(TimeStep timeStep) {
if(spawnTime > 0) {
spawnTime -= timeStep.getDeltaTime();
}
}
/**
* Updates the counter for looking at own death
* @param timeStep
*/
public void updateLookAtDeathTime(TimeStep timeStep) {
if(lookAtDeathTime > 0) {
lookAtDeathTime -= timeStep.getDeltaTime();
}
}
/**
* Marks the spot where this player was killed
*/
public void setKilledAt() {
if(this.entity != null) {
this.killedAt.set(this.entity.getPos());
}
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getKilledAt()
*/
@Override
public Vector2f getKilledAt() {
return killedAt;
}
/**
* @param weaponClass the weaponClass to set
*/
public void setWeaponClass(Type weaponClass) {
this.weaponClass = weaponClass;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getWeaponClass()
*/
@Override
public Type getWeaponClass() {
return weaponClass;
}
/**
* @param playerClass the playerClass to set
*/
public void setPlayerClass(PlayerClass playerClass) {
this.playerClass = playerClass;
}
/**
* @return the playerClass
*/
@Override
public PlayerClass getPlayerClass() {
return playerClass;
}
/**
* The player has died, delay their time to spawn
*/
public void applySpawnDelay() {
applySpawnDelay(SPAWN_DELAY);
}
/**
* The player has died, delay their time to spawn
*
* @param time
*/
public void applySpawnDelay(long time) {
this.spawnTime = time;
}
/**
* Let the player soak in that they have died.
*/
public void applyLookAtDeathDelay() {
if(!this.isLooking) {
this.lookAtDeathTime = LOOK_AT_DEATH_DELAY;
this.isLooking = true;
}
}
/**
* @return true if the spawn delay has been applied
*/
public boolean spawnDelayApplied() {
return spawnTime > 0;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#readyToSpawn()
*/
@Override
public boolean readyToSpawn() {
return (isDead() && spawnTime <= 0);
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#readyToLookAwayFromDeath()
*/
@Override
public boolean readyToLookAwayFromDeath() {
return this.isDead() && this.isLooking && this.lookAtDeathTime <= 0;
}
/**
* @param deaths the deaths to set
*/
public void setDeaths(int deaths) {
this.deaths = deaths;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getDeaths()
*/
@Override
public int getDeaths() {
return deaths;
}
public int incrementDeaths() {
return ++this.deaths;
}
public int incrementKills() {
return ++this.kills;
}
public int loseKill() {
return --this.kills;
}
public int incrementAssists() {
return ++this.assists;
}
/**
* @param hitPercentage the hitPercentage to set
*/
public void setHitPercentage(float hitPercentage) {
this.hitPercentage = (int) (hitPercentage*100f);
}
/**
* @return the hitPercentage
*/
public int getHitPercentage() {
return hitPercentage;
}
/**
* @param assists the assists to set
*/
public void setAssists(int assists) {
this.assists = assists;
}
/**
* @return the assists
*/
public int getAssists() {
return assists;
}
/**
* @param kills the kills to set
*/
public void setKills(int kills) {
this.kills = kills;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getKills()
*/
@Override
public int getKills() {
return kills;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getName()
*/
@Override
public String getName() {
return name;
}
/**
* @param ping the ping to set
*/
public void setPing(int ping) {
this.ping = ping;
}
/**
* @return the ping
*/
@Override
public int getPing() {
return ping;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isBot()
*/
@Override
public boolean isBot() {
return isBot;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isDummyBot()
*/
@Override
public boolean isDummyBot() {
return this.isDummy;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getJoinTime()
*/
@Override
public long getJoinTime() {
return joinTime;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getId()
*/
@Override
public int getId() {
return id;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isTeammateWith(int)
*/
@Override
public boolean isTeammateWith(int playerId) {
return getTeam().onTeam(playerId);
}
/**
* Kills themselves
*/
public void commitSuicide() {
if(hasEntity()) {
getEntity().kill(getEntity());
}
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#hasEntity()
*/
@Override
public boolean hasEntity() {
return this.entity != null;
}
@Override
public boolean canSpawn() {
return isDead() && !isPureSpectator() && !isCommander();
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isDead()
*/
@Override
public boolean isDead() {
return this.entity == null || !this.entity.isAlive();
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isAlive()
*/
@Override
public boolean isAlive() {
return !isDead();
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isSpectating()
*/
@Override
public boolean isSpectating() {
return getSpectatingEntity() != null || team==Team.SPECTATOR;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#isPureSpectator()
*/
@Override
public boolean isPureSpectator() {
return team==Team.SPECTATOR;
}
@Override
public boolean isCommander() {
return this.isCommander;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getSpectatingEntity()
*/
@Override
public PlayerEntity getSpectatingEntity() {
return spectating != null && spectating.isAlive() ? spectating.getEntity() : null;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getSpectatingPlayerId()
*/
@Override
public int getSpectatingPlayerId() {
PlayerEntity ent = getSpectatingEntity();
if(ent==null) {
return Entity.INVALID_ENTITY_ID;
}
return ent.getId();
}
/**
* Handle input from the player
*
* @param game
* @param keys
*/
public void handleInput(Game game, int keys) {
if (isSpectating()) {
if(Keys.LEFT.isDown(this.previousKeys) && !Keys.LEFT.isDown(keys)) {
Player spectateMe = game.getGameType().getPrevPlayerToSpectate(game.getPlayers(), this);
setSpectating(spectateMe);
}
else if(Keys.RIGHT.isDown(this.previousKeys) && !Keys.RIGHT.isDown(keys)) {
Player spectateMe = game.getGameType().getNextPlayerToSpectate(game.getPlayers(), this);
setSpectating(spectateMe);
}
this.previousKeys = keys;
}
}
/**
* Make this player a commander
*/
public void setCommander(boolean commander) {
this.isCommander = commander;
}
/**
* @param spectatingEntity the spectatingEntity to set
*/
public void setSpectating(Player spectating) {
this.spectating = spectating;
}
/**
* Stops spectating a player
*/
public void stopSpectating() {
this.spectating = null;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getSpectating()
*/
@Override
public Player getSpectating() {
return this.spectating;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getEntity()
*/
@Override
public PlayerEntity getEntity() {
return entity;
}
/**
* @param entity the entity to set
*/
public void setEntity(PlayerEntity entity) {
this.entity = entity;
if(hasEntity()) {
this.entity.setTeam(team);
this.spawnTime = SPAWN_DELAY;
this.spectating = null;
this.isLooking = false;
this.lookAtDeathTime = 0;
this.entity.setPlayerClass(getPlayerClass(), getWeaponClass());
}
}
/**
* @return the activeTile
*/
@Override
public int getActiveTile() {
return activeTile;
}
/**
* @param activeTile the activeTile to set
*/
public void setActiveTile(int activeTile) {
this.activeTile = activeTile;
}
/**
* @param team the team to set
*/
public void setTeam(Team team) {
this.team = team;
if(this.team==null) {
this.team = Team.SPECTATOR;
}
else if(hasEntity()) {
this.entity.setTeam(team);
}
this.teamId = this.team.getId();
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getTeam()
*/
@Override
public Team getTeam() {
return team;
}
/* (non-Javadoc)
* @see seventh.game.PlayerInfo#getTeamId()
*/
@Override
public byte getTeamId() {
return teamId;
}
/**
* @return the network player statistics
*/
public NetPlayerStat getNetPlayerStat() {
this.stats.isBot = this.isBot;
this.stats.joinTime = (int)this.joinTime;
this.stats.kills = (short)this.kills;
this.stats.assists = (short)this.assists;
this.stats.deaths = (short)this.deaths;
this.stats.hitPercentage = (byte)this.hitPercentage;
this.stats.ping = (short)this.ping;
this.stats.name = this.name;
this.stats.teamId = (team!=null) ? team.getId() : Team.SPECTATOR_TEAM_ID;
return this.stats;
}
/**
* @return the partial statistics of this player
*/
public NetPlayerPartialStat getNetPlayerPartialStat() {
this.partialStats.kills = (short)this.kills;
this.partialStats.deaths = (short)this.deaths;
this.partialStats.assists = (short)this.assists;
return this.partialStats;
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("id", getId())
.add("name", getName())
.add("deaths", getDeaths())
.add("kills", getKills())
.add("assists", getAssists())
.add("hitPercentage", getHitPercentage())
.add("ping", getPing())
.add("time_joined", new Date(getJoinTime()).toString())
.add("weapon_class", getWeaponClass().name())
.add("isAlive", isAlive())
.add("entity_id", isAlive() ? getEntity().getId() : null);
;
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 15,191 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Game.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Game.java | /*
* see license.txt
*/
package seventh.game;
import static seventh.shared.SeventhConstants.MAX_ENTITIES;
import static seventh.shared.SeventhConstants.MAX_PERSISTANT_ENTITIES;
import static seventh.shared.SeventhConstants.MAX_PLAYERS;
import static seventh.shared.SeventhConstants.MAX_TIMERS;
import static seventh.shared.SeventhConstants.SPAWN_INVINCEABLILITY_TIME;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
import seventh.ai.AISystem;
import seventh.ai.basic.AILeolaLibrary;
import seventh.ai.basic.DefaultAISystem;
import seventh.game.entities.Base;
import seventh.game.entities.Bomb;
import seventh.game.entities.BombTarget;
import seventh.game.entities.Door;
import seventh.game.entities.DroppedItem;
import seventh.game.entities.Entity;
import seventh.game.entities.Entity.KilledListener;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.Flag;
import seventh.game.entities.HealthPack;
import seventh.game.entities.LightBulb;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.vehicles.PanzerTank;
import seventh.game.entities.vehicles.ShermanTank;
import seventh.game.entities.vehicles.Tank;
import seventh.game.entities.vehicles.Vehicle;
import seventh.game.events.EventRegistration;
import seventh.game.events.GameEvent;
import seventh.game.events.GameEvent.EventType;
import seventh.game.events.PlayerJoinedEvent;
import seventh.game.events.PlayerKilledEvent;
import seventh.game.events.PlayerKilledListener;
import seventh.game.events.PlayerLeftEvent;
import seventh.game.events.PlayerSpawnedEvent;
import seventh.game.events.PlayerSpawnedListener;
import seventh.game.events.RoundEndedEvent;
import seventh.game.events.RoundEndedListener;
import seventh.game.events.RoundStartedEvent;
import seventh.game.events.RoundStartedListener;
import seventh.game.events.SoundEmittedEvent;
import seventh.game.events.SoundEmitterListener;
import seventh.game.events.TileAddedEvent;
import seventh.game.events.TileRemovedEvent;
import seventh.game.game_types.GameType;
import seventh.game.net.NetEntity;
import seventh.game.net.NetGamePartialStats;
import seventh.game.net.NetGameState;
import seventh.game.net.NetGameStats;
import seventh.game.net.NetGameUpdate;
import seventh.game.net.NetMapAddition;
import seventh.game.net.NetMapAdditions;
import seventh.game.net.NetMapDestructables;
import seventh.game.net.NetSound;
import seventh.game.net.NetSoundByEntity;
import seventh.game.weapons.Explosion;
import seventh.game.weapons.Fire;
import seventh.game.weapons.FlameThrower;
import seventh.game.weapons.Kar98;
import seventh.game.weapons.M1Garand;
import seventh.game.weapons.MP40;
import seventh.game.weapons.MP44;
import seventh.game.weapons.Risker;
import seventh.game.weapons.RocketLauncher;
import seventh.game.weapons.Shotgun;
import seventh.game.weapons.Smoke;
import seventh.game.weapons.Springfield;
import seventh.game.weapons.Thompson;
import seventh.game.weapons.Weapon;
import seventh.graph.GraphNode;
import seventh.map.GraphNodeFactory;
import seventh.map.Map;
import seventh.map.MapGraph;
import seventh.map.MapObject;
import seventh.map.Tile;
import seventh.map.TileData;
import seventh.math.OBB;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
import seventh.math.Vector4f;
import seventh.network.messages.AICommandMessage;
import seventh.network.messages.PlayerInputMessage;
import seventh.server.GameServerLeolaLibrary;
import seventh.server.SeventhScriptingCommonLibrary;
import seventh.shared.Cons;
import seventh.shared.Debugable;
import seventh.shared.EventDispatcher;
import seventh.shared.EventListener;
import seventh.shared.EventMethod;
import seventh.shared.Scripting;
import seventh.shared.SeventhConfig;
import seventh.shared.SeventhConstants;
import seventh.shared.SoundType;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
import seventh.shared.Updatable;
/**
* Represents the current Game Session
*
* @author Tony
*
*/
public class Game implements GameInfo, Debugable, Updatable {
/**
* Null Node Data.
*
* @author Tony
*
*/
private static class NodeData implements GraphNodeFactory<Void> {
@Override
public Void createEdgeData(Map map, GraphNode<Tile, Void> left,
GraphNode<Tile, Void> right) {
return null;
}
}
public static final Type[] alliedWeapons = {
Type.THOMPSON,
Type.SHOTGUN,
Type.M1_GARAND,
Type.SPRINGFIELD,
Type.RISKER,
Type.ROCKET_LAUNCHER,
Type.FLAME_THROWER,
};
public static final Type[] axisWeapons = {
Type.MP40,
Type.SHOTGUN,
Type.MP44,
Type.KAR98,
Type.RISKER,
Type.ROCKET_LAUNCHER,
Type.FLAME_THROWER,
};
private Entity[] entities;
private PlayerEntity[] playerEntities;
private int[] deadFrames;
private Map map;
private MapGraph<Void> graph;
private GameMap gameMap;
private GameType gameType;
private List<MapObject> collidableMapObjects;
private List<BombTarget> bombTargets;
private List<Vehicle> vehicles;
private List<Flag> flags;
private List<Door> doors;
private List<Smoke> smokeEntities;
private List<DroppedItem> droppedItems;
private List<Base> bases;
private Players players;
private EventDispatcher dispatcher;
private long time;
private Random random;
private SoundEventPool soundEvents
, lastFramesSoundEvents;
private boolean enableFOW;
// data members that are strictly here for performance
// reasons
public List<Tile> tilesInLineOfSight = new ArrayList<Tile>();
List<SoundEmittedEvent> aSoundsHeard = new ArrayList<SoundEmittedEvent>();
List<Entity> aEntitiesInView = new ArrayList<Entity>();
private Timers gameTimers;
private Triggers gameTriggers;
private final float DISTANCE_CHECK;
private final int TILE_WIDTH, TILE_HEIGHT;
private SeventhConfig config;
private int lastValidId;
private AISystem aiSystem;
private PlayerAwardSystem awardSystem;
private PlayerStatSystem statSystem;
private EventRegistration eventRegistration;
private LeoObject scriptObj;
/**
* @param config
* @param players
* @param gameType
* @param gameMap
* @param dispatcher
*/
public Game(SeventhConfig config,
final Players players,
final GameType gameType,
GameMap gameMap,
EventDispatcher dispatcher) {
this.config = config;
this.gameType = gameType;
this.dispatcher = dispatcher;
this.gameMap = gameMap;
this.map = gameMap.getMap();
this.collidableMapObjects = new ArrayList<MapObject>();
this.graph = map.createMapGraph(new NodeData());
this.gameTimers = new Timers(MAX_TIMERS);
this.gameTriggers = new Triggers(this);
this.entities = new Entity[MAX_ENTITIES];
this.playerEntities = new PlayerEntity[MAX_PLAYERS];
this.scriptObj = LeoObject.valueOf(this);
this.deadFrames = new int[MAX_ENTITIES];
markDeadFrames();
this.bombTargets = new ArrayList<BombTarget>();
this.vehicles = new ArrayList<Vehicle>();
this.flags = new ArrayList<Flag>();
this.doors = new ArrayList<Door>();
this.smokeEntities = new ArrayList<Smoke>();
this.droppedItems = new ArrayList<DroppedItem>();
this.bases = new ArrayList<Base>();
this.soundEvents = new SoundEventPool(SeventhConstants.MAX_SOUNDS);
this.lastFramesSoundEvents = new SoundEventPool(SeventhConstants.MAX_SOUNDS);
this.aiSystem = new DefaultAISystem();
this.random = new Random();
this.players = players;
this.enableFOW = true;
this.time = gameType.getMatchTime();
this.TILE_WIDTH = map.getTileWidth();
this.TILE_HEIGHT = map.getTileHeight();
this.DISTANCE_CHECK = TILE_HEIGHT * TILE_WIDTH * 2;
this.eventRegistration = new EventRegistration(this.dispatcher);
this.dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() {
@Override
@EventMethod
public void onPlayerKilled(PlayerKilledEvent event) {
if (gameType.isInProgress()) {
Player killed = event.getPlayer();
aiSystem.playerKilled(killed);
statSystem.onPlayerKilled(event);
}
}
});
this.dispatcher.addEventListener(PlayerSpawnedEvent.class, new PlayerSpawnedListener() {
@Override
@EventMethod
public void onPlayerSpawned(PlayerSpawnedEvent event) {
// aiSystem.playerSpawned(event.getPlayer());
}
});
this.dispatcher.addEventListener(SoundEmittedEvent.class, new SoundEmitterListener() {
@Override
@EventMethod
public void onSoundEmitted(SoundEmittedEvent event) {
soundEvents.emitSound(event);
}
});
this.dispatcher.addEventListener(RoundStartedEvent.class, new RoundStartedListener() {
@Override
public void onRoundStarted(RoundStartedEvent event) {
markDeadFrames();
// remove any nodes we may have created by destructable
// terrain
for(Tile tile : map.getRemovedTiles()) {
graph.removeNode(tile.getXIndex(), tile.getYIndex());
}
map.restoreDestroyedTiles();
map.removeAddedTiles();
loadMapScripts();
aiSystem.startOfRound(Game.this);
statSystem.onRoundStarted();
}
});
this.dispatcher.addEventListener(RoundEndedEvent.class, new RoundEndedListener() {
@Override
public void onRoundEnded(RoundEndedEvent event) {
gameTimers.removeTimers();
gameTriggers.removeTriggers();
aiSystem.endOfRound(Game.this);
}
});
this.aiSystem.init(this);
this.gameType.registerListeners(this, dispatcher);
this.awardSystem = new PlayerAwardSystem(this);
this.statSystem = new PlayerStatSystem(this);
}
/**
* This as a script object
*
* @return the script object of the game
*/
public LeoObject asScriptObject() {
return this.scriptObj;
}
/**
* @return the next available slot for an entity
*/
public int getNextPersistantId() {
for(int i = MAX_PLAYERS; i < MAX_PERSISTANT_ENTITIES; i++) {
if(entities[i] == null) {
return i;
}
}
return -1;
}
/**
* Calculates the next valid ID. If there are no entity slots available,
* this will create room by destroying a volatile object.
*
* @return a valid id.
*/
public int getNextEntityId() {
// NOTE: Maybe we want to keep track of the last
// assigned ID, so that we can more quickly find a new valid
// one -- for now we also start from the beginning.
lastValidId = 0;
for(int i = MAX_PLAYERS + MAX_PERSISTANT_ENTITIES + lastValidId; i < MAX_ENTITIES; i++) {
// We the delay the ability to reuse a volatile entity id
// because clients need time to timeout the current entity
// NOTE: Only persistent and player entities are told when
// they are dead
//
// The delay is 10 frames (at normal 20 fps ~500 ms delay)
if(entities[i] == null && deadFrames[i] > 10) {
lastValidId++;
return i;
}
}
/* if we ran out of id's, lets find a
* volatile object so we can respawn this
* latest object.
*/
for(int i = MAX_PLAYERS; i < MAX_ENTITIES; i++) {
Entity ent = entities[i];
if(ent!=null) {
Type type = ent.getType();
if(type == Type.DROPPED_ITEM || type == Type.BULLET) {
ent.softKill();
return i;
}
}
}
// Should we throw an error
return MAX_ENTITIES-1;
}
/**
* Emits a sound specifically for a player
*
* @param id
* @param sound
* @param pos
* @param forEntityId
*/
public void emitSoundFor(int id, SoundType sound, Vector2f pos, int forEntityId) {
soundEvents.emitSoundFor(id, sound, pos, forEntityId);
}
/**
* Emits a sound for the client to hear
*
* @param id
* @param sound
*/
public void emitSound(int id, SoundType sound) {
soundEvents.emitSound(id, sound, id);
}
/**
* Emits a sound for the client to hear
*
* @param sound
* @param pos
*/
public void emitSound(int id, SoundType sound, Vector2f pos) {
soundEvents.emitSound(id, sound, pos);
}
/**
* Starts the game
*/
public void startGame() {
this.gameType.start(this);
}
/**
* Attempts to add a bot to the world
* @param name
* @return the ID slot which the bot occupies.
*/
public int addBot(String name) {
for(int i = 0; i < this.players.maxNumberOfPlayers(); i++) {
if(!this.players.hasPlayer(i)) {
return addBot(i, name);
}
}
return -1;
}
/**
* Adds a bot
*
* @param id the bot id
* @param name
* @return the id of the added bot
*/
public int addBot(int id, String name) {
if(id >= 0) {
playerJoined(new Player( id, true, false, name));
}
return id;
}
/**
* Adds a Dummy bot. This is used for testing purposes.
* @param id
* @return the id of the added bot
*/
public int addDummyBot(int id) {
if(id >= 0) {
playerJoined(new Player( id, true, true, "Dummy"));
}
return id;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getAISystem()
*/
@Override
public AISystem getAISystem() {
return aiSystem;
}
/**
* @return the statSystem
*/
public PlayerStatSystem getStatSystem() {
return statSystem;
}
/**
* @return the awardSystem
*/
public PlayerAwardSystem getAwardSystem() {
return awardSystem;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getConfig()
*/
@Override
public SeventhConfig getConfig() {
return config;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getRandom()
*/
@Override
public Random getRandom() {
return random;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getDispatcher()
*/
@Override
public EventDispatcher getDispatcher() {
return dispatcher;
}
/**
* @return the gameTimers
*/
@Override
public Timers getGameTimers() {
return gameTimers;
}
/**
* Sends an ambient light adjustment to the client
*
* @param r
* @param g
* @param b
* @param intensity
*/
public void adjustLight(float r, float g, float b, float intensity) {
this.dispatcher.queueEvent(new GameEvent(this, EventType.LightAdjust, null, null, 0f, null, -1, -1, new Vector4f(r, g, b, intensity)));
}
/**
* Sends a message to the players HUD
*
* @param message
*/
public void text(String message) {
this.dispatcher.queueEvent(new GameEvent(this, EventType.Message, null, null, 0f, message, -1, -1, null));
}
/**
* Sends a message about broken glass
*
* @param pos
* @param dir
*/
public void breakGlass(Vector2f pos, Vector2f dir) {
double rotation = Vector2f.Vector2fAngle(Vector2f.RIGHT_VECTOR, dir);
this.dispatcher.queueEvent(new GameEvent(this, EventType.BrokenGlass, pos, null, (float)Math.toDegrees(rotation), null, -1, -1, null));
}
/**
* Adds an explosion trigger that is activated when a bullet/explosion/rocket
* strikes the tile at the supplied x/y location
*
* @param x
* @param y
* @param width
* @param height
*/
public void addExplosionTrigger(int x, int y, Integer width, Integer height) {
if(width==null||height==null) {
Tile tile = map.getWorldTile(0, x, y);
// snap to the tile
if(tile!=null) {
x = tile.getX();
y = tile.getY();
}
width = 32;
height = 32;
}
final Rectangle bounds = new Rectangle(x, y, width, height);
addTrigger(new Trigger() {
Entity trigger = null;
@Override
public boolean checkCondition(Game game) {
for(int i = 0; i < entities.length; i++) {
Entity ent = entities[i];
if(ent!=null) {
Type entType = ent.getType();
if(entType.equals(Type.BULLET) ||
entType.equals(Type.EXPLOSION) ||
entType.equals(Type.ROCKET)) {
if(bounds.intersects(ent.getBounds())) {
trigger = ent;
return true;
}
}
}
}
return false;
}
@Override
public void execute(Game game) {
if(trigger != null) {
game.newBigExplosion(new Vector2f(bounds.x, bounds.y), trigger, 15, 25, 1);
}
}
});
}
/**
* Binds an {@link EventListener}
*
* @param eventName - the name of the event to listen to
* @param function - the callback
*/
public void addEventListener(String eventName, final LeoObject function) {
this.eventRegistration.addEventListener(eventName, function);
}
/**
* Adds a trigger to the game world
*
* @param trigger
*/
public void addTrigger(Trigger trigger) {
this.gameTriggers.addTrigger(trigger);
}
/**
* Adds a trigger to the game world.
*
* @param function
*/
public void addTrigger(final LeoObject function) {
final LeoObject gameClass = asScriptObject();
final LeoObject cond = function.getObject("checkCondition");
final LeoObject exe = function.getObject("execute");
addTrigger(new Trigger() {
@Override
public boolean checkCondition(Game game) {
return LeoObject.isTrue(cond.call(gameClass));
}
@Override
public void execute(Game game) {
exe.call(gameClass);
}
});
}
/**
* Adds a {@link Timer}
*
* @param timer
* @return true if the timer was added;false otherwise
*/
public boolean addGameTimer(Timer timer) {
return this.gameTimers.addTimer(timer);
}
/**
* Adds the {@link LeoObject} callback as the timer function
* @param loop
* @param endTime
* @param function
* @return true if the timer was added;false otherwise
*/
public boolean addGameTimer(boolean loop, long endTime, final LeoObject function) {
return addGameTimer(new Timer(loop, endTime) {
@Override
public void onFinish(Timer timer) {
LeoObject result = function.call();
if(result.isError()) {
Cons.println("*** ERROR: Script error in GameTimer: " + result);
}
}
});
}
/**
* Adds the {@link LeoObject} callback as a the timer function, which will also randomize the start/end time.
*
* @param loop
* @param minStartTime
* @param maxEndTime
* @param function
* @return true if the timer was added;false otherwise
*/
public boolean addRandomGameTimer(boolean loop, final long minStartTime, final long maxEndTime, final LeoObject function) {
return addGameTimer(new Timer(loop, minStartTime) {
@Override
public void onFinish(Timer timer) {
LeoObject result = function.call();
if(result.isError()) {
Cons.println("*** ERROR: Script error in GameTimer: " + result);
}
long delta = maxEndTime - minStartTime;
int millis = Math.max(1, (int)delta / 100);
timer.setEndTime(minStartTime + random.nextInt(millis) * 100);
}
});
}
/**
* Adds a {@link Tile} to the game world
*
* @param type
* @param pos
* @return true if it was added
*/
public boolean addTile(int type, Vector2f pos) {
int tileX = (int)pos.x;
int tileY = (int)pos.y;
// ensure there is not already a collision tile here
// and also ensure no players are touching here
if(!map.hasWorldCollidableTile(tileX, tileY)) {
Tile groundTile = map.getWorldTile(0, tileX, tileY);
Rectangle bounds = groundTile.getBounds();
for(int i = 0; i < this.playerEntities.length; i++) {
PlayerEntity ent = this.playerEntities[i];
if(ent!=null) {
if(ent.getBounds().intersects(bounds)) {
return false;
}
}
}
TileData data = new TileData();
data.tileX = map.worldToTileX((int) pos.x);
data.tileY = map.worldToTileY((int) pos.y);
data.type = type;
Tile tile = map.getMapObjectFactory().createMapTile(map.geTilesetAtlas(), data);
if(tile != null) {
// add the tile to the world map
map.addTile(tile);
// make this tile unwalkable, so that pathfinding works correctly
graph.removeNode(data.tileX, data.tileY);
dispatcher.queueEvent(new TileAddedEvent(this, data.type, data.tileX, data.tileY));
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getLastFramesSoundEvents()
*/
@Override
public SoundEventPool getLastFramesSoundEvents() {
return lastFramesSoundEvents;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getSoundEvents()
*/
@Override
public SoundEventPool getSoundEvents() {
return soundEvents;
}
/**
* Kick a player
* @param id
*/
public void kickPlayer(int id) {
playerLeft(id);
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getPlayerById(int)
*/
@Override
public PlayerInfo getPlayerById(int playerId) {
return this.players.getPlayer(playerId);
}
/**
* @return the mutable list of {@link Players}
*/
public Players getPlayers() {
return players;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getBombTargets()
*/
@Override
public List<BombTarget> getBombTargets() {
return bombTargets;
}
/**
* @return the vehicles
*/
@Override
public List<Vehicle> getVehicles() {
return vehicles;
}
/**
* @return the doors
*/
@Override
public List<Door> getDoors() {
return doors;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getFlags()
*/
@Override
public List<Flag> getFlags() {
return this.flags;
}
/**
* @return the smokeEntities
*/
public List<Smoke> getSmokeEntities() {
return smokeEntities;
}
/**
* @return the droppedItems
*/
public List<DroppedItem> getDroppedItems() {
return droppedItems;
}
/**
* @return the bases
*/
public List<Base> getBases() {
return bases;
}
public List<MapObject> getMapObjects() {
return map.getMapObjects();
}
/**
* @return the collidableMapObjects
*/
public List<MapObject> getCollidableMapObjects() {
return collidableMapObjects;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getPlayerInfos()
*/
@Override
public PlayerInfos getPlayerInfos() {
return players;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getGameType()
*/
@Override
public GameType getGameType() {
return gameType;
}
/**
* Updates the game
* @param timeStep
*/
@Override
public void update(TimeStep timeStep) {
for(int i = 0; i < entities.length; i++) {
Entity ent = entities[i];
if(ent!=null) {
if(ent.isAlive()) {
deadFrames[i] = 0;
ent.update(timeStep);
}
else {
deadFrames[i]++;
if(deadFrames[i] > 1) {
entities[i] = null;
}
}
}
else {
deadFrames[i]++;
}
}
this.aiSystem.update(timeStep);
this.gameTimers.update(timeStep);
this.gameTriggers.update(timeStep);
this.gameType.update(this, timeStep);
this.time = this.gameType.getRemainingTime();
}
/**
* Invoked after an update, a hack to work
* around processing event queue
*/
public void postUpdate() {
lastFramesSoundEvents.clear();
lastFramesSoundEvents.set(soundEvents);
soundEvents.clear();
lastValidId = 0;
}
/**
* Loads any map scripts and/or special entities associated with the game map. This should
* be invoked every time a new Round begins
*/
private void loadMapScripts() {
// remove any previous scripted listeners
this.eventRegistration.unregisterListeners();
File propertiesFile = new File(gameMap.getMapFileName() + ".props.leola");
if(propertiesFile.exists()) {
try {
Leola runtime = Scripting.newSandboxedRuntime();
runtime.loadStatics(SeventhScriptingCommonLibrary.class);
GameServerLeolaLibrary gLib = new GameServerLeolaLibrary(this);
runtime.loadLibrary(gLib, "game2");
AILeolaLibrary aiLib = new AILeolaLibrary(this.aiSystem);
runtime.loadLibrary(aiLib, "ai");
runtime.put("game", this);
runtime.eval(propertiesFile);
}
catch(Exception e) {
Cons.println("*** ERROR -> Loading map properties file: " + propertiesFile.getName() + " -> ");
Cons.println(e);
}
}
this.collidableMapObjects.clear();
// Load the map objects
List<MapObject> objects = map.getMapObjects();
for(int i = 0; i < objects.size(); i++) {
MapObject mapObject = objects.get(i);
mapObject.onLoad(this);
if(mapObject.isCollidable()) {
this.collidableMapObjects.add(mapObject);
}
}
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getMap()
*/
@Override
public Map getMap() {
return map;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getEntities()
*/
@Override
public Entity[] getEntities() {
return entities;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getPlayerEntities()
*/
@Override
public PlayerEntity[] getPlayerEntities() {
return playerEntities;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#getGraph()
*/
@Override
public MapGraph<Void> getGraph() {
return graph;
}
/**
* Finds a free location on the map, one in which the supplied {@link PlayerEntity} will not collide with.
*
* @param player
* @return the {@link Vector2f} that is suitable for the {@link PlayerEntity}
*/
public Vector2f findFreeSpot(PlayerEntity player) {
Vector2f freeSpot = player.getPos();
int safety = 100000;
while((map.rectCollides(player.getBounds()) ||
map.hasWorldCollidableTile((int)player.getCenterPos().x, (int)player.getCenterPos().y) ||
doesTouchOthers(player, false) ||
doesTouchMapObject(player, false)) &&
safety>0) {
int w = (player.getBounds().width + 5);
int h = (player.getBounds().height + 5);
int x = random.nextInt(map.getMapWidth()-w);
int y = random.nextInt(map.getMapHeight()-h);
if(x <= w) {
x = w;
}
if(y <= h) {
y = h;
}
freeSpot.set(x, y);
player.moveTo(freeSpot);
safety--;
}
return freeSpot;
}
/**
* @param entity
* @return a random position anywhere in the game world
*/
public Vector2f findFreeRandomSpot(Entity entity) {
return findFreeRandomSpot(entity, 0, 0, map.getMapWidth()-20, map.getMapHeight()-20);
}
/**
* @param entity
* @param bounds
* @return a random position anywhere in the supplied bounds
*/
public Vector2f findFreeRandomSpot(Entity entity, Rectangle bounds) {
return findFreeRandomSpot(entity, bounds.x, bounds.y, bounds.width, bounds.height);
}
public Vector2f findFreeRandomSpot(Rectangle entity, Rectangle bounds) {
return findFreeRandomSpot(entity, bounds.x, bounds.y, bounds.width, bounds.height);
}
/**
*
* @param entity
* @param x
* @param y
* @param width
* @param height
* @return a random position anywhere in the supplied bounds
*/
public Vector2f findFreeRandomSpot(Entity entity, int x, int y, int width, int height) {
return findFreeRandomSpot(entity.getBounds(), x, y, width, height);
}
public Vector2f findFreeRandomSpot(Rectangle bounds, int x, int y, int width, int height) {
Vector2f pos = new Vector2f();
Rectangle temp = new Rectangle(bounds);
int loopChecker = 0;
do {
pos.x = x + random.nextInt(width);
pos.y = y + random.nextInt(height);
temp.setLocation(pos);
// this bounds doesn't have a free spot
if(loopChecker++ > 500_000) {
return null;
}
}
while(map.rectCollides(temp) ||
map.hasWorldCollidableTile(temp.x, temp.y) ||
doesTouchEntity(temp));
return pos;
}
/**
*
* @param entity
* @param x
* @param y
* @param width
* @param height
* @param notIn
* @return a random position anywhere in the supplied bounds and not in the supplied {@link Rectangle}
*/
public Vector2f findFreeRandomSpotNotIn(Entity entity, int x, int y, int width, int height, Rectangle notIn) {
Vector2f pos = new Vector2f(x+random.nextInt(width), y+random.nextInt(height));
Rectangle temp = new Rectangle(entity.getBounds());
temp.setLocation(pos);
int loopChecker = 0;
while (map.rectCollides(temp) ||
map.hasWorldCollidableTile(temp.x, temp.y) ||
doesTouchEntity(temp) ||
notIn.intersects(temp)) {
pos.x = x + random.nextInt(width);
pos.y = y + random.nextInt(height);
temp.setLocation(pos);
// this bounds doesn't have a free spot
if(loopChecker++ > 500_000) {
return null;
}
}
return pos;
}
public Vector2f findFreeRandomSpotNotIn(Entity entity, Rectangle bounds, OBB notIn) {
Vector2f pos = new Vector2f();
Rectangle temp = new Rectangle(entity.getBounds());
int numberOfAttempts = 0;
do {
pos.x = bounds.x + random.nextInt(bounds.width);
pos.y = bounds.y + random.nextInt(bounds.height);
temp.setLocation(pos);
if(numberOfAttempts++ > 100_000) {
return null;
}
}
while (map.rectCollides(temp) ||
map.hasWorldCollidableTile(temp.x, temp.y) ||
doesTouchEntity(temp) ||
notIn.expensiveIntersects(temp));
return pos;
}
/**
* A {@link Player} joined the game.
*
* @param player
*/
public void playerJoined(Player player) {
Cons.println("Player " + player.getName() + " has joined the game @ " + new Date());
this.players.addPlayer(player);
this.gameType.playerJoin(player);
this.aiSystem.playerJoined(player);
this.dispatcher.queueEvent(new PlayerJoinedEvent(this, player));
}
/**
* A {@link Player} left the game.
*
* @param player
*/
public void playerLeft(Player player) {
playerLeft(player.getId());
}
/**
* A {@link Player} left the game.
*
* @param playerId
*/
public void playerLeft(int playerId) {
Player player = this.players.removePlayer(playerId);
if(player!=null) {
Cons.println("Player " + player.getName() + " has left the game @ " + new Date());
this.aiSystem.playerLeft(player);
this.gameType.playerLeft(player);
player.commitSuicide();
this.dispatcher.queueEvent(new PlayerLeftEvent(this, player));
}
}
/**
* destroys the game, cleans up resources
*/
public void destroy() {
for(int i = 0; i < this.entities.length;i++) {
this.entities[i] = null;
this.deadFrames[i] = 0;
}
for(int i = 0; i < this.playerEntities.length;i++) {
this.playerEntities[i] = null;
}
this.bombTargets.clear();
this.vehicles.clear();
this.flags.clear();
this.doors.clear();
this.smokeEntities.clear();
this.droppedItems.clear();
this.players.resetStats();
this.aiSystem.destroy();
this.gameTimers.removeTimers();
this.dispatcher.removeAllEventListeners();
}
private void removePlayer(Entity entity) {
for(int i = 0; i < playerEntities.length;i++) {
if(playerEntities[i] == entity) {
playerEntities[i] = null;
break;
}
}
}
private void addPlayer(PlayerEntity player) {
int id = player.getId();
if(id >= 0 && id < MAX_PLAYERS) {
playerEntities[id] = player;
}
}
/**
* Spawns a {@link PlayerEntity} as the specified location. If the location is
* valid, it will attempt to find a valid random position
*
* @param id - the {@link Player#id}
* @param spawnPosition - the desired spawn location
* @return the {@link PlayerEntity}
*/
public PlayerEntity spawnPlayerEntity(final int id, Vector2f spawnPosition) {
final Player player = this.players.getPlayer(id);
if(player == null ) {
Cons.println("No player found with id: " + id);
return null;
}
// Spawn a bot (or dummy bot if need-be) or a remote controlled entity
final PlayerEntity playerEntity = new PlayerEntity(id, player.getPlayerClass(), spawnPosition, this);
// give them two seconds of invinceability
playerEntity.setInvinceableTime(SPAWN_INVINCEABLILITY_TIME);
playerEntity.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
dispatcher.queueEvent(new PlayerKilledEvent(this, player, killer, entity.getCenterPos()));
removePlayer(entity);
//entities.remove(entity); // we want them to be picked up via deadEntities
player.applySpawnDelay();
player.setKilledAt();
}
};
// this doesn't remove points
if(player.isAlive()) {
// player.commitSuicide();
Entity ent = player.getEntity();
ent.softKill();
removePlayer(ent);
}
// safe guard against faulty spawn points
spawnPosition = findFreeSpot(playerEntity);
player.setEntity(playerEntity);
addEntity(playerEntity);
addPlayer(playerEntity);
dispatcher.queueEvent(new PlayerSpawnedEvent(this, player, spawnPosition));
aiSystem.playerSpawned(player);
return playerEntity;
}
/**
* Adds an entity to the game world
*
* @param ent
*/
public void addEntity(Entity ent) {
int id = ent.getId();
if(id >= 0 && id < MAX_ENTITIES) {
entities[id] = ent;
}
}
public boolean playerSwitchedTeam(int playerId, byte teamId) {
boolean playerSwitched = false;
Player player = this.players.getPlayer(playerId);
if(player!=null) {
playerSwitched = gameType.switchTeam(player, teamId);
if(playerSwitched) {
// always kill the player
if(player.hasEntity()) {
player.commitSuicide();
}
if(Team.SPECTATOR_TEAM_ID != teamId) {
player.stopSpectating();
}
/* make sure the player has the teams weaponry */
switch(player.getWeaponClass()) {
case THOMPSON:
case MP40:
if(teamId == Team.ALLIED_TEAM_ID) {
player.setWeaponClass(Type.THOMPSON);
}
else {
player.setWeaponClass(Type.MP40);
}
break;
case KAR98:
case SPRINGFIELD:
if(teamId == Team.ALLIED_TEAM_ID) {
player.setWeaponClass(Type.SPRINGFIELD);
}
else {
player.setWeaponClass(Type.KAR98);
}
break;
case MP44:
case M1_GARAND:
if(teamId == Team.ALLIED_TEAM_ID) {
player.setWeaponClass(Type.M1_GARAND);
}
else {
player.setWeaponClass(Type.MP44);
}
break;
case SHOTGUN:
case ROCKET_LAUNCHER:
case RISKER:
case FLAME_THROWER:
break;
/* make the player use the default weapon */
default: {
if(teamId == Team.ALLIED_TEAM_ID) {
player.setWeaponClass(Type.THOMPSON);
}
else {
player.setWeaponClass(Type.MP40);
}
}
}
}
}
return playerSwitched;
}
/**
* A player has requested to switch its weapon class
*
* @param playerId
* @param weaponType
*/
public void playerSwitchWeaponClass(int playerId, Type weaponType) {
Player player = players.getPlayer(playerId);
if(player!=null) {
if(player.getPlayerClass().isAvailableWeapon(weaponType)) {
player.setWeaponClass(weaponType);
}
}
}
/**
* A player has requested to switch its player class
*
* @param playerId
* @param weaponType
*/
public void playerSwitchPlayerClass(int playerId, PlayerClass playerClass) {
Player player = players.getPlayer(playerId);
if(player!=null) {
gameType.switchPlayerClass(player, playerClass);
}
}
/**
* A player has requested to switch their active tile
* (this is for builder player classes)
*
* @param playerId
* @param newTileId
*/
public void playerSwitchTile(int playerId, int newTileId) {
Player player = players.getPlayer(playerId);
if(player!=null) {
player.setActiveTile(newTileId);
}
}
/**
* Attempts to change the player's commander status
* @param player
* @param isCommander
* @return true if successfully changed the commander status of the player
*/
public boolean playerCommander(Player player, boolean isCommander) {
if(player!=null) {
if(isCommander) {
Team team = player.getTeam();
if(team.isValid() && !team.hasCommander()) {
if(player.isAlive()) {
Entity ent = player.getEntity();
ent.softKill();
removePlayer(ent);
}
player.setCommander(isCommander);
return true;
}
}
else {
player.setCommander(isCommander);
return true;
}
}
return false;
}
/**
* Receives an AICommand from a player.
*
* @param fromPlayerId
* @param msg
*/
public void receiveAICommand(int fromPlayerId, AICommandMessage msg) {
Player player = players.getPlayer(fromPlayerId);
if(player != null) {
PlayerInfo botPlayer = getPlayerById(msg.botId);
if(botPlayer.isBot()) {
if(player.getTeamId() == botPlayer.getTeamId()) {
aiSystem.receiveAICommand(botPlayer, msg.command);
}
}
}
}
/**
* Applies the remote {@link PlayerInputMessage} to the {@link PlayerEntity}
*
* @param playerId
* @param msg
*/
public void applyPlayerInput(int playerId, PlayerInputMessage msg) {
Player player = this.players.getPlayer(playerId);
if(player != null) {
if(player.isAlive()) {
PlayerEntity entity = player.getEntity();
entity.handleUserCommand(msg.keys, msg.orientation);
}
else {
player.handleInput(this, msg.keys);
}
}
}
/**
* Kill all entities, invokes a softKill on
* all active game entities
*/
public void killAll() {
for(int i = 0; i < entities.length; i++) {
Entity ent = entities[i];
if(ent!=null) {
ent.softKill();
}
entities[i] = null;
}
for(int i = 0; i < playerEntities.length; i++) {
playerEntities[i] = null;
}
this.bombTargets.clear();
this.vehicles.clear();
this.flags.clear();
this.doors.clear();
this.smokeEntities.clear();
this.bases.clear();
markDeadFrames();
}
private void markDeadFrames() {
// mark all entities as dead, so that we can reload them
// on start up
for(int i = MAX_PLAYERS; i < deadFrames.length; i++) {
deadFrames[i] = 999;
}
}
/**
* Removes a destructable tile at the supplied world coordinate
*
* @param x
* @param y
*/
public void removeTileAtWorld(int x, int y) {
if(map.removeDestructableTileAtWorld(x, y)) {
int tileX = map.worldToTileX(x);
int tileY = map.worldToTileY(y);
// Add in a graph node so this terrain object
// can be traversed for path finding for bots
this.graph.addNode(tileX, tileY);
this.dispatcher.queueEvent(new TileRemovedEvent(this, tileX, tileY));
}
}
/**
* Spawns a new {@link PanzerTank}
*
* @param x
* @param y
* @return the {@link PanzerTank}
*/
public Tank newPanzerTank(float x, float y, Long timeToKill) {
return newPanzerTank(new Vector2f(x, y), timeToKill);
}
/**
* Spawns a new {@link PanzerTank}
*
* @param pos
* @param timeToKill the time it takes for this once it is destroyed to be
* set to the killed state
* @return the {@link PanzerTank}
*/
public Tank newPanzerTank(Vector2f pos, Long timeToKill) {
if(timeToKill==null) {
timeToKill = -1L;
}
return registerTank(new PanzerTank(pos, this, timeToKill));
}
/**
* Spawns a new {@link ShermanTank}
*
* @param x
* @param y
* @param timeToKill the time it takes for this once it is destroyed to be
* set to the killed state
* @return the {@link ShermanTank}
*/
public Tank newShermanTank(float x, float y, Long timeToKill) {
return newShermanTank(new Vector2f(x, y), timeToKill);
}
/**
* Spawns a new {@link ShermanTank}
*
* @param pos
* @param timeToKill the time it takes for this once it is destroyed to be
* set to the killed state
* @return the {@link ShermanTank}
*/
public Tank newShermanTank(Vector2f pos, Long timeToKill) {
if(timeToKill==null) {
timeToKill = -1L;
}
return registerTank(new ShermanTank(pos, this, timeToKill));
}
/**
* Register a {@link Tank} with the game
*
* @param tank
* @return the supplied tank
*/
private Tank registerTank(final Tank tank) {
tank.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
vehicles.remove(tank);
}
};
vehicles.add(tank);
addEntity(tank);
return tank;
}
/**
* Spawns a new {@link DroppedItem}
*
* @param pos
* @param item
* @return the item
*/
public DroppedItem newDroppedItem(Vector2f pos, Weapon item) {
final DroppedItem droppedItem = new DroppedItem(pos, this, item);
droppedItem.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
droppedItems.remove(droppedItem);
}
};
droppedItems.add(droppedItem);
addEntity(droppedItem);
return droppedItem;
}
/**
* Spawns a new {@link DroppedItem}
*
* @param pos
* @param item
* @return the item
*/
public DroppedItem newDroppedItem(Vector2f pos, String type) {
Type weaponType = Type.valueOf(type.toUpperCase());
Weapon weapon = null;
switch(weaponType) {
case THOMPSON:
weapon = new Thompson(this, null);
break;
case MP40:
weapon = new MP40(this, null);
break;
case M1_GARAND:
weapon = new M1Garand(this, null);
break;
case MP44:
weapon = new MP44(this, null);
break;
case KAR98:
weapon = new Kar98(this, null);
break;
case SPRINGFIELD:
weapon = new Springfield(this, null);
break;
case RISKER:
weapon = new Risker(this, null);
break;
case SHOTGUN:
weapon = new Shotgun(this, null);
break;
case ROCKET_LAUNCHER:
weapon = new RocketLauncher(this, null);
break;
case FLAME_THROWER:
weapon = new FlameThrower(this, null);
break;
default:
}
if(weapon!=null) {
return newDroppedItem(pos, weapon);
}
return null;
}
/**
* Spawns a new {@link Bomb}
* @param target
* @return the bomb
*/
public Bomb newBomb(BombTarget target) {
Bomb bomb = new Bomb(target.getCenterPos(), this);
addEntity(bomb);
return bomb;
}
/**
* Spawns a new {@link BombTarget}
* @param position
* @return the bomb target
*/
public BombTarget newBombTarget(Team owner, Vector2f position) {
final BombTarget target = new BombTarget(owner, position, this);
target.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
bombTargets.remove(target);
}
};
this.bombTargets.add(target);
addEntity(target);
return target;
}
/**
* Creates a new {@link HealthPack}
*
* @param x
* @param y
* @return the {@link HealthPack}
*/
public HealthPack newHealthPack(float x, float y) {
return newHealthPack(new Vector2f(x,y));
}
/**
* Creates a new {@link HealthPack}
*
* @param pos
* @return the {@link HealthPack}
*/
public HealthPack newHealthPack(Vector2f pos) {
HealthPack pack = new HealthPack(pos, this);
addEntity(pack);
return pack;
}
/**
* Adds a new {@link LightBulb} to the game
* @param pos
* @return a new light
*/
public LightBulb newLight(Vector2f pos) {
LightBulb light = new LightBulb(pos, this);
this.addEntity(light);
return light;
}
/**
* Adds a new {@link LightBulb} to the game
* @param x
* @param y
* @return a new light
*/
public LightBulb newLight(float x, float y) {
return newLight(new Vector2f(x,y));
}
/**
* Adds a new {@link Door} to the game
*
* @param pos
* @param facing
* @return a new Door
*/
public Door newDoor(Vector2f pos, Vector2f facing) {
Door door = new Door(pos, this, facing);
this.doors.add(door);
this.addEntity(door);
return door;
}
/**
* Adds a new {@link Door} to the game
*
* @param x
* @param y
* @param facingX
* @param facingY
* @return a new Door
*/
public Door newDoor(float x, float y, float facingX, float facingY) {
return newDoor(new Vector2f(x,y), new Vector2f(facingX, facingY));
}
/**
* Adds a new {@link Explosion}
* @param pos
* @param owner
* @param splashDamage
* @return the {@link Explosion}
*/
public Explosion newExplosion(Vector2f pos, Entity owner, int splashDamage) {
Explosion explosion = new Explosion(pos, 0, this, owner, splashDamage);
this.addEntity(explosion);
return explosion;
}
/**
* Adds a new {@link Smoke}
*
* @param pos
* @param owner
* @param damage
* @return the {@link Smoke}
*/
public Smoke newSmoke(Vector2f pos, int speed, Vector2f vel, Entity owner) {
final Smoke smoke = new Smoke(pos, speed, this, vel);
smoke.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
smokeEntities.remove(smoke);
}
};
this.smokeEntities.add(smoke);
this.addEntity(smoke);
return smoke;
}
/**
* Adds a new {@link Fire}
* @param pos
* @param owner
* @param damage
* @return the {@link Fire}
*/
public Fire newFire(Vector2f pos, int speed, Vector2f vel, Entity owner, int damage) {
Fire fire = new Fire(pos, speed, this, owner, vel, damage);
this.addEntity(fire);
return fire;
}
public void newBigExplosion(Vector2f position, Entity owner, int splashWidth, int maxSpread, int splashDamage) {
Vector2f tl = new Vector2f(position.x - (splashWidth + random.nextInt(maxSpread)),
position.y - (splashWidth + random.nextInt(maxSpread)));
newExplosion(tl, owner, splashDamage);
Vector2f tr = new Vector2f(position.x + (splashWidth + random.nextInt(maxSpread)),
position.y - (splashWidth + random.nextInt(maxSpread)));
newExplosion(tr, owner, splashDamage);
Vector2f bl = new Vector2f(position.x - (splashWidth + random.nextInt(maxSpread)),
position.y + (splashWidth + random.nextInt(maxSpread)));
newExplosion(bl, owner, splashDamage);
Vector2f br = new Vector2f(position.x + (splashWidth + random.nextInt(maxSpread)),
position.y + (splashWidth + random.nextInt(maxSpread)));
newExplosion(br, owner, splashDamage);
Vector2f center = new Vector2f(position.x,position.y);
newExplosion(center, owner, splashDamage);
}
public void newBigFire(Vector2f position, Entity owner, int damage) {
Random random = getRandom();
final int maxSpread = 360;
for(int i = 0; i < 8; i++) {
Vector2f vel = new Vector2f(1.0f, 0.0f);
double rd = Math.toRadians(random.nextInt(maxSpread));
Vector2f.Vector2fRotate(vel, rd, vel);
int speed = 110 + random.nextInt(15);
newFire(position.createClone(), speed, vel, owner, damage);
}
}
/**
* @param position
* @return a new Allied Flag
*/
public Flag newAlliedFlag(Vector2f position) {
Flag flag = new Flag(this, position, Type.ALLIED_FLAG);
addEntity(flag);
this.flags.add(flag);
return flag;
}
/**
* @param position
* @return a new Axis flag
*/
public Flag newAxisFlag(Vector2f position) {
Flag flag = new Flag(this, position, Type.AXIS_FLAG);
addEntity(flag);
this.flags.add(flag);
return flag;
}
/**
* @param position
* @return a new Allied base
*/
public Base newAlliedBase(Vector2f position) {
final Base base = new Base(this, position, Type.ALLIED_BASE);
base.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
bases.remove(base);
newBigExplosion(base.getCenterPos(), killer, 45, 40, 1);
}
};
addEntity(base);
this.bases.add(base);
return base;
}
/**
* @param position
* @return a new Axis base
*/
public Base newAxisBase(Vector2f position) {
final Base base = new Base(this, position, Type.AXIS_BASE);
base.onKill = new KilledListener() {
@Override
public void onKill(Entity entity, Entity killer) {
bases.remove(base);
newBigExplosion(base.getCenterPos(), killer, 45, 40, 1);
}
};
addEntity(base);
this.bases.add(base);
return base;
}
/**
* If the entity is near enough a dropped weapon to pick up.
*
* @param entity
* @return the dropped weapon which the entity is close enough to pick up,
* otherwise null
*/
public DroppedItem getArmsReachDroppedWeapon(PlayerEntity entity) {
int size = this.droppedItems.size();
for(int i = 0; i < size; i++) {
DroppedItem item = this.droppedItems.get(i);
if(item.canBePickedUpBy(entity)) {
return item;
}
}
return null;
}
/**
* If the entity is near enough a door to handle.
*
* @param entity
* @return the door which the entity is close enough to handle,
* otherwise null
*/
public Door getArmsReachDoor(PlayerEntity entity) {
int size = this.doors.size();
for(int i = 0; i < size; i++) {
Door door = this.doors.get(i);
if(door.canBeHandledBy(entity)) {
return door;
}
}
return null;
}
/*
* (non-Javadoc)
* @see seventh.game.GameInfo#getArmsReachBombTarget(seventh.game.PlayerEntity)
*/
@Override
public BombTarget getArmsReachBombTarget(PlayerEntity entity) {
BombTarget handleMe = null;
int size = this.bombTargets.size();
for(int i = 0; i < size; i++) {
BombTarget target = this.bombTargets.get(i);
if(target.canHandle(entity)) {
handleMe = target;
break;
}
}
return handleMe;
}
/*
* (non-Javadoc)
* @see seventh.game.GameInfo#getCloseOperableVehicle(seventh.game.Entity)
*/
@Override
public Vehicle getArmsReachOperableVehicle(Entity operator) {
Vehicle rideMe = null;
for(int i = 0; i < this.vehicles.size(); i++) {
Vehicle vehicle = this.vehicles.get(i);
if(vehicle.isAlive()) {
if(vehicle.canOperate(operator)) {
rideMe = vehicle;
break;
}
}
}
return rideMe;
}
/**
* @param vehicle
* @return true if the supplied {@link Vehicle} touches a {@link PlayerEntity}
*/
@Override
public boolean doesVehicleTouchPlayers(Vehicle vehicle) {
if(vehicle.hasOperator()) {
PlayerEntity operator = vehicle.getOperator();
for(int i = 0; i < this.playerEntities.length; i++) {
Entity other = this.playerEntities[i];
if(other != null) {
if(other != operator && vehicle.isTouching(other)) {
if(vehicle.onTouch != null) {
vehicle.onTouch.onTouch(vehicle, other);
return true;
}
}
}
}
}
return false;
}
@Override
public boolean doesTouchOthers(Entity ent) {
return doesTouchOthers(ent, true);
}
@Override
public boolean doesTouchOthers(Entity ent, boolean invokeTouch) {
for(int i = 0; i < this.vehicles.size(); i++) {
Entity other = this.vehicles.get(i);
if(other != null) {
if(other != ent && other.isTouching(ent)) {
if(!invokeTouch) {
return true;
}
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
for(int i = 0; i < this.doors.size(); i++) {
Entity other = this.doors.get(i);
if(other != null) {
if(other != ent && other.isTouching(ent)) {
if(!invokeTouch) {
return true;
}
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
return false;
}
@Override
public boolean doesTouchEntity(Rectangle bounds) {
for(int i = 0; i < this.entities.length; i++) {
Entity other = this.entities[i];
if(other != null) {
if(bounds.intersects(other.getBounds())) {
return true;
}
}
}
return false;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#doesTouchPlayers(seventh.game.Entity)
*/
@Override
public boolean doesTouchPlayers(Entity ent) {
for(int i = 0; i < this.playerEntities.length; i++) {
Entity other = this.playerEntities[i];
if(other != null) {
if(other != ent && /*other.bounds.intersects(ent.bounds)*/ ent.isTouching(other)) {
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
return false;
}
public boolean doesTouchBases(Entity ent) {
for(int i = 0; i < this.bases.size(); i++) {
Base base = this.bases.get(i);
if(base != ent && ent.isTouching(base)) {
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, base);
return true;
}
}
}
return false;
}
public boolean doesTouchMapObject(Entity ent) {
return doesTouchMapObject(ent, true);
}
public boolean doesTouchMapObject(Entity ent, boolean invokeTouch) {
List<MapObject> mapObjects = getCollidableMapObjects();
for(int i = 0; i < mapObjects.size(); i++) {
MapObject object = mapObjects.get(i);
if(object.isCollidable()) {
if(object.isTouching(ent)) {
if(!invokeTouch) {
return true;
}
if(!object.onTouch(this, ent)) {
continue;
}
if(ent.onMapObjectTouch != null) {
ent.onMapObjectTouch.onTouch(ent, object);
return true;
}
}
}
}
return false;
}
/*
* (non-Javadoc)
* @see seventh.game.GameInfo#doesTouchVehicles(seventh.game.Entity)
*/
@Override
public boolean doesTouchVehicles(Entity ent) {
for(int i = 0; i < this.vehicles.size(); i++) {
Entity other = this.vehicles.get(i);
if(other != null) {
if(other != ent && other.isTouching(ent)) {
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
return false;
}
@Override
public boolean doesTouchDoors(Entity ent) {
for(int i = 0; i < this.doors.size(); i++) {
Entity other = this.doors.get(i);
if(other != null) {
if(other != ent && other.isTouching(ent)) {
if(ent.onTouch != null) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
return false;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#doesTouchPlayers(seventh.game.Entity, seventh.math.Vector2f, seventh.math.Vector2f)
*/
@Override
public boolean doesTouchPlayers(Entity ent, Vector2f origin, Vector2f dir) {
if(ent.onTouch != null) {
for(int i = 0; i < this.playerEntities.length; i++) {
Entity other = this.playerEntities[i];
if(other != null) {
if(other != ent && other.canTakeDamage() && /*other.bounds.intersects(ent.bounds)*/ ent.isTouching(other)) {
if(isEntityReachable(other, origin, dir)) {
ent.onTouch.onTouch(ent, other);
return true;
}
}
}
}
}
return false;
}
/* (non-Javadoc)
* @see seventh.game.GameInfo#isEntityReachable(seventh.game.Entity, seventh.math.Vector2f, seventh.math.Vector2f)
*/
@Override
public boolean isEntityReachable(Entity other, Vector2f origin, Vector2f dir) {
// we only have to do weird checks if the target entity is
// ducking
if(other.getHeightMask() != Entity.STANDING_HEIGHT_MASK) {
Vector2f otherPos = other.getCenterPos();
// if the bullet came from another tile, we must
// check and see if this entity is being sheltered by
// a heightMask tile
float traveledSq = Vector2f.Vector2fDistanceSq(otherPos, origin);
if(traveledSq > DISTANCE_CHECK) {
Tile tile = map.getWorldTile(0, (int)otherPos.x, (int)otherPos.y);
if(tile != null) {
int adjacentX = (int)(tile.getX() + (TILE_WIDTH/2) + (TILE_WIDTH * -dir.x));
int adjacentY = (int)(tile.getY() + (TILE_HEIGHT/2) + (TILE_HEIGHT * -dir.y));
// if the target entity is safely crouching behind
// a heightMask tile, the bullet can't touch him
if( map.hasHeightMask( adjacentX, adjacentY) ) {
return false;
}
}
}
}
return true;
}
public void foreachEntity(final LeoObject func) {
for(int i = 0; i < this.entities.length; i++) {
Entity ent = this.entities[i];
if(ent!=null) {
if (LeoObject.isTrue(func.call(ent.asScriptObject()))) {
break;
}
}
}
}
public void foreachPlayer(final LeoObject func) {
for(int i = 0; i < this.playerEntities.length; i++) {
Entity ent = this.playerEntities[i];
if(ent!=null) {
if (LeoObject.isTrue(func.call(ent.asScriptObject()))) {
break;
}
}
}
}
/**
* @return the enableFOW
*/
public boolean isEnableFOW() {
return enableFOW;
}
/**
* @param enable
*/
public void enableFOW(boolean enable) {
this.enableFOW =enable;
}
/**
* @return the full networked game state
*/
public NetGameState getNetGameState() {
NetGameState gameState = new NetGameState();
for(int i = 0; i < this.entities.length; i++) {
Entity other = this.entities[i];
if(other != null) {
gameState.entities[i] = other.getNetEntity();
}
else {
gameState.entities[i] = null;
}
}
gameState.gameType = this.gameType.getNetGameTypeInfo();
gameState.map = this.gameMap.getNetMap();
gameState.stats = getNetGameStats();
List<Tile> removedTiles = this.map.getRemovedTiles();
if(!removedTiles.isEmpty()) {
int[] tiles = new int[removedTiles.size() * 2];
if(gameState.mapDestructables==null) {
gameState.mapDestructables = new NetMapDestructables();
}
int tileIndex = 0;
for(int i = 0; i < removedTiles.size(); i++, tileIndex += 2) {
Tile tile = removedTiles.get(i);
tiles[tileIndex + 0] = tile.getXIndex();
tiles[tileIndex + 1] = tile.getYIndex();
}
gameState.mapDestructables.length = tiles.length;
gameState.mapDestructables.tiles = tiles;
}
List<Tile> addedTiles = this.map.getAddedTiles();
if(!addedTiles.isEmpty()) {
gameState.mapAdditions = new NetMapAdditions();
gameState.mapAdditions.tiles = new NetMapAddition[addedTiles.size()];
for(int i = 0; i < addedTiles.size(); i++) {
Tile tile = addedTiles.get(i);
gameState.mapAdditions.tiles[i] = new NetMapAddition(tile.getXIndex(), tile.getYIndex(), tile.getType());
}
}
return gameState;
}
/**
* @return just returns the networked game statistics
*/
public NetGameStats getNetGameStats() {
return gameType.getNetGameStats();
}
/**
* @return returns the networked game (partial) statistics
*/
public NetGamePartialStats getNetGamePartialStats() {
return gameType.getNetGamePartialStats();
}
/**
* In order to properly play the location of a sound, some sounds are attached
* to an entity. But, not all players are updated every frame, so this can cause
* the sound to play in the wrong position; to fix this, if the Player is not included
* in this update, we enable the positional information of the NetSound and by pass
* the client's positional information.
*
* @param snds
* @param entities
*/
private void adjustNetSoundsPosition(NetSound[] snds, NetEntity[] entities) {
if(snds!=null) {
for(int sndIndex = 0; sndIndex < snds.length; sndIndex++) {
NetSound snd = snds[sndIndex];
if(snd != null) {
switch(snd.getSoundType().getSourceType()) {
case REFERENCED:
case REFERENCED_ATTACHED:
/* If the attached entity is not included in this
* packet, then include the positional information of the
* sound
*/
NetSoundByEntity sndByEntity = (NetSoundByEntity) snd;
if(entities[sndByEntity.entityId] == null) {
sndByEntity.enablePosition();
}
break;
default: /* do nothing */
}
}
}
}
}
/**
* @param playerId
* @return returns only the entities within the viewport of the supplied player
*/
public NetGameUpdate getNetGameUpdateFor(int playerId) {
Player player = this.players.getPlayer(playerId);
if(player == null) {
return null;
}
NetGameUpdate netUpdate = new NetGameUpdate();
if (player.isPureSpectator()) {
NetEntity.toNetEntities(entities, netUpdate.entities);
netUpdate.setNetSounds(NetSound.toNetSounds(soundEvents));
/*
* If the current player you are watching is dead,
* follow another player
*/
if( player.getSpectating()==null || player.getSpectating().isDead()) {
Player otherPlayer = this.players.getRandomAlivePlayer();
if(otherPlayer!=null) {
player.setSpectating(otherPlayer);
}
}
}
else if(player.isCommander()) {
Team team = player.getTeam();
List<Player> players = team.getPlayers();
aEntitiesInView.clear();
aSoundsHeard.clear();
for(int i = 0; i < players.size(); i++) {
Player p = players.get(i);
if(p.isAlive()) {
PlayerEntity playerEntity = p.getEntity();
aSoundsHeard = playerEntity.getHeardSounds(soundEvents, aSoundsHeard);
aEntitiesInView = playerEntity.getEntitiesInView(this, aEntitiesInView);
aEntitiesInView.add(playerEntity);
}
}
netUpdate.setNetSounds(NetSound.consolidateToNetSounds(aSoundsHeard));
NetEntity.toNetEntities(aEntitiesInView, netUpdate.entities);
adjustNetSoundsPosition(netUpdate.sounds, netUpdate.entities);
}
else {
PlayerEntity playerEntity = player.isSpectating() ? player.getSpectatingEntity() : player.getEntity();
if(playerEntity != null) {
/*
* Calculate all the sounds this player can hear
*/
aSoundsHeard.clear();
aSoundsHeard = playerEntity.getHeardSounds(soundEvents, aSoundsHeard);
netUpdate.setNetSounds(NetSound.toNetSounds(aSoundsHeard));
/*
* Calculate all the visuals this player can see
*/
aEntitiesInView.clear();
aEntitiesInView = playerEntity.getEntitiesInView(this, aEntitiesInView);
NetEntity.toNetEntities(aEntitiesInView, netUpdate.entities);
/* now add the players full entity state */
if(playerEntity.isAlive()) {
netUpdate.entities[playerEntity.getId()] = playerEntity.getNetPlayer();
}
adjustNetSoundsPosition(netUpdate.sounds, netUpdate.entities);
}
}
for(int i = 0; i < MAX_PERSISTANT_ENTITIES; i++) {
if(deadFrames[i] > 0) {
netUpdate.deadPersistantEntities.setBit(i);
}
}
netUpdate.time = (int)time;
netUpdate.spectatingPlayerId = player.getSpectatingPlayerId();
return netUpdate;
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("entities", this.entities)
.add("bombTargets", this.bombTargets)
.add("map", this.map)
.add("game_type", this.gameType)
.add("ai", this.aiSystem)
;
return me;
}
}
| 78,541 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SurfaceTypeToSoundType.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/SurfaceTypeToSoundType.java | /*
* see license.txt
*/
package seventh.game;
import seventh.map.Tile.SurfaceType;
import seventh.shared.SoundType;
/**
* Simple utility class to convert {@link SurfaceType}'s to {@link SoundType}'s
*
* @author Tony
*
*/
public class SurfaceTypeToSoundType {
/**
* Converts the {@link SurfaceType} to a sound for foot steps
* @param surface
* @return the appropriate foot steps sound
*/
public static SoundType toSurfaceSoundType(SurfaceType surface) {
SoundType result = SoundType.SURFACE_NORMAL;
switch(surface) {
case CEMENT:
result = SoundType.SURFACE_NORMAL;
break;
case DIRT:
result = SoundType.SURFACE_DIRT;
break;
case GRASS:
result = SoundType.SURFACE_GRASS;
break;
case METAL:
result = SoundType.SURFACE_METAL;
break;
case SAND:
result = SoundType.SURFACE_SAND;
break;
case UNKNOWN:
result = SoundType.SURFACE_NORMAL;
break;
case WATER:
result = SoundType.SURFACE_WATER;
break;
case WOOD:
result = SoundType.SURFACE_WOOD;
break;
default:
break;
}
return result;
}
/**
* Converts to the appropriate impact sound (for bullets)
* @param surface
* @return
*/
public static SoundType toImpactSoundType(SurfaceType surface) {
SoundType result = SoundType.IMPACT_DEFAULT;
switch(surface) {
case CEMENT:
result = SoundType.IMPACT_DEFAULT; // TODO
break;
case DIRT:
result = SoundType.IMPACT_DEFAULT;
break;
case GRASS:
result = SoundType.IMPACT_FOLIAGE;
break;
case METAL:
result = SoundType.IMPACT_METAL;
break;
case SAND:
result = SoundType.IMPACT_DEFAULT;
break;
case UNKNOWN:
result = SoundType.IMPACT_DEFAULT;
break;
case WATER:
result = SoundType.IMPACT_DEFAULT; // TODO
break;
case WOOD:
result = SoundType.IMPACT_WOOD;
break;
case GLASS:
result = SoundType.IMPACT_GLASS;
break;
default:
break;
}
return result;
}
}
| 2,701 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Team.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Team.java | /*
* see license.txt
*/
package seventh.game;
import java.util.ArrayList;
import java.util.List;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.net.NetTeam;
import seventh.game.net.NetTeamStat;
import seventh.math.Vector2f;
import seventh.shared.Debugable;
/**
* A team is a collection of {@link Player}s. The team contains a score, at the
* end of a game the team with the highest score wins!
*
* @author Tony
*
*/
public class Team implements Debugable {
/**
* Team ID's
*/
public static final byte ALLIED_TEAM_ID = 1,
AXIS_TEAM_ID = 2,
SPECTATOR_TEAM_ID = 0;
/**
* Team Names
*/
public static final String ALLIED_TEAM_NAME = "Allies";
public static final String AXIS_TEAM_NAME = "Axis";
public static final String SPECTATOR_NAME = "Spectator";
/**
* The Spectator team
*/
public static final Team SPECTATOR = new Team(SPECTATOR_TEAM_ID) {
/**
* Spectators are not allowed to score points
*/
public void score(int points) {
}
};
/**
* @return a new Allied team
*/
public static Team newAlliedTeam() {
return new Team(ALLIED_TEAM_ID);
}
/**
* @return a new Axis team
*/
public static Team newAxisTeam() {
return new Team(AXIS_TEAM_ID);
}
/**
* Gets the Team name based on the Team ID.
*
* @param id the Team ID
* @return the name representing the ID
*/
public static String getName(byte id) {
switch(id) {
case ALLIED_TEAM_ID: {
return ALLIED_TEAM_NAME;
}
case AXIS_TEAM_ID: {
return AXIS_TEAM_NAME;
}
default: {
return SPECTATOR_NAME;
}
}
}
private final byte id;
private List<Player> players;
private int score;
private boolean isAttacker;
private boolean isDefender;
/**
*
*/
private Team(byte id) {
this.id = id;
this.players = new ArrayList<Player>();
}
/**
* @param isAttacker the isAttacker to set
*/
public void setAttacker(boolean isAttacker) {
this.isAttacker = isAttacker;
this.isDefender = false;
}
/**
* @param isDefender the isDefender to set
*/
public void setDefender(boolean isDefender) {
this.isDefender = isDefender;
this.isAttacker = false;
}
/**
* @return the isAttacker
*/
public boolean isAttacker() {
return isAttacker;
}
/**
* @return the isDefender
*/
public boolean isDefender() {
return isDefender;
}
/**
* @return true if this is either the allied or axis team
*/
public boolean isValid() {
return this.getId() != SPECTATOR.getId();
}
/**
* Returns the number of players in the supplied list that are on this
* team.
* @param players
* @return the number of players in the list on this team
*/
public int getNumberOfPlayersOnTeam(List<PlayerEntity> players) {
int sum = 0;
for(int i = 0; i < players.size(); i++) {
PlayerEntity player = players.get(i);
if(player != null) {
Team team = player.getTeam();
if(team != null) {
if(team.getId() == getId()) {
sum++;
}
}
}
}
return sum;
}
/**
* @return the team name
*/
public String getName() {
return getName(getId());
}
/**
* Score points
*
* @param points
*/
public void score(int points) {
this.score += points;
}
/**
* @param score the score to set
*/
public void setScore(int score) {
this.score = score;
}
/**
* @return the score
*/
public int getScore() {
return score;
}
/**
* @return the id
*/
public byte getId() {
return id;
}
public void addPlayer(Player p) {
boolean isAlreadyOnTeam = false;
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(player != null) {
if(player.getId() == p.getId()) {
isAlreadyOnTeam = true;
break;
}
}
}
if(!isAlreadyOnTeam) {
this.players.add(p);
}
p.setTeam(this);
}
public void removePlayer(Player p) {
this.players.remove(p);
p.setTeam(null);
}
/**
* Determines if the supplied player is on the team
*
* @param p
* @return true if the supplied player is on the team
*/
public boolean onTeam(Player p) {
return onTeam(p.getId());
}
public boolean onTeam(int playerId) {
return getPlayerById(playerId) != null;
}
public Player getPlayerById(int playerId) {
int size = this.players.size();
for(int i = 0; i < size; i++) {
Player player = this.players.get(i);
if(player.getId() == playerId) {
return player;
}
}
return null;
}
/**
* @return the number of players on this team
*/
public int teamSize() {
return this.players.size();
}
/**
* @return the total number of kills this team as accrued
*/
public int getTotalKills() {
int kills = 0;
for(int i = 0; i < this.players.size(); i++) {
kills += this.players.get(i).getKills();
}
return kills;
}
/**
* @return true if and only if each team member is dead
*/
public boolean isTeamDead() {
boolean isDead = true;
for(int i = 0; i < this.players.size(); i++) {
isDead &= this.players.get(i).isDead();
}
return isDead;
}
/**
* @return true if there is a commander on this team
*/
public boolean hasCommander() {
for(int i = 0; i < this.players.size(); i++) {
if(this.players.get(i).isCommander()) {
return true;
}
}
return false;
}
/**
* @return a semi-random alive player that is on this team, null
* if no player is alive
*/
public Player getAlivePlayer() {
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(player.isAlive()) {
return player;
}
}
return null;
}
/**
* @return a semi-random alive player (that is a bot) that is on this team, null
* if no player is alive
*/
public Player getAliveBot() {
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(player.isAlive() && player.isBot()) {
return player;
}
}
return null;
}
/**
* @return all the players on this team
*/
public List<Player> getPlayers() {
return this.players;
}
/**
* Gets the closest alive player to the supplied entity
* @param other
* @return the closest player or null if no alive players
*/
public Player getClosestPlayerTo(Entity other) {
Player closest = null;
float distance = -1;
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(player.isAlive()) {
PlayerEntity ent = player.getEntity();
float dist = Vector2f.Vector2fDistanceSq(ent.getPos(), other.getPos());
if(closest != null || dist < distance) {
closest = player;
distance = dist;
}
}
}
return closest;
}
/**
* Gets the closest alive bot to the supplied entity
* @param other
* @return the closest bot or null if no alive players
*/
public Player getClosestBotTo(Entity other) {
Player closest = null;
float distance = -1;
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(player.isAlive() && player.isBot()) {
PlayerEntity ent = player.getEntity();
float dist = Vector2f.Vector2fDistanceSq(ent.getPos(), other.getPos());
if(closest != null || dist < distance) {
closest = player;
distance = dist;
}
}
}
return closest;
}
/**
* The next available alive player on this team from the 'oldPlayer'
* @param oldPlayer
* @return the next {@link Player} or null if none
*/
public Player getNextAlivePlayerFrom(Player oldPlayer) {
if(oldPlayer == null ) return getAlivePlayer();
int nextPlayerIndex = players.indexOf(oldPlayer);
if(nextPlayerIndex < 0) {
nextPlayerIndex = 0;
}
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(nextPlayerIndex);
if(player != null) {
if(player.isAlive() && player != oldPlayer) {
return player;
}
}
nextPlayerIndex = (nextPlayerIndex + 1) % players.size();
}
return null;
}
/**
* The previous available alive player on this team from the 'oldPlayer'
* @param oldPlayer
* @return the previous {@link Player} or null if none
*/
public Player getPrevAlivePlayerFrom(Player oldPlayer) {
if(oldPlayer == null ) return getAlivePlayer();
int nextPlayerIndex = players.indexOf(oldPlayer);
if(nextPlayerIndex < 0) {
nextPlayerIndex = Math.max(players.size() - 1, 0);
}
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(nextPlayerIndex);
if(player != null) {
if(player.isAlive() && player != oldPlayer) {
return player;
}
}
nextPlayerIndex = (nextPlayerIndex - 1) % players.size();
if(nextPlayerIndex < 0) {
nextPlayerIndex = Math.max(players.size() - 1, 0);
}
}
return null;
}
/**
* The next alive bot from the supplied Player slot
* @param old
* @return the next alive bot, or null if no bot is alive
*/
public Player getNextAliveBotFrom(Player old) {
if(old==null) {
return getAliveBot();
}
boolean found = false;
boolean firstIteration = true;
for(int i = 0; i < this.players.size(); i++) {
Player player = this.players.get(i);
if(firstIteration) {
if(old.getId() == player.getId()) {
found = true;
}
else if(found) {
if(player.isAlive() && player.isBot()) {
return player;
}
}
if(i>=this.players.size()-1) {
i = 0;
firstIteration = false;
}
}
else {
if(player.isAlive() && player.isBot()) {
return player;
}
}
}
return null;
}
/**
* @return the total number of deaths accrued on this team
*/
public int getTotalDeaths() {
int deaths = 0;
for(int i = 0; i < this.players.size(); i++) {
deaths += this.players.get(i).getDeaths();
}
return deaths;
}
/**
* The number of total alive players on this team
* @return the number of alive players on this team
*/
public int getNumberOfAlivePlayers() {
int numberOfAlivePlayers = 0;
for(int i = 0; i < this.players.size(); i++) {
if(this.players.get(i).isAlive()) {
numberOfAlivePlayers++;
}
}
return numberOfAlivePlayers;
}
/**
* @return the number of bots on this team
*/
public int getNumberOfBots() {
int numberOfBots = 0;
for(int i = 0; i < this.players.size(); i++) {
if(this.players.get(i).isBot()) {
numberOfBots++;
}
}
return numberOfBots;
}
/**
* @return the current team size
*/
public int getTeamSize() {
return this.players.size();
}
/**
* @return true if this team is the allied team
*/
public boolean isAlliedTeam() {
return this.id == Team.ALLIED_TEAM_ID;
}
/**
* @return true if this team is the axis team
*/
public boolean isAxisTeam() {
return this.id == Team.AXIS_TEAM_ID;
}
/**
* @return true if this team is the specator team
*/
public boolean isSpectatorTeam() {
return this.id == Team.SPECTATOR_TEAM_ID;
}
/**
* @return this team on a serializable form
*/
public NetTeam getNetTeam() {
NetTeam netTeam = new NetTeam();
netTeam.id = id;
netTeam.playerIds = new int[this.players.size()];
for(int i = 0; i < this.players.size(); i++) {
netTeam.playerIds[i] = this.players.get(i).getId();
}
netTeam.isDefender = this.isDefender;
netTeam.isAttacker = this.isAttacker;
return netTeam;
}
/**
* @return the netTeamStats
*/
public NetTeamStat getNetTeamStats() {
NetTeamStat netTeamStats = new NetTeamStat();
netTeamStats.id = id;
netTeamStats.score = score;
return netTeamStats;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if(obj instanceof Team) {
return ((Team)obj).getId() == this.getId();
}
return false;
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("name", getName())
.add("id", getId())
.add("score",getScore())
.add("total_deaths",getTotalDeaths())
.add("total_kills",getTotalKills())
.add("players", getPlayers())
;
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 15,571 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.