# Question
Title: Run Simple HLSL Pixel Shader with DirectX 9
I'm trying to run HLSL Pixel Shaders with DirectX 9 where I feed a texture in, run the HLSL code and copy the resulting texture back from memory. I think I'm getting pretty close, although a LOT of time could be wasted trying to figure out the details. It's kind of pointless to study the whole DirectX SDK just for doing this basic task; I just want to get it done. Could you take a look at this code, give pointers as to what's missing, and answer a few questions?

Fist here are my questions, then followed by the code I have so far

1. Am I on the right track?
2. Am I better to pre-compile the shaders with fxc.exe or compile them on-the-fly? If I pre-compile, how do I load a pre-compiled shader?
3. In Diff.hlsl shader below, certain data are defined with "register" (sampler s0 : register(s0);) What are those and how do I configure them?
4. Can HLSL shaders alter the size of the texture? If so, how do I get the size back to parse the texture data accordingly?
5. How do I configure the parameters and run the shader?
6. Will I run into performance issues running this code? It gets called to process a video with AviSynth, where GetFrame gets called for each video frame. 8 instances will run on 8 parallel threads.
7. Anything else I should know?

I'm copying the texture data back and forth between AviSynth and the shader texture. The only difference in the memory structure is that AviSynth has a padding to the right of each line which has to be removed when copying to the shader and added back when copying back to AviSynth.

Here are some of the shaders I'm trying to run

https://github.com/zachsaw/MPDN\_Extensions/blob/master/Extensions/RenderScripts/SuperRes/Diff.hlsl

https://github.com/zachsaw/MPDN\_Extensions/blob/master/Extensions/RenderScripts/SuperRes/SuperResEx.hlsl

Here's my code: Shader.cpp

```
#include "Shader.h"

Shader::Shader(PClip _child, IScriptEnvironment* env) :
GenericVideoFilter(_child) {
    if (vi.IsPlanar() || !vi.IsRGB32())
        env->ThrowError("Source must be float-precision RGB");

    InitDirectX(env);
}

void Shader::InitDirectX(IScriptEnvironment* env) {
    dx = Direct3DCreate9(D3D_SDK_VERSION);

    // Initialize DirectX9
    D3DDISPLAYMODE dxMode;
    dx->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &dxMode);
    D3DPRESENT_PARAMETERS dxSettings;
    ZeroMemory(&dxSettings, sizeof(dxSettings));
    dxSettings.Windowed = TRUE;
    dxSettings.SwapEffect = D3DSWAPEFFECT_DISCARD;
    dxSettings.BackBufferFormat = dxMode.Format;
    dxSettings.EnableAutoDepthStencil = TRUE;
    dxSettings.AutoDepthStencilFormat = D3DFMT_D16;
    dxSettings.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
    dx->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_NULLREF, NULL, NULL, &dxSettings, &dxDevice);

    // Create pixel shader
    LPD3DXBUFFER dxShaderCode;
    LPD3DXBUFFER errors = NULL;
    if (FAILED(D3DXCompileShaderFromFile("F:\AVSMeter\MPDN_Extensions-master\Extensions\RenderScripts\SuperRes\Diff.hlsl", NULL, NULL, "main", "ps_3_0", 0, &dxShaderCode, &errors, &dxShaderConstantTable))) {
        env->ThrowError((const char*)errors->GetBufferPointer());
        errors->Release();
    }
    dxDevice->CreatePixelShader((DWORD*)dxShaderCode->GetBufferPointer(), &dxShader);
    dxShaderCode->Release();
}

Shader::~Shader() {
    if (dxDevice != NULL) {
        dxDevice->Release();
        dxDevice = NULL;
    }
    if (dx != NULL) {
        dx->Release();
        dx = NULL;
    }
    if (dxShader != NULL) {
        dxShader->Release();
        dxShader = NULL;
    }
    if (dxShaderConstantTable != NULL) {
        dxShaderConstantTable->Release();
        dxShaderConstantTable = NULL;
    }
}

PVideoFrame __stdcall Shader::GetFrame(int n, IScriptEnvironment* env) {
    PVideoFrame src = child->GetFrame(n, env);

    // Copy data to texture buffer
    unsigned char* textureBuffer = (unsigned char*)malloc(vi.width * vi.height * 16);
    CopyToTexture(src->GetReadPtr(), src->GetPitch(), textureBuffer);

    // Create texture
    LPDIRECT3DTEXTURE9 dxTexture = NULL;
    HANDLE* dxTextureHandle = (HANDLE*)textureBuffer;
    dxDevice->CreateTexture(vi.width, vi.height, 1, 0, D3DFMT_A32B32G32R32F, D3DPOOL_SYSTEMMEM, &dxTexture, dxTextureHandle);

    // Run shader on texture
    dxDevice->SetTexture(0, dxTexture);
    dxDevice->SetPixelShader(dxShader);

    // Copy data back to frame
    CopyFromTexture(textureBuffer, src->GetWritePtr(), src->GetPitch());

    // Release texture
    dxTexture->Release();
    dxTexture = NULL;
    free(textureBuffer);
    return src;
}

void Shader::CopyToTexture(const byte* src, int srcPitch, unsigned char* dst) {
    for (int i = 0; i < vi.height; i++) {
        memcpy(dst, src, vi.width * pixelSize);
        src += srcPitch;
        dst += vi.width * pixelSize;
    }
}

void Shader::CopyFromTexture(const byte* src, unsigned char* dst, int dstPitch) {
    for (int i = 0; i < vi.height; i++) {
        memcpy(dst, src, vi.width * pixelSize);
        src += vi.width * pixelSize;
        dst += dstPitch;
    }
}

```

Shader.h

```
#include <windows.h>
#include <d3d9.h>
#include <d3dx9.h>
#include <cstdio>       //needed by OutputDebugString()
#include "avisynth.h"   //version 5, AviSynth 2.6 +

class Shader : public GenericVideoFilter {
public:
    Shader(PClip _child, IScriptEnvironment* env);
    ~Shader();
    PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env);
private:
    void InitDirectX(IScriptEnvironment* env);
    void Shader::CopyToTexture(const byte*, int srcPitch, unsigned char* dst);
    void Shader::CopyFromTexture(const byte* src, unsigned char* dst, int dstPitch);
    LPDIRECT3D9 dx = NULL;
    LPDIRECT3DDEVICE9 dxDevice = NULL;
    LPDIRECT3DPIXELSHADER9 dxShader = NULL;
    LPD3DXCONSTANTTABLE dxShaderConstantTable = NULL;
    const int precision = 4;
    const int pixelSize = 16;
};

```

# Answer
> 1 votes
Since this question has been viewed 1000 times, I might as well post a follow-up.

This is the code I ended up with, processing Avisynth video scripts through pixel shaders. https://github.com/mysteryx93/avisynthshader

2. I'm precompiling shaders because some shaders (Bicubic.hlsl) take a long time to compile, and you get all the errors at compile-time.
3. If I remember correctly, shader output size is set to the size of the output texture we're rendering to.
4. The performance bottleneck is in transfering GPU memory back to the CPU, as graphic cards are not designed for that. I got best performance by lining up all the shaders into a processing chain, and transfer only the result after processing them all at once. I'm also getting best performance by running 8 threads on 2 DirectX engines.

---
Tags: c++, shaders, directx, hlsl, directx9
---


# Question
Title: I don't understand code that builds 3D sphere
I'm trying to learn some lwjgl and opengl, and I was trying to make a 3d sphere etc, I found a code to do that, but I don't 100% understand the code and the math behind it and would like to get some deeper explanation about it.

This is my draw sphere method:

```
public void drawSphere(float radius) {
    final float PI = 3.141592f;
    float x, y, z, alpha, beta;
    int gradation = 100;
    for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation) {
        glBegin(GL_TRIANGLE_STRIP);
        for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation) {
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha));
            z = (float) (radius * Math.cos(alpha));
            glTexCoord2f(beta / (2.0f * PI), alpha / PI);
            glVertex3f(x, y, z);
            x = (float) (radius * Math.cos(beta) * Math.sin(alpha + PI / gradation));
            y = (float) (radius * Math.sin(beta) * Math.sin(alpha + PI / gradation));
            z = (float) (radius * Math.cos(alpha + PI / gradation));
            glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);
            glVertex3f(x, y, z);
        }
        glEnd();
    }
}

```

I understand the general idea of this, and I understand how the x, y, z are calculated, but what I don't understand is the 2 nested loops aka:

```
for (alpha = 0.0f; alpha < Math.PI; alpha += PI / gradation)

```

and

```
for (beta = 0.0f; beta < 2.01f * Math.PI; beta += PI / gradation)

```

One more thing, is the `glTexCoord2f` that I don't quite understand the math behind it, so an explanation about this would be really nice as well for:

```
glTexCoord2f(beta / (2.0f * PI), alpha / PI);

```

and

```
glTexCoord2f(beta / (2.0f * PI), alpha / PI + 1.0f / gradation);

```

# Answer
> 2 votes
Think of a globe with latitude and longitude lines drawn on it. What the loops are doing is marching around the longitude lines of the sphere at different latitudes. The outer loop goes from 0 to π radians, or 0 to 180°. This is from the south pole to the north. It's sometimes expressed as -π/2 to π/2 (-90° to +90°) with 0 radians/degrees being the equator.

At each latitude, the inner loop walks around the longitudinal lines from 0° to 360°.

To understand the texture coordinates, you need to understand an equirectangular projection. An image in this format has its x coordinates representing the longitudes, and the y coordinates representing the latitudes. I'm assuming that the texture is in a `GL_TEXTURE_2D` texture target. That means that the texture coordinates need to be normalized. So the 2 lines you quoted are converting the longitude and latitude from their normal ranges (longitude = 0 to π, latitude = 0 to 2 * π), into the range 0 to 1. This makes a texture in an equirectangular projection map properly onto the sphere. The vertex at lat/long of `(alpha, beta)` will be assigned a texture coordinate `(u, v)` in such a way that the bottom of the image is at the south pole, the equator is in the middle, the top is at the north pole, and the left and right edge meet at the international date line.

---
Tags: opengl, java, 3d, sphere, lwjgl3
---


