erincatto / box2d

Box2D is a 2D physics engine for games
https://box2d.org
MIT License
8.09k stars 1.52k forks source link

Android compilation issues #782

Closed eduardodoria closed 2 weeks ago

eduardodoria commented 2 weeks ago

I had to modify some parts to build for Android.

In file allocate.c the function aligned_alloc is only supported starting from Android API level 28, so I'm using posix_memalign instead:

#if defined(B2_PLATFORM_WINDOWS)
    void* ptr = _aligned_malloc( size32, B2_ALIGNMENT );
#elif defined(B2_PLATFORM_ANDROID)
    void* ptr = NULL;
    if (posix_memalign(&ptr, B2_ALIGNMENT, size32) != 0) {
        ptr = NULL;  // Allocation failed
    }
#else
    void* ptr = aligned_alloc( B2_ALIGNMENT, size32 );
#endif

In file core.h I modified this part to compile for x86 and arm (maybe need to rename B2_CPU_X64 macro):

// Define CPU
#if defined( __x86_64__ ) || defined( _M_X64 )
#define B2_CPU_X64
#elif defined( __i386__ ) || defined( _M_IX86 )
#define B2_CPU_X64
#elif defined( __aarch64__ ) || defined( _M_ARM64 )
#define B2_CPU_ARM
#elif defined( __arm__ ) || defined( _M_ARM )
#define B2_CPU_ARM
#elif defined( __EMSCRIPTEN__ )
#define B2_CPU_WASM
#else
#error Unsupported CPU
#endif

At same core.h file I needed to add B2_BREAKPOINT macro to Android:

#if defined( B2_COMPILER_MSVC )
#define B2_BREAKPOINT __debugbreak()
[...]
#elif defined( B2_PLATFORM_ANDROID )
#define B2_BREAKPOINT __builtin_trap()
[...]
#else
#error Unknown platform
#endif
erincatto commented 2 weeks ago

Thanks for the write up.

Shouldn't the application exit if it is out of memory?

Isn't the break point a property of the compiler?

eduardodoria commented 2 weeks ago

These modifications I did is working.

I've got many errors before:

allocate.c:71:14: error: call to undeclared library function 'aligned_alloc' with type 'void *(unsigned long, unsigned long)'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
          void* ptr = aligned_alloc( B2_ALIGNMENT, size32 )

After that I got "Unsupported CPU" error.

And after that, B2_BREAKPOINT is not defined.

I have not tested the possible implications that these changes may cause. But in my engine I updated to the Box2D "main" version (I also had more errors with 3.0.0 ) and needed to make these changes quickly.

You can look my workflow from Android: https://github.com/supernovaengine/supernova/actions/runs/10624088233/job/29451747819

erincatto commented 2 weeks ago

Fixed in #783