text:
Creating a flattened (panorama?) 2D view of a cubemap
I am trying to generate a 360 degree view of a scene by sampling a depth cubemap using spherical coordinates. x and y represent the horizontal, or azimuth, and elevation angles respectively and the actual value at each pixel is the depth.
Output: So far I have not been able to achieve this. I am not getting any errors just a blank 2D image.
Here are what I consider to be the essential parts of the process.
First creating a cubemap to store depth information,
# CREATE EMPTY CUBEMAP
######################
CM = 2

depth_map_fbo = glGenFramebuffers(1)
glBindFramebuffer(GL_FRAMEBUFFER, depth_map_fbo)

depth_cube_tex = glGenTextures(1)
glBindTexture(GL_TEXTURE_CUBE_MAP, depth_cube_tex)

for i in range(6):
    glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+i, 0, GL_DEPTH_COMPONENT32, CM*1024, CM*1024,
                    0, GL_DEPTH_COMPONENT, GL_FLOAT, None)

glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST) # or GL_LINEAR?
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
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)

# attach depth texture to fbo depth buffer
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depth_cube_tex, 0)
glDrawBuffer(GL_NONE)
glReadBuffer(GL_NONE)
glBindFramebuffer(GL_FRAMEBUFFER, 0)

Second, obtaining depth information for a simple scene made out of 3 cubes and a floor,
# CREATE A DEPTH CUBE
#####################

                    # relative are not correct???
#                   pitch, yaw, rel_pitch, rel_yaw, name, location
rotation_dict= {0: [   0,  90,         0,      90, 'X+', 'Right'],
                1: [   0, -90,         0,    -180, 'X-', 'Left'],
                2: [  90, 180,       -90,      90, 'Y+', 'Top'],
                3: [ -90, 180,       180,       0, 'Y-', 'Bottom'],
                4: [   0,   0,       -90,     180, 'Z+', 'Back'],
                5: [   0, 180,         0,    -180, 'Z-', 'Front']}

# cubemap camera
cubemap_camera.width = CM*1024
cubemap_camera.height = CM*1024
cubemap_camera.zoom = 90.0

# # bind depth map buffer
glBindFramebuffer(GL_FRAMEBUFFER, depth_map_fbo)

# set viewport size to cubemap size
glViewport(0, 0, CM*1024, CM*1024)

# activate cubemap shader
cubemap_shader.use()

# create a projection matrix
projection = glm.perspective(glm.radians(90.0), 1.0, 0.1, 100)
cubemap_shader.set_uniform_mat4('projection', projection)

# RENDER TO DEPTH CUBEMAP
##########################
for i in range(6):

    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X+i,
                           depth_cube_tex, 0)

    # all fine?
    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE):
        raise RuntimeError("ERROR.FRAMEBUFFER. Framebuffer is not complete!")

    # clear colors and buffers
    glClearColor(0.1,0.1,0.1,0.1)
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT)

    # rotate camera
    cubemap_camera.pitch = rotation_dict[i][0] #0
    cubemap_camera.yaw =  rotation_dict[i][1] #1
    cubemap_camera.update_camera_vectors()

    # update view (lookat matrix)?
    view = cubemap_camera.get_matrix_view()
    cubemap_shader.set_uniform_mat4('view',view)

    # load textures
    cube_texture = texture_from_file(pth, Path(r'textures/marble.jpg') )
    floor_texture = texture_from_file(pth, Path(r'textures/metal.png') )

    # render cubes
    glBindVertexArray(cube_vao)
    glActiveTexture(GL_TEXTURE0)
    glBindTexture(GL_TEXTURE_2D, cube_texture)

    # update projection and view matrices for display camera
    cubemap_shader.set_uniform_mat4('projection', projection)
    view = cubemap_camera.get_matrix_view()
    cubemap_shader.set_uniform_mat4('view',view)

    # cube 1
    model = glm.mat4(1.0)
    model = glm.translate(model, glm.vec3(0.0, 0.0, -5.0))
    cubemap_shader.set_uniform_mat4('model', model)
    glDrawArrays(GL_TRIANGLES, 0, 36)

    # cube 2
    model = glm.mat4(1.0)
    model = glm.translate(model, glm.vec3(-5.0, 0.0, 0.0))
    cubemap_shader.set_uniform_mat4('model', model)
    glDrawArrays(GL_TRIANGLES, 0, 36)

    # cube 3
    model = glm.mat4(1.0)
    model = glm.translate(model, glm.vec3(0.0, 2.0, 0.0))
    cubemap_shader.set_uniform_mat4('model', model)
    glDrawArrays(GL_TRIANGLES, 0, 36)

    glBindVertexArray(0) # remove binding

    # render floor
    glBindVertexArray(floor_vao)
    glBindTexture(GL_TEXTURE_2D, floor_texture)
    cubemap_shader.set_uniform_mat4('model', glm.mat4(1.0))
    glDrawArrays(GL_TRIANGLES, 0, 6)
    glBindVertexArray(0) # remove binding

    # #output ?
    # zbuffer = glReadPixelsf(0, 0, CM*1024, CM*1024, GL_DEPTH_COMPONENT, GL_FLOAT)
    # zbuffer = zbuffer.reshape((CM*1024, CM*1024))
    # np.save(f'{rotation_dict[i][5]}_cube', np.flipud(zbuffer))

    glfw.swap_buffers(window)

# unbind fbo
glBindFramebuffer(GL_FRAMEBUFFER, 0)

Last, sampling the cubemap just created. This is the part that I am less certain. How do I sample the cubemap in order to get the depth values for my 2D image. I am trying to do this using  shaders but I am not certain at all whether this are correct
# SAMPLING CUBEMAP
##################

hangle = np.array([0,360,0.05], dtype=np.float32)
vangle = np.array([-90,0, 0.05], dtype=np.float32)

raw_width = (hangle[1]-hangle[0]) / hangle[2]
raw_height = (vangle[1]-vangle[0]) / vangle[2]

# create scene buffer
scene_buffer = glGenFramebuffers(1)
glBindFramebuffer(GL_FRAMEBUFFER, scene_buffer)

# attach a render buffer
rbo = glGenRenderbuffers(1)
glBindRenderbuffer(GL_RENDERBUFFER, rbo)
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo)

if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE):
        raise RuntimeError("ERROR.FRAMEBUFFER. Framebuffer is not complete!")

# send information to sampling shader
cubemap_sampling_shader.use()
cubemap_sampling_shader.set_uniform_vec3('hangle', hangle)
cubemap_sampling_shader.set_uniform_vec3('vangle', vangle)
cubemap_sampling_shader.set_uniform_int('cubetex', depth_cube_tex)

# #output ?
zbuffer = glReadPixelsf(0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT)
zbuffer = zbuffer.reshape((height, width))
np.save('Scene', np.flipud(zbuffer))

glBindRenderbuffer(GL_RENDERBUFFER, 0)

As mention all I get for 2D image (a numpy array) that is blank made out of 0s.
My shaders for the sampling are: vertex,
#version 330 core

uniform vec3 hangle; // horizontal angular range and increment
uniform vec3 vangle; // vertical angular range and increment
out vec3 dir_vector;

void main(){
    for (float theta = vangle.x; theta < float(vangle.y); theta+= vangle.z){
        for (float psi = hangle.x;  psi <  float(hangle.y); psi+= hangle.z){
            float x = sin(radians(theta)) * cos(radians(psi));
            float z = sin(radians(theta)) * sin(radians(psi));
            float y = cos(radians(theta));
            dir_vector = vec3(x,y,z);
        }
    }
}

and fragment,
#version 330 core

in vec3 dir_vector;
uniform samplerCube cubetex;