# Question
Title: If I'm designing a melee combo system, should I get the combo animation sprites before coding, or can I code before getting them?
I intend to make a combo system like Devil May Cry 3 (meaning, combo attacks like `E-E-E`, or `E-(pause)-E-E`, and directional attacks like `forward+E` or `backward+E`, assuming E is the melee attack button). Right now my pseudocode for the first combo is the following:

```
var combo_frames = 60
var hitbox_show_frame = 24
var pause_threshold = 45
var hitbox_show_dur_in_frames = 6
var hitbox_consumed = false
var current_frame = 0
var hitbox_show_curr_frame = 0

func _physics_process(delta): #Godot2D's fixedUpdate()
    current_frame += 1
    if current_frame >= hitbox_show_frame and not hitbox_consumed:
        hitbox_coll.disabled = false
        if current_frame >= hitbox_show_frame + hitbox_show_dur_in_frames:
            hitbox_coll.disabled = false
            hitbox_consumed = true
    if frame_num >= combo_frames:
        combo_index = 0
        return Melee_Idle.new()
    pass

func _input(event):
    if hitbox_consumed:
        if current_frame < pause_threshold:
            return Melee_Combo2.new() #normal combo
        elif current_frame < combo_frames:
            return Melee_Combo2_Alt.new() #alternate combo after some delay

```

As seen, I've implemented a Finite State Machine for the combo system.

However, I don't have the animation sprites for these combos yet, so the frame numbers are just approximations. Should I get or make said animation sprites before designing this combo system, or can I think about it later and use the frame count like above for now?

# Answer
> 2 votes
In my experience it's always best to not count on hard animation times, especially when you're dealing with variable input times. Try implementing a onAnimationEnd event handler of some sort to make sure your animation has actually ended before you continue with your script. Also in most engines it's possible to insert key frames in your animation that allow you to execute pieces of code. That way you don't have to worry with exact animation times and your code becomes way more flexible.

---
Tags: game-design
---


# Question
Title: How do i manage skill collision target in Unity?
I wanted to make a skill that can be used by both Player & Enemy.

How do I make it such that the skill will not be colliding with the owner/caster or colliding with both?

One stupid way I have is to create empty gameObjects as the Skill's child and set their tag as "targetPlayer","targetEnemy" or "targetAll" whenever my player/enemy cast the skills.

And when the skill collided with Player/Enemy, i will check the skill's children and see if there's matching tag and proceed if so.

Is there better way to do what i wanted??

# Answer
You can put the skill object in a physics layer that collides only with players, enemies, or both. (Players & enemies each being in their own dedicated layer)

It's similar to your tag idea, except you don't need to check the tag inside the collision callback method. The callback won't even be called - the object will simply ignore collisions with objects it's not allowed to collide with according to the Collision Matrix you've configured.

If you don't want to do this layer-wide, you can also get a similar effect on a per-object basis using the Physics.IgnoreCollision() method to tell a particular pair of colliders to ignore each other (useful for a spellcaster to tell their own spell not to collide with themselves)
> 1 votes

# Answer
How about, when someone casts the skill, give a reference of the caster to it. Something like

```
caster.CastSkill(caster);

```

Then save `caster` inside the skill, and any time it collides with any other object, check if that object is the same as `caster`.

Alternatively, if you have a skill that has a specific target (for example) you can pass that target(s) and save them in the skill, so it can only collide with these targets.

