# Question
Title: Will a game made with .Net Desktop Development, be able to run on Windows' desktops?
I am new to making games (I have experience only with pygame), and I want to start creating with C#. I've found out that Monogame is a very good engine. On my way of setting up, in the part where I install Visual Studio, Monogame's site says:

> Before installing Monogame, you'll need to install Visual Studio 2019 or later (any edition, including Community) with the following components, depending on your target platform:
>
> * .NET Core cross-platform development - For Desktop OpenGL and DirectX platforms
> * Mobile Development with .NET - For Android and iOS platforms
> * Universal Windows Platform development - For Windows 10 and Xbox UWP platforms
> * .Net Desktop Development - For Desktop OpenGL and DirectX platforms to target normal .NET Framework

I want to create a game to be played on desktops (most preferably, on Windows), and as it writes, *Universal Windows* seems the most suitable. Is there any difference, if I use *.NET Desktop Development*? I see that for other type of applications, this is very common.

# Answer
You can view the list of platforms Monogame can export to here.

As you can see, the framework supports various templates which result in a game which runs on various target platforms. Those including Windows are:

* WindowsDX which runs on any Windows version since Vista
* DesktopGL, which runs on any Windows version since Vista, macOS and Linux (you need to compile a separate binary for each)
* WindowsUniversal which runs on Windows 10 and XBox One (and I *believe* later XBoxes), and requires that you distribute your game through the Windows Store.
> 0 votes

---
Tags: c#, monogame, .net
---


title: Lights not displayed on Sprite

text:
# Question
Title: Lights not displayed on Sprite
I have a scene that contains 3 elements:

* **Main Camera**
* **A 2D Sprite that renders a single white pixel image, scaled to 2000 x 1000**
* **A point light with a yellow color**

What should be done so that the light is actually rendered on the sprite?

I have recorded a short video showcasing the issue: https://www.youtube.com/watch?v=g2iZB6BXhPs

# Answer
> 0 votes
It sounds like you are using the default sprite material, which does not perform lighting computations.

If you would like to use 3D lighting, create a new `Material`, and set its shader to `Sprites/Diffuse`, then assign that material to your sprite.

---
Tags: unity, sprites, lighting
---


# Question
Title: Tracking how many people play my Unity game in which language?
In my game the user can **change the language of the game** and I'd like to know **how many people play it in English, German, etc**.

I'm using **Unity**, so possibly I would like to implement in Unity Analytics.

I was thinking about adding **segments** for the languages, but in that case if a user tries all languages, the user will appear in all languages' segments. So it won't really provide that much info.

A possible solution:

* When the user changes language, we signal a database to decrease the old language's counter and increase the new language's counter.

But there must be an easier, built-in solution than this.

# Answer
Possibly you could do something like:

```
if (languages.language = languages.English)
{
    englishNumber += 1.0f;
}

```

for English, and for each player. This way, for each player with English as their language, `englishNumber` is increased by 1. Then take that number and set into a database that will be changed by all users, so nobody is left out. So if there are 58 players using "English", and each one adds `+1` to `englishNumber` (note that I mean they all add "+1" to the **same** `englishNumber` variable), then the result is that `englishNumber` would equal 58.
> 0 votes

---
Tags: unity, analytics
---


# Question
Title: How do I bring the console window back into the same Unity window?
I have this issue where somehow I accidentally got the console window separated from the window that all unity things are n, so it floats around, blocking the unity screen behind it, as shown below:

And I don't know how to fix it. I tried right clicking the projects tab but the option to add the console window wasn't there. I also tried dragging around the console window back into place but that didn't work. Whenever I restart this still happens, and even new projects have this issue, ever since I accidentally dragged the window out from the unity window shown behind it in the image I showed. There has to be a simple fix to this.

# Answer
> 0 votes
You just click and drag the "Console" tab until it snaps to the place where you want it.

If you have trouble, you can open the Window menu and select Layouts \> Default (or another layout of your choice) to force all panels back into some standard arrangeement.

---
Tags: unity, console
---


title: Vertexes passed to OpenGL becoming zero

text:
# Question
Title: Vertexes passed to OpenGL becoming zero
I've got two methods of test code. The first uses a single VBO with the vertices and texture coordinates interwoven to draw a square to the window. The second uses an array of three VBOs to define the vertices, texture coordinates, and colour values.

The first method successfully renders a black square to the centre of the window. The second method does not render anything. I began troubleshooting with RenderDoc and found that under the "Mesh Viewer" tab the `glDrawArrays()` call from the first method lists the vertices and texture coordinates. When Examining the `glDrawArrays()` call from the second method all values passed are 0.

Can anyone explain to me why this is happening and how it can be resolved?

First Method:

```
public static void GenDrawQuad() {
        int quadVAO = 0;
        int quadVBO = 0;

        float vertices[] = {
                // Positions         Texcoords
                -0.5f,  0.5f, 0.0f,  -0.5f, 0.5f,
                -0.5f, -0.5f, 0.0f,  -0.5f,-0.5f,
                0.5f,  0.5f, 0.0f,   0.5f, 1.5f,
                0.5f, -0.5f, 0.0f,   0.5f,-0.5f,
        };

        // Gen VAO to contain VBO
        quadVAO = glGenVertexArrays();
        glBindVertexArray(quadVAO);

        // Gen and fill vertex buffer (VBO)
        quadVBO = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);

        // Bind vertex attributes (position, texcoords)
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 3, GL_FLOAT, false, 5*Float.BYTES,0); //Positions
        glEnableVertexAttribArray(1);
        glVertexAttribPointer(1, 2, GL_FLOAT, false, 5*Float.BYTES,3*Float.BYTES); //Texcoords

        // Draw quad
        glBindVertexArray(quadVAO);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        glBindVertexArray(0);

        // Delete buffers (VBO and VAO)
        glDeleteBuffers(quadVBO);
        glDeleteVertexArrays(quadVAO);
    }

```

RenderDoc for the first method:

Second Method:

```
public static void GenDrawQuadAlt() {
        int quadVAO = 0;
        int[] quadVBO = {0, 0, 0};
        Shader shaderProgram = GetShaderDefault();

        float vertices[] = {
                // Positions
                -0.5f,  0.5f, 0.0f,
                -0.5f, -0.5f, 0.0f,
                 0.5f,  0.5f, 0.0f,
                 0.5f, -0.5f, 0.0f
        };

        float[] texcoords = {
                 0.5f, -0.5f,
                -0.5f, -0.5f,
                 0.5f,  0.5f,
                 0.5f, -0.5f
        };

        float[] colour = {
                255, 109, 154, 255,
                255, 109, 154, 255,
                255, 109, 154, 255,
                255, 109, 154, 255
        };

        // Gen VAO to contain VBO
        quadVAO = glGenVertexArrays();
        glBindVertexArray(quadVAO);

        // Gen and fill vertex buffer (VBO)
        quadVBO[0] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[0]);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);

        quadVBO[1] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[1]);
        glBufferData(GL_ARRAY_BUFFER, texcoords, GL_STATIC_DRAW);

        quadVBO[2] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[2]);
        glBufferData(GL_ARRAY_BUFFER, colour, GL_STATIC_DRAW);

        // Bind vertex attributes (position, texcoords)
        glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt));
        glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt), 3, GL_FLOAT,
                false, 0,0); //Positions

        glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt));
        glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt), 2, GL_FLOAT,
                false, 0,0); //Texcoords

        glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt));
        glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt), 4, GL_FLOAT,
                false, 0, 0); //Colours

        // Draw quad
        glUseProgram(shaderProgram.getId());
        glBindVertexArray(quadVAO);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        glBindVertexArray(0);
        glUseProgram(0);

        // Delete buffers (VBO and VAO)
        glDeleteBuffers(quadVBO);
        glDeleteVertexArrays(quadVAO);
    }

```

RenderDoc for the second method:

**::EDIT::**

After a bit of tinkering I now have the following method which places the values in the expected locations for my shader and gives me a gl\_Position output, but does not render to the screen.

```
public static void GenDrawQuadAlt() {
        int quadVAO = 0;
        int[] quadVBO = {0, 0, 0, 0};
        Shader shaderProgram = rlglData.getState().getCurrentShader();

        float vertices[] = {
                -0.5f,  0.5f, 0.0f,
                -0.5f, -0.5f, 0.0f,
                0.5f,  0.5f, 0.0f,
                0.5f, -0.5f, 0.0f
        };

        float[] texcoords = {
                0.5f, -0.5f,
                -0.5f, -0.5f,
                0.5f,  0.5f,
                0.5f, -0.5f
        };

        float[] colour = {
                255, 109, 154, 255,
                255, 109, 154, 255,
                255, 109, 154, 255,
                255, 109, 154, 255
        };

        int[] indices = {
                0, 1, 2,
                0, 2, 3
        };

        // Gen VAO to contain VBO
        quadVAO = glGenVertexArrays();
        glBindVertexArray(quadVAO);

        // Gen and fill vertex buffer (VBO)
        quadVBO[0] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[0]);
        glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT,
                false, 0,0); //Positions
        glEnableVertexAttribArray(0);

        quadVBO[1] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[1]);
        glBufferData(GL_ARRAY_BUFFER, texcoords, GL_STATIC_DRAW);
        glVertexAttribPointer(1, 2, GL_FLOAT,
                false, 0,0); //Texcoords
        glEnableVertexAttribArray(1);

        quadVBO[2] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[2]);
        glBufferData(GL_ARRAY_BUFFER, colour, GL_STATIC_DRAW);
        glVertexAttribPointer(3, 4, GL_FLOAT,
                false, 0, 0); //Colours
        glEnableVertexAttribArray(3);

        quadVBO[3] = glGenBuffers();
        glBindBuffer(GL_ARRAY_BUFFER, quadVBO[3]);
        glBufferData(GL_ARRAY_BUFFER, indices, GL_STATIC_DRAW);

        // Draw quad
        glUseProgram(shaderProgram.getId());
        glBindVertexArray(quadVAO);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.length/3);
        glBindVertexArray(0);
        glUseProgram(0);

        // Delete buffers (VBO and VAO)
        glDeleteBuffers(quadVBO);
        glDeleteVertexArrays(quadVAO);
    }

```

My vertex shader:

```
#version 330
in vec3 vertexPosition;
in vec2 vertexTexCoord;
in vec4 vertexColor;
out vec2 fragTexCoord;
out vec4 fragColor;
uniform mat4 mvp;
void main()
{
    fragTexCoord = vertexTexCoord;
    fragColor = vertexColor;
    gl_Position = vec4(vertexPosition.x, vertexPosition.y, vertexPosition.z, 1.0);
}

```

My fragment shader:

```
#version 330
in vec2 fragTexCoord;
in vec4 fragColor;
out vec4 finalColor;
uniform sampler2D texture0;
uniform vec4 colDiffuse;
void main()
{
    vec4 texelColor = texture(texture0, fragTexCoord);
    finalColor = texelColor*colDiffuse*fragColor;
}

```

# Answer
After using `glGetUniformLocation()` to set the shader properties I discovered the shader location values were not being defined due to an error in my shader constructor. Once I rectified that error my quad was drawn to the screen.

Thanks for all the help and input!
> 0 votes

# Answer
**glVertexAttribPointer sources data from the currently bound GL\_ARRAY\_BUFFER**.

