Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 9 additions & 45 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,60 +3,26 @@ name: Build Lambda
on:
push:
branches:
- '**'
- 'master'
pull_request:

jobs:
check-runner:
name: Check Runner Availability
runs-on: ubuntu-latest

outputs:
runner-label: ${{ steps.set-runner.outputs.runner-label }}

steps:
- name: Set runner
id: set-runner
run: |
runners=$(curl -v -s -H "Accept: application/vnd.github+json" -H "Authorization: token ${{ secrets.REPO_ACCESS_TOKEN }}" "https://api.github.com/repos/${{ github.repository }}/actions/runners" --http1.1)
if [ $? -ne 0 ]; then
echo "Error: Failed to fetch runners from GitHub API" >&2
exit 1
fi

runners_count=$(echo "$runners" | jq '.runners | length')
if [ "$runners_count" -eq 0 ]; then
echo "No runners available or failed to retrieve runners." >&2
echo "runner-label=ubuntu-latest" >> $GITHUB_OUTPUT
exit 0
fi

available=$(echo "$runners" | jq '.runners[] | select(.status == "online" and .busy == false and .labels[] .name == "self-hosted")')
if [ $? -ne 0 ]; then
echo "Error: Failed to parse JSON response" >&2
exit 1
fi

if [ -n "$available" ]; then
echo "runner-label=lambda-linux-runner" >> $GITHUB_OUTPUT
else
echo "runner-label=ubuntu-latest" >> $GITHUB_OUTPUT
fi
build:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

needs: check-runner
runs-on: ${{ needs.check-runner.outputs.runner-label }}

name: Build Lambda
runs-on: ubuntu-latest

permissions:
contents: write

env:
SEGMENT_DOWNLOAD_TIMEOUT_MINS: '5'
steps:
- name: Checkout Repository
uses: actions/checkout@v4.1.1
uses: actions/checkout@v4

- name: Set current date as env variable
run: echo "DATE=$(date +'%Y-%m-%dT%H:%M:%S')" >> $GITHUB_ENV
Expand All @@ -65,11 +31,11 @@ jobs:
id: vars
run: echo "COMMIT_HASH=$(git rev-parse --short HEAD)" >> $GITHUB_ENV

- name: Set-Up JDK 17
- name: Set-Up JDK
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '17'
java-version: '21'
architecture: x64
cache: 'gradle'

Expand All @@ -81,7 +47,7 @@ jobs:
all: true

- name: Build Lambda
run: ./gradlew build
run: ./gradlew build --no-daemon

- name: Rename Files with Commit Hash
run: |
Expand Down Expand Up @@ -111,8 +77,6 @@ jobs:
### [Lambda Forge ${{ steps.all.outputs.modVersion }} ${{ steps.all.outputs.minecraftVersion }} (${{ env.COMMIT_HASH }})](https://r2-bucket.edouard127.christmas/${{ env.DATE }}-${{ env.COMMIT_HASH }}/lambda-forge-${{ steps.all.outputs.modVersion }}+${{ steps.all.outputs.minecraftVersion }}-${{ env.COMMIT_HASH }}.jar)

#### [API (Developer Dependency)](https://r2-bucket.edouard127.christmas/${{ env.DATE }}-${{ env.COMMIT_HASH }}/lambda-api-${{ steps.all.outputs.modVersion }}+${{ steps.all.outputs.minecraftVersion }}-${{ env.COMMIT_HASH }}.jar)

