# Question
Title: In an object-oriented game engine, should there be seperate classes for objects with and without parents?
I am developing a game engine in C++ (for an idea of what kind of design I'm going for, think of ROBLOX, if you're familiar with that) and I need help with a problem I have.

So basically, the objects in a scene are called "Instances", and they can have a parent and any number of children. The problem I'm trying to solve is: what should the parent of the root Instance in the hierarchy be?

I'm considering creating a separate `BaseInstance` class which has children but no parent and have it serve as the "root" Instance in each scene, though I feel this could needlessly complicate things. The alternative is letting the "root" Instance be a regular `Instance` with a parent, but this parent is a `nullptr` (or something along those lines), and then just trust that the code will never try to reference the parent of the "root" Instance.

Another problem I'm facing is whether the scene itself should be the root instance or not.

Sorry if this comes across as unclear; I'm just really confused about what I'm supposed to do here or even how to explain what I'm trying to do.

# Answer
> 7 votes
> what should the parent of the root Instance in the hierarchy be?

Nothing.

---

**Does `Instance`s without parent make sense?**

If you, for example, might want a factory that create `Instance`, then set their properties, perhaps compose them in some way, and then attach them to the scene tree...

Or if you, for another example, might want to be able to remove an `Instance` from the scene tree, manipulate it in some way, and the reattach it to the scene tree, perhaps in a different place...

Then it make sense that an `Instance` can have no parent. More precisely that an `Instance` can either have zero or one parent, and that the parent can change in runtime.

---

**Should the root of the scene tree be something special?**

It could be an object dedicated to just being the root.

However, often the root often has other functions, such as handling where the game will be rendered to (Window, Canvas, Viewport...). Furthermore, it might make sense to have multiple of those objects (e.g. a main window with children windows).

Although, that might not apply to your engine.

I remind you that even though the scene tree has a root, there will be another code that uses it. And so it will have a reference to its root. Thus, you might have a `SceneTree` class (which is not an `Instance` and thus has no parent) that has an `Instance` which is considered to be the root of the scene tree.

The problem then becomes: How do you guarantee that the root of the scene tree has no parent?

---

Before we get to that, here is a related question: **How do you guarantee that an `Instance` does not have two parents?** That has two parts:

* There is only one parent pointer, so it can only have one parent.
* When you are going to add a child `Instance` you check if it has a parent already.

---

**How do you guarantee that the root of the scene tree has no parent?**

Well, similar logic applies to the scene tree root:

* When you set a `Instance` as the root of the scene tree, you check it does not have a parent.
* When are going to add a child `Instance` you check *also* if it is the root of the scene tree.

But I'm skipping a question...

---

**Should you be able to change the scene tree root?**

If the scene tree root is the scene root, then yes. You should be able to change it, because you should be able to change scenes. Thus, not making the scene root the scene tree root allows you create the root of the scene tree during initialization and never change it.

Thus the first point above (checking if the `Instance` you will set as root of the scene tree has a parent before setting it) would not be necessary.

And the second is easier (checking if an `Instance` is the root of the scene tree) because anybody could access the root of the scene tree via the composition root to compare.

# Answer
> 1 votes
All this is ultimately up to you. OOP is a tool, not a rule. But if you're looking for suggestions and examples, here's what I did for mine:

In my engine library, there's an abstract `Drawable` type, which represents anything that can be drawn. I gave it an X and Y coordinate and a `Draw_Self` subprogram. I messed up at first and gave it a Sprite as well (which in turn is a type that contains a `Spritesheet` (also a type), origin, boundaries, etc), even though I would later decide that not everything that can be drawn needs a Sprite (for example, text boxes that I draw with a shader and a TTF rasterization library). So don't make that mistake. Having this parent lets me do things like keep track of its subtypes in arrays and lists rather than checking booleans endlessly to decide when to draw certain things.

There's an abstract `Game_Object` type, which inherits from `Drawable` and also has some boundary coordinates that define the space it physically occupies and an `Execute` subprogram, which it uses to actually do stuff. Change position, update animations, interact with stuff, etc. In practice, I find I normally give these an `Animate` subprogram as well just to keep the logic separate. Even things like trees fall into this category, so they can handle collisions and stuff. In addition to the advantages of the `Drawable` parent, this parent allows me to do things like check for collisions and other interactions between arbitrary `Game_Object` types.

There's an abstract `Controllable` type, which inherits from `Game_Object` and has the relevant control subprograms that you need for your target input types. In my case, `Button_Down`, `Button_Up`, `Mouse_Down`, `Mouse_Up`, `Mouse_Hover`, `Mouse_Exit`. This is kind of a must so that you can handle the events at an engine level and just call these functions on whatever object has the focus. It inherits from `Game_Object` and not `Drawable` directly, because anything that responds to input *does* something.

I also have a handful of reusable *non*-abstract implementations of these things as well, such as menus.

I've also made an abstract `Game_State` class, which I believe is similar to what you call a scene. This has `Initialize`, `Execute`, `Draw` and the same `Input` subprograms named above. These are things like the main menu, the pause menu, the world map, etc. The main engine loop keeps a list of these, picks the first item in the list, propagates inputs to the proper subprogram, runs its `Execute`, then its `Draw`. New `Game_States` are prepended to the list and popped LIFO when no longer needed. Each `Game_State` manages its own `Drawables`, `Game_Objects` and `Controllables`, figures out which of these to `Execute` and `Draw` when, checks for collisions, etc.

Now, I'm by no means an expert (I made all of this up as I developed it), so there are probably still a lot of ways to improve it. But more important than the specifics of what I did is the idea that your structure serves a purpose. It's not a right/wrong answer, but rather how do I organize all this functionality?

---
Tags: architecture, design-patterns, oop, objects
---


# Question
Title: How to sub-divide a hexagonal grid reference system
I have been using @amitp's excellent guide (and javascript library) to create a hexagonal grid system https://www.redblobgames.com/grids/hexagons/. I'm using flat-top, inverse-y cubic/axial system. However, I have elements that are located on the vertices, rather than "within" a tile. How would I refer to their position? I have considered using the index of the corner, but then the question is which tile do I use as my base? I would also like to extend the concept so that I could precisely position an element anywhere within a tile. I am thinking of something relating to the Ordnance Survey's method of sub-division within the British National Grid (OSGB 1936) but I cannot get my head around how this relates to a cubic/axial coordinate system.

# Answer
> I have considered using the index of the corner, but then the question is which tile do I use as my base?

In an (infinite) hexagonal grid, every hex got 6 adjacent vertices and every vertex is shared by 3 adjacent hexes. That means that if you want each vertex to "belong" to one and only one hex, then each hex would have to "own" two vertices. That way every vertex would have an "owner". Which two vertices? That's up to you. If you choose the same two vertices of each hex (the upper pair, the lower pair, left&right, or any other), then you will notice that every vertex now clearly belongs to a hex.

Unless, of course, if you have a finite grid. Then you would have vertices at the border which would need to be owned by a "virtual" hex that's outside of the grid. But that's a problem you have with rectangular tiles as well.

That means you can address every vertex by the address of its owning tile, plus an additional bit for "left vertex" or "right vertex".

> I would also like to extend the concept so that I could precisely position an element anywhere within a tile.

In that case I would use a sub-coordinate system for position within the tile. For consistency, I would recommend to use the same axis conventions as you are using for the tiles themselves. But that might depend on your requirements and personal preference.
> 1 votes

# Answer
**Only regarding your first question**

> but then the question is which tile do I use as my base?

ANY as long as you use a consistent scheme. For example ALWAYS find the leftmost tile (you need phantom extra ones for the edge of your map), and then (if applicable) the topmost of the two possible ones.

And then you only have one line (with a bent) on which to place any objects
> 0 votes

# Answer
An answer depends on a couple of facts: Can your elements only rest on vertices? If not can they move from a vertex of a hex to the center of that hex?

My first thought on this question was to set each vertex's coordinates to the average of the coordinates of the 3 hex' surrounding it, for instance, if a unit was on the vertex between the three tiles \[0, 0\], \[0, -1\] and \[+1, -1\] it would have the coordinate \[0.5, -1\].

But this results in two issues: one the vertex coordinates aren't unique when compared to the hex coordinates (There is a \[-2, +1\] tile and its rightmost vertex is also \[-2, +1\]) and two, referring back to my questions, if the elements can move from vertices to hex center's then when working out the distance becomes weird. Basically the distance from a vertex to an adjacent vertex is 1, from a vertex to one of the connected hexes' centers is also 1 and from a vertex to another vertex that is 2 vertices away (i.e. with flat top hexes from the left most vertex to the top right vertex) is a distance of 1.5 .

In other words the distance from hex to hex becomes equal to that from vertex to vertex with a couple twists.

Hopefully this helps, if you need images to show what I'm describing I can create them but I would rather wait for you to ask for them first.
> 0 votes

# Answer
Maybe I'm late, but I'm having similar problems, so here's my 6 cents

If you think about it, you can refer to the corners as neigbors of the center of the hexagon, and the actual neighboring hexagons then become diagonal neighbors. That is, you get a pointy top subdivided coordinate system. And you can easily make it by taking a (hex)vector, rotating it in some direction, and adding the rotated one to the original. You can simplify it to a very cheap calculation, and here's my implementation of it (c#):

GetSubdividedVector(HexVector v) =\> new(v.q - v.r, v.r - v.s, v.s - v.q);