What this means is that if you're drawing using 3 buffers, you must ensure that the correct buffer is bound for each glVertexAttribPointer call.

So instead of:

```
    // Gen and fill vertex buffer (VBO)
    quadVBO[0] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[0]);
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);

    quadVBO[1] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[1]);
    glBufferData(GL_ARRAY_BUFFER, texcoords, GL_STATIC_DRAW);

    quadVBO[2] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[2]);
    glBufferData(GL_ARRAY_BUFFER, colour, GL_STATIC_DRAW);

    // Bind vertex attributes (position, texcoords)
    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt));
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt), 3, GL_FLOAT,
            false, 0,0); //Positions

    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt));
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt), 2, GL_FLOAT,
            false, 0,0); //Texcoords

    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt));
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt), 4, GL_FLOAT,
            false, 0, 0); //Colours

```

You should do:

```
    // Gen and fill vertex buffer (VBO)
    quadVBO[0] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[0]);
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt), 3, GL_FLOAT,
            false, 0,0); //Positions

    quadVBO[1] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[1]);
    glBufferData(GL_ARRAY_BUFFER, texcoords, GL_STATIC_DRAW);
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt), 2, GL_FLOAT,
            false, 0,0); //Texcoords

    quadVBO[2] = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, quadVBO[2]);
    glBufferData(GL_ARRAY_BUFFER, colour, GL_STATIC_DRAW);
    glVertexAttribPointer(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt), 4, GL_FLOAT,
            false, 0, 0); //Colours

    // Bind vertex attributes (position, texcoords)
    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_POSITION.ShaderLocationInt));
    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_TEXCOORD01.ShaderLocationInt));
    glEnableVertexAttribArray(shaderProgram.getLocs().get(LOC_VERTEX_COLOR.ShaderLocationInt));

```

In the former case (your original code), for each glVertexAttribPointer call, the currently bound GL\_ARRAY\_BUFFER is quadVBO\[2\] so you're telling OpenGL that quadVBO\[2\] is the data source for each.

In the latter case, the buffer that you actually want to use for each is bound before each call, and everything will work as you want.

Note that it's valid to call glEnableVertexAttribArray after your other calls here.
> 1 votes

---
Tags: opengl, java, rendering, lwjgl3
---


# Question
Title: Is it possible to use Java as a scripting language?
Is it possible to use Java as a scripting language for a C++ engine/game?

I understand that you need to make a binding to the interpreter, but I haven't seen any around.

# Answer
> 7 votes
Quite possible.

You could probably use the GNU Interpreter for Java or some other such system. However I think you'll find a lot more cases (as mentioned above) of people using Lua, Python or other languages in games. Lua in particular is very well suited for the task of embedded scripting.

Additionally, you might check the jog interpreter project, which touts itself as, "...a lightweight but reasonably full-featured and fast Java compiler and interpreter." that is written in C++.

Amusingly, googling for "java interpreters in C++" seems to yield as many (if not more) hits for C++ interpreters written in Java instead of the other way around :)

# Answer
> 5 votes
Yes, it's possible. Way back in 1999, an article was published in Game Developer on the subject, entitled "Dirty Java: Using the JNI Within Games." I still have my copy of issue in fact. Fortunately the article also appears to be available online. Of course, the code in that article is probably a tad out of date, so you can also check out these articles as well:

However, these days it's probably better to consider a language like Python, Lua or Javascript for your embedding needs. They're a lot more lightweight and, in the case of Lua in particular, designed with embedding and scripting in mind.

# Answer
> 2 votes
Yes it is possible. Game Vampire the Masquerade - Redemption uses Java as a scripting language. And that game is the only serious game i know of using Java. Bear i mind, they are not using Java for their Nod engine.

Edit: There is JMonkeyEngine written completely in Java.

# Answer
> 2 votes
Bohemia Interactive (BIS) has announced that Arma3 will use Java as its scripting language. BIS will be introducing their Java scripting engine in the next patch for Take On Helicopters.

# Answer
> 1 votes
MMORPG Darkfall Online uses Java as a scripting engine.

# Answer
> 0 votes
Yes it is possible.

However if you are looking for a JVM langauge for scripting, I'd probably recommend either Clojure or Groovy over Java itself - both are dynamic langauges that are better suited for the interactive development style that you usually want with scripting langauges.

# Answer
> 0 votes
It definitely is possible, but Java isn't the best language to use for scripting, as a language it was designed with the goal of actually being used to write the core application itself, not for the scripting in the application.

---
Tags: c++, java, scripting
---


# Question
Title: What to do with d3dx9math.h when converting to DirectX11?
I'm converting an old game from DirectX9 to DirectX11 and I have a question: What I should use instead of `d3dx9math.h`?

Do I have to convert everything for `DirectXMath.h`(XNAMath), or I can continue with my old `d3dx9math.h` or even `d3dx10math.h`?

# Answer
It's just a math library, so as long as it doesn't interact with the actual D3D API, then you can in theory use any math library you wish.

Things to watch out for might include row-major vs column-major matrix conventions, -1..1 or 0..1 NDC Z conventions, etc, but otherwise choice of math library should be relatively constraint-free.
> 1 votes

---
Tags: c++, directx11, directx9
---


# Question
Title: save generated gameobject to an array for shuffling
hey everyone i have this script here that breaks down a sprite into pieces and makes each one a gameobject.im having touble saving them into an array so i can shuffle them as gameobjects.

```
 public void Start()
    {

        GameObject spritesRoot = GameObject.Find("SpritesRoot");
        Debug.Log("Array length: " + array2D.GetLength(0));

        for (int i = 0; i < array2D.GetLength(0); i++)
        {
            Debug.Log("x: " + array2D[i, 0]);
            Sprite newSprite = Sprite.Create(source, new Rect(array2D[i, 0], array2D[i, 1], array2D[i, 2], array2D[i, 3]), new Vector2(0.5f, 0.5f));
            GameObject n = new GameObject();
            SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
            sr.sprite = newSprite;
            n.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(array2D[i, 0], array2D[i, 1],0),0);
            n.transform.parent = spritesRoot.transform;
        }

    }

```

my shuffle function is this

<pre><code> public void Shuffle(GameObject[] gameObjects)
    {
        for (int i = 0; i < gameObjects.Length; i++)
        {

            // Find a random index
            int destIndex = Random.Range(0, gameObjects.Length);
            GameObject source = gameObjects[i];
            GameObject dest = gameObjects[destIndex];

            // If is not identical
            if (source != dest)
            {

                // Swap the position
                source.transform.position = dest.transform.position;

                // Swap the array item
                gameObjects[i] = gameObjects[destIndex];
            }
        }
    }
```
</code></pre>

# Answer
> 1 votes
First you create an array for those objects. When you want to retain that array after the Start-method, then that should be on the level of the class, not a local variable:

```
private GameObject[] spawnedGameObjects;

```

Then you need to initialize that array to the number of entries you need:

```
spawnedGameObjects = new GameObject[array2D.GetLength(0)];

```

Then you put each newly created game object into entries of that array after you created it:

```
spawnedGameObjects[i] = n;

```

Then you shuffle it:

```
Shuffle(spawnedGameObjects);

```

Full code:

```
private GameObject[] spawnedGameObjects;

public void Start()
{

    GameObject spritesRoot = GameObject.Find("SpritesRoot");
    Debug.Log("Array length: " + array2D.GetLength(0));
    spawnedGameObjects = new GameObject[array2D.GetLength(0)];

    for (int i = 0; i < array2D.GetLength(0); i++)
    {
        Debug.Log("x: " + array2D[i, 0]);
        Sprite newSprite = Sprite.Create(source, new Rect(array2D[i, 0], array2D[i, 1], array2D[i, 2], array2D[i, 3]), new Vector2(0.5f, 0.5f));
        GameObject n = new GameObject();
        SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
        sr.sprite = newSprite;
        n.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(array2D[i, 0], array2D[i, 1],0),0);
        n.transform.parent = spritesRoot.transform;
        spawnedGameObjects[i] = n;
    }

    Shuffle(spawnedGameObjects);

}

```

---
Tags: unity
---


# Question
Title: When should I use OnPointerClick vs. Input.GetMouseButton?
In all games I wrote so far, I used `Input.GetMouseButton` or `Input.GetMouseButtonDown` inside `Update` to detect mouse clicks.

Now I learned that there is another way - I can make my component implement `IPointerClickHandler`, and implement the method `OnPointerClick`.

What is the difference between these two input methods?
When is it recommended to use one vs. other?

# Answer
`Input.GetMouseButton` or `Input.GetMouseButtonDown` will just check the raw state of your input (and return a boolean, as it can be only pressed or not pressed)

the `OnPointerClick` callback is working with the Event System of your UI. It gets in parameter a class containing information about the event.

Generally (in UI), you should try to avoid using Raw input in your code. Using event callbacks, you make sure your code will only be called when the conditions are met (i.e you don't want your code to be called if you are targeting a canvas in front of your object)

Also, the difference between a pointer and a mouse input is that the pointer is "wrapping" the mouse, but also supports touchscreens, graphic tablet, and other pointing devices
> 1 votes

# Answer
IPointerClickHandler detects clicks on a gameObject with a collider. This makes it very useful when you want to have objects in your scene the player can click on in order to interact with them. Like units in an RTS or buildings in a city builder.

The combination of Input.GetMouseButton and Input.mousePosition is useful when you want to react to mouse inputs which are not specific to what the player is pointing at but rather how they move the mouse. Like aiming in a first person shooter, moving the camera around a map or implementing drag&drop functionality.
> 0 votes

---
Tags: unity, mouse
---


title: Vulkan dynamic UBO weird numbers

text:
# Question
Title: Vulkan dynamic UBO weird numbers
Why these numbers?? I have created a dynamic ubo and two objects, one for view and proj and the other for model.

Here I update the objects:

```
Render::UniformBufferObject ubo{};
        Render::UniformBufferObject2 ubo2{};

        ubo2.model = &model_transform.GetWorldMatrix();

        ubo.view =  &EditorCamera_transform.GetWorldMatrix().Inverse();

        ubo.proj = &current_camera->GetProjectionMatrix();

        // map memory without a staging buffer
        void* data;
        auto memory = uniform_buffer->get_ubo_memory();
        Render::VulkanMemoryAllocator::get_instance()->map_buffer_allocation(memory[current_image], &data);
        memcpy(data, &ubo, sizeof(ubo));
        memcpy(data, &ubo2, sizeof(ubo2));
        Render::VulkanMemoryAllocator::get_instance()->unmap_buffer_allocation(memory[current_image]);

```

Here binding and draw command:

```
std::array<uint32_t, 2> dynamicOffsets =
            { i * static_cast<uint32_t>(Render::StandardUniformBuffer::required_alignment(sizeof(Maths::Matrix4)*2)),
              i* static_cast<uint32_t>(Render::StandardUniformBuffer::required_alignment(sizeof(Maths::Matrix4)))
            };

            cmd.bindDescriptorSets(
                vk::PipelineBindPoint::eGraphics,
                *pipeline->get_pipeline_layout(),
                0,
                2,
                descriptor_set->get_descriptor_sets()->data(),
                2,
                dynamicOffsets.data());

            cmd.drawIndexed(static_cast<uint32_t>(index_buffer->get_primative_indices_size()), 1, 0, 0, 0);

