2

If I make Blender compute a modulo, then it does not work correctly for negative numbers.

In the picture, the part of the rectangular cuboid with a negative abscissa is incorrect.

Here is a render of a rectangular cuboid with a base color of $mod(abscissa,1)$, according to Blender:The modulo function does not work correctly with negative numbers in Blender.

How you fix that?

BlenderUser9000
  • 89
  • 1
  • 11

3 Answers3

6

Nowadays, Wrap is a simple way to an all-positive modulo:

enter image description here

Here, on an 8x8 plane. It also allows you to shift 0 without an extra node. There is a vector version, which gives you a sawtooth in any or all dimensions. (A Wave > Sawtooth will also do it in one of them, but the scaling is more fiddly.)

Robin Betts
  • 76,260
  • 8
  • 77
  • 190
3

The mod returns negative outputs for negative inputs. One way to get positive outputs is

$$((x \operatorname{mod} m) + m) \operatorname{mod} m$$

Nodes for ((x mod 2)+2) mod 2

Graphs of regular and fixed modulo function

scurest
  • 10,349
  • 13
  • 31
  • Okay, but why does the issue happen? – BlenderUser9000 Aug 07 '22 at 00:16
  • It's just a convention. Looks like it ultimately goes through C's fmodf function, which has this behavior. See Modulo operation. – scurest Aug 07 '22 at 00:23
  • It's not "just a convention", at least not as far as the math is concerned.. See my answer for an explanation. but basically it's how Blender clamps negative numbers to 0 when converting to colors. – Marty Fouts Aug 07 '22 at 00:27
  • @MartyFouts The sign of mod's output is indeed just a convention. For example, GLSL's mod function does what OP expects. See the wiki article for a catalog of the convention in different languages. – scurest Aug 07 '22 at 00:31
  • @scurest But that doesn't explain why half of his output is black. You have to explain why negative numbers come out black. This is what I was expanding on. – Marty Fouts Aug 07 '22 at 00:33
  • anyway, your approach generates a lot of overhead and there are far easier fixes. – Marty Fouts Aug 07 '22 at 00:34
2

The problem you are seeing is because Blender's gray scale is $[0..1]$ and Blender clamps values < 0 to 0 and values > 1 to 1. So all of your negative values come out as black. If you had values > 1 they would all come out as white.

While you can use other approaches, an efficient approach to solving this problem is to use the Map Range node to map your input values into a positive range:

Module applied to -1 to 1 remapped

Here I've used a Texture Coordinate node to generate the range $[-1..1]$ and a Map Range node to the resulting range $[0..20]. This will give you 10 iterations through the modulo operator set to 2, or 20 set to 1.

Marty Fouts
  • 33,070
  • 10
  • 35
  • 79