This will work great. Take note, that the new vector will have a smaller Size, (Size * (sqrt(3)/3)) to be exact.

I'm using this system to consistently label corner verticies and check overlapping positions as floating point errors would make it impossible after converting to world space.

Now tho, good luck reversing the process, that's what I'm struggling with rn
> 0 votes

---
Tags: hexagonal-grid
---


# Question
Title: 3D Impulse based collision resolution not behaving correctly, what could be wrong?
I've implemented a collision resolution system based on Ian Mellington's System Cyclone and afterwards based on the *Game Physics Cookbook*. Currently the last one is implemented.

For some reason the system behaves oddly. If I set up a test, where the cube drops from a bit up the Y-axis and with 45 degree rotation over the x axis it just stays on that edge, then it starts moving around weirdly. That last part is due to friction.

A video sample here

You should be able to see the contact points and their normal (up the Y axis)

If I move the object and slam it into a wall, it will end up rotating forever.

It's not the dampening, since that works fine - apply a force without gravity for instance and everything stops eventually.

It's not the inertia tensor.

The contact normal is pointing towards "B", meaning that it has to be negative for the object to be treated as "A"

The code is as follows:

```
while (currentiteration < 8) {
    for (int cidx = 0; cidx < contactDataFrame.size(); cidx++) {
        //apply impulse, frictionless
        {
            GVECTOR relativeContactPoint = Math::VectorSubtract(contactDataFrame[cidx].contactpoint, mPhysicsOBJData[0].position);
            GVECTOR closingVelocity = Math::VectorNegate(Math::VectorAdd(mPhysicsOBJData[0].velocity, Math::Vector3Cross(mPhysicsOBJData[0].rotation, relativeContactPoint)));

            float dp = Math::Vector3Dot(closingVelocity, Math::VectorNegate(contactDataFrame[cidx].contactnormal)).m128_f32[0];

            if (dp > 0.0f) {
                continue;
            }

            float numerator = (-(1.0f + restitution)) * dp;

            GMATRIX tensor = transformedTensors[0];;
            GVECTOR torque = Math::Vector3Cross(Math::Vec3MultiplyMatrixRHS(Math::Vector3Cross(relativeContactPoint, Math::VectorNegate(contactDataFrame[cidx].contactnormal)), tensor), relativeContactPoint);

            float denominator = mPhysicsOBJData[0].inverseMass + Math::Vector3Dot(Math::VectorNegate(contactDataFrame[cidx].contactnormal), torque).m128_f32[0];
            if (denominator == 0.0f) {
                PRINT_N("ERROR - denominator J == 0");
                continue;
            }

            float j = numerator / denominator;
            j /= contactDataFrame[cidx].contactcount;

            GVECTOR impulse = Math::VecMultiplyScalar(Math::VectorNegate(contactDataFrame[cidx].contactnormal), j);

            mPhysicsOBJData[0].velocity = Math::VectorSubtract(mPhysicsOBJData[0].velocity, Math::VecMultiplyScalar(impulse, mPhysicsOBJData[0].inverseMass));
            mPhysicsOBJData[0].rotation = Math::VectorSubtract(mPhysicsOBJData[0].rotation, Math::Vec3MultiplyMatrixRHS(Math::Vector3Cross(relativeContactPoint, impulse), tensor));

            GVECTOR tangentNormal = Math::VectorSubtract(closingVelocity, Math::VecMultiplyScalar(Math::VectorNegate(contactDataFrame[cidx].contactnormal), Math::Vector3Dot(closingVelocity, Math::VectorNegate(contactDataFrame[cidx].contactnormal)).m128_f32[0]));

            if (sqrt(Math::Vector3Dot(tangentNormal, tangentNormal).m128_f32[0]) == 0.0f) {
                PRINT_N("ERROR - NO TAGENT VECTOR");
                continue;
            }
            tangentNormal = Math::Vec3Normalize(tangentNormal);

            numerator = -Math::Vector3Dot(closingVelocity, tangentNormal).m128_f32[0];
            denominator = mPhysicsOBJData[0].inverseMass + Math::Vector3Dot(tangentNormal, Math::Vector3Cross(Math::Vec3MultiplyMatrixRHS(Math::Vector3Cross(relativeContactPoint, tangentNormal), tensor), relativeContactPoint)).m128_f32[0];
            if (denominator == 0.0f) {
                PRINT_N("ERROR - DENOMINATOR TANGET == 0");
                continue;
            }
            float jt = numerator / denominator;
            jt /= contactDataFrame[cidx].contactcount;

            if (jt == 0.0f) {
                PRINT_N("ERROR - NO JT IMPULSE");
                continue;
            }

            float friction = 3.75f;
            if (jt > j * friction) {
                jt = j * friction;

            }
            else if (jt < -j * friction) {
                jt = -j * friction;
            }

            GVECTOR tagentImpulse = Math::VecMultiplyScalar(tangentNormal, jt);
            mPhysicsOBJData[0].velocity = Math::VectorSubtract(mPhysicsOBJData[0].velocity, tagentImpulse);
            mPhysicsOBJData[0].rotation = Math::VectorSubtract(mPhysicsOBJData[0].rotation, Math::Vec3MultiplyMatrixRHS(Math::Vector3Cross(relativeContactPoint, tagentImpulse), tensor));
        }
    }
    currentiteration++;
}

```

# Answer
> 0 votes
The problem was related to the orientation quaternion. Nothing related to the physics code.

I figured it out by applying forces to specific axes. I realized that nothing worked when the force was a rotational force (torque) around the Z-axis.

I then debugged the way the rotational velocity was translated into the orientation quaternion during the integration step, I compared it to online calculators. Especially the quaternion multiplication function (implemented besides the code) stood out as wrong. After fixing that i got rid of the weird rotational problems.

---
Tags: c++, physics, collision-resolution, debugging
---


title: Skybox not texturing

text:
# Question
Title: Skybox not texturing
I have looked for a solution for a little while now however I'm not sure if other people have encountered my same problem. I am trying to draw a skybox in a blank opengl window, I have camera controls and I can zoom out and see the skybox is there but not being textured correctly/ at all. I have used code from opengl and I have only tried to implement it into a class.

Skybox.h

```
#pragma once

#include "wrapper_glfw.h"
#include <vector>
#include <glm/glm.hpp>
#include <vector>
#include <string>
#include "shader_m.h"
#include "camera.h"

class Skybox
{
public:
    Skybox();
    ~Skybox();

  void init(GLWrapper *glw);
  void makeSkybox();
  void drawSkybox(Camera camera, glm::mat4 projection);
  void setFaces(std::string skyboxPath);
  unsigned int loadCubemap();

    private:
    std::vector<std::string> faces
    {
        "../src/images/skybox/default/right.jpg",
        "../src/images/skybox/default/left.jpg",
        "../src/images/skybox/default/top.jpg",
        "../src/images/skybox/default/bottom.jpg",
        "../src/images/skybox/default/front.jpg",
        "../src/images/skybox/default/back.jpg"
    };

    unsigned int cubemapTexture;
    unsigned int skyboxVAO, skyboxVBO;
    GLuint skyboxShader;

    //skybox, model, view, projection
    GLuint skyboxID, modelID, viewID, projectionID;
;

};

```

Skybox.cpp

```
#include "skybox.h"
#include <iostream>
#include <filesystem>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

Skybox::Skybox()
{
}
Skybox::~Skybox()
{
  glDeleteVertexArrays(1, &skyboxVAO);
  glDeleteBuffers(1, &skyboxVBO);
}

void Skybox::init(GLWrapper *glw)
{
  skyboxShader = glw->LoadShader("shaders/skyboxShader/skybox.vert", "shaders/skyboxShader/skybox.frag");
  skyboxID = glGetUniformLocation(skyboxShader, "skybox");
  projectionID = glGetUniformLocation(skyboxShader, "projection");
  viewID = glGetUniformLocation(skyboxShader, "view");
  glUseProgram(skyboxShader);
}

void Skybox::makeSkybox()
{

float skyboxVertices[] = {
    // positions
    -5.0f,  5.0f, -5.0f,
    -5.0f, -5.0f, -5.0f,
     5.0f, -5.0f, -5.0f,
     5.0f, -5.0f, -5.0f,
     5.0f,  5.0f, -5.0f,
    -5.0f,  5.0f, -5.0f,

    -5.0f, -5.0f,  5.0f,
    -5.0f, -5.0f, -5.0f,
    -5.0f,  5.0f, -5.0f,
    -5.0f,  5.0f, -5.0f,
    -5.0f,  5.0f,  5.0f,
    -5.0f, -5.0f,  5.0f,

     5.0f, -5.0f, -5.0f,
     5.0f, -5.0f,  5.0f,
     5.0f,  5.0f,  5.0f,
     5.0f,  5.0f,  5.0f,
     5.0f,  5.0f, -5.0f,
     5.0f, -5.0f, -5.0f,

    -5.0f, -5.0f,  5.0f,
    -5.0f,  5.0f,  5.0f,
     5.0f,  5.0f,  5.0f,
     5.0f,  5.0f,  5.0f,
     5.0f, -5.0f,  5.0f,
    -5.0f, -5.0f,  5.0f,

    -5.0f,  5.0f, -5.0f,
     5.0f,  5.0f, -5.0f,
     5.0f,  5.0f,  5.0f,
     5.0f,  5.0f,  5.0f,
    -5.0f,  5.0f,  5.0f,
    -5.0f,  5.0f, -5.0f,

    -5.0f, -5.0f, -5.0f,
    -5.0f, -5.0f,  5.0f,
     5.0f, -5.0f, -5.0f,
     5.0f, -5.0f, -5.0f,
    -5.0f, -5.0f,  5.0f,
     5.0f, -5.0f,  5.0f
};

  // skybox VAO
  glGenVertexArrays(1, &skyboxVAO);
  glGenBuffers(1, &skyboxVBO);
  glBindVertexArray(skyboxVAO);
  glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO);
  glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices), &skyboxVertices, GL_STATIC_DRAW);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);

  cubemapTexture = loadCubemap();

  // glUniform1ui(skyboxID, 0);
  glGetError();
}

void Skybox::drawSkybox(Camera camera, glm::mat4 projection)
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // draw skybox as last
  glDepthFunc(GL_LEQUAL);  // change depth function so depth test passes when values are equal to depth buffer's content

  glUniformMatrix4fv(viewID, 1, GL_FALSE, &camera.getView()[0][0]);
    glUniformMatrix4fv(projectionID, 1, GL_FALSE, &projection[0][0]);

  // skybox cube
  glBindVertexArray(skyboxVAO);
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_CUBE_MAP, cubemapTexture);
  glDrawArrays(GL_TRIANGLES, 0, 36);
  glBindVertexArray(0);
  glDepthFunc(GL_LESS); // set depth function back to default
  glUniform1ui(skyboxID, cubemapTexture);
  glGetError();
}

unsigned int Skybox::loadCubemap()
{
    unsigned int textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    int width, height, nrChannels;
    for (unsigned int i = 0; i < faces.size(); i++)
    {
        unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0);
        if (data)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
            stbi_image_free(data);
        }
        else
        {
            std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
            stbi_image_free(data);
        }
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    return textureID;
}

```

