Splint warns undefined storage. Sanity check please? - c

I'm working on a game at the moment, and I'm having an issue with splint on the following code to add new enemy structs to my linked list.
void generate_enemy(enemy_struct* enemy)
{
enemy_struct* new_enemy;
// Make sure the incoming enemy isn't null.
if(enemy == NULL)
{
return;
}
// Run through till we find the last enemy in the list.
while(NULL != enemy->next_enemy)
{
enemy = enemy->next_enemy;
}
// Create a new enemy and point the last enemy to it.
new_enemy = malloc(sizeof(enemy_struct));
// If we're out of memory, don't bother making the new enemy.
if(NULL == new_enemy)
{
return;
}
else
{
// Initialise the new enemy.
new_enemy->location = 1;
new_enemy->motion = ENEMY_STATIC;
new_enemy->dead = false;//true;
// Ensure it carries the last enemy flag.
new_enemy->next_enemy = NULL;
// Put new enemy in previous enemy.
enemy->next_enemy = new_enemy;
}
return;
}
Splint gives the warning:
enemy.c: (in function generate_enemy)
enemy.c:57:12: Storage *(enemy->next_enemy) reachable from parameter contains 4
undefined fields: location, motion, dead, next_enemy
Storage derivable from a parameter, return value or global is not defined.
Use /*#out#*/ to denote passed or returned storage which need not be defined.
(Use -compdef to inhibit warning)
Line 57 is the last return in the function.
Now, I'm fairly confident my code cannot return undefined values, as I either set all fields, or don't change anything and drop out.
Is there some case I'm missing out where I send back stuff undefined? If not, what's the best way to stop splint giving this warning?

Related

Is there a way to prevent node glitching shaking during collisions?