void main(){
            gl_FragDepth = texture(cubetex, dir_vector).z;
}
```


text:
GooglePAD and Chunking to Reduce .aab Size
I would like to upload a large Android game to the Play Store. My .aab file is about 1.3 GB in size. When I try to upload it to the Play Store I get the following error message:
The total download size of upfront Asset Packs in this App Bundle is 1292631053. Upfront Asset Packs can have a combined download size of 1073741824.
I understand that I need to use GooglePAD. I’ve tried to set up the chunking, but now the main .aab is still as large as ever, but I do get several .pak files that add up to a combined file size of 1.3 GB.
Any advice?
Thanks.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Jagged peak artifacts on terrain
My terrain rendering shows these jagged peaks along the edges of some hills:

Why do these occur, and how can I fix this?
Here is the code I use to initialize my surface and draw a frame:
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {

    GLES30.glClearColor(184.0f / 255.0f, 213.0f / 255.0f, 238.0f / 255.0f, 1.0f);

    terrain = new Terrain(context);

}

@Override
public void onDrawFrame(GL10 gl) {

    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT);

    camera.Update();
    terrain.draw(gl, camera.camera_model, camera.camera_view, camera.camera_projection);

}

It looks like certain vertices are getting an invalid position - maybe zero, maybe infinity, maybe even NaN - causing alternating triangles along the ridge to either abort rendering or stretch out to some distant location. To diagnose this, we'd need to know what the source is for the vertex positions you're drawing (are you reading them from a heightmap texture, or procedurally generating the terrain in some way?) and see the vertex shader code that transforms these vertices to their rendered positions. Try editing your question to include a minimal reproducible example of the problem.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Convolution matrix based minimum distance calculation
I want to detect the minimum distance to each game object within a convolution matrix in a compute shader.
I know the code is a bit to read, but the logic itself is not too complicated. I am trying to use base 100 indexing for the variables (omegaX, omegaY which stores all deltas to each game object within a matrix for each invocation), because passing a small compute buffer from C# leads to indexing clashes due to race conditions and passing a large buffer causes memory overflow.
Here is my function:
[numthreads(12,12,1)]
void CSMain (uint3 id : SV_DispatchThreadID)
{
    if(int(id.x) - 59 < 0 || int(id.x) + 58 >= MaxWidth || int(id.y) - 59 < 0 || int(id.y) + 58 >= MaxHeight) {
        //Overflow prevention.
        //For now, ignore screen edges.
        return;
    }

    float4 srcPixel = Src[id.xy];

    if(any(srcPixel.rgba > float4(0,0,0,0).rgba)) {
        //Center of convolution matrix on opaque pixel
        float4 displayPixel = float4(0,0,0,0);

        uint visibleGameObjectCount = 0;
        for(int i = 0; i < GameObjectListCount; i++) {
            float4 colorAtDepth = ColorTextureArray.Load(uint3(id.xy, i));
            if(any(colorAtDepth.rgba > float4(0,0,0,0).rgba)) {
                displayPixel += colorAtDepth / GameObjectListCount;
                visibleGameObjectCount++;
            }
        }
        displayPixel *= (GameObjectListCount / visibleGameObjectCount);
        Dest[id.xy] = displayPixel;
        return;
    }
    else {
        bool emptyMatrix = true;

        //Variables to store minimum distances to each game object
            //deltaX and deltaY added here may be negative, because it is distance from id.xy

        //I need separate storages for positive and negative delta
            //Because adding a negative index to omegaX and omegaY makes the added number go out of its bounds
        uint omegaX = 0;
        uint omegaY = 0;

        //Or simply store only absolute values in omegaX and omegaY, store a separate variable that represents -,- or +,+ one for x and one for y for each game object, which is similarly indexed using each game object's index
            //Every time omegaX and omegaY is being updated, signUnsignXY will also be updated 1 for sign, 0 for unsign
        uint signUnsignXY = 0;

        //Will be used for avg. distance calculation
        float indexesForDistance = 0;

        //Counter for visible game objects within each convolution matrix
        float visibleGameObjectCountMatrix = 0;

        //Modified logic:
            //Check if a pixel within the convolution matrix is opaque
            //If it is, start iterating through ColorTextureArray at that location(xy)
            //In order to compare with the previous minimum, for *every* pixel that is *opaque* within
                //that xy's *ColorTextureArray*, use its index to access the actual deltaX and deltaY
                //that belongs to that game object, and if the current value is less than the previously
                //update the values using:
                    //omegaX = omegaX - ((omegaX / 100^i) % 100) + (deltaX * 100^i)
                    //omegaY = omegaY - ((omegaY / 100^i) % 100) + (deltaY * 100^i)
                    //When doing the actual comparison, it must be between pythagorean distances
        //Convolution matrix: size = 57x57(i.e. ~1.5 cm)
            //Caution: Proceed to read in a peaceful environment
        for(int i = 29; i > -28; i--) {
            for(int j = 29; j > -28; j--) {
                float4 srcPixel = Src[id.xy - int2(j, i)];
                if(any(srcPixel.rgba > float4(0,0,0,0).rgba)) {
                    emptyMatrix = false;
                    // Dest[id.xy] = float4(1,1,1,1);

                    //Current minimum that may or may not overwrite previous minimum
                    //For the first current minimum, either deltaX or deltaY must > 0, since case 0 is already
                        //taken care of above and the fact that it is visible at this location means a minimum of a GO
                    int deltaX = -j;
                    int deltaY = -i;
                    //Positive by default
                    uint signX = 1;
                    uint signY = 1;

                    if(deltaX < 0) {
                        signX = 0;
                    }
                    if(deltaY < 0) {
                        signY = 0;
                    }
                    //As long as a deltaX or deltaY exists, it's abs is guaranteed to be > 0
                    float minimumDistance = 1 / rsqrt(deltaX * deltaX + deltaY * deltaY);

                    for(int c = 0; c < GameObjectListCount; c++) {
                        float4 minimumDistancePixel = ColorTextureArray.Load(uint3(id.xy - int2(j, i), c));
                        //First check whether each pixel in ColorTextureArray at this location is opaque
                        if(any(minimumDistancePixel.rgba > float4(0,0,0,0).rgba)) {
                            //id.x + omegaX(indexed)
                            uint previousGameObjectAccessor = (uint)pow(100, c);

                            uint previousDeltaX = (omegaX / previousGameObjectAccessor) % 100;
                            //id.y + omegaY(indexed)
                            uint previousDeltaY = (omegaY / previousGameObjectAccessor) % 100;

                            //Previous pythagorean distance
                            float previousMinimumDistance = 0;

                            //Problem: while 1 / (1 / x) = x for most numbers, for 0, it becomes division by 0
                            if(previousDeltaX > 0 || previousDeltaY > 0) {
                                previousMinimumDistance = 1 / rsqrt(previousDeltaX * previousDeltaX + previousDeltaY * previousDeltaY);
                            }

                            if(previousMinimumDistance > minimumDistance) {
                                //New minimum for game object at index c, but it has been mapped already and can be indexed with discrete values

                                //Write new minimum in StorageTextureArray:
                                float4 previousStoredPixel = StorageTextureArray.Load(uint3(id.xy - int2(j, i), c));
                                if(all(previousStoredPixel.rgba <= float4(0,0,0,0).rgba)) {
                                    StorageTextureArray[uint3(id.xy - int2(j, i), c)] = minimumDistancePixel;
                                }

                                //Dest[id.xy - int2(j, i)] = float4(0,0,1,1);

                                //Update omegaX and omegaY while replacing previous deltaX and deltaY
                                omegaX = omegaX - ((omegaX / previousGameObjectAccessor) % 100) + abs(deltaX) * previousGameObjectAccessor;
                                omegaY = omegaY - ((omegaY / previousGameObjectAccessor) % 100) + abs(deltaY) * previousGameObjectAccessor;

                                //Update signUnsignXY (rewrite)
                                uint totalSign = signX * 10 + signY;
                                signUnsignXY = signUnsignXY - ((signUnsignXY / previousGameObjectAccessor) % 100) + totalSign * previousGameObjectAccessor;

                                //Once a mapping has been created for every visible game object, further updating indexes for distance not necessary,
                                //because every game object that was visible at least once in the matrix will also be factored in the weighted color
                                //computation that uses minimum distances of all game objects
                            }
                            //Is this valid logic to count unique game objects using this conditional?
                            else if(previousMinimumDistance == 0) {
                                //Very first instance of a unique game object index at xy
                                    //i.e. this if condition will run only once for each game object index

                                //Why can the matrix detect one game object but not 2???
                                    //This means previousMinimumDistance == 0  is true only once within the convolution matrix
                                    //Even though accessing a game object that hasn't been indexed yet must return 0

                                //Write new minimum in StorageTextureArray:
                                float4 previousStoredPixel = StorageTextureArray.Load(uint3(id.xy - int2(j, i), c));
                                if(all(previousStoredPixel.rgba <= float4(0,0,0,0).rgba)) {
                                    StorageTextureArray[uint3(id.xy - int2(j, i), c)] = minimumDistancePixel;
                                }

                                //Dest[id.xy - int2(j, i)] = float4(0,1/c,0,1);

                                //Update omegaX and omegaY without replacing with deltaX and deltaY (absolute value)
                                omegaX += abs(deltaX) * previousGameObjectAccessor;
                                omegaY += abs(deltaY) * previousGameObjectAccessor;

                                //Update signUnsignX
                                uint totalSign = signX * 10 + signY;
                                signUnsignXY += totalSign * previousGameObjectAccessor;

                                //Create (discrete index) to (game object index) mapping

                                //indexesForDistance += c * pow(100, visibleGameObjectCountMatrix);
                                //Increment this value until it becomes the maximum # of GO in matrix
                                //visibleGameObjectCountMatrix++;

                                //visibleGameObjectCountMatrix runs once for either case, but if one case runs, the other case doesn't
                                //Why the fuck does this happen?

                                visibleGameObjectCountMatrix++;
                            }
                        }
                    }
                }
            }
        }
        //End of convolution matrix processing

        //Come up with a test:
        //Test for accuracy of matrix
        // if(visibleGameObjectCountMatrix == 0) {
        //     //Dest[id.xy] = float4(1,0,0,1);
        // }

        //At this point, either emptyMatrix or we have all the information needed to apply to this pixel
        if(!emptyMatrix) {
            if(visibleGameObjectCountMatrix == 2) {
                Dest[id.xy] = float4(1,0,0,1);
            }

            //Test of whether for each xy, it properly colors the right location in StorageTextureArray
            // for(int i0 = 0; i0 < visibleGameObjectCountMatrix; i0++) {
            //     uint currentGameObjectIndex = (indexesForDistance / pow(100, i0)) % 100;

            //     //Access color
            //     int finalDeltaX = (omegaX / pow(100, currentGameObjectIndex)) % 100;
            //     int finalDeltaY = (omegaY / pow(100, currentGameObjectIndex)) % 100;
            //     float pythagoreanDelta = 1 / rsqrt(finalDeltaX * finalDeltaX + finalDeltaY * finalDeltaY);
            //     //Here, apply appropriate signs
            //         //Fetch sign for x
            //     if((((signUnsignXY / pow(100, currentGameObjectIndex)) % 100) / pow(10, 1)) % 10 == 0) {
            //         finalDeltaX = -finalDeltaX;
            //     }
            //         //Fetch sign for y
            //     if(((signUnsignXY / pow(100, currentGameObjectIndex)) % 100) % 10 == 0) {
            //         finalDeltaY = -finalDeltaY;
            //     }
            //     float4 storageColor = StorageTextureArray.Load(uint3(id.xy + int2(finalDeltaX, finalDeltaY), currentGameObjectIndex));
            //     //This is supposed to color only the slime borders...
            //     Dest[id.xy + int2(finalDeltaX, finalDeltaY)] = float4(1,0,0,1);
            // }

            //This logic seems to be problematic ()
                //Why the fuck is the shape of all the id.xy where # of game objects found within the matrix >= 2 fucked up?

            //This logic must be true for a wide area?
            // if(visibleGameObjectCountMatrix >= 2) {
            //     Dest[id.xy] = float4(1,0,1,1);
            // }

            // if(visibleGameObjectCountMatrix >= 2) {
            //     //Only apply metaball effect if at least 2 game objects are within the matrix, otherwise, meaningless
            //     float avgDistanceDelta = 0;
            //     float totalDistanceDelta = 0;
            //     float4 weightedColor = float4(0,0,0,0);

            //     //Loop responsible for computing:
            //         //1. avg distance
            //         //2. total distance
            //     for(uint i1 = 0; i1 < visibleGameObjectCountMatrix; i1++) {
            //         uint currentGameObjectIndex = (indexesForDistance / pow(100, i1)) % 100;

            //         //finalDeltaX and finalDeltaY are guaranteed to be > 0, since they were stored that way
            //         uint finalDeltaX = (omegaX / pow(100, currentGameObjectIndex)) % 100;
            //         uint finalDeltaY = (omegaY / pow(100, currentGameObjectIndex)) % 100;
            //         //pythagorean delta distance
            //         float pythagoreanDelta = 1 / rsqrt(finalDeltaX * finalDeltaX + finalDeltaY * finalDeltaY);
            //         //Avg
            //         avgDistanceDelta += pythagoreanDelta / visibleGameObjectCountMatrix;
            //         //Total
            //         totalDistanceDelta += pythagoreanDelta;
            //     }
            //     //Loop responsible computing weighted color
            //     for(uint i2 = 0; i2 < visibleGameObjectCountMatrix; i2++) {
            //         uint currentGameObjectIndex = (indexesForDistance / pow(100, i2)) % 100;

            //         //Access color
            //         int finalDeltaX = (omegaX / pow(100, currentGameObjectIndex)) % 100;
            //         int finalDeltaY = (omegaY / pow(100, currentGameObjectIndex)) % 100;
            //         float pythagoreanDelta = 1 / rsqrt(finalDeltaX * finalDeltaX + finalDeltaY * finalDeltaY);
            //         //Here, apply appropriate signs
            //             //Fetch sign for x
            //         if((((signUnsignXY / pow(100, currentGameObjectIndex)) % 100) / pow(10, 1)) % 10 == 0) {
            //             finalDeltaX *= -1;
            //         }
            //             //Fetch sign for y
            //         if(((signUnsignXY / pow(100, currentGameObjectIndex)) % 100) % 10 == 0) {
            //             finalDeltaY *= -1;
            //         }
            //         float4 unweightedColor = StorageTextureArray.Load(uint3(id.xy + int2(finalDeltaX, finalDeltaY), currentGameObjectIndex));
            //         //Why is this not contained in
            //         //int2(finalDeltaX / 1000, finalDeltaY / 1000)
            //         //int2(finalDeltaX, finalDeltaY)
            //         //Dest[id.xy + int2(finalDeltaX, finalDeltaY)] = float4(1,0,0,1);
            //         float weight = (totalDistanceDelta - pythagoreanDelta - ((visibleGameObjectCountMatrix * totalDistanceDelta - 2 * totalDistanceDelta) / visibleGameObjectCountMatrix)) / totalDistanceDelta;
            //         weightedColor += unweightedColor * weight;
            //     }

            //     //Condition to decide whether or not to color current dest.xy SV_DispatchThreadID
            //     if(avgDistanceDelta < 20) {
            //         //Dest[id.xy] = weightedColor;
            //         //Dest[id.xy] = weightedColor;
            //     }
            //     //Dest[id.xy] = float4(0,1,0,1);
            //     //Dest[id.xy] = max(testColor0, testColor1);
            //     Dest[id.xy] = float4(1,0,0,1);
            // }
            //else if (visibleGameObjectCountMatrix < 2) {
                //Dest[id.xy] = float4(1,0,0,1);
            //}
            //Dest[id.xy] = float4(1,0,1,1);
            // if((int)visibleGameObjectCountMatrix == 2) {
            //     Dest[id.xy] = float4(1,0,1,1);
            // }
            //Dest[id.xy] = float4(1,0,0,1);
        }
        return;
    }
    //Test:
    //If storage texture array was updated properly, then
    //float4 testColor0 = StorageTextureArray.Load(uint3(id.xy, 0));
    //float4 testColor1 = StorageTextureArray.Load(uint3(id.xy, 1));
    //Dest[id.xy] = max(testColor0, testColor1);
    //Dest[id.xy] = testColor1;
    //return;
}

As you can see in my test, all pixels where its respective matrix has discovered 2 game objects must be colored red, but that region looks ugly and disgusting like:

Please help me debug this.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.


text:
Why is my code giving an infinite while loop/crashing?
I have this large code that produces buttons that are meant to be clicked.
import pygame
import csv
import time
from datetime import datetime
#import RPi.GPIO as GPIO
#from picamera2 import Picamera2 , Preview
#from libcamera import controls
#from picamera2.encoders import H264Encoder

# Constants
ITI = 2 # Inter-trial interval in seconds

# Initialize pygame starts
pygame.init()

# Set the dimensions of the screen
screen_width = 1275
screen_height = 750

# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)

# Set the font
font = pygame.font.SysFont('Arial', 20)

# Set the button properties
button_radius = 70
button_x_spacing = 400
button_y_spacing = 200

# Set the button positions
button_positions = [
    (button_x_spacing, button_y_spacing),
    (button_x_spacing, button_y_spacing + 200),
    (button_x_spacing, button_y_spacing + 400)
]

# Inputs
trials = int(input("Number of trials: "))
AnimalName = input("Animal Name: ")
Trial_Duration = int(input("Trial Duration (s): "))

# Setting up Camera
#camera = Picamera2()
#vidconfig = camera.create_video_configuration()
#camera.configure(vidconfig)
#encoder = H264Encoder(bitrate=10000000)
#vidname = f"{AnimalName}_WCST_S3_{datetime.now().strftime('%Y%m%d_%H%M%S')}_Video.h264"
#camera.start_preview(Preview.QTGL)
#camera.start_recording(encoder,vidname)
#camera.annotate_text = f"{AnimalName}_WCST_S3_{datetime.now().strftime('%Y%m%d_%H%M%S')}"

# Initialize the screen
screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)

# Set the caption
pygame.display.set_caption("Marmoset Buttons")

# Set the clock
clock = pygame.time.Clock()

# Set the counters
correctleft = 0
correctmiddle = 0
correctright = 0
incorrectleft = 0
incorrectmiddle = 0
incorrectright = 0
trialnum = 0
timeouts = 0

# Set the lists
timelistleft = []
timelistmiddle = []
timelistright = []
summarysequence = []

# GPIO Setup
#GPIO.setmode(GPIO.BCM)
#GPIO.setwarnings(False)

# Psuedorandom sequence of numbers
sequence = [1,1,2,2,1,2,1,0,1,1, 1,2,1,0,1,0,1,2,1,1, 2,1,0,1,2,1,1,0,1,2, 2,1,0,2,1,1,1,0,1,1,
           1,1,0,1,1,1,2,0,2,1, 2,1,0,1,0,1,1,2,2,1, 1,0,1,1,0,0,1,1,2,2, 1,1,2,1,1,2,1,0,1,1,
           1,1,1,0,1,1,2,0,2,1, 0,1,1,2,1,0,1,2,1,0, 1,1,0,1,1,2,1,2,1,0, 2,1,2,1,1,2,1,1,0,1,
           1,0,1,1,0,1,1,1,1,1, 1,1,2,1,1,1,0,1,1,2, 1,2,1,0,1,2,2,2,1,0, 1,2,1,0,0,1,2,1,2,0,
           1,0,1,1,1,0,1,1,2,1, 0,1,2,2,1,1,1,0,1,1, 1,0,1,2,0,1,0,1,1,2, 0,1,2,1,2,1,2,2,1,0,
           1,1,1,0,1,1,0,1,1,0, 1,2,2,1,0,1,1,2,0,1, 1,0,1,2,1,0,1,2,1,0, 1,0,1,1,2,2,1,1,0,0,
           1,2,1,2,1,1,1,0,1,0, 1,1,0,1,2,1,1,2,1,0, 1,2,1,1,0,1,0,1,1,0, 1,2,0,2,1,2,1,0,0,1,
           1,1,1,1,0,0,1,2,0,1, 0,1,2,0,1,2,1,2,1,0, 1,0,1,2,1,1,2,0,1,2, 0,0,1,0,2,1,2,1,2,1,
           1,2,2,2,1,1,2,1,1,0, 1,2,1,1,0,2,1,2,1,1, 1,2,2,1,1,2,1,0,0,1, 2,1,2,1,0,2,1,2,0,0,
           1,0,1,1,2,2,1,0,1,0, 0,1,2,1,1,0,1,2,0,1, 1,0,0,1,2,1,2,1,0,0, 1,2,0,0,2,1,0,2,1,1,
           1,1,1,1,2,1,1,0,1,1, 2,1,0,1,1,0,1,2,1,0, 0,1,2,1,2,1,0,1,2,1, 2,1,0,2,1,2,1,1,2,1,
           1,1,0,1,1,1,2,1,1,1, 2,1,2,1,0,0,1,2,1,2, 1,0,1,2,1,2,0,1,2,2, 2,0,1,2,1,2,1,0,1,1,
           1,2,1,0,1,2,0,2,2,2, 1,2,2,1,1,0,1,1,0,0, 1,1,0,1,0,0,1,2,1,2, 1,0,2,1,2,1,2,1,0,1,
           1,2,1,1,0,1,1,0,0,1, 1,1,1,2,1,1,0,1,1,1, 1,2,1,0,2,2,1,2,0,1, 1,1,2,2,1,0,1,2,1,0,
           1,2,0,1,1,0,1,1,2,1, 1,2,2,2,1,1,1,0,1,0, 1,2,0,0,0,1,2,2,0,1, 0,2,1,0,0,1,2,2,2,1,
           1,1,2,1,0,1,0,1,2,1, 1,2,1,0,1,1,2,1,0,2, 1,0,2,2,1,0,1,0,2,1, 1,0,2,1,2,1,1,0,0,1,
           1,2,1,2,1,1,1,0,1,1, 1,1,0,0,1,2,1,2,1,0, 1,2,1,2,2,1,0,1,0,0, 2,1,0,2,0,1,0,1,2,1,
           1,1,0,1,0,1,1,1,0,1, 1,2,1,0,1,0,1,2,1,0, 2,1,2,2,1,0,1,0,1,1, 2,1,2,0,1,2,1,2,0,0,
           1,1,2,0,2,1,2,1,1,0, 1,2,1,0,0,1,1,2,1,2, 1,2,2,1,1,1,1,2,0,0, 1,2,1,0,0,2,1,0,2,1,
           1,0,1,1,2,1,2,0,1,2, 2,1,0,1,1,0,1,2,1,0, 0,1,0,1,2,1,1,2,1,0, 2,2,1,0,0,1,2,1,2,1]

# Truncating list
#trials = int(input("Number of trials: "))
n = len(sequence)
for i in range(0, n - trials):
    sequence.pop()

# Setting up CSV title
thedatetime = datetime.now()
thetime = thedatetime.strftime("%H:%M:%S")
title = f"{AnimalName}_WCST_S3_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"

# Write headers to csv file
data = open(title, 'w')
writer = csv.writer(data)
writer.writerow(["Trial#", "Event Code", "Time"])

time_start = time.time()

# For loop parsing through sequence
for i in sequence:

    trialnum += 1
    summarysequence.append(i)

    # Writing summary csv
    if trialnum%10 == 0:
        if trialnum == 10:
            title2 = f"{AnimalName}_WCST_S3_{datetime.now().strftime('%Y%m%d_%H%M%S')}_Summary.txt"
            summary = open(title2, "a+")
            summary.write(f"Trial Duration: {Trial_Duration}\n")
            summary.write(f"ITI: {ITI/1000}\n")
        meanleft = sum(timelistleft) / len(timelistleft)
        meanmiddle = sum(timelistmiddle) / len(timelistmiddle)
        meanright = sum(timelistright) / len(timelistright)
        #summary = open(title2, "a+")
        summary.write(f"Completed Trials (saved every 10th): {trialnum}\n")
        summary.write("Sequence: " + str(summarysequence) + "\n")
        summary.write(f"Correct: {correctleft},{correctmiddle},{correctright}\n")
        summary.write(f"Incorrect: {incorrectleft},{incorrectmiddle},{incorrectright}\n")
        summary.write(f"Total Reward: {correctleft+correctmiddle+correctright}\n")
        summary.write(f"Total No Reponses: {timeouts}\n")
        summary.write(f"Mean Reaction Times: {meanleft}, {meanmiddle}, {meanright}\n")
        summary.write("------------------------------------------------------------\n")

    # Delay between buttons
    screen.fill(black)
    pygame.display.update()

    time_end = time.time() + ITI
    while time.time() < time_end:
        if pygame.mouse.get_pressed()[0]:
            if i == 0:
                writer.writerow([trialnum, 210, time.time() - time_start])
                time_end += 0.5
            elif i == 1:
                writer.writerow([trialnum, 211, time.time() - time_start])
                time_end += 0.5
            elif i == 2:
                writer.writerow([trialnum, 212, time.time() - time_start])
                time_end += 0.5

    # While loop variable
    correct = False

    # Starts Timer
    #start_time = pygame.time.get_ticks()
    start_time = time.time()

    # Writing the button in csv file
    timedisplay = time.time()
    writer.writerow([trialnum, i, timedisplay - time_start])

    # Loops while button isn't correct
    while correct == False:

        # Time out for 15 seconds
        seconds = (time.time() - start_time)
        if seconds >= Trial_Duration:
            timeouts +=1
            timenow = time.time()
            writer.writerow([trialnum, 250, timenow - time_start])
            break

        # Checks when screen is touched
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:

                # Distance between point touched and button
                distance_button = pygame.math.Vector2(button_positions[i]) - pygame.math.Vector2(pygame.mouse.get_pos())

                # Checks if distance is within button
                if distance_button.length() < button_radius:

                    correct = True
                    timecorrect = time.time()
                    writer.writerow([trialnum, 150, timecorrect - time_start])

                    # Reward
                    #GPIO.setup(12,GPIO.OUT)
                    #GPIO.output(12,GPIO.HIGH)
                    #time.sleep(0.1)
                    #GPIO.output(12,GPIO.LOW)
                    #GPIO.cleanup()

                    # Counts which buttons were pressed
                    if i == 0:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistleft.append(timedifference)
                        correctleft += 1
                    elif i == 1:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistmiddle.append(timedifference)
                        correctmiddle += 1
                    elif i == 2:
                        timecorrect = time.time()
                        timedifference = timecorrect - timedisplay
                        timelistright.append(timedifference)
                        correctright += 1

                # Counts when touch was outside of button
                elif distance_button.length() > button_radius:
                    x, y = pygame.mouse.get_pos()
                    if y <= (screen_height/3):
                        incorrectleft += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 201, timenow - time_start])
                    elif y <= 2*(screen_height/3):
                        incorrectmiddle += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 200, timenow - time_start])
                    elif y > 2*(screen_height/3):
                        incorrectright += 1
                        timenow = time.time()
                        writer.writerow([trialnum, 202, timenow - time_start])

        # Draws the button
        pygame.draw.circle(screen, white, button_positions[i], button_radius)
        pygame.display.update()

# Closing objects
data.close()
summary_contents = summary.read()
print(summary_contents)
summary.close()
#camera.stop_recording()
#camera.stop_preview()

This snippet here is the part that I am working on
 time_end = time.time() + ITI
    while time.time() < time_end:
        if pygame.mouse.get_pressed()[0]:
            if i == 0:
                writer.writerow([trialnum, 210, time.time() - time_start])
                time_end += 0.5
            elif i == 1:
                writer.writerow([trialnum, 211, time.time() - time_start])
                time_end += 0.5
            elif i == 2:
                writer.writerow([trialnum, 212, time.time() - time_start])
                time_end += 0.5

I have an interval in between when the button is pressed and the next one shows up. I am trying to get it to increase that interval if it senses the mouse is clicked. if the mouse is being held it will continuously add 0.5 seconds to the time until nothing is being pressed. Currently, the code is crashing once it gets to the while loop. I'm not sure why this is as all documentation i've seen says to use pygame.mouse.get_pressed()

I'm not familiar with pygame, but ... while time.time() < time_end:  ...  time.time() is unlikely to change within a single frame (at least not unless you're doing something that will intentionally hang the game).


text:
Cinemachine camera snaps on unpause
In Unity, I am using a Cinemachine Freelook Camera with the Cinemachine Input Provider component. This follows around my character and overall responds correctly to 2-axis camera control.
However, when unpausing (setting Time.timeScale to 1 after it has been 0), the orbital camera will for a frame massively multiply the input of the camera control. This means that if the y axis control was 1, the orbital y value will effectively snap to 1 (instead of smoothly gliding there as it normally would).
I have determined it is not a case of buffered input in the paused state - it only considers the input at the moment of unpausing but unfortunately amplifies it.
Is there anything I can do to prevent or at least counteract this effect?
Note: The Cinemachine Brain updates on Fixed Update, and is not set to ignore time scale.


text:
Why my game is rejected by Crazy Games?
I crated this game:
https://muhomorgames.itch.io/bean-legacy
I uploaded it on crazy games I hane no idea why it's been rejected can anyone help me?

The controls are totally off (tried with mouse, no idea if there are others), the screen is cluttered, the goal is not really clear, no tutorial or options. But what exactly is the reason for rejection, only crazy game can tell.


text:
How to set reference to a c# file using an exposed field from a scriptable object?
Can't wrap my head around this, In my game I have the following:
SpecificItem.CS - different items that have different programmed functions/methods into them.
SpecificItemDataContainer.CS - scriptable objects for every different specificItem stats.
I have around 50 to hundreds of SpecificItem along with their respective containers. And I would like to be able to get reference to the different SpecificItems script at runtime by adding them to their corresponding SpecificItemDataContainers.
Turns out I can't drag/reference objects C# files from the project window to a scriptable objects serialized field.
I've thought of just adding each and every into an every SpecificItem scripts into a empty game object and creating a prefab to reference the script from the prefab but thought of it as counter intuitive.
Thought of also adding a SpecificItem variable field in the data container template but that would require me to input all specific items  which doesn't seem right.
I wanted to avoid as much as possible using  strings/ or exact location path name for the SpecificItem. How would you go about this?

A type must inherit from UnityEngine.Object to be dragable "instance" in the inspector. I'm not sure I understand the relation between items and containers. What is the problem with an item being a field  in the container or to make items inherit from ScriptableObject and be dragable themselfs? Or both parts merged into one SO containing methods and data?


text:
PyOpenGL-Demo sample code -- exiting app doesn't work
I am using the cube.py sample from PyOpenGL-Demo, and there is this snippet there to handle the app exit when user presses the Esc key:
def keyboard(key, x, y):
    if key == chr(27):
        import sys
        sys.exit(0)

There are two issue, one is pretty easy to fix (replace chr(27) by b'\x1b') but the sys.exit(0) call does not seem to fully close the app and clean up -- the window is still visible for example and the Python that was launched is still running.
I tried importing pygame and using pygame.quit() but that did not fix it... any ideas appreciated.
thanks


text:
How to make action get triggered as long as key is held in Unity new input system
I'm using unity new input system for a local multiplayer game.
My PlayerInput sends messages to my CharacterInputListener on every character object, one of such messages is OnDefend().

I want defendRequest to be true as long as the button bound to the action is being held and false otherwise.

I am trying to use the hold interaction but it returns false the frame after the button is held for 0.01 seconds. How can I achieve the behaviour I want?


text:
Splitting texture atlas/spritesheet using text file with sprite regions
I have a spritesheet that I am going to use for a game, and since the spritesheet is irregular/not a uniform grid I also have a text file that has the data for each sprite: name, topX, topY, width, and height. (I used https://www.leshylabs.com/apps/sstool/ to create the spritesheet data).
My question is how can I split the spritesheet and export it into separate PNG files using the original spritesheet PNG and the text file with sprite data?

Would it not be simpler or more efficient to program your game to read this sprite atlas as a whole, and sample the regions from it that your sprites need?

@DMGregory It would be, if I were using a conventional programming language or game engine, however I am not and it is not possible for me to do that. (I am using the block-based coding language Scratch)

That's a good thing to include in your question then.


text:
ComputeShader.SetTexture() isn't writing to the shader
The C# script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class clod : MonoBehaviour{

    [ExecuteInEditMode]
    public ComputeShader compushad;
    public RenderTexture rendtex;

    void start(){
        rendtex = new RenderTexture(256, 256, 24);
        rendtex.enableRandomWrite = true;
        rendtex.Create();

        compushad.SetTexture(0, "Result", rendtex);
        compushad.Dispatch(0, rendtex.width / 8, rendtex.height / 8, 1);
    }
}

The compute shader script:
#pragma kernel CSMain

RWTexture2D<float4> Result;

[numthreads(8,8,1)]
void CSMain (uint3 id : SV_DispatchThreadID){
    Result[id.xy] = float4(id.x & id.y, (id.x & 15)/15.0, (id.y & 15)/15.0, 0.0);
}

From a Youtube video that I saw: "After hitting the play button, the RenderTexture can be previewed from the inspector window." I can't access the RenderTexture in the inspector window.


text:
How do I move a camera around a tiledmap in Libgdx?
I have the following code for rendering a TiledMap and moving around a Texture representing the player on top of it and the camera is setup to follow the texture around.
However, when I try to move the player which in turn moves the camera, it seems like the tilemap moves as well resulting in the player not moving at all. Here's a gif showing the problem:
I am not sure what I am doing wrong but I would appreciate if anyone could help me out.
package com.worldgen.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.utils.ScreenUtils;
import com.worldgen.map.WorldMap;

public class WorldGenGame extends ApplicationAdapter {
    private static final int MAP_WIDTH = 512;
    private static final int MAP_HEIGHT = 512;
    private static final int TILE_SIZE = 16;
    public final static float VP_WIDTH = 32;
    public final static float VP_HEIGHT = 18;

    private SpriteBatch batch;
    private OrthographicCamera camera;

    WorldMap worldMap;
    private TiledMapRenderer tiledMapRenderer;

    private Texture playerTexture;
    private Rectangle player;

    @Override
    public void create () {
        batch = new SpriteBatch();
        playerTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
        player = new Rectangle(0, 0, 1, 1);

        camera = new OrthographicCamera();
        camera.setToOrtho(false, VP_WIDTH, VP_HEIGHT);

        worldMap = new WorldMap(MAP_WIDTH, MAP_HEIGHT, TILE_SIZE, TILE_SIZE);
        tiledMapRenderer = new OrthogonalTiledMapRenderer(worldMap.getMap(), 1f/TILE_SIZE);
    }

    @Override
    public void render () {
        ScreenUtils.clear(0, 0, 0, 1, true);
        // Update
        float deltaTime = Gdx.graphics.getDeltaTime();
        updateCamera(deltaTime);
        updatePlayer(deltaTime);

        //Draw map
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();

        //Draw player
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(playerTexture, player.x, player.y, player.width, player.height);
        batch.end();
    }

    @Override
    public void dispose () {
        batch.dispose();
        worldMap.dispose();
        playerTexture.dispose();
    }

    private void updatePlayer(float deltaTime) {
        float movementAmount = 4 * deltaTime;
        if (Gdx.input.isKeyPressed(Input.Keys.A)) {
            player.x -= movementAmount;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.D)) {
            player.x += movementAmount;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.W)) {
            player.y += movementAmount;
        }
        if (Gdx.input.isKeyPressed(Input.Keys.S)) {
            player.y -= movementAmount;
        }
    }

    private void updateCamera(float deltaTime) {
        camera.position.set(player.getX(), player.getY(), 0);
        camera.update();
    }
}

I suspect the camera position update is where the problem lies because if I comment out the camera update code, I can move around the player on the tilemap.
    private void updateCamera(float deltaTime) {
//      camera.position.set(player.getX(), player.getY(), 0);
        camera.update();
    }

Result:


text:
Having trouble creating an unbound game using FXGL
I am trying to recreate a game like Splix.io using FXGL, I have implemented the logic of the game for one player and it works. And for my game window I am using a 800*800 window. My problem is my game should be "unbounded" which means that the player should be able to move till infinity if it desires it and I have been trying different stuff to make this happen but none of them work.
As you know Splix.io has a gird like board so to create this grid I created Light Gray cells of 20 pixels like this:
@Spawns("cell")
public Entity newCell(SpawnData data) {
    return FXGL.entityBuilder(data)
            .view(new Rectangle(BLOCK_SIZE,BLOCK_SIZE, Color.LIGHTGRAY))
            .with(new CellComponent())
            .build();
}

@Spawns("player")
public Entity newPlayer(SpawnData data) {
    return FXGL.entityBuilder(data)
            .view("steve.png")
            .zIndex(100)
            .build();
}

and this is how I initialize the game board at the start:
cells = new Entity[40][40];

player = spawn("player", 400, 400);
for (int y = 0; y < 40; y++) {
    for (int x = 0; x < 40; x++) {
        cells[x][y] = spawn("cell", x * BLOCK_SIZE, y * BLOCK_SIZE);
    }
}

Can someone tell me how I can make this fixed size game unbounded? One idea that I had was to check if the player comes close to any side of the window and if they get close I make the game window bigger and move the board but I don't know if this is the right way or not and even if it is, I don't know how to properly implement it.


text:
Rain particle system scale
I'm using a rain particle system and using cone a radius to scale it.
My question is what is the best way to make the rain particle covering the entire map?
And does increasing the rate over time affect performance? And is it necessary to increase it when increasing the radius?

Recommended reading: RPS article How Did They Do... Satellite Reign's Rain?. That aside, it's hard to give answers about performance without knowing more & most of those details will be discovered more effectively by you trying stuff & profiling your game than asking devs who've never seen your project. If you run into something more specific, someone might be able to help, but as is, there's not much to go off of here.

The larger the area of your particle system, the more particles you'll need to have alive in that volume at any given time for it to look appropriately dense/full.
Every one of those particles has a cost.
Each raindrop costs processing time to animate it each frame, bandwidth to upload its vertices for rendering, vertex shading time to transform it to the screen (even the ones off-screen need to be transformed to find out whether they could be on-screen), and rasterization, shading, and blending costs for the few that actually end up visible on screen.
You'll also pay a lot of overdraw this way. If you want to render a heavy sleet with dense sheets of rain out into the distance, drawing it one raindrop at a time means you end up drawing over the same pixels again and again, adding very little visible difference with each pass, and devouring your GPU's fill rate budget.
Instead, it's helpful to use a camera-centric approach. The player only sees raindrops near the camera, so let's only spend time simulating and drawing those ones
Have a small-ish particle system positioned nearby in front of the camera, and co-moving with it, so that it always fills the field of view. Simulate the particles in world space, so that you can still walk past them as they fall, rather than the rain seeming to stay glued to you as you move.
If your movement speed is fast, you may need to teleport trailing particles from behind you back in front of you to keep the density consistent - otherwise you can outrun the rain: the emitter hasn't had enough time to drop rain in the new region you've moved into. I had to do this to simulate space dust for a fast-moving spaceship, poking into the particle system's particle buffer to reposition them manually. Your raindrop shader can fade drops to transparent just before this repositioning distance, so the player never sees rain just pop in/out of existence this way.
You can render more distant rain with a second particle system farther out with a simpler shader, or a full-screen quad that uses an animated shader effect to imitate dense, distant rain with a single shading and blending pass, instead of transforming and layering thousands of individual raindrop meshes. This makes it easier to dial the weather all the way up to hurricane intensity where visibility drops off, without murdering your framerate. Instead it acts more like a textured screenspace fog, with roughly constant rendering cost regardless of droplet density or draw distance. It won't parallax exactly correctly, but that's what the nearby particle rain is for, to sell the illusion where the player can see it best.
Games will often use a similar screen-space effect to render very close raindrops / ones splashing on the camera itself (if having a "physical" camera is part of your game's aesthetic). Rendering close, medium, and far rain effects separately like this helps you focus each layer's effects on what looks best at that distance, so you don't pay for beautiful refractions that are only visible up-close when you're rendering "filler" sleet a city block away.
You can see in this Reddit post that Starfield uses this layered local particles trick: there's a sparse rain within a span of a few meters of the player, and a dense rain just around their head (where the game camera usually sits):


text:
Add private GitHub repository in Unity Package Manager
Is there any way available to use a private Git repository directly in a package manager?
Currently, I have made a package and hosted it on GitHub. Now, I want to use it directly from GitHub in Unity. However, this is not accessible, as I have to provide my credentials, but the package manager does not have any credential column.

Here is the first result I get when I search for "unity private github". It references this section of the official Unity documentation explaining how to provide these credentials. Have you tried the solution described there? What steps did you take and what were the results?


text:
How to avoid polygon fill in substance painter painting unselected polygons?
when using polygon fill in substance painter, it sometimes also paints different polygons that I havn't selected. (See image).
I am using the Polygon Fill on a black mask that is attached to a fill layer.


text:
"rigidbody property has been deprecated" when trying to save ScriptableObject to JSON with NewtonSoft
I am using NewtonSoft Json to save data in my Unity game, but when I try to save something it get this error:
NotSupportedException: rigidbody property has been deprecated (wrapper dynamic-method) UnityEngine.GameObject.Getrigidbody(object)

I am not sure what to do here, since I'm not even using rigidbodies in any of my scripts currently and no other variable is called rigidbody, so I am assuming that it is something related to Unity's built-in scripts.
The error message also says there is a GetRigidBody() function on GameObjects, which is probably the deprecated part.
Also I am not saving any GameObjects / MonoBehaviours directly, but I am saving a ScriptableObject, so maybe it is related to that?
Basically, I need something to save my ScriptableObject.

Is there a specific reason you're reaching for the NewtonSoft library in this case? I've just tested and Unity's built-in JsonUtility successfully converts ScriptableObjects to JSON and can populate a receiver ScriptableObject with data deserialized from JSON, without throwing any error like this.

I tried using the built-in JsonUtility, but it only saved the InstanceID and when I split it up into an extra class to save all values, it saved everything twice and with the wrong values for some reason (e. g. a bool declared as "false" is set to true in the save file without ever being set to true in code). After going through some forums I noticed that most people use NewtonSoft JSON instead of the built-in JsonUtility.

If you'd like help troubleshooting those issues with JsonUtility, I recommend posting a question about it, including a Minimal Complete Verifiable Example. I'd bet once we can reproduce the problem, we'll be able to find a way to solve it. The built-in utility doesn't just fail randomly - it does what the code we write asks it to do - so you might just need a hand writing code that expresses what you want from it accurately.

I'm sorry, but I probably didn't ask the question correctly, the reason why I am not using the built-in JsonUtility is that it seems to just store the InstanceID when using lists of ScriptableObjects which is what I'm doing, I assumed that it generally isn't working with ScriptableObjects. So I am using NewtonSoft because on other forums it was said to also work with lists of ScriptableObjects. Unfortunately, because of the error, I haven't had the chance to actually see if it would work with lists.

You don't need to repeat yourself. "I failed to make it work with JsonUtility" is a good reason to post a question saying "How to fix this code that uses JsonUtility". If "Switch to NewtonSoft" is the answer to that question, someone will post a solution that uses it. But I bet we can either find a solution for you that works with JsonUtility, or your approach is more fundamentally flawed and you need a redesign to work with either serialization library. The only way for us to find out is if you share the code needed to reproduce a representative example of the problems you're encountering.

Created a new post with the saving code new post

That looks like it should be an edit to this post instead, to avoid being closed as a duplicate.


text:
Problem with JSON ScriptableObject saving using NewtonSoft JSON
I am saving a list of ScriptableObjects in a JSON file using NewtonSoft JSON, the problem being that the following error message is thrown when it tries to save:
NotSupportedException: rigidbody property has been deprecated(wrapper dynamic-method) UnityEngine.GameObject.Getrigidbody(object)
My code for saving and loading:
private static readonly string SaveFileFolder = Application.persistentDataPath + "/Saves/";

    public static void Save(SaveData data)
    {
        if(Directory.Exists(SaveFileFolder) == false)
        {
            Directory.CreateDirectory(SaveFileFolder);
        }

        File.WriteAllText(SaveFileFolder + "Data.sav", JsonConvert.SerializeObject(data));
    }

    public static SaveData Load()
    {
        string _savePath = SaveFileFolder + "Data.sav";

        if(File.Exists(_savePath) == true)
        {
            return(JsonConvert.DeserializeObject<SaveData>(File.ReadAllText(_savePath)));
        }
        else
        {
            Debug.LogWarning("SaveFile could not be found in: " + _savePath);
        }
    }

    [System.Serializable]
    public class SaveData
    {
        [SerializeField] public GlobalGameStatistics.ProgressData ProgressData = new GlobalGameStatistics.ProgressData();
        [SerializeField] public GlobalGameStatistics.StatisticsData StatisticsData = new GlobalGameStatistics.StatisticsData();

        public SaveData(SaveData data)
        {
            ProgressData = data.ProgressData;
            StatisticsData = data.StatisticsData;
        }

        public SaveData(GlobalGameStatistics.ProgressData progress, GlobalGameStatistics.StatisticsData statistics)
        {
            ProgressData = progress;
            StatisticsData = statistics;
        }
    }

The ScriptableObject I'm trying to save:
[CreateAssetMenu(fileName="MissionTemplate", menuName="Game/Mission Template"), Serializable]
public class MissionTemplate : ScriptableObject
{
    [Header("Settings:")]
    public float time;
    public MapTemplate map;
    public PopulationTemplate population;
    public TargetTemplate target;
    public StoryMessage[] messages;

    #region Classes

    [Serializable]
    public class StoryMessage
    {
        [HorizontalGroup("Header")]
        public string headline;
        [HorizontalGroup("Header")]
        public string sender;
        [TextArea(8, 8)] public string text;
        [HideInInspector] public bool read;
    }

    #endregion
}

The GlobalGameStatistics.Progress class is where a list of MissionTemplates is contained which should be saved.

Questions about debugging a problem in your game should include a Minimal Complete Verifiable Example. That means a reader should be able to paste the code, and it should compile, run, and demonstrate the issue, without them needing to ask any follow-up questions or stub-in code you didn't provide. Right now this code depends on several types like MapTemplate, PopulationTemplate, etc. that you have not provided. You should slim this down to a synthetic example that shows the kinds of serialization operations you need to support without the full dependency complexity of your whole game.

I'd create a MissionTemplateData, put all the fields in that and serialze/deserialize that -- ScriptableObjects aren't going to work with JSON serialization.

Here's what I use (swap in JSON for binary serialization if you really must):
public static class DataStorage
{
    static readonly string Data_Extension = ".GameData";

    public static string Save<T>(T obj, string savePath, string key)
    {
        string path = Path.Combine(Application.persistentDataPath, savePath);
        Directory.CreateDirectory(path);
        path = Path.Combine(path, $"{key}{Data_Extension}");
        File.Delete(path);

        Debug.Log($"Saving: {path}");
        using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate)) // Overwrite
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, obj);
        }

        return path; // this is here for test automation and/or debugging help
    }

    public static T Load<T>(string savePath, string key)
    {
        string path = Path.Combine(Application.persistentDataPath, savePath, $"{key}{Data_Extension}");
        T loadObject = default;
        if (!File.Exists(path)) return loadObject;

        Debug.Log($"Loading: {path}");
        using (FileStream stream = new FileStream(path, FileMode.Open))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            loadObject = (T) formatter.Deserialize(stream);
        }

        return loadObject;
    }
}

The data and ScriptableObject:
public class GameStateData
{
    public GameSource GameSource;
    public States State;
    public Vector3Int PlayerMapLocation;
}

public class GameStateSO : ScriptableObject
{
    public GameStateData Data = new GameStateData();
}

Then I call it with:
DataStorage.Save(gameStateSO.Data, savePath, "GameStateSO");

gameStateSO.Data = DataStorage.Load<GameStateData>(savePath, "GameStateSO");

Careful, BinaryFormatter is insecure and can be used to execute arbitrary code. Microsoft says apps should stop using it. This might not seem like a big deal; your game might not have any sensitive/secret stuff in it. But if an attacker can convince one of your players to load a malicious save file ("want a save with 100% completion and the ultimate weapon unlocked? Here you go!") then they can potentially use this pathway to install malware on the player's computer, or leak your player's secrets.

I'd call that list of impacted versions kind of a big deal if they're calling it by design/won't fix. Ugh. Thanks for the heads-up!

Unfortunately, BinaryFormatter dates back to a time when deserialization vulnerabilities were not so well understood by the global community — it wasn't just an isolated mistake. And that flaw is baked into the design of the API. It's not "won't fix" so much as "cannot fix" — no code conforming to the same API will ever be safe. They've provided other (de)serialization tools to serve secure implementations, but it's sadly not a drop-in replacement.


text:
How can I clearly distinguish between tap and swipe inputs on mobile?
How can I clearly distinguish tapping and swiping touches?
This is my interaction script:
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;

/// /// <summary>
/// Calf and Finger Interaction Script
/// Raising likes, getting angry when you get upset, etc
/// /// </summary>

public class CowRelationManager : MonoBehaviour
{
    // implemented by dragging the event system
    //a better way than this
    //refactoring later if present
    [SerializeField]
    [Tooltip("variable to check how many times you poke")]
    private int CowClickCount = 0;

    [SerializeField]
    private float sweepThreshold = 50f; // Swipe threshold for touch detection
    [SerializeField]
    private float doubleTapTimeThreshold = 0.3f; // time threshold for detecting push with double touch

    TutorialSceneManager tutorialSceneManager;
    Animator CowAnimator;

    private void Start()
    {
        tutorialSceneManager = TutorialSceneManager.Instance;
        Debug.Log($"TutorialSceneManager is : {tutorialSceneManager.IsUnityNull()}");
        CowAnimator = tutorialSceneManager.cowScriptableObject.CowObject.GetComponent<Animator>();
        Debug.Log($"CowAnimator is : {CowAnimator.IsUnityNull()}");
    }

    private void Update()
    {
        // Touch input processing
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);

            Ray ray = Camera.main.ScreenPointToRay(touch.position);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.collider.gameObject.name == "Cow")
                {
                    //Implementing rubbing
                    //on-the-of-touch
                    if (touch.phase == TouchPhase.Began)
                    {
                        Debug.Log("start cow stroke");
                    }
                    /* /* if (touch.phase == TouchPhase.Ended && touch.deltaTime > 0.05f)
                    {
                    //Touch over
                    Debug.Log ("Done rubbing");
                    Debug.Log("You've gained popularity.");
                    }*/
                    else if (touch.phase == TouchPhase.Moved && touch.deltaTime > 0.05f)
                    {
                        CowAnimator.SetTrigger("CowJump");
                        Debug.Log("stroke end");
                        Debug.Log("relationship is increase.");
                    }

                    //when you just poke it once
                    else if (touch.phase == TouchPhase.Ended && touch.deltaTime < 0.05f)
                    {
                        if (CowClickCount < 5)
                        {
                            Debug.Log("bulling the cow");
                            CowClickCount++;
                        }
                        else
                        {
                            CowAnimator.SetTrigger("CowAngry");
                            Debug.Log("cow get mad!!");
                            CowClickCount = 0;
                        }
                    }
                }
            }
        }
    }
}

I want to make two different interactions with my game objects - one from a touch & the other from a swipe (rub, stroke, etc). For example, swipe the pet object to increase relationship versus repeatedly tap a cow to make it mad.
But in the code, I can't distinguish between the two different interaction types; they always act together.

Please note the tag guidance for unityscript: you have a script in Unity written in C#; that's not the same thing as the very old, unityscript which was a Javascript like language.


text:
What are the advantages of TWeakObjectPtr automatic nulling?
When you use TWeakObjectPtr to hold an Actor reference then the pointer variable is automatically nulled for you by GC when the Actor is destroyed. Is there any meaningful advantage of this?
If you use IsValid in your pointer validation then it doesnt matter if the pointer is nullptr or not when Actor is already destroyed.


text:
Finding highest point on displacement map returns bizarre results
I find the highest point of a displacement map sampled at 9 different UV coordinates that i pass in an array to the shader. Then if the result is more than 0.7 I output a red pixel at every UV coordinate in the array. If it is less than 0.7 I output a green pixel. So, you'd expect all the colors to be either red or green. But bizarrely they're red AND green.
uniform float4 _ArrayCoordinatesOfSplats[9];
float4 frag(v2f i) : SV_Target
{
float4 heightOfDisplacementMapAtOutputPixel = tex2D(_MainTex, i.uv);
bool brushTouchingOutputPixel = false;
float greatestHeightAtSpotLocations = -1;

for (int index = 0; index < 9; index++)
{
    half2 diff = _ArrayCoordinatesOfSplats[index].xy - i.uv;
    half2 scaledDiff = diff * half2(_SizeX, _SizeY);
    if (abs(scaledDiff.x) < 0.5 && abs(scaledDiff.y) < 0.5)
    {
        float heightOfDisplacementMapAtSplatPosition = tex2D(_MainTex, _ArrayCoordinatesOfSplats[index].xy).r;
        if (heightOfDisplacementMapAtSplatPosition > greatestHeightAtSpotLocations)
        {
            greatestHeightAtSpotLocations = heightOfDisplacementMapAtSplatPosition;
        }
        brushTouchingOutputPixel = true;
    }
}
if (brushTouchingOutputPixel)
{
    if (greatestHeightAtSpotLocations < 0.7f)
    {
        return float4(0, 1, 0, 1);
    }
    else
    {
        return float4(1, 0, 0, 1);
    }
}
else
{
    return heightOfDisplacementMapAtOutputPixel;
}
}
```