skyboxShader.frag:

```
#version 410 core
out vec4 FragColor;

in vec3 TexCoords;

uniform samplerCube skybox;

void main()
{
    FragColor = texture(skybox, TexCoords);
}

```

skyboxShader.vert:

```
#version 410 core
layout (location = 0) in vec3 aPos;

out vec3 TexCoords;

uniform mat4 projection;
uniform mat4 view;

void main()
{
    TexCoords = aPos;
    vec4 pos = projection * view * vec4(aPos, 1.0);
    gl_Position = pos.xyww;
}

```

I am using an M2 Macbook and I do not have a shader class like I have seen a lot of people use, I implement my shaders the way my lecturer has done so. I hope I have provided enough and thank you in advance if anyone can help!

# Answer
> 1 votes
There were two mistakes I made which led to my skybox not texturing properly:

1. `Init` function was never called.... I'm sorry
2. `glUseProgram(skyboxShader)` should have been called in `drawSkybox` i.e. calling in the display loop. Thank you to everyone who replied and to anyone who had a look, feel free to steal my code if it is of any use to anyone

---
Tags: opengl, skybox
---


title: Name of 2D Image From Above

text:
# Question
Title: Name of 2D Image From Above
What do you call a 2D game where its view is directly from above looking down?

Does the art style have a similar name? (Ie isometric is a art style, but not the art style name I am after.)

When I use "top down", people do not seem to understand what I mean.

# Answer
It sounds like you're describing a *top down* or *overhead perspective*; similarly, isometric is a perspective that can be used by various styles.

The projection may also be a consideration and might be the source of some confusion. For example consider the following screenshots.

Hotline Miami:

Ape Out:

Both games use an overhead view. Hotline Miami has a parallel projection and uses pixel art. Ape out has a perspective projection and uses low res 3D modelled art.

Since some combination tend to be found together often, sometimes terms get used confused. If you're having trouble communicating what you mean to your artist verbally, include some examples.
> 2 votes

# Answer
Top down would be the right way to describe it but you could give examples like Diablo 2 or ragnarok online to get them to understand better.
> 1 votes

---
Tags: terminology, art, perspective
---


# Question
Title: NavMesh Runtime Generation In Specific Areas
Unity allows the runtime generation of NavMesh surfaces with the Unity.AI.Navigation package through the BuildNavMesh method. However, this function re-bakes the entire NavMesh in the current scene, which is very expensive. Is there any way to only bake for a specific area? e.g. within the radius of a Vector3 position, or within some defined grid?

