citizenfx / fivem

The source code for the Cfx.re modification frameworks, such as FiveM, RedM and LibertyM, as well as FXServer.
https://cfx.re/
3.52k stars 2.07k forks source link

Float values are not serialized in NUI callback #2171

Closed b2soft closed 5 months ago

b2soft commented 1 year ago

The Problem

I'm trying to use modern way of returning data from C# Client to NUI, utilizing result(object) call. For some reason float values are not serialized and equal null at NUI side.

Reproduce code

API.RegisterNuiCallback("Test::Request", new Action<IDictionary<string, object>, CallbackDelegate>(OnRequestData));
...
private void OnRequestData(IDictionary<string, object> arg, CallbackDelegate result)
{
    float vehicleSpeed = 42.0f;
    result(new { ok = true, speed = vehicleSpeed, test = "TEST" });
}

image

Possible problem

When I tested different types: float _a, double _b, int _c, long _d, string _e, bool _f, it seems like only float is not converted correctly image

I observed, that value of this result is serialized first to JSON, and then to MessagePack. https://github.com/citizenfx/fivem/blob/81fd97f8ee7def9f89fb2aafa99a13aadc045d10/code/components/nui-resources/src/ResourceUICallbacks.cpp#L23 Possibly, JSON part serializes floats wrong.

Workaround

For now I have 2 workarounds:

  1. Use double everywhere instead of float
  2. Serialize object -> JSON first, myself in C# code, and then pass result string to callback. It works, since strings are sent OK result(JsonConvert.SerializeObject(new { ok = true, speed = vehicleSpeed })); image
gottfriedleibniz commented 1 year ago

There is a case of a missing case msgpack::type::FLOAT32: in ConvertToJSON.

b2soft commented 1 year ago

There is a case of a missing case msgpack::type::FLOAT32: in ConvertToJSON.

Probably, that is the case. At least FLOAT32 and FLOAT may be encoded as Double. But we have only IsDouble, to keep from json conversion it's needed to add some float getter as well: https://github.com/citizenfx/fivem/blob/master/code/client/shared/MsgpackJson.h#L36C26-L36C26

Float getter/setter were added only after this PR in rapidjson https://github.com/Tencent/rapidjson/issues/341

gottfriedleibniz commented 1 year ago

Trying to round-trip float32's may lead some to backwards compatibility problems. Some care, if possible, will be required.

The missing msgpack::type::FLOAT32 in ConvertToJSON is a bug regardless.

b2soft commented 1 year ago

I think FLOAT32/float can be treated as double and returned as double safely. It will not break any backward compatibility issues (because floats did not work) and would not affect new code, if you continue using doubles