text:
Where are the docs and api reference for Python's Bullet-for-Ursina lib?
Where can I find the docs the and api reference for Bullet-for-Ursina?
I already searched things similar to "Python Bullet for Ursina docs" but with no success.

Since there is not much activity on that Github project, the last update more than one year ago, the chance is high that there is no documentation. Your best bet would be to contact the author over the email in the git account


text:
Xcode gives plenty of Undefined Symbol: Firebase_App error
I Build my Unity project to Xcode, trying to install it on ios device. It gives errors like as follow
> Undefined symbol: _Firebase_App_CSharp_FirebaseApp_GetApps
>
> Undefined symbol:
> _Firebase_App_CSharp_FirebaseApp_RegisterLibrariesInternal
>
> Undefined symbol:
> _Firebase_Auth_CSharp_AuthResult_AdditionalUserInfoInternal_get
>
> Undefined symbol:
> _Firebase_Auth_CSharp_AuthResult_CredentialInternal_get
>
> Undefined symbol: _Firebase_Auth_CSharp_AuthResult_UserInternal_get
>
> Undefined symbol: _Firebase_Auth_CSharp_AuthResult_UserInternal_set
>
> Undefined symbol:
> _Firebase_Auth_CSharp_FirebaseAuth_CreateUserWithEmailAndPasswordInternalAsync
>
> Undefined symbol:
> _Firebase_Auth_CSharp_FirebaseAuth_CreateUserWithEmailAndPasswordInternalAsync_DEPRECATED
>
> Undefined symbol:
> _Firebase_Auth_CSharp_FirebaseAuth_SignInAndRetrieveDataWithCredentialInternalAsync

