Need help with hexagonal mathematics for optimization

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Inces

Hello.

I have created custom map_to_world , detect_neighbours_in_shape_matrix and get_next_hex_in_direction for haxagonal tilemap, using offset xz coordinates. It works really nice, however my AI function forces thousands of these operations at one moment, and they provoke severe lag spike. Most calls is from get_next_hex and map_to_world.

I am pretty sure some of You must be an expert in hex mathematics, since it is a popular tilemap medium. Can You show me the simplest code to achieve these functions ? These are my current non-optimal functions :

static func nexthex(start,dir):
	if dir == 0:
		#print("samedir")
		return start
	var backrow = 1-int(abs(start.z))%2
	var possibledirections = [Vector3(1,0,-1),Vector3(1,0,0),Vector3(1,0,1),Vector3(-1,0,1),Vector3(-1,0,0),Vector3(-1,0,-1)]
	var direction = possibledirections[dir-1] 
	if direction.x < 0:
		backrow = 1-backrow
	if direction.z == 0:
		backrow = 0
	var target = start  - Vector3(1*backrow,0,0) * sign(direction.x) + direction 
	return target  

static func map2world(cell):
	var cell_size = cell_size()
	var hexspace = hexspace()
	return Vector3(cell.x * cell_size.x *hexspace + int(cell.z)%2*cell_size.x*0.5,0,cell.z * cell_size.z * 0.75 * hexspace  ) + Vector3(cell_size.x  * 0.5,0,cell_size.z * 0.5)

cell_size() and hexspace() only return predefined values, no calculations inside them.
To be honest transferring cooridnates to offset coordinates i so confusing, that I no longer can remember what these modulo manipulations were exactly doing, despite my older comments.