The function (code below) simply moves a character node (contact.nodeA) back after it has penetrated a collision node (contact.nodeB) that it's not allowed to pass through.
In a scenario where a user is trying to move the character node (contact.nodeA) while it's stuck in a corner, etc. the scene/character repeatedly shakes/glitches while its position is repeatedly being moved back away from contact.nodeB at 60hz.
Is it possible with SCNPhysicsContact in SceneKit to prevent contact.nodeA from moving forward into contact.nodeB in the first place? (ie., why does "contact.penetrationDistance" occur at all? Why can't we just be alerted when a physics contact has begun w/o contact.nodeA actually moving forward into contact.nodeB? We are, after all, catching the contact on "didBegin" yet there's already penetration that we have to readjust.)
(When a user is trying to move the character node while it's "stuck" in a corner, or between two rocks, etc.)
Or, is there another solution to prevent the repeated shaking of contact.nodeA as its position is repeatedly being readjusted to compensate for its penetration into contact.nodeB? Transform instead of position change?
I've already tried setting momentum to 0.0 and removing all animations, etc. However, since contact is still occurring with contact.nodeB, contact.nodeA cannot be moved away since its momentum is still being stopped during contact with nodeB.
Any help would be greatly appreciated.
private func characterNode(_ characterNode: SCNNode, hitWall wall: SCNNode, withContact contact: SCNPhysicsContact) {
if characterNode.name != "collider" { return }
if maxPenetrationDistance > contact.penetrationDistance { return }
var characterPosition = float3(characterNode.parent!.position)
var positionOffset = float3(contact.contactNormal) * Float(contact.penetrationDistance)
maxPenetrationDistance = contact.penetrationDistance
characterPosition.y += positionOffset.y
replacementPositions[characterNode.parent!] = SCNVector3(characterPosition)
}
extension GameViewController : SCNPhysicsContactDelegate {
func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {
if gameState != .playing { return }
contact.match(BitmaskWall) {
(matching, other) in
if other.name == "collider" {
self.characterNode(other, hitWall: matching, withContact: contact)
}
}
}

Instantiation attempted on a non-constructor

I'm trying to make a bomb catching game (I'm actually using the code from the AS3 Classroom in a Book on arrays). As soon as I changed the word fruit to bomb in the code I got error 1007. With the exception of changing basket_mc to eod_mc and fruit to bomb (I used command-F and replaced with case sensitive on) I haven't changed much. It worked with eod_mc, but doesn't with bomb.
var bombArray:Array = new Array(bomb);
var bombsOnstage:Array = new Array();
var bombsCollected:int = 0;
var bombsLost:int = 0;
for (var i:int = 0; i<20; i++) {
var pickBomb = bombArray[int(Math.random() * bombArray.length)];
var bomb:MovieClip = new pickBomb();
addChild(bomb);
bomb.x = Math.random() * stage.stageWidth-bomb.width;// bomb.width is subtracted from the random x position to elimate the slight possibility that a clip will be placed offstage on the right.
bomb.y = Math.random() * -500;
bomb.speed = Math.random() * 15 + 5;
bombsOnstage.push(bomb);
}
eod_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragEod);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);
function dragEod(e:Event):void {
eod_mc.startDrag();
}
function dragStop(e:Event):void {
eod_mc.stopDrag();
}
stage.addEventListener(Event.ENTER_FRAME, catchBomb);
function catchBomb(e:Event):void {
for (var i:int = bombsOnstage.length-1; i > -1; i--) {
var currentBomb:MovieClip = bombsOnstage[i];
currentBomb.y += currentBomb.speed;
if (currentBomb.y > stage.stageHeight - currentBomb.height) {
currentBomb.y = 0 - currentBomb.height;
bombsLost++;
field2_txt.text = "Total Bombs Detonated: " + bombsLost;
}
if (currentBomb.hitTestObject(eod_mc)) {
bombsCollected++;
removeChild(currentBomb);
bombsOnstage.splice(i,1);
field1_txt.text = "Total Bombs Caught: " + bombsCollected;
if (bombsCollected >= 20) {
eod_mc.gotoAndStop(20);
} else if (bombsCollected > 15) {
eod_mc.gotoAndStop(15);
} else if (bombsCollected>10) {
eod_mc.gotoAndStop(10);
} else if (bombsCollected>5) {
eod_mc.gotoAndStop(5);
}
}
}
if (bombsOnstage.length <= 0) {
field1_txt.text = "You Win! You have defused the bombs.";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
}
if (bombsLost >= 20) {
field1_txt.text = "Sorry you lose. You have lost your foot!";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
for (var j:int = bombsOnstage.length-1; j > -1; j--) {
currentBomb = bombsOnstage[j];
removeChild(currentBomb);
bombsOnstage.splice(j,1);
}
}
}
Maybe to avoid making your programming life more twisted than it is now...
There are objects and classes in programming, a class is a description of a set of objects, say "table" (or, as it's better to differ in names for classes and variables, "Table", first letter capitalized) is a name of a class. An instance or an object is a structure that belongs to one or more classes, with Object being the topmost, as everything in programming is either an object or a "simple variable", that is, a number, a true/false, a string of characters (these are object types in AS3 too, though, Number, Boolean, String, but these generally not need to be instantiated via new) or probably some other simple type I don't remember right now.
Classes have properties and methods. A property is something that can be requested off any object of the class, say "height" for tables. Properties can be of any type, including nested objects, depending on what your base class is. Say stage in AS3 is a property of any DisplayObject which is used to get the only Stage object there is at runtime[1]. Methods are what any object of a class can be told to do. Say, bombs fall, explode, MovieClips can be told to stop(), etc. You write class code keeping in mind that all of the objects of this class will have to behave exactly like you've written, but since they can differ in properties, you can give them conditional behavior. For example, if a bomb has already exploded, it cannot blow up once more.
A variable, whether a property or a standalone var (if you declare one in a function) is a reference to an object of a given type. Say var i:int refers to some kind of an integer. Simple type vars are containers instead, that is, i=2; will place a 2 in the referred integer, and i=j; will copy the value from j into i, while var theStage:Stage=this.stage will instead create a reference to an existing object, and if that object will change, the reference will give you the changed object instead of its previous state. An array is a collection of variables, reachable by indexes, in AS3 they don't have to be of one type, and a Vector is a typed array.
Next, the lifetime of objects. An object only lives while there's an active reference to it, whether in a property of another alive object, or in a visible variable, or in an event listener (AS3 specific). An object is created via new ClassName(<parameters>), lives while you can reach it somehow, and is destroyed once you have no active links to it and Flash player decides to run garbage collector. Prior to this programmers had to deallocate objects themselves, a rudiment can be seen at BitmapData.dispose(). So, in order to avoid Flash player to run out of free memory, take full control over creation and destruction of links. You don't need to care for simple vars, they are being cared for by Flash player.
A lot of basic functions for interactions has already been implemented in AS3, look for them and examples of how they work in Adobe's manual, navigate through packages in the lower left, most of the interactive stuff is in flash.display package, refer to other packages as necessary.
Hope this will bring you some insight into programming basics.
[1]: There is one stage unless you're doing a load of an SWF, then there could be more, one Stage per one SWF.

Array throwing exception

I can't seem to put my finger on this and why the array is not being initialized.
Basically I am coding a 2d top down spaceship game and the ship is going to be fully customizable. The ship has several allocated slots for certain "Modules" (ie weapons, electronic systems) and these are stored in an array as follows:
protected Array<Weapon> weaponMount;
Upon creating the ship none of the module arrays are initialized, since some ships might have 1 weapon slot, while others have 4.
So when I code new ships, like this example:
public RookieShip(World world, Vector2 position) {
this.width = 35;
this.height = 15;
// Setup ships model
bodyDef.type = BodyType.DynamicBody;
bodyDef.position.set(position);
body = world.createBody(bodyDef);
chassis.setAsBox(width / GameScreen.WORLD_TO_BOX_WIDTH, height / GameScreen.WORLD_TO_BOX_HEIGHT);
fixtureDef.shape = chassis;
fixtureDef.friction = 0.225f;
fixtureDef.density = 0.85f;
fixture = body.createFixture(fixtureDef);
sprite = new Sprite(new Texture(Gdx.files.internal("img/TestShip.png")));
body.setUserData(sprite);
chassis.dispose();
// Ship module properties
setShipName("Rookie Ship");
setCpu(50);
setPower(25);
setFuel(500);
setWeaponMounts(2, world);
setDefenseSlots(1);
addModule(new BasicEngine(), this);
addModule(new BasicBlaster(), this);
// Add hp
setHullHP(50);
setArmorHP(125);
setShieldHP(125);
}
#Override
public void addModule(Module module, Ship currentShip) {
// TODO Auto-generated method stub
super.addModule(module, currentShip);
}
#Override
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
// super.setWeaponMounts(weaponMounts, world);
}
#Override
public String displayInfo() {
String info = "Everyones first ship, sturdy, reliable and only a little bit shit";
return info;
}
When I set the number of weapon mounts the following method is called:
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
}
This basically initializes the array with a size (weapon mounts available) to whatever the argument is. Now to me this seems fine but I have setup a hotkey to output the size of the Array, which reports zero. If I try to reference any objects in the array, it throws an outofbounds exception.
The addModule method adds to the array as follows:
public void addModule(Module module, Ship currentShip) {
currentShip.cpu -= module.getCpuUsage();
currentShip.power -= module.getPowerUsage();
if(module instanceof Engine){
engine = (Engine) module;
}else if(module instanceof Weapon){
if(maxWeaponMounts == weaponMount.size){
System.out.println("No more room for weapons!");
}else{
maxWeaponMounts += 1;
weaponMount.add((Weapon)module);
}
}
}
My coding ain't great but heh, better than what I was 2 month ago....
Any ideas?
First of all, You should avoid instanceof. It's not a really big deal performance-wise, but it always points to problems with your general architecture. Implement two different addModule methods. One that takes a Weapon, and one that takes an Engine.
Now back to topic:
else if(module instanceof Weapon){
if (maxWeaponMounts == weaponMount.size) {
System.out.println("No more room for weapons!");
} else{
maxWeaponMounts += 1;
weaponMount.add((Weapon)module);
}
}
It looks like you use maxWeaponMounts as a counter instead of a limit. That's why I assume that it will initially be 0. The same holds for Array.size. It is not the limit, but size also counts how many elements the Array currently holds. Thus you will always have (maxWeaponMounts == weaponMount.size) as 0 == 0 and you will not add the weapon to the array. It will always stay empty and trying to reference any index will end in an OutOfBoundsException.
What you should actually do is using maxWeaponMounts as a fixed limit and not the counter.
public void setWeaponMounts(int weaponMounts, World world) {
weaponMount = new Array<Weapon>(weaponMounts);
maxWeaponMounts = weaponMounts;
}
else if(module instanceof Weapon){
if (weaponMount.size >= maxWeaponMounts) {
System.out.println("No more room for weapons!");
} else{
weaponMount.add((Weapon)module);
}
}