totally gives 69 error like this.
I tried to add GameKit.framework, but still continue.
XCode version is: 14.3.1 (14E300c)
Firebase pod versions: 10.12.0, also I tried with 10.11.0 and 10.10.0
minimum ios version is:12.0
Unity Version is: 2021.3.16.
Firebase Unity SDK is: 11.1.0
and my podfile:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'

target 'UnityFramework' do
  pod 'FBSDKCoreKit', '~> 16.0'
  pod 'FBSDKCoreKit_Basics', '~> 16.0'
  pod 'FBSDKGamingServicesKit', '~> 16.0'
  pod 'FBSDKLoginKit', '~> 16.0'
  pod 'FBSDKShareKit', '~> 16.0'
  pod 'FirebaseAuth', '10.11.0'
  pod 'FirebaseCore', '10.11.0'
  pod 'FirebaseDatabase', '10.11.0'
  pod 'FirebaseStorage', '10.11.0'
end
target 'Unity-iPhone' do
end
use_frameworks!

Can anyone assist me on this.


text:
Cubemap rotation
I have a skybox with stars cubemap
So, how can I rotate stars cubemap on Z axis using "Rotate About Axis"?

It's not clear to me what rotation you're describing. Consider adding a diagram to your question to illustrate?

What is incomprehensible in the rotation of Skybox?!!!!!

