Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee0cf0659d |
+120
-130
@@ -1,25 +1,25 @@
|
|||||||
extends RigidBody3D
|
extends RigidBody3D
|
||||||
# Initially I used a CharacterBody3D, however, I wanted the player to bounce off
|
# Initially I used a CharacterBody3D, however, I wanted the player to bounce off
|
||||||
# other objects in the environment and that would have required manual handling
|
# other objects in the environment and that would have required manual handling
|
||||||
# of collisions. So that's why we're using a RigidBody3D instead.
|
# of collisions. So that's why we're using a RigidBody3D instead.
|
||||||
|
|
||||||
const MOVE_SPEED := 8.0
|
const MOVE_SPEED := 8.0
|
||||||
const SPRINT_MOVE_SPEED :=13
|
const ACCELLERATION := 30.0
|
||||||
const ACCELLERATION := 30.0
|
const DECELLERATION := 40.0
|
||||||
const DECELLERATION := 40.0
|
const JUMP_SPEED := 4.0
|
||||||
const JUMP_SPEED := 4.0
|
const MAX_NUMBER_OF_JUMPS := 2
|
||||||
const MAX_NUMBER_OF_JUMPS := 2
|
|
||||||
const MIN_FOV := 10
|
const MIN_FOV := 10
|
||||||
const MAX_FOV := 180
|
const MAX_FOV := 180
|
||||||
const ZOOM_FACTOR := 1.1 # Zoom out when >1, in when < 1
|
const ZOOM_FACTOR := 1.1 # Zoom out when >1, in when < 1
|
||||||
var mouse_sensitivity := 0.005
|
var mouse_sensitivity := 0.005
|
||||||
var rotation_x := 0.0
|
var rotation_x := 0.0
|
||||||
var rotation_y := 0.0
|
var rotation_y := 0.0
|
||||||
var cameraMoveMode := false
|
var cameraMoveMode := false
|
||||||
var current_number_of_jumps := 0
|
var current_number_of_jumps := 0
|
||||||
var _pending_mouse_delta := Vector2.ZERO
|
var _pending_mouse_delta := Vector2.ZERO
|
||||||
var _last_move_forward := Vector3(0, 0, 1)
|
var _last_move_forward := Vector3(0, 0, 1)
|
||||||
var _last_move_right := Vector3(1, 0, 0)
|
var _last_move_right := Vector3(1, 0, 0)
|
||||||
var _camera_offset_local := Vector3.ZERO
|
var _camera_offset_local := Vector3.ZERO
|
||||||
var _camera_yaw := 0.0
|
var _camera_yaw := 0.0
|
||||||
var _camera_pitch := 0.0
|
var _camera_pitch := 0.0
|
||||||
@@ -37,42 +37,40 @@ var _jump_triggered := false
|
|||||||
@export var anim_idle_name := "Idle"
|
@export var anim_idle_name := "Idle"
|
||||||
@export var anim_walk_name := "Walk"
|
@export var anim_walk_name := "Walk"
|
||||||
@export var anim_jump_name := "Jump"
|
@export var anim_jump_name := "Jump"
|
||||||
@export var anim_run_name := "Run"
|
|
||||||
@export var anim_walk_speed_threshold := 0.25
|
@export var anim_walk_speed_threshold := 0.25
|
||||||
@export var anim_sprint_speed_threshold := 10.0
|
|
||||||
|
|
||||||
var jump_sound = preload("res://assets/audio/jump.ogg")
|
var jump_sound = preload("res://assets/audio/jump.ogg")
|
||||||
var audio_player = AudioStreamPlayer.new()
|
var audio_player = AudioStreamPlayer.new()
|
||||||
|
|
||||||
@export var camera_path: NodePath
|
@export var camera_path: NodePath
|
||||||
@onready var cam: Camera3D = get_node(camera_path) if camera_path != NodePath("") else null
|
@onready var cam: Camera3D = get_node(camera_path) if camera_path != NodePath("") else null
|
||||||
@export var phone_path: NodePath
|
@export var phone_path: NodePath
|
||||||
@onready var phone: CanvasLayer = get_node(phone_path) if phone_path != NodePath("") else null
|
@onready var phone: CanvasLayer = get_node(phone_path) if phone_path != NodePath("") else null
|
||||||
var phone_visible := false
|
var phone_visible := false
|
||||||
|
|
||||||
func _ready() -> void:
|
func _ready() -> void:
|
||||||
axis_lock_angular_x = true
|
axis_lock_angular_x = true
|
||||||
axis_lock_angular_z = true
|
axis_lock_angular_z = true
|
||||||
angular_damp = 6.0
|
angular_damp = 6.0
|
||||||
contact_monitor = true
|
contact_monitor = true
|
||||||
max_contacts_reported = 4
|
max_contacts_reported = 4
|
||||||
add_child(audio_player)
|
add_child(audio_player)
|
||||||
audio_player.stream = jump_sound
|
audio_player.stream = jump_sound
|
||||||
audio_player.volume_db = -20
|
audio_player.volume_db = -20
|
||||||
if cam:
|
if cam:
|
||||||
_camera_offset_local = cam.transform.origin
|
_camera_offset_local = cam.transform.origin
|
||||||
_camera_pitch = cam.rotation.x
|
_camera_pitch = cam.rotation.x
|
||||||
_camera_yaw = global_transform.basis.get_euler().y
|
_camera_yaw = global_transform.basis.get_euler().y
|
||||||
cam.set_as_top_level(true)
|
cam.set_as_top_level(true)
|
||||||
cam.global_position = global_position + (Basis(Vector3.UP, _camera_yaw) * _camera_offset_local)
|
cam.global_position = global_position + (Basis(Vector3.UP, _camera_yaw) * _camera_offset_local)
|
||||||
cam.global_rotation = Vector3(_camera_pitch, _camera_yaw, 0.0)
|
cam.global_rotation = Vector3(_camera_pitch, _camera_yaw, 0.0)
|
||||||
var move_basis := cam.global_transform.basis if cam else global_transform.basis
|
var move_basis := cam.global_transform.basis if cam else global_transform.basis
|
||||||
var forward := move_basis.z
|
var forward := move_basis.z
|
||||||
var right := move_basis.x
|
var right := move_basis.x
|
||||||
forward.y = 0.0
|
forward.y = 0.0
|
||||||
right.y = 0.0
|
right.y = 0.0
|
||||||
if forward.length() > 0.0001:
|
if forward.length() > 0.0001:
|
||||||
_last_move_forward = forward.normalized()
|
_last_move_forward = forward.normalized()
|
||||||
if right.length() > 0.0001:
|
if right.length() > 0.0001:
|
||||||
_last_move_right = right.normalized()
|
_last_move_right = right.normalized()
|
||||||
_vehicle_collision_layer = collision_layer
|
_vehicle_collision_layer = collision_layer
|
||||||
@@ -83,61 +81,56 @@ func _integrate_forces(state):
|
|||||||
linear_velocity = Vector3.ZERO
|
linear_velocity = Vector3.ZERO
|
||||||
return
|
return
|
||||||
if cameraMoveMode and _pending_mouse_delta != Vector2.ZERO:
|
if cameraMoveMode and _pending_mouse_delta != Vector2.ZERO:
|
||||||
rotation_x -= _pending_mouse_delta.y * mouse_sensitivity
|
rotation_x -= _pending_mouse_delta.y * mouse_sensitivity
|
||||||
rotation_y -= _pending_mouse_delta.x * mouse_sensitivity
|
rotation_y -= _pending_mouse_delta.x * mouse_sensitivity
|
||||||
rotation_x = clamp(rotation_x, deg_to_rad(-90), deg_to_rad(90)) # Prevent flipping
|
rotation_x = clamp(rotation_x, deg_to_rad(-90), deg_to_rad(90)) # Prevent flipping
|
||||||
_camera_pitch = rotation_x
|
_camera_pitch = rotation_x
|
||||||
rotation.y = rotation_y
|
rotation.y = rotation_y
|
||||||
_pending_mouse_delta = Vector2.ZERO
|
_pending_mouse_delta = Vector2.ZERO
|
||||||
|
|
||||||
# Input as 2D vector
|
# Input as 2D vector
|
||||||
var input2v := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
|
var input2v := Input.get_vector("ui_left", "ui_right", "ui_up", "ui_down")
|
||||||
|
|
||||||
if Input.is_action_just_pressed("player_phone"):
|
if Input.is_action_just_pressed("player_phone"):
|
||||||
phone_visible = !phone_visible
|
phone_visible = !phone_visible
|
||||||
if phone:
|
if phone:
|
||||||
phone.visible = phone_visible
|
phone.visible = phone_visible
|
||||||
|
|
||||||
# Camera based movement
|
# Camera based movement
|
||||||
var forward := Vector3.FORWARD * -1.0
|
var forward := Vector3.FORWARD * -1.0
|
||||||
var right := Vector3.RIGHT
|
var right := Vector3.RIGHT
|
||||||
if cam:
|
if cam:
|
||||||
forward = cam.global_transform.basis.z
|
forward = cam.global_transform.basis.z
|
||||||
right = cam.global_transform.basis.x
|
right = cam.global_transform.basis.x
|
||||||
# Project onto ground plane so looking up/down doesn't kill movement.
|
# Project onto ground plane so looking up/down doesn't kill movement.
|
||||||
forward.y = 0.0
|
forward.y = 0.0
|
||||||
right.y = 0.0
|
right.y = 0.0
|
||||||
if forward.length() > 0.0001:
|
if forward.length() > 0.0001:
|
||||||
forward = forward.normalized()
|
forward = forward.normalized()
|
||||||
_last_move_forward = forward
|
_last_move_forward = forward
|
||||||
else:
|
else:
|
||||||
forward = _last_move_forward
|
forward = _last_move_forward
|
||||||
if right.length() > 0.0001:
|
if right.length() > 0.0001:
|
||||||
right = right.normalized()
|
right = right.normalized()
|
||||||
_last_move_right = right
|
_last_move_right = right
|
||||||
else:
|
else:
|
||||||
right = _last_move_right
|
right = _last_move_right
|
||||||
|
|
||||||
var dir := (right * input2v.x + forward * input2v.y).normalized()
|
var dir := (right * input2v.x + forward * input2v.y).normalized()
|
||||||
|
var target_v := dir * MOVE_SPEED
|
||||||
var target_v := dir * MOVE_SPEED
|
|
||||||
|
var ax := ACCELLERATION if dir != Vector3.ZERO else DECELLERATION
|
||||||
# Sprinting
|
linear_velocity.x = move_toward(linear_velocity.x, target_v.x, ax * state.step)
|
||||||
if Input.is_key_pressed(KEY_SHIFT):
|
linear_velocity.z = move_toward(linear_velocity.z, target_v.z, ax * state.step)
|
||||||
target_v = dir * SPRINT_MOVE_SPEED
|
|
||||||
|
# Jump Logic
|
||||||
var ax := ACCELLERATION if dir != Vector3.ZERO else DECELLERATION
|
var on_floor = false
|
||||||
linear_velocity.x = move_toward(linear_velocity.x, target_v.x, ax * state.step)
|
for i in state.get_contact_count():
|
||||||
linear_velocity.z = move_toward(linear_velocity.z, target_v.z, ax * state.step)
|
var normal = state.get_contact_local_normal(i)
|
||||||
|
if normal.y > 0.5:
|
||||||
# Jump Logic
|
on_floor = true
|
||||||
var on_floor = false
|
break
|
||||||
for i in state.get_contact_count():
|
|
||||||
var normal = state.get_contact_local_normal(i)
|
|
||||||
if normal.y > 0.5:
|
|
||||||
on_floor = true
|
|
||||||
break
|
|
||||||
|
|
||||||
if Input.is_action_just_pressed("ui_accept") and (on_floor or current_number_of_jumps == 1):
|
if Input.is_action_just_pressed("ui_accept") and (on_floor or current_number_of_jumps == 1):
|
||||||
current_number_of_jumps = (current_number_of_jumps + 1) % 2
|
current_number_of_jumps = (current_number_of_jumps + 1) % 2
|
||||||
linear_velocity.y = JUMP_SPEED
|
linear_velocity.y = JUMP_SPEED
|
||||||
@@ -154,31 +147,31 @@ func _integrate_forces(state):
|
|||||||
|
|
||||||
_update_animation(on_floor, state.linear_velocity)
|
_update_animation(on_floor, state.linear_velocity)
|
||||||
_jump_triggered = false
|
_jump_triggered = false
|
||||||
|
|
||||||
func _input(event):
|
func _input(event):
|
||||||
if _in_vehicle:
|
if _in_vehicle:
|
||||||
return
|
return
|
||||||
if event is InputEventMouseButton:
|
if event is InputEventMouseButton:
|
||||||
if event.button_index == MOUSE_BUTTON_MIDDLE:
|
if event.button_index == MOUSE_BUTTON_MIDDLE:
|
||||||
if event.pressed:
|
if event.pressed:
|
||||||
cameraMoveMode = true
|
cameraMoveMode = true
|
||||||
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
|
Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
|
||||||
else:
|
else:
|
||||||
cameraMoveMode = false
|
cameraMoveMode = false
|
||||||
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
|
Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
|
||||||
|
|
||||||
if event is InputEventMouseMotion and cameraMoveMode:
|
if event is InputEventMouseMotion and cameraMoveMode:
|
||||||
_pending_mouse_delta += event.relative
|
_pending_mouse_delta += event.relative
|
||||||
|
|
||||||
if event is InputEventMouseButton and event.pressed:
|
if event is InputEventMouseButton and event.pressed:
|
||||||
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
|
if event.button_index == MOUSE_BUTTON_WHEEL_UP:
|
||||||
zoom_camera(1.0 / ZOOM_FACTOR) # Zoom in
|
zoom_camera(1.0 / ZOOM_FACTOR) # Zoom in
|
||||||
elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
|
elif event.button_index == MOUSE_BUTTON_WHEEL_DOWN:
|
||||||
zoom_camera(ZOOM_FACTOR) # Zoom out
|
zoom_camera(ZOOM_FACTOR) # Zoom out
|
||||||
|
|
||||||
if event.is_action_pressed("player_light"):
|
if event.is_action_pressed("player_light"):
|
||||||
_flashlight.visible = !_flashlight.visible
|
_flashlight.visible = !_flashlight.visible
|
||||||
|
|
||||||
func zoom_camera(factor):
|
func zoom_camera(factor):
|
||||||
var new_fov = cam.fov * factor
|
var new_fov = cam.fov * factor
|
||||||
cam.fov = clamp(new_fov, MIN_FOV, MAX_FOV)
|
cam.fov = clamp(new_fov, MIN_FOV, MAX_FOV)
|
||||||
@@ -195,10 +188,6 @@ func _update_animation(on_floor: bool, velocity: Vector3) -> void:
|
|||||||
if _anim_player.current_animation != anim_jump_name:
|
if _anim_player.current_animation != anim_jump_name:
|
||||||
_anim_player.play(anim_jump_name)
|
_anim_player.play(anim_jump_name)
|
||||||
return
|
return
|
||||||
if on_floor and horizontal_speed > anim_sprint_speed_threshold and _anim_player.has_animation(anim_run_name):
|
|
||||||
if _anim_player.current_animation != anim_walk_name:
|
|
||||||
_anim_player.play(anim_walk_name)
|
|
||||||
return
|
|
||||||
if horizontal_speed > anim_walk_speed_threshold and _anim_player.has_animation(anim_walk_name):
|
if horizontal_speed > anim_walk_speed_threshold and _anim_player.has_animation(anim_walk_name):
|
||||||
if _anim_player.current_animation != anim_walk_name:
|
if _anim_player.current_animation != anim_walk_name:
|
||||||
_anim_player.play(anim_walk_name)
|
_anim_player.play(anim_walk_name)
|
||||||
@@ -244,3 +233,4 @@ func exit_vehicle(exit_point: Node3D, vehicle_camera: Camera3D) -> void:
|
|||||||
vehicle_camera.current = false
|
vehicle_camera.current = false
|
||||||
if cam:
|
if cam:
|
||||||
cam.current = true
|
cam.current = true
|
||||||
|
|
||||||
|
|||||||
@@ -8,14 +8,16 @@ namespace CharacterApi.Controllers;
|
|||||||
|
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/[controller]")]
|
[Route("api/[controller]")]
|
||||||
public class CharactersController : ControllerBase
|
public class CharactersController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly CharacterStore _characters;
|
private readonly CharacterStore _characters;
|
||||||
|
private readonly LocationsClient _locations;
|
||||||
public CharactersController(CharacterStore characters)
|
|
||||||
{
|
public CharactersController(CharacterStore characters, LocationsClient locations)
|
||||||
_characters = characters;
|
{
|
||||||
}
|
_characters = characters;
|
||||||
|
_locations = locations;
|
||||||
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
[Authorize(Roles = "USER,SUPER")]
|
[Authorize(Roles = "USER,SUPER")]
|
||||||
@@ -54,17 +56,52 @@ public class CharactersController : ControllerBase
|
|||||||
|
|
||||||
[HttpDelete("{id}")]
|
[HttpDelete("{id}")]
|
||||||
[Authorize(Roles = "USER,SUPER")]
|
[Authorize(Roles = "USER,SUPER")]
|
||||||
public async Task<IActionResult> Delete(string id)
|
public async Task<IActionResult> Delete(string id)
|
||||||
{
|
{
|
||||||
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
if (string.IsNullOrWhiteSpace(userId))
|
if (string.IsNullOrWhiteSpace(userId))
|
||||||
return Unauthorized();
|
return Unauthorized();
|
||||||
|
|
||||||
var allowAnyOwner = User.IsInRole("SUPER");
|
var allowAnyOwner = User.IsInRole("SUPER");
|
||||||
var deleted = await _characters.DeleteForOwnerAsync(id, userId, allowAnyOwner);
|
var deleted = await _characters.DeleteForOwnerAsync(id, userId, allowAnyOwner);
|
||||||
if (!deleted)
|
if (!deleted)
|
||||||
return NotFound();
|
return NotFound();
|
||||||
|
|
||||||
return Ok("Deleted");
|
return Ok("Deleted");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
[HttpPut("{id}/move")]
|
||||||
|
[Authorize(Roles = "USER,SUPER")]
|
||||||
|
public async Task<IActionResult> Move(string id, [FromBody] MoveCharacterRequest req, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (req?.Coord is null)
|
||||||
|
return BadRequest("Coord required");
|
||||||
|
|
||||||
|
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||||
|
if (string.IsNullOrWhiteSpace(userId))
|
||||||
|
return Unauthorized();
|
||||||
|
|
||||||
|
var allowAnyOwner = User.IsInRole("SUPER");
|
||||||
|
var existing = await _characters.GetForOwnerByIdAsync(id, userId, allowAnyOwner);
|
||||||
|
if (existing is null)
|
||||||
|
return NotFound();
|
||||||
|
|
||||||
|
var presence = await _locations.UpdatePresenceAsync(id, req.Coord, ct);
|
||||||
|
if (!presence.Ok)
|
||||||
|
{
|
||||||
|
var message = string.IsNullOrWhiteSpace(presence.Body)
|
||||||
|
? "Location presence update failed"
|
||||||
|
: presence.Body;
|
||||||
|
return StatusCode((int)presence.Status, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
var updated = await _characters.UpdateCoordAsync(id, userId, allowAnyOwner, req.Coord);
|
||||||
|
if (!updated)
|
||||||
|
{
|
||||||
|
await _locations.UpdatePresenceAsync(id, existing.Coord, ct);
|
||||||
|
return StatusCode(500, "Failed to update character coord");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok("Moved");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,12 +4,21 @@ This service expects JSON request bodies for character creation and stores
|
|||||||
character documents in MongoDB.
|
character documents in MongoDB.
|
||||||
|
|
||||||
Inbound JSON documents
|
Inbound JSON documents
|
||||||
- CreateCharacterRequest (`POST /api/characters`)
|
- CreateCharacterRequest (`POST /api/characters`)
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"name": "string"
|
"name": "string"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
- MoveCharacterRequest (`PUT /api/characters/{id}/move`)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"coord": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Stored documents (MongoDB)
|
Stored documents (MongoDB)
|
||||||
- Character
|
- Character
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace CharacterApi.Models;
|
||||||
|
|
||||||
|
public class MoveCharacterRequest
|
||||||
|
{
|
||||||
|
public Coord? Coord { get; set; }
|
||||||
|
}
|
||||||
@@ -5,10 +5,15 @@ using Microsoft.OpenApi.Models;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
// DI
|
// DI
|
||||||
builder.Services.AddSingleton<CharacterStore>();
|
builder.Services.AddSingleton<CharacterStore>();
|
||||||
|
builder.Services.AddHttpClient<LocationsClient>(client =>
|
||||||
|
{
|
||||||
|
var baseUrl = builder.Configuration["LocationsApi:BaseUrl"] ?? "http://localhost:5002";
|
||||||
|
client.BaseAddress = new Uri(baseUrl);
|
||||||
|
});
|
||||||
|
|
||||||
// Swagger + JWT auth in Swagger
|
// Swagger + JWT auth in Swagger
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
|
|||||||
@@ -7,3 +7,4 @@ See `DOCUMENTS.md` for request payloads and stored document shapes.
|
|||||||
- `POST /api/characters` Create a character.
|
- `POST /api/characters` Create a character.
|
||||||
- `GET /api/characters` List characters for the current user.
|
- `GET /api/characters` List characters for the current user.
|
||||||
- `DELETE /api/characters/{id}` Delete a character owned by the current user.
|
- `DELETE /api/characters/{id}` Delete a character owned by the current user.
|
||||||
|
- `PUT /api/characters/{id}/move` Move a character to a new coord.
|
||||||
|
|||||||
@@ -21,14 +21,44 @@ public class CharacterStore
|
|||||||
|
|
||||||
public Task CreateAsync(Character character) => _col.InsertOneAsync(character);
|
public Task CreateAsync(Character character) => _col.InsertOneAsync(character);
|
||||||
|
|
||||||
public Task<List<Character>> GetForOwnerAsync(string ownerUserId) =>
|
public Task<List<Character>> GetForOwnerAsync(string ownerUserId) =>
|
||||||
_col.Find(c => c.OwnerUserId == ownerUserId).ToListAsync();
|
_col.Find(c => c.OwnerUserId == ownerUserId).ToListAsync();
|
||||||
|
|
||||||
public async Task<bool> DeleteForOwnerAsync(string id, string ownerUserId, bool allowAnyOwner)
|
public async Task<Character?> GetForOwnerByIdAsync(string id, string ownerUserId, bool allowAnyOwner)
|
||||||
{
|
{
|
||||||
var filter = Builders<Character>.Filter.Eq(c => c.Id, id);
|
var filter = Builders<Character>.Filter.Eq(c => c.Id, id);
|
||||||
if (!allowAnyOwner)
|
if (!allowAnyOwner)
|
||||||
{
|
{
|
||||||
|
filter = Builders<Character>.Filter.And(
|
||||||
|
filter,
|
||||||
|
Builders<Character>.Filter.Eq(c => c.OwnerUserId, ownerUserId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _col.Find(filter).FirstOrDefaultAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> UpdateCoordAsync(string id, string ownerUserId, bool allowAnyOwner, Coord coord)
|
||||||
|
{
|
||||||
|
var filter = Builders<Character>.Filter.Eq(c => c.Id, id);
|
||||||
|
if (!allowAnyOwner)
|
||||||
|
{
|
||||||
|
filter = Builders<Character>.Filter.And(
|
||||||
|
filter,
|
||||||
|
Builders<Character>.Filter.Eq(c => c.OwnerUserId, ownerUserId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var update = Builders<Character>.Update.Set(c => c.Coord, coord);
|
||||||
|
var result = await _col.UpdateOneAsync(filter, update);
|
||||||
|
return result.ModifiedCount > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteForOwnerAsync(string id, string ownerUserId, bool allowAnyOwner)
|
||||||
|
{
|
||||||
|
var filter = Builders<Character>.Filter.Eq(c => c.Id, id);
|
||||||
|
if (!allowAnyOwner)
|
||||||
|
{
|
||||||
filter = Builders<Character>.Filter.And(
|
filter = Builders<Character>.Filter.And(
|
||||||
filter,
|
filter,
|
||||||
Builders<Character>.Filter.Eq(c => c.OwnerUserId, ownerUserId)
|
Builders<Character>.Filter.Eq(c => c.OwnerUserId, ownerUserId)
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
using CharacterApi.Models;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
|
||||||
|
namespace CharacterApi.Services;
|
||||||
|
|
||||||
|
public class LocationsClient
|
||||||
|
{
|
||||||
|
private readonly HttpClient _http;
|
||||||
|
private readonly string _internalKey;
|
||||||
|
|
||||||
|
public LocationsClient(HttpClient http, IConfiguration cfg)
|
||||||
|
{
|
||||||
|
_http = http;
|
||||||
|
_internalKey = cfg["LocationsApi:InternalKey"] ?? string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<(bool Ok, HttpStatusCode Status, string? Body)> UpdatePresenceAsync(
|
||||||
|
string characterId,
|
||||||
|
Coord coord,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Post, "api/locations/presence")
|
||||||
|
{
|
||||||
|
Content = JsonContent.Create(new { characterId, coord })
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(_internalKey))
|
||||||
|
request.Headers.TryAddWithoutValidation("X-Internal-Key", _internalKey);
|
||||||
|
|
||||||
|
using var response = await _http.SendAsync(request, ct);
|
||||||
|
var body = await response.Content.ReadAsStringAsync(ct);
|
||||||
|
return (response.IsSuccessStatusCode, response.StatusCode, body);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
|
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
|
||||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
"LocationsApi": { "BaseUrl": "http://localhost:5002", "InternalKey": "dev-internal-key" },
|
||||||
|
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||||
"Logging": { "LogLevel": { "Default": "Information" } }
|
"Logging": { "LogLevel": { "Default": "Information" } }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
|
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5001" } } },
|
||||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
"LocationsApi": { "BaseUrl": "http://localhost:5002", "InternalKey": "dev-internal-key" },
|
||||||
|
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,12 @@ namespace LocationsApi.Controllers;
|
|||||||
public class LocationsController : ControllerBase
|
public class LocationsController : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly LocationStore _locations;
|
private readonly LocationStore _locations;
|
||||||
|
private readonly IConfiguration _cfg;
|
||||||
|
|
||||||
public LocationsController(LocationStore locations)
|
public LocationsController(LocationStore locations, IConfiguration cfg)
|
||||||
{
|
{
|
||||||
_locations = locations;
|
_locations = locations;
|
||||||
|
_cfg = cfg;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
@@ -31,6 +33,7 @@ public class LocationsController : ControllerBase
|
|||||||
{
|
{
|
||||||
Name = req.Name.Trim(),
|
Name = req.Name.Trim(),
|
||||||
Coord = req.Coord,
|
Coord = req.Coord,
|
||||||
|
CharacterIds = new List<string>(),
|
||||||
CreatedUtc = DateTime.UtcNow
|
CreatedUtc = DateTime.UtcNow
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -85,4 +88,28 @@ public class LocationsController : ControllerBase
|
|||||||
|
|
||||||
return Ok("Updated");
|
return Ok("Updated");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost("presence")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public async Task<IActionResult> UpdatePresence([FromBody] UpdateLocationPresenceRequest req)
|
||||||
|
{
|
||||||
|
var internalKey = _cfg["Internal:Key"];
|
||||||
|
if (!string.IsNullOrWhiteSpace(internalKey))
|
||||||
|
{
|
||||||
|
if (!Request.Headers.TryGetValue("X-Internal-Key", out var provided) || provided != internalKey)
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(req.CharacterId))
|
||||||
|
return BadRequest("CharacterId required");
|
||||||
|
|
||||||
|
if (req.Coord is null)
|
||||||
|
return BadRequest("Coord required");
|
||||||
|
|
||||||
|
var updated = await _locations.UpdatePresenceAsync(req.CharacterId.Trim(), req.Coord);
|
||||||
|
if (!updated)
|
||||||
|
return NotFound("Location not found");
|
||||||
|
|
||||||
|
return Ok("Updated");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,16 @@ Inbound JSON documents
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
`coord` cannot be updated.
|
`coord` cannot be updated.
|
||||||
|
- UpdateLocationPresenceRequest (`POST /api/locations/presence`)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"characterId": "string",
|
||||||
|
"coord": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Stored documents (MongoDB)
|
Stored documents (MongoDB)
|
||||||
- Location
|
- Location
|
||||||
@@ -32,6 +42,7 @@ Stored documents (MongoDB)
|
|||||||
"x": 0,
|
"x": 0,
|
||||||
"y": 0
|
"y": 0
|
||||||
},
|
},
|
||||||
|
"characterIds": ["string"],
|
||||||
"createdUtc": "string (ISO-8601 datetime)"
|
"createdUtc": "string (ISO-8601 datetime)"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ public class Location
|
|||||||
[BsonElement("coord")]
|
[BsonElement("coord")]
|
||||||
public required Coord Coord { get; set; }
|
public required Coord Coord { get; set; }
|
||||||
|
|
||||||
|
[BsonElement("characterIds")]
|
||||||
|
public List<string> CharacterIds { get; set; } = new();
|
||||||
|
|
||||||
[BsonElement("createdUtc")]
|
[BsonElement("createdUtc")]
|
||||||
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
|
public DateTime CreatedUtc { get; set; } = DateTime.UtcNow;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LocationsApi.Models;
|
||||||
|
|
||||||
|
public class UpdateLocationPresenceRequest
|
||||||
|
{
|
||||||
|
public string CharacterId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public Coord? Coord { get; set; }
|
||||||
|
}
|
||||||
@@ -8,3 +8,4 @@ See `DOCUMENTS.md` for request payloads and stored document shapes.
|
|||||||
- `GET /api/locations` List all locations (SUPER only).
|
- `GET /api/locations` List all locations (SUPER only).
|
||||||
- `DELETE /api/locations/{id}` Delete a location (SUPER only).
|
- `DELETE /api/locations/{id}` Delete a location (SUPER only).
|
||||||
- `PUT /api/locations/{id}` Update a location name (SUPER only).
|
- `PUT /api/locations/{id}` Update a location name (SUPER only).
|
||||||
|
- `POST /api/locations/presence` Update which characters are present at a coord (internal).
|
||||||
|
|||||||
@@ -34,13 +34,13 @@ public class LocationStore
|
|||||||
{
|
{
|
||||||
"$jsonSchema", new BsonDocument
|
"$jsonSchema", new BsonDocument
|
||||||
{
|
{
|
||||||
{ "bsonType", "object" },
|
{ "bsonType", "object" },
|
||||||
{ "required", new BsonArray { "name", "coord", "createdUtc" } },
|
{ "required", new BsonArray { "name", "coord", "createdUtc" } },
|
||||||
{
|
{
|
||||||
"properties", new BsonDocument
|
"properties", new BsonDocument
|
||||||
{
|
{
|
||||||
{ "name", new BsonDocument { { "bsonType", "string" } } },
|
{ "name", new BsonDocument { { "bsonType", "string" } } },
|
||||||
{
|
{
|
||||||
"coord", new BsonDocument
|
"coord", new BsonDocument
|
||||||
{
|
{
|
||||||
{ "bsonType", "object" },
|
{ "bsonType", "object" },
|
||||||
@@ -51,14 +51,21 @@ public class LocationStore
|
|||||||
{ "x", new BsonDocument { { "bsonType", "int" } } },
|
{ "x", new BsonDocument { { "bsonType", "int" } } },
|
||||||
{ "y", new BsonDocument { { "bsonType", "int" } } }
|
{ "y", new BsonDocument { { "bsonType", "int" } } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{ "createdUtc", new BsonDocument { { "bsonType", "date" } } }
|
{
|
||||||
}
|
"characterIds", new BsonDocument
|
||||||
}
|
{
|
||||||
}
|
{ "bsonType", "array" },
|
||||||
}
|
{ "items", new BsonDocument { { "bsonType", "string" } } }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ "createdUtc", new BsonDocument { { "bsonType", "date" } } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var collections = db.ListCollectionNames().ToList();
|
var collections = db.ListCollectionNames().ToList();
|
||||||
@@ -95,13 +102,31 @@ public class LocationStore
|
|||||||
return result.DeletedCount > 0;
|
return result.DeletedCount > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> UpdateNameAsync(string id, string name)
|
public async Task<bool> UpdateNameAsync(string id, string name)
|
||||||
{
|
{
|
||||||
var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
|
var filter = Builders<Location>.Filter.Eq(l => l.Id, id);
|
||||||
var update = Builders<Location>.Update.Set(l => l.Name, name);
|
var update = Builders<Location>.Update.Set(l => l.Name, name);
|
||||||
var result = await _col.UpdateOneAsync(filter, update);
|
var result = await _col.UpdateOneAsync(filter, update);
|
||||||
return result.ModifiedCount > 0;
|
return result.ModifiedCount > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> UpdatePresenceAsync(string characterId, Coord coord)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(characterId))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var pullFilter = Builders<Location>.Filter.AnyEq(l => l.CharacterIds, characterId);
|
||||||
|
var pullUpdate = Builders<Location>.Update.Pull(l => l.CharacterIds, characterId);
|
||||||
|
await _col.UpdateManyAsync(pullFilter, pullUpdate);
|
||||||
|
|
||||||
|
var targetFilter = Builders<Location>.Filter.And(
|
||||||
|
Builders<Location>.Filter.Eq(l => l.Coord.X, coord.X),
|
||||||
|
Builders<Location>.Filter.Eq(l => l.Coord.Y, coord.Y)
|
||||||
|
);
|
||||||
|
var addUpdate = Builders<Location>.Update.AddToSet(l => l.CharacterIds, characterId);
|
||||||
|
var result = await _col.UpdateOneAsync(targetFilter, addUpdate);
|
||||||
|
return result.MatchedCount > 0;
|
||||||
|
}
|
||||||
|
|
||||||
private void EnsureOriginLocation()
|
private void EnsureOriginLocation()
|
||||||
{
|
{
|
||||||
@@ -113,12 +138,13 @@ public class LocationStore
|
|||||||
if (existing is not null)
|
if (existing is not null)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var origin = new Location
|
var origin = new Location
|
||||||
{
|
{
|
||||||
Name = "Origin",
|
Name = "Origin",
|
||||||
Coord = new Coord { X = 0, Y = 0 },
|
Coord = new Coord { X = 0, Y = 0 },
|
||||||
CreatedUtc = DateTime.UtcNow
|
CharacterIds = new List<string>(),
|
||||||
};
|
CreatedUtc = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5002" } } },
|
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5002" } } },
|
||||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||||
|
"Internal": { "Key": "dev-internal-key" },
|
||||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||||
"Logging": { "LogLevel": { "Default": "Information" } }
|
"Logging": { "LogLevel": { "Default": "Information" } }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5002" } } },
|
"Kestrel": { "Endpoints": { "Http": { "Url": "http://0.0.0.0:5002" } } },
|
||||||
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
"MongoDB": { "ConnectionString": "mongodb://192.168.86.50:27017", "DatabaseName": "promiscuity" },
|
||||||
|
"Internal": { "Key": "dev-internal-key" },
|
||||||
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
"Jwt": { "Key": "SuperUltraSecureJwtKeyWithAtLeast32Chars!!", "Issuer": "promiscuity", "Audience": "promiscuity-auth-api" },
|
||||||
"Logging": { "LogLevel": { "Default": "Information" } },
|
"Logging": { "LogLevel": { "Default": "Information" } },
|
||||||
"AllowedHosts": "*"
|
"AllowedHosts": "*"
|
||||||
|
|||||||
Reference in New Issue
Block a user