# Answer
A NavMeshSurface component only takes into consideration the geometry defined in its children, not the whole scene, so you can have multiple surfaces and only rebake one at a time. It's not quite as much granularity as you want, but I don't think you can go finer than that (other than obstacles with cutting enabled, but I imagine that's not what you mean).
> 0 votes

---
Tags: unity, ai, navmesh, navmeshsurface
---


# Question
Title: Padding in a vec3f array in WebGPU memory layout
I'm trying to write a WGSL structs parser (sort of webgpu-utils thing). In order to better understand the memory layout, I'm using wgsl offset computer as a helper.

Having the next struct:

```
struct A {
  a: array<vec3f, 3>,
  b: f32
};

```

The layout given by the mentioned tool looks like:

I'm struggling with the difference between the graphical representation and the `AInfo` object. In the graphics, it is clearly seen that each item in the `array<vec3f, 3>` has alignment padding of 4 bytes and the offsets for three items are 0, 16 and 32 respectively. On the other hand, in the `AInfo` object the offset of the array `a` is zero and the length is 48 bytes, which implies the bytes arrangement in the array is consequent. Referencing to the graphics, I would expect the object representation to be sort of:

```
const AInfo = {
  a: [
    {type: Float32Array, byteOffset: 0, length: 4}, // 16 bytes
    {type: Float32Array, byteOffset: 16, length: 4}, // 16 bytes
    {type: Float32Array, byteOffset: 32, length: 4}, // 16 bytes
  ],
  b: {type: Float32Array, byteOffset: 48, length: 1}
};

```

What am I missing here?

# Answer
> 0 votes
My confusion was regarding inner padding of data passed to the `array<vec3f>`. It is now clear, that in order for it to work correctly, the data should be padded:

```
[
  1, 2, 3,
  4, 5, 6,
  7, 8, 9
] ->
[
  1, 2, 3, 0,
  4, 5, 6, 0,
  7, 8, 9, 0
]

```

---
Tags: javascript, graphics-programming, memory-efficiency, wgsl, webgpu
---


# Question
Title: Drag-select multiple units code Godot 3.5
The code from where I based my script.

The code I have has the these 2 problems:

* The visual area for the player to see what unit are going to be selected doesn't work as intended, if I start dragging from left to right, and down, the selection area is drawn inverted. If I try to do the same but inverting the movement the selection area is drawn correctly.
* The selection area and the units I want to select are not selected, or just selects just one, might have something to do with the problem above.
* Something I have tried is the code alone in another scene, this baffles me because it works as intended, it doesn't have any one of the problem above!

The code:

```
extends Node2D

var dragging = false  # are we currently dragging?
var selected_units = []  # array of selected units
var drag_start = Vector2.ZERO  # location where the drag begian
var select_rect = RectangleShape2D.new()
const blue =  Color(0.59, 0.86, 1.0,0.4)
var drag_end  = Vector2.ZERO
var selected = 0

func _unhandled_input(event):
    if event is InputEventMouseButton and event.button_index == BUTTON_LEFT:
        # When the mouse button is pressed, then the dragging starts
        if event.pressed:
            if selected_units.size() == 0:
                dragging = true
                drag_start = event.position
            else:
                for unit in selected_units:
                    unit.collider._set_selected(false)
                    selected_units = []
            dragging = true
            drag_start = event.position

        elif dragging:
            dragging = false
            drag_end = event.position
            update()
            drag_end = event.position
            select_rect.extents = (drag_end - drag_start) / 2
            var space = get_world_2d().direct_space_state
            var query = Physics2DShapeQueryParameters.new()
            query.collide_with_bodies = true
            query.set_shape(select_rect)
            query.transform = Transform2D(0, (drag_end + drag_start)/2)
            selected_units = space.intersect_shape(query)
            selected = selected_units.size()
            for unit in selected_units:
                unit.collider._set_selected(true)

    if event is InputEventMouseMotion and dragging:
        update()

func _draw():
    if dragging:
        draw_rect(Rect2(drag_start, get_global_mouse_position() - drag_start),
                blue, true)

```

Not sure why is that happening, now I think this is the line where the problem lies:

```
query.transform = Transform2D(0, (drag_end + drag_start)/2)

```

Since it's not inverting the area where we are trying to get the units selected. *not sure if did I missed something to configure elsewhere? why my code fails when it's in the main scene of my game but not on the test scene?*

# Answer
I found what was the issue with the code. It turns out that `event.position` gives back local space coordinates instead of the global coordinates. Using `get_global_mouse_position()` makes the code work as intended.
> 0 votes

---
Tags: 2d, input, godot, godot-3
---


# Question
Title: Getting smallest possible build filesize on Win build (other than optimizing assets)
Disclaimer: I'm currently just exploring techniques and trying to save literal kilobytes just to see if I can. Please don't give me speeches about how development time is not worth it.

So I got a bit disappointed that my small game with literally 3MB worth of assets takes 70MB of disk space. It should be lower, right? If I try a WebGL build, it leaves me with 12MBs, so what takes so much on a Windows build?

After that I created a test project just to see what else I can do to get rid of Unity's default engine bloat as assets are already as optimized as they can be.

Empty project. 0 assets. No code, no textures, no sound, nothing to optimize on my end. One empty scene.

The build weighs 65MBs.

I went into Package Manager and disabled literally everything. All extra packages, all built-in packages. Then went into Project Settings and set highest possible engine code stripping quality.

That left me with 48MB build. Weirdly enough, Unity still left a lot of executables in Managed folder, e.g. the one for Physics, even though it is absolutely not used. I can remove them and the game will still launch without crashing... On that note, I could probably remove the crash handler and save another megabyte... But first, I'd like to see if I can go lower from Unity itself instead of decapitating build once it's done.

Anyway, what are other ways to actually reduce the filesize? Most articles and questions talk about asset optimization, or focus on WebGL and mobile, where empty builds are actually within sensible values. Any settings I could use or maybe even assets that help with that? I'd appreciate any tips.

Currently worst offenders are:

UnityPlayer.dll (28MB)

mono-2.0-bdwgc.dll (7.5MB)

unity default resources (4.7MB) - do I even need those default resources?

# Answer
Without changing any build settings and fully empty projects, a minor increase in the game engine can result already in a bigger build size due to new features, bugfixes or other automatically included build settings. There are a lot of other things that can be excluded or are not needed but this will depend a lot of what your game actually is about.

Here is an example of version 2021.1.14f1 vs 2021.1.15f1

vs

The difference is already one file. The UnityPlayer.dll is also slightly bigger 27361KB vs 27376KB.

Anecdotally I can say that the earliest .exe I build with Delphi 3 were around 300KB. Rebuilding the same code 20 years later resulted in around 27MB for the same code with the newest version of Delphi.
> 1 votes

---
Tags: unity
---


title: Infinite scrolling with mouse

text:
# Question
Title: Infinite scrolling with mouse
I know we're able to scroll a background image hardcoded or using awsd keys(or arrows) if they're pressed. But what about scrolling it with mouse movement? So I have a piece of panoramic image as a background and I wanna embody background transform depending on mouse pos or rel. I came up with mouse.get\_rel() pygame function

ultra simplified code snippet:

```
from pygame import *

screen = display.set_mode((1920, 1080), RESIZABLE)

gx = -12288
gy = -5120

background = image.load(f'Content/Map/Overcast/Overcast_HQ.jpg')

run = True
while run:
    for e in event.get():
        if e.type == QUIT:
            run = False
        elif e.type == MOUSEMOTION:
            rel = mouse.get_rel()
            gx += rel[0]
            gy += rel[1]
    screen.blit(background, (gx,gy))
    display.flip()

```

but the thing i don't like here is if i move the cursor out of pygame window or if i reach a screen edge no more movement is detected while i'm actually moving a mouse. I need something similar to "mouse locking" when the cursor pos doesn't change (cursor itself dissapears) and player is able to rotate a camera limitlessly as far as his table allows to.

# Answer
My solution:

```
def lock_mouse(gx, gy, virtual_surface, check_pos_offset = False):   #enables limitless move with mouse
    px = virtual_surface.get_width()//2
    py = virtual_surface.get_height()//2
    mouse_pos = (px, py)
    rel = mouse.get_rel()
    gx += rel[0]
    gy += rel[1]
    if mouse.get_pos()[0] < mouse_pos[0] - 100 \
            or mouse.get_pos()[0] > mouse_pos[0] + 100 \
            or mouse.get_pos()[1] < mouse_pos[1] - 100 \
            or mouse.get_pos()[1] > mouse_pos[1] + 100:     # if set mouse pos to 0 every frame then mouse move will be flicky, that's why magic numbers are used
        mouse.set_pos([px, py])
        if check_pos_offset:    #if snapping to locked mouse mode then we have to compensate mouse position offset
            gx -= rel[0]
            gy -= rel[1]
    return gx, gy

```

So I had checked up this method right before I asked a question. The reason it hadn't worked is I was checking mouse position offset every frame and after each frame I reset mouse coordinates. There was a kind of movement but it was very flicky. And then I thought so what if we don't reset coords every frame but when the difference between default and current coords would be more than something; a range of 100 was enough for this.

And the last thing is we need to switch between locked mouse mode and a free mouse. And when the mouse is free its position might be far away from its allowable zone of 200 pixels. So once mouse is moved after going locked mode it drags to the default position and the background image also gets swiped because mouse movement in that frame is taken by `mouse.get_rel()`. In order to compensate it we can immediately substract the exact amount of movement off `gx` and `gy`.
> 1 votes

# Answer
I would consider the following to lock the mouse into the screen based on size that way they can't click out of it.

import pyautogui import time

# Set the coordinates of the window you want to lock the mouse to

window\_x = 100 window\_y = 100 window\_width = 800 window\_height = 600

# Set the interval for updating the mouse position (in seconds)

update\_interval = 0.1

try: while True: \# Get the current mouse position current\_x, current\_y = pyautogui.position()

```
    # Ensure the mouse stays within the window bounds
    new_x = max(window_x, min(current_x, window_x + window_width))
    new_y = max(window_y, min(current_y, window_y + window_height))

    # Move the mouse to the new position
    pyautogui.moveTo(new_x, new_y, duration=0.1)

    # Pause for the specified interval
    time.sleep(update_interval)

```

except KeyboardInterrupt: pass # Handle Ctrl+C to exit the loop
> 0 votes

---
Tags: python, pygame, mouse, scrolling
---


# Question
Title: What are my options for creating animated planets and stars in Godot 2D?
I'm creating a simple game / digital picture frame as a present. It is split into a picture scene and a planetary scene, which will have slight animations, date, time and maybe some messages.

The planetary scene will contain a sun in the center as well as the earth and a moon orbiting it. What are my options to animate the planets (comparable to Kurzgesagt art style, which is considered `flat design` or `flat neon color illustration`. I'm looking for something which can be picked up rather easy and doesn't need to be too fancy, as I'd like to finalize it before Christmas.

I'm somewhat aware how Kurzgesagt does it: They design in Adobe Illustrator and animate in After Effects.

Is this feasible for a Godot Project?

I know one can create images and animations and flatten them in a Spritesheet. Would this be preferable or should I look into shaders?

I'm a programmer and don't know much about illustration or the possibilities one has in game design. Any helpful response is appriciated.

# Answer
> 1 votes
The feasibility depends largely on your skills and expectations. Using Godot may have some complications.

Kurzgesagt uses SVG / vector art to get that smooth scaling art animation. Godot does not have direct SVG support. Rotating or scaling a sprite can look different than rotating or scaling vector art. Without more information, it's impossible to know if the results would be satisfactory for your slight animations. If you're sticking to sprites of simple geometric shapes (or things that can be built up from simple shapes) with solid colors (or maybe gradient fills), it could be fine.

You could do those operations in some other software & export the results. The results will likely look smoother, but it is going to add complexity to your workflow.

Godot does provide a custom drawing option which can be used to make smooth looking shapes. I haven't used it and am not familiar with its performance. It does require you to describe things programmatically though; it is not a point and click solution.

Objectively, I would recommend looking at some basic Godot tutorials, in particular the official Your first 2D game tutorial. If you can imagine how you might take whatever it is you're trying to make in terms of that (or other) tutorials, then there's a much better chance that Godot will be feasible for your project and timeline.

Finally, keep in mind that a simple looking result does not mean that the behinds the scenes process is simple. Kurzgesagt has a video called How to Make a Kurzgesagt Video in 1200 Hours. We cannot judge the whether or not your timeline is sufficient to learn to use a new engine with the hopes of achieving something that the engine isn't necessarily designed to support, especially given the lack of details in the expected results.

---
Tags: game-design, animation, godot, art
---


title: Stuck trying to build UE for iOS on Mac

text:
# Question
Title: Stuck trying to build UE for iOS on Mac
I am trying to build an AR game for iOS, using a custom build of Unreal Engine 5.1.1, on an Apple Silicon (M1 Max) Macbook Pro.

(I have to use a custom branch of UE5 because there is a problem with using AR and Scene Capture.)

Everything was going fine until I (stupidly) let my iPhone 14 update itself to iOS 17.

Now I cannot build for it anymore, because 17 requires using Xcode 15. But when I build our project in Xcode 15, for packaging in UE, it fails with some low level assembly/machine language instruction.

It works fine with Xcode 14, but I cannot install to my phone for testing. And obviously I cannot downgrade my phone.

Can anyone shed any light here?

# Answer
> 1 votes
I would say that the best path is to rebase your custom build of Unreal Engine to 5.3. I could build Unreal Engine 5.1 for Mac by applying the patches:

```
--- a/Engine/Source/Programs/UnrealBuildTool/Platform/Mac/ApplePlatformSDK.Versions.cs
+++ b/Engine/Source/Programs/UnrealBuildTool/Platform/Mac/ApplePlatformSDK.Versions.cs
@@ -22,13 +22,13 @@
 namespace UnrealBuildTool
                        if (RuntimePlatform.IsMac)
                        {
                                MinVersion = "13.4.0";
-                               MaxVersion = "14.9.9";
+                               MaxVersion = "15.9.9";
                        }
                        else
                        {
                                // @todo turnkey: these are MobileDevice .dll versions in Windows - to get the iTunes app version (12.3.4.1 etc) would need to hunt down the .exe
                                MinVersion = "1100.0.0.0";
-                               MaxVersion = "1499.0";
+                               MaxVersion = "1599.0";
                        }
                }

```

and

```
--- a/Engine/Source/Runtime/Core/Public/Apple/ApplePlatformCompilerPreSetup.h
+++ b/Engine/Source/Runtime/Core/Public/Apple/ApplePlatformCompilerPreSetup.h
@@ -37,6 +37,11 @@
 #else
        #pragma clang diagnostic warning "-Wparentheses-equality"
 #endif
+#if (__clang_major__ >= 15)
+#define unary_function __unary_function
+#pragma clang diagnostic ignored "-Wdeprecated-builtins"
+#pragma clang diagnostic ignored "-Wsingle-bit-bitfield-constant-conversion"
+#endif
 #pragma clang diagnostic ignored "-Winconsistent-missing-override"
 #pragma clang diagnostic ignored "-Wundefined-bool-conversion"
 #pragma clang diagnostic ignored "-Wunused-local-typedef"

```

and

```
--- a/Engine/Source/Programs/UnrealBuildTool/Platform/Mac/MacToolChain.cs
+++ b/Engine/Source/Programs/UnrealBuildTool/Platform/Mac/MacToolChain.cs
@@ -294,8 +294,6 @@
 namespace UnrealBuildTool

                        // Needed to make sure install_name_tool will be able to update paths in Mach-O headers
                        Arguments.Add("-headerpad_max_install_names");
-
-                       Arguments.Add("-lc++");
                }

```

and finally

```
--- a/Engine/Plugins/Experimental/NNI/Source/ThirdParty/ORT_4_1/Private/core/session/provider_stubs.cc
+++ b/Engine/Plugins/Experimental/NNI/Source/ThirdParty/ORT_4_1/Private/core/session/provider_stubs.cc
@@ -30,7 +30,7 @@ ORT_API_STATUS_IMPL(OrtSessionOptionsAppendExecutionProvider_DML, _In_ OrtSessio
 }
 #endif

-#ifndef USE_MIGRAPHX
+#if 0 // ndef USE_MIGRAPHX
 ORT_API_STATUS_IMPL(OrtSessionOptionsAppendExecutionProvider_MIGraphX,
                     _In_ OrtSessionOptions* options, int device_id) {
   ORT_UNUSED_PARAMETER(options);

```

This still produces some warnings, not sure if some of them are really critical.

---
Tags: ios, unreal, macos, unreal-5, xcode
---


# Question
Title: NullReferenceException when object is not null
So in the following code:

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

public class TreeHealthBar : MonoBehaviour
{
    public GameObject axe;

    public float healthBarSize;
    destroyTree destroy;
    RectTransform rectTransform;
    Vector3 size;

    Vector3 position;
    Image img;

    void Start()
    {
        destroy = axe.GetComponent<destroyTree>();
        rectTransform = GetComponent<RectTransform>();
        img = GetComponent<Image>();
        img.enabled = false;
    }

    void Hide()
    {
        img.enabled = false;
    }

    void Update()
    {
        if (destroy??false)
        {
            if (destroy.touchingTree() && destroy.GetTreeHealth() > 0f)
            {
                img.enabled = true;

                CancelInvoke();

                size = transform.localScale;

                size.x = destroy.GetTreeHealth() / 100f * healthBarSize;

                position = rectTransform.anchoredPosition;

                if (destroy.GetTreeHealth() < destroy.GetTreeMaxHealth())
                    position.x = 0.0f - 250.0f + (destroy.GetTreeHealth() * 5.0f) - ((50 - destroy.GetTreeHealth()) * 2.5f);
                else
                    position.x = 0.0f;

                transform.localScale = size;

                rectTransform.anchoredPosition = position;
            }

            else
            {
                Invoke(nameof(Hide), 1.5f);
            }

            if (destroy.touchingTree() && destroy.GetTreeHealth() <= 0)
            {
                img.enabled = false;
            }
        }
    }
}

```

it returns the NullReferenceException in the console: Object reference not set to an instance of an object. It is on line 37, which is where the if statement is containing the "destroy" object. But the big problem is that it shows this in the console when the axe (which the destroyTree is assigned to) is colliding with the tree. Yes, destroyTree is assigned, everything has its components and everything is assigned. I even made it CHECK if it's null, including trying to use `if (destroy != null)` instead of the ?? equation, but it still won't work. It's probably answered somewhere, but I actually don't even know what's causing the problem. I also put `&& destroy??false` in the line 37 if statement, and that seemed to always show the bar, and not even change the size or position. Ah, and the important part is, I never got this error message when I just used a cube, not a blender imported object. So it has something to do with that, and I didn't even need `if (destroy??false)` Here's my setup:

I'm assuming it would be helpful to include the actual destroyTree script:

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

public class destroyTree : MonoBehaviour
{

    public float globalCutCooldown = 0.5f;
    private float lastCutTime;
    public float axeCut;

    bool touching;

    cutTree cut;
    destroySelf ds;

    void Start()
    {
        cut = GetComponent<cutTree>();

        axeCut = 5f;
    }

    public float GetTreeHealth()
    {
        return ds.GetCurrentHealth();
    }

    public float GetTreeMaxHealth()
    {
        return ds.GetMaxHealth();
    }

    public bool touchingTree()
    {
        return touching;
    }

    public void OnTriggerStay(Collider other)
    {
        ds = other.gameObject.GetComponent<destroySelf>();

        touching = true;

        if (ds != null && cut.Cutting() && Time.time - lastCutTime > globalCutCooldown)
        {
            ds.TakeDamage(axeCut);
            lastCutTime = Time.time;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        touching = false;
    }
}

```

I don't know if I need to add my cutTree script. And this happens with all the other scripts that have to do with a tree health bar, with showing and hiding etc. And it's the same problem, there is an error on the same line as an if statement with a destroy object in it. It HAS to do with the destroyTree script therefore. Edit: with testing, it is a problem with the destroySelf script: So in the following code:

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

public class TreeHealthBar : MonoBehaviour
{
    public GameObject axe;

    public float healthBarSize;
    destroyTree destroy;
    RectTransform rectTransform;
    Vector3 size;

    Vector3 position;
    Image img;

    void Start()
    {
        destroy = axe.GetComponent<destroyTree>();
        rectTransform = GetComponent<RectTransform>();
        img = GetComponent<Image>();
        img.enabled = false;
    }

    void Hide()
    {
        img.enabled = false;
    }

    void Update()
    {
        if (destroy??false)
        {
            if (destroy.touchingTree() && destroy.GetTreeHealth() > 0f)
            {
                img.enabled = true;

                CancelInvoke();

                size = transform.localScale;

                size.x = destroy.GetTreeHealth() / 100f * healthBarSize;

                position = rectTransform.anchoredPosition;

                if (destroy.GetTreeHealth() < destroy.GetTreeMaxHealth())
                    position.x = 0.0f - 250.0f + (destroy.GetTreeHealth() * 5.0f) - ((50 - destroy.GetTreeHealth()) * 2.5f);
                else
                    position.x = 0.0f;

                transform.localScale = size;

                rectTransform.anchoredPosition = position;
            }

            else
            {
                Invoke(nameof(Hide), 1.5f);
            }

            if (destroy.touchingTree() && destroy.GetTreeHealth() <= 0)
            {
                img.enabled = false;
            }
        }
    }
}

```

it returns the NullReferenceException in the console: Object reference not set to an instance of an object. It is on line 37, which is where the if statement is containing the "destroy" object. But the big problem is that it shows this in the console when the axe (which the destroyTree is assigned to) is colliding with the tree. Yes, destroyTree is assigned, everything has its components and everything is assigned. I even made it CHECK if it's null, including trying to use `if (destroy != null)` instead of the ?? equation, but it still won't work. It's probably answered somewhere, but I actually don't even know what's causing the problem. I also put `&& destroy??false` in the line 37 if statement, and that seemed to always show the bar, and not even change the size or position. Ah, and the important part is, I never got this error message when I just used a cube, not a blender imported object. So it has something to do with that, and I didn't even need `if (destroy??false)` Here's my setup:

I'm assuming it would be helpful to include the actual destroyTree script:

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

public class destroyTree : MonoBehaviour
{

    public float globalCutCooldown = 0.5f;
    private float lastCutTime;
    public float axeCut;

    bool touching;

    cutTree cut;
    destroySelf ds;

    void Start()
    {
        cut = GetComponent<cutTree>();

        axeCut = 5f;
    }

    public float GetTreeHealth()
    {
        return ds.GetCurrentHealth();
    }

    public float GetTreeMaxHealth()
    {
        return ds.GetMaxHealth();
    }

    public bool touchingTree()
    {
        return touching;
    }

    public void OnTriggerStay(Collider other)
    {
        ds = other.gameObject.GetComponent<destroySelf>();

        touching = true;

        if (ds != null && cut.Cutting() && Time.time - lastCutTime > globalCutCooldown)
        {
            ds.TakeDamage(axeCut);
            lastCutTime = Time.time;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        touching = false;
    }
}

```

I don't know if I need to add my cutTree script. And this happens with all the other scripts that have to do with a tree health bar, with showing and hiding etc. And it's the same problem, there is an error on the same line as an if statement with a destroy object in it. It HAS to do with the destroyTree script therefore. And with further testing, apparently it is a problem with ds, the destroySelf in the ontriggerstay in destroyTree. Apparently THAT script is null, when it IS assigned. Here's the destroySelf script:

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

public class destroySelf : MonoBehaviour
{
    public InventoryManager inventoryManager;
    public Item[] itemsToPickup;

    public void PickupItem(int id)
    {
        bool result = inventoryManager.AddItem(itemsToPickup[id]);
    }

    public float maxHealth = 50f;
    private float currentHealth;

    private void Start()
    {
        currentHealth = maxHealth;
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;

        if (currentHealth <= 0f)
        {
            Destroy(gameObject);
            PickupItem(0);
        }
    }

    public float GetCurrentHealth()
    {
        return currentHealth;
    }

    public float GetMaxHealth()
    {
        return maxHealth;
    }
}

```

# Answer
> 0 votes
Ok so apparently the blender imported object is an empty game object, and so therefore I had to apply the script to the child objects.

---
Tags: unity, c#
---


# Question
Title: Cannot Draw a triangle without VAO on MacOS
So I was watching Cherno's Video on Vertex attributes and he was successful in drawing a triangle without a VAO, but in tutorials from learnopengl.com they specifically say they we need a VAO to draw VBO and I tested it and it works fine. Here is my snippet :

```
//==============================================================================
// glGenVertexArrays(1, &VAO);
// glBindVertexArray(VAO);

glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);

//-----------------------------------------------------------------------------
// Game Loop
//-----------------------------------------------------------------------------
/* Loop until the user closes the window */
while (!glfwWindowShouldClose(window))
{
    /* Poll for and process events */
    glfwPollEvents();

    /* Render here */
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);   // RGBA
    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(shaderProgram);
    // glBindVertexArray(VAO);// we did not unbind it so it's still binded to the assigned      VAO
    glDrawArrays(GL_TRIANGLES, 0, 3);

    /* Swap front and back buffers */
    glfwSwapBuffers(window);
}
//-----------------------------------------------------------------------------

