WebAssembly text format not working on negative

142 Views Asked by At
(module
  (func $pow2
    (param $v f64)
    (result f64)
    local.get $v
    local.get $v
    f64.mul
  )
  (func $_dist (export "_dist")
    (param $x0 f64)
    (param $y0 f64)
    (param $x1 f64)
    (param $y1 f64)
    (result f64)

    local.get $x0
    local.get $x1
    f64.sub
    call $pow2

    local.get $y0
    local.get $y1
    f64.sub
    call $pow2

    f64.add
    f64.sqrt
  )
  (func (export "_point_circle")
  (param $px f64)
  (param $py f64)
  (param $cx f64)
  (param $cy f64)
  (param $cr f64)
  (result i32)

    local.get $px
    local.get $py
    local.get $cx
    local.get $cy

    call $_dist
    local.get $cr
    f64.lt
  )
)

My code work good inside JavaScript!

This code detect collision of one point and a circle.

but not work in WebAssembly Text Format when some values is less than Zero

how to fix this problem ? WebAssembly Text Format does't have negative ??

1

There are 1 best solutions below

0
On

Webassembly does support negative numbers. When you read memory values using javascript, remember to use signed arrays which understand negative numbers vs unsigned arrays which do not. Using unsigned arrays will always produce positive numbers when read. For example reading memory in terms of signed bytes looks like

let i8_memory = new Int8Array(memory.buffer);

This array will recognize negative integers up to -128. However using an unsigned array, which looks like this

let i8_memory = new Uint8Array(memory.buffer);

will not recognize negative numbers and will simply display the positive numbers up to 255

The same data can be interpreted as negative or positive depending on the type of array you use to read that data.

Signed byte range -128 to 127 Unsigned byte range 0 to 255

You did't provide much as to where the problem is occurring so I can only guess why negative numbers are giving you a problem