still wip modularisation, game somehow boots

This commit is contained in:
minjaesong
2018-06-21 17:33:22 +09:00
parent 391cbcff34
commit ac09fa50e2
266 changed files with 2409 additions and 1122 deletions

1
.gitignore vendored
View File

@@ -7,3 +7,4 @@ Thumbs.db
~$*
assets/modules/basegame/demoworld
assets/modules/basegame/demoworld.gz
external_resource_packs.zip

44
assets/crt.frag Normal file
View File

@@ -0,0 +1,44 @@
#version 120
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform vec2 resolution;
uniform vec3 phosphor_colour = vec3(1.3, 0.8567, 0.0);
vec3 scanline_darkening = vec3(0.45, 0.45, 0.45);
// 0: every odd line will get darkened; 1: every even line will get darkened
uniform float alternative_scanline = 0.0; // 1.0: true
uniform float blur_blend = 0.3;
void main(void) {
vec3 color = texture2D(u_texture, v_texCoords).rgb;
vec3 color_pre = texture2D(u_texture, (gl_FragCoord + vec2(-1.0, 0.0)) / resolution).rgb;
vec3 color_next = texture2D(u_texture, (gl_FragCoord + vec2( 1.0, 0.0)) / resolution).rgb;
color = color * (1.0 - blur_blend) + color_pre * (blur_blend / 2.0) + color_next * (blur_blend / 2.0);
bool is_scanline = mod(int(gl_FragCoord.y), 2) == int(alternative_scanline);
float color_luminosity = (
3.0 * color.r +
4.0 * color.g +
1.0 * color.b
) / 8.0;
// out colour
color = vec3(color_luminosity) * phosphor_colour;
if (is_scanline) {
color = color * scanline_darkening;
}
gl_FragColor = vec4(color, 1.0);
}

BIN
assets/loopey.wav Normal file

Binary file not shown.

View File

@@ -6,8 +6,8 @@
import net.torvald.point.Point2d
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.modulebasegame.gameactors.AVKey
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarum.itemproperties.Calculate
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.itemproperties.Material

View File

@@ -8,7 +8,8 @@ description=The base game
author=Terrarum
# Name of the entry script
entrypoint=basegame.groovy
# Entry script must inherit net.torvald.terrarum.ModuleEntryPoint
entrypoint=net.torvald.terrarum.modulebasegame.EntryPoint
# Release date in YYYY-MM-DD
releasedate=2017-07-14

View File