```

This only works if I uncomment the VAO which is understandable, what I can't get my head around is how did Cherno got it working without a VAO and just using a VBO? Is it a MacOS specific thing?

# Answer
Above a certain GL version Macs only support OpenGL core profiles, which require VAOs. This is perfectly legal, but it does mean that code written for other platforms, where compatibility profiles are allowed, may not port.
> 1 votes

# Answer
I am also a beginner and it looks like we're studying on the same document. To render a triangle using VBO alone, just comment out these three lines of code (this approach may not be normative)

```
// glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
// glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

```
> 0 votes

---
Tags: opengl, vertex-buffer, vertex-arrays
---


# Question
Title: Stackable items: what's the point of an item not stacking to infinity?
Pretty much every inventory system that doesn't care about realism and still let's you carry thousands of useless items in your pocket will anyway decide to give items a maximum stack size. Which is usually quite arbitrary if not small: 8, 16, 32, 64...256...999 and so on.

Why not just make it infinite and simply shorten the integers that are to large with 2 numbers and 1 letter? Like once you got 3 billion and a half berries you gathered for some tedious useless question, it can just say "3.5B berries"?

# Answer
For starters, there are technical limitations, as there is a hard limit on how much value an variable can contain. (The limit of an int is 2,147,483,647. Which is roughly 2,14 Billion)

Then there are also intentional gameplay limitations. For example: If you had an unlimited stack of cheese, then you also never have to worry about running out of cheese, or healing items. Then there is also no value in carrying other items.

Inventory management and limitations depends from game to game. Terraria for example had once a limit of Health potions of 30 per stack, but you have a lot of inventory slots. So you could just use up more inventory slots for more space. through the updates this has been increased to 99, 999, and finally also 9999. At first sight I found it rather overwhelming, as almost anything past the 999 is already more than necessary. But Terraria has become a large game with tons of different items that fills the inventory, and some of these items reach the 999 cap pretty quick.
Other games like Fire Emblem have a much more strict inventory system, like 3 healing items per slot, where it's usually only 5 slots per character. Even the weapons have a limitation of uses, so more care has to be put in choosing the available options.

More limitations helps to give you more choice, which leads to a larger risk/reward system, "Should I carry this reviver or this damage boost? Should I store away items I don't use?"
Limits between these stacks can also give you a hint on how often you're going to use them. "9999 bullets, I guess I'll go through them fast", "5 mega blasts, I guess I'll be careful with them".

The higher a number is, the less value you'll see in the amount, the easier it would be to lose more. A larger limit won't really solve the problem, it'll only make things less clear. If you already have 999 'useless' items, then you already have more than you'll ever need. The max stack here actually helps to tell you to do something about it.

As for the 'arbitrary numbers', Minecraft uses a stack system that is always multiplied and dividable by 2 (2, 4, 8, 16, 32, 64, 128, 256 ect.), not only is this useful for building, but also for splitting item numbers in half.

And finally: If there's an infinite amount of resources, then it's no longer a resource. As care doesn't have to be taken into consideration.
> 4 votes

---
Tags: game-design, game-mechanics, inventory
---


title: Setting A Panel texture in GDScript

text:
# Question
Title: Setting A Panel texture in GDScript
I am messing around with Godot, and I couldn't seem to find a way to set the texture of a `Panel` node in Godot. First I tried using the `get_theme_stylebox()` function, but I don't know how that works. I read the Godot documentation and didn't find anything there. How can I go about this?

# Answer
> 1 votes
You can set an `StyleBoxTexture` to the `Panel` either by:

* Defining it in a `Theme` which you set in the `theme` property
* Or by setting it in the `theme_override_styles/panel` property.

If this texture is intended for all (or at least most) panels, use a `Theme`. As you can set the `Theme` in the root `Control` and all children `Control` take it.

---

Alternatively, you can set a `ShaderMaterial` in the `material` property, and write a shader that lets you set a texture. For example:

```
shader_type canvas_item;