```

# Answer
> 1 votes
It's actually hard to say anything for sure without knowing a lot more about your code base, but do `Render::UniformBufferObject` and `Render::UniformBufferObject2` consist of pointers to matrices, and not actual matrices (unless the `&` operator is overloaded somehow) ?

You're not supposed to write pointers to values into UBOs and expect the GPU to dereference them.

You also seem to be overwriting the content you wrote from `ubo` with contents in `ubo2` ; `data` points to the same location in both of the `memcpy` calls.

Assuming `Render::UniformBufferObject` and `Render::UniformBufferObject2` actually consists of matrix value members:

```
struct Render::UniformBufferObject {
  glm::mat4 view, proj
};
struct Render::UniformBufferObject2 {
  glm::mat4 model
};

```

Here's how I'd write the values to the uniform buffer, assuming `Render::StandardUniformBuffer::required_alignment` works the way I expect it to:

```
// Assuming uniform_buffer has enough size taking UBO offset alignment into account.
void* data;
auto memory = uniform_buffer->get_ubo_memory();
Render::VulkanMemoryAllocator::get_instance()->map_buffer_allocation(memory[current_image], &data);

// Write to the location we'll be telling vkCmdBindDescriptorSets in the form of dynamic offsets.
auto& ubo = reinterpret_cast<Render::UniformBufferObject*>(static_cast<uint8_t*>(data) + 0);
auto& ubo2 = reinterpret_cast<Render::UniformBufferObject2*>(static_cast<uint8_t*>(data) + Render::StandardUniformBuffer::required_alignment(sizeof(Render::UniformBufferObject)));

ubo.view = EditorCamera_transform.GetWorldMatrix().Inverse();
ubo.proj = current_camera->GetProjectionMatrix();
ubo2.model = model_transform.GetWorldMatrix();

// Remember to call vkFlushMappedMemoryRanges if the backing memory is NOT host coherent.

Render::VulkanMemoryAllocator::get_instance()->unmap_buffer_allocation(memory[current_image]);

```

And the dynamic offsets for `vkCmdBindDescriptorSets`:

```
// Offsets where we wrote the values:
std::array<uint32_t, 2> dynamicOffsets = {
  0,
  Render::StandardUniformBuffer::required_alignment(sizeof(Render::UniformBufferObject))
};

```

---
Tags: rendering, vulkan
---


# Question
Title: Is it possible to debug shaders in GLSL level instead of assembly language level?
I'm writing some Vulkan code and write my shaders in GLSL.

I tried to use Renderdoc to debug my shaders, but I only got disassembly code.

Is it possible to debug shaders at the level of GLSL if I have the source code of the shaders in GLSL format?

# Answer
No, as the main author Baldur Karlsson explicitly states in the tracking GitHub issue:

> Currently the debugging is primarily at SPIR-V level, not source language level

Vulkan Shader Debugging tracking issue · Issue #1908 · baldurk/renderdoc

You *can* use the `OpSource` SPIR-V instruction to include the source language text in the shader module, at which point the `Source Unavailable` button becomes a clickable `Debug in Source` button, but at this point it just doesn't (and isn't supposed to) work; stepping seems to jump all over the place.

Though it might be worth mentioning that including the source language text with `OpSource` enables you to use RenderDoc's shader editing feature which allows you to directly edit the GLSL code and immediately see the result in the texture viewer. (Use `glslang::TIntermediate::addSourceText` if you're compiling with glslang.)
> 1 votes

---
Tags: shaders, glsl, debugging, vulkan
---


# Question
Title: Photon Transforms syncing other transforms
I have a problem wherein this happens:

It's problematic because I'm unfamiliar how to set the same player value in the same transform over the network. Is there a way where if I get the list of transforms, it's in the same order in other clients?

My current setup is that each client creates his own `My Player Prefab` with a `Player Info` script that stores in the Photon's `Player`. `Spawn Manager` will be listening until both player prefabs have been created. From there, they'll do this code:

```
public void PlayerObjectReady(){
    playerObjectReady++;

    int totalPlayerCount = PhotonNetwork.PlayerList.Length;

    // check if we've readied all player objects in all clients
    if(playerObjectReady == totalPlayerCount){
        photonView.RPC("SpawnPlayer",RpcTarget.AllBufferedViaServer);
    }
}

[PunRPC]
void SpawnPlayer(){
    // update local list for all clients
    infos = FindObjectsOfType<PlayerInfo>(); // this line causes problems

    // update player references so that each character is owned by their player
    for (int i = 0; i < infos.Length; i++){
        infos[i].Player = PhotonNetwork.PlayerList[i];
        if(PhotonNetwork.IsMasterClient)
            infos[i].transform.position = spawnPoints[i].position;
    }
    TurnManager.Instance.AddPlayers(infos);

    // tell everyone i'm ready
    photonView.RPC("ImReady",RpcTarget.AllBufferedViaServer,PhotonNetwork.NickName);
}

```

The main problem here is that the player prefabs are not always in the correct order that I wanted them to be. Plus, their positions often clash together whenever Photon Transform view is enabled. And yes, the players here are right beside each other when they're actually spread across a small map.

Let me know a possible solution because I intend to use Photon Transform view. For now, disabling Photon Transform view is my current band-aid solution which only works when spawning and not moving the players.

# Answer
I got my own solution after testing for hours.

Essentially, when I create the **My Player** prefab which has its own `PhotonView` and I instantiate this prefab by the player who should own it at the start, I can access the Photon View's `Owner.ActorNumber` which can provide me with the ID needed to set my own player list of Transforms/GameObject/whatever script accordingly.

See my code below for reference:

```
[PunRPC]
void SpawnPlayer(){
    // update local list for all clients
    infos = FindObjectsOfType<PlayerInfo>();
    Array.Sort(infos, (PlayerInfo a,PlayerInfo b)=>a.photonView.Owner.ActorNumber.CompareTo(b.photonView.Owner.ActorNumber));

    // update player references so that each character is owned by their player
    for (int i = 0; i < infos.Length; i++){
        infos[i].Player = PhotonNetwork.PlayerList[i];
        if(PhotonNetwork.IsMasterClient)
            infos[i].transform.position = spawnPoints[i].position;
    }
}

```
> 1 votes

---
Tags: unity, photon
---


title: Make enemy move diagonally in 2D

text:
# Question
Title: Make enemy move diagonally in 2D
I'm making the enemy follow the player only straight or diagonally e.g.(1,1)(1,0)(0,1)(-1,1). I expected the problem that I have, but I don't really know how to fix it. When my enemy is placed diagonally (relative to the player but not exactly), It will alternate rapidly between going diagonally and straight, causing it to appear like its vibrating.

here is the simple script returning the Vector2 to follow:

```
        Vector2 direction = (player.position - goblinTr.position).normalized;
        direction.x = Mathf.Round(direction.x);
        direction.y = Mathf.Round(direction.y);

        return direction;

```

# Answer
> 2 votes
So I figured out a solution. I basically check the previous direction I got from my function (without rounding it) and check the angle with the new direction my sprite wants to go (without rounding it) by doing `Vector3.Angle(previousVector,direction)` and then verify if the angle is greater than 30. If it is, I change the direction. If not, I keep the previous direction.

```
Vector2 direction = (player.position - goblinTr.position).normalized;

if (Vector3.Angle(previousVec, direction) >= minVariation || previousVec == Vector2.zero)
{
   var = Vector3.Angle(previousVec, direction);
   previousVec = direction;
   direction.x = Mathf.Round(direction.x);
   direction.y = Mathf.Round(direction.y);

   return direction;
}
else
{
   previousVec.x = Mathf.Round(previousVec.x);
   previousVec.y = Mathf.Round(previousVec.y);

   return previousVec;
}

```

---
Tags: unity, 2d, sprites, movement, npc
---


title: Overlap color between objects

text:
# Question
Title: Overlap color between objects
I'm currently trying to build a game with Ogre3D that is basically a moving vehicle that leaves a green trail (2D manual mesh) in it's path, what i'm trying to achieve is exactly what this image shows:

My problem is that i need to change, by some method/technique, the color of the intersected path where the two meshes overlap (red area). I've been searching around the Ogre forum and found this thread http://www.ogre3d.org/forums/viewtopic.php?f=2&t=47674, I've replicated that solution in my code but now on the screen i only see the intersected path. I'm a total newbie in stencil buffers and in Ogre generally, so I'm still not sure if this is the best approach to solve my problem. should I try another method rather than applying a stencil buffer? vertex/fragment shader code that could help?

Any advice or direction that you could provide will be very appreciated. Thanks a lot

\***** UPDATE \*****

According to JasonPh's answers i've managed to start adding some code:

1) Create manual texture

```
Ogre::TextureManager* tmgr = Ogre::TextureManager::getSingletonPtr();
gkString mMapTextureName = "pathTexture";
if (!tmgr->resourceExists(mMapTextureName)) {
    Ogre::TexturePtr ptr = tmgr->createManual(mMapTextureName,
                           Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
                           Ogre::TEX_TYPE_2D,
                           480,  // Width
                           640,    // Height
                           1, // Depth
                           0,
                           Ogre::PF_A8R8G8B8,
                           Ogre::TU_RENDERTARGET);

    ptr->createInternalResources();
    ptr->load();

    Ogre::RenderTexture* pathTexture = ptr->getBuffer()->getRenderTarget();
    gkEngine* engine = gkEngine::getSingletonPtr();
    Ogre::Camera* camera = engine->getActiveScene()->getMainCamera()->getCamera();
    pathTexture->addViewport(camera);
    pathTexture->getViewport(0)->setClearEveryFrame(true);
    pathTexture->getViewport(0)->setBackgroundColour(Ogre::ColourValue::Black);
    pathTexture->getViewport(0)->setOverlaysEnabled(false);
    pathTexture->setAutoUpdated(true);
}

```

2) Create material from scratch and use the previously created texture. This material is then assigned to my "path" entity.

```
Ogre::MaterialManager* mmgr = Ogre::MaterialManager::getSingletonPtr();
mMaterialName = uniqueMaterialName("pathMaterial");
mMaterial = mmgr->create(mMaterialName, "General");

Ogre::Technique* tec = mMaterial->getTechnique(0);
tec->setSchemeName("ShaderGeneratorDefaultScheme");
Ogre::Pass* pass = tec->getPass(0);
pass->setVertexProgram("pathMaterial/vs", false);
pass->setFragmentProgram("pathMaterial/fs", false);
pass->setCullingMode(Ogre::CULL_NONE);
pass->setColourWriteEnabled(true);
pass->setLightingEnabled(true);
Ogre::TextureUnitState* tus = pass->createTextureUnitState();
tus->setTextureFiltering(Ogre::TFO_NONE);
tus->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP, Ogre::TextureUnitState::TAM_CLAMP, Ogre::TextureUnitState::TAM_CLAMP);
tus->setTexture(tmgr->getByName(mMapTextureName));

mMaterial->prepare();
mMaterial->load();

```

3) Fragment shader code

```
uniform sampler2D pathTexture;

