Skip to content

Commit

Permalink
some changes
Browse files Browse the repository at this point in the history
  • Loading branch information
GenerelSchwerz committed Mar 8, 2024
1 parent 268e25c commit 8762049
Show file tree
Hide file tree
Showing 14 changed files with 144 additions and 167 deletions.
84 changes: 38 additions & 46 deletions src/PathfinderHandling.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// @ts-nocheck
import { Bot, BotEvents } from 'mineflayer'
import { AStar as AAStar } from './abstract/algorithms/astar'
import { AStar, Path, PathProducer } from './mineflayer-specific/algs'
Expand Down Expand Up @@ -46,7 +47,6 @@ import { Task } from '@nxg-org/mineflayer-util-plugin'
import { reconstructPath } from './abstract/algorithms'
import { closestPointOnLineSegment, getScaffoldCount } from './utils'
import { World } from './mineflayer-specific/world/worldInterface'
import { InteractType } from './mineflayer-specific/movements/interactionUtils'

export interface PathfinderOptions {
partialPathProducer: boolean
Expand All @@ -58,7 +58,7 @@ const DEFAULT_PATHFINDER_OPTS: PathfinderOptions = {
partialPathLength: 50
}

const EMPTY_VEC = new Vec3(0, 0, 0)
// const EMPTY_VEC = new Vec3(0, 0, 0)

/**
* These are the default movement types and their respective executors.
Expand Down Expand Up @@ -109,10 +109,10 @@ interface PathGeneratorResult {
astarContext: AAStar<Move>
}

interface PerformOpts {
errorOnReset?: boolean
errorOnAbort?: boolean
}
// interface PerformOpts {
// errorOnReset?: boolean
// errorOnAbort?: boolean
// }

interface HandlerOpts {
world?: CacheSyncWorld
Expand Down Expand Up @@ -239,7 +239,7 @@ export class PathfinderHandler {
}

async interrupt (timeout = 1000, cancelCalculation = true, reasonStr?: ResetReason): Promise<void> {
console.log('INTERRUPT CALLED')
console.log('INTERRUPT CALLED')
if (this._currentProducer == null) return console.log('no producer')
this.abortCalculation = cancelCalculation

Expand Down Expand Up @@ -437,7 +437,7 @@ export class PathfinderHandler {

// utility for identifying where partial paths merge

async perform () {}
async perform (): Promise<void> {}

// path getting utilities

Expand Down Expand Up @@ -486,7 +486,7 @@ export class PathfinderHandler {
if (result.status === 'success') {
cleanup()
this.bot.emit('pathGenerated', result)
console.log('locality %', (MovementHandler.count / MovementHandler.totCount) * 100)
console.log('locality %', (MovementHandler.count / MovementHandler.totCount) * 100)
MovementHandler.count = 0
MovementHandler.totCount = 0
yield { result, astarContext }
Expand All @@ -495,7 +495,7 @@ export class PathfinderHandler {

if (this.abortCalculation) {
cleanup()
result.status === 'canceled'
result.status = 'canceled'
yield { result, astarContext }
return { result, astarContext }
}
Expand Down Expand Up @@ -570,7 +570,7 @@ export class PathfinderHandler {
await this.cleanupBot()
this.world.cleanup?.()

console.log('CLEANUP CALLED')
console.log('CLEANUP CALLED')

if (this.userAborted) this.bot.emit('goalAborted', goal)
else this.bot.emit('goalFinished', goal)
Expand All @@ -583,39 +583,37 @@ export class PathfinderHandler {
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
class Perform {
public currentIndex = 0
public curPath: Move[] = [];
public curPath: Move[] = []

constructor (private readonly bot: Bot, private readonly handler: PathfinderHandler, public readonly goal: goals.Goal) {}

async perform (): Promise<void> {
while (this.currentIndex < this.curPath.length) {
const move = this.curPath[this.currentIndex]
const executor = this.handler.movements.get(move.moveType.constructor as BuildableMoveProvider)
if (executor == null) throw new Error('No executor for move type.')

// this.handler.currentMove = move
// this.handler.currentExecutor = executor

try {
await executor.perform(move, this.currentIndex, this.curPath);
} catch (err) {
if (err instanceof AbortError) {
return
} else if (err instanceof ResetError) {
return
}else if (err instanceof CancelError) {
this.identRecover();
return
} else {
throw err
}
const move = this.curPath[this.currentIndex]
const executor = this.handler.movements.get(move.moveType.constructor as BuildableMoveProvider)
if (executor == null) throw new Error('No executor for move type.')

// this.handler.currentMove = move
// this.handler.currentExecutor = executor

try {
await executor.perform(move, this.currentIndex, this.curPath)
} catch (err) {
if (err instanceof AbortError) {
return
} else if (err instanceof ResetError) {
return
} else if (err instanceof CancelError) {
void this.identRecover()
return
} else {
throw err
}
}
}



}

async identRecover (): Promise<void> {}
Expand All @@ -632,9 +630,6 @@ class Perform {

// due to the nature of our partial paths, all new paths must be longer than the current path.
if (newPath.length < this.curPath.length) throw new Error('new path is shorter than current path')




for (let i = this.curPath.length - 1; i >= 0; i--) {
const move = this.curPath[i]
Expand All @@ -644,16 +639,13 @@ class Perform {

// if i is greater than current index, then merge is clean as we have not passed the overlap index.
if (i > this.currentIndex) {
// include current node
this.curPath = this.curPath.slice(0, i+1).concat(newPath.slice(1))
}
// we are already perfoming the move where overlap occurs.
else if (i == this.currentIndex) {
// include current node
this.curPath = this.curPath.slice(0, i + 1).concat(newPath.slice(1))
} else if (i === this.currentIndex) {
// we are already perfoming the move where overlap occurs.
if (this.curPath[i].exitPos.equals(newPath[0].entryPos)) this.curPath = this.curPath.slice(0, i).concat(newPath)
else throw new Error('overlap is not clean')
}
// TODO: handle
else if (i < this.currentIndex) throw new Error('overlap is not clean')
} else if (i < this.currentIndex) throw new Error('overlap is not clean')
}
}
}
50 changes: 22 additions & 28 deletions src/ThePathfinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
BuildableMoveProvider,
MovementHandler,
MovementOptions,
MovementSetup,
ExecutorMap,
MovementExecutor,
DEFAULT_MOVEMENT_OPTS
Expand All @@ -38,7 +37,7 @@ import {
IdleMovementExecutor
} from './mineflayer-specific/movements/movementExecutors'
import { DropDownOpt, ForwardJumpUpOpt, StraightAheadOpt } from './mineflayer-specific/post/optimizers'
import { BuildableOptimizer, OptimizationSetup, MovementOptimizer, OptimizationMap, Optimizer } from './mineflayer-specific/post'
import { BuildableOptimizer, MovementOptimizer, OptimizationMap, Optimizer } from './mineflayer-specific/post'
import { ContinuousPathProducer, PartialPathProducer } from './mineflayer-specific/pathProducers'
import { Block, HandlerOpts, ResetReason } from './types'
import { Task } from '@nxg-org/mineflayer-util-plugin'
Expand Down Expand Up @@ -113,9 +112,6 @@ interface PerformOpts {
errorOnAbort?: boolean
}




/**
* Eventually, I want all pathfinder logic entirely off thread.
*
Expand Down Expand Up @@ -240,7 +236,7 @@ export class ThePathfinder {
}

async interrupt (timeout = 1000, cancelCalculation = true, reasonStr?: ResetReason): Promise<void> {
console.log('INTERRUPT CALLED')
console.log('INTERRUPT CALLED')
if (this._currentProducer == null) return console.log('no producer')
this.abortCalculation = cancelCalculation

Expand Down Expand Up @@ -316,7 +312,7 @@ export class ThePathfinder {
if (place.vec.equals(pos)) {
switch (place.type) {
case 'solid':
console.log('if true, we are ignoring', block.boundingBox === 'block')
console.log('if true, we are ignoring', block.boundingBox === 'block')
return block.boundingBox === 'block'
case 'water':
return BlockInfo.waters.has(block.type)
Expand Down Expand Up @@ -485,7 +481,7 @@ export class ThePathfinder {
if (result.status === 'success') {
cleanup()
this.bot.emit('pathGenerated', result)
console.log('locality %', (MovementHandler.count / MovementHandler.totCount) * 100)
console.log('locality %', (MovementHandler.count / MovementHandler.totCount) * 100)
MovementHandler.count = 0
MovementHandler.totCount = 0
yield { result, astarContext }
Expand All @@ -494,7 +490,7 @@ export class ThePathfinder {

if (this.abortCalculation) {
cleanup()
result.status === 'canceled'
result.status = 'canceled'
yield { result, astarContext }
return { result, astarContext }
}
Expand Down Expand Up @@ -529,7 +525,7 @@ export class ThePathfinder {
* @param {goals.Goal | null} goal
*/
async goto (goal: goals.Goal, performOpts: PerformOpts = {}): Promise<void> {
console.log('GOTO CALLED')
console.log('GOTO CALLED')
if (goal == null) {
await this.cancel()
await this.executeTask.promise
Expand All @@ -538,7 +534,7 @@ export class ThePathfinder {
}

if (!this.executeTask.done) {
console.log('cancelling others')
console.log('cancelling others')
this.wantedGoal = goal
await this.cancel()
await this.executeTask.promise
Expand Down Expand Up @@ -567,7 +563,7 @@ export class ThePathfinder {
void this.cancel()
},
forAll: () => {
console.log('cleaned up')
console.log('cleaned up')
resolve()
}
})
Expand All @@ -576,14 +572,13 @@ export class ThePathfinder {
}

do {
let madeIt = false;
let madeIt = false
do {
setupWait()

console.log('reset I believe', doForever)
console.log('reset I believe', doForever)
let task: Promise<void> | null = null
let res1 = null


for await (const res of this.getPathTo(goal)) {
if (res.result.status !== 'success') {
Expand All @@ -605,11 +600,10 @@ export class ThePathfinder {
}
if (task === null) {
// technically, perform should keep track of the current index. So this *should* be fine.
task = this.perform(res1, goal)
task.then(() => {
task = this.perform(res1, goal).then(() => {
task = null
res1 = null
console.log('cleared task!')
console.log('cleared task!')
})
}
}
Expand All @@ -636,15 +630,15 @@ export class ThePathfinder {
}

if (this.resetReason == null) {
console.log('finished!', this.bot.entity.position, this.bot.listeners('entityMoved'), this.bot.listeners('entityGone'))
console.log('finished!', this.bot.entity.position, this.bot.listeners('entityMoved'), this.bot.listeners('entityGone'))
await this.cleanupBot()
manualCleanup()
setupWait()
madeIt = true
break
}

console.log('resetting!', this.resetReason, this.abortCalculation, this.userAborted)
console.log('resetting!', this.resetReason, this.abortCalculation, this.userAborted)
await this.cleanupBot()
manualCleanup()
}
Expand Down Expand Up @@ -699,7 +693,7 @@ export class ThePathfinder {
async perform (path: Path, goal: goals.Goal, entry = 0): Promise<void> {
if (entry > 10) throw new Error('Too many failures, exiting performing.')

console.log('ENTER PERFORM')
console.log('ENTER PERFORM')
let currentIndex = 0
const movementHandler = path.context.movementProvider as MovementHandler
const movements = movementHandler.getMovements()
Expand All @@ -725,14 +719,14 @@ export class ThePathfinder {

// if the movement has already been completed (another movement has already completed it), skip it.
if (executor.isAlreadyCompleted(move, tickCount, goal)) {
console.log('skipping', move.moveType.constructor.name, 'at index', currentIndex + 1, 'of', path.path.length)
console.log('skipping', move.moveType.constructor.name, 'at index', currentIndex + 1, 'of', path.path.length)

currentIndex++
continue
}

console.log('performing', move.moveType.constructor.name, 'at index', currentIndex + 1, 'of', path.path.length)
console.log(
console.log('performing', move.moveType.constructor.name, 'at index', currentIndex + 1, 'of', path.path.length)
console.log(
'toPlace',
move.toPlace.map((p) => p.vec),
'toBreak',
Expand Down Expand Up @@ -767,7 +761,7 @@ export class ThePathfinder {
}

currentIndex += adding as number
console.log('done with move', move.exitPos, this.bot.entity.position, this.bot.entity.position.distanceTo(move.exitPos))
console.log('done with move', move.exitPos, this.bot.entity.position, this.bot.entity.position.distanceTo(move.exitPos))
} catch (err) {
// immediately exit since we want to abort the entire path.
if (err instanceof AbortError) {
Expand All @@ -780,7 +774,7 @@ export class ThePathfinder {
// await this.cleanupBot()
break
} else if (err instanceof CancelError) {
console.log('canceled')
console.log('canceled')
// await this.cleanupBot()
// allow recovery if movement intentionall canceled.
// await this.recovery(move, path, goal, entry)
Expand All @@ -790,7 +784,7 @@ export class ThePathfinder {
}

await this.cleanupBot()
console.log('FINISHED PERFORM')
console.log('FINISHED PERFORM')
}

// TODO: implement recovery for any movement and goal.
Expand Down Expand Up @@ -876,7 +870,7 @@ export class ThePathfinder {
// this.bot.chat(this.world.getCacheSize())
this.world.cleanup?.()

console.log('CLEANUP CALLED')
console.log('CLEANUP CALLED')

if (this.userAborted) this.bot.emit('goalAborted', goal)
else this.bot.emit('goalFinished', goal)
Expand Down
2 changes: 1 addition & 1 deletion src/abstract/algorithms/astar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class AStar<Data extends PathData = PathData> implements Algorithm<Data>
// for debugging.
private lastAmt: number = 0
makeResult (status: PathStatus, node: PathNode<Data>): Path<Data, AStar<Data>> {
console.log(
console.log(
status,
// this.goal,
performance.now() - this.startTime,
Expand Down
Loading

0 comments on commit 8762049

Please sign in to comment.