Trouble with array order

I have a couple of if statements within a timer function, checking if the enemy's hp is 0. The enemies are added into an array. When one enemy hp hits 0, they are taken from the array and removed. When the array length is 0, the game goes to the next level. For some reason, when the first enemy's hp reaches 0, then it automatically goes to the next level without even checking the other enemy's hp. It worked on the first level, where I only had 1 enemy, but the second level, I have two enemies. I would have to defeat the second enemy, then the first in order for it to go to the next level. I think it may have something to do with the first enemy being the first in the array. Any ideas on how I can change the code to make it disregard the order in which enemy is defeated first?
public var enemy:Enemy = new Enemy();
public var enemy2:Enemy = new Enemy();
public var enemyArray:Array = [];
Level Timer(Timer that sets up the level, runs once):
if (level.levelNumber == 1)
{
enemyArray.push(enemy);
addChild(player);
addChild(enemy)
enemy.enemyMoveTimer.start();
enemy.enemyAttackTimer.start();
onGameTimer.start();
}
if (level.levelNumber == 2)
{
enemyArray.push(enemy, enemy2);
addChild(player);
addChild(enemy)
addChild(enemy2)
enemy.enemyMoveTimer.start();
enemy.enemyAttackTimer.start();
enemy2.enemyMoveTimer.start();
enemy2.enemyAttackTimer.start();
onGameTimer.start();
}
Game timer(timer that checks the enemy lives, keeps running):
if (enemyArray.length == 0)
{
trace("NEXT LEVEL");
removeChild(player);//remove player from the current level
onLevelTimer.removeEventListener(TimerEvent.TIMER, timerLevel);
levelNumber += 1;
onLevelTimer.addEventListener(TimerEvent.TIMER, timerLevel);
onGameTimer.stop();
}
if (enemy.enemyHP <= 0)
{
enemy.enemyHP = 0;
enemy.enemyMoveTimer.stop();
enemy.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(0,1);
try
{
removeChild(enemy)
}
catch (e:ArgumentError){
}
}
if (enemy2.enemyHP <= 0)
{
enemy2.enemyHP = 0;
enemy2.enemyMoveTimer.stop();
enemy2.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(1,1);
try
{
removeChild(enemy2)
}
catch (e:ArgumentError) {
}
}
There's more code there that could be the cause of the issue, so I'm just going to assume that it looks something like what I've written below. It also dispenses with multiple if statements, in favor of simply iterating over your enemyArray, checking each as you wanted to (behold the power of loops!).
var enemyMoveTimer:Timer = new Timer(1000, 0);
enemyMoveTimer.addEventListener(TimerEvent.TIMER, enemyTimerListener);
enemyMoveTimer.start();
var enemyArray:Array = [new Enemy("enemy1"), new Enemy("enemy2")];
function enemyTimerListener(e:Event):void {
for (var i:String in enemyArray) {
var enemy:Enemy = enemyArray[int(i)];
if (enemy.enemyHP <= 0) {
enemy.enemyMoveTimer.stop();
enemy.enemyAttackTimer.stop();
trace("DEAD");
enemyArray.splice(int(i),1);
if (enemy.parent != null) {
removeChild(enemy);
}
}
}
}
What isn't shown is how you're detecting and advancing to "the next level". How are these enemies being added to the array? Since it seems you've rolled your own Enemy class, what's that class look like? Why are you using try ... catch?
In any case, if the above works, fun; otherwise, we'll need more code to know what's going on.