uniform sampler2D tex:source_color;

void fragment() {
    COLOR = texture(tex, UV);
}

```

Using a `ShaderMaterial` would give you more control over how the texture is used, but you need to write the shader code for that.

---

Also consider using a `TextureRect` instead of a `Panel`.

---
Tags: godot, gdscript, godot-4
---


# Question
Title: Scrolling the screen left, right, up and down based on cameras rotation in Unity with C#
I'm making a building game in Unity and C#

I want to be able to scroll the screen in all 4 directions when in building mode.

At the moment, I can rotate the camera and scroll the screen left and right, but no matter what rotation the camera is oriented to, it always scrolls in the same direction. I.e. Starting the game the camera pans, left, right as intended. But if I rotate the camera 90 degrees, scrolling left now scrolls up and right scrolls down.

I want the camera to pan left, right, up and down based on the camera's rotation. I still have not figured out how to pan up or down as this just moves the camera up and down, so I have commented this out for now.

I tried scrolling relative to the cameras rotation but that didn't work. You can see my attempts in the update function.

I've been searching to find a solution but I've had no luck. This video shows my issue.

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

public class CamFollowPlayerScript : MonoBehaviour
{
    //----------- This script rotates the cam in isometric veiw

    public GameObject player; // declare player gameobject
    public Vector3 spinCam; // declare vector 3 for the camera
    public float camSpinSpeed; // declare float to hold the speed of the camera rotation
    public bool isCameraFollwingMouse;
    public Cursor mouseCurson;
    public float mSpeed; // Scale. Speed of the movement
    public Camera isoCam;

    public GameObject eastDirectrion;

    public Vector3 mRightDirection;// = 3.right; // Direction the camera should move when on the right edge
    public Vector3 mleftDirection;// = Vector3.left; // Direction the camera should move when on the right edge
    public Vector3 mUpDirection;// = Vector3.up; // Direction the camera should move when on the right edge
    public Vector3 mDownDirection;// = Vector3.down; // Direction the camera should move when on the right edge

    private void Start()
    {
        mSpeed = 5;
        camSpinSpeed = 20f;
    }

    private void Update()
    {

        spinCam = new Vector3(Input.GetAxis("VerticalIso"), Input.GetAxis("HorizontalIso"), 0.0f); // spinCam is a new vector 3, taking the axis from the unity input settings on the X and Y axis and 0 on the Z axis
        this.transform.Rotate(spinCam * camSpinSpeed * Time.deltaTime); // rotate the camera using the vector 3 from the spin cam, by the spinCamSpeed float by time.delta time.

         mUpDirection = new Vector3(0,0,0); // Direction the camera should move when on the right edge
         mDownDirection = new Vector3(0,0,0); // Direction the camera should move when on the right edge
         mRightDirection = new Vector3(isoCam.transform.rotation.x, 0, isoCam.transform.rotation.z);
         mleftDirection = new Vector3(-isoCam.transform.rotation.x, 0, -isoCam.transform.rotation.z);

        if (Input.GetKeyDown(KeyCode.M))
        {
            isCameraFollwingMouse = !isCameraFollwingMouse;
        }
    }

    void LateUpdate() // called after all update() methods have been called
    {
        if (!isCameraFollwingMouse)
        {
            transform.position = player.transform.position;//
        }

        if (isCameraFollwingMouse)
        {
            // Check if on the right edge
            if (Input.mousePosition.x >= Screen.width )
            {
                // Move the camera
                transform.position += Vector3.right * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.x <= 0)
            {
             // mm  // Move the camera
               transform.position += Vector3.left * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.y >= Screen.height)
            {
                // Move the camera
               // transform.position += mUpDirection * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.y <= 0)
            {
                // mm  // Move the camera
               // transform.position += mDownDirection * Time.deltaTime * mSpeed;
            }
        }
    }
}

```