void main()
{
   vec4 color = texture2D(pathTexture, gl_TexCoord[0].xy); =
   if(color == vec4(0.0, 1.0, 0.0, 1) //green
       gl_FragColor = vec4(1.0, 0.0, 0.0, 1) //red
   else
       gl_FragColor = vec4(0.0, 1.0, 0.0, 1) //green
}

```

This still needs some fixes to work, so new questions have emerged:

1) Do I realy need to render "pathTexture" on screen to this to work? Maybe that texture could only be used to decide pixel colors an then discard it?

2) To only use "pathTexture" as an "input" for my shader, should I add a second pass on my material file with "pathTexture" as a texture unit?

Thanks!

# Answer
What you are essentially doing is **counting the number of times each pixel is drawn to**. There are two obvious ways to do this: incrementing the stencil buffer, or incrementing the color buffer using additive blending. Due to the difficulty of using a texture as a stencil buffer in OpenGL, I recommend using additive blending in this case.

The basic steps are:

1. **Create a framebuffer with a texture as the color attachment** and prepare to render to it. See https://learnopengl.com/Advanced-OpenGL/Framebuffers for how to do this. Because we're only tracking one thing, it can be a single-channel texture format (e.g. GL\_R8).
2. **Set the blend mode to additive blending** using `glBlendFunc(GL_ONE, GL_ONE)`.
3. **Render the entire path mesh** in a solid off-black color. Doesn't matter how you do this - you could e.g. write a shader that sets `gl_FragColor.r = 1 / 255.0` (for an 8-bit texture). You could use other values here depending on how many stops you want and the precision of the color buffer, but beware of rounding errors and sRGB conversion.
4. At this point, you now have a texture with the information you want: every pixel stores how many times it was covered by the path mesh.
5. **Draw the texture you just rendered into as a fullscreen quad, using a lookup table in the fragment shader to convert the texture values to the corresponding colors** (e.g. white, green, red, etc.). The lookup table can be accomplished either by indexing into a uniform array, or sampling a 1D texture. Once again, take care to map the values correctly, avoiding sRGB conversions and, if you use an array for the lookup table, clamping the maximum value to avoid indexing past the end of the array.
> 1 votes

# Answer
First you will want to render your path to a separate texture(let's call it "pathTexure"), and when you create it you will fill it with white. When you render a pixel that is part of the path, you will check if the pixel is green, if it is you will set that pixel to red, else set it to green. Finally, you add the "pathTexure" onto whatever you are drawing on the scene(cars, backgrounds, etc.).
> 0 votes

---
Tags: shaders, geometry, ogre, intersection
---


# Question
Title: How to decide whether a Buff should be a component or a Buff object in an ECS?
I'm developing a top-down 2D game in Javascript using an Entity-Component-System architecture and I'm struggling with the question of exactly how to implement temporary buffs / permanent passives.

For example, let's say we want to give some entities `Regeneration`, such that they regenerate 5 health per second.

One option is to have a `BuffsComponent` that holds a list of all active buffs. You could create a `RegenerationBuff` object that inherits from some base `Buff` class, and then stick that in a list inside the `BuffsComponent`. Then a `BuffsSystem` would query all entities with a `BuffsComponent` every frame, and execute the active effect on each buff. Simple.

However, could you not argue that these effects could just be regular old components? That is, why not create a `Regeneration` component and then have a system that queries for all entities with a `Regeneration` component, and then update their health in that system?

Each approach seems to have its own pros and cons, and I'm not sure if I should have a mix of the two, or fully commit to one. I feel like fully committing to one approach would simplify the architecture and design of the program, so I'm leaning towards that, but I'm not sure which approach to pick. Even if I did have a mix, I'm not sure how to decide on what should be a component versus what should be a buff.

The first approach seems more computationally efficient I suppose? Because one potential implementation of such could involve you just iterating through the list of active buffs and calling execute on each one. However, I feel that while it may be more efficient, it may also be less powerful, because with the second solution I can directly query entities with certain buffs, so I could potentially have more complex interactions between entities based on who is holding which buffs. For example, with a `Flight` buff I would likely desire the ability to directly query entities with such a buff, so the latter solution would be preferable.

However, besides the latter solution being potentially slower, it also seems like it could get a bit out of hand. What if I ended up having over 100 different buffs? Adding and removing components to entities is O(1) with my ECS library, but still, it sounds like it could be a bit ridiculous to have hundreds of components for an entity, most of which are just random buffs / passives.

What should I do?

# Answer
> 1 votes
Component-per-buff may cause some serious performance issues. Of course, at this point we can only speculate about the performance, but so far I can only see the downsides — at least in comparison to a more traditional approach.

Some of the the major arguments for using ECS stem from it's ability to exploit cache locality and parallelism for the performance gains. All of that is either hard or impossible to achieve in JavaScipt. To make things worse, each additional system increases performance overhead of ECS just by existing, because each System's dependencies must be considered when an Entity is created or modified.

More specifically, due to the nature of buffs, entities will be modified often (as buffs being added and removed), triggering recalculation of the ECS cache, but Components will be updated rarely, causing Systems to loop a lot without achieving anything of use.

Contrarily, more specialized design enables minimal overhead and allows to extend beyond the capabilities of the ECS.

* Buffs may be represented by a priority queue of timers, limiting update to the only buffs that must be updated.
* Buffs may interact with each other, producing new buffs, modifying or cancelling each other.
* Buff rules will be isolated from the ECS, causing no namespace pollution.

---

And one last detail, tangential to the question:

> For example, with a Flight buff I would likely desire the ability to directly query entities with such a buff, so the latter solution would be preferable.

It should be more efficient to design an unified movement system, that allows flight with a flip of a switch. Besides, how your characters are supposed to move, given both the innate movement component *and* a temporary flying component *at the same time*?

---
Tags: javascript, architecture, design-patterns, entity-component-system
---


# Question
Title: Coins are solid objects and I can't collect them
I am just starting out with Unity following along with this video, and I am stuck at roughly 1 hour and 54 minutes in: https://www.youtube.com/watch?v=pwZpJzpE2lQ

It is worth noting that the video uses Unity 2019.4.4f1 whereas I am using Unity 2020.3.2f1.

My issue is that I cannot get my character to pick up coins and they are currently solid, uncollectable objects. The coins are all set to the Coin layer (layer 9) as per the video.

Here is my code (which I looked over a dozen times to see if there were any differences from the video's code and couldn't find any, hence my confusion). Does anyone know where I went wrong?

```
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] private Transform groundCheckTransform = null;
    [SerializeField] private LayerMask playerMask;

    private bool jumpKeyWasPressed;
    private float horizontalInput;
    private Rigidbody rigidbodyComponent;

    // Start is called before the first frame update
    void Start()
    {
        rigidbodyComponent = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        // Check if space key is pressed down
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyWasPressed = true;
        }

        horizontalInput = Input.GetAxis("Horizontal");
    }

    // FixedUpdate is called once every physic update
    private void FixedUpdate()
    {
        rigidbodyComponent.velocity = new Vector3(horizontalInput, GetComponent<Rigidbody>().velocity.y, 0);

        if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0)
        {
            return;
        }

        if (jumpKeyWasPressed)
        {
            rigidbodyComponent.AddForce(Vector3.up * 7, ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 9)
        {
            Destroy(other.gameObject);
        }
    }
}

```

# Answer
It sounds like you didn't tick the "Is Trigger" checkbox on the coins' Collider component.

Colliders have two modes:

* **Solid** (Is Trigger = false): the physics engine will try to stop and bounce-away movement that makes this collider intersect with another solid collider, generating an `OnCollisionEnter` event when they touch.
* **Trigger** (Is Trigger = true): the physics engine treats this collider as a ghost that can pass through solid colliders with no interference, generating an `OnTriggerEnter` event instead.

If your coins do not have Is Trigger checked, then they'll be treated as solid obstacles and will not call your `OnTriggerEnter` method.
> 2 votes

# Answer
I think the problem is with layer number. Try this

```
private void OnTriggerEnter(Collider other)
{
    // if you want to use tag
    if (other.transform.CompareTag("ObjectCoinTag"))
    {
    Destroy(other.gameObject);
    }

    // Or, you want to use the name object
    if (other.transform.name == "ObjectCoinsName") {
    Destroy(other.gameObject);

    }

}

```

I would like to advice you to watch short tutorials like the one unity do on their website.
> 0 votes

---
Tags: unity, c#, collision-detection, physics, collider
---


title: How do I add a roof to a Html Game

text:
# Question
Title: How do I add a roof to a Html Game
I kind of new to making games been doing it for a few months and want to make games in a browser so I took the w3schools game example and I'm trying to add on to the game until I make a recreation of flappy birds

So the problem I'm having is when adding in the "Skyhigh" function its not working I was trying to change the x and y the game freaks out so I just left it as the "Rockbottom" one I want to know how I would make the "Skyhigh" function to work and add a roof

**Code**

```
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40, "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.frameNo = 0;
        updateGameArea();
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
        this.hitTop();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    this.hitTop = function() {
        var skyhigh = myGameArea.canvas.height - this.height;
        if (this.y > skyhigh) {
            this.y = skyhigh;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright < otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        }
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    if (!myGameArea.interval) {myGameArea.interval = setInterval(updateGameArea, 20);}

    myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Click the ACCELERATE button to start the game</p>
<p>How long can you stay alive? Use the ACCELERATE button to stay in the air..</p>
</body>
</html>

```

# Answer
I see three likely errors, commented below. Try this and edit your question to describe the symptoms if it's still misbehaving.

```
this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
        this.y = rockbottom;
        this.gravitySpeed = 0;
    }
} // This curly brace was missing.

this.hitTop = function() {
    var skyhigh = 0;          // Top of the window.
    if (this.y < skyhigh) {   // Use less-than to check if you're above.
        this.y = skyhigh;
        this.gravitySpeed = 0;
    }
}