This obviously is skill-dependent. Some skills may not care who is the caster, some skills may only differentiate between ally/enemy (in which case @DMGregory's answer is better).
> 1 votes

---
Tags: unity, collision-detection
---


# Question
Title: Why the npc soldier is rotating to the other way instead facing the player?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

public class SpaceshipCutscene : MonoBehaviour
{
    public Transform player;
    public Transform npc;
    public Camera FPSCamera;
    public Camera mainCamera;
    public Animator anim;
    public float rotationSpeed = 3f;

    private bool moveNpc = false;

    // Use this for initialization
    void Start()
    {

    }

    private void Update()
    {
        if (moveNpc)
        {
           npc.rotation = Quaternion.RotateTowards(npc.rotation, player.rotation, Time.deltaTime * rotationSpeed);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.name == "Horizontal_Doors_Kit")
        {
            FPSCamera.enabled = false;
            mainCamera.enabled = true;
            moveNpc = true;
            anim.SetTrigger("SoldierAimingTrigger");
        }
    }
}

```

At this line:

```
npc.rotation = Quaternion.RotateTowards(npc.rotation, player.rotation, Time.deltaTime * rotationSpeed);

```

On screenshot on the right the player (FPSController) And the FPSController Inspector Rotation:

But you can see in the same screenshot that the soldier(Space\_Soldier\_A (2)) is rotating slowly to the other side and stop rotating in the end facing the spaceship on the back.

I want the soldier to rotate slowly and stop when facing the player(FPSController)

This is a screenshot of the soldier in the end when he stop rotating: He is facing the opposite side of the player:

What I tried now is to create a new script attached to the npc(Soldier) I want to rotate slowly facing the player(FPSController):

What I didn't try ? Everything. This is the latest try:

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

public class Rotate : MonoBehaviour
{
    public Transform player;
    public float rotationSpeed = 3f;

    private Vector3 direction;
    private Quaternion toRotation;

    // Use this for initialization
    void Start ()
    {

        //direction = player.position - transform.position;
        //toRotation = Quaternion.FromToRotation(transform.forward, direction);
    }

    // Update is called once per frame
    void Update ()
    {
        if (SpaceshipCutscene.moveNpc == true)
        {
            Quaternion q = Quaternion.LookRotation(transform.position - player.position);

            transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotationSpeed * Time.deltaTime);
            //Vector3 dir = player.position - transform.position;
            //transform.rotation = Quaternion.LookRotation(dir, Vector3.up);

            //transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, rotationSpeed * Time.time);
        }
    }
}

```

Again it's rotating the soldier slowly the Space\_Soldier\_A (2) but to the other opposite direction and not to the player direction not facing the player.

I found that if I only make in the Update simple:

```
transform.LookAt(player);

```

It will facing looking at the player but this is without slowly rotating. It seems like every rotation i'm trying to do with a speed rotating the soldier to the opposite direction.

In the first script I changed it: And did the moveNpc to be public static:

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

public class SpaceshipCutscene : MonoBehaviour
{
    public Transform player;
    public Transform npc;
    public Camera FPSCamera;
    public Camera mainCamera;
    public Animator anim;
    public float rotationSpeed = 3f;

    public static bool moveNpc = false;

    // Use this for initialization
    void Start()
    {

    }

    private void Update()
    {

    }

    private void OnTriggerExit(Collider other)
    {
        if (other.gameObject.name == "Horizontal_Doors_Kit")
        {
            FPSCamera.enabled = false;
            mainCamera.enabled = true;
            moveNpc = true;
            anim.SetTrigger("SoldierAimingTrigger");
        }
    }
}

```

I can't figure out yet why the soldier is rotating slowly to the opposite direction. Maybe the Cinemachine and virtual camera making the problem ? Maybe since the player(FPSController) have a Rigidbody component it's making the problem ?

This is a screenshot of the player FPSController inspector:

# Answer
I'm not really into Unity, but your `Quaternion.RotateTowards` function seems to be some kind of SLERP (Spherical Interpolation) which makes the npc's rotation to become identical to the player's rotation. This results in making the npc face in the same direction, that the player faces. To make them face each other you may try "rotate towards" the negative of the player's rotation (i.e. `-player.rotation`).

**EDIT:**

Just a small edit. I've seen, Unity integrates a SLERP function in it's Quaternion Class (see here).

So if your

```
transform.lookAt(player)

```

works, you could probably use it to achieve the effect you want. You'll want to do something like this:

```
Quaternion destOrientation;
destOrientation.lookAt(player.position);
npc.orientation = Quaternion.Slerp(npc.orientation, destOrientation, deltaTime);

```

Just be careful with the `deltaTime`, due to both Quaternions changing over time this may yield unexpected results (a fixed timestep, although, may be appropiate).
> 4 votes

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


# Question
Title: What are the benefits or drawbacks of splitting the player animation system from the wall collision system into multiple objects pinned to each other?
I'm currently making a simple platformer in GameMaker Studio 2 and I've had people telling me that I need to separate the two things into an invisible wall collider mover and animation sprites pinned on top of it. I've also had people telling me that's overcomplicated and stupid. But I've never heard the reasons why I would or should do it either way.

# Answer
The approaches you described are both equally valid, but as always your best choice *depends on what you want to achieve*.

### Defining "sub-systems"

Notice that collision and animation systems are always separated, as the former is related to game logic and the latter deals with rendering. For example, GameMaker objects have a **Sprite** and a **Collision Mask** field because a sprite is used to draw an object shape, while a *mask* is used for collision checking. Unity does the same, as well as other 2D and 3D engines, so one can't really say *not* to separate the two things.

Moreover, advanced engines use separate shapes depending on what kind of results are to be achieved:

* **Object rendering:** being the model a 2D sprite or a 3D mesh, this resource is highly detailed and used only for rendering purposes. The model is always rendered according to the game logic, being it an index of an animation frame or a spatial displacement due to a ragdoll system, but it never influences the game logic back.
* **Simple collision checking:** convex primitives are used to check for collision, for they are fast to compute. They usually wrap the actual model more or less precisely, and different shapes are chose depending on the game object being static/dynamic or the precision required. Example: a *capsule collider* can be used to model a character physics, which is usually separated from the rendered model, as you can see in this picture from the Unity Q&A forums.
* **LOD collision checking:** a separate collision shape can be used to check for collision at level of detail (LOD), when needed. On the GarageGames blog there's a clear example of separate collision shapes used for a tree: bigger and simpler boxes to detect *if* a collision has occured, and more and more precise shapes depending on how much precision is needed. For animated objects, the shape used for LOD collision check can be seen as a hierarchy of convex sub-shapes moving according to the animation applied to your game object. They are never as detailed as the rendered mesh, but a good precision in modeling them does the magic and gives good results.

I first said that an object model never influences the game logic back, and that an animated object's collision mesh can be moved according to the model animation. This is so because animations are usually treated as a separate resource rather than bonding them to a given model. After all, a single model can play several animation, while a given animation can be applied to multiple models.

### Pros and cons

The advantages of specializing different aspects of an object interaction/appearance are several, we can combine separated data to achieve good-looking effects, such as: altering a walking animation to fit some steps on the ground; using some parameters to make the character aiming their weapon towards a given angle with regards to joint constraints; changing the speed a wheel revolves according to the car acceleration... All these can't be simply accomplished if using *only* pre-made animations due to their intrinsic limitations.

Of course, dealing with all these components leads to a higher complexity that requires a non-negligible effort from the programmer, compared to a simpler animation system. Early *Super Mario* titles didn't need such complexity, sprites were drawn based only on the character states and facing direction, without having separate components. On the other hand, *Contra* allowed the player to aim towards different directions, so there was (probably) a script dealing with movement and collision, and another script drawing the right sprites for legs and arms; yet, I see no need for separate objects to detect whether the player was hit, as the main physics collider was fine to do the job.

If you want your animations to be more interactive with the surrounding environment, or just to make them smooth using the right math, you can go for the objects collection, treating these model members as "slaves" of the "master" object (in order to avoid action conflicts). Otherwise, if it's way too complex you probably don't need it.

If the animation is rendered without any concern for collisions with the character's *visible* shape, you can get rid of the objects collection and render only the sprites on top of it: this is an animation system as any other, you're just using sprites instead of objects to do the thing.
> 2 votes

# Answer
*I'll develop this answer as soon as I get more time and tell me if I'm off topic, I'm not really sure about what your actually asking. It's also one of my rare attempts to reply to a question, I'm always trying to improve the quality of my answers*

If I understand correctly, you are talking about hitboxes and sprite being drawn on top of them.

A simple hitbox can be represented as a rectangle/square shape used for collision detection.

I have some arguments for this.

**Easy collision detection**

If you use Axis Aligned Bounding Boxes (AABB) (see SO question here) you can solve collisions pretty easily ; it consists of checking if two rectangles intersects and such algorithm is implemented easily. (If you consider your walls & hitbox being rectangles)

If I follow your question, you might be talking about collision masks (more info about this topic here) or pixel perfect collision. This is feasible but such collision routine is much intensive than AABB collision and probably not that effective in terms of gameplay.

**Consistent gameplay**

Say you're designing levels with a sprite *s*. Suddenly your art style changes and you grow your sprites. You have to make platforms wider, adapt your whole level...

**Animation?**

What about animating sprites ? A frame could be wider than another one. This lack of consistency could be a problem for collision since your "collision mask/box" changes.

**Aesthetics / Perspective**

I hope this is not off-topic since you're talking about platformers, but say you're creating a top down game with a simple perspective like pokemon or zelda. You want to have a hitbox at the feet of your character so it doesn't collide with the bottom of the wall.

Here link is not colliding with the bottom pixel of the wall, he's like into it.
> 2 votes

---
Tags: animation, sprites, game-maker
---


title: Can I sell a game made with OpenGL?

text:
# Question
Title: Can I sell a game made with OpenGL?
I love creating games, and I've always made games using OpenGL and not with game engines such as Unity or Unreal. Can I legally sell the games I made with OpenGL?

# Answer
# Yes, you can sell OpenGL-rendered games.

The specifics depend on the library you're using. I'll get back to that.

First: OpenGL is an open standard and related API-set that establishes the protocol for communication between your application and video card / GPU. Typically this communication protocol is implemented by means of an operating system driver, and a supporting library which gets shipped with your game. OpenGL is fairly ubiquitous: Linux, Mac, Windows, iOS, and Android all typically have it pre-installed in the system. Loads of things you buy and that people sell are rendered using OpenGL.

It's the people making the operating systems and GPUs that have to worry about OpenGL licensing. OpenGL clarifies in its About section on Licensing that “End users, independent software vendors, and others writing code based on the OpenGL API are free from licensing requirements.” (That's you.)

<sup>(Thanks Jimmy for pointing out the About section.)</sup>

# The library's license is what matters.

There's probably a library you're using to render via OpenGL though. It might be GLFW, freeglut, Allegro, SDL, SFML, Ogre3D, or others. Your library's license has more relevance here because your program has to ship with the library and the license will control how you can do that.

If you're not actually using any library at all, you have no licensing expectations in this area.

If you are, fortunately all the OpenGL libraries I know of are fine with this:

* All the ones I just mentioned use the zlib license.
* Except for Freeglut and Ogre3D, which use the MIT license (the X Consortium variant in Freeglut's case).
* Older versions of Ogre3D (before 1.6) used Gnu LGPL.
* Older versions of Allegro used a giftware license (summarily “do whatever you want with it”).

Check the license for the exact version of the libraries you're using to know what your obligations are.

You'd have some problems if you used Gnu GPL (as opposed to **L**GPL) licensed libraries, since that can bind you to redistribute your software's source code. There may also be issues if the library required royalties but this is also not the case. (You could still sell your game, you'd just be obligated to fork some of the profit elsewhere.)

The specific license involved may bind you to give attribution to the library, or to ship the library's license with your source code, so check the license and see what it instructs you to do. Usually people have buried in their app somewhere an "About" section that contains a "Boring legal stuff" link which itself is just a long scrolling textbox full of all the licenses they have to reproduce, and usually that is enough. Consult your library's license.
> 29 votes

---
Tags: opengl, legal, sales
---


# Question
Title: Managing different types of Actors/Entities in a rendering engine
I'm coding a simple game engine using DirectX11, and I'm stuck on how to implement a kind of ECS. Now my rendering system look like this (sorry if the diagram is not real UML, it's just for description):

The architecture is really naive, I wanted to keep things as simple as possible, for learning purposes:

* Every entity is modeled as a new class (no, inheritance, no composition), and is added to a master Renderer class with a AddEntityXXX() method, which adds it to a vector of that kind of entity.
* Every ShaderXXX inherits from a base Shader class, which takes care of the common functionality of a shader (compiling the bytecode, binding the shader program, seting the input layout ecc..), while every subclass defines some type members (struct XXXConstantBuffer {...};) that contain shader parameters (constant buffers) to be uploaded/updated before rendering (UpdateXXXConstantBuffer() method).
* The renderer keeps a reference to a camera object, which contains the view and projection matrices, and uses some instances of a FrameBuffer class for offscreen rendering (shadow mapping, water reflections/refractions, postprocessing).
* Finally, the renderer renders each EntityXXX by calling a specific RenderXXX() member function and performing the appropriate work for each type of game object, like binding the specific shader, updating the constant buffers and issuing a draw call.

Now, since my engine will be more than a showcase of graphics features, I want to make each entity abstract, and I tried inheritance, but since each entity has its own "identity" it's not viable approach: an entity representing a player needs a Move() method, position and velocity state variables, while a terrain entity doesn't move ecc.. So I learned about the Component pattern and Entity Component System architecture / Game Actors. What I find most difficult in abstracting the various kinds of entities is how to manage the rendering: How can a renderer differentiate between them and update the shader parameters (constant buffers) accordingly? In some cases I need to pass to the UpdateXXXConstantBuffer() method a WorldViewProjection matrix only, in others (shadow mapping) I need to pass a LightViewprojection matrix as well, or an array of bone tranform matrices for animation.

How can a rendering engine be structured to address these issues? Please, don't give general pattern advices, I know the existence of the Component pattern, and the Entity Component System, but I'd like to learn some practical implementation for it. I mean how should an entity be structured so that a rendering process can be performed abstracting away the specific implementation of an entity/actor?

**EDIT** maybe my uber-question could be rephrased like this: how can I structure a simple but efficient RENDERING ENGINE? I know that there's no such thing as a generic rendering engine, but which are the guidelines (and by that I mean a foundation for an architecture/patterns) to implement one and how does this translate to a component based GAME ENGINE?

# Answer
Entities nor components need to know about how they should be rendered. The (sub)system should take care of it.

In the picture below the render system collects the data but doesn't render them yet. But rather collects them first, it's basically prepping the commands it needs to render. The collected data can be sorted if need be so objects sharing the same specifics are rendered in sequence to prevent overhead from changing textures/shader programs.

After collecting the data the rendersystem performs the actual calls to the gpu iterating over the array containing all data. The entity at this point is no longer relevant.

Since you're using c++ having simple structs should be sufficient to copy over the data from the components relevant to rendering. You shouldn't need to reference entities/components directly unless you are doing some special cases ( what they might be is entirely up to your implementation)

Here is an article that does something similar with bitkeys

The render struct contains meshID, MaterialID, etc. Which are just index pointers to some static collections of each loaded asset respectively. Which are then plugged into your draw calls.

Of course how you manage and reference assets is up to you. The article I've linked goes into more of the details how they used simple integers to leverage accessing assets.
> 2 votes

# Answer
Im not 100% sure you really understand ECS.

Your renderer shouldn't have all the entities, as other manager systems might also work with the entities (Physics Manager moving entities, influencing your bone transformation, the position in general, etc.), while other aspects of your entities are only used by your renderer (e.g. textures) and others only by other managers (sounds, inventory...).

Now, your entites are only containers or identifier / handler for a group of components. These components are what are interesting for your renderer and managers.

For example you have a shaderComponent, saving your shader informations, a modelComponent, for 3d models, a textureComponent, saving your texture information, a positionComponent, a soundComponent, a inventoryComponent and some other components.

Your entites are handler for all of those compoents and has the option to at least have one those components, maybe even 3 or 4 for some components.

Now, your renderer interates on the entities, but only if it has the components the renderer works with: shaderComponent, textureComponent, positionComponent... Your renderer than does its thing: if an entity has a shaderComponent, load this shader. If an entity has an animationComponent, apply the bone transformation on the model. Then if the entity has a model, render the model with the textures it may have, use the position from the positionComponent and so on.

Your renderer needs to know, what components to use and what to do with it. If an entities doesn't have a component, it doesn't try to work with those.

If some components need other components to work, your renderer either needs to know this, or your components have functions on their own to deal with that. In the case, what informations to send to the UpdateXXXConstantBuffer, i would suggest to have a worldViewMatrixComponent, when your shader needs it for an entity, and other components for other cases.

**Edit:** So first, the renderer iterates over every entity and asks what components it has. Then it calls those components in its wished order. Now, what it does depends on the next thing.

There are basically two different approaches to components in an ECS.

1. Components are function carrier
2. Components are Value-Only

The first approach has the components be called in the corresponding manager. In your example, the shaderComponent loads the shader into the GPU to render the next object, then the renderComponent is called to render the object, using the loaded shader.

As you can see, the shaderComponent doesnt care, what component comes next, as the manager has to know, when to call what component type of an entity.

For example, an entity has a corresponding renderingComponent, but no shaderComponent, the rendering manager would first try to look for the shaderComonent, then, if it cant find it, just use the standard shader instead. If there is no rendererComponent either, the entity will not be drawn. An Entity with only a shader could be something like water effects or other shader effects, that are not directly drawn. Im not that deep in graphics programming, so i may lack better examples

Pros:

* components are way more versatile, as you can implement what you want
* Components act in a void, they dont need other components to work (basically atoms), except maybe input parameters for the update function (rendererComponent need the current position and the current deformation matrix and so on.
* the renderer doesnt need to know anything other than the order and what informations to keep

Cons:

* As components know nothing about other components (could be dealt with, but is bad practice), the renderer needs to do the order. If something changes in a component, it might influence the order of component calls (no loose coupling between components and manager)
* Components NEED to have update(): Even if your component does nothing but save something, it does need to have an update function. This update() can be empty and your renderer may decide to call it, if it knows what type of component it is (like a positionComponent only containing a position), but that would mean stronger coupling of components and renderer.

The other method is to just save data in your components. I prefer this type, as it comes with some benefits to it. You can save shaders, textures and models by reference, others by value.

Pros:

* Loose coupling: Only the renderer knows the values of the components. The components themselves dont care, what the informations are. So if you change something in the renderer, the components couldn't care less.
* Loading from files: If you create a new type of enemy, just load the file with his texture, his model... no need to save functions in a scripting language (good for modding aswell)
* Informations from one component can easily be used in another. No need to call an update() with different parameters, just to give position and texture and so on.

Cons: \- less flexible: Your renderer needs a one-fits-all update-function. If the Enttiy has component a, b, c, do this, if it has a and b, not c, do this, and so on.

So, what do you want to do, to start a Graphics Engine. I go the "components have values only"-way

1. Make a general Manager class, that renderer inherits from. If you want to expande on this basic graphis engine, you want to do that. TRUST ME! And do the same for components.
2. Think of every aspect an Entity can have. Position and direction, Texture, Model... do that as atomic as possible. Working with 2d Sprites. have 2DTextureComponent and a spriteComponent. 3D? modelComponent, 3dTextureComponent and so on.
3. Add some helper classes, like a camera (saves viewMatrix, helps with smooth camera movements and so on) and a texture manager (so textures get loaded into the gpu memory only once and return that texture ID in gpu)
4. Now imagine a Master Manager class calls this Renderer class to create a graphical entity. It does that by givin all required informations (lets assume 2d): an Entity (lets assume by ID (a number)) with an exisiting positionComponent, a texture path and a sprite size (64 x 64 pixels or something like that. The renderer creates a spriteComponent (sprite size, no idea what other informations) and a textureComponent (texture by reference or id or whatever). It loads the texture into the gpu and is done for now.
    5. Your update( deltaTime ) of the renderer gets called. It gets (or calls for) every entity, that has corresponding components (why care for an object, if it has no spriteSize). It then iterates other every component of the wished type and does its thing: Read its positionComponent(mandatory for every Entity), calculate viewMatrix postition, then draw the entity with the given spriteSize and given texture. If it has a spriteComponent, but no textureComponent (or texture coulnt be loaded) you can fill in a default texture. If you have a shaderComponent, you can even order them and only do entities with shader A, then entities why shader b. Samething with textures (Entities with texture A -\> Entities with texture B -\> ...)

And that is basically it. You cant expend your Game Engine by adding more managers with their own components. Physics Component adds velocityComponent, physicalAttributCompnents (Weight and stuff, if you want it that sophisticated).
> 0 votes

---
Tags: game-design, architecture, rendering, entity-system
---


# Question
Title: GameObject.Find can't find the object after i changed its name
I created this script to create a group of plane meshes with offset between them in my game scene, then change their names and give an ID to every one of them:

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

public class creatingobjectslist : MonoBehaviour {

    public GameObject TargetPrefab;

    void Start () {
        for (int i = 0; i < 5; i++){
            Instantiate(TargetPrefab, new Vector3(i * 1.5f, 0f, 0f), Quaternion.identity);
            TargetPrefab.name = "Ben" +i;
        }
    }
}

```

Then I created this script and attached it to another object to move my object to one of the objects that was created with the `creatingobjectslist` script

```
using UnityEngine;
using System.Collections;
public class MoveCubeTogrid : MonoBehaviour {
    UnityEngine.AI.NavMeshAgent agent;

    void Start () {
        agent = GetComponent< UnityEngine.AI.NavMeshAgent >();
    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
                    //agent.destination = hit.point;
                    agent.destination = GameObject.Find("Ben0").transform.position;
            }
        }
    }
}

```

and after running that I get this error

```
NullReferenceException: Object reference not set to an instance of an object

```

# Answer
> 2 votes
# You're renaming the prefab, not the clone:

```
TargetPrefab.name = "Ben" +i;

```

As such, the first one has `OriginalName (clone)` for a name, the second one is called `Ben0 (clone)`, then `Ben1 (clone)` and so on.

If you had checked your scene hierarchy at runtime you would have noticed this.

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


# Question
Title: Suitable interpolation for animating explosions
Is there a standard interpolation function for animating explosions? Like there is with smoothstep or smootherstep for walking animations or cars going from point A to B.

I'm assuming the explosion needs to grow very fast at the beginning and then slow down - how much in relation to the default linear interpolation, I don't know.

I've tried inverse smoothstep and inverse squared from this article: *Interpolation Tricks*, but none quite cuts it, maybe I'm applying them wrong.

# Answer
There are multiple easing functions (https://easings.net) that can help you, more specifically **"ease out"** functions (faster at the beginning, slower at the end).

I have all of those in the link implemented, but in my opinion, the ones more suitable for an explosion effect are: quartic ease out, quintic ease out, exponential ease out and circular ease out.

> I'm assuming the explosion needs to grow very fast at the beginning and then slow down - how much in relation to the default linear interpolation, I don't know.
>
> I've tried inverse smoothstep and inverse squared from this article: Interpolation Tricks, but none quite cuts it, maybe I'm applying them wrong.

Work with easing functions as if you were working with a linear function, for each frame you add a **constant** to the value that you pass to the function:

```
/* EXPLOSION INITIALIZATION */
progress = 0.0;
frame_index = 0;

/* EXPLOSION UPDATE METHOD */
frame_index = quartic_ease_out(progress) * total_frames;
/* Add the constant 0.1 for the next frame */
progress = progress + 0.1;
if (progress > 1.0) {
  /* The explosion is over */
}

/* EXPLOSION DRAW METHOD */
draw_sprite(x, y, animation[frame_index].pixels);

```

The function receives an value from 0.0 to 1.0, and outputs an value form 0.0 to 1.0. Notice that you don't have to do any tricks with the value that you are passing to the function, you just need to update it linearly, and the function returns the proper "smoothed" value for you.
> 3 votes

# Answer
Yes, the velocities are the highest at detonation time, and as the explosion progresses, the system loses energy.

So fast growth that fizzles out would be a good model.

So a function with a fifth power could make for a suitable curve.

You could also simply raise x to the power of 0.2 over a 0..1 range to get a similar response.
> 2 votes

---
Tags: animation, interpolation
---


# Question
Title: Help creating combat for collection type game
sorry for my odd terminology, I am rather new to all this

I'm creating a collection/pokemon type game. as of right now I have created a separate GameObject prefab for every monster/character in the game. Each gameobject contains a script with enumerated values for it's stats. When combat begins It calls a random monster from a pool of gameobjets. The problem is at this point I'm not sure how to have it create a new instance of the enemy in a way where it retains the values in it's public floats from the prefab or have it's level be adjusted as it enters. And I don't know how I can derive it's stats and properties for scripts outside the function that spawned it. as the function that creates the new duplicate won't remember the new creature after the function resolves.

so In short, How can I reference the enumerated integers of a newly duplicated gameobject

I was asked to include some more information on what I've coded:

```
public List<baseMonsters> allMonsters = new List<baseMonsters> ();

public void EnterBattle(Rarity rarity)
{
    // this code swaps camera view to the battlefield from the overworld map
    playerCamera.SetActive(false);
    battleCamera.SetActive(true);

    // call function to determine which monster appears
    baseMonsters battleMonster = GetRandomMonsterFromList(GetMonsterRarity(rarity));

    // returns which monster was chosen
    Debug.Log (battleMonster.name);

    // prevents the player from moving after combat begins
    player.GetComponent<PLayermove>().isAllowedtoMove = false;

    //Creates the defending monster
    GameObject dMon = Instantiate (emptyMon, defencePodium.transform.position, Quaternion.identity);
    //Ensures scale from original is preserved
    dMon.transform.localScale = battleMonster.transform.localScale;

    Vector3 MonLocalPos = new Vector3 (0, 1, 0);
    dMon.transform.parent = defencePodium;
    dMon.transform.localPosition = MonLocalPos;

    //Adds the stat components of the original prefab
    baseMonsters tempMon = dMon.AddComponent<baseMonsters> () as baseMonsters;

    tempMon = battleMonster;

    dMon.GetComponent<SpriteRenderer> ().sprite = battleMonster.image;
    bm.ChangeMenu (BattleMenu.Selection);

}

```

the issue that I see with the code is that it's transforming an already existing object into what the prefab monster is, not copying it. what method can I use to copy the prefab in a way I can easily reference in the same function to change it's level?

-Update-

ok so changing everything over to instantiating a GameObject is what I want. now there is the other part from the code before:

```
public List<baseMonsters> GetMonsterRarity(Rarity rarity)
{
    List<baseMonsters> returnMonster = new List<baseMonsters> ();
    foreach (baseMonsters Monster in allMonsters)
    {
        if (Monster.rarity == rarity)
        returnMonster.Add (Monster);
    }
    return returnMonster;

}
public baseMonsters GetRandomMonsterFromList(List<baseMonsters> monList)
{
    baseMonsters mon = new baseMonsters ();
    int monIndex = Random.Range (0, monList.Count - 1);
    mon = monList [monIndex];
    return mon;
}

```

I was following a tutorial when I created this code, I am starting to understand more and more how spaghetti it is.
sorry for all the Alike Terms, baseMonsters is a class that houses things like the rarity and stats of the monster. These functions are searching by and for that script. How can I convert these codes over to searching the class from a list, to a Gameobject from a list, and still be able to read baseMonsters of each respective GameObject and it's rarity int?
as of right now, one workaround I can think of is to create a seperate list for each rarity. that way I can skip needing to read the rarities in the baseMonsters script entirely. But I will still need to know how I can call that class script for other things like determining level of the monster and what it's attacks will be?

# Answer
> 2 votes
As far as I can read the code, you're picking a monster from a prefab list with

```
baseMonsters battleMonster = GetRandomMonsterFromList(GetMonsterRarity(rarity));

```

Then you're creating an empty monster

```
GameObject dMon = Instantiate (emptyMon, defencePodium.transform.position, Quaternion.identity);

```

And you're trying to fill the empty monster instance with the current monster's 'attributes' with the rest of the code.

If your monsters are pre-made gameObjects themselves, then you could just create the monster you just picked, instead of dealing with the whole empty monster filling process.

```
GameObject dMon = Instantiate (battleMonster, defencePodium.transform.position, Quaternion.identity);

```

The rest of the code will need to change a bit too, but I can't really edit the whole thing because it will probably break some other functionality with the `tempMon` variable that you're not using in the current function.

Though these two lines shouldn't be necessary if you can instantiate the monster directly (since it will already have the image and the scale):

```
dMon.transform.localScale = battleMonster.transform.localScale;
dMon.GetComponent<SpriteRenderer> ().sprite = battleMonster.image;

```

# Answer
> 0 votes
See John's statement, What I decided on with the code I have is that I need to convert all the class based structure into GameObject Scructure instead. as most of my issues will likely just be cleared up by that alone.

---
Tags: unity, c#, game-design, game-mechanics, combat
---


# Question
Title: How to implement a Play As Guest feature on a mobile device using PhoneGap?
I have a Facebook Web Game that I converted to Android and iOS using PhoneGap. I can use Facebook for authentication on my mobile apps, but I would also like to allow the user to play as a guest. I've seen various games implement this workflow before and I'm curious how it is actually done. What unique identifier is the phone sending to the server to authenticate against? Does each phone have something unique about it that PhoneGap can expose via a plugin? Does anyone know the logic behind the "Play As Guest" feature many mobile games implement?

Thanks!

# Answer
A quick look at the documentation reveals that you can easily access the device identifier via device.uuid. From here, it should be easy to use this as an ID for the server.

If that fails, another approach would be to just create a new GUID to use as an identifier, and persist it on the device for reuse.

Depending on your game it might be worth asking if you even need to talk to a server, or can just let the guest play offline without autentication at all, but without knowing what your game entails I can't say for sure.
> 2 votes

---
Tags: android, javascript, ios, mobile
---


# Question
Title: Multiplayer game, design of server <-> client communication
I'm thinking about programming a multiplayer game. For communication, I will use a Server \<-\> Client design like the following:

> Client \<-\> Server \<-\> Client

The Game will be a kind of Tower Defense. Where two players can fight each other by sending soldiers to the enemy to destroy their base or build towers to defend.

To keep the games in sync, each action must be sent to the other player.

e.g. Player 1 set a tower on position x, y so Player 2 must know about this tower (It would be pretty unfair if the enemy has invisible towers)

To sync the two games I can think of two methods:

**First method:**
The client(Player 1) set a tower to position x, y and send a message to server: "I have placed a tower on position x, y". The server sends this message forward to the other client(Player 2)

```
//client 1
buildTowerOnPosition(x, y);
sendToServer(BuildTowerMessage(x, y))

//server
receiveMessageFromClient(BuildTowerMessage(x, y))
sendFurtherToOtherClient(BuildTowerMessage(x, y))

//client 2
receiveMessageFromServer(BuildTowerMessage(x, y))
buildEnemyTowerOnPosition(x, y)

```

By this method:
The server doesn't need to know the current game status and serves only as a bridge between the clients

**Second Method:**
The client(Player 1) send a message to server: "I will build a tower on position x, y" the server build a tower to position x, y and send the changes(New tower on position x, y) to the clients

```
//client 1
sendToServer(BuildTowerMessage(x, y))

//server
receiveMessageFromClient(BuildTowerMessage(x, y))
buildTowerOnPosition(x, y)
sendFurtherToBothClients(BuildTowerMessage(x, y))

//both clients
receiveMessageFromServer(BuildTowerMessage(x, y))
buildTowerOnPosition(x, y)

```

By this method: The server needs to know the current game status

**My thoughts are:**

By the first Method
The server only needs to forward the message and the main calculation is on the client side which relieves the server.

By the second Method:
The server can control the actions of the clients. For example: When both players set a tower on the same position at the same time, the first tower will be set and the second cannot be built anymore.
In the first Method the second tower will overbuild the first or in the worst case, both clients have different towers.

**Now to my question:**
Which method should I use for my game?
Is there more pro and contra by the methods?
Are there other methods?
Are there kinds of games where I should prefer another method than in my game?

Thank you for your advice

# Answer
In Multiplayer games, it is usually good to have the server be the authority. This will solve many (but of course not all) problems with network issues, cheating and so on.

You already mentioned part of it in your question: if the clients do all the work and the server only relays messages without checking them, you can get all kinds of inconsistencies if things happen at the same time or close to that. If one or both of the players has a spotty internet connection, all bets are off. And this only gets worse if you include cheaters into the equation - it's a lot easier to convince your own client that you have infinite money and just built 417 towers than to convince a server that effectively runs the game. Not to say that it's impossible to deal with this kind of thing any other way, but it is a bit easier if the logic is done in one place, by a server you control.

Of course, this is also means a bit more work. Some cases, like building a tower at the same place, should be caught without adding much code (I assume you check if it can be built there anyway). To prevent/mitigate other issues, you might have to do some sanity checks and validation on the client messages you receive, and you'd need to handle messages that might arrive in another order than they were sent in due to network issues, or messages being lost completely. The same goes for the client - you might need to make sure that it stays in sync with the state as the server sees it.

As for other methods: if the server only relays one client's messages to the other anyway, an alternative might be to have a direct connection between clients and skip the server part completely, or only use it for finding and joining a game. It would work out basically the same, because you'd need to validate and process messages on the client anyway.
> 4 votes

# Answer
I would advice not to invent the architectural wheel but the read the networking documentation for well-known engines such as Unity or Unreal and to see how they designed the things to work.

Regarding your question, about which method to use.

Same as @Christian, I would advise to the server to hold the authority and double check things that player are trying to do.

You need to answer the question: "Do I want cheaters in my game spoiling other people experiences?"

If the answer is no, then you need to double check everything, and server should hold the entire state of all the game worlds and double-check it with the clients actions and state. Clients should be merely the view, a reflection of the server state, but only server should tell what can be done and send appropriate commands to other clients.

For example, in the first variant of your message system, the malicious player could just spam your server with fake "I've build a tower" messages, and by merely replicating 'em, you will spoil other players experience.
> 2 votes

---
Tags: game-design, multiplayer, client-server
---


# Question
Title: Does it make sense to do more calculations in the fragment shader if there are more vertices than pixels?
I'm very new to graphics programming, and as I understand it vertex shaders are called per vertex and fragment shaders are per pixel (ignoring anti-aliasing). When it comes to optimization all sources I refer to say that calculations that could be done in either shaders should be done in the vertex shader, and it makes sense: 5\*8 done 3 times is way better than 5\*8 done 300'000 (640×480 for example).

And that's fine for this scale but the question almost poses itself: what happens when the amount of vertices exceeds the resolution. Here's a practical example: a typical AAA game could have upto 3'000'000 polys rendering on the screen, for the sake of simplicity let's say it's a very detailed triangle strip, that would give it exactly 3'000'002 vertices; while a full HD screen has 1920\*1080 ≈ 2'000'000 pixels. As you can tell a difference of a million operation could be a substantial performance increase.

Is my thought process sound, or does my ignorance of some details leave something to be desired?

# Answer
The calculation falls apart like so:

If every one of those 3 million polygons rasterizes to at least one pixel on average, then doing the operation in the fragment shader still results in it being evaluated (up to) 3 million times, even if your screen or output buffer has only 2 million pixels. If each one rasterizes to two pixels on average, then you might get up to 6 million fragment shader invocations - the screen size doesn't actually cap the number of times you perform this expensive operation.

The reason is overdraw. Your graphics card isn't guaranteed to draw just the frontmost polygon to each pixel. If the objects are drawn out of front-to-back order (say, terrain drawn before a dynamic object sitting on top of the terrain), or if the triangles within a single object aren't ordered front-to-back, or if you have intersecting polygons, or if you're rendering with transparency, you can potentially write to each pixel in the output many times over the course of rendering.

The amount of overdraw you get depends a lot on the contents of the scene and the viewpoint, so it can vary wildly from frame to frame. So if there are expensive operations in the fragment shader that could be in the vertex shader instead, this can contribute to performance-sapping spikes, compared to somewhat more predictable/steady/controllable vertex counts.

For many effects we can mitigate the overdraw problem with various forms of multi-pass rendering: first we render the geometry of the scene using a reasonably cheap shader, paying some overdraw cost where it overlaps itself, but we can accept this cost because each invocation of the fragment shader is inexpensive (usually just writing out some values to a G-buffer). Then we follow up with a screenspace quad that reads this already-rasterized scene information and renders a more complex effect on top of it. Since this is a single layer of geometry rendered in screenspace, we can guarantee it runs only once for each pixel it covers, not once for every layer of geometry that touches that pixel.

This is the basic idea behind Z-prepass & deferred lighting, or screenspace effects like SSAO & post-processing filters.

Looking at it another way though: if you have a triangle that rasterizes to only a few pixels, wouldn't you rather not draw such a triangle at all? It's probably ripe for level-of-detail simplification into a coarser mesh or imposter, or culling due to distance. So if you have so many such tiny triangles that moving operations to the fragment shader seems like a savings, you'll probably get bigger wins by investing in LoD & culling systems to draw fewer tiny triangles.
> 5 votes

---
Tags: shaders, graphics, graphics-programming, fragment-shader, vertex-shader
---


# Question
Title: Is it possible to apply a texture inside a GL_LINE_LOOP?
I am creating a game using Box2D and OpenGL ES 1.1.

I am taking the `b2PolygonShape` vertices and converting them into an OpenGL ES 1.1 `GL_LINE_LOOP`. The debugging view looks great, but now I want to apply textures to the **inside** of the line loop.

Is this possible? I used line loop instead of triangles because I am not sure how to handle complex polygons using triangles.

# Answer
> 6 votes
No.

Only rendered primitives get rasterized and shaded, and when you render using `GL_LINE_LOOP` your primitives are just the lines themselves, not the area enclosed by the lines.

If you want to rasterize and shade the area within the line, you have to render using a solid primitive like GL\_TRIANGLES. If you have complex polygons you will first need to break them down into triangles using some kind of triangulation technique (you can also search this site for other questions about polygon triangulation if you get stuck).

# Answer
> 0 votes
I know this question is pretty old, but I just had exactly the same question ...

And now I found out that everything works fine if one replaces `GL_LINE_LOOP` by `GL_POLYGON`. Nevertheless you have to consider the fact that the tesselation solution is much more efficient.

---
Tags: box2d, opengl-es
---


# Question
Title: What are good algorithms to generate borders / state areas on 2d star maps?
I'm trying to generate a fairly large two-dimensional star map that shows different factions / states, each owning one or more star systems. I'd like to automatically create borders / areas for the factions.

The idea is to essentially go from something like this (the dots represent star systems on a 2d plane, colors are faction affiliations)

to this

Generating maps like this seems like a fairly common requirement, so my actual question is this: **Are there standard algorithms for generating state areas as shown? If so, could you point them out to me? If not, can you think of a good algorithm (basic idea or pseudo code are fine)?**

The algorithm's performance is not a primary concern to me, so I'd rather have a "prettier" map than a faster-to-generate one. This similar question offers an approach that is probably applicable to my problem, albeit with some "prettification" needed: How to create a map from graph

Let me explain what I mean when I say prettier: At the bottom of the linked question, the asker presents her end result after implementing the accepted answer. My first issue here: The areas for nodes #6, #9 and #12 are very small and oddly shaped. Also, instead of the sharp edges, I would prefer a smoother, curved look.

My own ideas so far, including the respective drawbacks / questions I see with them:

* Generate a "convex hull" polygon for each faction, then expand outwards a bit. Problems: No concave features. Also, how do you deal with overlaps?
* Generate a voronoi graph for the dots, then use the voronoi polygon edges between neighboring systems of different factions as borders. Problem: Large polygons at the map edges - how do I identify and fix those?
* Generate a fixed-size polygon for each dot, union all polygons for a single faction (resulting in one large, potentially complex "faction polygon"). Then do something to reconcile overlapping areas between two factions. Problems: How would I do this exactly? Not exactly a trivial process. What if there is overlap between more than two factions?

Your help is appreciated.

---

**Addendum:** After thinking about the first two answers and their respective approaches to solving the problem, I've realized that my requirements above are incomplete.

I have to add that the map can have sparsely populated areas, meaning that there may be an isolated star or cluster of stars. I'd like to display each of those clusters with their own contiguous colored area. Something like this:

I realize that this might necessitate a first step which identifies clusters, and then running the actual algorithm for each of the clusters.

# Answer
> 18 votes
I think the Voronoi idea is a good one. Each star becomes a seed point for Voronoi, and then the Voronoi regions show the areas owned by each faction. However, there are some changes that will make it work better:

1. As you mentioned, there are empty areas that shouldn't be assigned to a faction. Voronoi will create large polygons that extend out to areas where the faction shouldn't reach. To fix this, use a blue noise algorithm like poisson disc to fill the unoccupied space with "owned by no one" stars. Blue noise is random but evenly distributed (it might also be useful for generating your star locations).
2. Voronoi produces blocky regions. To produce rounder cells, replace Voronoi's circumcenter calculation with a centroid calculation. I've written a little about this here with some comparison images.
3. Voronoi produces polygons, but you want round areas. At each corner, there are three polygons. When all three are the same faction, you can leave it alone. When two are the same faction, introduce a quadratic bezier curve that shifts the boundary towards the other faction. When all three factions are different, you can either leave the corner alone, or you can introduce three bezier curves to move all of the boundaries away from one another. I'm not sure which looks better.

Here's the output:

I also wrote a page which lets you paint the regions to see what they'd look like.

# Answer
> 4 votes
One of many methods is an influence map. You can search for specific code implementations, but the basic algorithm is fairly simple.

For each faction object (e.g. star system), assign a positive (hot) value. For all other factions' objects assign a negative (cold) value. The magnitude of hot or cold should be based on how much influence you think the object exerts on its surroundings and neighbors. These values do not have to be proportional if you ultimately want to keep a "dmz" between factions.

Use these details to create a temporary grid (e.g. array) that approximates your map's pixels. You can build such a grid to the resolution you desire including 1:1.

Next, use the heat/field transfer equation to iterate and propagate the faction objects' strengths (heat) against the adversaries' objects' strengths (cold) for each neighbor cell in the grid.

Rinse and repeat for each Faction on your map by creating separate faction grids for each.

Finally, interpolate the faction grids together to produce a contour of influence for each faction. Then transfer that grid back onto your pixel map given the resolution that you used for the grid (adding any faction specific colors, etc).

The art in this process is to determine how much influence each object should have and what game elements you use to quantify that value.

As an aside, the products of this method can be used for all kinds of other things, like your ai decision-making.

---

Additional reference: discussion thread on origins of influence mapping.

# Answer
> 2 votes
You should look into Voronoi diagrams. Here is the definition on wikipedia:

> In mathematics, a Voronoi diagram is a partitioning of a plane into regions based on distance to points in a specific subset of the plane.

The basic points are usually randomly generated and are often called nodes. In your case, each node could be your stars. That way, the faction associated with the stars can be associated with the voronoi cell surrounding the star and when every cell has been calculated, you join those with the same faction together and you should have a pretty neat border around your stars.

FastNoise library has support for Voronoi Diagrams, so maybe you should look at it.

**Smoothing of the regions**

Keep your stars in a « safe array » and use a copy of it where you actually add more points via interpolation of the nearest neighbors and generate the diagram from those points. It should give you smoother regions.

**Other ideas** The fortune algorithm is based on a straight line that sweeps the cartesian plane. An interesting idea would be to use a circle to sweep the plane from the center of your galaxy/space instead, maybe that could lead to some interesting shapes too.

**Geometry manipulation**

Your last idea of combining smaller polygons into bigger ones and then fixing the edges will require advanced spline algorithms to modify the shapes. Not sure if that would make it efficient or good looking. I’m pretty sure that the voronoi diagram with extra tessellation is the way to go as it fixes the edge problem by itself and can even offer some extra data by itself like the distance from the borders (which could be used to determine the zones of conflict between the different factions, the probability of encountering different kinds of ships, etc.)

---
Tags: 2d, algorithm, maps
---


# Question
Title: How do I resolve the error "Trying to send command for object without authority."?
I don't know what I did wrong I tried couple different ways from not using commands to using `SpawnWithClientAuthority`. But It either gives build and compile errors or just the Error in the title

Here the Start function of my player object

```
 void Start () {
    player = isLocalPlayer;
    race = Data.races[(int)selectRace].getInstance();
    clss = Data.classes[(int)selectClass].getInstance();
    health = race.Health * clss.HealthMultiplyer;
    speed = race.Speed * clss.SpeedMultiplyer;
    armor = race.Armor * clss.ArmorhMultiplayer;
    energy = race.Energy * clss.EnergyMultiplayer;
    skills.AddRange(race.RaceSkills);
    skills.AddRange(clss.ClassSkills);

        Data.entities.Add(this);

    Debug.Log(isLocalPlayer);

    if (!isLocalPlayer)
        return;
    int enID = Data.entities.IndexOf(this);
    foreach (Skill s in skills)
        s.CmdSpawn(enID);

}

```

And here is the spawn functions from skills I try to spawn

```
[Command]
public override void CmdSpawn(int enID)
{
    setEntity(Data.entities[enID]);
    Debug.Log("Spawned");
    dir = getEntity().lookingAt;
    gameObject.transform.position = getEntity().transform.position + dir * 0.65f;
    transform.up = dir;
    NetworkServer.Spawn(gameObject);
}

```

and

```
[Command]
public override void CmdSpawn(int enID)
{
    setEntity(Data.entities[enID]);
    dir = getEntity().lookingAt;
    transform.up = dir;
    dir = new Vector3(dir.z, dir.y, -dir.x);
    gameObject.transform.position = getEntity().transform.position + dir * 0.65f;

    NetworkServer.Spawn(gameObject);

}

```

If you can help, thank you ^.^

# Answer
> 1 votes
Your problem here is this line:

```
s.CmdSpawn(enID);

```

You are performing a Command on your Skills from the `PlayerController` which your player doesn't seem to have authority over. There are a few ways to fix this. Either you can assign authority of the skills to the player something like:

```
s.GetComponent<NetworkIdentity>().AssignClientAuthority(connectionToClient);

```

OR

I would personally change around your Spawn method so that it is on your `PlayerController` and instead of just passing in the `enID`, you should pass in the `Skill s` and the `enID`

```
CmdSpawn(s, enID);

```

# Answer
> 0 votes
Well this is the problem which i usally get when first i were learning UNET. So here is the general answer and i am sure it will solve your problem once you get that How UNET actually work.

Beside your code fragment, the error

> Trying to send command for object without authority.

clearly means that you are sending Command request from an object whose authority you don't have.

So What it means and how to resolve it you can see my answer **Here**.

According to your code fragment, Before sending the command (or executing command function), Assign authority of that object(where your script attached) to your Player.

**hope that it will make sense and solve the problem. Happy!**

---
Tags: unity, c#, networking, multiplayer, unet
---


# Question
Title: How to use a large number of different textures with a shader?
I need to be able to compile an ".hlsl, .fx" shader in my DirectX app. The issue is that, with the code below, I can only specify 6 textures by their default path directory.

I don't want this - I want to be able to set one path to the directory containing all of my textures, then compile my shader and see the shader effect on all those 50 textures.

I am using DirectX June 2010 and using Direct3D11 and Visual Studio 2015.

```
#define NUM_TEXTURES 7
DETAIL_TESSELLATION_TEXTURE_STRUCT DetailTessellationTextures[NUM_TEXTURES +
1] =
{
//    DiffuseMap              NormalHeightMap                 DisplayName,
fHeightScale fBaseTextureRepeat fDensityScale fMeaningfulDifference
{ L"Textures\\rocks.jpg",    L"Textures\\rocks_NM_height.dds",  L"Rocks",
10.0f,       1.0f,              25.0f,        2.0f/255.0f },
{ L"Textures\\stones.bmp",   L"Textures\\stones_NM_height.dds", L"Stones",
5.0f,        1.0f,              10.0f,        5.0f/255.0f },
{ L"Textures\\wall.jpg",     L"Textures\\wall_NM_height.dds",   L"Wall",
8.0f,        1.0f,              7.0f,         7.0f/255.0f },
{ L"Textures\\wood.jpg",     L"Textures\\four_NM_height.dds",   L"Four
shapes", 30.0f,       1.0f,              35.0f,        2.0f/255.0f },
{ L"Textures\\concrete.bmp", L"Textures\\bump_NM_height.dds",   L"Bump",
10.0f,       4.0f,              50.0f,        2.0f/255.0f },
{ L"Textures\\concrete.bmp", L"Textures\\dent_NM_height.dds",   L"Dent",
10.0f,       4.0f,              50.0f,        2.0f/255.0f },
{ L"Textures\\wood.jpg",     L"Textures\\saint_NM_height.dds",  L"Saints" ,
20.0f,       1.0f,              40.0f,        2.0f/255.0f },
{ L"",                       L"",                               L"Custom" ,
5.0f,        1.0f,              10.0f,        2.0f/255.0f },
};
DWORD                               g_dwNumTextures = 0;
ID3D11ShaderResourceView*
g_pDetailTessellationBaseTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*
g_pDetailTessellationHeightTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*
g_pDetailTessellationDensityTextureRV[NUM_TEXTURES+1];
ID3D11ShaderResourceView*           g_pLightTextureRV = NULL;
WCHAR
g_pszCustomTextureDiffuseFilename[MAX_PATH] = L"";
WCHAR
g_pszCustomTextureNormalHeightFilename[MAX_PATH] = L"";
DWORD                               g_bRecreateCustomTextureDensityMap  =
false;

```

# Answer
> 1 votes
Normally your textures are loaded by the program and not by the shader directly. You then set the parameters of the GPU in some fashion such as:

```
m_texturePtr = m_effect->GetVariableByName("shaderTexture")->AsShaderResource();

```

which I grabbed from this tutorial as an example: http://rastertek.com/dx10tut48.html

The Graphics Card isn't made to randomly read from an unlimited numbers of textures at a time. Normally you will batch all the objects who require the same textures into the same call to the graphics library so that you don't have to keep swapping textures a lot.

If you have an object or collection of objects that use many different textures but need to be drawn in a single batch, then it's conventional to pre-combine those textures into a texture atlas or array texture. This is a single logical texture as far as the shader is concerned, and texture coordinates are used to pick out the particular texture you wanted from the larger collection.

---

In your case, simply make it so that before you render a model, you send the necessary texture to the graphics library first. The below is my code (C# monogame; using DX11 shaders)

```
public static void BatchDraw(Effect effect, bool clear)
        {
            // walk through each texture type
            for (int j=0; j < (int)TextureType.MAX_TEXTURE; j++)
            {
                // derive the batch
                var currBatch = ObjectBatcher[j];

                // create a quad that is used for centering and sizing the texture
                var originalQuad = TextureSizes[j];

                // set the texture of the effect so that when we call draw, the correct type of texture is drawn
                //effect.Texture = TextureArray[j];
                effect.Parameters["colorTexture"].SetValue(TextureArray[j]);

                // for each of the "models", place it in 3-space and send the data to the graphics device
                var len = currBatch.PsuedoCount;
                for(int i=0; i<len; i++)
                {
                    AdjustModel(
                        // The offset of the texture to adjust the other vertices
                        originalQuad,
                        // The vertices that will be filled and then drawn
                        quadVertices,
                        // The quad will be centered on this obj's position and spun by this obj's rotation
                        currBatch[i]);

                    foreach (var pass in effect.CurrentTechnique.Passes)
                    {
                        pass.Apply();

                        // TODO: Look into the offset. Possibly a way to reduce my own computation?
                        myGD.DrawUserPrimitives(
                            // We’ll be rendering two triangles
                            PrimitiveType.TriangleList,
                            // The array of verts that we want to render
                            quadVertices,
                            // The offset, which is 0 since we want to start
                            // at the beginning of the floorVerts array
                            0,
                            // The number of triangles to draw
                            2);
                    }

                }

            }
        }

```

NOTE: I currently pass in each quad (my "models"), but instead I should pass in an array that describes all of those batched models at a time.

---
Tags: directx11
---


# Question
Title: Instantiated Object returns Null outside Start method
I'm attempting to access an instantiated 'goalTemp' GameObject from a different function inside the same script. I'm getting the information in the Start method, assigning the GameObject find/get component script code to a variable. When I'm printing the results outside the Start method, it returns null, even though the 'goal' variable is public.

```
void Start()
 {
     GameObject goalTemp = (GameObject)Instantiate(goal,respawnGoalLocation[CreateLevel.currentLevel-1],Quaternion.identity);
     goal = goalTemp.gameObject;
 }

```

---

```
public void Explode()
 {
     Debug.Log(goal);
     Instantiate(rockParticle, goal.transform.position, goal.transform.rotation);
     Instantiate(explosionParticle, goal.transform.position, goal.transform.rotation);
 }

```

---

What am I doing wrong here? Thanks for your time!

# Answer
> 2 votes
I cannot see why your code would not work outside of setting the goalTemp(GameObjects) variable to the .gameObject property since its already a GameObject, I am unsure if this would cause any issues though as that should just reference the same thing.

I set up a quick plain simple demo to show you how I would do it.

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

public class Test : MonoBehaviour {

    //the prefab we will spawn
    public GameObject prefab;
    //a reference to this instance, normally if there's more than one you put them in a list or array or whatever
    private GameObject prefabInstance;

    // Use this for initialization
    void Start ()
    {
        //assign the prefabinstance here
        prefabInstance = Instantiate(prefab, Vector3.zero, Quaternion.identity) as GameObject;
    }

    // Update is called once per frame
    void Update ()
    {
        //debug it on space pressed
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log(prefabInstance);
        }
    }
}

```

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


# Question
Title: How can I implement online high score in LibGDX?
I found some posts that said to use Google Play Services. What about other platforms? Is their some libgdx library that I can use to implement it in core section or do I need to write separate score implementation to each platform?

# Answer
have you tried using App42 JAVA SDK? Here\[http://api.shephertz.com/tutorial/Getting-Started-Java/?index=gs-javasdk&sdk=java\] is the documentation for the same and then simply use leaderboard API documentation to implement leaderboards\[http://api.shephertz.com/app42-docs/leaderboard-service/?sdk=java\] in your libGDX games.
> 0 votes

# Answer
Unless you know of a third-party service for leader boards that can be used on all devices, you'll have to write platform specific code. The wiki has a tutorial on that.
> -1 votes

---
Tags: libgdx, leaderboards
---


# Question
Title: maya: cannot rotate ik control in command
I use maya default human ik example, see my gif, when i rotate in viewport, rotate work, but when i undo and rotate with same command in script editor, it cannot rotate, how to rotate ik control in command

I try maya 2018 and maya lt 2018, it has same problem

# Answer
update 18-6-22 I find the solution, maya default doesn't show all commands, I should script editor \> history \> echo all commands

I need more code to change ik control in "control rig" status I select a ik control(like right arm), and run following python code:

```
import maya.mel as mel
import maya.cmds as cmds

mel.eval("hikManipStart 1 1")

cmds.rotate(0,0,73,r=True)

mel.eval("hikManipStop") //

```

it work

My tmp solution is: in human ik toolwin, set "Source" to none, and rotate original joint will work
> 1 votes

---
Tags: maya
---


title: Indices of a obj file format

text:
# Question
Title: Indices of a obj file format
If I have the obj file like below, what would be my indices. How do I find the indices? What would be the order of the indices also.(the triangles)

```
v 1.000000 0.000000 -1.000000

v -1.000000 0.000000 -1.000000

v 1.000000 0.000000 1.000000

v -1.000000 0.000000 1.000000

vt 0.9562 0.0001

vt 0.0001 0.9999

vt 0.0001 0.0001

vt 0.9562 0.9999

vn 0.0000 1.0000 0.0000

f 2/1/1 3/2/1 1/3/1

f 2/1/1 4/4/1 3/2/1

```

# Answer
Wavefront files don't contain the indices in a traditional sense. The lines starting with "f" are the closest one you get. Each one of those marks a triangle with 3 vertices. These vertices are represented in the `v/vt/n` format. The first value is the id of the vertex, the second is the uv coordinate and the third is the normal.

Neither D3D, nor OpenGL can deal with a format like this, so you'll have to manually convert it to the preferred format.

This makes the already pretty large file a bit smaller, because for example a flat shaded cube would require 24 different vertex declarations if you use the traditional way, but only 8 this way.
> 0 votes

# Answer
```
//================needed classes or structs =================
   public struct Vertex
    {
        private Vector3 position;
        private Vector3 normal;
        private Vector2 textureCoords;
        public Vertex(Vector3 position, Vector3 normal, Vector2 textureCoords )
        {
            this.normal = normal;
            this.position = position;
            this.textureCoords = textureCoords;

        }

        public static int Size => (3 + 3 + 2) * 4;

    }

 public class OBJLoader
    {

   public static RawModel LoadObjModel(String name)
        {
            string path = @"Models\" + name + ".obj";
            List<Vertex> Vertices = new List<Vertex>();
            List<string> VertexString = new List<string>();
            List<int> Indices = new List<int>();
            List<Vector3> Positions = new List<Vector3>();
            List<Vector2> TextureCoordinates = new List<Vector2>();
            List<Vector3> Normals = new List<Vector3>();
            List<string> Lines = new List<string>();
            string Line;
            System.IO.StreamReader file = new System.IO.StreamReader(path);
            while ((Line = file.ReadLine()) != null)
            {
                Lines.Add(Line);
            }
            file.Close();
            string FacePattern = "^f .*$";
            string PositionPattern = "^v .*$";
            string TextureCorrdinatesPattern = "^vt .*$";
            string NormalPattern = "^vn .*$";
            string FloatingPointPattern = @"[-+]?[0-9]*\.?[0-9]+";
            string VertexFacePattern = @"[0-9]*/[0-9]*/[0-9]*";
            string NumberPatten = @"\d+";
            MatchCollection FloatingPoints = null;
            MatchCollection FaceVertices = null;
            Lines.Where(L => Regex.IsMatch(L, PositionPattern)).ToList().ForEach(L =>
            {
                FloatingPoints = Regex.Matches(L, FloatingPointPattern);
                Positions.Add(new Vector3(float.Parse(FloatingPoints[0].ToString()), float.Parse(FloatingPoints[1].ToString()), float.Parse(FloatingPoints[2].ToString())));
            });
            Lines.Where(L => Regex.IsMatch(L, NormalPattern)).ToList().ForEach(L =>
            {
                FloatingPoints = Regex.Matches(L, FloatingPointPattern);
                Normals.Add(new Vector3(float.Parse(FloatingPoints[0].ToString()), float.Parse(FloatingPoints[1].ToString()), float.Parse(FloatingPoints[2].ToString())));
            });
            Lines.Where(L => Regex.IsMatch(L, TextureCorrdinatesPattern)).ToList().ForEach(L =>
            {
                FloatingPoints = Regex.Matches(L, FloatingPointPattern);
                TextureCoordinates.Add(new Vector2(float.Parse(FloatingPoints[0].ToString()), float.Parse(FloatingPoints[1].ToString())));
            });
            Lines.Where(L => Regex.IsMatch(L, FacePattern)).ToList().ForEach(L =>
            {
                FaceVertices = Regex.Matches(L, VertexFacePattern);
                VertexString.Add(FaceVertices[0].ToString());
                VertexString.Add(FaceVertices[1].ToString());
                VertexString.Add(FaceVertices[2].ToString());
            });
            List<string> AllVerticesStrings = new List<string>();
            AllVerticesStrings = VertexString;
            VertexString = VertexString.Distinct().ToList();
            MatchCollection indices = null;
            VertexString.ForEach(Vertex =>
            {
                indices = Regex.Matches(Vertex, NumberPatten);
                Vertices.Add(new VertexData.Vertex(Positions[int.Parse(indices[0].ToString()) - 1], Normals[int.Parse(indices[2].ToString()) - 1], TextureCoordinates[int.Parse(indices[1].ToString()) - 1]));
            });
            Dictionary<string, int> IndexKeyDictionary = new Dictionary<string, int>();
            for (int i = 0; i < VertexString.Count; i++)
            {
                IndexKeyDictionary.Add(VertexString[i], i);
            }
            AllVerticesStrings.ToList().ForEach(Key => Indices.Add(IndexKeyDictionary[Key]));
            return new RawModel(Vertices.ToArray(), Indices.ToArray());
        }

}

```
> -1 votes

---
Tags: c++, directx, obj
---


# Question
Title: Can't Get .enabled to Work for Children Sprites. What Gives?
So I have an object with a few children. I want to be able to disable/enable 2 of their SpriteRenderers via one of my scripts. I feel like I'm doing things right, but apparently I'm not. And yes, my game objects have the appropriate tags that are being searched for in my code. I'll paste the relevant bits of code below:

```
public bool isAiming = false;
Animator playerAnim;

GameObject arm;
GameObject weapon;

SpriteRenderer armRenderer;
SpriteRenderer weaponRenderer;

void Start()
 {
     playerAnim = gameObject.GetComponent<Animator>();

     arm = GameObject.FindGameObjectWithTag("Arm");
     weapon = GameObject.FindGameObjectWithTag("EquippedWeapon");

     armRenderer = arm.GetComponent<SpriteRenderer>();
     weaponRenderer = weapon.GetComponent<SpriteRenderer>();
 }

void Update()
 {
     CheckIfAiming();
 }

void CheckIfAiming()
 {
     if (Input.GetButton("Fire2")) // Holding right click
     {
         isAiming = true;

         armRenderer.enabled = true;
         weaponRenderer.enabled = true;

         playerAnim.SetBool("isAiming", isAiming);
     }
     else
     {
         isAiming = false;

         armRenderer.enabled = false;
         weaponRenderer.enabled = false;

         playerAnim.SetBool("isAiming", isAiming);
     }
 }

```

What gives? I want to just enable the sprite rendering when I hold down the right mouse click. SetActive(false/true) is not an option as I still want code to affect them while they're not visible.

Am I just trying to access the SpriteRenderers incorrectly?

# Answer
Finally figured it out! Pheonix2105's answer wasn't quite what I was looking for, but it quickly led me to find the right answer.

Here's what I used:

```
Renderer[] renderChildren = GetComponentsInChildren<Renderer>();

int i;
for(i = 1; i < renderChildren.Length; ++i)
{
    renderChildren[i].renderer.enabled = true;
}

```

And then when I wanted the SpriteRenderers to be disabled I did the same thing, except I set it to false. I started i equal to 1 so that it would skip the parent object's renderer and only change the children.
> 0 votes

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


title: Enemy walks to the nearest player?

text:
# Question
Title: Enemy walks to the nearest player?
I'm trying making my enemy goes to the nearest player to him but what i get is kind of hesitated or shaking. I think is from the first line on Update but i don't know how to solve it. Here is my script

```
private Animator enemy_anim;
private NavMeshAgent mAgent;
private GameObject[] player;
public GameObject[] dead_point;
public int farPoint, dead_point_number,player_number;
public float dist;
public bool enemt_run, enemy_atack = false;

void Start()
{
    mAgent = GetComponent<NavMeshAgent>();
    enemy_anim = GetComponent<Animator>();
    player = GameObject.FindGameObjectsWithTag("Player");
    dead_point = GameObject.FindGameObjectsWithTag("dead_point"); // 3 points
    enemy_dirction();

}

void Update()
{
    player_number = Random.Range(0,player.Length);
    dead_point_number = dead_point.Length;
    dist = Vector3.Distance(transform.position, player[player_number].transform.position);

    if (player != null && dist <= 5.1f)
    {
        mAgent.destination = player[player_number].transform.position;
        if (dist < 1.2f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
        }
    }
    else
    {
        if (dead_point_number > 0)
        {
            mAgent.destination = dead_point[farPoint].transform.position;
        }
        else
        {
            mAgent.destination = player[player_number].transform.position;

        }
        if (mAgent.remainingDistance <= 1.5f)
        {
            enemy_atack = true;
        }
        else
        {
            enemy_atack = false;
            enemt_run = true;

        }
    }

    mAgent.speed = 1.0f;

    enemy_anim.SetBool("run", enemt_run);
    enemy_anim.SetBool("attack", enemy_atack);
}// end update

void enemy_dirction()
{
    if (dead_point_number > 0)
    {
        farPoint = Random.Range(0, dead_point.Length);
        mAgent.destination = dead_point[farPoint].transform.position;
    }
    else
    {

    }
}

```

# Answer
> 3 votes
Every Update(), which is once per frame, you pick a new target with `player_number = Random.Range(0,player.Length);`, and if it's closer than 5.1 or if there are no dead\_points, you steer towards it.

This means that if you are within 5.1 units of multiple enemies or if there are no dead\_points, you bounce randomly between different targets every frame, causing a jitter.

You should only update `player_number` if:

1. you currently have no target and there is a close by target
2. OR your target becomes invalid, i.e. it died, it moved too far away, etc.

---

Edit: pick closest enemy each frame (still a suboptimal strategy, but it should eliminate the jittering)

```
player_number = 0;
for(int i=1; i<player.Length; i++) {
   if (Vector3.Distance(transform.position, player[i].transform.position) <
       Vector3.Distance(transform.position, player[player_number].transform.position)) {
       player_number = i;
   }
}

```

---
Tags: unity
---


# Question
Title: Dissolve object starting from the bottom
I'm currently getting into using the new "Unity Shader Graph"s and have made an OK dissolve shader that looks like this:

My next goal is to move this effect so the object dissolves bottom-up. This is where I'm stuck. I tried blending this effect with another effect that just fades the object from the bottom up but this does not create the effect I am looking for (#1 is the fade effect, #2 is the two shaders blended together):

The end effect should look something like this:

**How can I achieve this effect?** Answers do not have to be specific to Unity and a good answer should include the thought-process to creating this effect, not just code or pictures of a shader graph.

# Answer
> 3 votes
This Ominous Games dev blog post has a rather detailed explanation & code samples that acheives a similar looking effect.

**Summary of steps:**

* Use a grayscale noise texture to fade mesh alpha based on an interpolation factor.
* Use model-space fragment position to control dissolution based on a specified direction vector.
* Combine texture- and geometry-based alpha/clipping control to create a hybrid dissolve effect.
* Add in a glow effect by "predicting" the next areas to dissolve and adjusting model emission accordingly.

---
Tags: unity, shaders, unity-shader-graph
---


title: Why the plane is not black?

text:
# Question
Title: Why the plane is not black?
I created a new material and changed the material colors to make it black: R,G,B all value is 0 and A value is 255

The shader on the Plane is: Legacy Shaders/Transparent/Diffuse

But the Plane seems to be transparent.

The main goal is put a plane in front of the camera the FPSCamera and then using a script to fade in/out the alpha color.

# Answer
If you are trying to use the plane as a screen in front of the player instead use a UI pannel. They are easyer to manage, less likely to lag and more efficient as they don't take place in the 3D world.
> 4 votes

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