# Answer
> 0 votes
Using `transform.right` instead of `Vector3.right` worked great! I used it on my `isoCamera` camera object.

I used `transform.forward` and `-transform.forward` to move the camera forward and backwards. I used the rotation of an empty gameobject to set the forward and back direction as I am using a rotated isometric view on my camera.

using System.Collections.Generic;
using UnityEngine;

public class CamFollowPlayerScript : MonoBehaviour
{
    //----------- This script rotates the cam in isometric veiw

    public GameObject player; // declare player gameobject
    public Vector3 spinCam; // declare vector 3 for the camera
    public float camSpinSpeed; // declare float to hold the speed of the camera rotation
    public bool isCameraFollwingMouse;
    public float mSpeed; // Scale. Speed of the movement
    public Camera isoCam;
    public GameObject forwardFacingDirectionObject;

    private void Start()
    {
        mSpeed = 5;
        camSpinSpeed = 20f;
    }

    private void Update()
    {
        spinCam = new Vector3(Input.GetAxis("VerticalIso"), Input.GetAxis("HorizontalIso"), 0.0f); // spinCam is a new vector 3, taking the axis from the unity input settings on the X and Y axis and 0 on the Z axis
        this.transform.Rotate(spinCam * camSpinSpeed * Time.deltaTime); // rotate the camera using the vector 3 from the spin cam, by the spinCamSpeed float by time.delta time.

        if (Input.GetKeyDown(KeyCode.M))
        {
            isCameraFollwingMouse = !isCameraFollwingMouse;
        }
    }

    void LateUpdate() // called after all update() methods have been called
    {
        if (!isCameraFollwingMouse)
        {
            transform.position = player.transform.position;//
        }

        if (isCameraFollwingMouse)
        {
            // Check if on the right edge
            if (Input.mousePosition.x >= Screen.width )
            {
                // Move the camera
               transform.position += isoCam.transform.right * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.x <= 0)
            {
             // mm  // Move the camera
               transform.position += -isoCam.transform.right * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.y >= Screen.height)
            {
                // Move the camera
                transform.position += forwardFacingDirectionObject.transform.forward * Time.deltaTime * mSpeed;
            }

            if (Input.mousePosition.y <= 0)
            {
                // mm  // Move the camera
                transform.position += -forwardFacingDirectionObject.transform.forward * Time.deltaTime * mSpeed;
            }
        }
    }
}```

---
Tags: unity, c#, scrolling
---


# Question
Title: Why is this Godot extension class still considered abstract?
I'm working on building an extension to MultiplayerPeer for Godot, using GDExtension. As is my custom, even if I don't end up pushing it to the final product, I always start with a Nullary Pattern implementation—that is, an implementation that doesn't actually do anything, but fits the mold—just to make sure that I'm getting the class recognition that I need in the editor. Then, I fill it out with proper behavior and turn it into my goal class.

Now, I've gone through MultiplayerPeer.hpp, and found a number of methods that end in `= 0;`, which makes them pure virtuals. I've implemented a nullary version of all of them, as far as I can tell. However, Godot, while recognizing that my class exists, is still telling me that it's abstract.

It's been a little while since I really sharpened my C++ skills, so I might be missing something else. Unfortunately I can't just trigger a compiler error with it and read the objection, as I'm building a library through Scons. `nm` has not been terribly helpful.

Here's my code:

nullary\_multiplayer\_peer.h:

```
#ifndef NULLARY_MULTIPLAYER_PEER
#define NULLARY_MULTIPLAYER_PEER

#include <godot_cpp/classes/multiplayer_peer.hpp>
#include <godot_cpp/classes/crypto.hpp>

namespace godot {

class NullaryMultiplayerPeer : public MultiplayerPeer {
    GDCLASS(NullaryMultiplayerPeer, MultiplayerPeer);

private:

protected:
    static void _bind_methods();

public:
    NullaryMultiplayerPeer();
    ~NullaryMultiplayerPeer();

    void set_transfer_channel(int p_channel);
    int get_transfer_channel() const;
    void set_transfer_mode(TransferMode p_mode);
    TransferMode get_transfer_mode() const;
    void set_refuse_new_connections(bool p_enable);
    bool is_refusing_new_connections() const;
    bool is_server_relay_supported() const;

    void set_target_peer(int p_peer_id);

    int get_packet_peer() const;
    TransferMode get_packet_mode() const;
    int get_packet_channel() const;

    void disconnect_peer(int p_peer, bool p_force = false);

    bool is_server() const;

    void poll();
    void close();

    int get_unique_id() const;

    ConnectionStatus get_connection_status() const;
};

}

#endif

```

nullary\_multiplayer\_peer.cpp:

```
#include "nullary_multiplayer_peer.h"
#include <godot_cpp/core/class_db.hpp>

using namespace godot;

void NullaryMultiplayerPeer::_bind_methods() {
}

NullaryMultiplayerPeer::NullaryMultiplayerPeer() {
}

NullaryMultiplayerPeer::~NullaryMultiplayerPeer() {
}

void NullaryMultiplayerPeer::set_transfer_channel(int p_channel) {}

int NullaryMultiplayerPeer::get_transfer_channel() const { return 0; }

void NullaryMultiplayerPeer::set_transfer_mode(TransferMode p_mode) {}

MultiplayerPeer::TransferMode NullaryMultiplayerPeer::get_transfer_mode() const { return MultiplayerPeer::TransferMode::TRANSFER_MODE_UNRELIABLE; }

void NullaryMultiplayerPeer::set_refuse_new_connections(bool p_enable) {}

bool NullaryMultiplayerPeer::is_refusing_new_connections() const { return true; }

bool NullaryMultiplayerPeer::is_server_relay_supported() const { return false; }

void NullaryMultiplayerPeer::set_target_peer(int p_peer_id) { }

int NullaryMultiplayerPeer::get_packet_peer() const { return 0; }
MultiplayerPeer::TransferMode NullaryMultiplayerPeer::get_packet_mode() const { return MultiplayerPeer::TransferMode::TRANSFER_MODE_UNRELIABLE; }
int NullaryMultiplayerPeer::get_packet_channel() const { return 0; }

void NullaryMultiplayerPeer::disconnect_peer(int p_peer, bool p_force) { }

bool NullaryMultiplayerPeer::is_server() const { return false; }

void NullaryMultiplayerPeer::poll() {}
void NullaryMultiplayerPeer::close() {}

int NullaryMultiplayerPeer::get_unique_id() const { return 0; }

MultiplayerPeer::ConnectionStatus NullaryMultiplayerPeer::get_connection_status() const { return MultiplayerPeer::ConnectionStatus::CONNECTION_DISCONNECTED; }

```

Lastly, here is the code with the error, in GDScript:

```
func _ready():
#   var peer = ENetMultiplayerPeer.new()
#   NullaryMultiplayerPeer.new()
    var peer = NullaryMultiplayerPeer.new()
    peer.create_server(9999)
    self.multiplayer.multiplayer_peer = peer

```

The specific error, and all that I've been able to get out of it, is "Native class 'NullaryMultiplayerPeer' cannot be instantiated as it is abstract."

Can anyone see what I'm missing, and why Godot sees it as an abstract class?

# Answer
> 4 votes
I just ran into this while trying to extend `StreamPeer` to handle serial devices. It turns out that there is a `StreamPeerExtension` that is supposed to be as the base class instead. Using that got rid of the "Native class 'StreamPeerSerial' cannot be instantiated as it is abstract." error for me.

It looks like there is a `MultiplayerPeerExtension` class that should be used instead of `MultiplayerPeer`.

---
Tags: c++, godot-4, extension
---


# Question
Title: What transformations are performed under model space?
I am struggling to understand the relationship between model transformation, model space, and world space.

I understand that model transformation transforms an object from model space into world space.

Consider the usual ordering when it comes to transformations (SRT). Assume the world space is given by (x, y, z) and the model space is given by (u, v, w). Then, here is my initial guess.

1. Scaling happens in model space since scaling does not change the direction of the vector.
2. Rotation is the step that aligns (u, v, w) to (x, y, z). I don't know what space this transformation occurs in. Rotating an object around its center point in world space / rotating an object around its center point in model space all seem plausible to me.
3. Translation happens in world space since now (u, v, w) is aligned with (x, y, z).

What should be the correct way of thinking about this.

# Answer
Model space is the name of the space you are in *before* you have applied *any* of `S`, `R`, *or* `T`.

World space is the name of the space you are in *after* you have applied *all* of `S`, `R`, *and* `T`.

We don't generally name the spaces for each step of the transformation between the two. Often, all three are concatenated into one matrix `M = T * R * S`, so we're not applying them as individual steps at all but all at once, and a vector never exists in an intermediate space:

```
p_world = M * p_model