@@ -0,0 +1,367 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.lwjgl.audio;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import com.badlogic.gdx.Audio;
import com.badlogic.gdx.audio.AudioDevice;
import com.badlogic.gdx.audio.AudioRecorder;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.IntArray;
import com.badlogic.gdx.utils.IntMap;
import com.badlogic.gdx.utils.LongMap;
import com.badlogic.gdx.utils.ObjectMap;
import static org.lwjgl.openal.AL10.*;
/** @author Nathan Sweet */
public class OpenALAudio implements Audio {
private final int deviceBufferSize;
private final int deviceBufferCount;
private IntArray idleSources, allSources;
private LongMap<Integer> soundIdToSource;
private IntMap<Long> sourceToSoundId;
private long nextSoundId = 0;
private ObjectMap<String, Class<? extends OpenALSound>> extensionToSoundClass = new ObjectMap();
private ObjectMap<String, Class<? extends OpenALMusic>> extensionToMusicClass = new ObjectMap();
private OpenALSound[] recentSounds;
private int mostRecetSound = -1;
Array<OpenALMusic> music = new Array(false, 1, OpenALMusic.class);
boolean noDevice = false;
public OpenALAudio () {
this(16, 9, 512);
}
public OpenALAudio (int simultaneousSources, int deviceBufferCount, int deviceBufferSize) {
this.deviceBufferSize = deviceBufferSize;
this.deviceBufferCount = deviceBufferCount;
registerSound("ogg", Ogg.Sound.class);
registerMusic("ogg", Ogg.Music.class);
registerSound("wav", Wav.Sound.class);
registerMusic("wav", Wav.Music.class);
registerSound("mp3", Mp3.Sound.class);
registerMusic("mp3", Mp3.Music.class);
try {
AL.create();
} catch (LWJGLException ex) {
noDevice = true;
ex.printStackTrace();
return;
}
allSources = new IntArray(false, simultaneousSources);
for (int i = 0; i < simultaneousSources; i++) {
int sourceID = alGenSources();
if (alGetError() != AL_NO_ERROR) break;
allSources.add(sourceID);
}
idleSources = new IntArray(allSources);
soundIdToSource = new LongMap<Integer>();
sourceToSoundId = new IntMap<Long>();
FloatBuffer orientation = (FloatBuffer)BufferUtils.createFloatBuffer(6)
.put(new float[] {0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f}).flip();
alListener(AL_ORIENTATION, orientation);
FloatBuffer velocity = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_VELOCITY, velocity);
FloatBuffer position = (FloatBuffer)BufferUtils.createFloatBuffer(3).put(new float[] {0.0f, 0.0f, 0.0f}).flip();
alListener(AL_POSITION, position);
recentSounds = new OpenALSound[simultaneousSources];
}
public void registerSound (String extension, Class<? extends OpenALSound> soundClass) {
if (extension == null) throw new IllegalArgumentException("extension cannot be null.");
if (soundClass == null) throw new IllegalArgumentException("soundClass cannot be null.");
extensionToSoundClass.put(extension, soundClass);
}
public void registerMusic (String extension, Class<? extends OpenALMusic> musicClass) {
if (extension == null) throw new IllegalArgumentException("extension cannot be null.");
if (musicClass == null) throw new IllegalArgumentException("musicClass cannot be null.");
extensionToMusicClass.put(extension, musicClass);
}
public OpenALSound newSound (FileHandle file) {
if (file == null) throw new IllegalArgumentException("file cannot be null.");
Class<? extends OpenALSound> soundClass = extensionToSoundClass.get(file.extension().toLowerCase());
if (soundClass == null) throw new GdxRuntimeException("Unknown file extension for sound: " + file);
try {
return soundClass.getConstructor(new Class[] {OpenALAudio.class, FileHandle.class}).newInstance(this, file);
} catch (Exception ex) {
throw new GdxRuntimeException("Error creating sound " + soundClass.getName() + " for file: " + file, ex);
}
}
public OpenALMusic newMusic (FileHandle file) {
if (file == null) throw new IllegalArgumentException("file cannot be null.");
Class<? extends OpenALMusic> musicClass = extensionToMusicClass.get(file.extension().toLowerCase());
if (musicClass == null) throw new GdxRuntimeException("Unknown file extension for music: " + file);
try {
return musicClass.getConstructor(new Class[] {OpenALAudio.class, FileHandle.class}).newInstance(this, file);
} catch (Exception ex) {
throw new GdxRuntimeException("Error creating music " + musicClass.getName() + " for file: " + file, ex);
}
}
int obtainSource (boolean isMusic) {
if (noDevice) return 0;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceId = idleSources.get(i);
int state = alGetSourcei(sourceId, AL_SOURCE_STATE);
if (state != AL_PLAYING && state != AL_PAUSED) {
if (isMusic) {
idleSources.removeIndex(i);
} else {
if (sourceToSoundId.containsKey(sourceId)) {
long soundId = sourceToSoundId.get(sourceId);
sourceToSoundId.remove(sourceId);
soundIdToSource.remove(soundId);
}
long soundId = nextSoundId++;
sourceToSoundId.put(sourceId, soundId);
soundIdToSource.put(soundId, sourceId);
}
alSourceStop(sourceId);
alSourcei(sourceId, AL_BUFFER, 0);
AL10.alSourcef(sourceId, AL10.AL_GAIN, 1);
AL10.alSourcef(sourceId, AL10.AL_PITCH, 1);
AL10.alSource3f(sourceId, AL10.AL_POSITION, 0, 0, 1f);
return sourceId;
}
}
return -1;
}
void freeSource (int sourceID) {
if (noDevice) return;
alSourceStop(sourceID);
alSourcei(sourceID, AL_BUFFER, 0);
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
idleSources.add(sourceID);
}
void freeBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID) {
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
alSourceStop(sourceID);
alSourcei(sourceID, AL_BUFFER, 0);
}
}
}
void stopSourcesWithBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID) {
if (sourceToSoundId.containsKey(sourceID)) {
long soundId = sourceToSoundId.remove(sourceID);
soundIdToSource.remove(soundId);
}
alSourceStop(sourceID);
}
}
}
void pauseSourcesWithBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID)
alSourcePause(sourceID);
}
}
void resumeSourcesWithBuffer (int bufferID) {
if (noDevice) return;
for (int i = 0, n = idleSources.size; i < n; i++) {
int sourceID = idleSources.get(i);
if (alGetSourcei(sourceID, AL_BUFFER) == bufferID) {
if (alGetSourcei(sourceID, AL_SOURCE_STATE) == AL_PAUSED)
alSourcePlay(sourceID);
}
}
}
public void update () {
if (noDevice) return;
for (int i = 0; i < music.size; i++)
music.items[i].update();
}
public long getSoundId (int sourceId) {
if (!sourceToSoundId.containsKey(sourceId)) return -1;
return sourceToSoundId.get(sourceId);
}
public void stopSound (long soundId) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
alSourceStop(sourceId);
}
public void pauseSound (long soundId) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
alSourcePause(sourceId);
}
public void resumeSound (long soundId) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
if (alGetSourcei(sourceId, AL_SOURCE_STATE) == AL_PAUSED)
alSourcePlay(sourceId);
}
public void setSoundGain (long soundId, float volume) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSourcef(sourceId, AL10.AL_GAIN, volume);
}
public void setSoundLooping (long soundId, boolean looping) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
alSourcei(sourceId, AL10.AL_LOOPING, looping ? AL10.AL_TRUE : AL10.AL_FALSE);
}
public void setSoundPitch (long soundId, float pitch) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSourcef(sourceId, AL10.AL_PITCH, pitch);
}
public void setSoundPan (long soundId, float pan, float volume) {
if (!soundIdToSource.containsKey(soundId)) return;
int sourceId = soundIdToSource.get(soundId);
AL10.alSource3f(sourceId, AL10.AL_POSITION, MathUtils.cos((pan - 1) * MathUtils.PI / 2), 0,
MathUtils.sin((pan + 1) * MathUtils.PI / 2));
AL10.alSourcef(sourceId, AL10.AL_GAIN, volume);
}
public void dispose () {
if (noDevice) return;
for (int i = 0, n = allSources.size; i < n; i++) {
int sourceID = allSources.get(i);
int state = alGetSourcei(sourceID, AL_SOURCE_STATE);
if (state != AL_STOPPED) alSourceStop(sourceID);
alDeleteSources(sourceID);
}
sourceToSoundId.clear();
soundIdToSource.clear();
AL.destroy();
while (AL.isCreated()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
public AudioDevice newAudioDevice (int sampleRate, final boolean isMono) {
if (noDevice) return new AudioDevice() {
@Override
public void writeSamples (float[] samples, int offset, int numSamples) {
}
@Override
public void writeSamples (short[] samples, int offset, int numSamples) {
}
@Override
public void setVolume (float volume) {
}
@Override
public boolean isMono () {
return isMono;
}
@Override
public int getLatency () {
return 0;
}
@Override
public void dispose () {
}
};
return new OpenALAudioDevice(this, sampleRate, isMono, deviceBufferSize, deviceBufferCount);
}
public AudioRecorder newAudioRecorder (int samplingRate, boolean isMono) {
if (noDevice) return new AudioRecorder() {
@Override
public void read (short[] samples, int offset, int numSamples) {
}
@Override
public void dispose () {
}
};
return new JavaSoundAudioRecorder(samplingRate, isMono);
}
/** Retains a list of the most recently played sounds and stops the sound played least recently if necessary for a new sound to
* play */
protected void retain (OpenALSound sound, boolean stop) {
// Move the pointer ahead and wrap
mostRecetSound++;
mostRecetSound %= recentSounds.length;
if (stop) {
// Stop the least recent sound (the one we are about to bump off the buffer)
if (recentSounds[mostRecetSound] != null) recentSounds[mostRecetSound].stop();
}
recentSounds[mostRecetSound] = sound;
}
/** Removes the disposed sound from the least recently played list */
public void forget (OpenALSound sound) {
for (int i = 0; i < recentSounds.length; i++) {
if (recentSounds[i] == sound) recentSounds[i] = null;
}
}
}

View File

@@ -1,10 +1,8 @@
package net.torvald.aa
import net.torvald.point.Point2d
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.gameactors.sqr
import java.util.*
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarum.sqr
/**
* k-d Tree that uses binary heap instead of binary tree to improve data locality

View File

@@ -7,6 +7,34 @@ import com.badlogic.gdx.graphics.Color
* Created by minjaesong on 2017-01-12.
*/
object CIEXYZUtil {
/**
* 0..255 -> 0.0..1.0
*/
private val rgbLineariseLUT = Array<Float>(257, {
val step = minOf(it, 255) / 255f
if (step > 0.04045f)
((step + 0.055f) / 1.055f).powerOf(2.4f)
else step / 12.92f
})
/**
* 0..255 -> 0.0..1.0
*/
private val rgbUnLineariseLUT = Array<Float>(257, {
val step = minOf(it, 255) / 255f
if (step > 0.0031308f)
1.055f * step.powerOf(1f / 2.4f) - 0.055f
else
step * 12.92f
})
fun Color.brighterXYZ(scale: Float): Color {
val xyz = this.toXYZ()
xyz.X = xyz.X.times(1f + scale).clampOne()
@@ -37,8 +65,8 @@ object CIEXYZUtil {
fun Color.toXYZ(): CIEXYZ = RGB(this).toXYZ()
fun RGB.toXYZ(): CIEXYZ {
val newR = if (r > 0.04045f)
fun RGB.linearise(): RGB {
/*val newR = if (r > 0.04045f)
((r + 0.055f) / 1.055f).powerOf(2.4f)
else r / 12.92f
val newG = if (g > 0.04045f)
@@ -48,32 +76,78 @@ object CIEXYZUtil {
((b + 0.055f) / 1.055f).powerOf(2.4f)
else b / 12.92f
val x = 0.4124564f * newR + 0.3575761f * newG + 0.1804375f * newB
val y = 0.2126729f * newR + 0.7151522f * newG + 0.0721750f * newB
val z = 0.0193339f * newR + 0.1191920f * newG + 0.9503041f * newB
return RGB(newR, newG, newB, alpha)*/
val out = floatArrayOf(0f, 0f, 0f)
for (i in 0..2) {
val value = when (i) {
0 -> this.r
1 -> this.g
2 -> this.b
else -> throw Exception("Fuck you")
}
val step = value.clampOne() * 255f
val intStep = step.toInt()
out[i] = interpolateLinear(step - intStep, rgbLineariseLUT[intStep], rgbLineariseLUT[intStep + 1])
}
return RGB(out[0], out[1], out[2], alpha)
}
fun RGB.unLinearise(): RGB {
/*val newR = if (r > 0.0031308f)
1.055f * r.powerOf(1f / 2.4f) - 0.055f
else
r * 12.92f
val newG = if (g > 0.0031308f)
1.055f * g.powerOf(1f / 2.4f) - 0.055f
else
g * 12.92f
val newB = if (b > 0.0031308f)
1.055f * b.powerOf(1f / 2.4f) - 0.055f
else
b * 12.92f
return RGB(newR, newG, newB, alpha)*/
val out = floatArrayOf(0f, 0f, 0f)
for (i in 0..2) {
val value = when (i) {
0 -> this.r
1 -> this.g
2 -> this.b
else -> throw Exception("Fuck you")
}
val step = value.clampOne() * 255f
val intStep = step.toInt()
out[i] = interpolateLinear(step - intStep, rgbUnLineariseLUT[intStep], rgbUnLineariseLUT[intStep + 1])
}
return RGB(out[0], out[1], out[2], alpha)
}
fun RGB.toXYZ(): CIEXYZ {
val new = this.linearise()
val x = 0.4124564f * new.r + 0.3575761f * new.g + 0.1804375f * new.b
val y = 0.2126729f * new.r + 0.7151522f * new.g + 0.0721750f * new.b
val z = 0.0193339f * new.r + 0.1191920f * new.g + 0.9503041f * new.b
return CIEXYZ(x, y, z, alpha)
}
fun CIEXYZ.toRGB(): RGB {
var r = 3.2404542f * X - 1.5371385f * Y - 0.4985314f * Z
var g = -0.9692660f * X + 1.8760108f * Y + 0.0415560f * Z
var b = 0.0556434f * X - 0.2040259f * Y + 1.0572252f * Z
val r = 3.2404542f * X - 1.5371385f * Y - 0.4985314f * Z
val g = -0.9692660f * X + 1.8760108f * Y + 0.0415560f * Z
val b = 0.0556434f * X - 0.2040259f * Y + 1.0572252f * Z
if (r > 0.0031308f)
r = 1.055f * r.powerOf(1f / 2.4f) - 0.055f
else
r *= 12.92f
if (g > 0.0031308f)
g = 1.055f * g.powerOf(1f / 2.4f) - 0.055f
else
g *= 12.92f
if (b > 0.0031308f)
b = 1.055f * b.powerOf(1f / 2.4f) - 0.055f
else
b *= 12.92f
return RGB(r, g, b, alpha)
return RGB(r, g, b, alpha).unLinearise()
}
fun CIEXYZ.toColor(): Color {
@@ -94,8 +168,22 @@ object CIEXYZUtil {
private fun Float.powerOf(exp: Float) = FastMath.pow(this, exp)
private fun Float.clampOne() = if (this > 1f) 1f else if (this < 0f) 0f else this
private fun interpolateLinear(scale: Float, startValue: Float, endValue: Float): Float {
if (startValue == endValue) {
return startValue
}
if (scale <= 0f) {
return startValue
}
return if (scale >= 1f) {
endValue
}
else (1f - scale) * startValue + scale * endValue
}
}
/** Range: X, Y, Z: 0 - 1.0+ (One-based-plus) */
data class CIEXYZ(var X: Float = 0f, var Y: Float = 0f, var Z: Float = 0f, var alpha: Float = 1f) {
init {

View File

@@ -1,7 +1,7 @@
package net.torvald.point
import net.torvald.terrarum.gameactors.sqr
import net.torvald.terrarum.gameactors.sqrt
import net.torvald.terrarum.sqr
import net.torvald.terrarum.sqrt
import org.dyn4j.geometry.Vector2
/**

View File

@@ -1,9 +1,7 @@
package net.torvald.random
import com.jme3.math.FastMath
import net.torvald.terrarum.gameactors.floorInt
import net.torvald.terrarum.gameactors.round
import net.torvald.terrarum.gameactors.roundInt
import net.torvald.terrarum.floorInt
import net.torvald.terrarum.gameworld.fmod
import java.util.*

View File

@@ -7,7 +7,7 @@ package net.torvald.spriteanimation
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.jme3.math.FastMath
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack
class SpriteAnimation(val parentActor: ActorWithPhysics) {

View File

@@ -17,17 +17,20 @@ import java.util.Arrays;
import java.util.Random;
/**
* The framework's Application Loader
*
*
* Created by minjaesong on 2017-08-01.
*/
public class TerrarumAppLoader implements ApplicationListener {
public class AppLoader implements ApplicationListener {
private static TerrarumAppLoader INSTANCE = null;
private static AppLoader INSTANCE = null;
private TerrarumAppLoader() { }
private AppLoader() { }
public static TerrarumAppLoader getINSTANCE() {
public static AppLoader getINSTANCE() {
if (INSTANCE == null) {
INSTANCE = new TerrarumAppLoader();
INSTANCE = new AppLoader();
}
return INSTANCE;
}
@@ -100,7 +103,7 @@ public class TerrarumAppLoader implements ApplicationListener {
appConfig.foregroundFPS = 9999;
appConfig.title = GAME_NAME;
new LwjglApplication(new TerrarumAppLoader(), appConfig);
new LwjglApplication(new AppLoader(), appConfig);
}
@@ -198,7 +201,6 @@ public class TerrarumAppLoader implements ApplicationListener {
loadTimer += Gdx.graphics.getRawDeltaTime();
if (loadTimer >= showupTime) {
Terrarum.INSTANCE.setAppLoader(this);
Terrarum.INSTANCE.setScreenW(appConfig.width);
Terrarum.INSTANCE.setScreenH(appConfig.height);
setScreen(Terrarum.INSTANCE);
@@ -255,12 +257,16 @@ public class TerrarumAppLoader implements ApplicationListener {
}
public void setScreen(Screen screen) {
System.out.println("[AppLoader] Changing screen to " + screen.getClass().getCanonicalName());
if (this.screen != null) this.screen.hide();
this.screen = screen;
if (this.screen != null) {
this.screen.show();
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
System.out.println("[AppLoader] Screen transisiton complete: " + this.screen.getClass().getCanonicalName());
}
private void setCameraPosition(float newX, float newY) {

View File

@@ -10,8 +10,6 @@ import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Matrix4
import net.torvald.terrarum.gameactors.sqrt
import net.torvald.terrarumsansbitmap.gdx.GameFontBase
/**

View File

@@ -18,7 +18,7 @@ object DefaultConfig {
jsonObject.addProperty("imtooyoungtodie", false) // no perma-death
jsonObject.addProperty("language", TerrarumAppLoader.getSysLang())
jsonObject.addProperty("language", AppLoader.getSysLang())
jsonObject.addProperty("notificationshowuptime", 6500)
jsonObject.addProperty("multithread", true) // experimental!

View File

@@ -10,8 +10,8 @@ import net.torvald.terrarum.langpack.Lang
object ErrorDisp : Screen {
private val logoTex = TerrarumAppLoader.logo
private val font = TerrarumAppLoader.fontGame
private val logoTex = AppLoader.logo
private val font = AppLoader.fontGame
var title = Lang["ERROR_GENERIC_TEXT"]
@@ -26,7 +26,7 @@ object ErrorDisp : Screen {
private val titleTextLeftMargin = 8
private val titleText = "${TerrarumAppLoader.GAME_NAME} ${TerrarumAppLoader.getVERSION_STRING()}"
private val titleText = "${AppLoader.GAME_NAME} ${AppLoader.getVERSION_STRING()}"
override fun show() {

View File

@@ -8,16 +8,17 @@ import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.jme3.math.FastMath
import net.torvald.random.HQRNG
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.ai.ActorAI
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.*
import net.torvald.terrarum.serialise.ReadLayerData
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.ui.UITitleRemoConRoot
import net.torvald.terrarum.modulebasegame.ui.UITitleRemoConRoot
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.worlddrawer.*
import java.io.FileInputStream
@@ -52,7 +53,9 @@ class FuckingWorldRenderer(val batch: SpriteBatch) : Screen {
private var firstTime = true
override fun update(actor: HumanoidNPC, delta: Float) {
override fun update(actor: Actor, delta: Float) {
val actor = actor as HumanoidNPC
// fuck
val avSpeed = 1.0 // FIXME camera goes faster when FPS is high
actor.actorValue[AVKey.SPEED] = avSpeed
@@ -336,7 +339,7 @@ class FuckingWorldRenderer(val batch: SpriteBatch) : Screen {
batch.color = Color.LIGHT_GRAY
val COPYTING = arrayOf(
TerrarumAppLoader.COPYRIGHT_DATE_NAME,
AppLoader.COPYRIGHT_DATE_NAME,
Lang["COPYRIGHT_GNU_GPL_3"]
)

View File

@@ -8,10 +8,6 @@ import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.jme3.math.FastMath
import net.torvald.terrarum.gameactors.ceilInt
import net.torvald.terrarum.gameactors.floor
import net.torvald.terrarum.gameactors.floorInt
import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarumsansbitmap.gdx.GameFontBase
/**
@@ -64,7 +60,7 @@ object GlslTilingTest : ApplicationAdapter() {
//ErrorDisp.title = "Error in shader ${shader.vertexShaderSource}"
//ErrorDisp.text = shader.log.split('\n')
//TerrarumAppLoader.getINSTANCE().setScreen(ErrorDisp)
//AppLoader.getINSTANCE().setScreen(ErrorDisp)
System.exit(1)
}
@@ -172,4 +168,3 @@ object GlslTilingTest : ApplicationAdapter() {
}
}
private fun Float.ceil(): Float = FastMath.ceil(this).toFloat()

View File

@@ -0,0 +1,13 @@
package net.torvald.terrarum
import com.google.gson.JsonObject
/**
* Created by minjaesong on 2018-05-18.
*/
interface GsonSerialisable {
fun read(gson: JsonObject)
fun write(targetGson: JsonObject)
}

View File

@@ -1,9 +1,11 @@
package net.torvald.terrarum
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonValue
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import net.torvald.terrarum.gameactors.Actor
import java.util.*
import java.util.function.Consumer
import kotlin.collections.HashMap
typealias ItemValue = KVHashMap
@@ -12,7 +14,7 @@ typealias GameConfig = KVHashMap
/**
* Created by minjaesong on 2015-12-30.
*/
open class KVHashMap {
open class KVHashMap : GsonSerialisable {
constructor() {
hashMap = HashMap<String, Any>()
@@ -114,4 +116,15 @@ open class KVHashMap {
return KVHashMap(cloneOfMap)
}
override fun read(gson: JsonObject) {
}
override fun write(targetGson: JsonObject) {
hashMap.forEach { t, u ->
if (u is JsonPrimitive)
targetGson.add(t, u)
else
targetGson.add(t, Gson().toJsonTree(u))
}
}
}

View File

@@ -6,8 +6,8 @@ import com.badlogic.gdx.graphics.*
import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.jme3.math.FastMath
import net.torvald.dataclass.HistoryArray
import net.torvald.terrarum.gameactors.floor
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2017-07-13.

View File

@@ -8,6 +8,7 @@ import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.itemproperties.ItemID
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.EntryPoint
import net.torvald.terrarum.utils.JsonFetcher
import org.apache.commons.csv.CSVFormat
import org.apache.commons.csv.CSVParser
@@ -34,9 +35,6 @@ import javax.script.Invocable
*/
object ModMgr {
val groovyEngine = ScriptEngineManager().getEngineByExtension("groovy")!!
val groovyInvocable = groovyEngine as Invocable
val metaFilename = "metadata.properties"
val defaultConfigFilename = "default.json"
@@ -104,11 +102,11 @@ object ModMgr {
// run entry script in entry point
if (entryPoint.isNotBlank()) {
val extension = entryPoint.split('.').last()
val engine = ScriptEngineManager().getEngineByExtension(extension)!!
val invocable = engine as Invocable
engine.eval(FileReader(getFile(moduleName, entryPoint)))
invocable.invokeFunction("invoke", moduleName)
val newClass = Class.forName(entryPoint)
val newClassConstructor = newClass.getConstructor(/* no args defined */)
val newClassInstance = newClassConstructor.newInstance(/* no args defined */)
(newClassInstance as ModuleEntryPoint).invoke()
}

View File

@@ -0,0 +1,8 @@
package net.torvald.terrarum
/**
* Created by minjaesong on 2018-06-21.
*/
abstract class ModuleEntryPoint {
abstract fun invoke()
}

View File

@@ -11,14 +11,11 @@ import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.utils.GdxRuntimeException
import com.google.gson.JsonArray
import com.google.gson.JsonPrimitive
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.gameactors.floorInt
import com.jme3.math.FastMath
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.imagefont.TinyAlphNum
import net.torvald.terrarum.imagefont.Watch7SegMain
import net.torvald.terrarum.imagefont.WatchDotAlph
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.ui.ItemSlotImageBuilder
import net.torvald.terrarum.ui.MessageWindow
import net.torvald.terrarum.ui.ConsoleWindow
import net.torvald.terrarum.utils.JsonFetcher
import net.torvald.terrarum.utils.JsonWriter
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
@@ -29,6 +26,14 @@ import org.lwjgl.BufferUtils
import org.lwjgl.input.Controllers
import java.io.File
import java.io.IOException
import java.util.ArrayList
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JOptionPane
typealias RGBA8888 = Int
/**
@@ -36,38 +41,8 @@ import java.io.IOException
*
* LibGDX Version Created by minjaesong on 2017-06-15.
*/
/*fun main(args: Array<String>) {
Terrarum // invoke
val config = LwjglApplicationConfiguration()
config.vSyncEnabled = Terrarum.USE_VSYNC
config.resizable = true
config.width = 1072
config.height = 742
config.backgroundFPS = RENDER_FPS
config.foregroundFPS = RENDER_FPS
config.title = GAME_NAME
Terrarum.screenW = config.width
Terrarum.screenH = config.height
println("[TerrarumKt] usevsync = ${Terrarum.USE_VSYNC}")
// the game must run on same speed regardless of the display FPS;
// "Terrarum.TARGET_INTERNAL_FPS" denotes "execute as if FPS was set to this value"
LwjglApplication(Terrarum, config)
}*/
typealias RGBA8888 = Int
object Terrarum : Screen {
lateinit var appLoader: TerrarumAppLoader
var screenW = 0
var screenH = 0
@@ -120,7 +95,7 @@ object Terrarum : Screen {
var previousScreen: Screen? = null // to be used with temporary states like StateMonitorCheck
var ingame: Ingame? = null
var ingame: IngameInstance? = null
private val gameConfig = GameConfig()
val OSName = System.getProperty("os.name")
@@ -145,7 +120,7 @@ object Terrarum : Screen {
val fontGame: GameFontBase = TerrarumAppLoader.fontGame
val fontGame: GameFontBase = AppLoader.fontGame
lateinit var fontSmallNumbers: TinyAlphNum
var joypadLabelStart: Char = 0xE000.toChar() // lateinit
@@ -202,7 +177,7 @@ object Terrarum : Screen {
private lateinit var configDir: String
const val NAME = TerrarumAppLoader.GAME_NAME
const val NAME = AppLoader.GAME_NAME
val systemArch = System.getProperty("os.arch")
@@ -234,7 +209,7 @@ object Terrarum : Screen {
init {
println("$NAME version ${TerrarumAppLoader.getVERSION_STRING()}")
println("$NAME version ${AppLoader.getVERSION_STRING()}")
getDefaultDirectory()
@@ -418,16 +393,18 @@ object Terrarum : Screen {
TerrarumAppLoader.GAME_LOCALE = getConfigString("language")
println("[Terrarum] locale = ${TerrarumAppLoader.GAME_LOCALE}")
AppLoader.GAME_LOCALE = getConfigString("language")
println("[Terrarum] locale = ${AppLoader.GAME_LOCALE}")
ModMgr // invoke Module Manager, which will also invoke BlockCodex
ItemCodex // invoke Item Codex
ModMgr // invoke Module Manager
println("[Terrarum] all modules loaded successfully")
// jump right into the ingame
/*ingame = Ingame(batch)
@@ -439,18 +416,18 @@ object Terrarum : Screen {
// title screen
appLoader.setScreen(TitleScreen(batch))
AppLoader.getINSTANCE().setScreen(TitleScreen(batch))
//appLoader.setScreen(FuckingWorldRenderer(batch))
}
internal fun setScreen(screen: Screen) {
appLoader.setScreen(screen)
AppLoader.getINSTANCE().setScreen(screen)
}
override fun render(delta: Float) {
//appLoader.screen.render(deltaTime)
AppLoader.getINSTANCE().screen.render(deltaTime)
//GLOBAL_RENDER_TIMER += 1
// moved to TerrarumAppLoader; global event must be place at the apploader to prevent ACCIDENTAL forgot-to-update type of bug.
// moved to AppLoader; global event must be place at the apploader to prevent ACCIDENTAL forgot-to-update type of bug.
}
override fun pause() {
@@ -467,13 +444,6 @@ object Terrarum : Screen {
fontSmallNumbers.dispose()
ItemSlotImageBuilder.dispose()
WatchDotAlph.dispose()
Watch7SegMain.dispose()
WatchDotAlph.dispose()
MessageWindow.SEGMENT_BLACK.dispose()
MessageWindow.SEGMENT_WHITE.dispose()
//dispose any other resources used in this level
@@ -715,6 +685,159 @@ object Terrarum : Screen {
get() = Gdx.input.y
}
open class IngameInstance(val batch: SpriteBatch) : Screen {
var screenZoom = 1.0f
val ZOOM_MAXIMUM = 4.0f
val ZOOM_MINIMUM = 0.5f
lateinit var consoleHandler: ConsoleWindow
val ACTORCONTAINER_INITIAL_SIZE = 64
val actorContainer = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
val actorContainerInactive = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
override fun hide() {
}
override fun show() {
}
override fun render(delta: Float) {
}
override fun pause() {
}
override fun resume() {
}
override fun resize(width: Int, height: Int) {
}
override fun dispose() {
}
fun getActorByID(ID: Int): Actor {
if (actorContainer.size == 0 && actorContainerInactive.size == 0)
throw IllegalArgumentException("Actor with ID $ID does not exist.")
var index = actorContainer.binarySearch(ID)
if (index < 0) {
index = actorContainerInactive.binarySearch(ID)
if (index < 0) {
JOptionPane.showMessageDialog(
null,
"Actor with ID $ID does not exist.",
null, JOptionPane.ERROR_MESSAGE
)
throw IllegalArgumentException("Actor with ID $ID does not exist.")
}
else
return actorContainerInactive[index]
}
else
return actorContainer[index]
}
fun ArrayList<*>.binarySearch(actor: Actor) = this.binarySearch(actor.referenceID!!)
fun ArrayList<*>.binarySearch(ID: Int): Int {
// code from collections/Collections.kt
var low = 0
var high = this.size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)!!
if (ID > midVal.hashCode())
low = mid + 1
else if (ID < midVal.hashCode())
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
open fun removeActor(ID: Int) = removeActor(getActorByID(ID))
/**
* get index of the actor and delete by the index.
* we can do this as the list is guaranteed to be sorted
* and only contains unique values.
*
* Any values behind the index will be automatically pushed to front.
* This is how remove function of [java.util.ArrayList] is defined.
*/
open fun removeActor(actor: Actor) {
val indexToDelete = actorContainer.binarySearch(actor.referenceID!!)
if (indexToDelete >= 0) {
actorContainer.removeAt(indexToDelete)
}
}
open /**
* Check for duplicates, append actor and sort the list
*/
fun addNewActor(actor: Actor) {
if (theGameHasActor(actor.referenceID!!)) {
throw Error("The actor $actor already exists in the game")
}
else {
actorContainer.add(actor)
insertionSortLastElem(actorContainer) // we can do this as we are only adding single actor
}
}
fun isActive(ID: Int): Boolean =
if (actorContainer.size == 0)
false
else
actorContainer.binarySearch(ID) >= 0
fun isInactive(ID: Int): Boolean =
if (actorContainerInactive.size == 0)
false
else
actorContainerInactive.binarySearch(ID) >= 0
/**
* actorContainer extensions
*/
fun theGameHasActor(actor: Actor?) = if (actor == null) false else theGameHasActor(actor.referenceID!!)
fun theGameHasActor(ID: Int): Boolean =
isActive(ID) || isInactive(ID)
fun insertionSortLastElem(arr: ArrayList<Actor>) {
lock(ReentrantLock()) {
var j = arr.lastIndex - 1
val x = arr.last()
while (j >= 0 && arr[j] > x) {
arr[j + 1] = arr[j]
j -= 1
}
arr[j + 1] = x
}
}
inline fun lock(lock: Lock, body: () -> Unit) {
lock.lock()
try {
body()
}
finally {
lock.unlock()
}
}
}
inline fun SpriteBatch.inUse(action: (SpriteBatch) -> Unit) {
this.begin()
action(this)
@@ -852,3 +975,56 @@ val ccX = GameFontBase.toColorCode(0x853F)
val ccK = GameFontBase.toColorCode(0x888F)
typealias Second = Float
inline fun Int.sqr(): Int = this * this
inline fun Double.floorInt() = Math.floor(this).toInt()
inline fun Float.floorInt() = FastMath.floor(this)
inline fun Float.floor() = FastMath.floor(this).toFloat()
inline fun Double.ceilInt() = Math.ceil(this).toInt()
inline fun Float.ceil(): Float = FastMath.ceil(this).toFloat()
inline fun Float.ceilInt() = FastMath.ceil(this)
inline fun Double.round() = Math.round(this).toDouble()
inline fun Double.floor() = Math.floor(this)
inline fun Double.ceil() = this.floor() + 1.0
inline fun Double.roundInt(): Int = Math.round(this).toInt()
inline fun Float.roundInt(): Int = Math.round(this)
inline fun Double.abs() = Math.abs(this)
inline fun Double.sqr() = this * this
inline fun Double.sqrt() = Math.sqrt(this)
inline fun Float.sqrt() = FastMath.sqrt(this)
inline fun Int.abs() = if (this < 0) -this else this
fun Double.bipolarClamp(limit: Double) =
if (this > 0 && this > limit) limit
else if (this < 0 && this < -limit) -limit
else this
fun absMax(left: Double, right: Double): Double {
if (left > 0 && right > 0)
if (left > right) return left
else return right
else if (left < 0 && right < 0)
if (left < right) return left
else return right
else {
val absL = left.abs()
val absR = right.abs()
if (absL > absR) return left
else return right
}
}
fun Double.magnSqr() = if (this >= 0.0) this.sqr() else -this.sqr()
fun Double.sign() = if (this > 0.0) 1.0 else if (this < 0.0) -1.0 else 0.0
fun interpolateLinear(scale: Double, startValue: Double, endValue: Double): Double {
if (startValue == endValue) {
return startValue
}
if (scale <= 0.0) {
return startValue
}
if (scale >= 1.0) {
return endValue
}
return (1.0 - scale) * startValue + scale * endValue
}

View File

@@ -10,14 +10,16 @@ import com.badlogic.gdx.graphics.glutils.FrameBuffer
import com.jme3.math.FastMath
import net.torvald.random.HQRNG
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.ai.ActorAI
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.*
import net.torvald.terrarum.serialise.ReadLayerData
import net.torvald.terrarum.ui.UICanvas
import net.torvald.terrarum.ui.UITitleRemoConRoot
import net.torvald.terrarum.modulebasegame.ui.UITitleRemoConRoot
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.worlddrawer.*
import java.io.FileInputStream
@@ -52,7 +54,9 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
private var firstTime = true
override fun update(actor: HumanoidNPC, delta: Float) {
override fun update(actor: Actor, delta: Float) {
val actor = actor as HumanoidNPC
// fuck
val avSpeed = 1.0 // FIXME camera goes faster when FPS is high
actor.actorValue[AVKey.SPEED] = avSpeed
@@ -116,6 +120,9 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
private val TILE_SIZEF = TILE_SIZE.toFloat()
private fun loadThingsWhileIntroIsVisible() {
println("[TitleScreen] Intro pre-load")
demoWorld = ReadLayerData(FileInputStream(ModMgr.getFile("basegame", "demoworld")))
@@ -131,7 +138,7 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
})
cameraPlayer = object : HumanoidNPC(demoWorld, cameraAI, GameDate(1, 1), usePhysics = false) {
cameraPlayer = object : HumanoidNPC(demoWorld, cameraAI, GameDate(1, 1), usePhysics = false, forceAssignRefID = Player.PLAYER_REF_ID) {
init {
setHitboxDimension(2, 2, 0, 0)
hitbox.setPosition(
@@ -165,6 +172,8 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
}
override fun show() {
println("[TitleScreen] atrniartsientsarinoetsar")
initViewPort(Terrarum.WIDTH, Terrarum.HEIGHT)
logo = TextureRegion(Texture(Gdx.files.internal("assets/graphics/logo_placeholder.tga")))
@@ -340,7 +349,7 @@ class TitleScreen(val batch: SpriteBatch) : Screen {
batch.color = Color.LIGHT_GRAY
val COPYTING = arrayOf(
TerrarumAppLoader.COPYRIGHT_DATE_NAME,
AppLoader.COPYRIGHT_DATE_NAME,
Lang["COPYRIGHT_GNU_GPL_3"]
)

View File

@@ -5,9 +5,7 @@ import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.torvald.terrarum.gameactors.Second
import net.torvald.terrarum.gameactors.floorInt
import net.torvald.terrarum.gameactors.roundInt
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull
import net.torvald.terrarum.ui.*
/**

View File

@@ -7,6 +7,9 @@ import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import net.torvald.colourutil.CIELabUtil.darkerLab
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryCellBase
import net.torvald.terrarum.ui.*
/***
@@ -134,7 +137,7 @@ class UIItemInventoryElem(
override fun keyDown(keycode: Int): Boolean {
if (item != null && Terrarum.ingame != null && keycode in Input.Keys.NUM_1..Input.Keys.NUM_0) {
val inventory = Terrarum.ingame!!.player.inventory
val inventory = (Terrarum.ingame!! as Ingame).player.inventory
val slot = if (keycode == Input.Keys.NUM_0) 9 else keycode - Input.Keys.NUM_1
val currentSlotItem = inventory?.getQuickBar(slot)
@@ -164,7 +167,7 @@ class UIItemInventoryElem(
// equip da shit
val itemEquipSlot = item!!.equipPosition
val player = Terrarum.ingame!!.player
val player = (Terrarum.ingame!! as Ingame).player
if (item != player.inventory.itemEquipped.get(itemEquipSlot)) { // if this item is unequipped, equip it
player.equipItem(item!!)

View File

@@ -6,6 +6,9 @@ import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull
import net.torvald.terrarum.modulebasegame.ui.UIItemInventoryCellBase
import net.torvald.terrarum.ui.*
/**
@@ -122,7 +125,7 @@ class UIItemInventoryElemSimple(
println("keydown elemgrid")
val inventory = Terrarum.ingame!!.player.inventory
val inventory = (Terrarum.ingame!! as Ingame).player.inventory
val slot = if (keycode == Input.Keys.NUM_0) 9 else keycode - Input.Keys.NUM_1
val currentSlotItem = inventory.getQuickBar(slot)
@@ -154,7 +157,7 @@ class UIItemInventoryElemSimple(
// equip da shit
val itemEquipSlot = item!!.equipPosition
val player = Terrarum.ingame!!.player
val player = (Terrarum.ingame!! as Ingame).player
if (item != player.inventory.itemEquipped.get(itemEquipSlot)) { // if this item is unequipped, equip it
player.equipItem(item!!)

View File

@@ -6,19 +6,22 @@ package net.torvald.terrarum.audio
*
* Channels and their mapping:
*
* Notation: (front/side/rear.subwoofer/top-front)
* Notation: (front/rear.subwoofer/top-front)
* Plugs: G-Front (green), K-Rear (black), Y-Centre/Subwoofer (yellow), E-Side (grey)
* e.g. E-RC,NULL means GREY jack outputs REAR-CENTRE to its left and nothing to its right channel.
*
* = Headphones: Binaural
* = Stereo ---------- (2/0/0.0/0): G-FL,FR
* = Quadraphonic ---- (2/0/2.0/0): G-FL,FR; K-RL,RR
* = 4.0 ------------- (3/0/1.0/0): G-FL,FR; Y-FC,RC
* = 5.1 ------------- (3/0/2.1/0): G-FL,FR; Y-FC,SW; K-RL,RR
* = 6.1 ------------- (3/0/3.1/0): G-FL,FR; Y-FC,SW; K-RL,RR, E-RC,RC
* = 7.1 ------------- (3/2/2.1/0): G-FL,FR; Y-FC,SW; K-RL,RR, E-SL,SR
* = Dolby Atmos 5.1.2 (3/0/2.1/2): G-FL,FR; Y-FC,SW; K-RL,RR, E-TL,TR
* = Stereo ---------- (2/0.0/0): G-FL,FR
* = Quadraphonic ---- (2/2.0/0): G-FL,FR; K-RL,RR
* = 4.0 ------------- (3/1.0/0): G-FL,FR; Y-FC,RC
* = 5.1 ------------- (3/2.1/0): G-FL,FR; Y-FC,SW; K-RL,RR
* = 6.1 ------------- (3/3.1/0): G-FL,FR; Y-FC,SW; K-RL,RR, E-RC,RC
* = 7.1 ------------- (3/4.1/0): G-FL,FR; Y-FC,SW; K-RL,RR, E-SL,SR
* = Dolby Atmos*5.1.2 (3/2.1/2): G-FL,FR; Y-FC,SW; K-RL,RR, E-TL,TR
*
* = Extra options:
* = No centre speaker (5.1 and above)
* = No subwoofer (5.1 and above)
*
* Channel uses:
*
@@ -31,10 +34,115 @@ package net.torvald.terrarum.audio
* * If both side and rear speakers are not there, play weather/ambient to the stereo speakers but NOT TO THE CENTRE
* * For non-existent speakers, use channel phantoming
*
* Note: 5.1.2 does NOT output Dolby-compatible signals.
* Note: 5.1.2 does NOT output Dolby-compatible signals. It's just a customised 8 channel setup.
*
* @see spatialAudioMixMat.xlsx
*/
object SpatialAudioMixer {
const val centreQuotient = 0.7071f
const val PANNING_THREE = 0.708f
const val PANNING_FOUR_POINT_FIVE = 0.596f
const val PANNING_SIX = 0.5f
fun getPanning(coefficient: Float, panningLaw: Float = PANNING_FOUR_POINT_FIVE): Float {
val k = panningLaw.toDouble()
val a = 2.0 - 2.0 * k
val b = 4.0 * k - 1.0
return (coefficient*a*a + coefficient*b).toFloat()
}
const val PRESET_QUADRAPHONIC = """
FL=1,0,0,0,0,0,0,0
FC=0.5,0.5,0,0,0,0,0,0
FR=0,1,0,0,0,0,0,0
RL=0,0,0,0,0.75,0.25,0,0
RR=0,0,0,0,0.25,0.75,0,0
SL=0.25,0,0,0,0.75,0,0,0
RC=0,0,0,0,0.5,0.5,0,0
SR=0,0.25,0,0,0,0.75,0,0
AMB=0.25,0.25,0,0,0.25,0.25,0,0
LFE=0,0,0,0,0.5,0.5,0,0
"""
const val PRESET_FIVE_POINT_ONE = """
FL=1,0,0,0,0,0,0,0
FC=0,0,1,0,0,0,0,0
FR=0,1,0,0,0,0,0,0
RL=0,0,0,0,0.75,0.25,0,0
RR=0,0,0,0,0.25,0.75,0,0
SL=0.25,0,0,0,0.75,0,0,0
RC=0,0,0,0,0.5,0.5,0,0
SR=0,0.25,0,0,0,0.75,0,0
AMB=0.25,0.25,0,0,0.25,0.25,0,0
LFE=0,0,0,1,0,0,0,0
"""
const val PRESET_SEVEN_POINT_ONE = """
FL=1,0,0,0,0,0,0,0
FC=0,0,1,0,0,0,0,0
FR=0,1,0,0,0,0,0,0
SL=0,0,0,0,0,0,1,0
SR=0,0,0,0,0,0,0,1
RL=0,0,0,0,1,0,0,0
RC=0,0,0,0,0.5,0.5,0,0
RR=0,0,0,0,0,1,0,0
AMB=0.125,0.125,0,0,0.125,0.125,0.25,0.25
LFE=0,0,0,1,0,0,0,0
"""
const val PRESET_FIVE_POINT_ONE_POINT_TWO = """
FL=1,0,0,0,0,0,0,0
FC=0,0,1,0,0,0,0,0
FR=0,1,0,0,0,0,0,0
RL=0,0,0,0,0.75,0.25,0,0
RR=0,0,0,0,0.25,0.75,0,0
SL=0.25,0,0,0,0.75,0,0,0
RC=0,0,0,0,0.5,0.5,0,0
RR=0,0.25,0,0,0,0.75,0,0
AMB=0,0,0,0,0.125,0.125,0.375,0.375
LFE=0,0,0,1,0,0,0,0
"""
const val PRESET_FOUR_POINT_ONE = """
FL=0.75,0.25,0,0,0,0,0,0
FC=0,0,1,0,0,0,0,0
FR=0.25,0.75,0,0,0,0,0,0
SL=1,0,0,0,0,0,0,0
SR=0,1,0,0,0,0,0,0
RL=0.5,0,0,0,0.5,0,0,0
RC=0,0,0,0,1,0,0,0
RR=0,0.5,0,0,0.5,0,0,0
AMB=0.25,0.25,0,0,0.5,0,0,0
LFE=0,0,0,1,0,0,0,0
"""
const val PRESET_SIX_POINT_ONE = """
FL=1,0,0,0,0,0,0,0
FC=0,0,1,0,0,0,0,0
FR=0,1,0,0,0,0,0,0
RL=0,0,0,0,0.75,0.25,0,0
RR=0,0,0,0,0.25,0.75,0,0
SL=0.25,0,0,0,0.75,0,0,0
RC=0,0,0,0,0,0,1,0
SR=0,0.25,0,0,0,0.75,0,0
AMB=0.25,0.25,0,0,0.25,0.25,0,0
LFE=0,0,0,1,0,0,0,0
"""
const val PRESET_STEREO = """
FL=0.75,0.25,0,0,0,0,0,0
FC=0.5,0.5,0,0,0,0,0,0
FR=0.25,0.75,0,0,0,0,0,0
SL=1,0,0,0,0,0,0,0
SR=0,1,0,0,0,0,0,0
RL=1,0,0,0,0,0,0,0
RC=0.5,0.5,0,0,0,0,0,0
RR=0,1,0,0,0,0,0,0
AMB=0.5,0.5,0,0,0,0,0,0
LFE=0.5,0.5,0,0,0,0,0,0
"""
}

View File

@@ -0,0 +1,174 @@
package net.torvald.terrarum.audio.surroundpanner
import com.badlogic.gdx.Game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.files.FileHandle
import java.awt.BorderLayout
import javax.swing.*
/**
* Created by minjaesong on 2018-05-18.
*/
class SurroundPannerTest : JFrame() {
val mixerPanel = JPanel(BorderLayout()) // LR slider
val mixerPanSlider = JSlider(JSlider.HORIZONTAL, -32768, 32767, 0)
init {
val sliderPanel = JPanel(); sliderPanel.add(mixerPanSlider)
mixerPanel.add(sliderPanel, BorderLayout.CENTER)
this.add(mixerPanel, BorderLayout.CENTER)
this.defaultCloseOperation = EXIT_ON_CLOSE
this.isVisible = true
this.setSize(400, 600)
}
}
class AudioPlayerSlave : Game() {
lateinit var audioSample: FileHandle
lateinit var gdxSound: Sound
var soundID = 0L
lateinit var surroundPanner: SurroundPannerTest
override fun create() {
audioSample = Gdx.files.internal("assets/loopey.wav")
gdxSound = Gdx.audio.newSound(audioSample)
surroundPanner = SurroundPannerTest()
soundID = gdxSound.loop()
}
override fun render() {
gdxSound.setPan(soundID, surroundPanner.mixerPanSlider.value.toFloat() / 32768f, 0.5f)
}
override fun dispose() {
super.dispose()
gdxSound.dispose()
}
}
fun main(args: Array<String>) {
val appConfig = LwjglApplicationConfiguration()
appConfig.vSyncEnabled = false
appConfig.resizable = true
appConfig.width = 256
appConfig.height = 256
appConfig.backgroundFPS = 20
appConfig.foregroundFPS = 20
LwjglApplication(AudioPlayerSlave(), appConfig)
}
/*
package net.torvald.terrarum.audio.surroundpanner
import com.badlogic.gdx.Game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.files.FileHandle
import net.torvald.terrarum.audio.SpatialAudioMixer
import java.awt.BorderLayout
import java.io.StringReader
import java.util.*
import javax.swing.*
/**
* Created by minjaesong on 2018-05-18.
*/
class SurroundPannerTest(val panningMatrix: String) : JFrame() {
val panningSettings = Properties()
val mixerPanel = JPanel(BorderLayout()) // LR slider, options (pan-rear threshold: Double, panning law: Double)
val matricesPanel = JPanel(BorderLayout()) // show and edit panning matrix
val mixerPanSlider = JSlider(JSlider.HORIZONTAL, -32768, 32767, 0)
val mixerPanRearSelector = JSpinner(SpinnerNumberModel(6667, 0, 10000, 1))
val mixerPanLawSelector = JSpinner(SpinnerListModel(arrayOf(0.0, -3.0, -4.5, -6.0)))
init {
val sliderPanel = JPanel(); sliderPanel.add(mixerPanSlider)
sliderPanel.isVisible = true
val panRearPanel = JPanel(); panRearPanel.add(JLabel("Pan-rear threshold")); panRearPanel.add(mixerPanRearSelector)
panRearPanel.isVisible = true
val panLawPanel = JPanel(); panLawPanel.add(JLabel("Panning law")); panLawPanel.add(mixerPanLawSelector)
panLawPanel.isVisible = true
val optionsPanel = JPanel(); optionsPanel.add(panRearPanel); optionsPanel.add(panLawPanel)
optionsPanel.isVisible = true
mixerPanel.add(sliderPanel, BorderLayout.CENTER)
mixerPanel.add(optionsPanel, BorderLayout.SOUTH)
panningSettings.load(StringReader(panningMatrix))
this.add(mixerPanel, BorderLayout.CENTER)
this.add(matricesPanel, BorderLayout.SOUTH)
this.defaultCloseOperation = EXIT_ON_CLOSE
this.isVisible = true
this.setSize(400, 600)
}
}
class AudioPlayerSlave : Game() {
lateinit var audioSample: FileHandle
lateinit var gdxSound: Sound
var soundID = 0L
lateinit var surroundPanner: SurroundPannerTest
override fun create() {
audioSample = Gdx.files.internal("assets/loopey.wav")
gdxSound = Gdx.audio.newSound(audioSample)
surroundPanner = SurroundPannerTest(SpatialAudioMixer.PRESET_QUADRAPHONIC)
soundID = gdxSound.loop()
}
override fun render() {
gdxSound.setPan(soundID, surroundPanner.mixerPanSlider.value.toFloat() / 32768f, 1f)
}
override fun dispose() {
super.dispose()
gdxSound.dispose()
}
}
fun main(args: Array<String>) {
val appConfig = LwjglApplicationConfiguration()
appConfig.vSyncEnabled = false
appConfig.resizable = true
appConfig.width = 256
appConfig.height = 256
appConfig.backgroundFPS = 20
appConfig.foregroundFPS = 20
LwjglApplication(AudioPlayerSlave(), appConfig)
}
*/

View File

@@ -5,8 +5,9 @@ import com.badlogic.gdx.graphics.Color
import com.jme3.math.FastMath
import net.torvald.random.HQRNG
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.Second
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarum.Second
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameworld.WorldTime
import net.torvald.terrarum.worlddrawer.LightmapRenderer
import net.torvald.terrarum.weather.WeatherMixer
@@ -94,7 +95,7 @@ object BlockPropUtil {
fun getDynamicLumFunc(baseLum: Color, type: Int): Color {
return when (type) {
1 -> getTorchFlicker(baseLum)
2 -> Terrarum.ingame!!.world.globalLight.cpy().mul(LightmapRenderer.DIV_FLOAT) // current global light
2 -> (Terrarum.ingame!! as Ingame).world.globalLight.cpy().mul(LightmapRenderer.DIV_FLOAT) // current global light
3 -> WeatherMixer.getGlobalLightOfTime(WorldTime.DAY_LENGTH / 2).cpy().mul(LightmapRenderer.DIV_FLOAT) // daylight at noon
4 -> getSlowBreath(baseLum)
5 -> getPulsate(baseLum)

View File

@@ -6,6 +6,7 @@ import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import net.torvald.terrarum.Terrarum
import com.jme3.math.FastMath
import net.torvald.terrarum.modulebasegame.Ingame
import java.util.Arrays
@@ -26,8 +27,8 @@ object BlockStats {
// Get stats on no-zoomed screen area. In other words, will behave as if screen zoom were 1.0
// no matter how the screen is zoomed.
val map = Terrarum.ingame!!.world
val player = Terrarum.ingame!!.player
val map = (Terrarum.ingame!! as Ingame).world
val player = (Terrarum.ingame!! as Ingame).player
val renderWidth = FastMath.ceil(Terrarum.WIDTH.toFloat())
val renderHeight = FastMath.ceil(Terrarum.HEIGHT.toFloat())

View File

@@ -39,7 +39,7 @@ internal object Authenticator : ConsoleCommand {
Echo(msg)
println("[Authenticator] " + msg)
a = !a
(Terrarum.ingame!!.consoleHandler as ConsoleWindow).reset()
Terrarum.ingame!!.consoleHandler.reset()
}
else {
printUsage() // thou shalt not pass!

View File

@@ -1,13 +0,0 @@
package net.torvald.terrarum.console
import net.torvald.terrarum.Terrarum
object CheatWarnTest : ConsoleCommand {
override fun execute(args: Array<String>) {
Terrarum.ingame?.uiCheatMotherfuckerNootNoot?.setAsOpen()
}
override fun printUsage() {
}
}

View File

@@ -1,5 +1,6 @@
package net.torvald.terrarum.console
import net.torvald.terrarum.modulebasegame.console.*
import java.util.HashMap
/**

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
import net.torvald.terrarum.console.ConsoleCommand
/**
* Created by minjaesong on 2016-01-15.
*/

View File

@@ -1,20 +0,0 @@
package net.torvald.terrarum.console
import net.torvald.terrarum.*
import net.torvald.terrarum.Terrarum
/**
* Created by minjaesong on 2016-06-16.
*/
internal object Seed : ConsoleCommand {
override fun execute(args: Array<String>) {
Echo("Map$ccW: $ccG${Terrarum.ingame!!.world.generatorSeed}")
println("[seed] Map$ccW: $ccG${Terrarum.ingame!!.world.generatorSeed}")
// TODO display randomiser seed
}
override fun printUsage() {
Echo("prints out the generator seed of the current game.")
}
}

View File

@@ -3,6 +3,7 @@ package net.torvald.terrarum.console
import com.badlogic.gdx.graphics.Color
import net.torvald.terrarum.worlddrawer.LightmapRenderer
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-02-17.
@@ -22,7 +23,7 @@ internal object SetGlobalLightOverride : ConsoleCommand {
val GL = Color(r, g, b, a)
lightOverride = true
Terrarum.ingame!!.world.globalLight = GL
(Terrarum.ingame!! as Ingame).world.globalLight = GL
}
catch (e: NumberFormatException) {
Echo("Wrong number input.")

View File

@@ -1,8 +1,7 @@
package net.torvald.terrarum.console
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppLoader
import net.torvald.terrarum.AppLoader
import java.io.IOException
@@ -12,14 +11,14 @@ import java.io.IOException
internal object SetLocale : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2) {
val prevLocale = TerrarumAppLoader.GAME_LOCALE
TerrarumAppLoader.GAME_LOCALE = args[1]
val prevLocale = AppLoader.GAME_LOCALE
AppLoader.GAME_LOCALE = args[1]
try {
Echo("Set locale to '" + TerrarumAppLoader.GAME_LOCALE + "'.")
Echo("Set locale to '" + AppLoader.GAME_LOCALE + "'.")
}
catch (e: IOException) {
Echo("could not read lang file.")
TerrarumAppLoader.GAME_LOCALE = prevLocale
AppLoader.GAME_LOCALE = prevLocale
}
}

View File

@@ -2,7 +2,7 @@ package net.torvald.terrarum.console
import com.badlogic.gdx.Gdx
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppLoader
import net.torvald.terrarum.AppLoader
import net.torvald.terrarum.langpack.Lang
/**
@@ -11,7 +11,7 @@ import net.torvald.terrarum.langpack.Lang
internal object Version : ConsoleCommand {
override fun execute(args: Array<String>) {
Echo("${Terrarum.NAME} ${TerrarumAppLoader.getVERSION_STRING()}")
Echo("${Terrarum.NAME} ${AppLoader.getVERSION_STRING()}")
Echo("Polyglot language pack version ${Lang.POLYGLOT_VERSION}")
Echo("GL_VERSION: ${Terrarum.GL_VERSION}")
Echo("Renderer: ${Gdx.graphics.glVersion.rendererString}, ${Gdx.graphics.glVersion.vendorString}")

View File

@@ -5,6 +5,7 @@ import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.itemproperties.ItemCodex.ACTORID_MIN
typealias ActorID = Int
/**
@@ -34,48 +35,21 @@ abstract class Actor(val renderOrder: RenderOrder) : Comparable<Actor>, Runnable
* Valid RefID is equal to or greater than 16777216.
* @return Reference ID. (16777216-0x7FFF_FFFF)
*/
open var referenceID: ActorID = generateUniqueReferenceID()
open var referenceID: ActorID? = null
var actorValue = ActorValue(this)
@Volatile var flagDespawn = false
override fun equals(other: Any?) = referenceID == (other as Actor).referenceID
override fun hashCode() = referenceID
override fun hashCode() = referenceID!!
override fun toString() =
if (actorValue.getAsString(AVKey.NAME).isNullOrEmpty())
if (actorValue.getAsString("name").isNullOrEmpty())
"${hashCode()}"
else
"${hashCode()} (${actorValue.getAsString(AVKey.NAME)})"
override fun compareTo(other: Actor): Int = (this.referenceID - other.referenceID).sign()
"${hashCode()} (${actorValue.getAsString("name")})"
override fun compareTo(other: Actor): Int = (this.referenceID!! - other.referenceID!!).sign()
fun Int.sign(): Int = if (this > 0) 1 else if (this < 0) -1 else 0
/**
* Usage:
*
* override var referenceID: Int = generateUniqueReferenceID()
*/
fun generateUniqueReferenceID(): ActorID {
fun hasCollision(value: ActorID) =
try {
Terrarum.ingame!!.theGameHasActor(value) ||
value < ItemCodex.ACTORID_MIN ||
value !in when (renderOrder) {
RenderOrder.BEHIND -> RANGE_BEHIND
RenderOrder.MIDDLE -> RANGE_MIDDLE
RenderOrder.MIDTOP -> RANGE_MIDTOP
RenderOrder.FRONT -> RANGE_FRONT
}
}
catch (gameNotInitialisedException: KotlinNullPointerException) {
false
}
var ret: Int
do {
ret = HQRNG().nextInt().and(0x7FFFFFFF) // set new ID
} while (hasCollision(ret)) // check for collision
return ret
}
/**
* ActorValue change event handler
@@ -83,6 +57,7 @@ abstract class Actor(val renderOrder: RenderOrder) : Comparable<Actor>, Runnable
* @param value null if the key is deleted
*/
abstract @Event fun onActorValueChange(key: String, value: Any?)
}
annotation class Event

View File

@@ -1,6 +1,8 @@
package net.torvald.terrarum.gameactors
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.Hitbox
/**
* Actor with visible body

View File

@@ -1,11 +1,10 @@
package net.torvald.terrarum.gameactors.ai
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppLoader
import net.torvald.terrarum.AppLoader
import net.torvald.terrarum.gameactors.AIControlled
import net.torvald.terrarum.gameactors.AVKey
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.worlddrawer.LightmapRenderer
import net.torvald.terrarum.modulebasegame.gameactors.AVKey
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarum.blockproperties.Block
import net.torvald.terrarum.blockproperties.BlockCodex
import org.luaj.vm2.*
@@ -15,7 +14,7 @@ import org.luaj.vm2.lib.ZeroArgFunction
/**
* Created by minjaesong on 2016-10-24.
*/
internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
/*internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
// FIXME when actor jumps, the actor releases left/right stick
@@ -233,7 +232,7 @@ internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
luatable[y - feetTilePos[1]] = LuaTable()
for (x in feetTilePos[0] - radius..feetTilePos[0] + radius) {
val tile = BlockCodex[Terrarum.ingame!!.world.getTileFromTerrain(x, y) ?: Block.NULL]
val tile = BlockCodex[(Terrarum.ingame!! as Ingame).world.getTileFromTerrain(x, y) ?: Block.NULL]
val solidity = tile.isSolid.toInt()
val liquidity = tile.isFluid.toInt()
val gravity = tile.isFallable.toInt()
@@ -277,7 +276,7 @@ internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
// search down
var searchDownCounter = 0
while (true) {
val tile = Terrarum.ingame!!.world.getTileFromTerrain(x, feetTilePos[1] + searchDownCounter) ?: Block.STONE
val tile = (Terrarum.ingame!! as Ingame).world.getTileFromTerrain(x, feetTilePos[1] + searchDownCounter) ?: Block.STONE
if (BlockCodex[tile].isSolid || searchDownCounter >= searchDownLimit) {
luatable[x - feetTilePos[0]] = searchDownCounter
break
@@ -320,7 +319,7 @@ internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
// search up
var searchUpCounter = 0
while (true) {
val tile = Terrarum.ingame!!.world.getTileFromTerrain(x, feetTilePos[1] - searchUpCounter) ?: Block.STONE
val tile = (Terrarum.ingame!! as Ingame).world.getTileFromTerrain(x, feetTilePos[1] - searchUpCounter) ?: Block.STONE
if (BlockCodex[tile].isSolid || searchUpCounter >= searchUpLimit) {
luatable[x - feetTilePos[0]] = searchUpCounter
break
@@ -362,7 +361,7 @@ internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
// search up
var searchUpCounter = 0
while (true) {
val tile = Terrarum.ingame!!.world.getTileFromTerrain(x, feetTilePos[1] - searchUpCounter) ?: Block.STONE
val tile = (Terrarum.ingame!! as Ingame).world.getTileFromTerrain(x, feetTilePos[1] - searchUpCounter) ?: Block.STONE
if (!BlockCodex[tile].isSolid || searchUpCounter >= searchUpLimit) {
luatable[x - feetTilePos[0]] = searchUpCounter
break
@@ -381,16 +380,16 @@ internal class AILuaAPI(g: Globals, actor: ActorWithPhysics) {
class GameVersion : ZeroArgFunction() {
override fun call(): LuaValue {
return TerrarumAppLoader.getVERSION_STRING().toLua()
return AppLoader.getVERSION_STRING().toLua()
}
}
class GameVersionRaw : ZeroArgFunction() {
override fun call(): LuaValue {
return TerrarumAppLoader.VERSION_RAW.toLua()
return AppLoader.VERSION_RAW.toLua()
}
}
}
}*/
fun Double.toLua() = LuaValue.valueOf(this)
fun Int.toLua() = LuaValue.valueOf(this)

View File

@@ -1,10 +1,11 @@
package net.torvald.terrarum.gameactors.ai
import net.torvald.terrarum.gameactors.HumanoidNPC
import net.torvald.terrarum.gameactors.Actor
/**
* Created by minjaesong on 2016-03-02.
*/
interface ActorAI {
fun update(actor: HumanoidNPC, delta: Float)
fun update(actor: Actor, delta: Float)
}

View File

@@ -1,9 +1,6 @@
package net.torvald.terrarum.gameactors.ai
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.ActorHumanoid
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.gameactors.HumanoidNPC
import org.luaj.vm2.Globals
import org.luaj.vm2.LuaError
import org.luaj.vm2.LuaInteger
@@ -15,7 +12,7 @@ import java.io.Reader
/**
* Created by minjaesong on 2017-02-04.
*/
class LuaAIWrapper(private val scriptPath: String) : ActorAI {
/*class LuaAIWrapper(private val scriptPath: String) : ActorAI {
protected val luag: Globals = JsePlatform.standardGlobals()
@@ -27,14 +24,14 @@ class LuaAIWrapper(private val scriptPath: String) : ActorAI {
private lateinit var aiLuaAPI: AILuaAPI
private lateinit var targetActor: ActorWithPhysics
private lateinit var targetActor: Actor
/**
* The initialiser
*
* Use ```(p.ai as LuaAIWrapper).attachActor(p)```
*/
fun attachActor(actor: ActorWithPhysics) {
fun attachActor(actor: Actor) {
targetActor = actor
luag["io"] = LuaValue.NIL
@@ -47,7 +44,7 @@ class LuaAIWrapper(private val scriptPath: String) : ActorAI {
luaInstance.call()
}
override fun update(actor: HumanoidNPC, delta: Float) {
override fun update(actor: Actor, delta: Float) {
// run "update()" function in the script
luag.get("update").call(delta.toLua())
}
@@ -112,4 +109,4 @@ class LuaAIWrapper(private val scriptPath: String) : ActorAI {
}
fun Float.toLua(): LuaValue = LuaInteger.valueOf(this.toDouble())
}
}*/

View File

@@ -0,0 +1,12 @@
package net.torvald.terrarum.gameactors.ai
import net.torvald.terrarum.gameactors.Actor
/**
* Created by minjaesong on 2018-06-07.
*/
class NullAI : ActorAI {
override fun update(actor: Actor, delta: Float) {
// null AI does nothing
}
}

View File

@@ -3,11 +3,11 @@ package net.torvald.terrarum.gamecontroller
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.InputAdapter
import net.torvald.terrarum.Ingame
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.floorInt
import net.torvald.terrarum.worlddrawer.WorldCamera
/**

View File

@@ -4,6 +4,8 @@ package net.torvald.terrarum.gameworld
import com.badlogic.gdx.graphics.Color
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.modulebasegame.gameworld.GameEconomy
import net.torvald.terrarum.modulebasegame.gameworld.WorldTime
import org.dyn4j.geometry.Vector2
typealias BlockAddress = Long

View File

@@ -1,6 +1,6 @@
package net.torvald.terrarum.gameworld
import net.torvald.terrarum.virtualcomputer.tvd.ByteArray64
import net.torvald.terrarum.modulecomputers.virtualcomputer.tvd.ByteArray64
/**
* Created by minjaesong on 2016-01-17.

View File

@@ -2,8 +2,6 @@ package net.torvald.terrarum.gameworld
import net.torvald.point.Point2d
import java.io.Serializable
class MapPoint {
var startPoint: Point2d? = null

View File

@@ -48,7 +48,7 @@ object TinyAlphNum : BitmapFont() {
else if (c in 0.toChar()..255.toChar()) {
batch.color = colourHolder.cpy().mul(0.5f, 0.5f, 0.5f, 1f)
batch.draw(fontSheet.get(c.toInt() % 16, c.toInt() / 16), x + charsPrinted * W + 1, y)
batch.draw(fontSheet.get(c.toInt() % 16, c.toInt() / 16), x + charsPrinted * W , y + 1)
batch.draw(fontSheet.get(c.toInt() % 16, c.toInt() / 16), x + charsPrinted * W, y + 1)
batch.draw(fontSheet.get(c.toInt() % 16, c.toInt() / 16), x + charsPrinted * W + 1, y + 1)

View File

@@ -1,6 +1,7 @@
package net.torvald.terrarum.itemproperties
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.modulebasegame.gameactors.ActorHumanoid
import net.torvald.terrarum.sqrt
/**
* Created by minjaesong on 2017-04-17.

View File

@@ -3,8 +3,8 @@ package net.torvald.terrarum.itemproperties
import com.badlogic.gdx.graphics.Color
import net.torvald.random.HQRNG
import net.torvald.terrarum.ItemValue
import net.torvald.terrarum.gameactors.ActorInventory
import net.torvald.terrarum.gameactors.Pocketed
import net.torvald.terrarum.modulebasegame.gameactors.ActorInventory
import net.torvald.terrarum.modulebasegame.gameactors.Pocketed
import net.torvald.terrarum.itemproperties.ItemCodex.ITEM_DYNAMIC
import net.torvald.terrarum.langpack.Lang
@@ -140,7 +140,7 @@ abstract class GameItem : Comparable<GameItem>, Cloneable {
* note: DO NOT super() this!
*
* Consumption function is executed in net.torvald.terrarum.gamecontroller.IngameController,
* in which the function itself is defined in net.torvald.terrarum.gameactors.ActorInventory
* in which the function itself is defined in net.torvald.terrarum.modulebasegame.gameactors.ActorInventory
*/
open fun primaryUse(delta: Float): Boolean = false

View File

@@ -4,12 +4,13 @@ import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureRegion
import net.torvald.point.Point2d
import net.torvald.terrarum.KVHashMap
import net.torvald.terrarum.gameactors.CanBeAnItem
import net.torvald.terrarum.modulebasegame.gameactors.CanBeAnItem
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.worlddrawer.FeaturesDrawer.TILE_SIZE
import java.util.*
@@ -22,7 +23,7 @@ object ItemCodex {
* <ItemID or RefID for Actor, TheItem>
* Will return corresponding Actor if ID >= ACTORID_MIN
*/
private val itemCodex = HashMap<ItemID, GameItem>()
val itemCodex = HashMap<ItemID, GameItem>()
private val dynamicItemDescription = HashMap<ItemID, KVHashMap>()
val ITEM_TILES = 0..GameWorld.TILES_SUPPORTED - 1
@@ -34,10 +35,14 @@ object ItemCodex {
private val itemImagePlaceholder = TextureRegion(Texture("./assets/item_kari_24.tga"))
//private val ingame = Terrarum.ingame!! as Ingame
// TODO: when generalised, there's no guarantee that blocks will be used as an item. Write customised item prop loader and init it on the Ingame
init {
println("[ItemCodex] recording item ID ")
/*println("[ItemCodex] recording item ID ")
// blocks.csvs are loaded by ModMgr beforehand
// block items (blocks and walls are the same thing basically)
@@ -69,7 +74,7 @@ object ItemCodex {
// check for collision with actors (BLOCK only)
if (this.inventoryCategory == Category.BLOCK) {
Terrarum.ingame!!.actorContainer.forEach {
ingame.actorContainer.forEach {
if (it is ActorWithPhysics && it.hIntTilewiseHitbox.intersects(mousePoint))
return false
}
@@ -77,25 +82,25 @@ object ItemCodex {
// return false if the tile is already there
if (this.inventoryCategory == Category.BLOCK &&
this.dynamicID == Terrarum.ingame!!.world.getTileFromTerrain(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.dynamicID == ingame.world.getTileFromTerrain(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.inventoryCategory == Category.WALL &&
this.dynamicID - ITEM_WALLS.start == Terrarum.ingame!!.world.getTileFromWall(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.dynamicID - ITEM_WALLS.start == ingame.world.getTileFromWall(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.inventoryCategory == Category.WIRE &&
this.dynamicID - ITEM_WIRES.start == Terrarum.ingame!!.world.getTileFromWire(Terrarum.mouseTileX, Terrarum.mouseTileY)
this.dynamicID - ITEM_WIRES.start == ingame.world.getTileFromWire(Terrarum.mouseTileX, Terrarum.mouseTileY)
)
return false
// filter passed, do the job
// FIXME this is only useful for Player
if (i in ITEM_TILES) {
Terrarum.ingame!!.world.setTileTerrain(
ingame.world.setTileTerrain(
Terrarum.mouseTileX,
Terrarum.mouseTileY,
i
)
}
else {
Terrarum.ingame!!.world.setTileWall(
ingame.world.setTileWall(
Terrarum.mouseTileX,
Terrarum.mouseTileY,
i
@@ -105,7 +110,7 @@ object ItemCodex {
return true
}
}
}
}*/
// test copper pickaxe
/*itemCodex[ITEM_STATIC.first] = object : GameItem() {
@@ -130,30 +135,30 @@ object ItemCodex {
override fun primaryUse(delta: Float): Boolean {
val mousePoint = Point2d(Terrarum.mouseTileX.toDouble(), Terrarum.mouseTileY.toDouble())
val actorvalue = Terrarum.ingame!!.player.actorValue
val actorvalue = ingame.player.actorValue
using = true
// linear search filter (check for intersection with tilewise mouse point and tilewise hitbox)
// return false if hitting actors
Terrarum.ingame!!.actorContainer.forEach {
ingame.actorContainer.forEach {
if (it is ActorWithPhysics && it.hIntTilewiseHitbox.intersects(mousePoint))
return false
}
// return false if there's no tile
if (Block.AIR == Terrarum.ingame!!.world.getTileFromTerrain(Terrarum.mouseTileX, Terrarum.mouseTileY))
if (Block.AIR == ingame.world.getTileFromTerrain(Terrarum.mouseTileX, Terrarum.mouseTileY))
return false
// filter passed, do the job
val swingDmgToFrameDmg = delta.toDouble() / actorvalue.getAsDouble(AVKey.ACTION_INTERVAL)!!
Terrarum.ingame!!.world.inflictTerrainDamage(
ingame.world.inflictTerrainDamage(
Terrarum.mouseTileX,
Terrarum.mouseTileY,
Calculate.pickaxePower(Terrarum.ingame!!.player, material) * swingDmgToFrameDmg
Calculate.pickaxePower(ingame.player, material) * swingDmgToFrameDmg
)
return true
}
@@ -161,7 +166,7 @@ object ItemCodex {
override fun endPrimaryUse(delta: Float): Boolean {
using = false
// reset action timer to zero
Terrarum.ingame!!.player.actorValue[AVKey.__ACTION_TIMER] = 0.0
ingame.player.actorValue[AVKey.__ACTION_TIMER] = 0.0
return true
}
}*/
@@ -184,7 +189,7 @@ object ItemCodex {
TODO("read from dynamicitem description (JSON)")
}
else {
val a = Terrarum.ingame!!.getActorByID(code) // actor item
val a = (Terrarum.ingame!! as Ingame).getActorByID(code) // actor item
if (a is CanBeAnItem) return a.itemData
throw IllegalArgumentException("Attempted to get item data of actor that cannot be an item. ($a)")

View File

@@ -2,6 +2,7 @@ package net.torvald.terrarum.itemproperties
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.ai.toLua
import net.torvald.terrarum.modulebasegame.Ingame
import org.luaj.vm2.Globals
import org.luaj.vm2.LuaTable
import org.luaj.vm2.LuaValue
@@ -43,13 +44,13 @@ class ItemEffectsLuaAPI(g: Globals) {
class StrikeEarth : ThreeArgFunction() {
override fun call(x: LuaValue, y: LuaValue, power: LuaValue): LuaValue {
Terrarum.ingame!!.world.inflictTerrainDamage(x.checkint(), y.checkint(), power.checkdouble())
(Terrarum.ingame!! as Ingame).world.inflictTerrainDamage(x.checkint(), y.checkint(), power.checkdouble())
return LuaValue.NONE
}
}
class StrikeWall : ThreeArgFunction() {
override fun call(x: LuaValue, y: LuaValue, power: LuaValue): LuaValue {
Terrarum.ingame!!.world.inflictWallDamage(x.checkint(), y.checkint(), power.checkdouble())
(Terrarum.ingame!! as Ingame).world.inflictWallDamage(x.checkint(), y.checkint(), power.checkdouble())
return LuaValue.NONE
}
}

View File

@@ -2,7 +2,7 @@ package net.torvald.terrarum.langpack
import net.torvald.terrarum.utils.JsonFetcher
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.TerrarumAppLoader
import net.torvald.terrarum.AppLoader
import java.io.*
import java.util.*
@@ -112,7 +112,7 @@ object Lang {
fun fallback(): String = langpack["${key}_$FALLBACK_LANG_CODE"] ?: "$$key"
val ret = langpack["${key}_${TerrarumAppLoader.GAME_LOCALE}"]
val ret = langpack["${key}_${AppLoader.GAME_LOCALE}"]
val ret2 = if (ret.isNullOrEmpty()) fallback() else ret!!
// special treatment
@@ -129,7 +129,7 @@ object Lang {
fun pluralise(word: String, count: Int): String {
if (count < 2) return word
when (TerrarumAppLoader.GAME_LOCALE) {
when (AppLoader.GAME_LOCALE) {
"fr" -> {
if (Arrays.binarySearch(FRENCH_WORD_NORMAL_PLURAL, word) >= 0) {
return word + "s"

View File

@@ -0,0 +1,106 @@
package net.torvald.terrarum.modulebasegame
import net.torvald.point.Point2d
import net.torvald.terrarum.ModMgr
import net.torvald.terrarum.ModuleEntryPoint
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.itemproperties.Material
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
/**
* Created by minjaesong on 2018-06-21.
*/
class EntryPoint : ModuleEntryPoint() {
override fun invoke() {
ModMgr.GameBlockLoader.invoke("basegame")
ModMgr.GameItemLoader.invoke("basegame")
ModMgr.GameLanguageLoader.invoke("basegame")
/////////////////////////////////
// load customised item loader //
/////////////////////////////////
println("[ItemCodex] recording item ID ")
// blocks.csvs are loaded by ModMgr beforehand
// block items (blocks and walls are the same thing basically)
for (i in ItemCodex.ITEM_TILES + ItemCodex.ITEM_WALLS) {
ItemCodex.itemCodex[i] = object : GameItem() {
override val originalID = i
override var dynamicID = i
override val isUnique: Boolean = false
override var baseMass: Double = BlockCodex[i].density / 1000.0
override var baseToolSize: Double? = null
override var equipPosition = EquipPosition.HAND_GRIP
override val originalName = BlockCodex[i % ItemCodex.ITEM_WALLS.first].nameKey
override var stackable = true
override var inventoryCategory = if (i in ItemCodex.ITEM_TILES) Category.BLOCK else Category.WALL
override var isDynamic = false
override val material = Material(0,0,0,0,0,0,0,0,0,0.0)
init {
print("$originalID ")
}
override fun primaryUse(delta: Float): Boolean {
return false
// TODO base punch attack
}
override fun secondaryUse(delta: Float): Boolean {
val ingame = Terrarum.ingame!! as Ingame
val mousePoint = Point2d(Terrarum.mouseTileX.toDouble(), Terrarum.mouseTileY.toDouble())
// check for collision with actors (BLOCK only)
if (this.inventoryCategory == Category.BLOCK) {
ingame.actorContainer.forEach {
if (it is ActorWithPhysics && it.hIntTilewiseHitbox.intersects(mousePoint))
return false
}
}
// return false if the tile is already there
if (this.inventoryCategory == Category.BLOCK &&
this.dynamicID == ingame.world.getTileFromTerrain(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.inventoryCategory == Category.WALL &&
this.dynamicID - ItemCodex.ITEM_WALLS.start == ingame.world.getTileFromWall(Terrarum.mouseTileX, Terrarum.mouseTileY) ||
this.inventoryCategory == Category.WIRE &&
this.dynamicID - ItemCodex.ITEM_WIRES.start == ingame.world.getTileFromWire(Terrarum.mouseTileX, Terrarum.mouseTileY)
)
return false
// filter passed, do the job
// FIXME this is only useful for Player
if (i in ItemCodex.ITEM_TILES) {
ingame.world.setTileTerrain(
Terrarum.mouseTileX,
Terrarum.mouseTileY,
i
)
}
else {
ingame.world.setTileWall(
Terrarum.mouseTileX,
Terrarum.mouseTileY,
i
)
}
return true
}
}
}
println("Welcome back!")
}
}

View File

@@ -1,4 +1,4 @@
package net.torvald.terrarum
package net.torvald.terrarum.modulebasegame
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
@@ -13,11 +13,11 @@ import net.torvald.terrarum.blockstats.BlockStats
import net.torvald.terrarum.concurrent.ThreadParallel
import net.torvald.terrarum.console.*
import net.torvald.terrarum.gameactors.*
import net.torvald.terrarum.gameactors.physicssolver.CollisionSolver
import net.torvald.terrarum.modulebasegame.gameactors.physicssolver.CollisionSolver
import net.torvald.terrarum.gamecontroller.IngameController
import net.torvald.terrarum.gamecontroller.KeyToggler
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.gameworld.WorldSimulator
import net.torvald.terrarum.modulebasegame.gameworld.WorldSimulator
import net.torvald.terrarum.weather.WeatherMixer
import net.torvald.terrarum.worlddrawer.BlocksDrawer
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
@@ -32,17 +32,27 @@ import javax.swing.JOptionPane
import com.badlogic.gdx.graphics.OrthographicCamera
import net.torvald.random.HQRNG
import net.torvald.terrarum.*
import net.torvald.terrarum.gameworld.fmod
import net.torvald.terrarum.modulebasegame.console.AVTracker
import net.torvald.terrarum.modulebasegame.console.ActorsList
import net.torvald.terrarum.console.Authenticator
import net.torvald.terrarum.console.SetGlobalLightOverride
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.modulebasegame.gameactors.*
import net.torvald.terrarum.modulebasegame.imagefont.Watch7SegMain
import net.torvald.terrarum.modulebasegame.imagefont.WatchDotAlph
import net.torvald.terrarum.modulebasegame.ui.*
import net.torvald.terrarum.ui.*
import net.torvald.terrarum.worldgenerator.RoguelikeRandomiser
import net.torvald.terrarum.worldgenerator.WorldGenerator
import net.torvald.terrarum.modulebasegame.worldgenerator.RoguelikeRandomiser
import net.torvald.terrarum.modulebasegame.worldgenerator.WorldGenerator
/**
* Created by minjaesong on 2017-06-16.
*/
class Ingame(val batch: SpriteBatch) : Screen {
class Ingame(batch: SpriteBatch) : IngameInstance(batch) {
private val ACTOR_UPDATE_RANGE = 4096
@@ -53,10 +63,10 @@ class Ingame(val batch: SpriteBatch) : Screen {
/**
* list of Actors that is sorted by Actors' referenceID
*/
val ACTORCONTAINER_INITIAL_SIZE = 64
//val ACTORCONTAINER_INITIAL_SIZE = 64
val PARTICLES_MAX = Terrarum.getConfigInt("maxparticles")
val actorContainer = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
val actorContainerInactive = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
//val actorContainer = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
//val actorContainerInactive = ArrayList<Actor>(ACTORCONTAINER_INITIAL_SIZE)
val particlesContainer = CircularArray<ParticleBase>(PARTICLES_MAX)
val uiContainer = ArrayList<UICanvas>()
@@ -70,9 +80,9 @@ class Ingame(val batch: SpriteBatch) : Screen {
inline val player: ActorHumanoid // currently POSSESSED actor :)
get() = playableActorDelegate.actor
var screenZoom = 1.0f
val ZOOM_MAXIMUM = 4.0f
val ZOOM_MINIMUM = 0.5f
//var screenZoom = 1.0f // definition moved to IngameInstance
//val ZOOM_MAXIMUM = 4.0f // definition moved to IngameInstance
//val ZOOM_MINIMUM = 0.5f // definition moved to IngameInstance
companion object {
val lightmapDownsample = 4f //2f: still has choppy look when the camera moves but unnoticeable when blurred
@@ -84,6 +94,36 @@ class Ingame(val batch: SpriteBatch) : Screen {
camera.update()
batch.projectionMatrix = camera.combined
}
/**
* Usage:
*
* override var referenceID: Int = generateUniqueReferenceID()
*/
fun generateUniqueReferenceID(renderOrder: Actor.RenderOrder): ActorID {
fun hasCollision(value: ActorID) =
try {
Terrarum.ingame!!.theGameHasActor(value) ||
value < ItemCodex.ACTORID_MIN ||
value !in when (renderOrder) {
Actor.RenderOrder.BEHIND -> Actor.RANGE_BEHIND
Actor.RenderOrder.MIDDLE -> Actor.RANGE_MIDDLE
Actor.RenderOrder.MIDTOP -> Actor.RANGE_MIDTOP
Actor.RenderOrder.FRONT -> Actor.RANGE_FRONT
}
}
catch (gameNotInitialisedException: KotlinNullPointerException) {
false
}
var ret: Int
do {
ret = HQRNG().nextInt().and(0x7FFFFFFF) // set new ID
} while (hasCollision(ret)) // check for collision
return ret
}
}
@@ -110,7 +150,6 @@ class Ingame(val batch: SpriteBatch) : Screen {
lateinit var consoleHandler: UICanvas
lateinit var debugWindow: UICanvas
lateinit var notifier: UICanvas
@@ -195,7 +234,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
when (gameLoadMode) {
GameLoadMode.CREATE_NEW -> enter(gameLoadInfoPayload as NewWorldParameters)
GameLoadMode.LOAD_FROM -> enter(gameLoadInfoPayload as GameSaveData)
GameLoadMode.LOAD_FROM -> enter(gameLoadInfoPayload as GameSaveData)
}
LightmapRenderer.world = this.world
@@ -248,7 +287,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
println("[Ingame] loaded successfully.")
}
else {
LoadScreen.addMessage("${Terrarum.NAME} version ${TerrarumAppLoader.getVERSION_STRING()}")
LoadScreen.addMessage("${Terrarum.NAME} version ${AppLoader.getVERSION_STRING()}")
LoadScreen.addMessage("Creating new world")
@@ -338,7 +377,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
// quick bar
uiQuickBar = UIQuickBar()
uiQuickBar.isVisible = true
uiQuickBar.setPosition(0, 0)
uiQuickBar.setPosition((Terrarum.WIDTH - uiQuickBar.width) / 2 + 12, -10)
// pie menu
uiPieMenu = UIPieMenu()
@@ -463,7 +502,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
Gdx.graphics.setTitle(TerrarumAppLoader.GAME_NAME +
Gdx.graphics.setTitle(AppLoader.GAME_NAME +
" — F: ${Gdx.graphics.framesPerSecond} (${Terrarum.TARGET_INTERNAL_FPS})" +
" — M: ${Terrarum.memInUse}M / ${Terrarum.memTotal}M / ${Terrarum.memXmx}M"
)
@@ -701,7 +740,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
batch.draw(lightTex,
xrem,
yrem,
lightTex.width * Ingame.lightmapDownsample, lightTex.height * Ingame.lightmapDownsample
lightTex.width * lightmapDownsample, lightTex.height * lightmapDownsample
//lightTex.width.toFloat(), lightTex.height.toFloat() // for debugging
)
@@ -771,7 +810,7 @@ class Ingame(val batch: SpriteBatch) : Screen {
batch.draw(lightTex,
xrem,
yrem,
lightTex.width * Ingame.lightmapDownsample, lightTex.height * Ingame.lightmapDownsample
lightTex.width * lightmapDownsample, lightTex.height * lightmapDownsample
//lightTex.width.toFloat(), lightTex.height.toFloat() // for debugging
)
@@ -1190,35 +1229,15 @@ class Ingame(val batch: SpriteBatch) : Screen {
private fun ActorWithBody.inScreen() =
distToCameraSqr(this) <=
(Terrarum.WIDTH.plus(this.hitbox.width.div(2)).
times(1 / Terrarum.ingame!!.screenZoom).sqr() +
times(1 / screenZoom).sqr() +
Terrarum.HEIGHT.plus(this.hitbox.height.div(2)).
times(1 / Terrarum.ingame!!.screenZoom).sqr())
times(1 / screenZoom).sqr())
/** whether the actor is within update range */
private fun ActorWithBody.inUpdateRange() = distToCameraSqr(this) <= ACTOR_UPDATE_RANGE.sqr()
/**
* actorContainer extensions
*/
fun theGameHasActor(actor: Actor?) = if (actor == null) false else theGameHasActor(actor.referenceID)
fun theGameHasActor(ID: Int): Boolean =
isActive(ID) || isInactive(ID)
fun isActive(ID: Int): Boolean =
if (actorContainer.size == 0)
false
else
actorContainer.binarySearch(ID) >= 0
fun isInactive(ID: Int): Boolean =
if (actorContainerInactive.size == 0)
false
else
actorContainerInactive.binarySearch(ID) >= 0
fun removeActor(ID: Int) = removeActor(getActorByID(ID))
override fun removeActor(ID: Int) = removeActor(getActorByID(ID))
/**
* get index of the actor and delete by the index.
* we can do this as the list is guaranteed to be sorted
@@ -1227,10 +1246,10 @@ class Ingame(val batch: SpriteBatch) : Screen {
* Any values behind the index will be automatically pushed to front.
* This is how remove function of [java.util.ArrayList] is defined.
*/
fun removeActor(actor: Actor) {
override fun removeActor(actor: Actor) {
if (actor.referenceID == player.referenceID || actor.referenceID == 0x51621D) // do not delete this magic
throw RuntimeException("Attempted to remove player.")
val indexToDelete = actorContainer.binarySearch(actor.referenceID)
val indexToDelete = actorContainer.binarySearch(actor.referenceID!!)
if (indexToDelete >= 0) {
actorContainer.removeAt(indexToDelete)
@@ -1239,19 +1258,19 @@ class Ingame(val batch: SpriteBatch) : Screen {
if (actor is ActorWithBody) {
when (actor.renderOrder) {
Actor.RenderOrder.BEHIND -> {
val i = actorsRenderBehind.binarySearch(actor.referenceID)
val i = actorsRenderBehind.binarySearch(actor.referenceID!!)
actorsRenderBehind.removeAt(i)
}
Actor.RenderOrder.MIDDLE -> {
val i = actorsRenderMiddle.binarySearch(actor.referenceID)
val i = actorsRenderMiddle.binarySearch(actor.referenceID!!)
actorsRenderMiddle.removeAt(i)
}
Actor.RenderOrder.MIDTOP -> {
val i = actorsRenderMidTop.binarySearch(actor.referenceID)
val i = actorsRenderMidTop.binarySearch(actor.referenceID!!)
actorsRenderMidTop.removeAt(i)
}
Actor.RenderOrder.FRONT -> {
val i = actorsRenderFront.binarySearch(actor.referenceID)
val i = actorsRenderFront.binarySearch(actor.referenceID!!)
actorsRenderFront.removeAt(i)
}
}
@@ -1262,8 +1281,8 @@ class Ingame(val batch: SpriteBatch) : Screen {
/**
* Check for duplicates, append actor and sort the list
*/
fun addNewActor(actor: Actor) {
if (theGameHasActor(actor.referenceID)) {
override fun addNewActor(actor: Actor) {
if (theGameHasActor(actor.referenceID!!)) {
throw Error("The actor $actor already exists in the game")
}
else {
@@ -1290,8 +1309,8 @@ class Ingame(val batch: SpriteBatch) : Screen {
}
fun activateDormantActor(actor: Actor) {
if (!isInactive(actor.referenceID)) {
if (isActive(actor.referenceID))
if (!isInactive(actor.referenceID!!)) {
if (isActive(actor.referenceID!!))
throw Error("The actor $actor is already activated")
else
throw Error("The actor $actor already exists in the game")
@@ -1335,40 +1354,6 @@ class Ingame(val batch: SpriteBatch) : Screen {
uiContainer.add(ui)
}
fun getActorByID(ID: Int): Actor {
if (actorContainer.size == 0 && actorContainerInactive.size == 0)
throw IllegalArgumentException("Actor with ID $ID does not exist.")
var index = actorContainer.binarySearch(ID)
if (index < 0) {
index = actorContainerInactive.binarySearch(ID)
if (index < 0) {
JOptionPane.showMessageDialog(
null,
"Actor with ID $ID does not exist.",
null, JOptionPane.ERROR_MESSAGE
)
throw IllegalArgumentException("Actor with ID $ID does not exist.")
}
else
return actorContainerInactive[index]
}
else
return actorContainer[index]
}
private fun insertionSortLastElem(arr: ArrayList<Actor>) {
lock(ReentrantLock()) {
var j = arr.lastIndex - 1
val x = arr.last()
while (j >= 0 && arr[j] > x) {
arr[j + 1] = arr[j]
j -= 1
}
arr[j + 1] = x
}
}
private fun insertionSortLastElemAV(arr: ArrayList<ActorWithBody>) { // out-projection doesn't work, duh
lock(ReentrantLock()) {
var j = arr.lastIndex - 1
@@ -1381,38 +1366,6 @@ class Ingame(val batch: SpriteBatch) : Screen {
}
}
private fun ArrayList<*>.binarySearch(actor: Actor) = this.binarySearch(actor.referenceID)
private fun ArrayList<*>.binarySearch(ID: Int): Int {
// code from collections/Collections.kt
var low = 0
var high = this.size - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)!!
if (ID > midVal.hashCode())
low = mid + 1
else if (ID < midVal.hashCode())
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
inline fun lock(lock: Lock, body: () -> Unit) {
lock.lock()
try {
body()
}
finally {
lock.unlock()
}
}
fun setTooltipMessage(message: String?) {
if (message == null) {
uiTooltip.setAsClose()
@@ -1525,6 +1478,16 @@ class Ingame(val batch: SpriteBatch) : Screen {
uiAliases.forEach { it.dispose() }
uiAlasesPausing.forEach { it.dispose() }
WatchDotAlph.dispose()
Watch7SegMain.dispose()
WatchDotAlph.dispose()
ItemSlotImageBuilder.dispose()
MessageWindow.SEGMENT_BLACK.dispose()
MessageWindow.SEGMENT_WHITE.dispose()
}
@@ -1534,6 +1497,8 @@ class Ingame(val batch: SpriteBatch) : Screen {
* Camera will be moved so that (newX, newY) would be sit on the top-left edge.
*/
fun setCameraPosition(newX: Float, newY: Float) {
Ingame.setCameraPosition(batch, camera, newX, newY)
setCameraPosition(batch, camera, newX, newY)
}
}

View File

@@ -1,7 +1,11 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.debuggerapp.ActorValueTracker
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.debuggerapp.ActorValueTracker
import java.util.*
/**
@@ -12,7 +16,7 @@ internal object AVTracker : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size < 2) {
jPanelInstances.add(ActorValueTracker(Terrarum.ingame!!.player))
jPanelInstances.add(ActorValueTracker((Terrarum.ingame!! as Ingame).player))
}
else {
try {

View File

@@ -1,7 +1,10 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.debuggerapp.ActorsLister
import net.torvald.terrarum.modulebasegame.Ingame
import java.util.*
/**
@@ -12,8 +15,8 @@ internal object ActorsList : ConsoleCommand {
override fun execute(args: Array<String>) {
jPanelInstances.add(ActorsLister(
Terrarum.ingame!!.actorContainer,
Terrarum.ingame!!.actorContainerInactive)
(Terrarum.ingame!! as Ingame).actorContainer,
(Terrarum.ingame!! as Ingame).actorContainerInactive)
)
}

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import java.io.IOException
import java.nio.file.FileSystems
import java.nio.file.Files

View File

@@ -0,0 +1,15 @@
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.modulebasegame.Ingame
object CheatWarnTest : ConsoleCommand {
override fun execute(args: Array<String>) {
(Terrarum.ingame as? Ingame)?.uiCheatMotherfuckerNootNoot?.setAsOpen()
}
override fun printUsage() {
}
}

View File

@@ -1,7 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.ccO
import net.torvald.terrarum.ccW
import net.torvald.terrarum.console.CommandDict
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.langpack.Lang
import java.util.Formatter

View File

@@ -1,7 +1,10 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.utils.JsonWriter
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import java.io.IOException
@@ -13,7 +16,7 @@ internal object ExportAV : ConsoleCommand {
if (args.size == 2) {
try {
JsonWriter.writeToFile(
Terrarum.ingame!!.player.actorValue,
(Terrarum.ingame!! as Ingame).player.actorValue,
Terrarum.defaultDir + "/Exports/" + args[1] + ".json")
Echo("ExportAV: exported to " + args[1] + ".json")

View File

@@ -1,7 +1,8 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.serialise.WriteLayerData
import net.torvald.terrarum.serialise.WriteMeta
/**
* Created by minjaesong on 2017-07-18.

View File

@@ -1,9 +1,13 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.colourutil.Col4096
import net.torvald.terrarum.utils.RasterWriter
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.blockproperties.Block
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
import java.io.*
import java.util.HashMap
@@ -58,12 +62,14 @@ internal object ExportMap : ConsoleCommand {
}
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as Ingame).world
if (args.size == 2) {
var mapData = ByteArray(Terrarum.ingame!!.world.width * Terrarum.ingame!!.world.height * 3)
var mapData = ByteArray(world.width * world.height * 3)
var mapDataPointer = 0
for (tile in Terrarum.ingame!!.world.terrainIterator()) {
for (tile in world.terrainIterator()) {
val colArray = (colorTable as Map<Int, Col4096>)
.getOrElse(tile, { Col4096(0xFFF) }).toByteArray()
@@ -82,7 +88,7 @@ internal object ExportMap : ConsoleCommand {
try {
RasterWriter.writePNG_RGB(
Terrarum.ingame!!.world.width, Terrarum.ingame!!.world.height, mapData, dir + args[1] + ".png")
world.width, world.height, mapData, dir + args[1] + ".png")
Echo("ExportMap: exported to " + args[1] + ".png")
}

View File

@@ -1,4 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
/**
* Created by minjaesong on 2016-01-18.

View File

@@ -1,7 +1,11 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.*
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-01-19.
@@ -10,9 +14,12 @@ internal object GetAV : ConsoleCommand {
override fun execute(args: Array<String>) {
try {
if (args.size == 1 && Terrarum.ingame!!.player != null) {
val ingame = Terrarum.ingame!! as Ingame
if (args.size == 1 && ingame.player != null) {
// print all actorvalue of player
val av = Terrarum.ingame!!.player.actorValue
val av = ingame.player.actorValue
val keyset = av.keySet
Echo("$ccW== ActorValue list for ${ccY}player $ccW==")
@@ -29,20 +36,20 @@ internal object GetAV : ConsoleCommand {
// check if args[1] is number or not
if (!args[1].isNum()) { // args[1] is ActorValue name
Echo("${ccW}player.$ccM${args[1]} $ccW= " +
ccG +
Terrarum.ingame!!.player.actorValue[args[1]] +
" $ccO" +
Terrarum.ingame!!.player.actorValue[args[1]]!!.javaClass.simpleName
ccG +
ingame.player.actorValue[args[1]] +
" $ccO" +
ingame.player.actorValue[args[1]]!!.javaClass.simpleName
)
println("[GetAV] player.${args[1]} = " +
Terrarum.ingame!!.player.actorValue[args[1]] +
ingame.player.actorValue[args[1]] +
" " +
Terrarum.ingame!!.player.actorValue[args[1]]!!.javaClass.simpleName
ingame.player.actorValue[args[1]]!!.javaClass.simpleName
)
}
else {
// args[1] is actor ID
val actor = Terrarum.ingame!!.getActorByID(args[1].toInt())
val actor = ingame.getActorByID(args[1].toInt())
val av = actor.actorValue
val keyset = av.keySet
@@ -64,14 +71,14 @@ internal object GetAV : ConsoleCommand {
val id = args[1].toInt()
val av = args[2]
Echo("$ccW$id.$ccM$av $ccW= $ccG" +
Terrarum.ingame!!.getActorByID(id).actorValue[av] +
" $ccO" +
Terrarum.ingame!!.getActorByID(id).actorValue[av]!!.javaClass.simpleName
ingame.getActorByID(id).actorValue[av] +
" $ccO" +
ingame.getActorByID(id).actorValue[av]!!.javaClass.simpleName
)
println("$id.$av = " +
Terrarum.ingame!!.getActorByID(id).actorValue[av] +
ingame.getActorByID(id).actorValue[av] +
" " +
Terrarum.ingame!!.getActorByID(id).actorValue[av]!!.javaClass.simpleName
ingame.getActorByID(id).actorValue[av]!!.javaClass.simpleName
)
}
}

View File

@@ -1,9 +1,13 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.gameactors.Factionable
import net.torvald.terrarum.gameactors.Player
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.Player
import net.torvald.terrarumsansbitmap.gdx.GameFontBase
/**

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.langpack.Lang
/**

View File

@@ -1,6 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-03-20.
@@ -8,7 +11,7 @@ import net.torvald.terrarum.Terrarum
internal object GetTime : ConsoleCommand {
override fun execute(args: Array<String>) {
val worldTime = Terrarum.ingame!!.world.time
val worldTime = (Terrarum.ingame!! as Ingame).world.time
Echo(worldTime.getFormattedTime())
}

View File

@@ -1,7 +1,10 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import com.google.gson.Gson
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import java.io.BufferedWriter
import java.io.FileWriter
@@ -13,7 +16,7 @@ import java.io.IOException
internal object GsonTest : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2) {
val avelem = Gson().toJsonTree(Terrarum.ingame!!.player)
val avelem = Gson().toJsonTree((Terrarum.ingame!! as Ingame).player)
val jsonString = avelem.toString()

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.langpack.Lang
/**

View File

@@ -1,10 +1,12 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.serialise.ReadLayerData
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import java.io.FileInputStream
import java.util.zip.GZIPInputStream
/**
* Created by minjaesong on 2017-07-18.
@@ -18,10 +20,10 @@ object ImportLayerData : ConsoleCommand {
//val fis = GZIPInputStream(FileInputStream(args[1])) // this gzip is kaput
val fis = FileInputStream(args[1])
Terrarum.ingame!!.world = ReadLayerData(fis)
Terrarum.ingame!!.player.setPosition(
Terrarum.ingame!!.world.spawnY * FeaturesDrawer.TILE_SIZE.toDouble(),
Terrarum.ingame!!.world.spawnX * FeaturesDrawer.TILE_SIZE.toDouble()
(Terrarum.ingame!! as Ingame).world = ReadLayerData(fis)
(Terrarum.ingame!! as Ingame).player.setPosition(
(Terrarum.ingame!! as Ingame).world.spawnY * FeaturesDrawer.TILE_SIZE.toDouble(),
(Terrarum.ingame!! as Ingame).world.spawnX * FeaturesDrawer.TILE_SIZE.toDouble()
)
fis.close()
Echo("Successfully loaded ${args[1]}")

View File

@@ -1,16 +1,20 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.Player
import net.torvald.terrarum.gameactors.Pocketed
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.gameactors.Player
import net.torvald.terrarum.modulebasegame.gameactors.Pocketed
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-12-12.
*/
internal object Inventory : ConsoleCommand {
private var target: Pocketed? = Terrarum.ingame!!.player
private var target: Pocketed? = (Terrarum.ingame!! as Ingame).player
override fun execute(args: Array<String>) {
if (args.size == 1) {
@@ -20,7 +24,7 @@ internal object Inventory : ConsoleCommand {
when (args[1]) {
"list" -> listInventory()
"add" -> if (args.size > 3) addItem(args[2].toInt(), args[3].toInt())
else addItem(args[2].toInt())
else addItem(args[2].toInt())
"target" -> setTarget(args[2].toInt())
"equip" -> equipItem(args[2].toInt())
else -> printUsage()

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.swingapp.IMStringReader
/**

View File

@@ -1,6 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.langpack.Lang
/**

View File

@@ -1,5 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.langpack.Lang
/**

View File

@@ -1,6 +1,8 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.random.HQRNG
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
object MoneyDisp : ConsoleCommand {
override fun execute(args: Array<String>) {

View File

@@ -1,7 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.audio.Music
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
/**
* Created by minjaesong on 2016-08-02.

View File

@@ -1,7 +1,7 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.langpack.Lang
import java.util.*
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
/**
* Created by minjaesong on 2016-07-04.

View File

@@ -0,0 +1,23 @@
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.*
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-06-16.
*/
internal object Seed : ConsoleCommand {
override fun execute(args: Array<String>) {
Echo("Map$ccW: $ccG${(Terrarum.ingame!! as Ingame).world.generatorSeed}")
println("[seed] Map$ccW: $ccG${(Terrarum.ingame!! as Ingame).world.generatorSeed}")
// TODO display randomiser seed
}
override fun printUsage() {
Echo("prints out the generator seed of the current game.")
}
}

View File

@@ -1,7 +1,11 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.*
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-01-15.
@@ -59,7 +63,7 @@ internal object SetAV : ConsoleCommand {
return
}
Terrarum.ingame!!.player.actorValue[args[1]] = newValue
(Terrarum.ingame!! as Ingame).player.actorValue[args[1]] = newValue
Echo("${ccW}Set $ccM${args[1]} ${ccW}for ${ccY}player ${ccW}to $ccG$newValue")
println("[SetAV] set ActorValue '${args[1]}' for player to '$newValue'.")
}

View File

@@ -1,7 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.langpack.Lang
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-01-23.
@@ -24,7 +26,7 @@ internal object SetBulletin : ConsoleCommand {
* @param message real message
*/
fun send(message: Array<String>) {
Terrarum.ingame!!.sendNotification(message)
(Terrarum.ingame!! as Ingame).sendNotification(message)
println("sent notifinator")
}
}

View File

@@ -1,7 +1,11 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
/**
* Created by minjaesong on 2017-01-20.
@@ -10,10 +14,10 @@ internal object SetScale : ConsoleCommand {
override fun execute(args: Array<String>) {
if (args.size == 2 || args.size == 3) {
try {
val targetID = if (args.size == 3) args[1].toInt() else Terrarum.ingame!!.player.referenceID
val targetID = if (args.size == 3) args[1].toInt() else (Terrarum.ingame!! as Ingame).player.referenceID
val scale = args[if (args.size == 3) 2 else 1].toDouble()
val target = Terrarum.ingame!!.getActorByID(targetID)
val target = Terrarum.ingame!!.getActorByID(targetID!!)
if (target !is ActorWithPhysics) {
EchoError("Target is not ActorWithPhysics")

View File

@@ -1,20 +1,26 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.gameworld.WorldTime
import net.torvald.terrarum.modulebasegame.gameworld.WorldTime
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-03-20.
*/
internal object SetTime : ConsoleCommand {
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as Ingame).world
if (args.size == 2) {
val timeToSet = WorldTime.parseTime(args[1])
Terrarum.ingame!!.world.time.setTimeOfToday(timeToSet)
world.time.setTimeOfToday(timeToSet)
Echo("Set time to ${Terrarum.ingame!!.world.time.todaySeconds} " +
"(${Terrarum.ingame!!.world.time.hours}h${formatMin(Terrarum.ingame!!.world.time.minutes)})")
Echo("Set time to ${world.time.todaySeconds} " +
"(${world.time.hours}h${formatMin(world.time.minutes)})")
}
else {
printUsage()

View File

@@ -1,6 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-03-20.
@@ -10,12 +13,15 @@ internal object SetTimeDelta : ConsoleCommand {
val HARD_LIMIT = 60
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as Ingame).world
if (args.size == 2) {
Terrarum.ingame!!.world.time.timeDelta = args[1].toInt()
if (Terrarum.ingame!!.world.time.timeDelta == 0)
world.time.timeDelta = args[1].toInt()
if (world.time.timeDelta == 0)
Echo("時間よ止まれ!ザ・ワルド!!")
else
Echo("Set time delta to ${Terrarum.ingame!!.world.time.timeDelta}")
Echo("Set time delta to ${world.time.timeDelta}")
}
else {
printUsage()

View File

@@ -1,8 +1,10 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.gameactors.PhysTestBall
import net.torvald.terrarum.modulebasegame.gameactors.PhysTestBall
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.worlddrawer.WorldCamera
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import org.dyn4j.geometry.Vector2
/**
@@ -11,6 +13,9 @@ import org.dyn4j.geometry.Vector2
internal object SpawnPhysTestBall : ConsoleCommand {
@Throws(Exception::class)
override fun execute(args: Array<String>) {
val world = (Terrarum.ingame!! as Ingame).world
val mouseX = Terrarum.mouseX
val mouseY = Terrarum.mouseY
@@ -20,7 +25,7 @@ internal object SpawnPhysTestBall : ConsoleCommand {
val xvel = args[2].toDouble()
val yvel = if (args.size >= 4) args[3].toDouble() else 0.0
val ball = PhysTestBall(Terrarum.ingame!!.world)
val ball = PhysTestBall(world)
ball.setPosition(mouseX, mouseY)
ball.elasticity = elasticity
ball.applyForce(Vector2(xvel, yvel))
@@ -30,7 +35,7 @@ internal object SpawnPhysTestBall : ConsoleCommand {
else if (args.size == 2) {
val elasticity = args[1].toDouble()
val ball = PhysTestBall(Terrarum.ingame!!.world)
val ball = PhysTestBall(world)
ball.setPosition(mouseX, mouseY)
ball.elasticity = elasticity

View File

@@ -1,8 +1,10 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.PhysTestLuarLander
import net.torvald.terrarum.worlddrawer.WorldCamera
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.PhysTestLuarLander
/**
* Created by minjaesong on 2018-01-18.
@@ -11,7 +13,7 @@ internal object SpawnPhysTestLunarLander : ConsoleCommand {
override fun execute(args: Array<String>) {
val mouseX = Terrarum.mouseX
val mouseY = Terrarum.mouseY
val lander = PhysTestLuarLander(Terrarum.ingame!!.world)
val lander = PhysTestLuarLander((Terrarum.ingame!! as Ingame).world)
lander.setPosition(mouseX, mouseY)

View File

@@ -1,7 +1,9 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.DecodeTapestry
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.gameactors.DecodeTapestry
import java.io.File
/**

View File

@@ -1,14 +1,17 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.FixtureTikiTorch
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.FixtureTikiTorch
/**
* Created by minjaesong on 2016-12-17.
*/
internal object SpawnTikiTorch : ConsoleCommand {
override fun execute(args: Array<String>) {
val torch = FixtureTikiTorch(Terrarum.ingame!!.world)
val torch = FixtureTikiTorch((Terrarum.ingame!! as Ingame).world)
torch.setPosition(Terrarum.mouseX, Terrarum.mouseY)
Terrarum.ingame!!.addNewActor(torch)

View File

@@ -1,8 +1,12 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.EchoError
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
/**
* Created by minjaesong on 2016-01-24.
@@ -23,7 +27,7 @@ internal object Teleport : ConsoleCommand {
return
}
Terrarum.ingame!!.player.setPosition(x.toDouble(), y.toDouble())
(Terrarum.ingame!! as Ingame).player.setPosition(x.toDouble(), y.toDouble())
}
else if (args.size == 4) {
if (args[2].toLowerCase() != "to") {
@@ -35,7 +39,7 @@ internal object Teleport : ConsoleCommand {
try {
val fromActorID = args[1].toInt()
val targetActorID = if (args[3].toLowerCase() == "player")
Terrarum.ingame!!.player.referenceID
(Terrarum.ingame!! as Ingame).player.referenceID!!
else
args[3].toInt()

View File

@@ -1,15 +1,18 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.modulebasegame.Ingame
/**
* Created by minjaesong on 2016-01-19.
*/
internal object ToggleNoClip : ConsoleCommand {
override fun execute(args: Array<String>) {
val status = Terrarum.ingame!!.player.isNoClip()
val status = (Terrarum.ingame!! as Ingame).player.isNoClip()
Terrarum.ingame!!.player.setNoClip(!status)
(Terrarum.ingame!! as Ingame).player.setNoClip(!status)
Echo("Set no-clip status to " + (!status).toString())
}

View File

@@ -1,6 +1,8 @@
package net.torvald.terrarum.console
package net.torvald.terrarum.modulebasegame.console
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.ConsoleCommand
import net.torvald.terrarum.console.Echo
/**
* Created by minjaesong on 2016-01-25.

View File

@@ -1,12 +1,13 @@
package net.torvald.terrarum.debuggerapp
package net.torvald.terrarum.modulebasegame.debuggerapp
import net.torvald.terrarum.*
import net.torvald.terrarum.gameactors.ActorValue
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.console.Echo
import net.torvald.terrarum.console.SetAV
import net.torvald.terrarum.modulebasegame.console.SetAV
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.gameactors.ActorWithPhysics
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.modulebasegame.gameactors.ActorWithPhysics
import net.torvald.terrarum.worlddrawer.FeaturesDrawer
import java.awt.BorderLayout
import java.awt.GridLayout
@@ -67,7 +68,7 @@ class ActorValueTracker constructor() : JFrame() {
"${actor!!.referenceID};" +
"${modavInputKey.text};" +
"${modavInputValue.text}"
).split(';').toTypedArray())
).split(';').toTypedArray())
}
}
})
@@ -83,7 +84,7 @@ class ActorValueTracker constructor() : JFrame() {
buttonChangeActor.addMouseListener(object : MouseAdapter() {
override fun mousePressed(e: MouseEvent?) {
if (actorIDField.text.toLowerCase() == "player") {
actor = Terrarum.ingame!!.player
actor = (Terrarum.ingame!! as Ingame).player
actorValue = actor!!.actorValue
}
else if (actorIDField.text.isNotBlank()) {

View File

@@ -1,4 +1,4 @@
package net.torvald.terrarum.gameactors
package net.torvald.terrarum.modulebasegame.gameactors
/**
* See [res/raw/Creature_raw_doc.md] for information about raw.
@@ -103,4 +103,9 @@ object AVKey {
* Or for NPCs, how long it has been waiting for next move
*/
const val __ACTION_TIMER = "__actiontimer"
const val HEALTH = "health"
const val MAGIC = "magic"
}

View File

@@ -1,15 +1,21 @@
package net.torvald.terrarum.gameactors
package net.torvald.terrarum.modulebasegame.gameactors
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.jme3.math.FastMath
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.bipolarClamp
import net.torvald.terrarum.gameactors.Controllable
import net.torvald.terrarum.gameactors.Factionable
import net.torvald.terrarum.gameactors.Hitbox
import net.torvald.terrarum.gameactors.Luminous
import net.torvald.terrarum.gameactors.faction.Faction
import net.torvald.terrarum.gameworld.GameWorld
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.itemproperties.Material
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarum.ui.UIInventoryFull
import net.torvald.terrarum.modulebasegame.ui.UIInventoryFull
import net.torvald.terrarum.worlddrawer.LightmapRenderer
import org.dyn4j.geometry.Vector2
import java.util.*
@@ -143,7 +149,7 @@ open class ActorHumanoid(
protected var isRightDown = false
protected var isJumpDown = false
protected inline val isGamer: Boolean
get() = if (Terrarum.ingame == null) false else this == Terrarum.ingame!!.player
get() = if (Terrarum.ingame == null) false else this == (Terrarum.ingame!! as Ingame).player
private val nullItem = object : GameItem() {
@@ -487,10 +493,10 @@ open class ActorHumanoid(
get() {
// compare all the affecting variables
if (oldMAX_JUMP_LENGTH == MAX_JUMP_LENGTH &&
oldJUMPPOWER == actorValue.getAsDouble(AVKey.JUMPPOWER)!! &&
oldJUMPPOWERBUFF == actorValue.getAsDouble(AVKey.JUMPPOWERBUFF) ?: 1.0 &&
oldScale == scale &&
oldDragCoefficient == dragCoefficient) {
oldJUMPPOWER == actorValue.getAsDouble(AVKey.JUMPPOWER)!! &&
oldJUMPPOWERBUFF == actorValue.getAsDouble(AVKey.JUMPPOWERBUFF) ?: 1.0 &&
oldScale == scale &&
oldDragCoefficient == dragCoefficient) {
return field
}
// if variables are changed, get new value, store it and return it
@@ -590,7 +596,7 @@ open class ActorHumanoid(
// force update inventory UI
try {
(Terrarum.ingame!!.uiInventoryPlayer as UIInventoryFull).rebuildList()
((Terrarum.ingame!! as Ingame).uiInventoryPlayer as UIInventoryFull).rebuildList()
}
catch (LateInitMyArse: kotlin.UninitializedPropertyAccessException) { }
}

View File

@@ -1,13 +1,14 @@
package net.torvald.terrarum.gameactors
package net.torvald.terrarum.modulebasegame.gameactors
import com.badlogic.gdx.Gdx
import net.torvald.terrarum.Terrarum
import net.torvald.terrarum.blockproperties.BlockCodex
import net.torvald.terrarum.gameactors.Actor
import net.torvald.terrarum.itemproperties.GameItem
import net.torvald.terrarum.itemproperties.ItemCodex
import net.torvald.terrarum.itemproperties.ItemCodex.ITEM_DYNAMIC
import net.torvald.terrarum.itemproperties.ItemCodex.ITEM_WALLS
import net.torvald.terrarum.itemproperties.ItemID
import net.torvald.terrarum.modulebasegame.Ingame
import java.util.*
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
@@ -61,8 +62,8 @@ class ActorInventory(val actor: Pocketed, var maxCapacity: Int, var capacityMode
"These commands are NOT INTERCHANGEABLE; they handle things differently according to the context.")
if (item.originalID == Player.PLAYER_REF_ID || item.originalID == 0x51621D) // do not delete this magic
throw IllegalArgumentException("Attempted to put human player into the inventory.")
if ((Terrarum.ingame?.gameFullyLoaded ?: false) &&
(item.originalID == Terrarum.ingame?.player?.referenceID))
if (((Terrarum.ingame as? Ingame)?.gameFullyLoaded ?: false) &&
(item.originalID == (Terrarum.ingame as? Ingame)?.player?.referenceID))
throw IllegalArgumentException("Attempted to put active player into the inventory.")
if ((!item.stackable || item.dynamicID in ITEM_DYNAMIC) && count > 1)
throw IllegalArgumentException("Attempting to adding stack of item but the item is not stackable; item: $item, count: $count")

View File

@@ -1,9 +1,8 @@
package net.torvald.terrarum.gameactors
package net.torvald.terrarum.modulebasegame.gameactors
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.jme3.math.FastMath
import net.torvald.point.Point2d
import net.torvald.terrarum.*
import net.torvald.terrarum.gameworld.GameWorld
@@ -13,16 +12,18 @@ import net.torvald.spriteanimation.SpriteAnimation
import net.torvald.terrarum.worlddrawer.WorldCamera
import net.torvald.terrarum.blockproperties.Block
import net.torvald.terrarum.blockproperties.BlockProp
import net.torvald.terrarum.gameactors.ActorWithBody
import net.torvald.terrarum.gameactors.Controllable
import net.torvald.terrarum.gameactors.Hitbox
import net.torvald.terrarum.gamecontroller.KeyToggler
import net.torvald.terrarum.gameworld.BlockAddress
import net.torvald.terrarum.modulebasegame.Ingame
import net.torvald.terrarum.realestate.LandUtil
import net.torvald.terrarumsansbitmap.gdx.TextureRegionPack
import org.dyn4j.geometry.Vector2
import java.util.*
typealias Second = Float
/**
* Base class for every actor that has animated sprites. This includes furnishings, paintings, gadgets, etc.
* Also has all the usePhysics
@@ -105,7 +106,7 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
/** Apparent scale. Use "avBaseScale" for base scale */
var scale: Double
inline get() = (actorValue.getAsDouble(AVKey.SCALE) ?: 1.0) *
(actorValue.getAsDouble(AVKey.SCALEBUFF) ?: 1.0)
(actorValue.getAsDouble(AVKey.SCALEBUFF) ?: 1.0)
set(value) {
val scaleDelta = value - scale
actorValue[AVKey.SCALE] = value / (actorValue.getAsDouble(AVKey.SCALEBUFF) ?: 1.0)
@@ -675,15 +676,15 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
// points to the EDGE of the tile in world dimension (don't use this directly to get tilewise coord!!)
val offendingTileWorldX = if (selfCollisionStatus in listOf(6, 12))
newHitbox.endX.div(TILE_SIZE).floor() * TILE_SIZE - 0.00001
newHitbox.endX.div(TILE_SIZE).floor() * TILE_SIZE - 0.00001
else
newHitbox.startX.div(TILE_SIZE).ceil() * TILE_SIZE
newHitbox.startX.div(TILE_SIZE).ceil() * TILE_SIZE
// points to the EDGE of the tile in world dimension (don't use this directly to get tilewise coord!!)
val offendingTileWorldY = if (selfCollisionStatus in listOf(3, 6))
newHitbox.endY.div(TILE_SIZE).floor() * TILE_SIZE - 0.00001
newHitbox.endY.div(TILE_SIZE).floor() * TILE_SIZE - 0.00001
else
newHitbox.startY.div(TILE_SIZE).ceil() * TILE_SIZE
newHitbox.startY.div(TILE_SIZE).ceil() * TILE_SIZE
val offendingHitboxPointX = if (selfCollisionStatus in listOf(6, 12))
newHitbox.endX
@@ -912,23 +913,23 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
val tileY: Int
if (side == COLLIDING_LEFT) {
tileX = div16TruncateToMapWidth(hitbox.hitboxStart.x.roundInt()
+ i + translateX)
+ i + translateX)
tileY = div16TruncateToMapHeight(hitbox.hitboxEnd.y.roundInt() + translateY)
}
else if (side == COLLIDING_TOP) {
tileX = div16TruncateToMapWidth(hitbox.hitboxStart.x.roundInt()
+ i + translateX)
+ i + translateX)
tileY = div16TruncateToMapHeight(hitbox.hitboxStart.y.roundInt() + translateY)
}
else if (side == COLLIDING_RIGHT) {
tileX = div16TruncateToMapWidth(hitbox.hitboxEnd.x.roundInt() + translateX)
tileY = div16TruncateToMapHeight(hitbox.hitboxStart.y.roundInt()
+ i + translateY)
+ i + translateY)
}
else if (side == COLLIDING_LEFT) {
tileX = div16TruncateToMapWidth(hitbox.hitboxStart.x.roundInt() + translateX)
tileY = div16TruncateToMapHeight(hitbox.hitboxStart.y.roundInt()
+ i + translateY)
+ i + translateY)
}
else {
throw IllegalArgumentException(side.toString() + ": Wrong side input")
@@ -1324,7 +1325,7 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
}
private fun forEachOccupyingTilePos(hitbox: Hitbox, consumer: (BlockAddress) -> Unit) {
val newTilewiseHitbox = Hitbox.fromTwoPoints(
val newTilewiseHitbox = Hitbox.fromTwoPoints(
hitbox.startX.div(TILE_SIZE).floor(),
hitbox.startY.div(TILE_SIZE).floor(),
hitbox.endX.minus(0.00001).div(TILE_SIZE).floor(),
@@ -1410,8 +1411,8 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
private fun div16TruncateToMapWidth(x: Int): Int {
if (x < 0)
return 0
else if (x >= Terrarum.ingame!!.world.width shl 4)
return Terrarum.ingame!!.world.width - 1
else if (x >= (Terrarum.ingame!! as Ingame).world.width shl 4)
return (Terrarum.ingame!! as Ingame).world.width - 1
else
return x and 0x7FFFFFFF shr 4
}
@@ -1419,8 +1420,8 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
private fun div16TruncateToMapHeight(y: Int): Int {
if (y < 0)
return 0
else if (y >= Terrarum.ingame!!.world.height shl 4)
return Terrarum.ingame!!.world.height - 1
else if (y >= (Terrarum.ingame!! as Ingame).world.height shl 4)
return (Terrarum.ingame!! as Ingame).world.height - 1
else
return y and 0x7FFFFFFF shr 4
}
@@ -1478,55 +1479,3 @@ open class ActorWithPhysics(val world: GameWorld, renderOrder: RenderOrder, val
}
}
inline fun Int.sqr(): Int = this * this
inline fun Double.floorInt() = Math.floor(this).toInt()
inline fun Float.floorInt() = FastMath.floor(this)
inline fun Float.floor() = FastMath.floor(this).toFloat()
inline fun Double.ceilInt() = Math.ceil(this).toInt()
inline fun Float.ceil(): Float = FastMath.ceil(this).toFloat()
inline fun Float.ceilInt() = FastMath.ceil(this)
inline fun Double.round() = Math.round(this).toDouble()
inline fun Double.floor() = Math.floor(this)
inline fun Double.ceil() = this.floor() + 1.0
inline fun Double.roundInt(): Int = Math.round(this).toInt()
inline fun Float.roundInt(): Int = Math.round(this)
inline fun Double.abs() = Math.abs(this)
inline fun Double.sqr() = this * this
inline fun Double.sqrt() = Math.sqrt(this)
inline fun Float.sqrt() = FastMath.sqrt(this)
inline fun Int.abs() = if (this < 0) -this else this
fun Double.bipolarClamp(limit: Double) =
if (this > 0 && this > limit) limit
else if (this < 0 && this < -limit) -limit
else this
fun absMax(left: Double, right: Double): Double {
if (left > 0 && right > 0)
if (left > right) return left
else return right
else if (left < 0 && right < 0)
if (left < right) return left
else return right
else {
val absL = left.abs()
val absR = right.abs()
if (absL > absR) return left
else return right
}
}
fun Double.magnSqr() = if (this >= 0.0) this.sqr() else -this.sqr()
fun Double.sign() = if (this > 0.0) 1.0 else if (this < 0.0) -1.0 else 0.0
fun interpolateLinear(scale: Double, startValue: Double, endValue: Double): Double {
if (startValue == endValue) {
return startValue
}
if (scale <= 0.0) {
return startValue
}
if (scale >= 1.0) {
return endValue
}
return (1.0 - scale) * startValue + scale * endValue
}

View File

@@ -1,4 +1,4 @@
package net.torvald.terrarum.gameactors
package net.torvald.terrarum.modulebasegame.gameactors
import net.torvald.terrarum.itemproperties.GameItem

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