```
> 0 votes

---
Tags: javascript, html5
---


# Question
Title: How to perform a fast ray cylinder intersection test?
I need an algorithm in c++ to get the intersection point of a line if there is an intersection. My cylinder is defined by a 3d vector center point, a float height and radius. I don't need to take rotation into consideration at all so I don't need any rotation parameters.

The only one found similar to my needs was this: https://github.com/iceman201/RayTracing/blob/master/Ray%20tracing/Cylinder.cpp but after implementing it gave me wrong results. All the other ones I found used weird arguments that weren't even close to my desire. So I am pretty stuck now.

# Answer
> 2 votes
First we'll subtract the cylinder center from the ray origin, to translate our whole problem to be centered at (0, 0, 0).

**Case 0: Inside**

First, check if the ray origin is inside the cylinder from the start.

$$\text{origin}\_x^2 + \text{origin}\_z^2 \leq \text{radius}^2 \quad \text{and}\quad -\frac {\text{height}} 2 \leq \text{origin}\_y \leq \frac {\text{height}} 2$$

If so, it's conventional to return no hit (we only count hits going into the cylinder). Though you could instead invert the following cases to check for a hit exiting the cylinder.

**Case 1: Above / Below**

If our shifted origin is above \\$\frac {\text{height}} 2\\$ or below \\$-\frac {\text{height}} 2\\$, then we check whether its direction takes it closer to the cylinder:

$$\text{origin}\_y \times \text{direction}\_y \< 0 ?$$

If it does not, we know the ray is too high/low to ever hit the cylinder, and we can early-out with no hit.

Otherwise, we can advance the ray to the time \\$t\\$ when it crosses the plane of the cylinder's top (or bottom):

$$t\_{\text{plane}} = -\frac {\text{origin}\_y - \text{sign}(\text{origin}\_y)\frac {\text{height}} 2} {\text{direction}\_y}$$

The ray's position at that time is \\$\vec p\_1= \vec {\text{origin}} + t\_\text{plane} \cdot \vec {\text{direction}}\\$

If that point is inside the cylinder's radius,

$${p\_1}\_x^2 + {p\_1}\_z^2 \leq \text{radius}^2$$

Then we have a hit against the top/bottom cap of the cylinder, with a vertical collision normal.

If not, we can proceed as though the ray had started somewhere beside the cylinder, rather than above/below:

**Case 2: Beside**

Next we'll check if the ray hits the circle. For that we want to know the earliest positive time \\$t\\$ at which...

$$||\vec {\text{origin}} + t \cdot \vec {\text{direction}}|| = r\\ (\vec {\text{origin}} + t \cdot \vec {\text{direction}})^2 = r^2\\ t^2 \cdot \text{direction}^2 + t \cdot 2(\vec {\text{origin}} \cdot \vec {\text{direction}}) + \text{origin}^2 - r^2 = 0$$

You can solve this with quadratic formula. Choose the smallest positive solution, and call it \\$t\_\text{circle}\\$. If there is no positive real solution, return no hit.

Then, as we did with case 1, find the position at that time: \\$\vec p\_2= \vec {\text{origin}} + t\_\text{circle} \cdot \vec {\text{direction}}\\$

Now we check whether that's on our cylinder, or if it missed:

$$| {p\_2}\_y| \< \frac {\text{height}} 2 ? $$

If the hit is within this height range, then we have a hit, with collision normal parallel to \\$\vec p\_2\\$. Otherwise, we miss the cylinder and return no hit.

---

If you do find a hit, add the cylinder center back to the hit position \\$\vec p\_1\\$ or \\$\vec p\_2\\$ to get the hit position in world space.

---
Tags: c++, raycasting, intersection
---


# Question
Title: How to make prefabs UI work on any canvas scaller?
I want to make my UI prefab working on all size of canvas reference resolution scaler because I already make one which is not prefab UI its work to all reference resolution but when I make it prefab and instantiate it it's fit only specific resolution.

like this, I have reference resolution 2560x1440 which normally all UI will be set on that resolution and working fine on 720p or 1080p screen but make it prefab, it's working only on the 2960x1440 screen.

here the script for instantiating that object

public static MM_PilihAyat instance;
    private void Awake()
    {
        instance = this;
    }

    public List<_PlayerInventory> playerInventories;

    public GameObject pilihAyatPrefab;
    public Transform contentHolderPilihAyat;

    public GameObject bacaPanel;
    public Transform bacaContent;

    private void Start()
    {
        for (int i = 0; i < playerInventories.Count; i++)
        {
            GameObject go = Instantiate(pilihAyatPrefab, transform.position, transform.rotation);
            go.transform.SetParent(contentHolderPilihAyat.transform);
            MM_PilihAyatItem.instance.inventory = playerInventories[i];
        }
    }

    public void BackToBaca()
    {
        MM_PilihAyatItem.instance.BackToBaca();
        MM_BacaPanel.instance.inventory = null;
    }
```
</code></pre>

# Answer
> 0 votes
I already solve this by adding `bool worldpositionstays` when `setParent` which is in my case when instantiating the UI prefab will set on current Canvas scaler resolution

```
private void Start()
    {
        for (int i = 0; i < playerInventories.Count; i++)
        {
            GameObject go = Instantiate(pilihAyatPrefab, transform.position, transform.rotation);
            go.transform.SetParent(contentHolderPilihAyat.transform,false);
            MM_PilihAyatItem.instance.inventory = playerInventories[i];
        }
    }

```

---
Tags: unity, unity-ui
---


# Question
Title: Add a sound to all the buttons in a project
Is there an option on the texture\_button or something like that where you can specify a sound to be played on button-press. I have created a global sound\_manager but for the button presses, I have to manually code it everywhere the script has a button\_pressed signal. Or some kind of logic that when a button is pressed anywhere in the project, sound\_manager plays a particular sound.

# Answer
> 5 votes
This can be done using an AutoLoad script that connects to the "pressed" signal of all buttons in the tree.

Create a `UISoundPlayer` scene which consists of a node with an `AudioStreamPlayer` attached, which is used to play the UI sounds.

Add that scene as an AutoLoad, and attach this script to the root node:

```
extends Node

func _ready():
    # when _ready is called, there might already be nodes in the tree, so connect all existing buttons
    connect_buttons(get_tree().root)
    get_tree().connect("node_added", self, "_on_SceneTree_node_added")

func _on_SceneTree_node_added(node):
    if node is Button:
        connect_to_button(node)

func _on_Button_pressed():
    $ButtonSound.play()

# recursively connect all buttons
func connect_buttons(root):
    for child in root.get_children():
        if child is BaseButton:
            connect_to_button(child)
        connect_buttons(child)

func connect_to_button(button):
    button.connect("pressed", self, "_on_Button_pressed")

```

The code should be self-explanatory. It connects to all buttons on \_ready and to newly added buttons.

Here is an example project: https://gofile.io/d/LTBvQf

# Answer
> 1 votes
Another solution can be to make a new Scene, add an empty button to it, add a script to it and connect the pressed signal to sound\_manager inside the init function. Then use this scene for every button which should make a sound. And, if the, sound is made an export var it can be customized in the editor.

# Answer
> 0 votes
Just want to add to Jummit's answer above (which got me out a bind because I didn't plan ahead, assuming Buttons would have a built-in way to make a noise, thank you Jummit)...

Be sure to set your `UISoundPlayer` node to `Pause Mode Process` so that the sounds still play when the game is paused.

---
Tags: godot, sound
---


# Question
Title: Voxel raycasting algorithm not working correctly
I am using Unity with a compute shader to render to a texture. So far I have been checking points along the rays in units of 1 just for testing, so I know it works. Now I am simply trying to write a function that increments the ray to stop at the next voxel face, basically. And I think I understand the algorithm but my implementation is not working correctly. I included pictures of the problem below.

EDIT: Got it working, it is just really slow at 1080p. I can't really do more than a view distance of 100 without it being unplayable. If I used something like OpenGL or Vulcan, would it be significantly faster? I thought this would be fast enough because while it is Unity it's basically directX11 when it's all on the compute shader. I was really hoping this would work. And advice on how to speed it up would be much appreciated.

I later optimized the crap out of it and it is a tiny bit faster but still slow so I think it has something to do with Unity.

Here is the full compute shader:

```
#pragma kernel CSMain

RWTexture2D<float4> Result; // the actual array of pixels the player sees
float width; // in pixels
float height;

StructuredBuffer<int> voxelMaterials; // for now just getting a flat voxel array
int voxelBufferRowSize;
StructuredBuffer<float3> rayDirections; // I'm now actually using it as points instead of directions
float maxRayDistance;

float3 playerCameraPosition; // relative to the voxelData, ie the first voxel's bottom, back, left corner position, no negative coordinates
float3 playerWorldForward;
float3 playerWorldRight;
float3 playerWorldUp;

[numthreads(8, 8, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    Result[id.xy] = float4(0, 0, 0, 0); // setting the pixel to black by default
    float3 pointHolder = playerCameraPosition; // initializing the first point to the player's position
    float3 p = rayDirections[id.x + (id.y * width)]; // vector transformation getting the world space directions of the rays relative to the player
    float3 u1 = p.x * playerWorldRight;
    float3 u2 = p.y * playerWorldUp;
    float3 u3 = p.z * playerWorldForward;
    float3 direction = u1 + u2 + u3; // the direction to that point

    float distanceTraveled = 0;
    while (distanceTraveled < maxRayDistance)
    {
        // finding the distances to the next voxel on all axises
        float3 distancesXYZ = { 1000, 1000, 1000 };
        if (direction.x > 0) {
            distancesXYZ.x = (ceil(pointHolder.x) - pointHolder.x) / direction.x;
            if (distancesXYZ.x == 0) {
                distancesXYZ.x = 1 / direction.x;
            }
        }
        else if (direction.x < 0) {
            distancesXYZ.x = (floor(pointHolder.x) - pointHolder.x) / direction.x;
            if (distancesXYZ.x == 0) {
                distancesXYZ.x = 1 / abs(direction.x);
            }
        }
        if (direction.y > 0) {
            distancesXYZ.y = (ceil(pointHolder.y) - pointHolder.y) / direction.y;
            if (distancesXYZ.y == 0) {
                distancesXYZ.y = 1 / direction.y;
            }
        }
        else if (direction.y < 0) {
            distancesXYZ.y = (floor(pointHolder.y) - pointHolder.y) / direction.y;
            if (distancesXYZ.y == 0) {
                distancesXYZ.y = 1 / abs(direction.y);
            }
        }
        if (direction.z > 0) {
            distancesXYZ.z = (ceil(pointHolder.z) - pointHolder.z) / direction.z;
            if (distancesXYZ.z == 0) {
                distancesXYZ.z = 1 / direction.z;
            }
        }
        else if (direction.z < 0) {
            distancesXYZ.z = (floor(pointHolder.z) - pointHolder.z) / direction.z;
            if (distancesXYZ.z == 0) {
                distancesXYZ.z = 1 / abs(direction.z);
            }
        }

        int face = 0; // 1 = x, 2 = y, 3 = z
        // finding smallest distance along the direction to the next voxel
        float smallestDistance = 1000;
        if (distancesXYZ.x < smallestDistance) {
            smallestDistance = distancesXYZ.x;
            face = 1;
        }
        if (distancesXYZ.y < smallestDistance) {
            smallestDistance = distancesXYZ.y;
            face = 2;
        }
        if (distancesXYZ.z < smallestDistance) {
            smallestDistance = distancesXYZ.z;
            face = 3;
        }
        if (face == 0) {
            break;
        }

        pointHolder += direction * smallestDistance;
        distanceTraveled += smallestDistance;

        // convert the point into a voxel index and check if a voxel exists there

        int3 voxelIndexXYZ = { -1,-1,-1 }; // the integer coordinates within the buffer

        if (face == 1) {
            if (direction.x >= 0) {
                voxelIndexXYZ.x = floor(pointHolder.x);
            }
            else {
                if (voxelIndexXYZ.x == 0) {
                    break; // breaking and leaving the pixel black because this is out of bounds of the voxel buffer
                }
                voxelIndexXYZ.x = ceil(pointHolder.x - 1);
            }
            voxelIndexXYZ.y = floor(pointHolder.y);
            voxelIndexXYZ.z = floor(pointHolder.z);
        }
        else if (face == 2) {
            if (direction.y >= 0) {
                voxelIndexXYZ.y = floor(pointHolder.y);
            }
            else {
                if (voxelIndexXYZ.y == 0) {
                    break; // breaking and leaving the pixel black because this is out of bounds of the voxel buffer
                }
                voxelIndexXYZ.y = ceil(pointHolder.y - 1);
            }
            voxelIndexXYZ.x = floor(pointHolder.x);
            voxelIndexXYZ.z = floor(pointHolder.z);
        }
        else if (face == 3) {
            if (direction.z >= 0) {
                voxelIndexXYZ.z = floor(pointHolder.z);
            }
            else {
                if (voxelIndexXYZ.z == 0) {
                    break; // breaking and leaving the pixel black because this is out of bounds of the voxel buffer
                }
                voxelIndexXYZ.z = ceil(pointHolder.z - 1);
            }
            voxelIndexXYZ.y = floor(pointHolder.y);
            voxelIndexXYZ.x = floor(pointHolder.x);
        }
        else {
            break;
        }

        //check if voxelIndexXYZ is within bounds of the voxel buffer
        if (voxelIndexXYZ.x < voxelBufferRowSize && voxelIndexXYZ.x >= 0 &&
            voxelIndexXYZ.y < voxelBufferRowSize && voxelIndexXYZ.y >= 0 &&
            voxelIndexXYZ.z < voxelBufferRowSize && voxelIndexXYZ.z >= 0)
        {
            int voxelIndex = voxelIndexXYZ.x + (voxelIndexXYZ.z * voxelBufferRowSize) + (voxelIndexXYZ.y * (voxelBufferRowSize * voxelBufferRowSize)); // the voxel index in the flat array

            if (voxelMaterials[voxelIndex] == 1) { // if the voxel has a material ID of 1, using integers to represent materials, 0 is empty
                Result[id.xy] = float4((distanceTraveled / maxRayDistance) * 2, (float)voxelIndex / (voxelBufferRowSize * voxelBufferRowSize * voxelBufferRowSize), pointHolder.z, 0); // giving it a crazy color
                break;
            }
        }
    }
}

```