A skybox has as many degrees of rotational freedom as any other object. If you're trying to simulate motion of stars as observed from the north pole, you'd rotate around one axis. If your observer is at the equator, you'd use a different rotation axis. If you want to simulate an observer at an arbitrary latitude, you'd use another axis yet. It also depends on how the contents of your skybox texture are set up. (eg. is Polaris in the center of the y+ face, or is your skybox oriented relative to the ecliptic plane instead?) This is why a diagram helps make your situation unambiguous.

I want to simulate motion of stats. But how can I simulate the axis by float like set the float 90° to make it rotate to right?

And thanks for the explanation

To whose right? What axis are we rotating around?

around the Y axis

So what is the reference to "when it is zero it rotates to the left on the z axis" in your question, if it is only ever a y-axis rotation you want? Try editing to clarify.

Here is a simple skybox shader graph that allows you to rotate a cubemap about the y axis by an angle you provide in degrees:

The Axis = (0, 1, 0) is what makes it rotate around the y axis. You can change this to a different axis, or even chain two of these nodes if you'd like to combine rotation due to time of day with rotation due to the observer's latitude.

Thank you, I have done this before, but this is not what I wanted, but I will implement it until I find out the way I want it.

This is why I wrote comments asking you to clarify what you wanted. The more specific you can be, the better your chances of getting an answer that delivers what you really want. Try explaining, in detail and with diagrams or screenshots, how the behaviour you observe with this graph differs from what you want.