**Runner:** \`${{ needs.check-runner.outputs.runner-label }}\`
EOF

- name: Failover Upload
Expand Down
20 changes: 20 additions & 0 deletions common/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ val kotlinxCoroutinesVersion: String by project
val discordIPCVersion: String by project
val fuelVersion: String by project
val resultVersion: String by project
val mockitoKotlin: String by project
val mockitoInline: String by project
val mockkVersion: String by project

base.archivesName = "${base.archivesName.get()}-api"

Expand Down Expand Up @@ -57,6 +60,10 @@ dependencies {

// Baritone
modImplementation("baritone-api:baritone-unoptimized-fabric:1.10.2") { isTransitive = false }
testImplementation(kotlin("test"))
testImplementation("org.mockito.kotlin:mockito-kotlin:$mockitoKotlin")
testImplementation("org.mockito:mockito-inline:$mockitoInline")
testImplementation("io.mockk:mockk:${mockkVersion}")
}

tasks {
Expand All @@ -66,5 +73,18 @@ tasks {

test {
useJUnitPlatform()
jvmArgs("-XX:+EnableDynamicAgentLoading", "-Xshare:off")
}
}

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "17"
}
}

subprojects {
tasks.named("build") {
dependsOn("test")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ object PacketLimiter : Module(
) {
private var packetQueue = LimitedDecayQueue<PacketEvent.Send.Pre>(99, 1000)
private val limit by setting("Limit", 99, 1..100, 1, "The maximum amount of packets to send per given time interval", unit = " packets")
.onValueChange { _, to -> packetQueue.setMaxSize(to) }
.onValueChange { _, to -> packetQueue.setSizeLimit(to) }

private val interval by setting("Duration", 1000L, 1L..1000L, 50L, "The interval / duration in milliseconds to limit packets for", unit = " ms")
.onValueChange { _, to -> packetQueue.setDecayTime(to) }
Expand Down
6 changes: 3 additions & 3 deletions common/src/main/kotlin/com/lambda/task/Task.kt
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ typealias TaskGeneratorOrNull<R> = SafeContext.(R) -> Task<*>?
typealias TaskGeneratorUnit<R> = SafeContext.(R) -> Unit

abstract class Task<Result> : Nameable, Muteable {
private var parent: Task<*>? = null
private val subTasks = mutableListOf<Task<*>>()
private var state = State.INIT
var parent: Task<*>? = null
val subTasks = mutableListOf<Task<*>>()
var state = State.INIT
override val isMuted: Boolean get() = state == State.PAUSED || state == State.INIT
var age = 0
private val depth: Int get() = parent?.depth?.plus(1) ?: 0
Expand Down
16 changes: 8 additions & 8 deletions common/src/main/kotlin/com/lambda/task/tasks/OpenContainer.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ class OpenContainer @Ta5kBuilder constructor(
private val interact: InteractionConfig = TaskFlowModule.interact,
private val sides: Set<Direction> = Direction.entries.toSet(),
) : Task<ScreenHandler>() {
override val name get() = "${state.description(inScope)} at ${blockPos.toShortString()}"
override val name get() = "${containerState.description(inScope)} at ${blockPos.toShortString()}"

private var screenHandler: ScreenHandler? = null
private var state = State.SCOPING
private var containerState = State.SCOPING
private var inScope = 0

enum class State {
Expand All @@ -57,39 +57,39 @@ class OpenContainer @Ta5kBuilder constructor(

init {
listen<InventoryEvent.Open> {
if (state != State.OPENING) return@listen
if (containerState != State.OPENING) return@listen

screenHandler = it.screenHandler
state = State.SLOT_LOADING
containerState = State.SLOT_LOADING

if (!waitForSlotLoad) success(it.screenHandler)
}

listen<InventoryEvent.Close> {
if (screenHandler != it.screenHandler) return@listen

state = State.SCOPING
containerState = State.SCOPING
screenHandler = null
}

listen<InventoryEvent.FullUpdate> {
if (state != State.SLOT_LOADING) return@listen
if (containerState != State.SLOT_LOADING) return@listen

screenHandler?.let {
success(it)
}
}

listen<TickEvent.Pre> {
if (state != State.SCOPING) return@listen
if (containerState != State.SCOPING) return@listen

val target = lookAtBlock(blockPos, sides, config = interact)
if (rotate && !target.requestBy(rotation).done) return@listen

val hitResult = target.hit?.hitIfValid()?.blockResult ?: return@listen
interaction.interactBlock(player, Hand.MAIN_HAND, hitResult)

state = State.OPENING
containerState = State.OPENING
}
}
}
28 changes: 13 additions & 15 deletions common/src/main/kotlin/com/lambda/util/VarIntIterator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ package com.lambda.util

class VarIntIterator(
private val bytes: ByteArray,
private val bitsPerEntry: Int = 7,
private val maxGroups: Int = 5,
) : Iterator<Int> {
private var index: Int = 0

Expand All @@ -31,23 +29,23 @@ class VarIntIterator(
throw NoSuchElementException("No more elements to read")

var value = 0
var bitsRead = 0
var size = 0

val groupMask = (1 shl bitsPerEntry) - 1
val continuationBit = 1 shl bitsPerEntry

var b: Byte
do {
if (index >= bytes.size)
throw NoSuchElementException("Unexpected end of byte array while reading VarInt")

b = bytes[index++]
value = value or ((b.toInt() and groupMask) shl bitsRead)
bitsRead += bitsPerEntry
val b = bytes[index++].toInt()
value = value or ((b and SEGMENT_BIT) shl (size++ * 7))

require(bitsRead <= bitsPerEntry * maxGroups) { "VarInt size cannot exceed $maxGroups bytes" }
} while ((b.toInt() and continuationBit) != 0)
if (size > 5) throw IllegalArgumentException("VarInt size cannot exceed 5 bytes")
} while ((b and CONTINUE_BIT) != 0)

return value
}

companion object {
const val SEGMENT_BIT = 127
const val CONTINUE_BIT = 128
}
}

inline fun ByteArray.varIterator(block: (Int) -> Unit) =
VarIntIterator(this).forEach(block)
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,17 @@ class LimitedDecayQueue<E>(
* Updates the maximum allowed size for the queue and triggers a cleanup operation
* to remove elements exceeding the new size or falling outside the allowed time interval.
*
* Elements starting from the head will be removed.
*
* @param newSize The new maximum size for the queue. Must be a non-negative integer.
*/
fun setMaxSize(newSize: Int) {
fun setSizeLimit(newSize: Int) {
sizeLimit = newSize
cleanUp()

while (queue.size > newSize) {
queue.poll()
}
}

/**
Expand All @@ -131,4 +137,4 @@ class LimitedDecayQueue<E>(
onDecay(queue.poll().first)
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package com.lambda.util.extension
import com.lambda.Lambda.mc
import com.lambda.util.VarIntIterator
import com.lambda.util.math.MathUtils.logCap
import com.lambda.util.varIterator
import com.lambda.util.world.FastVector
import com.lambda.util.world.fastVectorOf
import com.lambda.util.world.x
Expand Down Expand Up @@ -117,8 +118,8 @@ private fun StructureTemplate.readSpongeV1OrException(

val newBlocks = NbtList()
var blockIndex = 0
VarIntIterator(nbt.getByteArray("BlockData"))
.forEach { blockId ->
nbt.getByteArray("BlockData")
.varIterator { blockId ->
val blockpos = positionFromIndex(width, length, blockIndex++)

newBlocks.add(NbtCompound().apply {
Expand Down
2 changes: 2 additions & 0 deletions common/src/main/kotlin/com/lambda/util/math/MathUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ object MathUtils {
private const val PI_FLOAT = 3.141593f

inline val Int.sq: Int get() = this * this
inline val Float.sq: Float get() = this * this
inline val Double.sq: Double get() = this * this

fun Float.toRadian() = this / 180.0f * PI_FLOAT
fun Double.toRadian() = this / 180.0 * PI
Expand Down
6 changes: 3 additions & 3 deletions common/src/main/kotlin/com/lambda/util/math/Vectors.kt
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ infix operator fun Vec3d.times(other: Int): Vec3d = multiply(other.toDouble())

infix operator fun Vec3d.div(other: Vec3d): Vec3d = multiply(1.0 / other.x, 1.0 / other.y, 1.0 / other.z)
infix operator fun Vec3d.div(other: Vec3i): Vec3d = Vec3d(x / other.x, y / other.y, z / other.z)
infix operator fun Vec3d.div(other: Double): Vec3d = times(1 / other)
infix operator fun Vec3d.div(other: Float): Vec3d = times(1 / other)
infix operator fun Vec3d.div(other: Int): Vec3d = times(1 / other)
infix operator fun Vec3d.div(other: Double): Vec3d = times(1.0 / other)
infix operator fun Vec3d.div(other: Float): Vec3d = times(1.0 / other)
infix operator fun Vec3d.div(other: Int): Vec3d = times(1.0 / other)

/* Vec3i */
val Vec3i.vec3d get() =
Expand Down
4 changes: 2 additions & 2 deletions common/src/main/kotlin/com/lambda/util/world/Position.kt
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,12 @@ infix fun FastVector.div(scalar: Double): FastVector =
/**
* Modulo the position by the given scalar.
*/
infix fun FastVector.mod(scalar: Int): FastVector = fastVectorOf(x % scalar, y % scalar, z % scalar)
infix fun FastVector.remainder(scalar: Int): FastVector = fastVectorOf(x % scalar, y % scalar, z % scalar)

/**
* Modulo the position by the given scalar.
*/
infix fun FastVector.mod(scalar: Double): FastVector =
infix fun FastVector.remainder(scalar: Double): FastVector =
fastVectorOf((x % scalar).toLong(), (y % scalar).toLong(), (z % scalar).toLong())

/**
Expand Down
Loading
Loading