```

A "space" is not just the direction of its basis vectors, but also its scaling and absolute position / "reference zero". So we can't really say the vector is in either model ot world space when we've applied some of these steps but not all of them.

What we can say is...

* The first three diagonal components of the `S` matrix (`S[0,0]`, `S[1,1]` and `S[2,2]`) are the scale factors to apply to the model's `u`, `v`, and `w` axes, respectively.

The result could be called "scaled model space"
* The first three columns of the `R` matrix are the unit direction vectors in world space that you want the model's `u`, `v`, and `w` axes to point along after rotation. This rotation does not change the location of the model's origin (the point `u = v = w = 0`) — we pivot around this origin point.

The result could be called "scaled and rotated model space" or "unshifted world space" since it does not incorporate translation yet.
* The last column of the `T` matrix is point in world space where you want the model's pivot/origin to move to, after rotation.

Does that answer what you needed to know?
> 1 votes

---
Tags: transformation, models, spaces
---


title: Hide Children of Node

text:
# Question
Title: Hide Children of Node
I am making a addon for my friends, and I am trying to make a custom node. It works, but I have a problem, the children of the custom node is visible in the scene dock.

The `Text` node has children, but they aren't visible in the scene dock. I want the same thing with the Inventory node. (I added the `Text`, `GridContainer`,and `CenterContainer` nodes from another scene through code)

How would I go about this. (Preferably a solutions that uses GDScript)

# Answer
If you are adding nodes from code in a tool script, you need to set their `owner` in order for them to show in the scene dock and for them to be saved alongside the scene. For example, like this:

```
add_child(t)
t.owner = self if owner == null else owner

```

Since you don't want that, you just **don't set their `owner` property** (i.e. remove that part of the code).

Bear in mind this means that your custom node must also add its children in runtime since they won't be part of the scene.

*You can use `Engine.is_editor_hint()` to check if your code is running in the editor... But since you want to do the same thing in runtime, you don't need to do that either.*

Be aware that since they won't be accesible from the scene dock, the users of your addon won't be able to modify their properties directly or connect signals to or from them directly.
> 3 votes

---
Tags: godot, gdscript, godot-4
---


# Question
Title: how can i make my jump animation and fall animation to work in godot 4.2? when i press jump it doesnt play the animation and when it fall, the same
this is the code im using

```
    extends CharacterBody2D

@export var SPEED = 200.0
@export var JUMP_VELOCITY = -400.0
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

func _physics_process(delta):
    if not is_on_floor():
        velocity.y += gravity * delta
        $AnimatedSprite2D.play("fall")

    if Input.is_action_just_pressed("ui_up") and is_on_floor():
        velocity.y = JUMP_VELOCITY
        $AnimatedSprite2D.play("jump")

    var direction = Input.get_axis("ui_left", "ui_right")
    if direction:
        velocity.x = direction * SPEED
    else:
        velocity.x = move_toward(velocity.x, 0, SPEED)
    if velocity.x > 0 and is_on_floor_only() or velocity.x < 0 and is_on_floor_only():
        $AnimatedSprite2D.play("run")
    else:
        $AnimatedSprite2D.play("idle")

    if direction:
        if direction < 0:
            $AnimatedSprite2D.flip_h = true
            $AnimatedSprite2D.position.x = -20
        else:
            $AnimatedSprite2D.flip_h = false
            $AnimatedSprite2D.position.x = 20

    move_and_slide()

```

can someone help me please T-T

# Answer
Here's my guess. (I don't know if this is how it works though). You press the jump button and it plays the jump animation, but later down the road it checks if it is touching the ground and either plays the "run" or "idle" animation, and since it doesn't move until `move_and_slide()`, it is still touching the ground. Here's what I suggest.

```
if not is_on_floor() and velocity.y > 0:
   $AnimatedSprite2D.play("jump")
elif not is_on_floor() and velocity.y > 0:
   $AnimatedSprite2D.play("fall")

```

This may or may not fix it. (I am not 100% sure this will work, but it's something)
> 0 votes

---
Tags: godot-4
---


# Question
Title: How to achieve smooth camera dragging with the mouse in SDL2?
I am working on a 2D isometric perspective game using SDL2 and I would like to implement the ability to pan the map when the right mouse button is held down.

I was wondering what is best way to set this up? My existing solutions involve checking if the mouse button is held down and if it is, moving the camera relative to the direction of the motion of the mouse. But this is not very responsive and leads to stuttering.

I wonder if there is a generally agreed upon way of doing this?

# Answer
> 1 votes
It's difficult to understand what you mean by stuttering (is the camera panning too fast? Or is there tearing?), but here's a way to implement smooth camera movement.

For the sake of simplicity, I assume your camera has two variables `cameraX` and `cameraY` which determine the camera's position.

Add 2 new variables, `cameraTargetX` and `cameraTargetY`.

The idea is, every time the mouse moves the camera, instead of modifying the variables `cameraX` and `cameraY` it will move the `cameraTargetX` and `cameraTargetY`. Then in your `Update` you modify the value of `cameraX` and `cameraY` to get closer to `cameraTargetX` and `cameraTargetY` like so:

```
void update() {
    cameraX += cameraTargetX -cameraX *0.5;
    cameraY += cameraTargetY -cameraY *0.5;
}

```

This will cause the camera to move **half** the distance towards the target every frame. This is only an example, you can make a custom formula depending on how your game currently works, but hopefully this is enough to show a method of achieving this.

> I wonder if there is a generally agreed upon way of doing this?

In general with game development, there's multiple ways of doing things. As long as you get the desired result that runs with acceptable resources, you are good to go.

---
Tags: camera, sdl, mouse
---


# Question
Title: Texture loading issue with open gl es on android
I'm programming an app with OpenGL ES on Android in Java. The app uses 9 textures during a render loop pass. A depth, position, normal, albedo, noise, SSAO, SSAO blur and two image textures for the models I draw. The problem is that 9/10 times, the image textures fail to load. I get no GL error during or after loading the texture. I get an error 1282 when I bind the texture 8 and 9 during the draw call. But only when they don't load/show up. When they load and show up I get no error and they are displayed correctly on the primitives.

According to the documentation of `glBindTexture`, the method generates the error code 1282 (`GL_INVALID_OPERATION`) if texture was previously created with a target that doesn't match that of the target. The only target I use in the whole application is `GL_TEXTURE_2D`, so I don't understand why I get this error.

Since I'm using a deferred rendering pipeline, I thought that maybe the albedo buffer is messed up, but I could rule that out by setting constant colors for the whole scene directly in the fragment shader of the geometry pass, and that is working fine every time.

I managed to take GPU-snapshots of both cases using snapdragon profiler to debug the app/profile the GPU (Adreno 630). I could verify that all the uniforms are correct, the attribute arrays are also correct and the correct units are active in both cases. The difference I could notice in the error case is that both image textures are missing, the rest is there. These are all the textures on the GPU when they load:

Here, in the other snapshot they are missing, even though it is the exact same code that loads the textures. In both cases I get valid handles/indexes when I call `glGenTexture`.

It just seems that somehow the textures aren't loaded anymore during the draw call.

The image textures are being loaded like this:

```
AssetManager assetManager = context.getAssets();
InputStream stream = assetManager.open(id.getResourceName());
int[] textureHandle = new int[1];

BitmapFactory.Options option = new BitmapFactory.Options();
option.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, option);
//GLES30.glActiveTexture(GLES30.GL_TEXTURE5);
GLES30.glGenTextures(1, textureHandle, 0);
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureHandle[0]);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_MIRRORED_REPEAT);
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_MIRRORED_REPEAT);
if (bitmap != null) {
    Log.d(TextureLoader.class.getSimpleName(), "Texture format: " + GLUtils.getInternalFormat(bitmap));
    GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0);
    bitmap.recycle();
}
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);

ShaderUtil.checkGLError(TextureLoader.class.getSimpleName(), "Failed to load texture");

Log.d("Texture id", String.valueOf(textureHandle[0]));

return textureHandle[0];

```
* The code above is executed during the `onSurfaceCreated` invocation, so I have a valid OpenGL context.
* The code above is executed two times, once per image texture in sequential order.
* Both textures are of type 32 bit RGBA (PNG) 512px x 512px

The code below is executed in the render loop. I have multiple models, some are using one texture and some the other one.

```
GLES30.glActiveTexture(GLES30.GL_TEXTURE5);
GLES30.glUniform1i(shaderHandles.getTextureMapHandle(), 5);
ShaderUtil.checkGLError("Render loop", "Activate unit");
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureDataHandle);
ShaderUtil.checkGLError("Render loop", "Activate " + textureDataHandle);

```

I've been debugging for multiple days now, so I appreciate any help. Thank you

Edit: Some new discoveries i made were, that if I load the textures before I create the all the frame buffers for shadow mapping and SSAO, I get the content of the shadow map texture on one model (just the red channel) and the position buffer as rgb content of the other model. That happens since I get index 1 & 2 for the image textures from open gl, but the depth, position, ... texture restart at 1 with indexing. And then I bind the texture with index 1 & 2 as model textures, which happen to be the depth texture and the position texture. I just dont understand why the indexing restarts.

Edit 2: Using the profiler I found out that I have two contexts and the image textures are loaded in the other context. Why am I having two contexts?

# Answer
> 0 votes
I figuerd out why the texture loading was not working. I had two `glSurfaceView` in two fragments in my project.

Switching from one to another messed the EGL context up and created a race condition where the texture loaded on the current context and sometimes on the old context. Im not sure if it was the old context or another one that was created just in the `onSurfaceCreated` callback.

I solved it by creating my own `SurfaceViews` and managing the context, render thread, ... by my self.

---
Tags: android, opengl-es
---