After trying I think I will let it like that

But I'm still facing the problem of consistency of the cubemap with moon shape

If this answer solved your problem with rotating a cubemap, you can click the checkmark icon in the top left to mark it as Accepted. If it did not, you'll need to edit your question to clarify. You have a separate question about the moon, so we will not address that here.

Thank you it worked


text:
Source of truth for raising events in an Event-driven architecture?
I am developing a turn-based strategy game and am using Events to implement a "Buff" / "Debuff" system. The code is very OOP-y right now, not very ECS.
I am adding an event system similar to the one described here: https://gameprogrammingpatterns.com/event-queue.html.
The motivation is if a unit is damaged, there could be some condition called "OnDamage" that maybe triggers an AoE ability around them.
The problem is I am not sure what the source of truth for where the event should be raised should be.
I have a class:
class Unit
{
    int hp;

    ...

    void UpdateHp(...)
    {
         // clamp HP above 0, calculate shields, etc.
    }
}

class State
{
    ...

    map<string, coordinate> unitLocations;

    func updateUnitLocation(unitId, newLoc)
    {
        unitLocations[iconId] = newLoc;
    }

    ...
}

We also have this concept of Modifiers which are functions that change State. An example is a DamageModifier which takes in the State and calculates some Damage, then calls UpdateHp(...) on that unit.
Example modifier:
void Execute(State state, EventManager em, Unit initiatorUnit, List<Unit> targetUnits)
{
    long totalDamage = 0;
    foreach (var unit in targets)
    {
        int oldHealth = target.GetHp();
        int damage = CalculateDamage(initiator, defender); // based on some stats
        int newHealth = oldHp - damage;
        target.UpdateHp(newHealth);
    }
}