That code produces this:

and in case you were curious this is what it looks like marching the ray by 1 unit. It was taken at a different time without the middle pole of voxels and a smaller view distance which changes the color.

The bottom is two layers deep. Marching the ray by one actually looks cool except it violently wiggles around when the player moves.

# Answer
(Apologies, I'm not familiar with Unity/HLSL at all, so my syntax may be wonky.)

Let's restart, with

```
float4  eye;     // Player camera position, .w = 0
float4  proj0;   // Corner of the projection plane, .w = 0
float4  projX;   // Projection plane X axis, .w = 0
float4  projY;   // Projection plane Y axis, .w = 0

```

so that picture plane pixel `uint3 id` is at `proj0 + id.x*projX + id.y*projY` in the voxel coordinates. (We'll use the w component for the distance, saving a number of operations; that's why these are four-component vectors.)

The ray starting point `position` and unit direction vector `unitdir` are then

```
float4  position = proj0 + id.x*projX + id.y*projY;
float4  unitdir = normalize(start - eye);

```

We can save some operations if we set

```
position.w = 0.0f;
unitdir.w = 1.0f;

```

here, but that's the sort of optimization you'll need to do yourself here.

Next, we need the distances to the very first faces the ray intersects (as measured along the ray itself):

```
float xstart, ystart, zstart;

if (unitdir.x > 0) {
    xstart = (1.0f + floor(unitdir.x) - unitdir.x) / unitdir.x;
} else
if (unitdir.x < 0) {
    xstart = (floor(unitdir.x) - unitdir.x) / unitdir.x;
} else {
    xstart = +INF;
}

if (unitdir.y > 0) {
    ystart = (1.0f + floor(unitdir.y) - unitdir.y) / unitdir.y;
} else
if (unitdir.y < 0) {
    ystart = (floor(unitdir.y) - unitdir.y) / unitdir.y;
} else {
    ystart = +INF;
}

if (unitdir.y > 0) {
    zstart = (1.0f + floor(unitdir.z) - unitdir.z) / unitdir.z;
} else
if (unitdir.y < 0) {
    zstart = (floor(unitdir.z) - unitdir.z) / unitdir.z;
} else {
    zstart = +INF;
}

```

The part in parentheses is the distance along the axis, so dividing by the same axis unit vector component we get the length along the ray.

Note that `xstart`, `ystart`, and `zstart` are all positive.

Again, the above can be computed much more efficiently. Now, we initialize the first positions where the ray intersects the first face of each type,

```
float4  xnext = position + xstart * unitdir;
float4  ynext = position + ystart * unitdir;
float4  znext = position + zstart * unitdir;
xnext.w = xstart;  // This can be omitted, since position.w = 0 and unitdir.w = 1
ynext.w = ystart;  // This can be omitted, since position.w = 0 and unitdir.w = 1
znext.w = zstart;  // This can be omitted, since position.w = 0 and unitdir.w = 1

```

and when we "use" one of those vectors, we add the corresponding delta,

```
float4  xdelta = (1.0f / unitdir.x) * unitdir;
float4  ydelta = (1.0f / unitdir.y) * unitdir;
float4  zdelta = (1.0f / unitdir.z) * unitdir;
xdelta.w = 1.0f / unitdir.x;  // This can be omitted, since unitdir.w = 1
ydelta.w = 1.0f / unitdir.y;  // This can be omitted, since unitdir.w = 1
zdelta.w = 1.0f / unitdir.z;  // This can be omitted, since unitdir.w = 1

```

The actual ray traversal loop is then

```
int4   cell;  /* Cell integer coordinates */
float4 cellf; /* Fractional cell coordinates */
uint   face;  /* Face, edge, or vertex */

while (1) {
    if (position.w >= maxRayDistance) {
        face = 0;
        break;
    }

    if (xnext.w < ynext.w && xnext.w < znext.w) {
        position = xnext;
        xnext += xdelta;
        face = 1;  // X face
    } else
    if (ynext.w < xnext.w && ynext.w < znext.w) {
        position = ynext;
        ynext += ydelta;
        face = 2;  // Y face
    } else
    if (znext.w < xnext.w && znext.w < ynext.w) {
        position = znext;
        znext += zdelta;
        face = 4;  // Z face
    } else
    if (xnext.w == ynext.w && xnext.w < znext.w) {
        position = xnext;
        xnext += xdelta;
        ynext += ydelta;
        face = 3;  // XY edge
    } else
    if (xnext.w == znext.w && xnext.w < ynext.w) {
        position = xnext;
        xnext += xdelta;
        znext += zdelta;
        face = 5;  // XZ edge
    } else
    if (ynext.w == znext.w && ynext.w < xnext.w) {
        position = ynext;
        ynext += ydelta;
        znext += zdelta;
        face = 6;  // YZ edge
    } else
    if (xnext.w == ynext.w && xnext.w == znext.w) {
        position = xnext;
        xnext += xdelta;
        ynext += ydelta;
        znext += zdelta;
        face = 7;  // XYZ vertex
    } else {
        // .w are all +INF
        face = 0;
        break;
    }

    cellf = modf(position, cell);

    // We intersected with 'face' at cell
    //     cell.x, cell.y, cell.z
    // with fractional coordinates
    //     cellf.x, cellf.y, cellf.z
    // The exact coordinates are
    //     position.x = cell.x + cellf.x
    //     position.y = cell.y + cellf.y
    //     position.z = cell.z + cellf.z
    // but note that cellf can be negative.

    // TODO: Examine the voxel buffer.
    // Note: position.w is the distance from the projection plane
    //       to the face intersection point.  This can be useful
    //       for depth buffers.
}

```

It is up to you if you use `face` at all, but all eight cases do need to be handled. (It is unlikely the eighth case ever occurs, but it's good to be thorough, methinks.)
> 1 votes

# Answer
Here is a full C99/C11 implementation of a simple voxel renderer.

First, let's define `vectors.h`, for `float3`, `float4`, and `int4` support:

```
// SPDX-License-Identifier: CC0-1.0
//
#ifndef  VECTORS_H
#define  VECTORS_H
#include <math.h>

/*
 *  float3 support
*/

typedef struct {
    float   x;
    float   y;
    float   z;
} float3;

static inline float3  Float3(const float x, const float y, const float z)
{
    const float3  result = { x, y, z };
    return result;
}

static inline float3  float3_sub3(const float3 a, const float3 b)
{
    const float3  result = { a.x - b.x, a.y - b.y, a.z - b.z };
    return result;
}

static inline float3  float3_add3(const float3 a, const float3 b)
{
    const float3  result = { a.x + b.x, a.y + b.y, a.z + b.z };
    return result;
}

static inline float  float3_length(const float3 a)
{
    return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z);
}

static inline float  float3_dot(const float3 a, const float3 b)
{
    return a.x*b.x + a.y*b.y + a.z*b.z;
}

static inline float3  float3_cross(const float3 a, const float3 b)
{
    const float3  result = { a.y*b.z-a.z*b.y, a.z*b.x-a.x*b.z, a.x*b.y-a.y*b.x };
    return result;
}

static inline float3  float3_mul1(const float3 a, const float b)
{
    const float3  result = { a.x*b, a.y*b, a.z*b };
    return result;
}

static inline float3  float3_scale_to_length(const float3 a, const float b)
{
    const float n = float3_length(a);
    const float3  result = { a.x*b/n, a.y*b/n, a.z*b/n };
    return result;
}

/*
 *  float4 support
*/

typedef struct {
    float   x;
    float   y;
    float   z;
    float   w;
} float4;

static inline float4  Float4(const float x, const float y, const float z, const float w)
{
    const float4  result = { x, y, z, w };
    return result;
}

/* float4_length(a) == || a ||, Euclidean length of vector a */
static inline float  float4_length(const float4 a)
{
    return sqrtf(a.x*a.x + a.y*a.y + a.z*a.z + a.w*a.w);
}

/* float4_normalize(a) == a / || a || */
static inline float4  float4_normalize(const float4 a)
{
    const float   n = float4_length(a);
    const float4  result = { a.x/n, a.y/n, a.z/n, a.w/n };
    return result;
}

/* float4_sign(a): Component-wise sign: -1.0, 0.0, or +1.0 */
static inline float4  float4_sign(const float4 a)
{
    const float4  result = { (a.x < 0.0f) ? -1.0f : (a.x > 0.0f) ? +1.0f : 0.0f,
                             (a.y < 0.0f) ? -1.0f : (a.y > 0.0f) ? +1.0f : 0.0f,
                             (a.z < 0.0f) ? -1.0f : (a.z > 0.0f) ? +1.0f : 0.0f,
                             (a.w < 0.0f) ? -1.0f : (a.w > 0.0f) ? +1.0f : 0.0f };
    return result;
}

/* float4_max(a, b): Component-wise maximum */
static inline float4  float4_max4(const float4 a, const float4 b)
{
    const float4  result = { (a.x >= b.x) ? a.x : b.x,
                             (a.y >= b.y) ? a.y : b.y,
                             (a.z >= b.z) ? a.z : b.z,
                             (a.w >= b.w) ? a.w : b.w };
    return result;
}

/* float4_min(a, b): Component-wise minimum */
static inline float4  float4_min4(const float4 a, const float4 b)
{
    const float4  result = { (a.x <= b.x) ? a.x : b.x,
                             (a.y <= b.y) ? a.y : b.y,
                             (a.z <= b.z) ? a.z : b.z,
                             (a.w <= b.w) ? a.w : b.w };
    return result;
}

/* float4_add(a, b) == a + b */
static inline float4  float4_add4(const float4 a, const float4 b)
{
    const float4  result = { a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w };
    return result;
}

/* float4_sub4(a, b) == a - b */
static inline float4  float4_sub4(const float4 a, const float4 b)
{
    const float4  result = { a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w };
    return result;
}

/* float4_floor4(a): Round each component towards negative infinity */
static inline float4  float4_floor4(const float4 a)
{
    const float4  result = { floorf(a.x), floorf(a.y), floorf(a.z), floorf(a.w) };
    return result;
}

/* float4_mul1(a, b) = { a.x*b, a.y*b, a.z*b, a.w*b } */
static inline float4  float4_mul1(const float4 a, const float b)
{
    const float4  result = { a.x*b, a.y*b, a.z*b, a.w*b };
    return result;
}

/* float4_div1(a, b) = { a.x/b, a.y/b, a.z/b, a.w/b } */
static inline float4  float4_div1(const float4 a, const float b)
{
    const float4  result = { a.x/b, a.y/b, a.z/b, a.w/b };
    return result;
}

/* float4_div4(a, b) = { a.x/b.x, a.y/b.y, a.z/b.x, a.w/b.w } */
static inline float4  float4_div4(const float4 a, const float4 b)
{
    const float4  result = { a.x/b.x, a.y/b.y, a.z/b.z, a.w/b.w };
    return result;
}

/*
 * int4 support
*/

typedef struct {
    int     x;
    int     y;
    int     z;
    int     w;
} int4;

static inline int4  Int4(const int x, const int y, const int z, const int w)
{
    const int4  result = { x, y, z, w };
    return result;
}

static inline int4  int4_add4(const int4 a, const int4 b)
{
    const int4  result = { a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w };
    return result;
}

/* float4_int4(a): Component-wise cast to int. */
static inline int4  float4_int4(const float4 a)
{
    const int4  result = { (int)floorf(a.x), (int)floorf(a.y), (int)floorf(a.z), (int)floorf(a.w) };
    return result;
}

#endif /* VECTORS_H */

```

Here is the example renderer, `render.c`:

```
// SPDX-License-Identifier: CC0-1.0
//
// Compile using e.g.
//      gcc -DSPHERE -Wall -Wextra -O2 render.c -lm -o render
// or a simpler test with
//      gcc -Wall -Wextra -O2 render.c -lm -o render

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include "vectors.h"

float4           voxel_rgba[256][8];    /* Look-up table for voxel faces; all components [0..1]. x is red, y is green, z is blue, w is opacity (0=transparent, 1=opaque). */
int4             voxel_size;
unsigned char   *voxel_cell = NULL;
size_t           voxel_xstride = 0;     /* Typically 1 */
size_t           voxel_ystride = 0;     /* Typically voxel_size.x */
size_t           voxel_zstride = 0;     /* Typically voxel_size.x * voxel_size.y */

/* Trace one voxel ray starting at (projection plane) pos, with eye/camera at eye.
 * Return the color and distance { .x=red, .y=green, .z=blue, .w=distance }
*/
float4 voxel_ray(float4 eye, float4 pos, float maxdist)
{
    /* On input, eye and pos are really 3-component vectors; we need the fourth one to be zero,
       so that it won't affect the unit direction length vector below. */
    eye.w = 0.0f;
    pos.w = 0.0f;

    /* Ray unit direction vector */
    float4  dir = float4_normalize(float4_sub4(pos, eye));
    /* We rely on the .w component to track length, so set that one now. */
    dir.w = 1.0f;

    float4  posf = float4_sub4(pos, float4_floor4(pos));
    /* Note: 0 <= posf.x < 1,
             0 <= posf.y < 1,
             0 <= posf.z < 1. */

    /* Find first intersections with a voxel cell wall (*next),
       and the delta to the consecutive following intersections */
    float4  xnext,  ynext,  znext;
    float4  xdelta, ydelta, zdelta;

    if (dir.x > 0.0f) {
        xnext  = float4_add4(pos, float4_mul1(dir, (1.0f - posf.x) / dir.x));
        xdelta = float4_div1(dir, dir.x);
    } else
    if (dir.x < 0.0f) {
        xnext  = float4_add4(pos, float4_mul1(dir, -posf.x / dir.x));
        xdelta = float4_div1(dir, -dir.x);
    } else {
        xnext  = Float4(0.0f, 0.0f, 0.0f, maxdist);
        xdelta = Float4(0.0f, 0.0f, 0.0f, 0.0f);
    }

    if (dir.y > 0.0f) {
        ynext  = float4_add4(pos, float4_mul1(dir, (1.0f - posf.y) / dir.y));
        ydelta = float4_div1(dir, dir.y);
    } else
    if (dir.y < 0.0f) {
        ynext  = float4_add4(pos, float4_mul1(dir, -posf.y / dir.y));
        ydelta = float4_div1(dir, -dir.y);
    } else {
        ynext  = Float4(0.0f, 0.0f, 0.0f, maxdist);
        ydelta = Float4(0.0f, 0.0f, 0.0f, 0.0f);
    }

    if (dir.z > 0.0f) {
        znext  = float4_add4(pos, float4_mul1(dir, (1.0f - posf.z) / dir.z));
        zdelta = float4_div1(dir, dir.z);
    } else
    if (dir.z < 0.0f) {
        znext  = float4_add4(pos, float4_mul1(dir, -posf.z / dir.z));
        zdelta = float4_div1(dir, -dir.z);
    } else {
        znext  = Float4(0.0f, 0.0f, 0.0f, maxdist);
        zdelta = Float4(0.0f, 0.0f, 0.0f, 0.0f);
    }

    float4  color = { 0.0f, 0.0f, 0.0f, 0.0f };  /* Transparent! */

    while (1) {
        unsigned char  intersection = 0;    /* 1:x, 2:y, 4:z */

        if (pos.w >= maxdist) {
            pos.w = maxdist;
            break;
        }
        if (color.w >= 1.0f)
            break;

        /* Pick the closest next step first. */
        pos = xnext;
        if (pos.w > ynext.w) {
            pos = ynext;
        }
        if (pos.w > znext.w) {
            pos = znext;
        }

        /* Update intersection and prepare for the next step. */
        if (pos.w >= xnext.w) {
            intersection |= 1;
            xnext = float4_add4(xnext, xdelta);
        }
        if (pos.w >= ynext.w) {
            intersection |= 2;
            ynext = float4_add4(ynext, ydelta);
        }
        if (pos.w >= znext.w) {
            intersection |= 4;
            znext = float4_add4(znext, zdelta);
        }

        /* If pos.w == INF, we have intersection = 0. */
        if (!intersection) {
            pos.w = maxdist;
            break;
        }

        /* Position within the wraparound voxel space. */
        float4  temp = float4_floor4(pos);
        int4    posi = float4_int4(temp);
        /* We could use the fractional positive sub-voxel coordinates posf,
              posf = float4_sub4(pos, temp);
           where 0 <= posf.x < 1, 0 <= posf.y < 1, 0 <= posf.z < 1
           and if (intersection & 1), posf.x = 0 (except for rounding errors),
               if (intersection & 2), posf.y = 0 (except for rounding errors),
               if (intersection & 4), posf.z = 0 (except for rounding errors),
           for interpolation etc.
        */

        /* Adjust cell coordinates so that each cell always defines an outer wall. */
        if ((intersection & 1) && (dir.x < 0.0f)) --posi.x;
        if ((intersection & 2) && (dir.y < 0.0f)) --posi.y;
        if ((intersection & 4) && (dir.z < 0.0f)) --posi.z;

        /* Ensure posi is within the positive voxel space. */
        posi.x = posi.x % voxel_size.x; if (posi.x < 0) posi.x += voxel_size.x;
        posi.y = posi.y % voxel_size.y; if (posi.y < 0) posi.y += voxel_size.y;
        posi.z = posi.z % voxel_size.z; if (posi.z < 0) posi.z += voxel_size.z;

        /* Look up the voxel cell properties for this intersection. */
        float4  c = voxel_rgba[voxel_cell[ (size_t)posi.x * voxel_xstride
                                         + (size_t)posi.y * voxel_ystride
                                         + (size_t)posi.z * voxel_zstride ]][ intersection ];

        if (c.w >= 1.0f) {
            /* Opaque; good, ray ends here. Blend 'c' behind 'color'. */
            color = float4_add4(color, float4_mul1(c, 1.0f - color.w));
            break;
        } else
        if (c.w > 0.0f) {
            /* Blend color 'color' *behind* color 'c'. */
            color = float4_add4(color, float4_mul1(c, 1.0f - color.w));
        }
    }
    color.w = pos.w;
    return color;
}

void renderPPM(FILE *outppm, FILE *outpgm, int width, int height, const float3 eye, const float3 forward, const float3 right, const float maxdist)
{
    /* Assume 'right' is perpendicular to 'forward'.  'up' is perpendicular to both, with length (height/width) times that of 'right'. */
    const float3  up = float3_scale_to_length(float3_cross(forward, right), float3_length(right) * (float)height / (float)width);

    /* Image plane corner, rowstart = eye + forward - right + up */
    float3  rowstart = float3_add3(float3_sub3(float3_add3(eye, forward), right), up);

    /* Delta vectors per pixel for the image plane */
    const float3  dx = float3_mul1(right, 2.0f / (float)width);
    const float3  dy = float3_mul1(up,   -2.0f / (float)height);

    if (outppm) fprintf(outppm, "P6\n%d %d 255\n", width, height);
    if (outpgm) fprintf(outpgm, "P5\n%d %d 255\n", width, height);

    float  mind = +3.0f*maxdist;
    float  maxd = -3.0f*maxdist;

    for (int y = 0; y < height; y++, rowstart = float3_add3(rowstart, dy)) {
        float3  pos = rowstart;
        for (int x = 0; x < width; x++, pos = float3_add3(pos, dx)) {
            const float4  c = voxel_ray( Float4(eye.x, eye.y, eye.z, 0.0f),
                                         Float4(pos.x, pos.y, pos.z, 0.0f), maxdist);
            const int  r8 = (c.x <= 0.0f) ? 0 : (c.x < 1.0f) ? (int)(0.5f + 255.0f * c.x) : 255;
            const int  g8 = (c.y <= 0.0f) ? 0 : (c.y < 1.0f) ? (int)(0.5f + 255.0f * c.y) : 255;
            const int  b8 = (c.z <= 0.0f) ? 0 : (c.z < 1.0f) ? (int)(0.5f + 255.0f * c.z) : 255;
            const int  d8 = (c.w <= 0.0f) ? 0 : (c.w < maxdist) ? (int)(0.5f + 255.0f * c.w / maxdist) : 255;
            if (c.w < maxdist) {
                if (mind > c.w) mind = c.w;
                if (maxd < c.w) maxd = c.w;
            }

            if (outppm) {
                fputc(r8, outppm);
                fputc(g8, outppm);
                fputc(b8, outppm);
            }
            if (outpgm) {
                fputc(d8, outpgm);
            }
        }
        fprintf(stderr, "\rRow %d of %d completed.", y + 1, height);
        fflush(stderr);
    }

    if (outppm) fflush(outppm);
    if (outpgm) fflush(outpgm);
    fprintf(stderr, "\rRendering complete. Distances varied between %.6f and %.6f.\n", mind, maxd);
    fflush(stderr);
}

int main(int argc, char *argv[])
{
    FILE *ppm, *pgm;

    if (argc != 3 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
        const char *arg0 = (argc > 0 && argv && argv[0] && argv[0][0]) ? argv[0] : "(this)";
        fprintf(stderr, "\n");
        fprintf(stderr, "Usage: %s [ -h | --help ]\n", arg0);
        fprintf(stderr, "       %s OUT.ppm DEPTH.pgm\n", arg0);
        fprintf(stderr, "\n");
        return EXIT_FAILURE;
    }

    voxel_size.x = 64;
    voxel_size.y = 64;
    voxel_size.z = 64;

    voxel_xstride = 1;
    voxel_ystride = (size_t)voxel_size.x;
    voxel_zstride = voxel_ystride * (size_t)voxel_size.y;
    const size_t  size = voxel_zstride * (size_t)voxel_size.y;

    voxel_cell = (unsigned char *)malloc(size);
    if (!voxel_cell) {
        fprintf(stderr, "Not enough memory for a %d x %d x %d voxel map.\n", voxel_size.x, voxel_size.y, voxel_size.z);
        return EXIT_FAILURE;
    }
    memset(voxel_cell, 0, size);

    /* Make all cell values transparent, */
    for (int i = 0; i < 256; i++) {
        for (int k = 0; k < 8; k++) {
            voxel_rgba[i][k] = Float4(0.0f, 0.0f, 0.0f, 0.0f);
        }
    }

    /* Cell type 1 faces are blue, red, and green; edges and vertices their mix. */
    voxel_rgba[1][1] = Float4(0.0f, 0.0f, 1.0f, 1.0f);
    voxel_rgba[1][2] = Float4(0.0f, 1.0f, 0.0f, 1.0f);
    voxel_rgba[1][4] = Float4(1.0f, 0.0f, 0.0f, 1.0f);
    voxel_rgba[1][3] = Float4(0.0f, 0.8f, 0.8f, 1.0f);
    voxel_rgba[1][5] = Float4(0.8f, 0.0f, 0.8f, 1.0f);
    voxel_rgba[1][6] = Float4(0.8f, 0.8f, 0.0f, 1.0f);
    voxel_rgba[1][7] = Float4(0.6f, 0.6f, 0.6f, 1.0f);

#ifdef SPHERE
    /* Create a shell at the center, minradius 10, maxradius 12 */
    {
        const int  cx = 32;
        const int  cy = 32;
        const int  cz = 32;
        const int  rrmin = 10*10;
        const int  rrmax = 12*12;

        for (int z = 0; z < voxel_size.z; z++) {
            const int  zz = (z-cz)*(z-cz);
            for (int y = 0; y < voxel_size.y; y++) {
                const int  zzyy = zz + (y-cy)*(y-cy);
                for (int x = 0; x < voxel_size.x; x++) {
                    const int  dd = zzyy + (x-cx)*(x-cx);
                    if (dd >= rrmin && dd < rrmax) {
                        voxel_cell[(size_t)x * voxel_xstride + (size_t)y * voxel_ystride + (size_t)z * voxel_zstride] = 1;
                    }
                }
            }
        }
    }
#else
    voxel_cell[voxel_xstride + voxel_ystride] = 1;
    voxel_cell[voxel_xstride] = 1;
    voxel_cell[voxel_ystride] = 1;
    voxel_cell[voxel_zstride] = 1;
#endif

    fprintf(stderr, "Constructed a %d x %d x %d voxel map.\n", voxel_size.x, voxel_size.y, voxel_size.z);

    ppm = fopen(argv[1], "wb");
    if (!ppm) {
        fprintf(stderr, "%s: %s.\n", argv[1], strerror(errno));
        return EXIT_FAILURE;
    }
    pgm = fopen(argv[2], "wb");
    if (!pgm) {
        fprintf(stderr, "%s: %s.\n", argv[2], strerror(errno));
        fclose(ppm);
        remove(argv[1]);
        return EXIT_FAILURE;
    }

#ifdef SPHERE
    renderPPM(ppm, pgm, 512, 384, Float3(0.0f, 0.0f, 0.0f), Float3(4.0f, 5.0f, 6.0f), Float3(4.0f, -2.0f, -1.0f), 128.0f);
#else
    renderPPM(ppm, pgm, 512, 512, Float3(-8.0f, -8.0f, -8.0f), Float3(1.0f, 4.0f, 4.0f), Float3(-1.0f, 0.0f, 1.0f), 9.0f);
#endif

    if (fclose(ppm)) {
        fprintf(stderr, "%s: Error closing file.\n", argv[1]);
        fclose(pgm);
        remove(argv[1]);
        remove(argv[2]);
        return EXIT_FAILURE;
    }
    if (fclose(pgm)) {
        fprintf(stderr, "%s: Error closing file.\n", argv[2]);
        remove(argv[1]);
        remove(argv[2]);
        return EXIT_FAILURE;
    }

    fprintf(stderr, "Saved PPM image as '%s', and depth graymap as PGM image '%s'.\n", argv[1], argv[2]);
    return EXIT_SUCCESS;
}

```

There were issues in `xnext`, `ynext`, `znext`, `xdelta`, `ydelta`, and `zdelta` calculations, causing each voxel cell to be displayed as intersecting planes, instead of cube walls. It is important to note that when correct, they all have nonnegative `w` components, and that `xnext.x`, `xdelta.x`, `ynext.y`, `ydelta.y`, `znext.z`, and `zdelta.z` are all integers.

The code that makes the voxel space periodic is this:

```
        /* Position within the wraparound voxel space. */
        float4  temp = float4_floor4(pos);
        int4    posi = float4_int4(temp);

        /* Ensure posi is within the positive voxel space. */
        posi.x = posi.x % voxel_size.x; if (posi.x < 0) posi.x += voxel_size.x;
        posi.y = posi.y % voxel_size.y; if (posi.y < 0) posi.y += voxel_size.y;
        posi.z = posi.z % voxel_size.z; if (posi.z < 0) posi.z += voxel_size.z;

```

Floating-point vector modulo can also be used, but be careful of the semantics: usually, the remainder has the same sign as the argument, but here we want the *positive* remainder.

If you don't mind mirroring the voxel space, you can use something like `posi = floor(modf(abs(pos), size))` instead in HLSL. Then, positive voxel space is periodic, but is mirrored with respect to each axial plane (x=0, y=0, and z=0).

To move each voxel cell wall towards the eye, I added the section

```
        /* Adjust cell coordinates so that each cell always defines an outer wall. */
        if ((intersection & 1) && (dir.x < 0.0f)) --posi.x;
        if ((intersection & 2) && (dir.y < 0.0f)) --posi.y;
        if ((intersection & 4) && (dir.z < 0.0f)) --posi.z;

```

You can replace this with a single vector addition or subtraction, if you create an array of 8 vectors (one for each possible intersection type).

Without this adjustment, looking towards negative x would show the y and z faces of the cell before the x face. This is because normally, the cells have only three faces, and to create a cube, you need to set *four* voxel cells: (0,0,0) has all three faces, (+1,0,0) has the opposite x face, (0,+1,0) has the opposite y face, and (0,0,+1) has the opposite z face.

What the above adjustment does, is shift the voxel cell walls so that they always face the eye. So, each voxel effectively has six faces.

This is what the results look like, if compiled with `SPHERE` defined (`-DSPHERE`):
> 0 votes

# Answer
For optimizing voxel tracing, I can think of two different approaches:

1. Multi-level mapping to skip larger empty volumes
2. Ganged initial tracing, so that a single tracer handles the common parts of many rays

---

Multi-level mapping means that you have an additional voxel map for blocks of k×k×k voxels. At minimum, each block is just a flag whether that block is empty or not. Point `(x, y, z)` belongs to block `(floor(x/k), floor(y/k), floor(z/k))`, so you wish to pick a `k` whose inverse you can express exactly with a floating-point number; for example, a power of two (k = 2, 4, 8, 16, 32, 64, ...).

Whenever the inner tracing function notices that the voxel block changes, it checks if the voxel block is empty. If it is empty, the inner tracing function can skip the voxel block entirely (using an inner loop that advances normally, but never examines the voxel data, just loops until it exits the current voxel block).

I don't think one can expect massive speedups with this, but it can be useful if the voxel block is actually either empty, or a reference to a look-up voxel map (which are all k×k×k voxels in size). This means that large voxel maps with lots of empty regions can fit in less memory.

Another option, making the tracing non-voxel-like, is to use large voxel cells (but small tracing depths, say on the order of 50 or so maximum). When one finds the nearest next position, the current and that next position forms a line through the current voxel; between two adjacent or opposite faces. If the contents of that voxel are represented using geometric primitives et cetera, one can check if the ray intersects anything within the voxel or not. Essentially, the voxel map is then just a way to group the possibly intersecting objects into subsets.

---

Ganged initial tracing means you have two different types of tracers.

The initial tracers take four rays, each with their own starting point, direction; and the screen coordinates for the set. For example, let `S00`, `S01`, `S10`, and `S11` be their starting points (`float3` or `float4`), `D00`, `D01`, `D10`, and `D11` be their directions (`float3` or `float4`), `x0` be the screen x coordinate for `S00` and `S10`, `x1` be the screen x coordinate for `S01` and `S11`, `y0` be the screen y coordinate for `S00` and `S01`, and `y1` be the screen y coordinate for `S10` and `S11`.

As long as the four rays stay in the same voxel, they are advanced by the same tracer. Whenever they diverge, the set is split according to their screen x and y coordinates. Whenever the set refers to only four connected pixels (i.e. `x1 = x0 + 1` and `y1 = y0 + 1`), they are split into individual rays, and traced as described in my other answer as an individual ray.

The "trick" is that one cannot just use the average of the corresponding ray to calculate the added rays when splitting: they must be weighted per the coordinates.

For example, if we have `x0 = 4` and `x1 = 7`, we can choose the split point `x = 5` or `x = 6`. Whichever we pick, the new ray starting location is weighed by `(x1 - x) / (x1 - x0)` for the one corresponding to `x0`, and by `(x - x0) / (x1 - x0)` for the one corresponding to `x1`.

(Note, it may look like the weights are swapped, but they're not. Linear interpolation from `x0` to `x1` using `0 <= w <= 1` is `(1-w)*x0 + w*x1`, you see. Here, `1 - (x - x0) / (x1 - x0) = (x1 - x0 - x + x0) / (x1 - x0) = (x1 - x) / (x1 - x0)`.)

If the ganged (initial) tracer finds that the voxel cell – remember, it only progresses the rays if they stay within the same voxel cell – it has to "paint" a rectangular region of the display plane, from `(x0,y0)` to `(x1,y1)`.

Now, in my other answer, the distance to the first voxel face the ray intersects with is calculated directly; that point saved in the `xnext`, `ynext`, and `znext` vectors. The ganged tracing (for a set of four rays) can be continued as long as the rays stay in the same or neighboring voxels. So, one option would be to gang rays that have the same $y$ coordinate, as long as their first intersections are in the same voxel. Assuming the rendered image is much wider than it is tall (which is typical for humans, we have a field of vision that is wider than it is tall), this could be a suitable compromise between complexity and speedup obtained.

(Then, one type of tracer takes two rays. As soon as the dot product of the ray current position integer coordinates exceeds 1, they are split. Otherwise, the rays are advanced as a pair. Splitting uses the split point x coordinate as the weight as described above. The new split ray may not be at a voxel face, though.)

I think I shall test the horizontally ganged tracer, and compare its speed to the individual one, and report here later if it was worth it.
> 0 votes

---
Tags: raycasting, voxels, compute-shader
---