game_pathfinding 0.1.3

一个寻路库,包含AStar和Recast,目前还在开发阶段
Documentation
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

struct CPoint {
  int32_t x;
  int32_t y;
};

struct CPointArray {
    uintptr_t length;
    const struct CPoint *data;
    uintptr_t cap;
};

struct CPointArray find_path(int64_t map_id, const struct CPoint *start_point, const struct CPoint *end_point);

int64_t load_map(const char *c_string);

int64_t load_map_from_string(const char *file_content);

void free_path(struct CPointArray path);

bool set_walkable(int64_t map_id, const struct CPoint *start_point, int32_t walkable);

void init_runtime(uintptr_t worker_threads);

int main()
{
    /*int64_t map_id = load_map("./astar_map_16_16.map");
    struct CPoint start, end;
    start.x = 1;
    start.y = 0;
    end.x = 14;
    end.y = 15;
    struct CPointArray path = find_path(map_id, &start, &end);
    printf("path len: %d\n", path.length);
    for(int i = 0; i < path.length; i++)
    {
        printf("(%d, %d)\n", path.data[i].x, path.data[i].y);
    }
    free((void*)path.data);*/

    init_runtime(1);

    FILE *file;
    char *buffer;
    long file_length;

    // 打开文件
    file = fopen("World.json", "rb");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    file_length = ftell(file);
    rewind(file);

    buffer = (char *)malloc(file_length + 1);
    if (buffer == NULL) {
        perror("Error allocating memory");
        fclose(file);
        return 1;
    }

    if (fread(buffer, 1, file_length, file) != file_length) {
        perror("Error reading file");
        free(buffer);
        fclose(file);
        return 1;
    }

    // 在文件末尾添加字符串结束符
    buffer[file_length] = '\0';

    int64_t map_id = load_map_from_string(buffer);

    // 释放内存和关闭文件
    free(buffer);
    fclose(file);

    if(map_id == 0)
    {
        printf("加载地图失败\n");
        return 2;
    }

    for(int x = 0; x < 10; x++)
    {
        struct CPoint start, end;
        start.x = 1;
        start.y = 0;
        end.x = 14;
        end.y = 15;
        struct CPointArray path = find_path(map_id, &start, &end);
        printf("path len: %d\n", path.length);

        if(path.length == 0)
        {
            printf("寻路失败\n");
            sleep(1);
            continue;
        }

        for(int i = 0; i < path.length; i++)
        {
            printf("(%d, %d)\n", path.data[i].x, path.data[i].y);
        }


        struct CPoint walkable_point;
        walkable_point.x = path.data[3 + x].x;
        walkable_point.y = path.data[3 + x].y;
        set_walkable(map_id, &walkable_point, 1);

        free_path(path);

        sleep(1);
    }

    return 0;
}