My question is where are events generally raised? If a Unit moves I thought I would raise the event from UpdateLocation, but we could also do it in the MoveModifier. With the former there is a single source of the event. All modifiers that do movement must go through that function. We have multiple "modifiers" now that need to raise the MoveEvent, such as a DisplacementModifier, MoveModifier.
For Damage, we could raise the DamageEvent from the Unit class. The problem is the Unit class now takes a dependency on the EventManager. I think that might be OK to make sure there's a single source of truth for all of those. We also have 2-3 DamageModifiers, one that does flat damage, one that calculates it based on stats.
Former:
class Unit
{
    int hp;

    ...

    void UpdateHp(..., EventManager em)
    {
         // clamp HP above 0, calculate shields, etc.
         em.Raise(new DamageEvent(...));
    }
}

class State
{
    ...

    map<string, coordinate> unitLocations;

    func updateUnitLocation(unitId, newLoc, EventManager em)
    {
        unitLocations[iconId] = newLoc;
        em.Raise(new MoveEvent(...));
    }

    ...
}

Latter:
func void Execute(State state, EventManager em, Unit initiatorUnit, List<Unit> targetUnits)
{
    long totalDamage = 0;
    foreach (var unit in targets)
    {
        int oldHealth = target.GetHp();
        int damage = CalculateDamage(initiator, defender); // based on some stats
        int newHealth = oldHp - damage;
        target.UpdateHp(newHealth);

        em.Raise(new DamageEvent(...)); // processed later
    }
}

On the flip side, these "modifiers" seem like the "systems" in ECS. In the ECS world as I understand it, the events are generally raised in the systems and its ok if the same event is raised in multiple systems. For instance, fall damage in a physics system, or damage from a combat/ability system, or damage from a fatigue system.
The main difference I see is the modifier way makes it the caller's responsibility to raise the event, and that seems dangerous but potentially more flexible.
Also interested in any resources on ECS. I can't find anything that goes deep with example systems, just surface level things.


text:
Make moon using cubemap in shadergraph
I'm trying to make moon with a cubemap texture in shadergraph.
I made it, but the texture is incorrect.
I'm using a cubemap from NASA as a texture and it works, but it's bigger than moon shape and thee larger I make the radius, the more of the texture appears.
I want to fit the cubemap within the moon shape.
Shader graph:

The problem with this shader graph is that you're sampling the moon's surface cubemap with your view direction vector (the green vector on the left). What you want is the red vector on the right.

We can get that vector with a little trigonometry. I'll spare you the full derivation and just jump straight to the shader graph code that implements it:

In this first section, we transform the view vector into a coordinate space where z+ is the "to moon" direction. (You can rotate the mesh this shader is being rendered on to change where the moon sits in the sky, or replace this with your own preferred coordinate transformation)
We then break down that vector into components that get us the trig ratios we need for angle \$a\$ in the diagram above, and use that to get some trig ratios for angle \$c\$.

Then we do some math on those to get the tangent ratio of angle \$b\$, and use that to construct a vector in the moon surface direction. That's the vector we'll use to sample the moon cubemap. You can also normalize it to get a surface normal vector for lighting calculations, like rendering the phases of the moon.
(By default, this setup will give you a moon that's tidally locked: the same side always points toward the viewer. If you don't want this, you can rotate the moon surface direction vector before passing it to the Sample Cubemap node)

Of course, all this math is only valid for view rays that actually hit the moon. For pixels outside that narrow cone, we want to skip as much of that calculation as we can and just draw stars, then do a light feathered blend between the two. Here are the nodes that do that:

As you can see, this lets you control the size of the moon in the sky, and the moon's features scale with the moon - when the moon gets smaller, it doesn't crop the surface texture, it shrinks the whole thing together.

Yes, you are right. I applied wrongly and corrected it, but I noticed a difference in the scale of the moon I use moon radius= minimum 0 and maximum 2.5 and you used distance so how can I control the scale with radius?

You can replace the node that multiplies Sine(a) by MoonDistance with a node that divides Sine(a) by MoonRadius. The floating point division is slightly more expensive than the multiplication, so that's why I chose to parametrize this shader in terms of distance instead, but it's a trivial change if you prefer to tune it in terms of radius. The radius units will then be measured in orbital radii. If you know the angular radius you want, you can take the tangent ratio of that angle and use it as the radius parameter. (You can do that tan() in the shader, but again, more expensive).


text:
How to fix the flag bool variable become null and never stop the coroutine?
The script is attached to some objects and in another script when checking distance, I'm starting the blinking and then should stop the blinking. but it's never got inside the stop method because the variable blinkCoroutine is null.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlinkingObject : MonoBehaviour
{
    public float blinkInterval = 0.5f;
    public Color blinkColor = Color.red;

    private Renderer[] blinkRenderers = null;
    private Color[][] originalColors = null;
    private Coroutine blinkCoroutine = null;

    private void Start()
    {
        CollectRenderers(transform, ref blinkRenderers); // Get all renderers in children and store them in blinkRenderers
        CopyOriginalColors(); // Copy the original colors of the materials of the blinkRenderers
    }

    private void CollectRenderers(Transform parent, ref Renderer[] renderers)
    {
        // Collect renderers in children
        List<Renderer> rendererList = new List<Renderer>();
        CollectRenderersRecursive(parent, rendererList);
        renderers = rendererList.ToArray();
    }

    private void CollectRenderersRecursive(Transform parent, List<Renderer> renderers)
    {
        // Recursive function to collect renderers in children
        foreach (Transform child in parent)
        {
            Renderer renderer = child.GetComponent<Renderer>();
            if (renderer != null)
            {
                renderers.Add(renderer);
            }

            CollectRenderersRecursive(child, renderers);
        }
    }

    private void CopyOriginalColors()
    {
        // Copy the original colors of the materials of the blinkRenderers
        originalColors = new Color[blinkRenderers.Length][];
        for (int i = 0; i < blinkRenderers.Length; i++)
        {
            Material[] materials = blinkRenderers[i].materials;
            originalColors[i] = new Color[materials.Length];
            for (int j = 0; j < materials.Length; j++)
            {
                originalColors[i][j] = materials[j].color;
            }
        }
    }

    private IEnumerator BlinkCoroutine()
    {
        // Blink the materials of the children of the object together
        while (true)
        {
            SetColor(blinkColor);
            yield return new WaitForSeconds(blinkInterval / 2f);
            SetOriginalColors();
            yield return new WaitForSeconds(blinkInterval / 2f);
        }
    }

    private void SetColor(Color color)
    {
        // Set the color of all materials in blinkRenderers to color
        for (int i = 0; i < blinkRenderers.Length; i++)
        {
            Material[] materials = blinkRenderers[i].materials;
            for (int j = 0; j < materials.Length; j++)
            {
                materials[j].color = color;
            }
            blinkRenderers[i].materials = materials;
        }
    }

    private void SetOriginalColors()
    {
        // Set the color of all materials in blinkRenderers to their original colors
        for (int i = 0; i < blinkRenderers.Length; i++)
        {
            Material[] materials = blinkRenderers[i].materials;
            for (int j = 0; j < materials.Length; j++)
            {
                materials[j].color = originalColors[i][j];
            }
            blinkRenderers[i].materials = materials;
        }
    }

    public void StartBlinking()
    {
        if (blinkCoroutine == null)
        {
            blinkCoroutine = StartCoroutine(BlinkCoroutine());
        }
    }

    public void StopBlinking()
    {
        if (blinkCoroutine != null)
        {
            StopCoroutine(blinkCoroutine);
            blinkCoroutine = null;
            SetOriginalColors();
        }
    }
}

and using it in another script:
if (distanceToWaypoint <= distanceThreshold)
            {
                waypoints[currentWaypoint].GetComponent<BlinkingObject>().StartBlinking();
            }
            else
            {
                waypoints[currentWaypoint].GetComponent<BlinkingObject>().StopBlinking();
            }

I tried to debug and it's getting inside the method StopBlinking in the BlinkingObject script but the variable blinkCoroutine is null even if it's first starting the blinking in the method StartBlinking and I checked when it's getting inside the StartBlinking after doing this line:
blinkCoroutine = StartCoroutine(BlinkCoroutine());

the variable blinkCoroutine is not null but it become null when it's trying to stop in the StopBlinking method.
how to fix it?

Variables in C# do not suddenly become null without code setting them to null - even a destroyed GameObject or MonoBehaviour still exists as long as any variable references it - it cannot be claimed by the garbage collector until every reference to it goes out of scope. I expect your problem here is that you're calling StartBlinking() on waypoints[0] and then calling StopBlinking() on waypoints[1] - some other code changed which waypoint you were talking to between the start and stop, and the new waypoint never started blinking. Try printing the waypoint ID in each place you call these


text:
Shadow squares on meshes

I had created project on r3f (React THREE Fiber), and after "blocking" when I decided to add high resolution models, I noticed this shadow issue.
Help me to understand, how can I fix the shadow stairs on my models?
I had tried some of the variants, I had exported model with and without smooth shading and auto-smoothing on normals.
So I decided to look on Directional light or Point light and tried to handle them.
But it gave me nothing like increasing shadow map size.
But one thing I knew, the light is the reason why my models show this buf with the shadows.
On this site I have a good results, without shadow stairs etc.
When we have  light angle of 90° relative to the model's surface, everything looks fine. But if we have a sharper angle, we will have shadow stairs.