access a movie clip on a certain frame within an array as3

I have movie clip in an array (newStep) that is being added to the stage dynamically. It's randomly choosing a frame to go to every time an instance is added. There is a nested movie clip (stepLine) that i need to change the alpha of. This code actually works for adding a string to to the dynamic text box (pointsDText) but when i try to access the nested movie clip (stepLine) it gives me 1009 null object reference error. The funny thing is the code actually works and does change the alpha of the movie clip but i still get that error, and i think it's making my game more glitchy. I've tried using if(contains(steps[r].stepLine)) too but it doesn't work. Is there a better way to access this movie clip without getting the error?
if(newStep != null){
for(var r:int = 0; r<steps.length;r++){
if(steps[r].currentLabel == "points"){
steps[r].pointsDText.text = String(hPoints);
}
if(steps[r].currentLabel == "special"){
steps[r].stepLine.alpha = sStepAlpha;
}
if(steps[r].currentLabel == "life"){
steps[r].stepLine.alpha = hStepAlpha;
}
}
}
This is so difficult to explain but i hope you understand.
Thanks so much.
A null reference error happens when you try to access properties of a variable that doesn't point to any object -- a null reference. You're effectively trying to access an object that doesn't exist. For example, perhaps stepLine doesn't exist in one of those instances, so stepLine.alpha is causing the error. (How do you set the alpha of a non-existent clip?) Maybe the steps[r] clip is on a frame where there is not yet any stepLine MovieClip.
You should run the movie in debug mode by pressing Ctrl+Shift+Enter in the Flash IDE. This should show you the exact line that causes the error, and it will let you inspect the values of any variables at that point. This should help you track down the problem. Similarly, you can use trace statements to aid in debugging. For example, you could trace(steps[r].stepLine); to check for null values, or even simply if(!steps[r].stepLine) trace("ERROR");. Additionally, if you wrap your accesses in if statements, you can avoid the null reference errors, even though this doesn't really address the underlying problem:
if(newStep != null){
for(var r:int = 0; r<steps.length;r++){
// only touch things if the movieclip actually exists
if(steps[r] && steps[r].stepLine){
if(steps[r].currentLabel == "points"){
steps[r].pointsDText.text = String(hPoints);
}
if(steps[r].currentLabel == "special"){
steps[r].stepLine.alpha = sStepAlpha;
}
if(steps[r].currentLabel == "life"){
steps[r].stepLine.alpha = hStepAlpha;
}
}
}
}

Resources