text:
Implementing Camera Movement and Rotation in 3D Game Engine
Apologies in advance for any mistakes on terminology, I'm really really new to this
I'm completely new to 3d (and it's maths) but as a personal exercise I'm doing my own game engine that displays a simple wireframe.
I've implemented rotate (x, y and z), orthogonal, isometric, perspective projection matrices (column major) and a look_at function.
I've got a list of points and my rudimentary pipeline (on keypress) is as follows:

get original points
scale
rotate_x
rotate_y
rotate_z
look_at(cam,target,up)
projection
translate to centre of the window
It works fine with hardcoded camera and target coordinates

However I want to be able to:

move the camera up/down/left/right in the same plane I'm currently at.
To be able to rotate that plane around the z axis
and to bring the plane the camera is closer or farther from the z axis
But I have no Idea how to do that.

The reason I want to rotate around the z axis and not the y is because I haven't implemented any coordinate system and the hardcoded camera and target values are for an isometric projection.
How can I do this?


text:
Using Render Doc with Maya
I am creating a plug-in that utilizes OpenGL to render to a seperate device however the plugin is only showing a black screen I suspect due to an OpenGL error. However, when I try and attach Render doc to the process, I am unable to get any data out.
I am unable to start maya with render doc as it stops at what appears to be asking for licensing and quits. If I inject into the process after maya is started I can get a connection however the API always says none and no data is transmitted.
I have tried a few of the common tools listed when searching for tools like render doc and they all seem to have build or run issues.
Is there some other common tool for debugging an open gl application in maya ? or Has anyone successfully used Render Doc with Maya?


text:
MediaPlayer looping video freezes after 1st or 2nd loop
I am trying to make a VHS effect for my game in UE5, using a looping MP4 video for the user interface. The video just freezes after the 1st or 2nd loop during test in viewport.

I tried to set different scalability groups or load different videos, but the problem persists.
How can I make this video loop endlessly with no freezing?


text:
WHY doesn't Python's Ursina module load textures from .mtl file?
Why doesn't the Ursina module directly load all textures from an obj's mtl file?
Let's assume I have 4 files:
test.py:
from ursina import *
app = Ursina()
e = Entity(model="test.obj")
EditorCamera()
app.run()

test.obj:
mtllib test.mtl
o Plane
v -1 0 1
v 1 0 1
v -1 0 -1
v 1 0 -1
vt 0 0
vt 1 0
vt 1 1
vt 0 1
vn 0 1 0
usemtl test
s off
f 1/1/1 2/2/1 4/3/1 3/4/1

test.mtl:
newmtl test
Kd 1 1 1
map_Kd texture.png

texture.png:

If I run the .obj file in a 3D viewer, it loads the texture, but WHY doesn't Ursina do the same but just ignores all map_* and refl commands in the mtl file?
I want to know WHY Ursina ignores those texture commands, not how to fix it.

You'll need to ask the developers. We have no insight into their design decisions.


text:
Ursina not applying shader and light to entity
I'm making a terrain-based game in Ursina. I finished making the terrain and the texture, and all of them run well, but Ursina is having problems with the lights and the shaders.
from ursina import *
from ursina.shaders import lit_with_shadows_shader as lwss
app = Ursina()
window.borderless = False
t = Entity(model="Terrain.obj",texture="Terrain.png",collider="mesh",shader=lwss); t.texture.filtering = "mipmap"
p = EditorCamera()
l = Light(shadows=True,position=(1000,256,0))
app.run()

I tried all types of Light() (PointLight(), SpotLight(), etc.) and also adding the Light class into a list and multiplying it with 100, but none of them worked. What am I doing wrong? I want the terrain to have shadows and have (nearly) realistic lighting (parts on sides not hit by the light rays should be darker)
Note: The texture works, it looks like one color just because I screenshotted from big distance.


text:
How to start particle from skybox
I'm trying to create a lightning particle system but I want to make the top of the particles at the skybox and the bottom on the ground.
Is this possible?

Yes. But thunder is more of a hear thing than a see thing. If you mean lightning, how could a player notice the difference from an up to down strike compared to skybox to earth strike? What kind of camera do you have, what kind of view is the player having? Is it 2D or 3D?

No, this is not possible, because the skybox isn't an actual 3d box with well-defined vertex coordinates. Geometrically-speaking, its distance from the camera is undefined. If you wanted to place a 3d game object on the skybox, it would need to have an infinite distance from the camera.
All you can do is make the starting point of the lightning bolt high enough that the player can not tell the difference.

I will try to make it high enough.


text:
Make night sky with moon
I want to make skybox with moon (texture 2d) with shader graph and be able to modify moon radius.
Moon Texture 2d :

When you haven't accepted previous answers where volunteers here have put in work to help you (or up-voted them, once you've earned the rep to do so), it can dampen their enthusiasm to spend their time helping you further.

I did not accept it because it did not help me completely. If it helped me, I would not have needed to write another question. Note in the question that I wrote instead of a cubemap.

That's not how things work here. It's normal to accept an answer when it correctly answers the question that was asked, even if you later find your game needs something different than was asked. This does a few useful things: 1) it signals to the question filtering system that the old question is resolved, so it does not keep re-circulating to the top of the question feed for new input, 2) it rewards users who take the time to offer help, incentivizing them to keep coming to the site and keep helping you or other users, 3) it signals to future readers which solutions have been verified.

Ok I will do that.

Which is better for cubemap or texture2d performance?

If you only need one side, a texture is cheaper on memory and sampling math.

I noticed that in both of your moon shader questions, you're asking for very specific things. That's great if you know exactly what you need, but there's also benefit in including your high level outcomes to avoid XY problems. Editing to include info about what your end goal is & why/how the cubemap solution failed to meet that goal increases the chance that you'll get a solution that helps you solve your actual problem.

It did not fail, but I found that there was no need for it, as I would not benefit from it, so I decided to use a texture2d

Here's a shader that does this (click for a larger version so you can read the text):

And the result in a Unity scene:

The strategy is similar to my previous answer with the cubemap. We'll use the object space view vector (the vector pointing from the fragment being shaded back at the camera, in the object's local space) to make it easy to control the positioning and twist of the moon image: you can rotate the skybox itself. The moon will get drawn wherever the object's local z+ axis (blue arrow on the local translation gizmo) points, extended to infinity. You can use a world space view vector to sample the starfield if you want to angle the two independently.
We use the X and Y components of the view vector as texture coordinates to look up into our moon texture. First, dividing them by our desired moon radius (so at the desired radius, the length of the XY vector becomes 1), then multiplying them by a half and adding a half to bring them into the 0-1 texture coordinate range. I also negate them in this step, because otherwise we'd draw the moon rotated 180 degrees.
I also put a conditional branch in here so we only sample the moon texture when it will contribute to the image, and skip that work for the majority of the sky.

@AhmedDyaa, may I ask why you removed the accept checkmark on this answer and the previous? If there's something about the answer that needs to be improved, please provide details in a comment or by editing your question.

How can I implement it with my used shader that I send it's picture?

Because it didn't work for me. I think I did something wrong.

I need to see what you did to try to incorporate this answer before I can help you fix it. I also need to know what specific symptoms of "not working" you observed.

I modified the question and added your solution.

A lesson in communication: the issue here is NOT that "this shader for drawing the moon does not work". The issue is "I have another part of my shader that draws a glowing halo around the moon, and it does not draw that halo in the same position as the moon texture". Note that this was not part of the text of your original question. To ensure you get help that accurately meets your needs, make sure you explicitly state ALL of those requirements in the text of your question from the beginning. This helps avoid days of back-and-forth miscommunications and wasted time.

The halo is not related to the body of the moon and has no effect on it. It follows the moon only through the moon dir, so I did not mention it.

If you want them both to be drawn in the same place, then it's related, and MUST be mentioned. You're not going to get agreement between these two things by coincidence: you have to ask for it and arrange for it to happen specifically.

No, The halo is completely independent of the Moon, except for its position. And I only need to draw moon shape (circle in the centre of halo)

"except for" means it's NOT independent. The position calculation needs to be consistent between the two. You've used my position calculation for the moon texture, then used a completely unrelated position calculation for the halo, so they're obviously not going to match in general. You need to use the same direction information for both. If you'd like to know how to do that, make sure you ask "how do I align this halo with the position where the moon is drawn?"

I'm using the same direction information for moon shape and it's halo by "Moon Direction"  you will find that in "Moon shader after add moon texture node" image in the question, and your texture use view vector so how do I align your texture with moon Direction and dot product?

You don't. One vector isn't enough information to control both where the moon is drawn and its twist (which way the 'top' of the texture points) — that's why I use the rotation of the skybox for that purpose. Again, edit your question to ask "how can I align this halo with the moon" and I can show you how to correct the halo to match.


text:
Scene transitions to Game on host, but not on player client
I've been following Mirror tutorials on Youtube, where there was a transition between a lobby scene and a game scene, I wanted to add a loading scene inbetween them. The issue is the game transitions only on host but not on player. So the host gets into the game scene while player stays in the loading scene. Tested out this behaviour on builds and in editor, only host can access the game. I transition through a button with command:
NetworkRoomPlayerLobby.cs:
    [Command]
    public void CmdStartGame()
    {
        if (Room.RoomPlayers[0].connectionToClient != connectionToClient) { return; }

        Room.StartTransitionScene();
    }

then it  gets into the NetworkManagerLobby script and transitions the scene there:
NetworkManagerLobby.cs:
    public void StartTransitionScene() //sets scene to loading scene
    {
        if(SceneManager.GetActiveScene().path == menuScene)
        {
            if (!IsReadyToStart()) { return; }

            ServerChangeScene("Loading");
        }

        StartGame();
    }

    public override void ServerChangeScene(string newSceneName)
    {
        if(SceneManager.GetActiveScene().path == loadingScene && newSceneName.StartsWith("Game"))
        {
            for (int i = RoomPlayers.Count - 1; i >= 0; i--) //converts room players to game players
            {
                var conn = RoomPlayers[i].connectionToClient;
                var gameplayerInstance = Instantiate(gamePlayerPrefab);
                gameplayerInstance.SetDisplayName(RoomPlayers[i].DisplayName);

                NetworkServer.Destroy(conn.identity.gameObject);

                NetworkServer.ReplacePlayerForConnection(conn, gameplayerInstance.gameObject);
            }
        }
        base.ServerChangeScene(newSceneName);
    }

    public void StartGame()
    {
        ServerChangeScene("Game"); //change the scene to game scene
    }

The gameplayerInstances are not found in the Game scene. Could that be correlated?
Added a method for starting the game,I have two things on my mind that are causing the issues and I boiled them down to this:

The override method checks the condition before the scene is loaded hence issues with the game scene
Durring the transition(Lobby => Loading => Game) there is potential object destruction