id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
722,101
./clinfinity/Clinfinity.c4d/Vehicles.c4d/Platform.c4d/Script.c
/* Script: Platform A controllable, floating platform, powered by steam. */ #strict 2 #include L_DC // Interval in frames which times steam transactions static const PLTF_SteamPayTimer = 250; // Timer interval as defined in the DefCore static const PLTF_SteamTimer = 10; // Steam a single platform uses on its own every PLTF_SteamPayTimer frames static const PLTF_SteamUsage = 10; // Allowed horizontal movement in pixel static const PLTF_HorizontalMovement = 90; // Helper 'direction' for ControlMediator static const PLTF_Explode = -1; local controlMediator; /* Constructor: CreatePlatform Factory method for platforms. The coordinates are relative to the calling object in local calls, otherwise global. *Note:* You should always create a platform using this method. Parameters: x - Horizontal coordinate. y - Vertical coordinate. owner - Owner of the created platform: Player index. Use NO_OWNER for ownerless platforms. Returns: The created platform. */ public func CreatePlatform(int x, int y, int owner) { var platform = CreateObject(PLTF, x, y, owner); CreateAdditionalObjectsFor(platform); return platform; } private func CreateAdditionalObjectsFor(object platform) { var mediator = CreateObject(COMD, AbsX(3), AbsY(3), platform->GetOwner()); mediator->LocalN("controlledPlatform") = platform; platform->LocalN("controlMediator") = mediator; platform->SetAction("Fly"); var lever = COLV->CreateLever(platform->GetX() - 35, platform->GetY() - 3, mediator); lever->AttachTo(platform); var prop = PROP->CreateProp(platform->GetX(), platform->GetY() + 12, platform); mediator->AddControlEventListener(platform); mediator->AddMovementEventListener(lever); mediator->AddMovementEventListener(prop); } protected func Construction() { ScheduleCall(this, "CheckAfterConstruction", 1); inherited(...); } protected func Destruction() { // remove everything that's connected controlMediator->RemoveObject(); for(var obj in FindObjects(Find_ActionTarget(this), Find_Not(Find_ID(PLTF)), Find_Procedure("ATTACH"))) { obj->Schedule("RemoveObject()", 1); } } protected func CheckAfterConstruction() { if(controlMediator == 0) { Log("Platform: You created a platform without using the factory method. If changing the owner, don't forget to set the correct one of lever and prop, too!"); CreateAdditionalObjectsFor(this); } } /* Function: IsPlatform Marks objects to have platform-like capabilities. */ public func IsPlatform() { return true; } protected func Flying() { SetSolidMask(0, 4, 90, 4); } protected func ContactLeft() { FloatStop(); } protected func ContactRight() { FloatStop(); } protected func ContactTop() { FloatStop(); } protected func ContactBottom() { FloatStop(); } /* Function: AttachEvent Event handler, called after an object was attached to a new parent object or detached from it. A platform hands the event to its control mediator. Parameters: attached - The attached object. attachedTo - The new parent object. isDetaching - *true* if the object was detached. *false* if it was attached. source - Source of the event. */ public func AttachEvent(object attached, object attachedTo, bool isDetaching, object source) { return GetControlMediator()->AttachEvent(attached, attachedTo, isDetaching, source); } /* Section: Control */ private func GetControlMediator() { return controlMediator; } /* Function: ControlEvent Event handler for control events. Parameters: direction - Direction of control, specified by one of the COMD_* constants. source - Source of the event. See Also: <Control mediator> */ public func ControlEvent(int direction, object source) { if(direction == COMD_Stop) { FloatStop(); } else if(direction == COMD_Up) { FloatUp(); } else if(direction == COMD_Down) { FloatDown(); } else if(direction == PLTF_Explode) { Explode(GetDefWidth() / 2); } } private func FloatStop() { if(missingSteam) { controlMediator->ControlEvent(PLTF_Explode, this); return; } SetComDir(COMD_None); SetXDir(0); SetYDir(0); controlMediator->MovementEvent(COMD_Stop, this); } private func FloatUp() { SetComDir(COMD_Up); controlMediator->MovementEvent(COMD_Up, this); } private func FloatDown() { SetComDir(COMD_Down); controlMediator->MovementEvent(COMD_Down, this); } /* Section: Master/Slave system */ /* Function: Connect Connects two platforms so they move in unison. When connected, both platforms can be controlled from either control lever. By calling this method, the left platform becomes the master of the right platform. Parameters: leftPlatform - The left platform. rightPlatform - The right platform. Returns: *true* if the platforms could successfully be connected, *false* otherwise. */ public func Connect(object leftPlatform, object rightPlatform) { if(IsPlatformOkay(leftPlatform) && IsPlatformOkay(rightPlatform) && leftPlatform != rightPlatform) { var leftMediator = leftPlatform->GetControlMediator(); var rightMediator = rightPlatform->GetControlMediator(); return COMD->Connect(leftMediator, rightMediator); } return false; } public func Disconnect(object leftPlatform, object rightPlatform) { if(IsPlatformOkay(leftPlatform) && IsPlatformOkay(rightPlatform) && leftPlatform != rightPlatform) { var leftMediator = leftPlatform->GetControlMediator(); var rightMediator = rightPlatform->GetControlMediator(); return COMD->Disconnect(leftMediator, rightMediator); } return false; } private func IsPlatformOkay(object platform) { return platform != 0 && platform->~IsPlatform(); } public func CopyChildrenVertices(object child) { return inherited(child); } /* Function: HasSharedBuildingsWith Checks whether there are any buildings standing on this platform that are shared with another platform. This function will only check for buildings that aren't attached to this platform but seem to be visually standing on this platform. Note: Control levers (COLV) are excluded from search. Parameters: otherPlatform - The other platform. Returns: true when there is a shared building. */ public func HasSharedBuildingsWith(object otherPlatform) { return !!FindObject2(Find_Not(Find_ID(COLV)), Find_ActionTarget(otherPlatform), Find_Procedure("ATTACH"), Find_OnPlatform()); } /* -- Steam Usage -- */ local missingSteam, steamUsage; protected func CheckSteam() { if(missingSteam) { missingSteam += MatSysDoTeamFill(-missingSteam, GetOwner(), STEM); if(missingSteam) ScheduleCall(this, "CheckSteam", 1); else StopFall(); return; // nothing else to do } // only if this is the master and it's pay time else if(GetActTime() % PLTF_SteamPayTimer < PLTF_SteamTimer && !GetControlMediator()->HasMaster()) { var usage = GetControlMediator()->AccumulateSteamUsage(); usage /= PLTF_SteamPayTimer / PLTF_SteamTimer; missingSteam = usage + MatSysDoTeamFill(-usage, GetOwner(), STEM); if(missingSteam) { FreeFall(); ScheduleCall(this, "CheckSteam", 1); } } // every platform: calculate steam usage if(GetControlMediator()->HasMaster()) // connected platforms use less steam steamUsage += PLTF_SteamUsage / 2; else steamUsage += PLTF_SteamUsage; steamUsage += CalculateWeight() / 50; } /* Function: ResetSteamUsage Resets the steam usage variable for the current period. Returns: The counter before the reset. */ public func ResetSteamUsage() { var temp = steamUsage; steamUsage = 0; return temp; } private func FreeFall() { SetAction("Idle"); SetYDir(1); } private func StopFall() { SetAction("Fly"); FloatStop(); } /* Function: Find_OnPlatform FindObject2/FindObjects search criteria: Find all objects standing on this platform Note: This function might also find objects that aren't actually standing on the platform, but are on a platform further down and overlapping with this platform, for example. */ public func Find_OnPlatform() { return Find_And(Find_OnLine(-GetDefWidth()/2, -GetDefHeight()/2-2, GetDefWidth()/2, -GetDefHeight()/2-2), Find_Not(Find_Or(Find_Func("IsPlatform"), Find_Category(C4D_StaticBack)))); } /* Function: Find_BuildingsOnPlatform FindObject2/FindObjects search criteria: Find all buildings standing on this platform Does not find the control lever (COLV). See note on <Find_OnPlatform> */ public func Find_BuildingsOnPlatform() { return Find_And(Find_OnPlatform(), Find_Not(Find_ID(COLV)), Find_Procedure("ATTACH")); } /* Function: CalculateWeight Adds the mass of everything on top of the platform. Returns: The corresponding sum of masses. */ public func CalculateWeight() { var weights = FindObjects(Find_OnPlatform(), Find_Not(Find_And(Find_Not(Find_ActionTarget(this)), Find_Procedure("ATTACH")))); var mass = 0; for(var weight in weights) { mass += GetMass(weight); } return mass; } /*-- Damage Control --*/ public func MaxDamage() { return 40; } public func Damage(int change) { // only get damaged while there aren't any buildings on top of the platform if(change > 0 && FindObject2(Find_BuildingsOnPlatform())) DoDamage(-change); else return inherited(change, ...); }
722,102
./clinfinity/Clinfinity.c4d/Vehicles.c4d/Platform.c4d/ControlLever.c4d/Script.c
/* Script: Control lever Floating platforms are controlled with this lever. */ #strict 2 local controlMediator; local gearStop, gearUp, gearDown; local vertical, startPos; /* Constructor: CreateLever Factory method for levers. The coordinates are relative to the calling object in local calls, otherwise global. *Note:* You should always create a lever using this method. Parameters: x - Horizontal coordinate. y - Vertical coordinate. forMediator - The control mediator this lever sends its events to. Returns: The created lever. */ public func CreateLever(int x, int y, object forMediator) { var lever = CreateObject(COLV, x, y, forMediator->GetOwner()); lever->LocalN("controlMediator") = forMediator; lever->SetAction("Control"); return lever; } protected func Initialize() { gearStop = 0; gearUp = 1; gearDown = 2; // save position Schedule("startPos = GetX()", 1); AddEffect("HorizontalBoundsCheck", this, 1, 0, this); } /* Function: GetPlatform Returns the platform controlled by this lever. */ public func GetPlatform() { return controlMediator->GetControlledPlatform(); } protected func MouseSelection(int player) { Sound("Ding"); } private func HostileCheck(object clonk) { if(Hostile(GetOwner(), clonk->GetOwner())) { SetCommand(clonk, "UnGrab"); return true; } } protected func Grabbed(object controller, bool grab) { if(grab && Hostile(GetOwner(), controller->GetOwner())) { Sound("CommandFailure1"); SetCommand(controller, "UnGrab"); } } protected func ControlUp(object controller) { if(HostileCheck(controller)) return false; if(vertical || GetDir() == gearDown) { controlMediator->ControlEvent(COMD_Stop, this); } else if(GetDir() == gearStop) { controlMediator->ControlEvent(COMD_Up, this); } else { return false; } return true; } protected func ControlDownSingle(object controller) { if(HostileCheck(controller)) return false; if(vertical || GetDir() == gearUp) { controlMediator->ControlEvent(COMD_Stop, this); } else if(GetDir() == gearStop) { controlMediator->ControlEvent(COMD_Down, this); } else { return false; } return true; } protected func ControlLeft(object controller) { if(HostileCheck(controller)) return false; // No horizontal movement when there are connected platforms. if(controlMediator->GetMaster() || controlMediator->GetSlave()) return ControlUp(controller); // We need to stop if the platform isn't already moving to the left. if(!vertical && GetDir() || GetDir() == gearDown) controlMediator->ControlEvent(COMD_Stop, this); else if(GetDir() == gearStop) { // Are we allowed to go further left? if(GetX() - startPos < -PLTF_HorizontalMovement) { Sound("CommandFailure1"); return; } controlMediator->GetControlledPlatform()->SetComDir(COMD_Left); SetDir(gearUp); Sound("lever", false, this, 15); vertical = true; StartHorizontalBoundsCheck(); } } protected func ControlRight(object controller) { if(HostileCheck(controller)) return false; // No horizontal movement when there are connected platforms. if(controlMediator->GetMaster() || controlMediator->GetSlave()) return ControlDownSingle(controller); // We need to stop if the platform isn't already moving to the right. if(!vertical && GetDir() || GetDir() == gearUp) controlMediator->ControlEvent(COMD_Stop, this); else if(GetDir() == gearStop) { // Are we allowed to go further right? if(GetX() - startPos > PLTF_HorizontalMovement) { Sound("CommandFailure1"); return; } controlMediator->GetControlledPlatform()->SetComDir(COMD_Right); SetDir(gearDown); Sound("lever", false, this, 15); vertical = true; StartHorizontalBoundsCheck(); } } public func MovementEvent(int direction, object source) { var oldDirection = GetDir(); if(direction == COMD_Stop) { SetDir(gearStop); } else if(direction == COMD_Up) { SetDir(gearUp); } else if(direction == COMD_Down) { SetDir(gearDown); } if(GetDir() != oldDirection) { Sound("lever", false, this, 15); } vertical = false; StopHorizontalBoundsCheck(); } private func StartHorizontalBoundsCheck() { ChangeEffect("HorizontalBoundsCheck", this, 0, "HorizontalBoundsCheck", 10); } private func StopHorizontalBoundsCheck() { ChangeEffect("HorizontalBoundsCheck", this, 0, "HorizontalBoundsCheck", 0); } protected func FxHorizontalBoundsCheckTimer(object target, int effectNum, int effectTime) { if(Abs(GetX() - startPos) > PLTF_HorizontalMovement) controlMediator->ControlEvent(COMD_Stop, this); } /* -- Platform Connection Control -- */ protected func ControlDigDouble(object controller) { if(HostileCheck(controller)) return false; CreateMenu(CXCN, controller, this, C4MN_Extra_Components); // find leftest platform var leftest, prev = controlMediator; while(leftest = prev->GetMaster()) prev = leftest; AddPlatformMenuItem(controller, 0, ObjectNumber(prev)); // dis/connect var left = controlMediator->GetMaster() || PlatformMediator(FindPlatform(false)); var right = controlMediator->GetSlave() || PlatformMediator(FindPlatform(true)); ConnectionMenuItem(controller, left, controlMediator); ConnectionMenuItem(controller, controlMediator, right); // find rightest platform var rightest, prev = controlMediator; while(rightest = prev->GetSlave()) prev = rightest; AddPlatformMenuItem(controller, ObjectNumber(prev), 0); } // Finds platforms to the left/right private func FindPlatform(bool right) { right = right * 2 - 1; var platform = controlMediator->GetControlledPlatform(); return FindObject2(platform->Find_AtPoint(right * GetDefWidth(PLTF)), Find_Allied(GetOwner()), Find_Func("IsPlatform")); } private func PlatformMediator(object platform) { return platform && platform->GetControlMediator(); } private func ConnectionMenuItem(object clonk, object master, object slave) { var mn, sn; if(master) mn = ObjectNumber(master); if(slave) sn = ObjectNumber(slave); var command; if(master && slave) { if(master->IsMasterOf(slave)) { command = Format("DisconnectPlatforms(Object(%d), Object(%d))", mn, sn); AddMaterialMenuItem("$Disconnect$", command, MS4C, clonk, 0, 0, "", 2, 4); } else { command = Format("ConnectPlatforms(Object(%d), Object(%d))", mn, sn); AddMaterialMenuItem("$Connect$", command, MS4C, clonk, 0, 0, "", 2, 1); } } } private func AddPlatformMenuItem(object clonk, int mn, int sn) { var command = Format("AddPlatform(Object(%d), Object(%d))", mn, sn); AddMaterialMenuItem("$NewPlatform$", command, PLTF, clonk, 0, 0, "", 2, !sn); } protected func AddPlatform(object master, object slave) { var platform = (master || slave)->GetControlledPlatform(), width = GetDefWidth(PLTF); var dir = !!master * 2 - 1; // inner x: left/right edge of the existing platform var ix = platform->GetX() + dir * (width / 2 + 1); // outer x: edge of the new platform var ox = platform->GetX() + dir * width * 3 / 2; var y = platform->GetY(); if(ox < 0 || ox > LandscapeWidth() || !PathFree(ix, y, ox, y)) { Sound("Error"); Message("$PathNotFree$", this); return; } if(!MatSysSubtractComponents(PLTF, GetOwner())) { Sound("Error"); return; } Sound("Connect"); var new = platform->CreatePlatform(-87, GetDefHeight(PLTF) / 2, GetOwner())->GetControlMediator(); if(master) slave = new; else master = new; COMD->Connect(master, slave); } protected func ConnectPlatforms(object master, object slave) { Sound("Connect"); COMD->Connect(master, slave); } protected func DisconnectPlatforms(object master, object slave) { var masterPlatform = master->GetControlledPlatform(), slavePlatform = slave->GetControlledPlatform(); if(masterPlatform->HasSharedBuildingsWith(slavePlatform) || slavePlatform->HasSharedBuildingsWith(masterPlatform)) { Message("$DisconnectNotPossible$", this); Sound("Error"); return; } Sound("Connect"); COMD->Disconnect(master, slave); // move slave a bit to the right so the platforms aren't stuck var platform = slave->GetControlledPlatform(); platform->SetPosition(platform->GetX() + 2, platform->GetY()); }
722,103
./clinfinity/Clinfinity.c4d/Vehicles.c4d/Platform.c4d/ControlMediator.c4d/Script.c
/* Script: Control mediator Encapsulates the interactions between platforms and the event flow for control events and movement events between platforms, levers, and possibly other objects. See Also: General information on the <mediator pattern at http://en.wikipedia.org/wiki/Mediator_pattern>. */ #strict 2 local controlledPlatform; local controlEventListeners, movementEventListeners; local masterMediator, slaveMediator; protected func Initialize() { controlEventListeners = []; movementEventListeners = []; } protected func Destruction() { if(masterMediator) Disconnect(masterMediator, this); if(slaveMediator) Disconnect(this, slaveMediator); } /* Function: ControlEvent Called by the source when it wants to broadcast a control event. This can be, for example, a lever that has been switched into its "up" position. Parameters: direction - Direction of control. Must be one of the COMD_* constants. source - Source of the event. */ public func ControlEvent(int direction, object source) { if(masterMediator == 0) { ControlEventToListeners(direction, this); } else { if(source == masterMediator) { ControlEventToListeners(direction, this); } else { masterMediator->ControlEvent(direction, this); } } } /* Function: MovementEvent Called by the source when it wants to broadcast its movement status. Platforms use this when they start or stop moving to notify levers, for example. Parameters: direction - Direction of movement. Must be one of the COMD_* constants. source - Source of the event. */ public func MovementEvent(int direction, object source) { if(masterMediator == 0) { MovementEventToListeners(direction, this); } else { if(source == masterMediator) { MovementEventToListeners(direction, this); } else { masterMediator->MovementEvent(direction, this); } } } /* Function: AttachEvent Event handler, called after an object was attached to a new parent object or detached from it. Parameters: attached - The attached object. attachedTo - The new parent object. isDetaching - *true* if the object was detached. *false* if it was attached. source - Source of the event. */ public func AttachEvent(object attached, object attachedTo, bool isDetaching, object source) { if(masterMediator == 0) { if(isDetaching) { GetControlledPlatform()->RemoveCopiedChildrenVertices(attached); } else { GetControlledPlatform()->CopyChildrenVertices(attached); } } else { if(source == masterMediator) { if(isDetaching) { GetControlledPlatform()->RemoveCopiedChildrenVertices(attached); } else { GetControlledPlatform()->CopyChildrenVertices(attached); } } else { masterMediator->AttachEvent(attached, attachedTo, isDetaching, source); } } } /* Function: AddControlEventListener Adds a listener for control events. The control mediator will call the method ControlEvent() in each listener when a control event arrives. Parameters: listener - The listener to add. */ public func AddControlEventListener(object listener) { if(listener != 0 && !InArray(listener, controlEventListeners)) { PushBack(listener, controlEventListeners); } } /* Function: AddMovementEventListener Adds a listener for movement events. The control mediator will call the method MovementEvent() in each listener when a movement event arrives. Parameters: listener - The listener to add. */ public func AddMovementEventListener(object listener) { if(listener != 0 && !InArray(listener, movementEventListeners)) { PushBack(listener, movementEventListeners); } } /* Function: RemoveControlEventListener Removes a listener for control events. Parameters: listener - The listener to remove. */ public func RemoveControlEventListener(object listener) { RemoveElement(listener, controlEventListeners); } /* Function: RemoveMovementEventListener Removes a listener for movement events. Parameters: listener - The listener to remove. */ public func RemoveMovementEventListener(object listener) { RemoveElement(listener, movementEventListeners); } private func ControlEventToListeners(int direction, object source) { for(var listener in controlEventListeners) { listener->ControlEvent(direction, source); } } private func MovementEventToListeners(int direction, object source) { for(var listener in movementEventListeners) { listener->MovementEvent(direction, source); } } /* Section: Master/slave system Methods that concern the list-like structure of connected control mediators. If the mediators of two adjacent platforms are connected, the mediator of the left platform acts as the master of the right platform's mediator. An arbitrary number of mediators can be connected this way, forming a doubly linked list. Each event that is fired in a slave gets handed to its master. This is repeated until the event reaches the "absolute" master at the left of the connected mediators. From there, the event gets routed back to the right, and additionally, to all listeners for the respective event. This way, an event fired anywhere in the list can be received by any listener in the list. */ /* Function: Connect Connects the control mediators of two adjacent platforms. The left mediator becomes the master of the right mediator. Parameters: leftMediator - Mediator of the left platform. rightMediator - Mediator of the right platform. Returns: *true* if the mediators could successfully be connected, *false* otherwise. */ public func Connect(object leftMediator, object rightMediator) { if(leftMediator->HasSlave() || rightMediator->HasMaster()) { return false; } leftMediator->SetSlave(rightMediator); rightMediator->SetMaster(leftMediator); var leftPlatform = leftMediator->GetControlledPlatform(); var rightPlatform = rightMediator->GetControlledPlatform(); rightPlatform->SetAction("FlySlave", leftPlatform); rightPlatform->AttachTo(leftPlatform, 1, 2); rightPlatform->RemoveCopiedChildrenVertices(); // Stop the platforms leftMediator->ControlEvent(COMD_Stop); return true; } public func Disconnect(object leftMediator, object rightMediator) { if(!leftMediator->IsMasterOf(rightMediator) || !rightMediator->IsSlaveOf(leftMediator)) { return false; } leftMediator->RemoveSlave(); rightMediator->RemoveMaster(); var leftPlatform = leftMediator->GetControlledPlatform(); var rightPlatform = rightMediator->GetControlledPlatform(); rightPlatform->SetAction("Fly"); rightPlatform->SetActionTargets(0, 0); rightPlatform->CopyChildrenVertices(); leftMediator->AttachEvent(rightPlatform, leftPlatform, true, this); return true; } /* Function: GetNumberOfPlatforms Counts all connected platforms. Returns: The number of platforms connected with this platform (including this one). */ public func GetNumberOfPlatforms() { var platform = this, result = 1; while(platform = platform->GetMaster()) result++; platform = this; while(platform = platform->GetSlave()) result++; return result; } /* Function: AccumulateSteamUsage Calculates the steam usage of all platforms connected with this one. Works by calling <ResetSteamUsage> in the platforms. Returns: The steam usage of all platforms connected with this one (including this one). */ public func AccumulateSteamUsage() { var mediator = this, result = GetControlledPlatform()->ResetSteamUsage(); while(mediator = mediator->GetMaster()) result += mediator->GetControlledPlatform()->ResetSteamUsage(); mediator = this; while(mediator = mediator->GetSlave()) result += mediator->GetControlledPlatform()->ResetSteamUsage(); return result; } private func HasMaster() { return masterMediator != 0; } private func HasSlave() { return slaveMediator != 0; } private func GetMaster() { return masterMediator; } private func GetSlave() { return slaveMediator; } private func IsMasterOf(object mediator) { return slaveMediator == mediator; } private func IsSlaveOf(object mediator) { return masterMediator == mediator; } private func SetMaster(object newMaster) { masterMediator = newMaster; } private func RemoveMaster() { masterMediator = 0; } private func SetSlave(object newSlave) { AddControlEventListener(newSlave); AddMovementEventListener(newSlave); slaveMediator = newSlave; } private func RemoveSlave() { if(slaveMediator != 0) { RemoveControlEventListener(slaveMediator); RemoveMovementEventListener(slaveMediator); slaveMediator = 0; } } private func GetControlledPlatform() { return controlledPlatform; }
722,104
./clinfinity/Clinfinity.c4d/Vehicles.c4d/Platform.c4d/Prop.c4d/Script.c
/* Script: Prop Attached to the underside of platforms. Generates enough force to make platforms fly! */ #strict 2 local leftDraft, rightDraft; // width of one propeller static const PROP_Width = 25; // height of draft static const PROP_DraftHeight = 50; /* Constructor: CreateProp Factory method for propellers. The coordinates are relative to the calling object in local calls, otherwise global. *Note:* You should always create a prop using this method. Parameters: x - Horizontal coordinate. y - Vertical coordinate. forPlatform - The platform this prop attaches to. Returns: The created prop. */ public func CreateProp(int x, int y, object forPlatform) { var prop = CreateObject(PROP, x, y, forPlatform->GetOwner()); prop->AttachTo(forPlatform); return prop; } /* Function: MovementEvent Event handler for movement events. Parameters: direction - Direction of movement, specified by one of the COMD_* constants. source - Source of the event. See Also: <Control mediator> */ public func MovementEvent(int direction, object source) { if(direction == COMD_Up) { SetAction("AttachFast"); var height = PROP_DraftHeight * 5 / 4; leftDraft->SetSize(PROP_Width, height); rightDraft->SetSize(PROP_Width, height); } else if(direction == COMD_Down) { SetAction("AttachSlow"); var height = PROP_DraftHeight * 3 / 4; leftDraft->SetSize(PROP_Width, height); rightDraft->SetSize(PROP_Width, height); } else { SetAction("Attach"); leftDraft->SetSize(PROP_Width, PROP_DraftHeight); rightDraft->SetSize(PROP_Width, PROP_DraftHeight); } } protected func Initialize() { leftDraft = CreateDraft(); rightDraft = CreateDraft(); rightDraft->SetActionData(1); } private func CreateDraft() { var draft = CreateObject(DRFT); draft->SetR(180); draft->SetSize(25, 50); draft->SetAction("Attach", this); return draft; } protected func Destruction() { leftDraft->RemoveObject(); rightDraft->RemoveObject(); }
722,105
./clinfinity/Clinfinity.c4d/Items.c4d/Debris.c4d/Script.c
/*-- Fragment --*/ #strict func Initialize() { SetAction(Format("g%d",Random(4)+1)); //SetGraphics (0, 0, 0, 0, GFXOV_MODE_Action, Format("g%d",Random(4)+1)); return(1); } protected func Activate(){ var i = Random(5); while(i--) { CastObject([METL] [Random(2)]); } Sound("Connect"); RemoveObject(); } private func CastObject(id ID) { var pObj = CreateObject(ID, 0, 0, GetOwner()); pObj -> SetSpeed(RandomX(-10, 10), RandomX(-10, 10)); return 1; } protected func Hit() { Sound("MetalHit*"); return(1); }
722,106
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Musket.c4d/Script.c
/* Script: Musket A long-range projectile weapon. */ #strict 2 #include L_SS // overlay position public func HandX() { return 9000; } public func HandY() { return 2000; } // clip size public func MaxFill() { return 6; } private func FillPicture() { return 0; } // minimum and maximum damage static const MUSK_MinDamage = 5; static const MUSK_MaxDamage = 20; static const MUSK_DamageDeviation = 3; // charging duration in frames static const MUSK_ChargeDuration = 150; // minimum charge for knockback static const MUSK_KnockbackCharge = 50; // timer interval for charging effect static const MUSK_ChargeRefreshRate = 5; // charge progress in percent local charge, chargeIndicator; protected func Initialize() { DoFill(MaxFill()); } // collect clip protected func Entrance(object container) { var musket = FindObject2(Find_Container(container), Find_ID(GetID()), Find_Exclude(this)); if(musket) { musket->DoFill(GetFill()); RemoveObject(); } } /* Charging */ private func StartCharging() { StopCharging(); AddEffect("Charging", this, 1, MUSK_ChargeRefreshRate, this); chargeIndicator = Contained()->CreateObject(CRGE, 0, -20, Contained()->GetOwner()); chargeIndicator->AttachTo(Contained()); } private func StopCharging() { RemoveEffect("Charging", this); charge = 0; if(chargeIndicator) chargeIndicator->RemoveObject(); } private func CalcDamage() { var deviation = RandomX(-MUSK_DamageDeviation, MUSK_DamageDeviation); return ChangeRange(charge, 0, 100, MUSK_MinDamage, MUSK_MaxDamage) + deviation; } private func ChargeKnockback() { return charge >= MUSK_KnockbackCharge; } protected func FxChargingTimer(object target, int effectNum, int effectTime) { charge += 100 * MUSK_ChargeRefreshRate / MUSK_ChargeDuration; if(charge >= 100) { charge = 100; UpdateChargeIndicator(); return FX_Execute_Kill; } UpdateChargeIndicator(); } private func UpdateChargeIndicator() { chargeIndicator->SetCharge(charge); if(ChargeKnockback()) chargeIndicator->On(); } /* Steuerung */ public func GetTargets() { return FindObjects(Find_Distance(1000), Find_Hostile(Contained()->GetOwner()), Find_OCF(OCF_Alive), Find_NoContainer(), Sort_Distance()); } public func CanLoad() { return !IsFull() && MatSysGetTeamFill(Contained()->GetOwner(), METL) >= 1; } public func StartLoading() { Sound("MusketReload"); StopCharging(); } public func Load() { if(MatSysDoTeamFill(-1, Contained()->GetOwner(), METL)) { DoFill(MaxFill()); } StartCharging(); } public func StartAiming() { Sound("MusketDeploy"); StartCharging(); } public func Abort() { StopCharging(); } public func Fire(object clonk, int angle) { // cooldown if(GetEffect("ReloadRifle", this)) return; // enough ammo in clip? if(!GetFill()) { Sound("MusketEmpty"); // try to reload clonk->LoadRifle(); return; } // enough steam? var owner = clonk->GetOwner(); if(MatSysGetTeamFill(owner, STEM) < 5) return; MatSysDoTeamFill(-5, owner, STEM); DoFill(-1); var obj, obj2, x, y, r, xDir, yDir, rDir, dir, phase; var ammo = CreateContents(CSHO); // Launch parameter calculation dir = clonk->GetDir() * 2 - 1; phase = clonk->GetPhase(); r = angle * dir + 90; xDir = (Sin(angle, 22) + 1) * dir; yDir = -Cos(angle, 22); rDir = 0; // See AVTR::WeaponAt var dst = 10 + GetDefWidth() - HandX() / 1000; x = (Sin(angle, dst)) * dir; y = -Cos(angle, dst) - HandY() / 1000; // Owner is important for awarding kills SetOwner(clonk->GetOwner(), ammo); Exit(ammo, AbsX(x + clonk->GetX()), AbsY(y + clonk->GetY()), r, xDir, yDir, rDir); ammo->Launch(-1, CalcDamage(), ChargeKnockback()); // Muzzle flash particle: same position as ammo launch CreateParticle("MuzzleFlash", AbsX(x + clonk->GetX()), AbsY(y + clonk->GetY()), xDir, yDir, 35, RGBa(255, 255, 255, 0), clonk); Sound("MusketShoot*", 0, clonk); Smoke(x, y, 2); Smoke(x, y + Random(2), 3); CreateParticle("Casing", AbsX(x / 2 + GetX(clonk)), AbsY(y / 2 + GetY(clonk)), -dir * RandomX(1, 5), -RandomX(3, 7), 15, RGBa(250, 140, 80, 0)); // Cooldown before the next shot can be fired AddEffect("ReloadRifle", this, 101, 30); // Restart charging. StartCharging(); return 1; } /* Objekt ist eine Waffe */ public func IsWeapon () { return 1; } /* Objekt ist keine Handfeuerwaffe */ public func IsGun () { return 0; } /* Objekt ist ein Gewehr */ public func IsRifle () { return 1; } /* Objekt wurde ausgewΣhlt */ public func Selection () { Sound("RevolverDraw"); }
722,107
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Musket.c4d/Charge.c4d/Script.c
#strict 2 local columns; protected func Initialize() { SetVisibility(VIS_Owner); SetCharge(0); Off(); columns = GetActMapVal("Length", "Charge"); } protected func SetCharge(int charge) { SetAction("Charge"); var phase = charge * (columns - 1) / 100; SetPhase(phase); } protected func On() { SetStillOverlayAction("On", 1); } protected func Off() { SetStillOverlayAction("Off", 1); }
722,108
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Musket.c4d/Crosshair.c4d/Script.c
/*-- Fadenkreuz --*/ #strict 2 protected func Initialize() { SetVisibility(VIS_Owner); }
722,109
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Musket.c4d/Shot.c4d/Script.c
/*-- fliegende Patrone --*/ #strict 2 #include ARRW local xdir, ydir, dam, knockback; /* Eigenschaften */ // Wird zur korrekten Inventarverwaltung gebraucht public func PackTo() { return AMBO; } public func IsBullet() { return 1; } public func IsArrow() { return 0; } /* Wird abgefeuert */ public func Launch(int dir, int damage, bool knock) { ChangeDef(CSHO); SetCategory(C4D_Vehicle); if(dir == DIR_Left) xdir = -100; if(dir == DIR_Right) xdir = +100; ydir = GetYDir(); dam = damage; // Schaden knockback = knock; SetAction("Travel"); } local oldX, oldY; /* Fliegt */ private func Travel() { var actTime = GetActTime(); // trace flight if(oldX && actTime > 1) { var color = RGB(255, 255, 255); DrawParticleLine("PSpark", 0, 0, AbsX(oldX), AbsY(oldY), 3, 20, color, color); } // Bewegung if(xdir != 0) { // Revolverschu▀ SetXDir(xdir); ydir = 0; if(actTime > 20) ydir = 5; } // fixed ydir SetYDir(ydir); // Auf Treffer prⁿfen if(actTime > 2) CheckHit(); oldX = GetX(); oldY = GetY(); return; } private func CheckHit() { // Nur wenn schon passende Werte da sind if(!oldX && !oldY) return; // Distance zur letzten Position berechnen var xDist = GetX() - oldX; var yDist = GetY() - oldY; // Treffer-▄berprⁿfung var steps = Abs(xDist / 4); if(Abs(GetXDir()) < Abs(GetYDir())) steps = Abs(yDist / 4); var x, y, obj; // Mit Schleife alle Zwischenpunkte abklappern for(var i = steps; i; i--) { x = -xDist * i / steps; y = -yDist * i / steps; if(!y) y = 1; //CreateParticle("NoGravSpark", x, y, 0, 0, 30, RGB(i*255/steps, (steps-i)*255/steps)); if(obj = FindObject(0, x, y, 0, 0, OCF_Alive, 0, 0, NoContainer())) return HitLiving(obj); } } /* Treffer */ protected func Hit() { // Vielleicht stand jedoch zwischen Wand und letzter Position noch jemand // -> also nochmal prⁿfen if(CheckHit()) return; Sound("Ricochet*"); RemoveObject(); } private func HitLiving(living) { Sound("Punch*"); // Schaden machen if(knockback) // Damage with knockback. Punch(living, dam); else DoEnergy(-dam, living); return RemoveObject(); } public func Entrance(clonk) { if(clonk->~IsWeapon() || GetID(clonk) == WCHR) return; return _inherited(clonk, ...); }
722,110
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Steamlauncher.c4d/Script.c
/* Script: Steam grenade launcher A long-range explosive weapon. Shoots ballistically moving steam grenades. See <Weapons> for a general reference about weapons. */ #strict 2 #include L_SS /* Constants: Material consumption when filling magazine SGLR_AmmoMaterial - Material to use. SGLR_AmmoSteamUsage - Amount of steam to use. */ static const SGLR_AmmoMaterial = METL; static const SGLR_AmmoSteamUsage = 20; /* Constants: Grenade launching SGLR_GrenadeExitDistance - Distance of the muzzle, relative to the offset. SGLR_GrenadeExitSpeed - The grenade's initial speed after being launched. SGLR_SteamExitDistance - Distance where steam exits the muzzle. SGLR_SteamExitMinSpeed - Minimum speed of steam blast effect. SGLR_SteamExitMaxSpeed - Maximum speed of steam blast effect. */ static const SGLR_GrenadeExitDistance = 12; static const SGLR_GrenadeExitSpeed = 10; static const SGLR_SteamExitDistance = 20; static const SGLR_SteamExitMinSpeed = 15; static const SGLR_SteamExitMaxSpeed = 40; // overlay position public func HandX() { return 7000; } public func HandY() { return 2000; } public func MaxFill() { return 1; } private func FillPicture() { return 0; } /* Section: Events */ /* Function: Initialize Called when the steam grenade launcher is created. It is initialised with a full magazine. */ protected func Initialize() { DoFill(MaxFill()); } /* Function: Entrance Event call when entering an object. If the steam grenade launcher is collected by a crew member who is already carrying another steam grenade launcher, their ammunition is combined and the collected launcher is removed. Parameters: into - The object that the steam grenade launcher entered. */ protected func Entrance(object into) { if((into->GetOCF() & OCF_CrewMember) == 0) return; var steamlauncher = FindObject2(Find_Container(into), Find_ID(GetID()), Find_Exclude(this)); if(steamlauncher) { steamlauncher->DoFill(GetFill()); RemoveObject(); } } /* Function: Load Called by a crew member after its loading animation has finished. See <Weapons> for reference. If all the required materials and enough steam are available in the material system, the launcher's magazine gets filled completely. */ public func Load() { if(CanLoad()) { MatSysDoTeamFill(-1, Contained()->GetOwner(), SGLR_AmmoMaterial); MatSysDoTeamFill(-SGLR_AmmoSteamUsage, Contained()->GetOwner(), STEM); DoFill(MaxFill()); } } public func StartLoading() { Sound("SteamlauncherReload"); } public func StartAiming() { Sound("MusketDeploy"); } /* Function: GetTargets Called by a crew member to get a list of possible targets for auto-aiming. See <Weapons> for reference. Since auto-aiming is disabled for the steam grenade launcher, this always returns no targets. Returns: An empty array. */ public func GetTargets() { return []; } public func Abort() { /* Nothing to do */ } public func CanLoad() { return !IsFull() && MatSysGetTeamFill(Contained()->GetOwner(), SGLR_AmmoMaterial) >= 1 && MatSysGetTeamFill(Contained()->GetOwner(), STEM) >= SGLR_AmmoSteamUsage; } public func Fire(object clonk, int angle) { // Cool down if(GetEffect("ReloadRifle", this)) return; // Ammo in clip? if(!GetFill()) { Sound("MusketEmpty"); // Try to reload clonk->LoadRifle(); return; } DoFill(-1); var direction = clonk->GetDir() * 2 - 1; var phase = clonk->GetPhase(); var x = Sin(angle, SGLR_GrenadeExitDistance * direction); var y = -Cos(angle, SGLR_GrenadeExitDistance) + HandY() / 1000; var xSpeed = Sin(angle, SGLR_GrenadeExitSpeed * direction); var ySpeed = -Cos(angle, SGLR_GrenadeExitSpeed); var grenade = CreateContents(BOMB); grenade->SetOwner(clonk->GetOwner()); Exit(grenade, x, y, 0, xSpeed, ySpeed, 0); grenade->Launch(); Sound("SteamlauncherShoot*", 0, clonk); var steamAmount = RandomX(5, 10); var steamX = Sin(angle, SGLR_SteamExitDistance * direction); var steamY = -Cos(angle, SGLR_SteamExitDistance); for(var i = 0; i < steamAmount; i++) { BSTE->LaunchSteam(steamX + GetX(), steamY + GetY(), RandomX(SGLR_SteamExitMinSpeed, SGLR_SteamExitMaxSpeed), angle * direction); } AddEffect("ReloadRifle", this, 101, 30); return 1; } public func IsWeapon() { return 1; } public func Selection() { Sound("RevolverDraw"); }
722,111
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Yo-Yo.c4d/Script.c
/* Script: Yo-yo A short-range throwing weapon. Technical details: Internally, the yo-yo object is in one of three discrete states: * Inactive * Thrown * Returning When inactive, the yo-yo exhibits no special behaviour. This is the default state. In the "Thrown" state, activated when a Clonk (or any other type of crew member) throws the yo-yo, the following rules apply * The yo-yo flies in a regular flight path, determined by the Clonk engine. * Its starting speed is different from that of other objects, to be able to hit Clonks standing in front of the thrower. * A line is drawn between the thrower and the yo-yo. * After a set timespan or when hitting a living being, the yo-yo automatically switches do the "Returning" state. * Nobody but its thrower can collect the yo-yo. In the returning state, the yo-yo moves back to the original thrower, straight into its current direction. Initially, it moves at a set maximum speed, but slows down to not injure the thrower. When close enough, the following happens * The yo-yo gets moved into the thrower's inventory. * The drawn line is removed. * The yo-yo switches to the "Inactive" state. Two events, namely death and removal of the thrower, make the yo-yo switch to the "Inactive" state immediately. */ #strict 2 /* Constants: Internal yo-yo states YOYO_StateInactive - Denotes the inactive state without special behaviour. YOYO_StateThrown - Denotes the state: Yo-yo has been thrown. YOYO_StateReturning - Denotes the state: Yo-yo moves back towards the original thrower. */ static const YOYO_StateInactive = 0; static const YOYO_StateThrown = 1; static const YOYO_StateReturning = 2; /* Constants: Yo-yo flight YOYO_ThrowFlightTime - The time between getting thrown and switching to the "Returning" state. YOYO_ReturnMaxSpeed - Maximum speed the yo-yo moves while returning to the thrower. YOYO_ReturnSlowDownDistance - Distance where the yo-yo slows down when approaching the thrower. YOYO_MaxCollectionDistance - Maximum distance in which the yo-yo returns itself to the thrower's inventory. */ static const YOYO_ThrowFlightTime = 12; static const YOYO_ReturnMaxSpeed = 40; static const YOYO_ReturnSlowDownDistance = 5; static const YOYO_MaxCollectionDistance = 10; /* Constants: Yo-yo hits YOYO_Damage - Damage one single yo-yo hit does. YOYO_MaxHitMoveDistance - Maximum distance a target that was hit gets knocked away from the thrower. YOYO_FlingTargetChance - Determines the chance for a "lucky strike" that flings a target. The chance is calculated as 1/YOYO_FlingTargetChance. YOYO_FlingSpeed - Fling speed for the "lucky strike". */ static const YOYO_Damage = 2; static const YOYO_MaxHitMoveDistance = 5; // static const YOYO_FlingTargetChance = 6; // Chance: 1 of YOYO_FlingTargetChance is a lucky strike/critical hit static const YOYO_FlingSpeed = 2; local thrower; local line; local currentState; /* Section: Events */ /* Function: Initialize Called when the yo-yo is created. The yo-yo is initialised as inactive. */ protected func Initialize() { YoyoInactive(); } /* Function: ContainerThrow If a Clonk throws the yo-yo in flight (and does not want to drop it), activate the yo-yo and make it fly downwards. Returns: _true_ if the yo-yo was activated as weapon, _false_ otherwise. */ public func ContainerThrow() { var container = Contained(); // Thrown in flight by a Clonk: Act as weapon. if((container->GetOCF() & OCF_CrewMember) != 0 && container->GetAction() == "Jump" && !GetPlrDownDouble(container->GetOwner())) { var exitX = -9 + container->GetDir() * 18; var exitY = 0; var exitXSpeed = -2 + container->GetDir() * 4; var exitYSpeed = 2; if(container->~IsGliding()) { exitX += container->GetXDir() / 10; exitY = 10; exitYSpeed = Max(2, container->GetYDir() * 2 / 10); } Exit(0, exitX, exitY, 0, exitXSpeed, exitYSpeed, 0); YoyoThrown(container); return true; } return false; } /* Function: Departure If a Clonk throws the yo-yo while standing, activate the yo-yo. Parameters: from - The object the yo-yo departed from. */ protected func Departure(object from) { // If the yo-yo was thrown by a Clonk, act as weapon. if((from->GetOCF() & OCF_CrewMember) != 0 && from->GetAction() == "Throw" && !OtherYoyoThrownBy(from)) { // Set speed to fly lower, because it's supposed to hit enemies. SetXDir(GetXDir() * 3); SetYDir(-5); YoyoThrown(from); } } private func OtherYoyoThrownBy(object clonk) { return FindObject2(Find_ID(YOLN), Find_ActionTarget(clonk)) != 0; } /* Function: Hit Event call when hitting solid materials. If the yo-yo was thrown, it returns to the thrower. Parameters: xSpeed - Horizontal speed. ySpeed - Vertical speed. */ protected func Hit(int xSpeed, int ySpeed) { HitEffect(); if(currentState == YOYO_StateThrown) { YoyoReturn(true); } } /* Function: QueryStrikeBlow Event call, called before the yo-yo hits another object. When it was thrown and therefore used as a weapon, the yo-yo will recoil from living beings instead of hitting them normally. Parameters: target - The object the yo-yo is about to hit. Returns: _true_ when recoiling from living beings, _false_ otherwise. */ protected func QueryStrikeBlow(object target) { // Recoil from living beings when used as weapon. if((target->GetOCF() & OCF_Living) != 0) { if(currentState == YOYO_StateThrown || currentState == YOYO_StateReturning) { HitEffect(); target->DoEnergy(-YOYO_Damage); var awayFromThrower = -1; if(GetX() > thrower->GetX()) awayFromThrower = 1; if(target->GetProcedure() != "FLIGHT") { target->SetAction("KneelUp"); // Move target away from thrower, but don't make it stuck in solid materials. for(var i = 0; i < YOYO_MaxHitMoveDistance; i++) { target->SetPosition(target->GetX() + awayFromThrower, target->GetY()); if(target->Stuck()) { target->SetPosition(target->GetX() - awayFromThrower, target->GetY()); break; } } } if(!Random(YOYO_FlingTargetChance)) { Fling(target, awayFromThrower * YOYO_FlingSpeed, -YOYO_FlingSpeed); } if(currentState == YOYO_StateThrown) YoyoReturn(true); return true; } } } private func HitEffect() { Sound("Yo-yo hit"); CastParticles("PxSpark", RandomX(3, 5), 16, 0, 0, 15, 30, RGB(83, 41, 25), RGB(193, 95, 60)); } /* Function: RejectEntrance Reject entrance into other objects than the original thrower when active or returning. Parameters: into - The object that the yo-yo is about to enter. Returns: _true_ if the yo-yo rejects entrance into the object, _false_ if entrance is allowed. */ protected func RejectEntrance(object into) { return (currentState != YOYO_StateInactive && into != thrower); } /* Function: Entrance Event call when entering an object. The yo-yo is set to the inactive state. Parameters: into - The object that the yo-yo entered. */ protected func Entrance(object into) { YoyoInactive(); } /* Section: Yo-yo functionality */ /* Function: GetThrower Returns the object that threw the yo-yo. Returns: The original thrower. */ public func GetThrower() { return thrower; } /* Function: YoyoInactive Sets the yo-yo to inactive state. Clears the scheduled call of "YoyoReturn" and removes returning effects, so it stays inactive. Removes the string between the thrower and the yo-yo and resets the yo-yo's vertex. */ protected func YoyoInactive() { currentState = YOYO_StateInactive; ClearScheduleCall(this, "YoyoReturn"); RemoveEffect("YoyoReturning", this); if(line != 0) { line->RemoveObject(); } SetVertex(0, 2, CNAT_Center); Sound("Yo-yo spin", false, this, 100, 0, -1); } /* Function: YoyoThrown Sets the yo-yo to thrown state. The yo-yo schedules a call of "YoyoReturn" so it only flies for a short time. Additionally, a string attached to the thrower and to the yo-yo is created. _Note_: The flight speed of the yo-yo must be set by the calling code. Parameters: by - The yo-yo was thrown by this object. */ protected func YoyoThrown(object by) { currentState = YOYO_StateThrown; thrower = by; line = CreateObject(YOLN, 0, 0, GetOwner()); ObjectSetAction(line, "Connect", by, this); ScheduleCall(0, "YoyoReturn", YOYO_ThrowFlightTime); Sound("Yo-yo spin", false, this, 100, 0, 1); } /* Function: YoyoReturn Makes the yo-yo return to its original thrower. The cause for returning is distinguished between two cases: * Hitting a solid material or a target. * Reaching the maximum flight timespan (reaching the "end of the string", so to say). While returning, the yo-yo's vertex is set to not collide with solid materials, so the yo-yo can return to the thrower in any case. Parameters: byHit - _true_ if the yo-yo returns because of a hit. */ protected func YoyoReturn(bool byHit) { currentState = YOYO_StateReturning; ClearScheduleCall(this, "YoyoReturn"); AddEffect("YoyoReturning", this, 150, 1, this, 0, byHit); SetVertex(0, 2, CNAT_NoCollision); } /* Yo-yo returning effect */ protected func FxYoyoReturningStart(object target, int effectNumber, int temporary, bool byHit) { if(temporary == 0 && !byHit) { Sound("Yo-yo whoosh", false, target, 25); } } protected func FxYoyoReturningTimer(object target, int effectNumber, int effectTime) { // Problem handling if(target->GetThrower() == 0) return FX_Execute_Kill; if(!target->GetThrower()->GetAlive()) return FX_Execute_Kill; // Approach until close enough for the Clonk to catch the yo-yo if(target->ObjectDistance(target->GetThrower()) > YOYO_MaxCollectionDistance) { var xDistance = target->GetThrower()->GetX() - target->GetX(); var yDistance = target->GetThrower()->GetY() - target->GetY(); // Speed calculation: Approach fast when far away but slow when very close. // Otherwise, if too fast the yo-yo hits the thrower and it oscillates strangely around the Clonk. if(Abs(xDistance) > YOYO_ReturnSlowDownDistance) { var sign = xDistance / Abs(xDistance); target->SetXDir(sign * YOYO_ReturnMaxSpeed); } else { target->SetXDir(xDistance * 4); } target->SetYDir(BoundBy(target->GetThrower()->GetY() - target->GetY(), -50, 50)); return FX_OK; } else { target->Enter(target->GetThrower()); return FX_Execute_Kill; } } protected func FxYoyoReturningStop(object target, int effectNumber, int reason, bool temporary) { if(!temporary) { YoyoInactive(); } }
722,112
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Yo-Yo.c4d/Yo-yo string.c4d/Script.c
#strict 2 protected func Initialize() { Local(0) = 4; // Line colour Local(1) = 4; // Vertex colour SetAction("Connect"); SetVertex(0,0,GetX()); SetVertex(0,1,GetY()); SetVertex(1,0,GetX()); SetVertex(1,1,GetY()); SetPosition(0, 0, this()); }
722,113
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Bomb.c4d/Script.c
/* Script: Steam grenade A grenade that bounces once and detonates on second impact. Bouncing: The steam grenade only bounces off from ceilings with full speed. For walls, the vertical speed is kept but the horizontal speed is reversed and reduced. Similarly for floors, the vertical speed is reversed and reduced while the horizontal speed is kept. The reduced speed is calculated using the following formula: :new speed = -1 * original speed / BOMB_BounceDenominator To ensure bouncing once, the grenade delays the detection of the second impact. This prevents immediate detonations when two vertices touch the landscate at the same time. */ #strict 2 /* Constants: Bouncing BOMB_BounceDenominator - Determines how much the grenade bounces off a surface. BOMB_SecondContactDelay - Determines after how many frames contacs are again evaluated. */ static const BOMB_BounceDenominator = 3; static const BOMB_SecondContactDelay = 5; /* Constants: Detonation BOMB_DetonationRadius - Determines the radius of the detonation effects. BOMB_DamageToStructures - Damage done to structures. BOMB_CrewFlingSpeedY - Vertical speed when the detonation flings crew members. BOMB_CrewFlingSpeedX - Maximum horizontal speed when the detonation flings crew members. BOMB_OtherFlingSpeedY - Vertical speed when the detonation flings objects and vehicles. BOMB_OtherFlingSpeedX - Maximum horizontal speed when the detonation flings objects and vehicles. */ static const BOMB_DetonationRadius = 40; static const BOMB_DamageToStructures = 20; static const BOMB_CrewFlingSpeedY = 3; static const BOMB_CrewFlingSpeedX = 4; static const BOMB_OtherFlingSpeedY = 3; static const BOMB_OtherFlingSpeedX = 5; local isBounced; public func Launch() { SetAction("Active"); Sound("steam_exhaust", false, this, 20, 0, 1); } private func Active() { LeakSteam(); if(FindObject2(Find_AtPoint(0, 0), Find_Category(C4D_Structure)) != 0) { Detonate(); } } private func LeakSteam() { Smoke(0, -3, 5); } private func Detonate() { // Fling crew members, objects and vehicles. Crew members aren't flung as far horizontally to keep it fair. var crew = FindObjects(Find_Category(C4D_Living), Find_OCF(OCF_CrewMember | OCF_InFree), Find_Distance(BOMB_DetonationRadius), Find_NoContainer()); for(var member in crew) { var xDistance = member->GetX() - GetX(); if(Abs(xDistance) < 10 && GetXDir() != 0) { xDistance = 10 * GetXDir() / Abs(GetXDir()); } var xFlingSpeed = BOMB_CrewFlingSpeedX * xDistance / BOMB_DetonationRadius; Fling(member, xFlingSpeed, -BOMB_CrewFlingSpeedY); } var stuffs = FindObjects(Find_Or(Find_Category(C4D_Object), Find_Category(C4D_Vehicle)), Find_OCF(OCF_InFree), Find_Distance(BOMB_DetonationRadius), Find_NoContainer(), Find_Not(Find_Procedure("FLOAT"))); for(var stuff in stuffs) { var xDistance = stuff->GetX() - GetX(); var xFlingSpeed = BOMB_OtherFlingSpeedX * xDistance / BOMB_DetonationRadius; Fling(stuff, xFlingSpeed, -BOMB_OtherFlingSpeedY); } // Damage structures var structures = FindObjects(Find_Category(C4D_Structure), Find_Distance(BOMB_DetonationRadius)); for(var structure in structures) { structure->DoDamage(BOMB_DamageToStructures); } Sound("SteamGrenadeDetonate*"); var steamAmount = RandomX(30, 50); for(var i = 0; i < steamAmount; i++) { BSTE->LaunchSteam(GetX(), GetY(), RandomX(BOMB_DetonationRadius / 2, BOMB_DetonationRadius * 6 / 5), Random(360)); } RemoveObject(); } /* Section: Events */ protected func Initialize() { isBounced = false; } /* Function: Departure If a crew member throws the grenade or drops it in various situations, it activates. Parameters: from - The object the grenade departed from. */ protected func Departure(object from) { if((from->GetOCF() & OCF_CrewMember) != 0 && (from->GetAction() == "Throw" || from->GetProcedure() == "FLIGHT" || from->GetProcedure() == "SCALE" || from->GetProcedure() == "HANGLE")) { Launch(); } } protected func Hit() { Sound("MetalHit*"); CastParticles("PxSpark", RandomX(3, 5), 16, 0, 0, 15, 30, RGB(25, 25, 25), RGB(100, 100, 100)); } protected func ContactTop() { Bounce(GetXDir(), -GetYDir()); } protected func ContactRight() { Bounce(-GetXDir() / BOMB_BounceDenominator, GetYDir()); } protected func ContactBottom() { Bounce(GetXDir(), -GetYDir() / BOMB_BounceDenominator); } protected func ContactLeft() { Bounce(-GetXDir() / BOMB_BounceDenominator, GetYDir()); } private func Bounce(int xSpeed, int ySpeed) { if(GetAction() == "Active") { if(!isBounced) { isBounced = true; // Wait one frame until setting the new speed. Otherwise the current speed is kept unchanged. ScheduleCall(this, "DoBounce", 1, 0, xSpeed, ySpeed); // Don't detonate right now when two vertices have contact at the same time. AddEffect("DelaySecondContact", this, 101, BOMB_SecondContactDelay); } else if(!GetEffect("DelaySecondContact", this)) { Detonate(); } } } public func DoBounce(int xSpeed, int ySpeed) { SetXDir(xSpeed); SetYDir(ySpeed); } protected func QueryStrikeBlow(object target) { Detonate(); }
722,114
./clinfinity/Clinfinity.c4d/Items.c4d/Weapons.c4d/Bomb.c4d/BombSteam.c4d/Script.c
/* Script: Grenade steam Visual steam shock wave effect for the <Steam grenade>. Its animation is divided into two phases: Expansion and fuming. Expansion: * A steam cloud moves from the point where it is created to an end point. * Initially, it moves fast but slows down continuously, until its speed is zero at the end point. * Its speed is calculated using a <geometric series at http://en.wikipedia.org/wiki/Geometric_series>. When creating a shockwave with several steam clouds, the movement in this phase leads to the visual impression that the steam is stopped by air drag. Fuming: * The steam cloud starts moving upwards. * It accelerates until it reaches a randomly chosen maximum speed. * At the same time, it quickly fades out until it disappears completely. */ #strict 2 /* Constants: Expansion phase BSTE_ExpansionNumerator - Numerator used in the geometric series. BSTE_ExpansionDenominator - Denominator used in the geometric series. BSTE_ExpansionFrames - Length of the expansion phase in frames. */ static const BSTE_ExpansionNumerator = 1023; static const BSTE_ExpansionDenominator = 512; static const BSTE_ExpansionFrames = 10; /* Constants: Fuming phase BSTE_MinTargetYSpeed - Minimum value for target vertical speed. BSTE_MaxTargetYSpeed - Maximum value for target vertical speed. */ static const BSTE_MinTargetYSpeed = -10; static const BSTE_MaxTargetYSpeed = -22; local maxXDistance, maxYDistance, transparency, targetYSpeed; /* Function: LaunchSteam Factory method for launching single steam clouds. The coordinates are relative to the calling object in local calls, otherwise global. *Note:* For best results, launch steam using this method. This is not mandatory, though. Parameters: x - Horizontal coordinate. y - Vertical coordinate. maxRadius - Distance between start and end point for the expansion phase. direction - Direction to move in the expansion phase. */ public func LaunchSteam(int x, int y, int maxRadius, int direction) { var steam = CreateObject(BSTE, x, y + 16, NO_OWNER); steam->LocalN("maxXDistance") = Sin(direction, maxRadius); steam->LocalN("maxYDistance") = -Cos(direction, maxRadius); } protected func Initialize() { SetAction("Expanding"); SetDir(Random(15)); SetCon(RandomX(10, 50)); SetR(Random(360)); SetRDir(RandomX(-10, 10)); transparency = RandomX(100, 200); SetClrModulation(RGBa(255, 255, 255, transparency)); } protected func Expand() { if(GetActTime() >= BSTE_ExpansionFrames) { StartFume(); return; } var deltaX = (BSTE_ExpansionDenominator * maxXDistance) / (BSTE_ExpansionNumerator * (GetActTime() + 1)); var deltaY = (BSTE_ExpansionDenominator * maxYDistance) / (BSTE_ExpansionNumerator * (GetActTime() + 1)); SetPosition(GetX() + deltaX, GetY() + deltaY); } protected func StartFume() { SetAction("Fuming"); targetYSpeed = RandomX(BSTE_MinTargetYSpeed, BSTE_MaxTargetYSpeed); SetYDir(-10); } protected func Fume() { if(GetYDir() > targetYSpeed) { SetYDir(GetYDir() - 1); } transparency += 2; if(transparency > 255) { RemoveObject(); } else { SetClrModulation(RGBa(255, 255, 255, transparency)); } }
722,115
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Script.c
/* Script: Hats Library: Provides functionality for hats. */ #strict 2 /* Function: IsHat Yes, it is! Returns: _true_ */ public func IsHat() { return true; } /* Function: QueryStrikeBlow Hats are not supposed to collide with anything, so this always returns _true_. Parameters: target - The target that receives the blow. Returns: _true_ */ public func QueryStrikeBlow(object target) { return true; } /* Function: AttachTo Attaches the hat to a clonk. Parameters: clonk - the clonk */ public func AttachTo(object clonk) { SetAction("Attach", clonk); SetActionData(1); AddEffect("Hat", clonk, 1, 1, this); } /* Function: StartFade Starts the fade effect, eventually removing the hat. */ public func StartFade() { AddEffect("Fade", this, 1, 10, this); } /* Function: AddHat Adds a hat to the calling clonk. Parameters: hatID - the hat's id Returns: The hat. */ global func AddHat(id hatID) { var hat = CreateObject(hatID, 0, 0, GetOwner()); hat->AttachTo(this); return hat; } protected func FxHatTimer(object target, int effectNumber) { // Richtung an Clonk anpassen var rot = 5; var cx, cy; var action = target->GetAction(); var phase = target->GetPhase(); var dir = target->GetDir(); if (action == "Swim") { rot = 0; cx = -5; cy = 2; } else if (action == "Dig" || action == "Bridge") { if (phase > 7) phase = 15-phase; rot = 15-phase*3; cx = -1+phase/3; cy = 6-phase*6/7; } else if (action == "Dive") { rot = BoundBy(phase*15, 5, 40+phase*5); cx = Min(0+phase*2, -3); cy = phase*13/7; } else if (action == "Tumble") { // lose hat SetAction("Idle"); SetXDir(target->GetXDir()); SetYDir(target->GetYDir()); if(GetDir() == DIR_Left) SetRDir(10); else SetRDir(-10); return -1; } else if (action == "Build") { rot = 35; cy += 5; } else if (action == "FlatUp") { rot = (8 - phase) * 10; cy += 10 - phase; } else if(action == "Jump" && target->IsGliding()) { rot = -90; if(dir == DIR_Right) cx = -8; else cx = -5; cy = -8; } if(dir == DIR_Right) { cx = -cx; rot = -rot; } // update SetR(rot); MoveTo(cx, cy, dir == DIR_Right); } protected func FxHatStop(object target, int effectNum, int reason, bool temp) { if(temp) return; SetAction("Idle"); StartFade(); } private func MoveTo(int cx, int cy, bool flip) { var wdt = 1000; if(flip) wdt *= -1; SetObjDrawTransform(wdt, 0, 1000 * cx, 0, 1000, 1000 * cy); } protected func FxFadeTimer(object target, int effectNum, int effectTime) { if(effectTime > 500) { var alpha = EffectVar(0, target, effectNum) + 2; if(alpha >= 255) RemoveObject(); else { SetClrModulation(RGBa(255, 255, 255, alpha)); EffectVar(0, target, effectNum) = alpha; } } }
722,116
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/ScrewGravity.c4d/Script.c
/*-- Gentleman's Reward --*/ #strict 2 #include L_HT
722,117
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Gentlemans Reward.c4d/Script.c
/*-- Gentleman's Reward --*/ #strict 2 #include L_HT
722,118
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Dat Modem Wombat.c4d/Script.c
/*-- DMC --*/ #strict 2 #include L_HT
722,119
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Angry Bird.c4d/Script.c
/*-- Angry Bird --*/ #strict 2 #include L_HT protected func Cackle() { if(!Random(5)) { Sound(Format("Chicken%d", RandomX(1, 6))); } }
722,120
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/FL320.c4d/Script.c
/*-- Beanie Boy --*/ #strict 2 #include L_HT
722,121
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Vermin Hatpreme.c4d/Script.c
/*-- Vermin Hatpreme --*/ #strict 2 #include L_HT
722,122
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Genius Goggles.c4d/Script.c
/*-- Genius Goggles --*/ #strict 2 #include L_HT
722,123
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Mad Hatter.c4d/Script.c
/*-- Gentleman's Reward --*/ #strict 2 #include L_HT
722,124
./clinfinity/Clinfinity.c4d/Items.c4d/Hats.c4d/Beanie Boy.c4d/Script.c
/*-- Beanie Boy --*/ #strict 2 #include L_HT
722,125
./clinfinity/Clinfinity.c4d/System.c4g/Lumberjack.c
#strict 2 #appendto CLNK private func Chopping() { if(_inherited()) { var tree = GetActionTarget(); if(tree->Shrink()) { var matSys = GetMatSys(GetOwner(), true); if(matSys != 0 && InArray(WOOD, GetMatSysIDs())) { matSys->DoFill(1, WOOD); } else { CreateContents(WOOD); } } else FinishCommand(this, true); } return true; }
722,126
./clinfinity/Clinfinity.c4d/System.c4g/SaveMessage.c
#strict 2 #appendto CLNK local name, deathMessage; protected func Recruitment() { name = GetName(); deathMessage = GetObjCoreDeathMessage(); return inherited(...); }
722,127
./clinfinity/Clinfinity.c4d/System.c4g/Material.c
/* Script: Material.c Provides helper functions related to material manipulation. */ #strict 2 /* Function: DrawMaterialHLine Draws a horizontal material line. All coordinates are global. Parameters: matTex - Material-Texture combination for the material to be drawn. x1 - X coordinate of the start point. y1 - Y coordinate of the start point. wdt - Width of the line. sub - If true, the material will be drawn as 'underground'. */ global func DrawMaterialHLine(string matTex, int x, int y, int wdt, bool sub) { return DrawMaterialQuad(matTex, x, y, x, y+1, x+wdt, y, x+wdt, y+1, sub); } /* Function: GetMaterialColorRGB Determines the color of a material. Parameters: mat - Index of the material of which to determine color. number - Material color index (0-2). Returns: The material color as RGB value. */ global func GetMaterialColorRGB(int mat, int number) { return RGB(GetMaterialColor(mat, number, 0), GetMaterialColor(mat, number, 1), GetMaterialColor(mat, number, 2)); }
722,128
./clinfinity/Clinfinity.c4d/System.c4g/Flag.c
// Flag appendto to prevent collection #strict 2 #appendto FLAG protected func RejectEntrance() { return true; }
722,129
./clinfinity/Clinfinity.c4d/System.c4g/Serialize.c
/* Serialisierung der Objekte */ #strict 2 global func GetObjects() { // Objekte serialisieren var data = SerializeObjects(0,0,LandscapeWidth(), LandscapeHeight(), Find_And(Find_Not(Find_Func("IsHUD")),Find_Not(Find_Func("IsLight")))); // Aufbereiten return data; } global func LogObjects() { var objects = GetObjects(); var reference = [[],[]]; var obj, data; var i = 0; // Alle Objekte for (data in objects) { // Daten in data. // [0] ID // [1] X-Pos // [2] Y-Pos // [3] Besitzer // [4] Extra (weitere Aufrufe) // [5] Noch mehr Extra (???) // Sonderbehandlung (z.B. PlaceSpawnpoint) if (data[0] == -1) { Log("%s;",Format(data[4], data[1], data[2])); } // Ansonsten normal else { // CreateObject-String formatieren. var str = Format("CreateObject(%i,%d,%d,%d);",data[0], data[1], data[2], data[3]); var v = false; // falls noch was mit dem Objekt geschieht muss dieses Objekt gemerkt werden for (var extra in data[4]) { // vor den Logs also ausgeben... if(!v) { v = true; Log("var obj%d = %s",i,str); } if (GetType(extra) == C4V_Array) { reference[0][GetLength(reference[0])] = [i, extra]; } else { Log("obj%d->%s;", i, extra); } } for (var j in data[5]) { // auch hier... aber nicht doppelt if(!v) { v = true; Log("var obj%d = %s",i,str); } reference[1][j] = i; } // Variablenname benutzt, hochzΣhlen if(v) { ++i; // ansonsten das CreateObject ausgeben } else { Log(str); } } } for (data in reference[0]) { // Hier kommt es normalerweise zu einem BUG!!! :( Log("obj%d->%s;", data[0], Format(data[1][0], reference[1][data[1][1]], reference[1][data[1][2]], reference[1][data[1][3]], reference[1][data[1][4]], reference[1][data[1][5]])); } } global func SerializeObjects(iX, int iY, int iW, int iH, exclusions) { // ArraykompabilitΣt if (!iW || !iH) { iY = iX[1]; iW = iX[2]; iH = iX[3]; iX = iX[0]; } var exp = Find_And( Find_InRect(iX, iY, iW, iH), Find_Not(Find_Func("NoSerialize")), Find_Not(Find_Category(C4D_Goal)), Find_Not(Find_Category(C4D_Rule)), Find_Not(Find_Category(C4D_Environment)) ); if (exclusions) exp = Find_And(exp, exclusions); var search = FindObjects(exp); var objects = CreateArray(2); objects[0] = CreateArray(GetLength(search)); // Vorallokierung objects[1] = CreateArray(GetLength(search)); var extra, extray, i = 0; for(obj in search) { // wenn das Objekt von seinem Container gel÷scht werden soll if (obj->Contained() && obj->Contained()->~RejectContainedSerialize(obj)) { // Allokierung kⁿrzen SetLength(objects[0], GetLength(objects[0])-1); SetLength(objects[1], GetLength(objects[1])-1); continue; } // AufrΣumen extra = CreateArray(); extray = 0; // Objektzeiger temporΣr aufbewahren objects[1][i] = obj; // Rotation if (obj->GetR() != 0) extra[GetLength(extra)] = Format("SetR(%d)", obj->GetR()); // Gr÷▀e if (obj->GetCon() != 100) { extra[GetLength(extra)] = Format("SetCon(%d)", obj->GetCon()); extray = -GetDefCoreVal("Offset", "DefCore", GetID(obj), 1) * (100-obj->GetCon()) / 100; } if (obj->Contained()) { extra[GetLength(extra)] = Format("Enter(Object(%d))", obj->Contained()); } // Sonderbehandlung if (obj->~Serialize(extra, extray)) { // Kein CreateObject(ID, relative Position, Besitzer)->Extracalls Verfahren. // Hier nur eval(Format(extra,x,y)) objects[0][i++] = [-1, -iX, -iY, 0, extra]; continue; } // Aufzeichnen objects[0][i++] = [ GetID(obj), -iX+GetX(obj), -iY+GetY(obj)-GetDefCoreVal("Offset", "DefCore", GetID(obj), 1)-extray, GetOwner(obj), extra, []]; } // Objektzeiger in den extras aufbereiten i = 0; // Index der Objektzeigerliste for (var index_object=0; index_object<GetLength(objects[0]); ++index_object) { // eigene eval formatierte Aufrufe brauchen keine Objektzeiger if (objects[0][index_object][0] == -1) continue; for (var index_extra=0; index_extra<GetLength(objects[0][index_object][4]); ++index_extra) { // keine Strings, nur [String, obj, ...] Inhalte if (GetType(objects[0][index_object][4][index_extra]) != C4V_Array) continue; for (var index_pointer=1; index_pointer<GetLength(objects[0][index_object][4][index_extra]); ++index_pointer) { // den Zeiger in der temporΣren Liste object[1] suchen for (var j=0; j<GetLength(objects[1]); ++j) { if (objects[0][index_object][4][index_extra][index_pointer] == objects[1][j]) { // das Zielobjekt markieren, damit es sich in die Verfⁿgbarkeitsliste eintrΣgt objects[0][j][5][GetLength(objects[0][j][5])] = i; // und die Referenz auf das Objekt in der Liste setzen objects[0][index_object][4][index_extra][index_pointer] = i; ++i; break; } } } } } return objects[0]; } global func DeserializeObjects(array objects, int x, int y) { var reference = [[],[]]; var obj, data; for (data in objects) { if (data[0] == -1) { // Sonderbehandlung eval(data[4], data[1]+x, data[2]+y); } else { obj = CreateObject(data[0], data[1]+x, data[2]+y, data[3]); for (var extra in data[4]) { if (GetType(extra) == C4V_Array) { reference[0][GetLength(reference[0])] = [obj, extra]; } else { eval(Format("Object(%d)->%s", ObjectNumber(obj), extra)); } } for (var i in data[5]) { reference[1][i] = obj; } } } for (data in reference[0]) { eval(Format("Object(%d)->%s", ObjectNumber(data[0]), Format(data[1][0], ObjectNumber(reference[1][data[1][1]]), ObjectNumber(reference[1][data[1][2]]), ObjectNumber(reference[1][data[1][3]]), ObjectNumber(reference[1][data[1][4]]), ObjectNumber(reference[1][data[1][5]])))); } } /* TODO!!! */ // Hazardclonk (KI Commands, ...) /* UNWICHTIG :D */ // Leitern (auf Arrays umstellen und bla) // Wegpunkte (arrive command data auch objekt-referenzieren)
722,130
./clinfinity/Clinfinity.c4d/System.c4g/HashTable.c
/* HashTable.c * * Copyright (c) 2008 Nicolas Hake * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #strict 2 /** Create an empty hash. */ global func CreateHash() { return [0, [[]]]; } /** Insert a value into a hash. * \param[in,out] hash The hash to modify * \param[in] key The key of the element * \param[in] val The value of the element * \return An iterator pointing in front of the inserted element */ global func HashPut(&hash, key, val) { _Hash_Resize(hash); var hashval = _Hash_HashVal(key); var bidx = _Hash_UMod(hashval, GetLength(hash[_Hash_Bucket])); if(!Inside(bidx, 0, GetLength(hash[_Hash_Bucket]) - 1)) Log("bidx out of bounds: %d (of %d)", bidx, GetLength(hash[_Hash_Bucket]) - 1); for(var i = 0; i < GetLength(hash[_Hash_Bucket][bidx]); ++i) { if(key == hash[_Hash_Bucket][bidx][i][_HashNode_Key]) { hash[_Hash_Bucket][bidx][i][_HashNode_Val] = val; return [hash, bidx, i]; } } var ni = GetLength(hash[_Hash_Bucket][bidx]); hash[_Hash_Bucket][bidx][ni] = [key, val, hashval]; ++hash[_Hash_Size]; return [hash, bidx, ni]; } /** Find a value in a hash. * \param[in] hash The haystack * \param[in] key The needle * \return An iterator pointing in front of the inserted element. If no element with the * given \p key exists, an iterator pointing behind the last element is returned. * \sa HashIterHasNext */ global func HashFind(&hash, key) { var hashval = _Hash_HashVal(key); var bidx = _Hash_UMod(hashval, GetLength(hash[_Hash_Bucket])); for(var i = 0; i < GetLength(hash[_Hash_Bucket][bidx]); ++i) { if(key == hash[_Hash_Bucket][bidx][i][_HashNode_Key]) { return [hash, bidx, i]; } } var it = HashIter(hash); HashIterToBack(it); return it; } /** Checks for the existence of an element with a given key. * \param[in] hash The hash to search * \param[in] key The key to find * \return \c true if an element with the key \c key exists, \c false otherwise. */ global func HashContains(&hash, key) { var it = HashFind(hash, key); return HashIterHasNext(it); } /** Get a value from a hash. * \param[in] hash The hash to search in * \param[in] key The key of the wanted element * \param[in] returnSuccess Whether to indicate success with the return value * \return If \p returnSuccess is \c false, returns the value of the element with the given * \p key, or 0 if no element is found. If \p returnSuccess is \c true, returns an array * which has the value as first element. The second element indicates whether a match was * found. */ global func &HashGet(&hash, key, bool returnSuccess) { var hashval = _Hash_HashVal(key); var bidx = _Hash_UMod(hashval, GetLength(hash[_Hash_Bucket])); for(var i = 0; i < GetLength(hash[_Hash_Bucket][bidx]); ++i) { if(key == hash[_Hash_Bucket][bidx][i][_HashNode_Key]) { if(returnSuccess) return [hash[_Hash_Bucket][bidx][i][_HashNode_Val], true]; else return hash[_Hash_Bucket][bidx][i][_HashNode_Val]; } } if(returnSuccess) return [0, false]; else return 0; } /** Remove an element from a hash. * \param[in,out] hash The hash to modify * \param[in] key The key of the element to be removed * \return \c true if an element was removed, \c false otherwise. */ global func HashErase(&hash, key) { var hashval = _Hash_HashVal(key); var bidx = _Hash_UMod(hashval, GetLength(hash[_Hash_Bucket])); var found = false; for(var i = 0; i < GetLength(hash[_Hash_Bucket][bidx]); ++i) { if(found) { hash[_Hash_Bucket][bidx][i - 1] = hash[_Hash_Bucket][bidx][i]; } else if(key == hash[_Hash_Bucket][bidx][i][_HashNode_Key]) { found = true; } } if(found) { SetLength(hash[_Hash_Bucket][bidx], GetLength(hash[_Hash_Bucket][bidx]) - 1); --hash[_Hash_Size]; } _Hash_Resize(hash); return found; } /** Returns the number of elements in the hash. */ global func HashSize(&hash) { return hash[_Hash_Size]; } /** Create an iterator on a hash. * \param[in] hash The hash to iterate over */ global func HashIter(&hash) { return [hash, 0, 0]; } /** Checks whether the iterator can advance. * \param[in] iter The iterator in question * \return \c true if there is at least one more element, \c false if \p iter points at the * back of the corresponding hash. */ global func HashIterHasNext(&iter) { var ni = iter[_HashIter_Node]; for(var bi = iter[_HashIter_Bucket]; bi < GetLength(iter[_HashIter_Hash][_Hash_Bucket]); ++bi) { if(ni < GetLength(iter[_HashIter_Hash][_Hash_Bucket][bi])) return true; ni = 0; } return false; } /** Advances the iterator. * \param[in,out] iter The iterator to advance * \return An array of [key, value] of the element traversed, or 0 if \p iter pointed at * the back of the hash. */ global func HashIterNext(&iter) { var ni = iter[_HashIter_Node]; var val; for(var bi = iter[_HashIter_Bucket]; bi < GetLength(iter[_HashIter_Hash][_Hash_Bucket]); ++bi) { if(ni < GetLength(iter[_HashIter_Hash][_Hash_Bucket][bi])) { val = iter[_HashIter_Hash][_Hash_Bucket][bi][ni]; iter[_HashIter_Bucket] = bi; iter[_HashIter_Node] = ni + 1; return val; } ni = 0; } return 0; } /** Checks whether the iterator can step back. * \param[in] iter The iterator in question * \return \c true if there is at least one element before the current one, \c false if \p * iter points at the beginning of the hash. */ global func HashIterHasPrev(&iter) { if(iter[_HashIter_Node]) return true; for(var bi = iter[_HashIter_Bucket] - 1; bi >= 0; --bi) { if(GetLength(iter[_HashIter_Hash][_Hash_Bucket][bi])) return true; } return false; } /** Moves the iterator backwards. * \param[in,out] iter The iterator to move * \return An array of [key, value] of the element traversed, or 0 if \p iter pointed at * the beginning of the hash. */ global func HashIterPrev(&iter) { if(iter[_HashIter_Node]) { return iter[_HashIter_Hash][_Hash_Bucket][iter[_HashIter_Bucket]] [--iter[_HashIter_Node]]; } for(var bi = iter[_HashIter_Bucket] - 1; bi >= 0; --bi) { iter[_HashIter_Node] = GetLength(iter[_HashIter_Hash] [_Hash_Bucket][bi]); if(iter[_HashIter_Node] > 0) { iter[_HashIter_Bucket] = bi; return iter[_HashIter_Hash][_Hash_Bucket][iter[_HashIter_Bucket]] [--iter[_HashIter_Node]]; } } iter[_HashIter_Bucket] = iter[_HashIter_Node] = 0; return 0; } /** Moves the iterator to the front of the hash. */ global func HashIterToFront(&iter) { iter[_HashIter_Bucket] = iter[_HashIter_Node] = 0; return iter; } /** Moves the iterator to the back of the hash. */ global func HashIterToBack(&iter) { iter[_HashIter_Bucket] = GetLength(iter[_HashIter_Hash][_Hash_Bucket]) - 1; iter[_HashIter_Node] = GetLength(iter[_HashIter_Hash][_Hash_Bucket] [iter[_HashIter_Bucket]]); return iter; } /*---- Implementation detail follows. ----* *---- Function presence and/or semantics may change ----* *---- at any time. Do NOT rely on these to last. ----* *---- YOU HAVE BEEN WARNED. ----*/ // Array indices static const _Hash_Size = 0; static const _Hash_Bucket = 1; static const _HashNode_Key = 0; static const _HashNode_Val = 1; static const _HashNode_Hash = 2; static const _HashIter_Hash = 0; static const _HashIter_Bucket = 1; static const _HashIter_Node = 2; global func _Hash_DebugDump(&hash) { Log("Hash debug dump"); Log("Entries: %d. Buckets: %d. Load factor: %d.", hash[_Hash_Size], GetLength(hash[_Hash_Bucket]), _Hash_LoadFactor(hash)); Log("--------------------"); var iter = HashIter(hash); var v; for(;;) { v = HashIterNext(iter); if(!v) break; Log("[%d @%d,%d] %s: %v => %s: %v", v[2], iter[_HashIter_Bucket], iter[_HashIter_Node] - 1, _Hash_DebugDump_Type(GetType(v[0])), v[0], _Hash_DebugDump_Type(GetType(v[1])), v[1]); } Log("--------------------"); } global func _Hash_DebugDump_Type(int t) { if(t == C4V_String) return "string"; if(t == C4V_Int) return "int"; if(t == C4V_C4Object) return "object"; if(t == C4V_C4ID) return "id"; if(t == C4V_Array) return "array"; if(t == C4V_Bool) return "bool"; return "any"; } global func _Hash_Resize(&hash) { var lf = _Hash_LoadFactor(hash); var buckets, bc = GetLength(hash[_Hash_Bucket]); if(lf > 75) { // MOAR BUCKETS! bc *= 2; } else if(lf < 25) { // Less buckets bc /= 2; ++bc; } if(bc == GetLength(hash[_Hash_Bucket])) return; buckets = CreateArray(bc); for(var i = 0; i < bc; ++i) { buckets[i] = []; } // Move each node to new bucket for(var b in hash[_Hash_Bucket]) { for(var n in b) { buckets[_Hash_UMod(n[_HashNode_Hash], bc)] [GetLength(buckets[_Hash_UMod(n[_HashNode_Hash],bc)])] = n; } } hash[_Hash_Bucket] = buckets; } global func _Hash_LoadFactor(&hash) { return hash[_Hash_Size]*100/GetLength(hash[_Hash_Bucket]); } global func _Hash_HashVal(val) { var h = 0; if(!val) { return 0; } else if(GetType(val) == C4V_String) { // sdbm hash function for(var i = 0, c; c = GetChar(val, i++);) { h = c + (h << 16) + (h << 6) - h; } return h; } else if(GetType(val) == C4V_Int || GetType(val) == C4V_Bool) { // cf. Knuth, sec. 6.4 return val * 0x9e3779b1; } else if(GetType(val) == C4V_C4Object) { return _Hash_HashVal(val->ObjectNumber()); } else if(GetType(val) == C4V_Array) { for(var v in val) { h = _Hash_HashVal(v) + (h << 16) + (h << 6) - h; } return h; } else if(GetType(val) == C4V_C4ID) { return _Hash_HashVal(CastInt(val)); } else { FatalError("Type not hashable"); } } global func _Hash_UMod(int a, int b) { if(a < 0) a += (Abs(a/b) + 1) * b; return a % b; }
722,131
./clinfinity/Clinfinity.c4d/System.c4g/Arrays.c
/* Script: Arrays Various helper functions for working with arrays. */ #strict 2 /* Function: InArray Tests if a value is contained in an array. Parameters: Test - The value to test. aArray - The array that might contain the value. Returns: *true* if Test is in aArray, *false* otherwise. */ global func InArray(Test, array aArray) { return GetIndexOf(Test, aArray) != -1; } // Sucht einen Wert im Array und l÷scht diesen global func RemoveArrayValue(Test, array &aArray) { // Aus der Liste l÷schen var i = GetLength(aArray), iLength = GetLength(aArray); while(i--) if(aArray[i] == Test) { aArray[i] = 0; while(++i < iLength) aArray[i-1] = aArray[i]; SetLength(aArray, iLength-1); return 1; } return 0; } global func ShuffleArray(array& aArray) { var rnd; var iCount = GetLength(aArray); var aShuffled = CreateArray(iCount); for(var i = 0; i < iCount; i++) { rnd = Random(iCount-i); aShuffled[i] = aArray[rnd]; DeleteArrayItem2(rnd, aArray); } aArray = aShuffled; return aShuffled; } //L÷scht ein Item aus einem Array global func DeleteArrayItem(iNumber, &aArray) { var temp=[]; for(var cnt;cnt<GetLength(aArray);cnt++) { if(cnt==iNumber)continue; var dif=0; if(cnt>iNumber)dif=-1; temp[cnt+dif]=aArray[cnt]; } aArray=temp; return aArray; } //L÷scht ein Item aus einem Array, kann m÷glicherweise umsortieren global func DeleteArrayItem2(iNumber,&aArray) { //Ein ganz leeres Array? if(GetLength(aArray)==1)return (aArray=CreateArray()); //Wenn das letzte Element ist diese Funktion auch nciht toller. if(GetLength(aArray)-1==iNumber) return DeleteArrayItem(iNumber, aArray); //Los! var last=aArray[GetLength(aArray)-1]; aArray[GetLength(aArray)-1]=0; SetLength(aArray,GetLength(aArray)-1); aArray[iNumber]=last; return aArray; } //Sucht ein Item im array global func GetArrayItemPosition(&value,&aArray) { //2do: remove that return GetIndexOf(value, aArray); } /* Function: PushBack Appends an element to an array. Parameters: value - The element to append. aArray - The array that gets appended to. */ global func PushBack(value, &aArray) { aArray[GetLength(aArray)] = value; } //Fⁿgt ein Item am Anfang ein global func PushFront(value,&aArray) { var aNew=[]; aNew[GetLength(aNew)]=value; for(var cnt=0;cnt<GetLength(aArray);cnt++) aNew[GetLength(aNew)]=aArray[cnt]; aArray=aNew; return 1; } //Fⁿhrt mit jedem Item im Array einen beliebigen Vergleich vor, der als String vorliegen sollte und gibt ein Array mit Ergebnissen zurⁿck // zB ForEach("<0",myArray); // ForEach("->~IsClonk()",myArray); /*global func ForEach(sFunction,aArray) { var aResults=[]; Log("%d",GetLength(aArray)); for(var cnt=0;cnt<GetLength(aArray);cnt++) { //var result= // eval(Format("Var(0)=(aArray[%d]%s)",cnt,sFunction)); Var(0)=eval(Format("(%d%s)",aArray[cnt],sFunction)); PushBack(Var(0),aResults); } return aResults; } global func Test() { var arr=[]; arr[GetLength(arr)]=1; arr[GetLength(arr)]=20; arr[GetLength(arr)]=34; arr[GetLength(arr)]=21; arr[GetLength(arr)]=564; arr[GetLength(arr)]=13; arr[GetLength(arr)]=4; arr[GetLength(arr)]=76; arr[GetLength(arr)]=124; var res=ForEach("<150",arr); for(var integer in res) Log("%d",integer); }*/ //blame JCaesar if this function sucks: global func PopElements(array &aArray, int iStart, int iCount) { if(iCount < 1) iCount = 1; for(iStart+iCount; iStart<GetLength(aArray); iStart++) { aArray[iStart-iCount] = aArray[iStart]; } SetLength(aArray, GetLength(aArray)-iCount); } global func ConcatArrays(array a, array b) { var lenA = GetLength(a), lenB = GetLength(b); SetLength(a, lenA + lenB); for(var i = 0; i < lenB; i++) a[lenA + i] = b[i]; return a; } /* Function: RemoveElement Removes the indicated element from the array. Might not preserve the order of elements. Parameters: element - The element to remove. targetArray - The array to remove the element from. Returns: *true* if the element was removed, *false* otherwise. */ global func RemoveElement(element, array &targetArray) { var length = GetLength(targetArray); for(var i = 0; i < length; i++) { if(targetArray[i] == element) { if(i <= length - 1) { // Move last element here targetArray[i] = targetArray[length - 1]; } // Shorten by one SetLength(targetArray, length - 1); return true; } } return false; } /* Function: PopElement Removes the first element from an array without reordering. Parameters: targetArray - The array. Returns: The removed element. */ global func PopElement(array &targetArray) { var element = targetArray[0]; DeleteArrayItem(0, targetArray); return element; }
722,132
./clinfinity/Clinfinity.c4d/System.c4g/MatSys.c
/* Script: MatSys.c Contains some global helper function for using the Material System from arbitrary objects. */ #strict 2 /* Function: CreateMatSys Creates a material system for the given player or for every player if iPlr == NO_OWNER. Parameters: iPlr - The player for whom the material system should be created or NO_OWNER. */ global func CreateMatSys(int iPlr) { if(iPlr == NO_OWNER) for(var i = 0; i < GetPlayerCount(); i++) CreateMatSys(GetPlayerByIndex(i)); else CreateObject(MSYS, 0, 0, iPlr); } /* Function: GetMatSys Returns the material system for the given player, creating one if there is none. Parameters: iPlr - The player whose material system should be returned. bDoNotCreateMatSys - When true, the function won't create a material system for that player. Returns: The material system for the given player or 0 if there is none. */ global func GetMatSys(int iPlr, bool bDoNotCreateMatSys) { if(GetType(aMaterialSystem) != C4V_Array || !aMaterialSystem[iPlr]) { if(!bDoNotCreateMatSys) CreateMatSys(iPlr); else return; } return aMaterialSystem[iPlr]; } /* Function: MatSysGetFill Parameters: iPlr - The player whose fill level should be returned. Key - The material id. Returns: The fill level. */ global func MatSysGetFill(int iPlr, id Key) { return GetMatSys(iPlr) -> GetFill(Key); } /* Function: MatSysGetTeamFill Parameters: plr - A player of the team whose fill level should be returned. Key - The material id. Returns: The combined fill level of all team members. */ global func MatSysGetTeamFill(int plr, id Key) { var fill = 0; for(var count = GetPlayerCount(), i = 0; i < count; i++) { var p = GetPlayerByIndex(i); if(!Hostile(plr, p)) fill += MatSysGetFill(p, Key); } return fill; } /* Function: MatSysDoFill Changes the fill level for a given player/id. Parameters: iChange - The amount of change. iPlr - The player whose fill level should be changed. Key - The material id. noMsg - Don't output a message. Note: You should probably define *NoMatSysMessages(id mat) instead, see <MatSysMessage>. Returns: The actual change. */ global func MatSysDoFill(int iChange, int iPlr, id Key, bool noMsg) { var actual = GetMatSys(iPlr) -> DoFill(iChange, Key); if(!noMsg) MatSysMessage(actual, Key); return actual; } /* Function: MatSysDoTeamFill Changes the fill level for a given team/id. Parameters: change - The amount of change. plr - A player of the team whose fill level should be changed. Key - The material id. Returns: The actual change. */ global func MatSysDoTeamFill(int change, int plr, id Key) { var orig = change; // first, try the given player change -= MatSysDoFill(change, plr, Key, true); // then, loop through the other players for(var count = GetPlayerCount(), i = 0; i < count && change != 0; i++) { var p = GetPlayerByIndex(i); if(!Hostile(plr, p)) { change -= MatSysDoFill(change, p, Key); } } var actual = orig - change; MatSysMessage(actual, Key); return actual; } /* Function: MatSysSubtractComponents Tries to subtract the components of the specified object. *Important:* This function ignores materials not managed by the material system, so the return values only relate to those actually in the system. This removes the ambiguity whether _false_ means that something is managed but just not in storage currently, or not managed at all. Any other materials should be handled by the calling code appropriately. Parameters: definition - The definition whose components should be subtracted. player - A player of the team whose MatSys should be used. Returns: _true_ if all materials were in storage, _false_ otherwise. */ global func MatSysSubtractComponents(id definition, int player) { var components = []; for(var i = 0, comp, num; (comp = GetComponent(0, i, 0, definition)) && (num = GetComponent(comp, i, 0, definition)); i++) { if(!InArray(comp, GetMatSysIDs())) continue; if(MatSysGetTeamFill(player, comp) < num) { return false; } PushBack([comp, num], components); } for(var c in components) MatSysDoTeamFill(-c[1], player, c[0]); return true; } /* Function: GetMatSysIDs Defines the material system ids. This function will call the scenario's function SpecialMatSysIDs, which will be prepended to the list. This allows a scenario to have special materials. Returns: An array containing the material system ids. */ global func GetMatSysIDs() { var aIDs = [STEM, WOOD, ROCK, METL]; ConcatArrays(aIDs, GameCall("SpecialMatSysIDs")); // vertauschte Reihenfolge, da von rechts nach links return aIDs; }
722,133
./clinfinity/Clinfinity.c4d/System.c4g/String.c
/* Script: String.c Some helper functions for using strings. */ #strict 2 /* Function: Substring Returns a subset of a string between one index and another, or through the end of the string. <Substring> extracts characters from indexA up to but not including indexB. When indexB is omitted or 0 the function will extract characters to the end of the string. Parameters: str - The string. indexA - An integer between 0 and one less than the length of the string. indexB - (optional) An integer between 0 and the length of the string. Returns: The specified substring. */ global func Substring(string str, int indexA, int indexB) { var len = GetLength(str), result = ""; if(indexA < 0) indexA = 0; if(indexB <= 0) indexB = len; for(var i = indexA; i < indexB && i < len; i++) result = Format("%s%s", result, GetStrChar(str, i)); return result; } /* Function: IndexOf Parameters: str - The string in which will be searched. searchValue - A string representing the value to search for. fromIndex - The location within the string to start the search from. Returns: The index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, or -1 if the value is not found. */ global func IndexOf(string str, string searchValue, int fromIndex) { var len = GetLength(str), slen = GetLength(searchValue); for(var i = fromIndex; i < len - slen; i++) { var matching = true; for(var j = 0; j < slen; j++) { if(GetChar(str, i + j) != GetChar(searchValue, j)) { matching = false; break; } } if(matching) return i; } return -1; } /* Function: IntToStr Converts an integer to a string. Parameters: num - The number to convert. keepSign - Also include a + for positive numbers. Returns: The string containing the integer. */ global func IntToStr(int num, bool keepSign) { if(keepSign && num > 0) return Format("+%d", num); else return Format("%d", num); } /* Function: GetStrChar Combination of <GetStr> and <GetChar>. Parameters: str - The string whose character will be extracted. pos - The position of the character to extract. Returns: A string containing the character at the given position. */ global func GetStrChar(string str, int pos) { return GetStr(GetChar(str, pos)); } /* Function: GetStr Maps characters according to CP-1252. Parameters: char - ASCII code Returns: A string that contains the corresponding character. */ global func GetStr(int char) { return [" ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "DEL", "Ç", "", "é", "â", "ä", "à", "å", "ç", "ê", "ë", "è", "ï", "î", "", "Ä", "", "", "æ", "Æ", "ô", "ö", "ò", "û", "ù", "ÿ", "Ö", "Ü", "¢", "£", "", "₧", "ƒ", "NBSP", "í", "ó", "ú", "ñ", "Ñ", "ª", "º", "¿", "⌐", "¬", "½", "¼", "SHY", "«", "»", "░", "▒", "▓", "│", "┤", "╡", "╢", "╖", "╕", "╣", "║", "╗", "╝", "╜", "╛", "┐", "└", "┴", "┬", "├", "─", "┼", "╞", "╟", "╚", "╔", "╩", "╦", "╠", "═", "╬", "╧", "╨", "╤", "╥", "╙", "╘", "╒", "╓", "╫", "╪", "┘", "┌", "█", "▄", "▌", "▐", "▀", "α", "ß", "Γ", "π", "Σ", "σ", "µ", "τ", "Φ", "Θ", "Ω", "δ", "∞", "φ", "ε", "∩", "≡", "±", "≥", "≤", "⌠", "⌡", "÷", "≈", "°", "∙", "·", "√", "ⁿ", "²", "■", " "][char - 32]; }
722,134
./clinfinity/Clinfinity.c4d/System.c4g/WingSuit.c
#strict 2 #appendto CLNK local maxGlideSpeedY, glideSpeedXFactor; local glideParticleColour; protected func Initialize() { maxGlideSpeedY = 30; glideSpeedXFactor = 2; glideParticleColour = RGBa(255, 255, 255, 210); return _inherited(); } protected func ControlDownSingle() { var result = _inherited(); if( result == 0 ) { if(GetAction() == "Jump" || GetAction() == "Dive") { if(IsGliding()) { RemoveEffect("WingSuit", this); } else if(GetPhase() > 3) { AddEffect("WingSuit", this, 150, 1, this); } else { return 0; } return true; } } else { return result; } return 0; } public func IsGliding() { return GetEffect("WingSuit", this) != 0; } protected func FxWingSuitStart(object target, int effectNumber, int temporary) { if(temporary == 0) { Sound("SailDown", false, target, 50); if(target->GetAction() != "Jump") target->SetAction("Jump"); } } protected func FxWingSuitTimer(object target, int effectNumber, int effectTime) { if(target->GetAction() == "Jump") { // Maximale Sinkgeschwindigkeit if( target->GetYDir() > maxGlideSpeedY ) { target->SetYDir( target->GetYDir() - 2 ); } // Horizontale Geschwindigkeit berechnen und anpassen var targetXDir = Max( Abs(target->GetYDir()), 5 ) * (-glideSpeedXFactor + 2 * glideSpeedXFactor * target->GetDir()); var currentXDir = target->GetXDir(); if(currentXDir < targetXDir) { target->SetXDir( target->GetXDir() + 1 ); } else if(currentXDir > targetXDir) { target->SetXDir( target->GetXDir() - 1 ); } // Rotiert die Jump-Animation, sodass es aussieht, als wⁿrde der Clonk einen Wingsuit tragen. SetObjDrawTransform(0, 1000 - 2000 * target->GetDir(), 0, -1000, 0, 0); if(!Random(9)) { CreateParticle("NoGravSpark", RandomX(-7, 7), RandomX(-3, 3), target->GetXDir() / 2, target->GetYDir() / 2, 40, glideParticleColour); } return 0; } else { return -1; } } protected func FxWingSuitStop(object target, int effectNumber, int reason, bool temporary) { if(!temporary) { Sound("SailUp", false, target, 50); SetObjDrawTransform(1000, 0, 0, 0, 1000, 0, 0); } } /* Prevents the Clonk from tumbling after hitting something while gliding. */ protected func Hit(int xdir, int ydir) { if(IsGliding() && GetAction() == "Tumble") { SetXDir(BoundBy(xdir, -10, 10)); SetYDir(BoundBy(ydir, -10, 10)); SetAction("Jump"); } return _inherited(xdir, ydir, ...); }
722,135
./clinfinity/Clinfinity.c4d/System.c4g/MatSysCollection.c
/* Manages collection of MatSys materials. */ #strict 2 #appendto CLNK protected func Collection(object obj) { var ID = obj->GetID(); if(InArray(ID, GetMatSysIDs())) { var matSys = GetMatSys(GetOwner(), true); if(matSys) { matSys->DoFill(1, ID); obj->RemoveObject(); return; } } return _inherited(obj, ...); }
722,136
./clinfinity/Clinfinity.c4d/System.c4g/FragileRock.c
#strict 2 #appendto ROCK protected func Hit() { _inherited(...); if(GetOCF() & OCF_HitSpeed4) { var colourIndex = Random(3); var red = GetMaterialColor(Material("Rock"), colourIndex, 0); var green = GetMaterialColor(Material("Rock"), colourIndex, 1); var blue = GetMaterialColor(Material("Rock"), colourIndex, 2); CastParticles("MatSpark", RandomX(3, 6), RandomX(20, 30), 0, 0, 40, 60, RGBa(red, green, blue, 50), RGBa(red, green, blue, 50)); Sound("Rock_burst"); RemoveObject(); } }
722,137
./clinfinity/Clinfinity.c4d/System.c4g/PullUp.c
#strict 2 #appendto CLNK local maxPullUpHeight; protected func Initialize() { maxPullUpHeight = 10; return _inherited(); } protected func ControlUp() { var result = _inherited(); if( result == 0 ) { if( GetAction() == "Hangle" && GetComDir() == COMD_None ) { for(var i = -11; i > -11 - maxPullUpHeight; i--) { if(!GBackSemiSolid(0, i)) { SetPosition(GetX(), GetY() + i - (GetDefHeight(GetID()) / 2) + 1); SetAction("FlatUp"); break; } } return true; } } else { return result; } return 0; }
722,138
./clinfinity/Clinfinity.c4d/System.c4g/DeactivateFlag.c
/*-- No Homebase --*/ //needed to avoid buy-menue on frigate #strict #appendto FLAG func ResetCategory() { SetCategory(2576); return; }
722,139
./clinfinity/Clinfinity.c4d/System.c4g/DoubleJump.c
#strict 2 #appendto CLNK local doubleJumpPossible; local jumpParticleColour; local maxDoubleJumpStartSpeed, doubleJumpAcceleration; protected func Initialize() { jumpParticleColour = RGBa(255, 255, 255, 150); maxDoubleJumpStartSpeed = 50; doubleJumpAcceleration = 34; return _inherited(); } protected func ControlLeft() { if( _inherited() == 0 ) { if( GetAction() == "Jump" ) { SetDir( DIR_Left ); } } return 0; } protected func ControlRight() { if( _inherited() == 0 ) { if( GetAction() == "Jump" ) { SetDir( DIR_Right ); } } return 0; } protected func ControlUp() { var result = _inherited(); if( result == 0 ) { if( GetAction() == "Jump" ) { if( doubleJumpPossible ) { doubleJumpPossible = false; if( GetDir() == DIR_Left ) { SetXDir( -1 * Abs( GetXDir() ) ); } else { SetXDir( Abs( GetXDir() ) ); } // To make double jumping useful when flying upwards, add more speed if(GetYDir() < 0) { SetYDir(-Sqrt(GetYDir() ** 2 + doubleJumpAcceleration ** 2)); } else { SetYDir(-doubleJumpAcceleration); } for( var i = 0; i < 7; i++ ) { CreateParticle("MSpark", -3 + i, 9 + Random(3), -3 + i, 8 - Random(3), 40, jumpParticleColour); } Sound("DoubleJump"); return true; } } } else { return result; } return 0; } protected func MakeDoubleJumpPossible() { doubleJumpPossible = true; } protected func CheckStuck() { if(GetAction() == "Jump") { // Visual clue that double jump is not available any more: Tumble if falling speed is too high. if(GetYDir() > maxDoubleJumpStartSpeed && !(this->~IsGliding())) { SetAction("Tumble"); } } return _inherited(); }
722,140
./clinfinity/Clinfinity.c4d/System.c4g/Ease.c
/* Script: Ease.c Provides some universal easing functions. */ #strict 2 /* Function: CreateEaseFunction Creates an easing function for later use with <EvalEase>. Possible easing functions are: - poly(k): raises t to the specified power k (last parameter) - quad: equivalent to poly(2) - cubic: equivalent to poly(3) - sin: applies the trigonometric function *sin* - circle: a quarter circle Possible modes are: - in: the identity function - out: reverses the easing direction - in-out: copies and mirrors the easing function from [0, max/2] and [max/2, max] Parameters: function - The easing function (see above), and an optional mode (see above) separated by a minus. Example: "cubic-in-out" max - The maximum for t (see <EvalEase>). Returns: An easing function. */ global func CreateEaseFunction(string function, int max) { var i = IndexOf(function, "-"); var f, mode; if(i >= 0) { f = Substring(function, 0, i); mode = Substring(function, i + 1); } else { f = function; mode = "in"; } // determine function var exe; if(f == "quad") exe = "EasePoly(2, %d, %d)"; else if(f == "cubic") exe = "EasePoly(3, %d, %d)"; else if(f == "poly") exe = Format("EasePoly(%d, %%d, %%d)", Par(3)); else if(f == "sin") exe = "EaseSin(%d, %d)"; else if(f == "circle") exe = "EaseCircle(%d, %d)"; else FatalError(Format("CreateEaseFunction: Invalid easing function %s!", f)); // check if mode is valid if(mode != "in" && mode != "out" && mode != "in-out") FatalError(Format("CreateEaseFunction: Invalid easing mode %s!", mode)); return [exe, mode, max]; } /* Function: EvalEase Evaluates an easing function. Parameters: f - The easing function, created by <CreateEaseFunction>. t - A number 0 <= t <= max Returns: The new value. */ global func EvalEase(array f, int t) { var exe = f[0], mode = f[1], max = f[2]; t = BoundBy(t, 0, max); // execute depending on mode if(mode == "in") exe = Format(exe, t, max); else if(mode == "out") exe = Format("%d - (%s)", max, Format(exe, max - t, max)); else if(mode == "in-out") { if(t < max / 2) exe = Format(exe, 2 * t, max); else exe = Format("%d - (%s)", 2 * max, Format(exe, 2 * max - 2 * t, max)); exe = Format("(%s) / 2", exe); } return eval(exe); } /* Function: Ease Interpolates a number 0 <= t <= max according to the given function. For performance reasons, you should probably use <CreateEaseFunction> and <EvalEase>, caching the function. Parameters: function - The easing function, consisting of a function and a modifier. t - A number 0 <= t <= max max - The maximum Returns: The new value. */ global func Ease(string function, int t, int max) { var exe = CreateEaseFunction(function, max); return EvalEase(exe, t); } global func EasePoly(int e, int t, int max) { return t ** e / max ** (e - 1); } global func EaseSin(int t, int max) { return max - Cos(t * 90 / max, max); } global func EaseCircle(int t, int max) { return max - Sqrt(max*max - t*t); } global func TestEasing(string f) { var max = 500; var easeFunction = CreateEaseFunction(f, max); for(var x = 0; x < max; x++) { var y = EvalEase(easeFunction, x); CreateParticle("PSpark", x, y, 0, 0, 30, RGB(255, 255, 255)); } }
722,141
./clinfinity/Clinfinity.c4d/System.c4g/MatSysMenu.c
/*-- Functionality for material system menus --*/ #strict 2 /* Function: AddMaterialMenuItem Adds a menu item to a menu as documented, but also shows required materials in the players material system. */ global func AddMaterialMenuItem(string caption, string command, id item, object menuObject, int iCount, par, string infoCaption, int extra, par1, par2) { var symbol = GetMenu(menuObject); if(!symbol) return; if(command) { var effect = GetEffect("MaterialMenuCheck", menuObject); if(!effect) effect = AddEffect("MaterialMenuCheck", menuObject, 300, 1, menuObject, symbol, symbol); EffectCall(menuObject, effect, "AddItem", item); } AddMenuItem(caption, command, item, menuObject, iCount, par, infoCaption, extra, par1, par2); } global func CreateMenu() { if(GetEffect("MaterialMenuCheck", Par(1))) RemoveEffect("MaterialMenuCheck", Par(1)); return inherited(...); } global func FxMaterialMenuCheckStart(object target, int effectNum, int temp, id menuId) { if(temp) return; EffectVar(0, target, effectNum) = menuId; //menuId EffectVar(1, target, effectNum) = []; //menuItems } global func FxMaterialMenuCheckAddItem(object target, int effectNum, id menuId) { var menuItems = EffectVar(1, target, effectNum); menuItems[GetLength(menuItems)] = menuId; EffectVar(1, target, effectNum) = menuItems; } global func FxMaterialMenuCheckTimer(object target, int effectNum) { var menuId = EffectVar(0, target, effectNum); var matSys = GetMatSys(GetOwner(target)); if(GetMenu(target) != menuId || !matSys) return -1; var menuItems = EffectVar(1, target, effectNum); if(!GetLength(menuItems)) return; var type = menuItems[GetMenuSelection(target)]; if(!type) return GetMatSys(GetOwner(target))->ClearMaterialCheck(); matSys->MaterialCheck(type); } global func FxMaterialMenuCheckStop(object target, int effectNum, int reason, bool temp) { if(temp) return; var menuId = EffectVar(0, target, effectNum); if(GetMenu(target) == menuId) CloseMenu(target); GetMatSys(GetOwner(target))->ClearMaterialCheck(); }
722,142
./clinfinity/Clinfinity.c4d/System.c4g/Attach.c
/* Script: Attach.c Helper functions related to attaching stuff! */ #strict 2 /* Function: AttachTo Attaches the calling object to the object _to_. *Note:* This also changes the object order, so _to_ is internally sorted before the calling object. Furthermore, the target object may receive an attach event by providing a method called AttachEvent(). If the calling object isn't already in an action with procedure ATTACH the function will set the action "Attach". When callerVertex or targetVertex are omitted, this function will add new vertices so that the object won't move. *Important:* Vertex indices are starting at 1 instead of 0. Parameters: to - Object to which the caller should be attached. callerVertex - The caller object's vertex which will be attached. targetVertex - The vertex to attach to. */ global func AttachTo(object to, int callerVertex, int targetVertex) { if(GetProcedure() != "ATTACH") SetAction("Attach"); SetActionTargets(to); // correct z-order SetObjectOrder(to); // optionally add vertices if(callerVertex == 0) { if(targetVertex == 0) // use first vertex targetVertex = 1; var tx = to->GetVertex(targetVertex - 1, false), ty = to->GetVertex(targetVertex - 1, true); AddVertex(AbsX(tx + to->GetX()), AbsY(ty + to->GetY())); callerVertex = GetVertexNum(); } else if(targetVertex == 0) { var cx = GetVertex(callerVertex - 1, false), cy = GetVertex(callerVertex - 1, true); to->AddVertex(to->AbsX(cx + GetX()), to->AbsY(cy + GetY())); targetVertex = to->GetVertexNum(); } else { var newX = to->GetVertex(targetVertex - 1, false) - GetVertex(callerVertex - 1, false) + to->GetX(); var newY = to->GetVertex(targetVertex - 1, true) - GetVertex(callerVertex - 1, true) + to->GetY(); SetPositionWithChildren(newX, newY); } callerVertex--; targetVertex--; SetActionData(256 * callerVertex + targetVertex); to->~AttachEvent(this, to, false, this); } /* Function: CopyVertices Copies all *DefCore-defined* vertices from another object. The copied vertices are saved using an Effect, allowing easy removal using _RemoveCopiedVertices_. Parameters: from - Object from which the vertices are copied. */ global func CopyVertices(object from) { var start = GetVertexNum(); for(var num = from->GetDefCoreVal("Vertices", "DefCore"), i = 0; i < num; i++) { var vx = from->GetDefCoreVal("VertexX", "DefCore", 0, i), vy = from->GetDefCoreVal("VertexY", "DefCore", 0, i); AddVertex(AbsX(vx + from->GetX()), AbsY(vy + from->GetY())); SetVertex(start + i, 2, from->GetDefCoreVal("VertexCNAT", "DefCore", 0, i)); SetVertex(start + i, 3, from->GetDefCoreVal("VertexFriction", "DefCore", 0, i)); } // save vertices var effect = AddEffect("CopiedVertices", this, 1); EffectVar(0, this, effect) = from; //Log("%v add: %v", this, from); } static vertexRemoveOperation; /* Function: StartCopiedVerticesRemoval Improves performance of removing multiple vertices by only re-adding the remaining vertices in the end. *Important:* You need to call <EndCopiedVerticesRemoval> after all calls to <RemoveCopiedVertices> are done. */ global func StartCopiedVerticesRemoval() { vertexRemoveOperation = true; } /* Function: EndCopiedVerticesRemoval Ends a batch removal using <RemoveCopiedVertices>. */ global func EndCopiedVerticesRemoval() { vertexRemoveOperation = false; RemoveCopiedVertices(); } /* Function: RemoveCopiedVertices Removes vertices which were previously copied using <CopyVertices>. *Important:* This function will remove all user-defined vertices that aren't copied from other objects. Note: Use <StartCopiedVerticesRemoval> when calling this function repeatedly with different objects. Parameters: from - Object from which the vertices were copied. */ global func RemoveCopiedVertices(object from) { // remove all additional vertices SetR(GetR()); var i = GetEffectCount("CopiedVertices", this), success = false; var effects = CreateArray(i); while(i--) { var effect = GetEffect("CopiedVertices", this, i); var obj = EffectVar(0, this, effect); effects[i] = [effect, obj]; } for(var e in effects) { var effect = e[0], obj = e[1]; if(obj == from) { RemoveEffect(0, this, effect); success = true; } else if(!vertexRemoveOperation) { RemoveEffect(0, this, effect); // re-add vertices CopyVertices(obj); } } //Log("%v remove: %v", this, from); return success; } /* Function: RemoveAllCopiedVertices Removes all vertices which were previously copied using <CopyVertices>. */ global func RemoveAllCopiedVertices() { // remove all additional vertices SetR(GetR()); var i = GetEffectCount("CopiedVertices", this); while(i--) { RemoveEffect("CopiedVertices", this, i); } return true; } /* Function: DebugCopiedVertices Prints all objects from which vertices were copied to the log. */ global func DebugCopiedVertices() { var i = GetEffectCount("CopiedVertices", this); while(i--) { var effect = GetEffect("CopiedVertices", this, i); var obj = EffectVar(0, this, effect); Log("%v", obj); } } /* Function: CopyChildrenVertices Copies all *DefCore-defined* vertices from all attached objects. This is done recursively, thus the vertices of both directly and indirectly attached objects are copied. Parameters: child - [optional] The attached object where the copying starts. */ global func CopyChildrenVertices(object child) { if(child == 0) { child = this; } else { CopyVertices(child); } var grandchildren = FindObjects(Find_ActionTarget(child), Find_Procedure("ATTACH")); for(var grandchild in grandchildren) { CopyChildrenVertices(grandchild); } } /* Function: RemoveCopiedChildrenVertices Removes all vertices which were previously copied from all attached objects. This is done recursively, all vertices of directly and indirectly attached objects are removed. Parameters: child - [optional] The attached object where the removal starts. rec - internal parameter, ignore. */ global func RemoveCopiedChildrenVertices(object child, bool rec) { if(!rec) StartCopiedVerticesRemoval(); if(child == 0) { child = this; } var grandchildren = FindObjects(Find_ActionTarget(child), Find_Procedure("ATTACH")); for(var grandchild in grandchildren) { RemoveCopiedChildrenVertices(grandchild, true); } if(child != this) { RemoveCopiedVertices(child); } if(!rec) EndCopiedVerticesRemoval(); } /* Function: SetPositionWithChildren Sets the position of the calling object, including all objects attached to it. Coordinates are global. Parameters: x - New horizontal coordinate. y - New vertical coordinate. */ global func SetPositionWithChildren(int x, int y) { var children = FindObjects(Find_ActionTarget(this), Find_Procedure("ATTACH")); for(var child in children) { var childX = child->GetX() - GetX() + x; var childY = child->GetY() - GetY() + y; child->SetPositionWithChildren(childX, childY); } SetPosition(x, y); }
722,143
./clinfinity/Clinfinity.c4d/System.c4g/DrawResource.c
/* Script: DrawResource.c Draws a resource vein. The algorithm draws a vein in consecutive triangles, clockwise, around a central point. This algorithm was originally implemented by <Zapper at http://www.clonkforge.net/user.php?usr=533>. */ #strict 2 /* Function: DrawResource Draws a resource vein around a central point. The size parameters determine the side lengths of the drawn triangles. Parameters: materialIndex - Material the vein will be made of. materialTexture - The material's texture. tunnelBackground - If true, the vein will be drawn as 'underground'. x - Horizontal coordinate of the centre. y - Vertical coordinate of the centre. minSize - [optional] Minimal side length. maxSize - [optional] Maximal side length. drawingCycles - [optional] Number of full cycles the vein is drawn. */ global func DrawResource(int materialIndex, string materialTexture, bool tunnelBackground, int x, int y, int minSize, int maxSize, int drawingCycles) { AddEffect("DrawResource", 0, 1, 1, 0, 0, [materialIndex, materialTexture, tunnelBackground], [x, y], [minSize, maxSize], drawingCycles); } /* Indices */ static const DrawResourceMaterialIndex = 0; static const DrawResourceMaterialTexture = 1; static const DrawResourceTunnelBackground = 2; static const DrawResourceCentreX = 3; static const DrawResourceCentreY = 4; static const DrawResourceStartEdgeX = 5; static const DrawResourceStartEdgeY = 6; static const DrawResourcePreviousEdgeX = 7; static const DrawResourcePreviousEdgeY = 8; static const DrawResourceMinSize = 9; static const DrawResourceMaxSize = 10; static const DrawResourceSize = 11; static const DrawResourceDrawingCycles = 12; /* Standards and constant values */ static const DrawResourceStandardMinSize = 10; static const DrawResourceStandardMaxSize = 65; static const DrawResourceSizeChange = 6; static const DrawResourceAngularRate = 5; static const DrawResourceStandardDrawingCycles = 2; global func FxDrawResourceStart(object target, int effectNumber, int temporary, array materialDescription, array position, array sizeDescription, int drawingCycles) { if(temporary == 0) { EffectVar(DrawResourceMaterialIndex, target, effectNumber) = materialDescription[0]; EffectVar(DrawResourceMaterialTexture, target, effectNumber) = materialDescription[1]; EffectVar(DrawResourceTunnelBackground, target, effectNumber) = materialDescription[2]; EffectVar(DrawResourceCentreX, target, effectNumber) = position[0]; EffectVar(DrawResourceCentreY, target, effectNumber) = position[1]; EffectVar(DrawResourceMinSize, target, effectNumber) = sizeDescription[0]; if(sizeDescription[0] == 0) { EffectVar(DrawResourceMinSize, target, effectNumber) = DrawResourceStandardMinSize; } EffectVar(DrawResourceMaxSize, target, effectNumber) = sizeDescription[1]; if(sizeDescription[1] == 0) { EffectVar(DrawResourceMaxSize, target, effectNumber) = DrawResourceStandardMaxSize; } // Determine initial size var sizeRange = EffectVar(DrawResourceMaxSize, target, effectNumber) - EffectVar(DrawResourceMinSize, target, effectNumber); var minInitialSize = Min(2 * EffectVar(DrawResourceMinSize, target, effectNumber), EffectVar(DrawResourceMaxSize, target, effectNumber)); var maxInitialSize = BoundBy(EffectVar(DrawResourceMinSize, target, effectNumber) + sizeRange / 3, minInitialSize, EffectVar(DrawResourceMaxSize, target, effectNumber)); var size = RandomX(minInitialSize, maxInitialSize); EffectVar(DrawResourceSize, target, effectNumber) = size; EffectVar(DrawResourceStartEdgeX, target, effectNumber) = size; EffectVar(DrawResourceStartEdgeY, target, effectNumber) = 0; EffectVar(DrawResourcePreviousEdgeX, target, effectNumber) = size; EffectVar(DrawResourcePreviousEdgeY, target, effectNumber) = 0; EffectVar(DrawResourceDrawingCycles, target, effectNumber) = drawingCycles; if(drawingCycles == 0) { EffectVar(DrawResourceDrawingCycles, target, effectNumber) = DrawResourceStandardDrawingCycles; } } } global func FxDrawResourceTimer(object target, int effectNumber, int effectTime) { var materialIndex = EffectVar(DrawResourceMaterialIndex, target, effectNumber); var material = Format("%s-%s", MaterialName(materialIndex), EffectVar(DrawResourceMaterialTexture, target, effectNumber)); var tunnelBackground = EffectVar(DrawResourceTunnelBackground, target, effectNumber); var centreX = EffectVar(DrawResourceCentreX, target, effectNumber); var centreY = EffectVar(DrawResourceCentreY, target, effectNumber); var previousX = EffectVar(DrawResourcePreviousEdgeX, target, effectNumber); var previousY = EffectVar(DrawResourcePreviousEdgeY, target, effectNumber); var result = FX_OK; var size, currentX, currentY; if(effectTime < EffectVar(DrawResourceDrawingCycles, target, effectNumber) * 360 / DrawResourceAngularRate) { size = EffectVar(DrawResourceSize, target, effectNumber); size = BoundBy(size + RandomX(-DrawResourceSizeChange, DrawResourceSizeChange), EffectVar(DrawResourceMinSize, target, effectNumber), EffectVar(DrawResourceMaxSize, target, effectNumber)); currentX = Cos(effectTime * DrawResourceAngularRate, size); currentY = Sin(effectTime * DrawResourceAngularRate, size) / 2; } else { // Make start and end fit together size = EffectVar(DrawResourceStartEdgeX, target, effectNumber); currentX = EffectVar(DrawResourceStartEdgeX, target, effectNumber); currentY = EffectVar(DrawResourceStartEdgeY, target, effectNumber); result = FX_Execute_Kill; } EffectVar(DrawResourcePreviousEdgeX, target, effectNumber) = currentX; EffectVar(DrawResourcePreviousEdgeY, target, effectNumber) = currentY; EffectVar(DrawResourceSize, target, effectNumber) = size; DrawMaterialQuad(material, centreX, centreY, centreX + previousX, centreY + previousY, centreX + currentX, centreY + currentY, centreX, centreY, tunnelBackground); var particleMinSize = 300; var particleMaxSize = EffectVar(DrawResourceMaxSize, target, effectNumber) * 31; var particleMinSpeed = 30; var particleMaxSpeed = EffectVar(DrawResourceMaxSize, target, effectNumber) * 50 / 65; var particleSize = RandomX(particleMinSize, particleMaxSize); var particleSpeed = particleMinSpeed + (particleMaxSize - particleSize) * (particleMaxSpeed - particleMinSpeed) / (particleMaxSize - particleMinSize); var particleMoveAngle = Random(360); var particleSpeedX = Cos(particleMoveAngle, particleSpeed); var particleSpeedY = Sin(particleMoveAngle, particleSpeed); CreateParticle("PSpark", centreX, centreY, particleSpeedX, particleSpeedY, particleSize, RGBa(255, 255, 255, 100)); return result; }
722,144
./clinfinity/Clinfinity.c4d/System.c4g/Fade.c
/* Script: Fade.c Provides convenience functions for fading objects in and out. After fading is finished, the function _OnFadeFinish_ is called in the target object, with the final modulation as first parameter. */ #strict 2 static const Fade_CurrentRed = 0; static const Fade_CurrentGreen = 1; static const Fade_CurrentBlue = 2; static const Fade_CurrentAlpha = 3; static const Fade_TargetRed = 4; static const Fade_TargetGreen = 5; static const Fade_TargetBlue = 6; static const Fade_TargetAlpha = 7; static const Fade_ChangeRed = 8; static const Fade_ChangeGreen = 9; static const Fade_ChangeBlue = 10; static const Fade_ChangeAlpha = 11; /* Function: FadeIn Fades an object from completely transparent to a specified modulation. If the modulation is not specified, the object will be faded to complete visibility, retaining its current colour modulation. Parameters: targetColourModulation - [optional] Colour modulation to fade to. Current modulation by default. Returns: _true_ if fading successfully started, _false_ otherwise. */ global func FadeIn(int targetColourModulation) { if(targetColourModulation == 0) { if(GetClrModulation() == 0) { targetColourModulation = RGB(255, 255, 255); } else { targetColourModulation = SetRGBaValue(GetClrModulation(), 0, 0); } } return FadeFromTo(SetRGBaValue(targetColourModulation, 255, 0), targetColourModulation); } /* Function: FadeOut Fades an object from a specified modulation to completely transparent. If the modulation is not specified, the object's current modulation will be used as starting point. Parameters: initialColourModulation - [optional] Colour modulation to fade from. Current modulation by default. Returns: _true_ if fading successfully started, _false_ otherwise. */ global func FadeOut(int initialColourModulation) { if(initialColourModulation == 0) { initialColourModulation = GetClrModulation(); } return FadeFromTo(initialColourModulation, SetRGBaValue(initialColourModulation, 255, 0)); } /* Function: FadeFromTo Fades an object between specified colour modulations. Parameters: initialColourModulation - Initial modulation for the object. targetColourModulation - Modulation to fade to. Returns: _true_ if fading successfully started, _false_ otherwise. */ global func FadeFromTo(int initialColourModulation, int targetColourModulation) { return 0 != AddEffect("Fade", this, 101, 1, this, 0, initialColourModulation, targetColourModulation); } global func FxFadeStart(object target, int effectNumber, int temporary, int initialColourModulation, int targetColourModulation) { if(temporary == 0) { if(initialColourModulation == 0 || targetColourModulation == 0) { return FX_Start_Deny; } var initRed, initGreen, initBlue, initAlpha; SplitRGBaValue(initialColourModulation, initRed, initGreen, initBlue, initAlpha); EffectVar(Fade_CurrentRed, target, effectNumber) = initRed; EffectVar(Fade_CurrentGreen, target, effectNumber) = initGreen; EffectVar(Fade_CurrentBlue, target, effectNumber) = initBlue; EffectVar(Fade_CurrentAlpha, target, effectNumber) = initAlpha; var targetRed, targetGreen, targetBlue, targetAlpha; SplitRGBaValue(targetColourModulation, targetRed, targetGreen, targetBlue, targetAlpha); EffectVar(Fade_TargetRed, target, effectNumber) = targetRed; EffectVar(Fade_TargetGreen, target, effectNumber) = targetGreen; EffectVar(Fade_TargetBlue, target, effectNumber) = targetBlue; EffectVar(Fade_TargetAlpha, target, effectNumber) = targetAlpha; EffectVar(Fade_ChangeRed, target, effectNumber) = CalculateChange(initRed, targetRed); EffectVar(Fade_ChangeGreen, target, effectNumber) = CalculateChange(initGreen, targetGreen); EffectVar(Fade_ChangeBlue, target, effectNumber) = CalculateChange(initBlue, targetBlue); EffectVar(Fade_ChangeAlpha, target, effectNumber) = CalculateChange(initAlpha, targetAlpha); target->SetClrModulation(RGBa(initRed, initGreen, initBlue, initAlpha)); } } global func FxFadeTimer(object target, int effectNumber, int effectTime) { var currentRed = EffectVar(Fade_CurrentRed, target, effectNumber); var currentGreen = EffectVar(Fade_CurrentGreen, target, effectNumber); var currentBlue = EffectVar(Fade_CurrentBlue, target, effectNumber); var currentAlpha = EffectVar(Fade_CurrentAlpha, target, effectNumber); var targetRed = EffectVar(Fade_TargetRed, target, effectNumber); var targetGreen = EffectVar(Fade_TargetGreen, target, effectNumber); var targetBlue = EffectVar(Fade_TargetBlue, target, effectNumber); var targetAlpha = EffectVar(Fade_TargetAlpha, target, effectNumber); var matches = 0; if(currentRed == targetRed) { EffectVar(Fade_ChangeRed, target, effectNumber) = 0; matches++; } if(currentGreen == targetGreen) { EffectVar(Fade_ChangeGreen, target, effectNumber) = 0; matches++; } if(currentBlue == targetBlue) { EffectVar(Fade_ChangeBlue, target, effectNumber) = 0; matches++; } if(currentAlpha == targetAlpha) { EffectVar(Fade_ChangeAlpha, target, effectNumber) = 0; matches++; } if(matches == 4) { target->~OnFadeFinish(RGBa(targetRed, targetGreen, targetBlue, targetAlpha)); return FX_Execute_Kill; } currentRed += EffectVar(Fade_ChangeRed, target, effectNumber); currentGreen += EffectVar(Fade_ChangeGreen, target, effectNumber); currentBlue += EffectVar(Fade_ChangeBlue, target, effectNumber); currentAlpha += EffectVar(Fade_ChangeAlpha, target, effectNumber); target->SetClrModulation(RGBa(currentRed, currentGreen, currentBlue, currentAlpha)); EffectVar(Fade_CurrentRed, target, effectNumber) = currentRed; EffectVar(Fade_CurrentGreen, target, effectNumber) = currentGreen; EffectVar(Fade_CurrentBlue, target, effectNumber) = currentBlue; EffectVar(Fade_CurrentAlpha, target, effectNumber) = currentAlpha; return FX_OK; } global func FxFadeEffect(string newEffectName, object target, int effectNumber, int newEffectNumber, var1, var2, var3, var4) { if(newEffectName == "Fade") { if(var2 == 0) { return FX_Effect_Deny; } return FX_Effect_Annul; } } global func FxFadeAdd(object target, int effectNumber, string newEffectName, int newEffectTimer, int initialColourModulation, int targetColourModulation) { var currentRed = EffectVar(Fade_CurrentRed, target, effectNumber); var currentGreen = EffectVar(Fade_CurrentGreen, target, effectNumber); var currentBlue = EffectVar(Fade_CurrentBlue, target, effectNumber); var currentAlpha = EffectVar(Fade_CurrentAlpha, target, effectNumber); var targetRed, targetGreen, targetBlue, targetAlpha; SplitRGBaValue(targetColourModulation, targetRed, targetGreen, targetBlue, targetAlpha); EffectVar(Fade_TargetRed, target, effectNumber) = targetRed; EffectVar(Fade_TargetGreen, target, effectNumber) = targetGreen; EffectVar(Fade_TargetBlue, target, effectNumber) = targetBlue; EffectVar(Fade_TargetAlpha, target, effectNumber) = targetAlpha; EffectVar(Fade_ChangeRed, target, effectNumber) = CalculateChange(currentRed, targetRed); EffectVar(Fade_ChangeGreen, target, effectNumber) = CalculateChange(currentGreen, targetGreen); EffectVar(Fade_ChangeBlue, target, effectNumber) = CalculateChange(currentBlue, targetBlue); EffectVar(Fade_ChangeAlpha, target, effectNumber) = CalculateChange(currentAlpha, targetAlpha); } global func CalculateChange(int start, int target) { if(start < target) { return 1; } else if(start == target) { return 0; } else { return -1; } }
722,145
./clinfinity/Clinfinity.c4d/System.c4g/RelSetR.c
#strict 2 /** Rotiert ein Objekt um einen beliebigen Punkt herum. */ global func RelSetR(int rotation, int xPos, int yPos) { // Winkel zu den gedrehten Koordinaten var angle1 = Angle(0, 0, xPos, yPos); var angle2 = angle1 + GetR(); var radius = Distance(0, 0, xPos, yPos); // angle2 + Radius => Umgerechneter Drehpunkt var rotX = (Sin(angle2, 100) * radius) / 100; var rotY = (-Cos(angle2, 100) * radius) / 100; // rotation + angle1 + Radius + umgerechneter Drehpunkt => Endpunkt angle1 += rotation; var targetX = (-Sin(angle1, 100) * radius) / 100 + rotX; var targetY = (Cos(angle1, 100) * radius) / 100 + rotY; SetPosition(GetX() + targetX, GetY() + targetY); SetR(rotation); }
722,146
./clinfinity/Clinfinity.c4d/System.c4g/AntiFloatVegetation.c
/* Stop some kind of vegetation from growing in the air. */ #strict 2 #appendto GRAS //Grass #appendto PLNT //Plants #appendto SRUB //Shrubs protected func Initialize() { AddEffect("CheckAir", this, 1, 30, this); return inherited(...); } protected func FxCheckAirTimer(object target, int effectNum, int effectTime) { if(GetMaterial(0,10) != Material("Earth")) DoCon(-10); }
722,147
./clinfinity/Clinfinity.c4d/System.c4g/FindObject.c
/* Helpers! */ #strict 2 global func GetRect(id idDef, &ox, &oy, &wdt, &hgt) { ox = GetDefCoreVal("Offset", "DefCore", idDef, 0); oy = GetDefCoreVal("Offset", "DefCore", idDef, 1); wdt = GetDefCoreVal("Width", "DefCore", idDef); hgt = GetDefCoreVal("Height", "DefCore", idDef); } global func Find_AtObject(object pObj) { if (!pObj) pObj = this; if (!pObj) return; var ox, oy, wdt, hgt; GetRect(GetID(pObj), ox, oy, wdt, hgt); var xpos = GetX(pObj); var ypos = GetY(pObj); return([C4FO_AtRect, xpos + ox, ypos + oy, wdt, hgt]); } global func Find_ActionTarget2(object pObj) { return Find_Func("IsActionTarget2", pObj); } global func Find_ActionTargets(object pTarget) { return Find_Or(Find_ActionTarget(pTarget), Find_ActionTarget2(pTarget)); } global func IsActionTarget2 (object pObj) { return GetActionTarget(1) == pObj; } global func Find_Angle() { return Find_Func("IsAtAngle", this, ...); } global func IsAtAngle(object pObj, int iAngle1, int iAngle2, int iX, int iY) { iX += pObj -> GetX(); iY += pObj -> GetY(); var iAngle = Angle(iX, iY, GetX(), GetY()); //Log("%v - %v: w1 %d; w2 %d; w %d", pObj, this, iAngle1, iAngle2, iAngle); if(iAngle <= iAngle1 && iAngle >= iAngle2) return 1; // Spezialfall: Winkel 1 kleiner als Winkel 2, z.B. 10; 350 if(iAngle1 < iAngle2 && (iAngle <= iAngle1 || iAngle >= iAngle2)) return 1; }
722,148
./clinfinity/Clinfinity.c4d/System.c4g/RotatedTrees.c
#strict 2 #appendto TREE local maxTreeRotation; protected func Construction() { maxTreeRotation = 5; ScheduleCall(this, "RotateTree", 1); return _inherited(); } protected func RotateTree() { RelSetR(RandomX(-maxTreeRotation, maxTreeRotation), 0, GetObjHeight() / 2); }
722,149
./clinfinity/Clinfinity.c4d/System.c4g/Catapult.c
/*-- Catapult Trajectory --*/ #strict 2 #appendto CATA protected func Grabbed(object clonk, bool grab) { SetOwner(clonk->GetOwner()); ShowTrajectory(grab); } protected func GrabLost() { ShowTrajectory(false); } private func AimUp() { inherited(...); ShowTrajectory(true); } private func AimDown() { inherited(...); ShowTrajectory(true); } private func AimUpdate() { inherited(...); ShowTrajectory(true); } private func ShowTrajectory(bool show) { var phase = GetPhase(); if(show && phase) { var x = (GetDir()*2-1)*12; var y = -10; var xDir = +8 * (GetDir() * 2 - 1) * phase / 6; var yDir = -12 * phase / 6; AddTrajectory(this, GetX() + x, GetY() + y, xDir*10, yDir*10); if(!GetEffect("UpdateTrajectory", this)) AddEffect("UpdateTrajectory", this, 1, 5, this); } else { RemoveTrajectory(this); RemoveEffect("UpdateTrajectory", this); } } local oldDir; protected func FxUpdateTrajectoryTimer(object target, int effectNum, int effectTime) { if(GetDir() != oldDir) { ShowTrajectory(true); oldDir = GetDir(); } if(effectTime % 10 == 0 && !FindObject2(Find_OCF(OCF_CrewMember), Find_Action("Push"), Find_ActionTarget(this))) { ShowTrajectory(false); } }
722,150
./clinfinity/Clinfinity.c4d/System.c4g/LumberjackTree.c
#strict 2 #appendto TREE protected func Construction() { AddEffect("NoChopDown", this, 50, 0, this); return _inherited(); } protected func FxNoChopDownDamage(object target, int effectNumber, int damage, int cause) { if(cause != FX_Call_DmgChop && cause != FX_Call_EngFire) { Shrink(); } return 0; } // Catch calls by BlastObjects() public func CanBeHitByShockwaves() { return true; } public func BlastObjectsShockwaveCheck() { return true; } public func OnShockwaveHit(int level, int x, int y) { var wood = CreateObject(WOOD, 0, 0, GetOwner()); var xdir = GetX() - x, ydir = GetY() - y; wood->SetXDir(xdir * level, 0, 100); wood->SetYDir(ydir * level, 0, 100); return true; } public func Shrink() { var rest = Max(GetComponent(WOOD), 1); var shrinkage = GetCon() / rest; var oldHeight = GetObjHeight(); DoCon(-shrinkage); // Unrotated trees shrink towards their offset instead their bottom. Thus, adjust their position so they stay on the ground. if(GetR() != 0) { var verticalAdjustment = (oldHeight - GetObjHeight()) / 3; SetPosition(GetX(), GetY() + verticalAdjustment); } return GetCon(); } protected func Destruction() { // Replace the tree with a tiny one. PlaceVegetation(GetID(), 0, 0, LandscapeWidth(), LandscapeHeight(), 1); _inherited(...); }
722,151
./clinfinity/Clinfinity.c4d/System.c4g/Events.c
/* Script: Events.c Provides functions for dispatching effect-based events which can be handled by listeners. */ #strict 2 /* Function: AddEventListener Adds an event listener to the calling object. The first parameter specifies the object which will receive calls when an event is emitted. All other parameters specify the events which will be handled, optionally as an array which contains the handling function as a second parameter. Parameters: listener - the object receiving event calls event... - the event name or an array [event name, function name to call] Returns: The number of listeners which were added. */ global func AddEventListener(object listener/*, event...*/) { var i = 1, event, function; while(event = Par(i++)) { if(GetType(event) == C4V_Array) { function = event[1]; event = event[0]; } else function = event; var effectNum = AddEffect("EventListener", this, 1, 0, listener); EffectVar(0, this, effectNum) = event; EffectVar(1, this, effectNum) = function; } return i - 2; } /* Function: GetEventListener Finds the effect numbers of one or all event listeners (in case on of the parameters is 0). Parameters: listener - the listening object event - the event name Returns: The effect number or an array of effect numbers. */ global func GetEventListener(object listener, string event) { var i = GetEffectCount("EventListener", this), results = []; while(i--) { var effectNum = GetEffect("EventListener", this, i); if(event == 0 || EffectVar(0, this, effectNum) == event) { if(listener == 0 || GetEffect(0, this, effectNum, 4) == listener) { PushBack(effectNum, results); } } } if(GetLength(results) > 1) return results; else return results[0]; } global func FxEventListenerCall(object target, int effectNum) { Call(EffectVar(1, target, effectNum), target, ...); } /* Function: Emit Emits the given event. The handling function will be passed the calling object and any additional parameters. Parameters: event - the event name ... - all other parameters are passed to the handler Returns: The number of listeners that handled this event. */ global func Emit(string event) { var i = GetEffectCount("EventListener", this), listeners = 0; while(i--) { var effectNum = GetEffect("EventListener", this, i); if(EffectVar(0, this, effectNum) == event) { EffectCall(this, effectNum, "Call", ...); listeners++; } } return listeners; }
722,152
./clinfinity/Clinfinity.c4d/System.c4g/Find_Procedure.c
/* Script: Find_Procedure.c Provides procedure finding functions for FindObject2/FindObjects. */ #strict 2 /* Function: Find_Procedure FindObject2/FindObjects criteria: Find objects with the given procedure. Parameters: procedure - The procedure to look for. */ global func Find_Procedure(string procedure) { return Find_Func("CompareProdecure", procedure); } /* Function: CompareProdecure Compares the procedure of an object to the given procedure. Parameters: procedure - Comparison value. Returns: *true* if the procedure matches, *false* otherwise. */ global func CompareProdecure(string procedure) { return GetProcedure() == procedure; }
722,153
./clinfinity/Clinfinity.c4d/System.c4g/Flints.c
#strict 2 #appendto FLNT #appendto TFLN public func IsFlint() { return true; }
722,154
./clinfinity/Clinfinity.c4d/System.c4g/QueryCatchBlow.c
/* Script: QueryCatchBlow.c Clonk appendto for QueryCatchBlow. Defines a new event: QueryStrikeBlow, which is the counterpart for QueryCatchBlow called in the striking object. */ #strict 2 #appendto CLNK protected func QueryCatchBlow(object obj) { if(obj->~QueryStrikeBlow(this)) return true; return _inherited(obj, ...); } /* Function: QueryStrikeBlow Event call, called before the object hits another object. By returning _true_, QueryStrikeBlow can reject physical blows. Parameters: target - The object about to be hit. Returns: _true_ to reject physical blows, _false_ otherwise. */ public func QueryStrikeBlow(object target) { // Do nothing, this function is just here for documentation purposes. return _inherited(...); }
722,155
./clinfinity/Clinfinity.c4d/System.c4g/SetOverlayAction.c
/* Aktion mit Animation als Overlay setzen */ /* IntOverlayAction Vars * 0: szAction * 1: iOverlay * 2: iLength * 3: iFrame (or just i) * 4: fReverse * 5: szPhaseCall * 6: szEndCall * 7: fNoCalls * 8: fNoRotationChecks */ #strict 2 global func OverlayShiftX(int iWidth) { return 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 0) + iWidth/2); } global func OverlayShiftY(int iHeight) { return 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 1) + iHeight/2); } /* Methode 1: alle Einzelframes in der ActMap.txt */ global func OverlayActionInit(string szAction, id ID) { if(!ID && !(ID = GetID())) return; var iLength = GetActMapVal("Length", szAction, ID); if(!iLength) return; var iFacetX = GetActMapVal("Facet", szAction, ID, 0), iFacetY = GetActMapVal("Facet", szAction, ID, 1), iFacetWidth = GetActMapVal("Facet", szAction, ID, 2), iFacetHeight = GetActMapVal("Facet", szAction, ID, 3), iFacetPX = GetActMapVal("Facet", szAction, ID, 4), iFacetPY = GetActMapVal("Facet", szAction, ID, 5); for(var i = 0; i < iLength; i++) { Log("[Action]"); Log("Name=%s%d", szAction, i); Log("Length=1"); Log("Facet=%d,%d,%d,%d,%d,%d", iFacetX + iFacetWidth * i, iFacetY, iFacetWidth, iFacetHeight, iFacetPX, iFacetPY); } return iLength; } // Grafik einer nicht animierten Aktion setzen global func SetStillOverlayAction(string szAction, int iOverlay) { if(!iOverlay) iOverlay = GetUnusedOverlayID(1); SetGraphics(0, this, GetID(), iOverlay, GFXOV_MODE_Action, szAction); if(GetDir() == DIR_Left) SetObjDrawTransform(1000, 0, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 0) + GetActMapVal("Facet", szAction, GetID(), 2)/2 + GetActMapVal("Facet", szAction, GetID(), 4)), 0, 1000, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 1) + GetActMapVal("Facet", szAction, GetID(), 3)/2 + GetActMapVal("Facet", szAction, GetID(), 5)), this, iOverlay); else if(GetDir() == DIR_Right) { SetObjDrawTransform(-1000, 0, 1000*(-GetDefCoreVal("Offset", "DefCore", GetID(), 0) - GetActMapVal("Facet", szAction, GetID(), 2)/2 - GetActMapVal("Facet", szAction, GetID(), 4)), 0, 1000, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 1) + GetActMapVal("Facet", szAction, GetID(), 3)/2 + GetActMapVal("Facet", szAction, GetID(), 5)), this, iOverlay); } } global func SetOverlayAction(string szAction, int iOverlay, bool fReverse, bool fNoCalls, string szPhaseCall, string szEndCall, bool fNoRotation) { if(!this) return; if(!iOverlay) iOverlay = GetUnusedOverlayID(1); if(!GetDefRotate(GetID()) || GetDefRotate(GetID()) == "") fNoRotation = true; var iDelay; if(fNoRotation) iDelay = GetActMapVal("Delay", szAction, GetID()); else iDelay = 1; if(iDelay == 1) fNoRotation = true; //This might look hacky, But the rotation check is not needed if the gfx is updated every frame AddEffect("IntOverlayAction", this, 100, iDelay, this, 0, szAction, iOverlay, fReverse, [fNoCalls, szPhaseCall, szEndCall, fNoRotation]); return iOverlay; } global func FxIntOverlayActionStart(object pTarget, int iEffectNumber, int iTemp, string szAction, int iOverlay, bool fReverse, array aPars) { if(iTemp) return; var iLength = GetActMapVal("Length", szAction, GetID()); EffectVar(0, pTarget, iEffectNumber) = szAction; EffectVar(1, pTarget, iEffectNumber) = iOverlay; EffectVar(2, pTarget, iEffectNumber) = iLength; // 3: i if(fReverse) { EffectVar(3, pTarget, iEffectNumber) = iLength - 1; EffectVar(4, pTarget, iEffectNumber) = true; } else { EffectVar(3, pTarget, iEffectNumber) = 0; //Calling callbacks from script is hack. } if(!aPars[0]) { var szStartCall = GetActMapVal("StartCall", szAction, GetID()), szPhaseCall = GetActMapVal("PhaseCall", szAction, GetID()), szEndCall = GetActMapVal("EndCall", szAction, GetID()); if(szStartCall) Call(szStartCall); EffectVar(5, pTarget, iEffectNumber) = szPhaseCall; EffectVar(6, pTarget, iEffectNumber) = szEndCall; } else { EffectVar(5, pTarget, iEffectNumber) = aPars[1]; EffectVar(6, pTarget, iEffectNumber) = aPars[2]; EffectVar(7, pTarget, iEffectNumber) = true; } EffectVar(7, pTarget, iEffectNumber) = aPars[3]; Sound(GetActMapVal("Sound", szAction, GetID(pTarget)), 0, pTarget, 0, 0, +1); UpdateActionOverlayTransform(pTarget, iOverlay, szAction, EffectVar(3, pTarget, iEffectNumber)); } global func FxIntOverlayActionTimer(object pTarget, int iEffectNumber, int iEffectTime) { var szAction = EffectVar(0, pTarget, iEffectNumber), i = EffectVar(3, pTarget, iEffectNumber), iOverlay = EffectVar(1, pTarget, iEffectNumber), fNoRotationChecks = EffectVar(7, pTarget, iEffectNumber), iDelay = GetActMapVal("Delay", szAction, GetID(pTarget)); if(!iDelay || iDelay == "") iDelay = 1; if(fNoRotationChecks || !(iEffectTime%GetActMapVal("Delay", szAction, GetID(pTarget)))) { //a new frame, just a gfx update var iLength = EffectVar(2, pTarget, iEffectNumber), fReverse = EffectVar(4, pTarget, iEffectNumber), szPhaseCall = EffectVar(5, pTarget, iEffectNumber); UpdateActionOverlayTransform(pTarget, iOverlay, szAction, i); if(szPhaseCall) Call(szPhaseCall, szAction, iOverlay, iLength, i, fReverse); if(fReverse) { i--; if(i < 0) { var szNextAction = GetActMapVal("NextAction", szAction, GetID(pTarget)); if(szNextAction && szNextAction != "") { Sound(GetActMapVal("Sound", szAction, GetID(pTarget)), 0, pTarget, 0, 0, +1); //Preserve the sound if FxIntOverlayActionStop(pTarget, iEffectNumber); SetOverlayAction(szNextAction, iOverlay, GetActMapVal("Reverse", szNextAction, GetID())); Sound(GetActMapVal("Sound", szAction, GetID(pTarget)), 0, pTarget, 0, 0, -1); i = EffectVar(3, pTarget, iEffectNumber); } else return -1; } } else { i++; if(i == iLength) { var szNextAction = GetActMapVal("NextAction", szAction, GetID(pTarget)); if(szNextAction && szNextAction != "") { Sound(GetActMapVal("Sound", szAction, GetID(pTarget)), 0, pTarget, 0, 0, +1); //Preserve the sound if FxIntOverlayActionStop(pTarget, iEffectNumber); SetOverlayAction(szNextAction, iOverlay, GetActMapVal("Reverse", szNextAction, GetID())); Sound(GetActMapVal("Sound", szAction, GetID(pTarget)), 0, pTarget, 0, 0, -1); i = EffectVar(3, pTarget, iEffectNumber); } else return -1; }/* else if(i > iLength) { FatalError("An Action did not break when it should."); }*/ } EffectVar(3, pTarget, iEffectNumber) = i; } else { //UpdateActionOverlayTransform(pTarget, iOverlay, szAction, i); } } global func FxIntOverlayActionStop(object pTarget, int iEffectNumber) { if( EffectVar(4, pTarget, iEffectNumber) && EffectVar(3, pTarget, iEffectNumber) != 0 || !EffectVar(4, pTarget, iEffectNumber) && EffectVar(3, pTarget, iEffectNumber) < EffectVar(2, pTarget, iEffectNumber)-1) { var szAbortCall = EffectVar(6, pTarget, iEffectNumber); if(szAbortCall) Call(szAbortCall, EffectVar(0, pTarget, iEffectNumber), EffectVar(1, pTarget, iEffectNumber)); } else { var szEndCall = EffectVar(6, pTarget, iEffectNumber); if(szEndCall) Call(szEndCall, EffectVar(0, pTarget, iEffectNumber), EffectVar(1, pTarget, iEffectNumber)); } Sound(GetActMapVal("Sound", EffectVar(0, pTarget, iEffectNumber), GetID(pTarget)), 0, pTarget, 0, 0, -1); } //I must guess that this function does not work correctly. global func FxIntOverlayActionEffect(string szNewEffectName, object pTarget, int iEffectNumber, int iNewEffectNumber, string szAction, int iOverlay, bool fReverse, array aPars) { if(szNewEffectName != "IntOverlayAction") return 0; if(iOverlay == EffectVar(1, pTarget, iEffectNumber)) { return -2; } } global func FxIntOverlayActionAdd(object pTarget, int iEffectNumber, string szNewEffectName, int iNewEffectTimer, string szAction, int iOverlay, bool fReverse, array aPars) { FxIntOverlayActionStop(pTarget, iEffectNumber); FxIntOverlayActionStart(pTarget, iEffectNumber, false, szAction, iOverlay, fReverse, aPars); } global func GetOverlayAction(int iOverlay, object pTarget) { if(!pTarget && !(pTarget=this)) return false; var iEffect; for(var i; iEffect=GetEffect("IntOverlayAction", this, i); i++) { if(EffectVar(1, pTarget, iEffect) == iOverlay) return EffectVar(0, pTarget, iEffect); } return "Idle"; } global func UpdateActionOverlayTransform(object pTarget, iOverlay, szAction, i) { SetGraphics(0, this, GetID(), iOverlay, GFXOV_MODE_Action, Format("%s%d", szAction, i)); var fsin=Sin(-GetR(0), 1000), fcos=Cos(-GetR(), 1000); if(GetDir() == DIR_Left) SetObjDrawTransform(fcos, fsin, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 0) + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 2)/2 + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 4)), -fsin, fcos, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 1) + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 3)/2 + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 5)), this, iOverlay); else if(GetDir() == DIR_Right) { SetObjDrawTransform(-fcos, fsin, 1000*(-GetDefCoreVal("Offset", "DefCore", GetID(), 0) - GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 2)/2 - GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 4)), -fsin, fcos, 1000*(GetDefCoreVal("Offset", "DefCore", GetID(), 1) + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 3)/2 + GetActMapVal("Facet", Format("%s%d", szAction, i), GetID(), 5)), this, iOverlay); } }
722,156
./clinfinity/Clinfinity.c4d/System.c4g/Reparation.c
/* Manages building reparation. */ #strict 2 #appendto CLNK #appendto COLV protected func ContextRepair(object clonk) { [$CtxRepair$|Image=CXCN|Condition=AtBuildingToRepair] var struct = AtBuildingToRepair(); if(!struct) { Message("$NothingtoRepair$", this); return false; } // Materialien einsammeln var needed = struct->GetMissingComponents(); for(var i = 0; i < GetLength(needed[0]); i++) { var ID = needed[0][i], num = needed[1][i]; struct->DoRepairComponent(ID, -struct->MatSysDoTeamFill(-num, GetOwner(), ID)); } // Repair as much as possible! while(struct->Repair(1) && struct->GetDamage()); if(struct->GetDamage()) { // Print missing material var needed = struct->GetMissingComponents(); var output = "$NeededMaterials$"; for(var i = 0; i < GetLength(needed[0]); i++) { var ID = needed[0][i], num = needed[1][i]; output = Format("%s|%dx %s", output, num, GetName(0, ID)); } Message(output, this); } } protected func AtBuildingToRepair() { if(GetID() == COLV) { var platform = this->~GetPlatform(); return platform->GetDamage() && platform; } return FindObject2(Find_AtObject(), Find_Category(C4D_Structure), Find_Allied(GetOwner()), Find_Func("GetDamage"), Find_Func("MaxDamage")); }
722,157
./clinfinity/Clinfinity.c4d/System.c4g/Respawntime.c
/* Script: Respawntime.c Manages the respawn timer for each team. */ #strict 2 static respawnTime; /* Function: SetRespawnTime Sets the respawn time for the given team. Parameters: team - the team number time - the new respawn time in frames */ global func SetRespawnTime(int team, int time) { if(!respawnTime) respawnTime = CreateArray(2); respawnTime[team - 1] = time; } /* Function: GetRespawnTime Returns the respawn time for the given team. Parameters: team - the team number Returns: The respawn time in frames. */ global func GetRespawnTime(int team) { return respawnTime && respawnTime[team - 1]; }
722,158
./clinfinity/Clinfinity.c4d/System.c4g/GetPlayersByTeam.c
/* Script: GetPlayersByTeam */ #strict 2 /* Function: GetPlayersByTeam Parameters: iTeam - the team whose players will be returned Returns: All players in the given team. */ global func GetPlayersByTeam(int iTeam) { if(!GetTeamName(iTeam)) return []; var aPlayers = CreateArray(); for(var i = 0; i < GetPlayerCount(); i++) if(GetPlayerTeam(GetPlayerByIndex(i)) == iTeam) aPlayers[GetLength(aPlayers)] = GetPlayerByIndex(i); return aPlayers; }
722,159
./clinfinity/Clinfinity.c4d/System.c4g/SkyColourModulation.c
/* Script: SkyColourModulation.c Provides individual colour modulation layers for the sky background. Layers can be drawn additively or subtractively. With this mechanism, you can apply several different modulations without worrying about their combination yourself. For example, a magic spell can simply set the colours of the appropriate layer, without having to consider other effects on the sky, such as night and day, lightning, etc. For this, ten layers are available. Generally, lower layer indices mean longer colour changess, while higher indices mean shorter effects. Their exact purpose is summarised by the following table. You should generally abide by these conventions, it is not mandatory, though. (start table) Layer | Purpose --------+---------------------- 0 | Scenario global value 1 | Climate 2 | Season 3 | Free 4 | Day/night cycle 5 | Twilight effects 6 | Free 7 | Lightning 8 | Magic effects 9 | Free (end) */ #strict 2 /* Internal variables */ static const SkyColourLayerCount = 10; static SkyColours; static SkyColoursSubtractive; /* Function: SetSkyColourModulation Sets the colour modulation of the specified layer. Parameters: colour - Colour modulation. subtractive - If _true_, this layer will be drawn subtractively, additively otherwise. layerIndex - Index of the layer to be set. */ global func SetSkyColourModulation(int colour, bool subtractive, int layerIndex) { if(!Inside(layerIndex, 0, SkyColourLayerCount - 1)) return; CheckSkyColourArrayInitialization(); SkyColours[layerIndex] = colour; SkyColoursSubtractive[layerIndex] = subtractive; var red = 255; var green = 255; var blue = 255; var alpha, backRed, backGreen, backBlue; for(var layer = 0; layer < SkyColourLayerCount; ++layer) { var layerColour = GetSkyColourModulation(layer); if(IsSkyColourModulationSubtractive(layer)) { red -= 255 - GetRGBValue(layerColour, 1); green -= 255 - GetRGBValue(layerColour, 2); blue -= 255 - GetRGBValue(layerColour, 3); } else { red += GetRGBValue(layerColour, 1); green += GetRGBValue(layerColour, 2); blue += GetRGBValue(layerColour, 3); } } backRed = BoundBy(red - 255, 0, 255); backGreen = BoundBy(green - 255, 0, 255); backBlue = BoundBy(blue - 255, 0, 255); red = BoundBy(red, 0, 255); green = BoundBy(green, 0, 255); blue = BoundBy(blue, 0, 255); alpha = Max(backRed, Max(backGreen, backBlue)); SetSkyAdjust(RGBa(red, green, blue, alpha), RGB(backRed, backGreen, backBlue)); } /* Function: GetSkyColourModulation Returns the current colour modulation of the specified layer. Parameters: layerIndex - Index of the layer. */ global func GetSkyColourModulation(int layerIndex) { if(!Inside(layerIndex, 0, SkyColourLayerCount - 1)) return; CheckSkyColourArrayInitialization(); return SkyColours[layerIndex]; } /* Function: IsSkyColourModulationSubtractive Returns whether the specified layer is drawn additively or subtractively. Returns: _true_ if subtractive, _false_ if additive. */ global func IsSkyColourModulationSubtractive(int layerIndex) { if(!Inside(layerIndex, 0, SkyColourLayerCount - 1)) return; CheckSkyColourArrayInitialization(); return SkyColoursSubtractive[layerIndex]; } /* Function: ResetSkyColourModulation Resets all layers to default values, so the sky is completely without modulation. */ global func ResetSkyColourModulation() { CheckSkyColourArrayInitialization(); for(var i = 0; i < SkyColourLayerCount; i++) { SkyColours[i] = RGBa(0, 0, 0, 0); SkyColoursSubtractive[i] = false; } SetSkyAdjust(RGBa(255, 255, 255, 0), RGB(0, 0, 0)); } /* Internal helper */ global func CheckSkyColourArrayInitialization() { if(SkyColours == 0) { SkyColours = CreateArray(SkyColourLayerCount); SkyColoursSubtractive = CreateArray(SkyColourLayerCount); } }
722,160
./clinfinity/Clinfinity.c4d/System.c4g/TeamOwner.c
// Manages owner transfership when a player is eliminated. #strict 2 // hijack goals #appendto GOAL protected func RemovePlayer(int plr) { var team = GetPlayerTeam(plr); if(team) { var players = GetPlayersByTeam(team); var newOwner = NO_OWNER; for(var p in players) { if(p != plr) { newOwner = p; break; } } if(newOwner != NO_OWNER) { for(var obj in FindObjects(Find_Owner(plr))) obj->SetOwner(newOwner); } } return _inherited(plr, ...); }
722,161
./clinfinity/Clinfinity.c4d/System.c4g/Conkit.c
/* Conkit ability for aviator */ #strict 2 #appendto AVTR public func ContextConkit(object caller) { [$CtxConkit$|Image=CCNT] SetComDir(COMD_Stop); if(!GetPhysical("CanConstruct", PHYS_Current)) { PlayerMessage(GetController(), "$TxtCantConstruct$", this, GetName()); return; } CreateMenu(CXCN, this, this, C4MN_Extra_Components, "$TxtNoconstructionplansa$"); var type; var i = 0; while(type = GetPlrKnowledge(GetOwner(), 0, i++, C4D_Structure)) { if(type->~IsConkitBuilding() || (!type->~IsIndianHandcraft() && !type->~IsTrapperHandcraft())) { AddMaterialMenuItem("$TxtConstructions$", "CreateConstructionSite", type, this); } } } protected func CreateConstructionSite(id type) { if(GetAction() != "Walk") return; if(Contained()) return; if(type->~RejectConstruction(0, 10, this)) return; var fNeedMaterial; if(fNeedMaterial = FindObject(CNMT)) { var hNeeded = CreateHash(), iNeeded, ID; for(ID in GetMatSysIDs()) { if(iNeeded = GetComponent(ID, 0, 0, type)) { if(MatSysGetTeamFill(GetOwner(), ID) < iNeeded) { PlayerMessage(GetOwner(), "<c ff0000>$TxtNotEnoughMaterial$</c>", this); return; } else HashPut(hNeeded, ID, iNeeded); } } } var site; if(!(site = CreateConstruction(type, 0, 10, GetOwner(), 100, true, true))) return; if(fNeedMaterial) { var iter = HashIter(hNeeded), node; while(node = HashIterNext(iter)) { MatSysDoTeamFill(-node[1], GetOwner(), node[0]); site->SetComponent(node[0], node[1]); } } Message("$TxtConstructions$", this, GetName(site)); }
722,162
./clinfinity/Clinfinity.c4d/System.c4g/CannonAmmo.c
/* Defines objects that can be shot by the cannon. */ #strict 2 #appendto ROCK #appendto FLNT #appendto SFLN #appendto EFLN public func CannonAmmo() { return true; }
722,163
./clinfinity/Clinfinity.c4d/System.c4g/Tutorial.c
/*-- Tutorial Helpers --*/ #strict 2 static const SHOWCTRLPOS_Top = 0, SHOWCTRLPOS_TopLeft = 3, SHOWCTRLPOS_TopRight = 4, SHOWCTRLPOS_BottomLeft = 2, SHOWCTRLPOS_BottomRight = 1; static g_msgpos, g_msgoffx, g_msgoffy, g_msgwdt; global func HasSpeech(string strMessage) { var len = GetLength(strMessage); for (var i = 0; i < len; i++) if (GetChar(strMessage, i) == GetChar("$")) return true; return false; } global func TutorialMessage(string strMessage) { // Message with speech marker if (HasSpeech(strMessage)) // PlayerMessage will handle the speech output (and it won't show the message) PlayerMessage(0, strMessage); // Normal message display, in addition to speech output if (GetLength(strMessage)) strMessage = Format("@%s", strMessage); CustomMessage(strMessage, 0, GetPlayerByIndex(0), g_msgoffx, g_msgoffy, 0xffffff, DECO, "Portrait:SCLK::0000ff::1", g_msgpos | MSG_DropSpeech, g_msgwdt); } global func wait(int iTicks) { ScriptGo(0); Schedule("ScriptGo(1)", iTicks * 10); } global func repeat() { goto(ScriptCounter() - 1); } global func SetTutorialMessagePos(int posflags, int offx, int offy, int wdt) { g_msgpos = posflags; g_msgoffx = offx; g_msgoffy = offy; g_msgwdt = wdt; return true; }
722,164
./clinfinity/Clinfinity.c4d/System.c4g/GetComponents.c
/*-- GetComponents --*/ #strict 2 global func GetComponents() { // alles durchzΣhlen var aIDs, aNum, iNum = 0; // IDs finden, aus denen das GebΣude zusammengesetzt ist aIDs = CreateArray(); for (var i = 0, component; component = GetComponent(0, i); ++i) { aIDs[i] = component; } aNum = CreateArray(GetLength(aIDs)); // Dazugeh÷rige Anzahl for (var i = 0; i < GetLength(aIDs); ++i) { aNum[i] = GetComponent(aIDs[i]); iNum += aNum[i]; } // IDs der Components, dazugeh÷rige Anzahl, Anzahl insgesamt return [aIDs, aNum, iNum]; }
722,165
./clinfinity/Clinfinity.c4d/System.c4g/ContainerControl.c
/* Script: ContainerControl.c Clonk appendto. Defines control events called in the first carried object, analogous to the other control functions. */ #strict 2 #appendto CLNK protected func ControlLeft() { if(Control2Contents("Left")) return true; return inherited(...); } protected func ControlLeftDouble() { if(Control2Contents("LeftDouble")) return true; return inherited(...); } protected func ControlLeftReleased() { if(Control2Contents("LeftReleased")) return true; return inherited(...); } protected func ControlRight() { if(Control2Contents("Right")) return true; return inherited(...); } protected func ControlRightDouble() { if(Control2Contents("RightDouble")) return true; return inherited(...); } protected func ControlRightReleased() { if(Control2Contents("RightReleased")) return true; return inherited(...); } protected func ControlUp() { if(Control2Contents("Up")) return true; return inherited(...); } protected func ControlUpDouble() { if(Control2Contents("UpDouble")) return true; return inherited(...); } protected func ControlUpReleased() { if(Control2Contents("UpReleased")) return true; return inherited(...); } protected func ControlDown() { if(Control2Contents("Down")) return true; return inherited(...); } protected func ControlDownSingle() { if(Control2Contents("DownSingle")) return true; return inherited(...); } protected func ControlDownDouble() { if(Control2Contents("DownDouble")) return true; return inherited(...); } protected func ControlDownReleased() { if(Control2Contents("DownReleased")) return true; return inherited(...); } protected func ControlDig() { if(Control2Contents("Dig")) return true; return inherited(...); } protected func ControlDigSingle() { if(Control2Contents("DigSingle")) return true; return inherited(...); } protected func ControlDigDouble() { if(Control2Contents("DigDouble")) return true; return inherited(...); } protected func ControlDigReleased() { if(Control2Contents("DigReleased")) return true; return inherited(...); } protected func ControlThrow() { if(Control2Contents("Throw")) return true; return inherited(...); } protected func ControlUpdate(object self, int commandDirection, bool dig, bool throw) { if(Control2Contents("Update", commandDirection, dig, throw)) return true; return inherited(self, commandDirection, dig, throw); } protected func ControlCommand(string commandName, object target, int targetX, int targetY, object target2, data) { if(Control2Contents("Command", commandName, target, targetX, targetY, target2, data)) return true; return inherited(...); } private func Control2Contents(string controlName, a, b, c, d, e, f) { return Contents(0) != 0 && ObjectCall(Contents(0), Format("Container%s", controlName), a, b, c, d, e, f); }
722,166
./clinfinity/Clinfinity.c4d/System.c4g/Message.c
/* Script: Message.c Provides functions related to messages. */ #strict 2 /* Function: FadingMessage Creates a moving and fading message. These messages will be queued if multiple are created at the same time. Parameters: message - The content of the message. x - Start position (relative to normal message position) y - Start position tx - End position ty - End position duration - Duration the message is shown. color - Color of the message text. ease - Easing function, see <CreateEaseFunction>. */ global func FadingMessage(string message, int x, int y, int tx, int ty, int duration, int color, string ease) { var timer = 1; // wait if there's another message var i = 0, existing; // find running effect while((existing = GetEffect("FadingMessage", this, i++)) && !GetEffect(0, this, existing, 3)); if(existing) timer = 0; var effectNum = AddEffect("FadingMessage", this, 10, timer, this, 0); EffectVar(0, this, effectNum) = message; EffectVar(1, this, effectNum) = x; EffectVar(2, this, effectNum) = y; EffectVar(3, this, effectNum) = tx; EffectVar(4, this, effectNum) = ty; EffectVar(5, this, effectNum) = duration; EffectVar(6, this, effectNum) = color; EffectVar(7, this, effectNum) = CreateEaseFunction(ease || "cubic-out", duration); if(existing) { var waiting = EffectVar(8, this, existing) || []; PushBack(effectNum, waiting); EffectVar(8, this, existing) = waiting; } } global func FxFadingMessageTimer(object target, int effectNum, int effectTime) { var duration = EffectVar(5, target, effectNum); var ease = EffectVar(7, target, effectNum); var easedVal = EvalEase(ease, effectTime); var color = SetRGBaValue(EffectVar(6, target, effectNum), ChangeRange(easedVal, 0, duration, 0, 255)); var x = EffectVar(1, target, effectNum), y = EffectVar(2, target, effectNum), tx = EffectVar(3, target, effectNum), ty = EffectVar(4, target, effectNum); if(x != tx) x = ChangeRange(easedVal, 0, duration, x, tx); if(y != ty) y = ChangeRange(easedVal, 0, duration, y, ty); CustomMessage(EffectVar(0, target, effectNum), this, NO_OWNER, x, y, color); if(effectTime > duration) return -1; } global func FxFadingMessageStop(object target, int effectNum, int reason, bool temp) { if(temp) return; var waiting = EffectVar(8, target, effectNum); if(waiting) { var effect = PopElement(waiting); ChangeEffect(0, this, effect, "FadingMessage", 1); if(GetLength(waiting)) EffectVar(8, target, effect) = waiting; } } /* Function: MatSysMessage Creates a fading message showing a change in MatSys storage. This function is automatically called by <MatSysDoFill> and <MatSysDoTeamFill>. Objects that don't want these messages to show can define a function NoMatSysMessages(id mat) that returns _true_ when no message should be displayed. The position of the message can be altered by defining a function MatSysMessagePosition(id mat) that returns an array [x, y]. Parameters: change - The amount by which the storage changed. mat - The id of the material whose storage changed. */ global func MatSysMessage(int change, id mat) { if(change == 0 || !this || this->~NoMatSysMessages(mat)) return; var pos = this->~MatSysMessagePosition(mat) || [0, 0]; var msg = Format("{{%i}}%s", mat, IntToStr(change, true)); var color; if(change < 0) color = RGB(255, 0, 0); else color = RGB(0, 255, 0); FadingMessage(msg, pos[0], pos[1], pos[0], pos[1] - 50, 75, color, "circle"); }
722,167
./clinfinity/Clinfinity.c4d/System.c4g/Demolition.c
/* Manages building demolition. */ #strict 2 #appendto CLNK #appendto COLV protected func ContextDemolition(object clonk) { [$CtxDemolitionDesc$|Image=CRYC|Condition=FindBuildingToDemolish] CreateMenu(CXCN, clonk, this); AddMenuItem("$CtxDemolitionDesc$!", "StartDemolition", MS4C, clonk, 0, 0, "OK", 2, 3); } protected func FindBuildingToDemolish() { if(GetID() == COLV) { var platform = this->~GetPlatform(); return !FindObject2(platform->Find_BuildingsOnPlatform()) && platform; } return FindObject2(Find_AtObject(), Find_Category(C4D_Structure), Find_Allied(GetOwner()), Find_Not(Find_Owner(NO_OWNER)), Find_Not(Find_Func("NoDemolition"))); } protected func StartDemolition() { var building = FindBuildingToDemolish(); if(building) { var owner = GetOwner(); for(var i = 0, comp, num; (comp = GetComponent(0, i, building)) && (num = GetComponent(comp, i, building)); i++) { MatSysDoFill(RandomX(1, num / 2), owner, comp); } Sound("DePressurize"); building->CastParticles("PSpark", 10, 70, RandomX(-10, 10), RandomX(-10, 10), 50, 200); building->CastParticles("PxSpark", 10, 70, RandomX(-10, 10), RandomX(-10, 10), 50, 200); building->RemoveObject(); } }
722,168
./clinfinity/Clinfinity.c4d/System.c4g/Math.c
/* Mathematische Funktionen */ #strict 2 static const RoundUp = 1, RoundDown = 2; global func Round(int iValue, int iNum, int iDir) { var iMod = iValue % iNum; if(iDir == RoundDown || (!iDir && Abs(iMod) < iNum / 2)) iValue -= iMod; else if(iDir == RoundUp || (!iDir && Abs(iMod) >= iNum / 2)) iValue += iNum - iMod; return iValue; } global func ChangeRange(int iValue, int iOldMin, int iOldMax, int iMin, int iMax) { return (iValue - iOldMin) * (iMax - iMin) / (iOldMax - iOldMin) + iMin; } /* Rotates the point (x, y) around (ox, oy) by angle degrees. */ global func Rotate(int angle, int &x, int &y, int ox, int oy, int prec) { var xr = Cos(angle, x - ox, prec) - Sin(angle, y - oy, prec), yr = Sin(angle, x - ox, prec) + Cos(angle, y - oy, prec); x = xr; y = yr; }
722,169
./clinfinity/Clinfinity.c4d/System.c4g/IsleRespawn.c
/* Script: Isle Respawn Provides functionality for saving an island and later respawning it or even copying it to other places. Island Save Format ================== The island is saved using an array with the following structure: - First element: Array saving the rectangle passed to <SaveIsland> - Second element: Array of arrays of the format [material, texture, number]. They express a horizontal string of material pixels of one type. "Line breaks" have to be figured out using the first element. */ #strict 2 /* Function: SaveIsland Saves and returns the island specified by the parameters. Parameters: x - Top-left point of the saving rectangle y - Top-left point of the saving rectangle wdt - Width of the saving rectangle hgt - Height of the saving rectangle Returns: The island data. */ global func SaveIsland(int x, int y, int wdt, int hgt) { var isle = [[x, y, wdt, hgt], []]; var i = 1, mat = GetMaterial(x, y), tex = GetTexture(x, y), n = 0, nextMat, nextTex; for(var iy = y; iy < y + hgt; iy++) { for(var ix = x; ix < x + wdt; ix++) { nextMat = GetMaterial(ix, iy); nextTex = GetTexture(ix, iy); if(nextMat == mat && nextTex == tex) n++; else { PushBack([mat, tex, n], isle[1]); mat = nextMat; tex = nextTex; n = 1; } } } PushBack([mat, tex, n], isle[1]); return isle; } /* Function: RestoreIsland Restores a saved island instantly. *Warning*: This function might freeze the game for a short moment if the island is very large. The x and y parameters can be used to copy the saved island to other places. Parameters: isle - The island data generated by <SaveIsland> ox - (optional) A new x coordinate overwriting the original one oy - (optional) A new y coordinate overwriting the original one */ global func RestoreIsland(array isle, int ox, int oy) { var x = ox || isle[0][0], y = oy || isle[0][1], wdt = isle[0][2], hgt = isle[0][3]; var ix = x, iy = y; var length, remaining, n, yInc; for(var ms in isle[1]) { length = ms[2]; while(length > 0) { // remaining pixels in this line remaining = wdt - ix + x; n = length; yInc = false; if(length >= remaining) { n = remaining; yInc = true; } if(ms[0] != -1) { DrawMaterialHLine(Format("%s-%s", MaterialName(ms[0]), ms[1]), ix, iy, n, true); CreateParticle("PSpark", ix, iy, 20, 5, 50, GetMaterialColorRGB(ms[0])); } ix += n; length -= n; if(yInc) { ix = x; iy++; } } } return true; } /* Function: PeriodicIslandRespawn Saves and restores the given island periodically. The island won't be restored while there are Clonks inside. Parameters: interval - Time interval in which the specified island is restored other parameters - see <SaveIsland> */ global func PeriodicIslandRespawn(int interval, int x, int y, int wdt, int hgt) { var effectNum = AddEffect("PeriodicIslandRespawn", 0, 1, interval); EffectVar(0, 0, effectNum) = SaveIsland(x, y, wdt, hgt); } global func FxPeriodicIslandRespawnTimer(object target, int effectNum, int effectTime) { var isle = EffectVar(0, target, effectNum), rect = isle[0]; if(!FindObject2(Find_OCF(OCF_Alive), Find_InRect(rect[0], rect[1], rect[2], rect[3]))) { RestoreIsland(isle); } }
722,170
./clinfinity/Clinfinity.c4d/Crew.c4d/Aviator.c4d/Script.c
/* Script: Aviator */ #strict 2 #include CLNK static const AVTR_WeaponOverlay = 2; /* Itemlimit */ public func MaxContentsCount() { return 3; } protected func RejectCollect(id ID, object obj) { // Only two flints at any time. return obj->~IsFlint() && ObjectCount2(Find_Container(this), Find_Func("IsFlint")) >= 2; } /* Inhalt durchwechseln */ protected func ControlSpecial() { ShiftContents(); } protected func Death(int killedBy) { /* Respawn */ var tank = FindObject2(Find_ID(STMT), Find_Allied(GetOwner())); if(tank) { var new = CreateObject(GetID(), 0, 0, GetOwner()); new->GrabObjectInfo(this); new->Enter(tank); } // try to award a hat if(Hostile(GetController(), killedBy)) { var clonk = GetCursor(killedBy); if(clonk) clonk->AddHat(C4Id(Format("HAT%d", RandomX(1, 9)))); } return _inherited(killedBy, ...); } /* Section: Weapons Provides functionality for aiming and shooting weapons (previously only rifles). Compatible weapons must define the following functions: - IsWeapon - HandX/HandY: Overlay position in 1/1000px - GetTargets: Possible targets for auto aim - CanLoad: Whether the weapon must be loaded - StartLoading: Called when a reload is starting - Load: Called after the loading animation finished - Abort: Called when aiming is aborted - Fire(clonk, angle): Called when the user wants to fire */ // aim radius in degrees static const AVTR_MinAimAngle = 0; static const AVTR_MaxAimAngle = 140; static const AVTR_InitialAimAngle = 84; static const AVTR_AimStep = 20; local activeRifle, crosshair, aimAngle; /* Function: CanUseRifle The Aviator can use rifles. Returns: *true* */ public func CanUseRifle() { return true; } /* Function: StartAiming Sets the appropriate aiming action, allowing the player to aim and fire the weapon. Parameters: rifle - the rifle which will receive the _Load()_, _Fire()_ and _Abort()_ events */ public func StartAiming(object rifle) { var action = GetAction(); if(rifle->IsWeapon()) { var aimAction; if(action == "Walk") aimAction = "AimRifle"; else if(action == "Ride" || action == "RideStil") aimAction = "RideAimRifle"; if(aimAction) { activeRifle = rifle; aimAngle = AVTR_InitialAimAngle; SetAction(aimAction); CreateCrosshair(); DrawWeaponOverlay(); UpdateAimPhase(); rifle->~StartAiming(this); return true; } } } // creates a crosshair for better aiming private func CreateCrosshair() { crosshair = CreateObject(WCHR, 0, 0, GetOwner()); crosshair->SetAction("Crosshair", this); } // Updates the Aviator's aim phase to the current aimAngle private func UpdateAimPhase() { if(aimAngle < 6) SetPhase(0); else if(aimAngle < 24) SetPhase(1); else if(aimAngle < 35) SetPhase(2); else if(aimAngle < 48) SetPhase(3); else if(aimAngle < 54) SetPhase(4); else if(aimAngle < 72) SetPhase(5); else if(aimAngle < 90) SetPhase(6); else if(aimAngle < 108) SetPhase(7); else if(aimAngle < 128) SetPhase(8); else SetPhase(9); AdjustWeaponOverlay(); // update crosshair placement var dir = GetDir() || -1; crosshair->SetVertexXY(0, -Sin(aimAngle, 40)*dir, Cos(aimAngle, 40) + activeRifle->~HandY() / 1000); } // Draws the weapon overlay on top of the aiming aviator. // Adjustments are automatically done when the aim angle changes. private func DrawWeaponOverlay() { SetGraphics(0, this, activeRifle->GetID(), AVTR_WeaponOverlay, GFXOV_MODE_Object, 0, 0, activeRifle); //SetGraphics(0, this, activeRifle->GetID(), AVTR_WeaponOverlay, GFXOV_MODE_Base); } // Calculates weapon position and angle. private func WeaponAt(&x, &y, &r) { if(IsReloading()) r = 45; else r = aimAngle - 90; x = -Sin(aimAngle, 10); y = Cos(aimAngle, 10); } // Adjusts the weapon overlay on top of the aviator depending on the current aiming angle. // Stolen from Hazard (Items.c4d/Weapons.c4d/Weapon.c4d/Script.c) private func AdjustWeaponOverlay() { // Variablen für die Transformation var width, height; // Breiten- und Höhenverzerrung der Waffe var xskew, yskew; // Zerrung der Waffe, wird zur Rotation gebraucht var size; // Größe der Waffe in der Hand: 1000 = 100% // Variablen für die Position var xaim, yaim; // Offset, dass sich durch zielen ergibt var dir; // Richtung in die das Objekt schaut var xoff, yoff, r; WeaponAt(xoff, yoff, r); // Variablen mit Werten versehen width = height = xskew = yskew = 1; size = 1000; dir = GetDir()*2-1; if(r > 180 || r < -180) dir *= -1; r *= dir; var xfact = size * activeRifle->~HandX(); var yfact = size * activeRifle->~HandY(); xoff += Cos(r,xfact)/1000 + dir*Sin(r,yfact)/1000; yoff -= Cos(r,yfact)/1000 - dir*Sin(r,xfact)/1000; if(dir == 1) { height = -1; xskew = -1; yskew = -1; } r = -90*dir-r-90; height *= width *= Cos(r, size); xskew *= Sin(r, size); yskew *= -xskew; xoff *= dir; SetObjDrawTransform(1000,xskew,xoff,yskew,1000,yoff, 0, AVTR_WeaponOverlay); //position activeRifle->SetObjDrawTransform(width,xskew,0,yskew,height); //Größe und Rotation } // Removes the weapon overlay created by DrawWeaponOverlay(). private func RemoveWeaponOverlay() { SetGraphics(0, this, 0, AVTR_WeaponOverlay); } /* Function: IsAiming Returns: Whether the Aviator is currently aiming his rifle. */ public func IsAiming() { var action = GetAction(); return action == "AimRifle" || action == "RideAimRifle"; } /* Function: IsReloading Returns: Whether the Aviator is currently reloading his gun. */ public func IsReloading() { var action = GetAction(); return action == "LoadRifle" || action == "RideLoadRifle"; } /* Function: DoAim Changes the aim by *angle* degrees. Parameters: angle - How much the aim should be changed. Negative -> up, positive -> down. */ public func DoAim(int angle) { aimAngle = BoundBy(aimAngle + angle, AVTR_MinAimAngle, AVTR_MaxAimAngle); UpdateAimPhase(); } /* Function: AutoAim Adjusts the current aim by searching for potential targets. Calls _GetTargets()_ in the gun to get a selection of potential targets. */ public func AutoAim() { if(!IsAiming()) return; var x = GetX(), y = GetY(), tx, ty; var targets = activeRifle->GetTargets(); for(var target in targets) { tx = target->GetX(); ty = target->GetY(); // check angle var angle = Angle(x, y, tx, ty); if(GetDir() == DIR_Left) angle = 360 - angle; // roughly in direction of current aim and nothing solid inbetween? if(Inside(angle, AVTR_MinAimAngle, AVTR_MaxAimAngle) && Inside(angle, aimAngle - AVTR_AimStep, aimAngle + AVTR_AimStep) && PathFree(x, y, tx, ty)) { // target found! // aim at target aimAngle = angle; UpdateAimPhase(); return true; } } } /* Function: LoadRifle Starts the appropriate rifle loading action when aming and returns to the aim action again. Calls the function _Load()_ in the active weapon after loading finishes. */ public func LoadRifle() { var action = GetAction(), loadingAction; if(action == "AimRifle") loadingAction = "LoadRifle"; else if(action == "RideAimRifle") loadingAction = "RideLoadRifle"; if(loadingAction && activeRifle->CanLoad()) { activeRifle->~StartLoading(); SetAction(loadingAction); AdjustWeaponOverlay(); } else { Sound("CommandFailure1"); } } /* Function: AbortAiming Stops aiming, returning to the 'Walk' action if possible. This function is also automatically called when the Aviator is hit by something while aiming. */ public func AbortAiming() { // don't do anything if just for reloading if(IsReloading()) return; if(IsAiming()) SetAction("Walk"); RemoveWeaponOverlay(); if(crosshair) { crosshair->RemoveObject(); activeRifle->Abort(); activeRifle = 0; } } /* Control and Action calls {{{ */ protected func AimAgain() { activeRifle->Load(); SetAction("AimRifle"); UpdateAimPhase(); } protected func AimAgainRide() { activeRifle->Load(); SetAction("RideAimRifle"); UpdateAimPhase(); } protected func ControlThrow() { if(IsAiming()) { AutoAim(); activeRifle->Fire(this, aimAngle); return 1; } var obj = Contents(); if(obj && obj->~IsWeapon()) { StartAiming(obj); return 1; } return inherited(...); } public func ControlCommand(string command, object pClonk, int iX, int iY) { if(!IsAiming()) return inherited(command, pClonk, iX, iY, ...); if(GetAction(pClonk) != "AimRifle" && GetAction(pClonk) != "RideAimRifle") return 1; var iAngle = Angle(GetX(pClonk), GetY(pClonk), iX, iY); // Shoot into correct direction if(iAngle < 180) { SetDir(1, pClonk); SetPhase(BoundBy(iAngle, 0, 135) / 15, pClonk); if(GetAction(pClonk) == "RideAimRifle" && GetDir(GetActionTarget(0, pClonk)) == DIR_Left) GetActionTarget(0, pClonk)->~TurnRight(); } else { SetDir(0, pClonk); SetPhase((360 - BoundBy(iAngle, 225, 360)) / 15, pClonk); if(GetAction(pClonk) == "RideAimRifle" && GetDir(GetActionTarget(0, pClonk)) == DIR_Right) GetActionTarget(0, pClonk)->~TurnLeft(); } if(iAngle > 180) iAngle = -iAngle + 360; aimAngle = iAngle; UpdateAimPhase(); activeRifle->Fire(this, iAngle); return 1; } protected func ControlDig() { if(IsAiming()) { LoadRifle(); return 1; } return inherited(...); } protected func ControlUp() { if(IsAiming()) { DoAim(-AVTR_AimStep); return 1; } return inherited(...); } protected func ControlUpDouble() { if(IsAiming()) { DoAim(-AVTR_AimStep); return 1; } return inherited(...); } protected func ControlDown() { if(IsAiming()) { DoAim(AVTR_AimStep); return 1; } return inherited(...); } protected func ControlDownDouble() { if(IsAiming()) { DoAim(AVTR_AimStep); return 1; } return inherited(...); } protected func ControlLeft() { if(IsAiming()) { SetDir(DIR_Left); UpdateAimPhase(); return 1; } return inherited(...); } protected func ControlRight() { if(IsAiming()) { SetDir(DIR_Right); UpdateAimPhase(); return 1; } return inherited(...); } protected func ControlLeftDouble() { if(IsAiming()) { AbortAiming(); return 1; } return inherited(...); } protected func ControlRightDouble() { if(IsAiming()) { AbortAiming(); return 1; } return inherited(...); } // stubs for Gun Action calls (not implemented yet) protected func DrawingGun() {} protected func FiringGun() {} protected func AbortJumpDrawGun() {} protected func AbortJumpReplaceGun() {} protected func LoadGunEnd() {} /* Control functions end }}} */ // vim: fdm=marker
722,171
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Rain.c4d/Script.c
/*-- Regen --*/ #strict protected func Initialize() { SetPosition(0,0); return 1; } private func Rain() { if(!GetPlayerCount()) return 0; var plr = 0; var range = 1000; var borderleft = GetX(GetCursor(GetPlayerByIndex(plr)))-range; var borderright = GetX(GetCursor(GetPlayerByIndex(plr)))+range; for(; plr < GetPlayerCount(); plr++) { borderleft = Min(borderleft, GetX(GetCursor(GetPlayerByIndex(plr)))-range); borderright = Max(borderright, GetX(GetCursor(GetPlayerByIndex(plr)))+range); } for(var cnt = 0; cnt < 20; cnt++) CreateParticle("Raindrop", RandomX(borderleft, borderright), 0, RandomX(GetWind(0,0,1)*3, GetWind(0,0,1)*5), RandomX(200, 300), 5*64 + Random(32), 0, this); return 1; }
722,172
./clinfinity/Clinfinity.c4d/Enviroment.c4d/BirdSong.c4d/Script.c
/*-- BirdTweet --*/ #strict 2 #include RULE local tweetCount; private func Initialized(int ruleTypeCount) { tweetCount = ruleTypeCount; if(IsDay()) ScheduleTweets(); var time = FindObject2(Find_ID(TIME)); if(time == 0) return; time->AddEventListener(this, ["OnDay", "ScheduleTweets"]); time->AddEventListener(this, "OnNightfall"); time->AddAlarmListener(this, time->GetDaybreakTime() + TIME_TwilightLength / 4); time->AddAlarmListener(this, time->GetNightfallTime() + TIME_TwilightLength * 3 / 4); } protected func ScheduleTweets() { for(var i = 0; i < tweetCount; ++i) { // randomize start ScheduleCall(0, "Singing", 25 - Random(20)); } } public func OnAlarm(object clock, int time) { if(IsDaybreak()) Sound("Rooster*"); else Sound("Owl"); } public func OnNightfall(object clock) { ClearScheduleCall(this, "Singing"); } private func Singing() { if(!Random(20)) { // check if there are some trees left if(ObjectCount2(Find_Category(C4D_StaticBack), Find_Func("IsTree")) >= 10) { //Sound("BirdSong*", 1); var sound = Random(15)+1; Sound(Format("BirdSong%d", sound), true); //Log("%d", sound); } else Sound("Crow*", 1); } ScheduleCall(this, "Singing", 25); }
722,173
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Nightsky.c4d/BigDipper.c4d/Script.c
#strict 2 // Local(0) and Local(1) are used for parallax movement protected func Initialize() { SetClrModulation(RGBa(255, 255, 255, 255)); Local(0) = Local(1) = Random(5); }
722,174
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Stars.c4d/Script.c
/*-- Sternenhimmel --*/ #strict 2 #include RULE local constellations; private func Initialized(int ruleTypeCount) { var time = FindObject2(Find_ID(TIME)); if(time == 0) { RemoveObject(); return; } SetPosition(0, 0); time->AddEventListener(this, "OnNightfall"); time->AddAlarmListener(this, time->GetDaybreakTime() - 255 * TIME_SecondsPerFrame); // Constellations constellations = []; PushBack(CreateObject(NSBD, Random(LandscapeWidth()), Random(LandscapeHeight()), NO_OWNER), constellations); var maxStarsCount = (LandscapeWidth() * LandscapeHeight() * ruleTypeCount) / 20000; for(var i = 0; i < maxStarsCount; ++i) { CreateObject(STAR, Random(LandscapeWidth()), Random(LandscapeHeight()), NO_OWNER); } } public func OnNightfall() { for(var star in FindObjects(Find_ID(STAR))) { ScheduleCall(0, "FadeStarIn", RandomX(TIME_TwilightLength * 9 / 10 / TIME_SecondsPerFrame, TIME_TwilightLength / TIME_SecondsPerFrame), 0, star); } for(var constellation in constellations) { ScheduleCall(0, "FadeStarIn", RandomX(TIME_TwilightLength * 9 / 10 / TIME_SecondsPerFrame, TIME_TwilightLength / TIME_SecondsPerFrame), 0, constellation); } } public func OnAlarm(object clock, int time) { for(var star in FindObjects(Find_ID(STAR))) { ScheduleCall(0, "FadeStarOut", RandomX(1, TIME_TwilightLength / 10 / TIME_SecondsPerFrame), 0, star); } for(var constellation in constellations) { ScheduleCall(0, "FadeStarOut", RandomX(1, TIME_TwilightLength / 10 / TIME_SecondsPerFrame), 0, constellation); } } public func FadeStarIn(object star) { star->FadeIn(); } public func FadeStarOut(object star) { star->FadeOut(); }
722,175
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Stars.c4d/Star.c4d/Script.c
/*-- Star --*/ #strict 2 local brightness; // Local(0) and Local(1) are used for parallax movement protected func Initialize() { brightness = Random(10) + 1; SetAction("Shine"); SetPhase(brightness - 1); if(Random(3)) { SetClrModulation(RGBa(Random(100) + 156, Random(100) + 156, Random(100) + 156, 255)); } else { SetClrModulation(RGBa(255, 255, 255, 255)); } SetCategory(GetCategory() | C4D_Parallax | C4D_Background); Local(0) = Local(1) = Random(5) + brightness * 1 - 1; }
722,176
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Beam.c4d/Script.c
/* -- Plank -- */ #strict 2 protected func Left() { SetSolidMask(0, 22, 41, 22, 0, 0); } protected func Right() { SetSolidMask(41, 22, 41, 22, 0, 0); } protected func CheckClonk() { // any clonk on me? if(FindObject2(Find_InRect(-20, -30, 40, 25), Find_Or(Find_OCF(OCF_Alive), Find_Category(C4D_Object)), Find_Or(Find_Func("GetXDir"), Find_Func("GetYDir")))) { Sound("squeak*"); } }
722,177
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Crumbling Island.c4d/Script.c
/*-- Crumbling Island --*/ #strict 2 func Initialize(obj) { Local(0) = RandomX(95, 98); Local(1) = 92; } protected func Crumble(){ if(!Random(20)) SetAction("Crumble"); } protected func RemoveObj(obj){ RemoveObject(obj); }
722,178
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Ruin.c4d/Script.c
/*-- Ruin --*/ #strict func Initialize() { CreateObject(RAIL, 5, 19, -1); //rail CreateObject(CPFR, 28, 20, -1); //campfire return(1); }
722,179
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Ruin.c4d/CampFire.c4d/Script.c
/*-- Lagerfeuer --*/ #strict protected func ControlThrow(caller){ // get player var plr = caller->GetOwner(); if(MatSysGetTeamFill(plr, WOOD) >= 1) { MatSysDoTeamFill(-1, plr, WOOD); CreateContents(WOOD); } else { Sound("Error"); Message("$TxtNoWood$", caller); } } private func Smoking() { Smoke(Random(3), Random(3), Random(8) + 5); } protected func CheckContents() { if(GetActTime()>5000) SetAction("Idle"); if(ActIdle()) if(ContentsCount(WOOD)) return(BurnWood()); } private func BurnWood() { var pWood; if(pWood=FindContents(WOOD)) RemoveObject(pWood); Sound("Inflame"); SetAction("Burn"); } // au▀er Holz nichts aufnehmen protected func RejectCollect(def,pObj) { if(def!=WOOD) return(1); }
722,180
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Waterfall.c4d/Script.c
/*-- Wasserfall --*/ #strict protected func Initialize(){ DigFree(0,0,2); } protected func CastPXS2() { CastPXS("Water",5,20,0); return(1); }
722,181
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Tower.c4d/Script.c
/*-- Tower --*/ #strict 2 func Initialize() { Local(0) = RandomX(90, 100); Local(1) = 95; }
722,182
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Webs.c4d/Script.c
/*-- Weben --*/ #strict 2 protected func Initialize() { SetAction("Be"); if(Random(3)) SetCategory(C4D_Foreground); SetPhase (Random(5), 0); SetClrModulation(RGBa(255,255,255,55+RandomX(-7,12))); } public func Set(phase) { SetPhase(phase); var width = GetDefCoreVal("Width", "DefCore", GetID()); var height = GetDefCoreVal("Height", "DefCore", GetID()); }
722,183
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Tower2.c4d/Script.c
/*-- Tower --*/ #strict 2 func Initialize() { Local(0) = RandomX(99, 100); Local(1) = 95; }
722,184
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Mushroom.c4d/Script.c
#strict #include TREE private func ReproductionAreaSize() { return(80); } private func ReproductionRate() { return(23); } private func MaxTreeCount() { return(4); } protected func Damage() {} protected func Incineration() { SetCategory(16); } public func Construction() { SetAction("Exist"); // zufΣllige Animationsphase SetDir(Random(4)); SetPosition(GetX(),GetY()-5); // baum-syndrom var dwRGB = HSL(RandomX(0,38),RandomX(127,255),RandomX(64,160)); SetColorDw(dwRGB); } public func GetMyColor(dwColor) { var dwRGB = dwColor; var h,s,l,a; dwRGB = RGB2HSL(dwRGB); SplitRGBaValue(dwRGB,h,s,l,a); h = h+RandomX(-10,+10); // jede Farbe ist zⁿchtbar! s = BoundBy(s+RandomX(-15,+15),127,255); l = BoundBy(l+RandomX(-10,+10),64,227); dwRGB = HSL(h,s,l); SetColorDw(dwRGB); } public func Reproduction() { // Ist noch Platz fⁿr einen Baum? var iSize = ReproductionAreaSize(); var iOffset = iSize / -2; if (ObjectCount(GetID(), iOffset, iOffset, iSize, iSize)<MaxTreeCount()) { // OK, hin damit var pMush = PlaceVegetation(GetID(), iOffset, iOffset, iSize, iSize, 10); if(pMush) pMush->GetMyColor(GetColorDw()); return(1); } // Kein Platz ;'( return(0); } public func ContextChop(pClonk) // per Kontextmenⁿ pflⁿcken { [$TxtPick$|Image=MUSH|Condition=IsStanding] Pick(); return(1); } protected func RejectEntrance() { if(GetCon()<100) return(1); } public func Entrance() { // per Einsammeln pflⁿcken [$TxtPick$] if(IsStanding()) Pick(); return(1); } public func Pick() { // pflⁿcken Sound("Grab"); var iDir = GetDir(); SetAction("Idle"); SetAction("Exist"); SetDir(iDir); SetCategory(16); } public func Activate(object pClonk) // essen { [$TxtEat$] Eat(pClonk); return(1); } protected func Eat(object pClonk) { pClonk->~Feed(20); DoMagicEnergy(4,pClonk); RemoveObject(); return(1); } protected func Existing() { if(IsStanding()) return(); // re-seed if(!Contained()) if(!GetYDir()) if(!GetXDir()) SetCategory(C4D_StaticBack); } public func IsStanding() { return(GetCategory() & C4D_StaticBack); } // steht noch func IsAlchemContainer() { return(true); } func AlchemProcessTime() { return(80); } func IsTree() { return false; } // kann nicht zur Holzproduktion verwendet werden protected func Hit() { Sound("WoodHit*"); }
722,185
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/FadingFog.c4d/Script.c
/*-- Fading Fog --*/ #strict 2 protected func Initialize() { var time = FindObject2(Find_ID(TIME)); if(time != 0) time->AddAlarmListener(this, GetNightfallTime()); } protected func OnAlarm() { FadeFromTo(RGBa(255, 255, 255, 0), RGBa(255, 255, 255, 120)); }
722,186
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Skyland.c4d/Script.c
/*-- Skyland --*/ #strict 2 func Initialize() { Local(0) = RandomX(60, 80); Local(1) = 90; }
722,187
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Crate.c4d/Script.c
/*-- Crate --*/ #strict 2 func Initialize() { //random angle SetAction(Format("%d", RandomX(1,7))); }
722,188
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Sign.c4d/Script.c
/*-- Trailsign --*/ #strict protected func ControlUp(obj){ Message("$Message$", obj); }
722,189
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Decoration.c4d/Moon.c4d/Script.c
/*-- Moon --*/ #strict 2 func Initialize() { Local(0) = RandomX(50, 80); Local(1) = 70; SetAction("Shine"); }
722,190
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Cicadas.c4d/Script.c
/*-- Zikaden --*/ #strict 2 protected func Initialize() { var time = FindObject2(Find_ID(TIME)); if(time == 0) { StartCicadas(); return; } else if(IsNight()) { StartCicadas(); } time->AddEventListener(this, ["OnNight", "StartCicadas"]); time->AddEventListener(this, ["OnDaybreak", "StopCicadas"]); } protected func StartCicadas() { SetAction("Cicadas"); SetPhase(Random(20)); } protected func StopCicadas() { SetAction("Idle"); } private func Cicadas() { if(!Random(20)) Sound("Cricket*", true); }
722,191
./clinfinity/Clinfinity.c4d/Enviroment.c4d/Time.c4d/Script.c
/* Script: Time Controls the passage of time and the day/night cycle. See <Day/night cycle> for details about the phases of the day/night cycle. Time is measured in the standard 24-hour clock. The function <Time> should be used to express and compare points in time, see there and <SetTime> for examples. Several events are sent by the Time object. - OnClockStrike, sent every full hour. The current time is passed as parameter to the event handler function. - OnDay, sent after daybreak is over and the day begins. - OnNight, sent after nightfall, when the night begins. - OnDaybreak, sent when daybreak begins. - OnNightfall, sent when nightfall begins. Additionally, settable <Alarms> are supported. */ #strict 2 /* Constants: Passage of time TIME_TotalDayLength - Total day length in seconds. TIME_TwilightLength - Length of twilight (daybreak and nightfall) in seconds. TIME_SecondsPerFrame - Number of seconds represented by one frame in game. */ static const TIME_TotalDayLength = 86400; static const TIME_TwilightLength = 6000; // = 100 Minutes (which is about the time it takes in reality) static const TIME_SecondsPerFrame = 4; /* Constants: Sky brightness and colours TIME_DarkSkyBlue - Value for brightness/blue during the blue hour. TIME_BrightSkyBlue - Value for brightness/blue at the beginning and end of daytime. */ static const TIME_DarkSkyBlue = 30; static const TIME_BrightSkyBlue = 255; // These are set in Initialize(). Don't change them afterwards! local daybreak, nightfall; // These get calculated automatically. Internal use only, don't touch! local day, night; local dayLength, nightLength; local currentSeconds; local alarms; protected func Initialize() { alarms = CreateHash(); // Important: If you set custom values, you absolutely must make sure that nightfall and daybreak don't overlap. daybreak = Time(5, 00); nightfall = Time(21, 30); CalculateDaytimes(); CalculateDurations(); var hours = 12; var minutes = 0; var seconds = 0; currentSeconds = hours * 3600 + minutes * 60 + seconds; ResumeClock(); } private func CalculateDaytimes() { day = daybreak + TIME_TwilightLength; night = (nightfall + TIME_TwilightLength) % TIME_TotalDayLength; } private func CalculateDurations() { dayLength = nightfall - day; nightLength = TIME_TotalDayLength - night + daybreak; } // Advances the clock by TIME_SecondsPerFrame protected func AdvanceClock() { currentSeconds += TIME_SecondsPerFrame; currentSeconds %= 86400; var alarmListeners = HashGet(alarms, currentSeconds, false); if(alarmListeners != 0) { for(var listener in alarmListeners) { listener->~OnAlarm(this, currentSeconds); } } if((currentSeconds % 3600) == 0) { Emit("OnClockStrike", currentSeconds); } SetSkyColour(); ScheduleCall(this, "AdvanceClock", 1); } private func SetSkyColour() { if(IsDay()) { if(SecondsSince(day) < TIME_SecondsPerFrame) { Emit("OnDay"); } SetSkyColourModulation(CalculateDayBrightness(SecondsSince(day)), true, 4); } else if(IsNight()) { if(SecondsSince(night) < TIME_SecondsPerFrame) { Emit("OnNight"); } SetSkyColourModulation(CalculateNightBlue(SecondsSince(night)), true, 4); } else if(IsDaybreak()) { var progress = SecondsSince(daybreak); if(progress < TIME_SecondsPerFrame) { Emit("OnDaybreak"); } SetSkyColourModulation(CalculateDaybreakBlue(progress), true, 4); //SetSkyColourModulation(CalculateDaybreakRed(progress), false, 5); } else if(IsNightfall()) { if(SecondsSince(nightfall) < TIME_SecondsPerFrame) { Emit("OnNightfall"); } SetSkyColourModulation(CalculateNightfallBrightness(SecondsSince(nightfall)), true, 4); SetSkyColourModulation(CalculateNightfallRed(SecondsSince(nightfall)), false, 5); } } private func CalculateNightBlue(int progress) { /*if(progress < nightLength / 4) { var blue = 4 * TIME_DarkSkyBlue * (nightLength / 4 - progress) / nightLength; return RGB(0, 0, blue); } else if(progress > nightLength * 3 / 4) { var blue = TIME_DarkSkyBlue * 4 * progress / nightLength - 3 * TIME_DarkSkyBlue; return RGB(0, 0, blue); }*/ progress -= nightLength / 2; var blue = 3 * TIME_DarkSkyBlue * Abs(progress) / nightLength - TIME_DarkSkyBlue / 2; return RGB(0, 0, Max(0, blue)); } private func CalculateDaybreakBlue(int progress) { /*if(progress < TIME_TwilightLength / 2) { var maxBrightness = TIME_DarkSkyBlue; var brightness = 2 * maxBrightness * progress / TIME_TwilightLength; return RGB(brightness, brightness, TIME_DarkSkyBlue); } else { var minBrightness = TIME_DarkSkyBlue; var maxBrightness = TIME_BrightSkyBlue; var brightness = 2 * (maxBrightness - minBrightness) * progress / TIME_TwilightLength + (2 * minBrightness - maxBrightness); return RGB(brightness, brightness, brightness); }*/ var brightness = TIME_BrightSkyBlue * progress / TIME_TwilightLength; var blue = (TIME_BrightSkyBlue - TIME_DarkSkyBlue) * progress / TIME_TwilightLength + TIME_DarkSkyBlue; return RGB(brightness, brightness, blue); } /*private func CalculateDaybreakRed(int progress) { var maxRed = 200; progress -= TIME_TwilightLength / 2; var red = maxRed - (maxRed * 2 * Abs(progress) / TIME_TwilightLength); var green = red * 3 / 8; var blue = red * 1 / 4; return RGB(red, green, blue); }*/ private func CalculateDayBrightness(int progress) { if(progress < dayLength / 4) { var brightness = 4 * (255 - TIME_BrightSkyBlue) * progress / dayLength + TIME_BrightSkyBlue; return RGB(brightness, brightness, brightness); } else if(progress > dayLength * 3 / 4) { var brightness = 4 * (TIME_BrightSkyBlue - 255) * progress / dayLength + 4 * 255 - 3 * TIME_BrightSkyBlue; return RGB(brightness, brightness, brightness); } else { return RGB(255, 255, 255); } } private func CalculateNightfallBrightness(int progress) { /*var brightness = -TIME_BrightSkyBlue * progress / TIME_TwilightLength + TIME_BrightSkyBlue; var blue = (TIME_DarkSkyBlue - TIME_BrightSkyBlue) * progress / TIME_TwilightLength + TIME_BrightSkyBlue; return RGB(brightness, brightness, blue);*/ if(progress < TIME_TwilightLength / 2) { var brightness = 2 * (TIME_DarkSkyBlue - TIME_BrightSkyBlue) * progress / TIME_TwilightLength + TIME_BrightSkyBlue; return RGB(brightness, brightness, brightness); } else { progress -= TIME_TwilightLength / 2; var brightness = 2 * -TIME_DarkSkyBlue * progress / TIME_TwilightLength + TIME_DarkSkyBlue; return RGB(brightness, brightness, TIME_DarkSkyBlue); } } private func CalculateNightfallRed(int progress) { var maxRed = 200; progress -= TIME_TwilightLength / 2; var red = maxRed - (maxRed * 2 * Abs(progress) / TIME_TwilightLength); var green = red * 3 / 8; var blue = red * 1 / 4; return RGB(red, green, blue); } /* Passage of time */ private func NormaliseTime(int time) { time %= TIME_TotalDayLength; if(time < 0) { time += TIME_TotalDayLength; } time = time / TIME_SecondsPerFrame * TIME_SecondsPerFrame; // Don't allow 'odd' seconds. return time; } /* Function: Time Composes a time value from the given parameters _hours_, _minutes_ and _seconds_, with the latter being optional. You can also use this function to compare times. The following example code checks if it is afternoon: > var isAfternoon = GetTime() > Time(12, 00); Parameters: hours - Hours part. minutes - Minutes part. seconds - [optional] Seconds part. Returns: The specified point in time, measured in seconds. */ global func Time(int hours, int minutes, int seconds) { hours = BoundBy(hours, 0, 23); minutes = BoundBy(minutes, 0, 59); seconds = BoundBy(seconds, 0, 59); return hours * 3600 + minutes * 60 + seconds; } public func SetTime(int time) { currentSeconds = NormaliseTime(time); SetSkyColour(); } public func GetTime() { return currentSeconds; } public func PauseClock() { ClearScheduleCall(this, "AdvanceClock"); } public func ResumeClock() { if(GetEffectCount("IntScheduleCall", this) == 0) { ScheduleCall(this, "AdvanceClock", 1); } } /* Function: SecondsSince Returns how many seconds have passed since the specified point in time. The maximum returned value is 86399 (23 hours 59 minutes 59 seconds). If more time than that passes, the return value restarts at zero. Parameters: time - Point in time, measured in seconds. Returns: Seconds since _time_, measured in seconds. */ public func SecondsSince(int time) { time = NormaliseTime(time); var result; if(currentSeconds >= time) { result = currentSeconds - time; } else { result = 24 * 60 * 60 - time + currentSeconds; } return result; } /*public func SecondsToTime(int seconds) { var hours = seconds / 3600 * 100; var minutes = seconds / 60 % 60; return hours + minutes; }*/ public func GetDaybreakTime() { return daybreak; } public func GetDayTime() { return day; } public func GetNightfallTime() { return nightfall; } public func GetNightTime() { return night; } public func IsDaybreak() { return Inside(currentSeconds, daybreak, day - 1); } public func IsDay() { return Inside(currentSeconds, day, nightfall - 1); } public func IsNightfall() { return Inside(currentSeconds, nightfall, night - 1); } public func IsNight() { if(night < daybreak) { // Night starts after midnight return currentSeconds >= night && currentSeconds < daybreak; } else { // Night starts before midnight return currentSeconds >= night || currentSeconds < daybreak; } } /* Re-routed global functions */ /* Function: SetTime Sets the clock to the specified time. You should use the function _Time()_ for convenience. A typical call that sets the time to 19:30 (7:30 PM) looks like this: > SetTime(Time(19, 30)) Parameters: time - Time measured in seconds. */ global func SetTime(int time) { var timeObject = FindObject2(Find_ID(TIME)); if(timeObject != 0) timeObject->SetTime(time); } /* Function: GetTime Returns the current time measured in seconds. If no TIME object is present, it is always noon (12:00). Returns: The current time. */ global func GetTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) return time->GetTime(); else return Time(12, 00); } /* Function: PauseClock Stops the advancement of the clock. */ global func PauseClock() { var time = FindObject2(Find_ID(TIME)); if(time != 0) time->PauseClock(); } /* Function: ResumeClock Starts or resumes the advancement of the clock. */ global func ResumeClock() { var time = FindObject2(Find_ID(TIME)); if(time != 0) time->ResumeClock(); } global func GetDaybreakTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) return time->GetDaybreakTime(); } global func GetDayTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) return time->GetDayTime(); } global func GetNightfallTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) return time->GetNightfallTime(); } global func GetNightTime() { var time = FindObject2(Find_ID(TIME)); if(time != 0) return time->GetNightTime(); } /* Section: Alarms With alarms, listeners can receive a call (the "alarm") at a specified point in time. The listeners should implement a function called _OnAlarm()_, which receives the calling object and the current time, measured in seconds, as parameters. */ /* Function: AddAlarmListener Adds a listener, which will receive the alarm at the specified time. Notes: - The same listener can receive several _OnAlarm()_ calls at different points in time. However, it is not possible to add the same listener more than once for the same time. - The specified time is rounded to the next lower multiple of TIME_SecondsPerFrame. Parameters: listener - Listener that will receive the call. time - Alarm time. */ public func AddAlarmListener(object listener, int time) { time = NormaliseTime(time); var listeners = HashGet(alarms, time, false); if(listeners == 0) { listeners = [listener]; } else if(!InArray(listener, listeners)) { PushBack(listener, listeners); } HashPut(alarms, time, listeners); } /* Function: RemoveAlarmListener Removes a listener from the alarms list for the specified time. After calling this, the listener will no longer receive alarm calls for the specified point in time, but it will still receive the calls for other alarm times, if it was added to any. If the listener was not added for the specified alarm time before calling this function, the function call has no effect. Parameters: listener - Listener to remove. time - Alarm time. */ public func RemoveAlarmListener(object listener, int time) { time = NormaliseTime(time); var listeners = HashGet(alarms, time, false); if(listeners != 0 && InArray(listener, listeners)) { RemoveElement(listener, listeners); HashPut(alarms, time, listeners); } } /* Section: Day/night cycle The cycle consists of the four following phases - Day: The sky is brightest during this phase. - Nightfall: The sky darkens. - Night: Very dark or black sky. - Daybreak: The sky brightens again. In each phase, specifics things can occur. For example, nocturnal animals may wake up during nightfall and go to sleep when daybreak begins. It should be noted that the functions in this section only return *true* during the respective phase. For example, IsDay() does not return *true* during daybreak, even though the sky may already be bright. */ /* Function: IsDaybreak Returns: *true* if it is daybreak currently, *false* otherwise. */ global func IsDaybreak() { var time = FindObject2(Find_ID(TIME)); return time != 0 && time->IsDaybreak(); } /* Function: IsDay Returns: *true* if it is daytime currently or if no TIME object exists, *false* otherwise. */ global func IsDay() { var time = FindObject2(Find_ID(TIME)); return time == 0 || time->IsDay(); } /* Function: IsNightfall Returns: *true* if it is nightfall currently, *false* otherwise. */ global func IsNightfall() { var time = FindObject2(Find_ID(TIME)); return time != 0 && time->IsNightfall(); } /* Function: IsNight Returns: *true* if it is nighttime currently, *false* otherwise. */ global func IsNight() { var time = FindObject2(Find_ID(TIME)); return time != 0 && time->IsNight(); }
722,192
./clinfinity/Clinfinity.c4d/Helpers.c4d/Trajectory.c4d/Script.c
/*-- Projektilvorschau --*/ #strict 2 static const g_CrosshairID = TRTY; protected func Initialize() { } global func RemoveTrajectory(object obj) { // Finden und vernichten var trajectory = FindObject2(Find_ID(TRTY), Find_ActionTarget(obj)); if(trajectory) RemoveObject(trajectory); } /* Function: AddTrajectory Adds a trajectory preview to the given object. Parameters: obj - The object to attach the preview to. x - Start coordinates y - Relative to obj xDir - Launch speed yDir - Launch speed color - Color of the shown dots Returns: A trajectory object. */ global func AddTrajectory(object obj, int x, int y, int xDir, int yDir, int color) { if(!color) color = RGB(0, 255); //Log("Object: %s, x: %d, y: %d, xdir: %d, ydir: %d",GetName(obj),x,y,xDir,yDir); // Alte Vorschau l÷schen RemoveTrajectory(obj); // Neues Hilfsobjekt erzeugen var trajectory = CreateObject(TRTY, GetX(obj) - GetX(), GetY(obj) - GetY(), GetOwner(obj)); //Log("Trajectory: %d %d",GetX(trajectory),GetY(trajectory)); trajectory->AttachTo(obj); // Startwerte setzen var i = -1, xOld, yOld; var faktor = 100; x *= faktor; y *= faktor; yDir *= 5; xDir *= 5; y -= 4 * faktor; xOld = x; yOld = y; // Flugbahn simulieren while(++i < 500) { // Geschwindigkeit und Gravitation aufrechnen x += xDir; y += yDir + GetGravity() * i / 20; // Wenn wir weit genug weg sind fⁿr einen neuen Punkt diesen einfⁿgen if(Distance((xOld - x) / faktor, (yOld - y) / faktor) >= 10) { CreateParticle("Aimer", x / faktor - GetX(trajectory), y / faktor - GetY(trajectory), xDir / 500, yDir / 500, 10, color, trajectory); xOld = x; yOld = y; } // Oder ist es hier schon aus? if(GBackSolid(x / faktor - GetX(), y / faktor - GetY())) break; } // So, fertig return trajectory; } public func AttachTargetLost() { RemoveObject(); }
722,193
./clinfinity/Clinfinity.c4d/Helpers.c4d/Rule.c4d/Script.c
#strict 2 protected func Initialize() { ScheduleCall(this, "Initializing", 1); } private func Initializing() { var ruleTypeCount = ObjectCount2(Find_ID(GetID())); var others = FindObjects(Find_ID(GetID()), Find_Exclude(this)); for(var other in others) { other->RemoveObject(); } Initialized(ruleTypeCount); } private func Initialized(int ruleTypeCount) {}
722,194
./clinfinity/Clinfinity.c4d/Helpers.c4d/Damage.c4d/Script.c
/*-- Explosionsteuerung --*/ #strict 2 /* Dieses Objekt stellt die GrundfunktionalitΣt fⁿr GebΣudeexplosionen zur Verfⁿgung. */ static StructComp; local RepairComp; protected func Construction() { if(GetType(StructComp) != C4V_Array) StructComp = CreateHash(); if(!HashContains(StructComp, GetID())) { var ID = GetID(); var aIDs, aNum, iNum = 0; // IDs finden, aus denen das GebΣude zusammengesetzt ist aIDs = CreateArray(); for (var i = 0, component; component = GetComponent(0, i, 0, ID); ++i) { aIDs[i] = component; } aNum = CreateArray(GetLength(aIDs)); // Anzahl for (var i = 0; i < GetLength(aIDs); ++i) { aNum[i] = GetComponent(aIDs[i], 0, 0, ID); iNum += aNum[i]; } HashPut(StructComp, ID, [aIDs, aNum, iNum]); } RepairComp = CreateHash(); return _inherited(...); } public func Damage(int iChange) { UpdateDamageGraphic(); if(iChange <= 0) return; if (GetDamage() > MaxDamage()) DestroyBlast(); var ox, oy, wdt, hgt; GetRect(GetID(), ox, oy, wdt, hgt); var glascount = iChange + Random(4); for (var i = 0; i < glascount; ++i) { CastParticles("Glas", 1, RandomX(30,50), ox+Random(wdt), oy+Random(hgt), 20, 20); } var frazzlecount = GetDamage() * 5 / MaxDamage(); for (var i = 0; i < frazzlecount; ++i) { CastParticles("Fragment1", 1, RandomX(30,50), ox+Random(wdt), oy+Random(hgt), 20, 20); } // Important: This assumes that structures are not faded in any other way. RemoveEffect("Fade", this); FadeFromTo(RGB(255, 190, 190), RGB(255, 255, 255)); /* Components verlieren */ var aComponents = GetComponents(); var aIDs = aComponents[0], aNum = aComponents[1], iNum = aComponents[2]; var aNormal = HashGet(StructComp, GetID()); // wie viele Components mⁿssen entfernt werden? var iCompDiff = aNormal[2] - iNum; var iDamDiff = ChangeRange(GetDamage(), 0, MaxDamage(), 0, aNormal[2]); //Log("CompDiff: %d; DamDiff: %d; MaxDamage: %d; Normal: %d", iCompDiff, iDamDiff, MaxDamage(), aNormal[2]); iDamDiff -= iCompDiff; // Components zufΣllig entfernen for(var i = 0; iNum && i < iDamDiff; i++) { var c = Random(GetLength(aIDs)); if(aNum[c]) { SetComponent(aIDs[c], --aNum[c]); iNum--; //Log("Removed: %i", aIDs[c]); } else i--; // nochmal versuchen } } // overwrite this! public func DamageGraphics() { return 0; } local currentDamageGraphic; private func UpdateDamageGraphic() { var max = MaxDamage(); var dmg = Min(GetDamage(), max); var step = max / (DamageGraphics() + 1), n = 0; while((n + 1) * step < dmg) n++; if(n != currentDamageGraphic) { if(n) SetGraphics(Format("Damaged%d", n)); else SetGraphics(); currentDamageGraphic = n; } } private func DestroyBlast(object pTarget) { if(!pTarget) if(!(pTarget=this)) return; var ox, oy, wdt, hgt; GetRect(pTarget->GetID(), ox, oy, wdt, hgt); var count = GetComponent(METL, 0, 0, pTarget -> GetID()) + Random(GetComponent(WOOD, 0, 0, pTarget -> GetID())); var power = Sqrt(wdt ** 2 + hgt ** 2); pTarget->CastObjects(DEBR,count/2,power); for(var pObj in FindObjects(Find_Container(pTarget), Find_Not(Find_Func("IsLight")))) pObj -> Exit(0, Random(wdt) - wdt / 2, Random(hgt) - hgt / 2); pTarget -> Explode(power / 2); return true; } public func MaxDamage () { return 1; } //▄berlade mich! /* GebΣudereparatur */ public func GetMissingComponents() { // IDs + Anzahl finden, aus denen das GebΣude momentan zusammengesetzt ist var aComponents = GetComponents(); var aIDs = aComponents[0], aNum = aComponents[1], iNum = aComponents[2]; var aNormal = HashGet(StructComp, GetID()); var aNormalIDs = aNormal[0], aNormalNum = aNormal[1]; // Unterschiede feststellen var aDiffIDs = CreateArray(), aDiffNum = CreateArray(); for(var i = 0; i < GetLength(aNormalIDs); i++) { var ID = aNormalIDs[i]; var index = GetIndexOf(ID, aIDs); var iDiff = 0; if(index == -1) iDiff = aNormalNum[i]; else iDiff = aNormalNum[i] - aNum[index]; iDiff -= HashGet(RepairComp, ID); if(iDiff) { PushBack(ID, aDiffIDs); PushBack(iDiff, aDiffNum); } } // Unterschiede (IDs), (Menge), Anzahl der fehlenden Components (insgesamt) return [aDiffIDs, aDiffNum, aNormal[2] - iNum]; } public func DoRepairComponent(id ID, int num) { return HashPut(RepairComp, ID, HashGet(RepairComp, ID) + num); } public func Repair(int percent) { var iChange = Max(ChangeRange(percent, 0, 100, 0, MaxDamage()), 1); if(GetDamage() - iChange < 0) iChange = GetDamage(); // Werden zusΣtzlich Components gebraucht? // Nur, wenn Baumaterial aktiviert if(ObjectCount2(Find_ID(CNMT))) { // aktuelle Components var aComponents = GetComponents(); var aIDs = aComponents[0], aNum = aComponents[1], iNum = aComponents[2]; // ursprⁿnglich var aNormal = HashGet(StructComp, GetID()); var iCompDiff = aNormal[2] - iNum; var iDamDiff = ChangeRange(GetDamage() - iChange, 0, MaxDamage(), 0, aNormal[2]); //Log("CompDiff: %d; DamDiff: %d; MaxDamage: %d; Normal: %d", iCompDiff, iDamDiff, MaxDamage(), aNormal[2]); iDamDiff -= iCompDiff; // fehlen Components fⁿr die ─nderung? while(iDamDiff++ < 0) { // mal sehen was wir so alles da haben! var iter = HashIter(RepairComp); var node = HashIterNext(iter); // nichts da? Dann keine Reparatur. if(!node) return; if(!--node[1]) HashErase(RepairComp, node[0]); else HashPut(RepairComp, node[0], node[1]); SetComponent(node[0], GetComponent(node[0]) + 1); } } // success! DoDamage(-iChange); return 1; }
722,195
./clinfinity/Clinfinity.c4d/Helpers.c4d/StorageSystem.c4d/Script.c
/* Script: Storage System Library: Provides functionality for saving arbitrary integer values in a hash. It allows the definition of maximum fill levels, a sound to play when changing the fill level and overlaying numbers indicating the fill level. These options can be configured by overloading functions, see below. */ #strict 2 protected func Construction() { if(GetID() == L_SS) { DebugLog("ERROR: Dieses Objekt darf nicht erstellt werden"); RemoveObject(); } hFillLevel = CreateHash(); UpdatePicture(); return _inherited(...); } // Fⁿllstand local hFillLevel; // h wie Hash :x private func TypeCheck() { if(GetType(hFillLevel) != C4V_Array) hFillLevel = CreateHash(); } /* Fⁿllung */ /* Function: GetFill Parameters: Key - The hash key. Returns: A reference to the fill level. */ public func & GetFill(Key) { TypeCheck(); return HashGet(hFillLevel, Key); } /* Function: GetMaxFill Checks for the maximum fill by first calling MaxFill_[Key] and then, if that function does not exist or returns zero, the function MaxFill. These functions must be declared public. Parameters: Key - The hash key. Returns: The maximum fill for the given key or -1 if there is no maximum. */ public func GetMaxFill(Key) { var szFunc = "MaxFill", szFunc2, iFill; if(Key) { if(GetType(Key) == C4V_String) szFunc2 = Format("%s_%s", szFunc, Key); else szFunc2 = Format("%s_%v", szFunc, Key); } if(!(szFunc2 && (iFill = eval(Format("this->~%s()", szFunc2))))) iFill = Call(szFunc); return iFill; } /* Function: DoFill Changes the fill level, optionally playing the fill change sound. This function will check for the fill bounds: 0 is the fixed lower bound and GetMaxFill(Key) is the upper bound. Parameters: iChange - The fill level will be changed by adding this number. Key - The hash key. fNoSound - No sound will be played if this variable is true. Returns: The actual change of the fill level. */ public func DoFill(int iChange, Key, bool fNoSound) { // fixed minimum: 0 var iNewFill = Max(GetFill(Key) + iChange, 0); var maxFill = GetMaxFill(Key); // negative maxFill -> no maximum if(maxFill > 0) iNewFill = Min(iNewFill, maxFill); if (iNewFill == GetFill(Key)) return; iChange = iNewFill - GetFill(Key); OnFillChange(Key, iChange); if(!fNoSound) FillSound(Key, iChange); HashPut(hFillLevel, Key, iNewFill); UpdatePicture(); // TatsΣchliche ─nderung des Fⁿllstandes zurⁿckgeben return iChange; } /* Function: IsFull Parameters: Key - The hash key. Returns: Whether the fill level for the given key is full. */ public func IsFull(Key) { return GetFill(Key) == GetMaxFill(Key); } /* Function: UpdatePicture Updates the fill picture. This function is automatically called by DoFill, but you will need to call it when updating the fill level via GetFill's reference. Returns: true if the picture was successfully updated, false otherwise. */ public func UpdatePicture() { var Key = FillPicture(); if(Key == -1) return false; if(GetFill(Key)>99) { SetGraphics(0,0,GetNumberID(GetFill(Key) / 100),1,GFXOV_MODE_Picture); SetObjDrawTransform(400,0,-14000,0,400,+10000, this, 1); } else SetGraphics(0,0,0,1,0); if(GetFill(Key)>9) { SetGraphics(0,0,GetNumberID(GetFill(Key) / 10 - GetFill(Key) / 100 * 10),2,GFXOV_MODE_Picture); SetObjDrawTransform(400,0,-7000,0,400,+10000, this, 2); } else SetGraphics(0,0,0,2,0); SetGraphics(0,0,GetNumberID(GetFill(Key) % 10),3,GFXOV_MODE_Picture); SetObjDrawTransform(400,0,0,0,400,+10000, this, 3); return true; } /* ID des passenden Zahlobjektes ausgeben */ private func GetNumberID(i) { return(C4Id(Format("SNB%d", i))); } /* Bei Bedarf ⁿberladen */ /* Function: FillPicture This function needs to be overwritten to use the fill level indicator. Returns: The hash key for the fill level to show or -1 (default) if there should not be an indicator. */ private func FillPicture() { return -1; } /* Function: FillSound This function will be called to play a fill sound. It doesn't do anything as default action. When overriding, the function shouldn't do anything but calling Sound(). Parameters: Key - The hash key. iChange - The amount by which the fill level was changed. */ private func FillSound(Key, int iChange) { return; } /* Function: OnFillChange This function will be called whenever any fill level changes. It doesn't do anything as default action. Parameters: Key - The hash key. iChange - The amount by which the fill level was changed. */ private func OnFillChange(Key, int iChange) { return; }
722,196
./clinfinity/Clinfinity.c4d/Helpers.c4d/PlayerMaterial.c4d/Script.c
/*-- Spielermaterialien --*/ #strict 2 #include L_SS private func MaxFill() { return -1; } static aMaterialSystem; local hIcons; // HashGet(GetMatSys()->LocalN("hIcons"), WOOD) public func Initialize() { if(GetType(aMaterialSystem) != C4V_Array) aMaterialSystem = CreateArray(GetPlayerCount()); aMaterialSystem[GetOwner()] = this; var aIDs = GetMatSysIDs(); var iX = -166, pIcon; hIcons = CreateHash(); for(var idObj in aIDs) { pIcon = CreateObject(LPMI, 0, 0, GetOwner()); pIcon -> SetPosition(iX); pIcon -> Set(idObj); HashPut(hIcons, idObj, pIcon); iX -= 40; } } public func OnFillChange(Key, &iChange, bool dontNotify) { // notify other team member's MatSys var owner = GetOwner(); if(!dontNotify) { for(var count = GetPlayerCount(), i = 0; i < count; i++) { var p = GetPlayerByIndex(i); if(p != owner && !Hostile(p, owner)) GetMatSys(p)->OnFillChange(Key, iChange, true); } } // add to the score DoScore(owner, iChange * GetValue(0, Key)); // highlight change HashGet(hIcons, Key)->Flash(iChange); return 1; } public func DoFill(int change, id ID, bool noUpdate) { if(!noUpdate) change = UpdateFillEffects(ID, change); return inherited(change, ID); } // checks for global effects defining the fill level // these effects must define a function FxMatSys<ID>Update private func UpdateFill(id ID) { var effectName = Format("MatSys%i", ID), i = GetEffectCount(effectName); if(i > 0) { var fill = 0; while(i--) fill += EffectCall(0, GetEffect(effectName, 0, i), "Update", GetOwner()); // prevent looping DoFill(fill - GetFill(ID), ID, true); return true; } return false; } // changes the actual fill if defined by effects private func UpdateFillEffects(id ID, int change) { var effectName = Format("MatSys%i", ID), i = GetEffectCount(effectName); if(i > 0) { var original = change; while(i-- && change != 0) change -= EffectCall(0, GetEffect(effectName, 0, i), "Change", GetOwner(), change); return original - change; } return change; } local fNoStatusMessage; public func Timer() { if(fNoStatusMessage) return; var owner = GetOwner(); var iter = HashIter(hIcons), node; while(node = HashIterNext(iter)) { UpdateFill(node[0]); var fill = MatSysGetTeamFill(owner, node[0]); node[1] -> SetStatusMessage(Format("@%d", fill)); } } public func MaterialCheck(id idType) { fNoStatusMessage = 1; var owner = GetOwner(); var iter = HashIter(hIcons), node; while(node = HashIterNext(iter)) { var fill = MatSysGetTeamFill(owner, node[0]); node[1] -> BuildMessage(GetComponent(node[0], 0, 0, idType), fill); } } public func ClearMaterialCheck() { fNoStatusMessage = 0; }
722,197
./clinfinity/Clinfinity.c4d/Helpers.c4d/PlayerMaterial.c4d/InfoIcon.c4d/Script.c
/* Script: Informationicon MatSys HUD display: Shows the contents of a specific material. */ #strict 2 static MatSys_FlashEasing; func Initialize() { SetVisibility(VIS_Owner); if(!MatSys_FlashEasing) MatSys_FlashEasing = CreateEaseFunction("circle-in-out", 255); return 1; } /* Function: Set Sets the shown object. Parameters: idObj - The object's id. */ public func Set(id idObj) { // draw the overlay twice SetGraphics(0, this, idObj, GFX_Overlay, GFXOV_MODE_IngamePicture); AdjustGraphic(idObj, GFX_Overlay); SetGraphics(0, this, idObj, 2, GFXOV_MODE_IngamePicture); AdjustGraphic(idObj, 2); } private func AdjustGraphic(id idObj, int overlay) { var iWidth = 566, iHeight = 566, iXAdjust = 28000, iYAdjust = 13000; if(idObj != LHBK && idObj != LHTL) { iXAdjust *= 2; iXAdjust += 3000; iYAdjust *= 2; iWidth += 150; iHeight += 34; } SetObjDrawTransform(iWidth, 0, iXAdjust, 0, iHeight, iYAdjust, 0, overlay); } /* Function: SetStatusMessage Creates the text below the symbol. Paramters: msg - The message to show. lines - The number of lines the message has. */ public func SetStatusMessage(string msg, int lines) { CustomMessage(msg, this, GetOwner(), 30, 60 + lines * 125 / 10); // jede Zeile hat 12,5px } /* Function: BuildMessage Creates a message showing how much of this material is needed. Parameters: iNeededMaterial - How much material is needed. iMaterial - How much material is actually there. */ public func BuildMessage(int iNeededMaterial, int iMaterial) { var szMessage = Format("@%d|<c ", iMaterial); if(iNeededMaterial > iMaterial) Add(szMessage, "ff0000"); else Add(szMessage, "00ff00"); Add(szMessage, Format(">%d</c>", iNeededMaterial)); SetStatusMessage(szMessage, 2); return 1; } private func Add(string &szString1, string szString2) { return szString1 = Format("%s%s", szString1, szString2); } /* Function: Flash Flashes the material graphic red or green to indicate a change in storage amount. Paramters: change - How much the storage has changed. Negative -> red flash; positive -> green flash. */ public func Flash(int change) { // remove previous effect if there is one RemoveEffect("Flash", this); AddEffect("Flash", this, 1, 2, this, 0, change); } static const MatSys_FlashDuration = 20; protected func FxFlashStart(object target, int effectNum, int temp, int change) { if(temp) return; EffectVar(0, target, effectNum) = change; } protected func FxFlashTimer(object target, int effectNum, int effectTime) { if(effectTime > MatSys_FlashDuration) { // reset modulation SetClrModulation(RGB(255, 255, 255), this, 2); return -1; } var color, alpha = EvalEase(MatSys_FlashEasing, 255 * effectTime / MatSys_FlashDuration); if(EffectVar(0, target, effectNum) < 0) color = RGBa(255, 0, 0, alpha); else color = RGBa(0, 255, 0, alpha); SetClrModulation(color, this, 2); }
722,198
./clinfinity/Clinfinity.c4d/Helpers.c4d/DeathAnnounce.c4d/Script.c
/* Script: DeathAnnounce Handles improved death messages. */ #strict 2 static const DANN_Duration = 350; local message, posEase, alphaEase, messageColor; /* Function: Announce Announces the death of the given Clonk. Parameters: clonk - the clonk to announce death for */ public func Announce(object clonk) { var messages = ["$DeathMsg1$", "$DeathMsg2$", "$DeathMsg3$", "$DeathMsg4$", "$DeathMsg5$", "$DeathMsg6$", "$DeathMsg7$"]; message = clonk->LocalN("deathMessage"); if(!GetLength(message)) message = Format(messages[Random(7)], clonk->LocalN("name")); posEase = CreateEaseFunction("cubic-in-out", DANN_Duration); alphaEase = CreateEaseFunction("quad-in-out", DANN_Duration); messageColor = Desaturate(clonk->GetColorDw()); AddEffect("Fade", this, 1, 1, this); // Point to the death PointOut(messageColor, Format("å %s", GetPlayerName(clonk->GetOwner()))); } /* Function: DeathAnnounce Overwrites the global engine-defined function to provide the custom message. */ global func DeathAnnounce() { CreateObject(DANN)->Announce(this); return true; } private func Desaturate(int color) { var hsl = RGB2HSL(color); var hue, sat, light, alpha; SplitRGBaValue(hsl, hue, sat, light, alpha); return HSL(hue, sat / 4, light); } func FxFadeTimer(object target, int effectNum, int effectTime) { var color = SetRGBaValue(messageColor, ChangeRange(EvalEase(alphaEase, effectTime), 0, DANN_Duration, 0, 255)); CustomMessage(message, this, NO_OWNER, 0, -EvalEase(posEase, effectTime), color); if(effectTime > DANN_Duration) RemoveObject(); }
722,199
./clinfinity/Clinfinity.c4d/Helpers.c4d/ControlPoint.c4d/Script.c
/* Script: Control Point Library: Provides functionality for TF2-style control points. - Initially, the point doesn't have an owner. - The first clonk entering its capture zone (as defined by _CaptureZone()_) will start a capture for his team. - Enemy clonks entering the zone will block the capture progress. - If the enemy clonks defeat the initial capturers, they will revert the capture, then starting to capture for their team. - A successful capture will change the owner to a player of the capturing team. - Reverting capture time isn't possible for the owning team. - Capture time will decrease slowly while there is no capturing clonk on point. */ #strict 2 /* Function: SetupTime Should be overwritten. Returns: The time in frames a before the control point is available for capture. */ public func SetupTime() { return 1; } /* Function: CaptureTime Should be overwritten. Returns: The time in frames a single clonk needs to capture the point. */ public func CaptureTime() { return 200; } /* Function: CaptureZone Should be overwritten. Returns: FindObject2-criteria which define the capture zone. Defaults to the object's shape. */ public func CaptureZone() { var x = GetDefOffset(GetID(), 0), y = GetDefOffset(GetID(), 1), wdt = GetDefWidth(GetID()), hgt = GetDefHeight(GetID()); return Find_InRect(x, y, wdt, hgt); } // the timer interval static const CP_Interval = 5; // a player of the capturing team local capturingPlayer; // the current capture time local captureTime; // the wait time before the capture time starts decreasing local wait; // are we in overtime? local overtime; protected func Completion() { ScheduleCall(this, "EnablePoint", SetupTime()); capturingPlayer = NO_OWNER; captureTime = 0; overtime = false; return _inherited(...); } /* Function: EnablePoint Enables the control point, making it available for capture. This function will automatically be called after the point is created and <SetupTime>() frames have passed. */ public func EnablePoint() { if(!GetEffect("ControlPoint", this)) { AddEffect("ControlPoint", this, 1, CP_Interval, this); return true; } } /* Function: DisablePoint Disables the control point, freezing all current capture operations. A disabled point can be re-enabled using <EnablePoint>. */ public func DisablePoint() { RemoveEffect("ControlPoint", this); return true; } protected func FxControlPointTimer(object target, int effectNum, int effectTime) { var clonks = FindObjects(Find_OCF(OCF_CrewMember), CaptureZone()); var owner = GetOwner(); var capturingClonks = 0; var defendingClonks = 0; for(var clonk in clonks) { var plr = clonk->GetOwner(); if(capturingPlayer == NO_OWNER) { if(owner == NO_OWNER || Hostile(plr, owner)) { capturingPlayer = plr; capturingClonks++; } } else if(Hostile(capturingPlayer, plr)) { defendingClonks++; } else { capturingClonks++; } } UpdateCaptureTime(capturingClonks, defendingClonks); CheckCapture(); } /* Function: UpdateCaptureTime Updates the capture time according to the number of capturing clonks and the number of defending clonks. Parameters: capturing - the number of capturing clonks defending - the number of defending clonks */ public func UpdateCaptureTime(int capturing, int defending) { var prev = captureTime; if(capturing) { if(defending) { // don't do anything return; } // callback when capture is just starting if(captureTime == 0) CaptureStarting(); // increase capture time captureTime += CP_Interval * capturing; wait = 20; } else if(defending && GetOwner() == NO_OWNER) { // decrease capture time captureTime -= CP_Interval * defending; } else if(overtime) { // overtime! Decrease faster: 150 frames to finish captureTime -= CaptureTime() * CP_Interval / 150; } else { // nobody there if(wait-- < 0) captureTime -= CP_Interval / 2; } if(captureTime <= 0) { captureTime = 0; if(prev) CaptureEnding(); } } /* Function: CheckCapture Checks whether the point has been captures and updates its owner and the capture time accordingly. Returns: _true_ if the point has been captured. */ public func CheckCapture() { if(captureTime > CaptureTime()) { SetOwner(capturingPlayer); capturingPlayer = NO_OWNER; captureTime = 0; overtime = false; Captured(); return true; } else { if(captureTime == 0) capturingPlayer = NO_OWNER; return false; } } /* Function: SetOvertime Enables or disables overtime mode. In overtime, capture progress decreases much faster if nobody is on point. Parameters: val - _true_ to enable overtime mode */ public func SetOvertime(bool val) { if(val && !overtime) OvertimeStarting(); overtime = val; } /* Function: IsControlPoint This is a control point. Returns: _true_ */ public func IsControlPoint() { return true; } /* Function: GetCapturingPlayer Returns: The capturing player or NO_OWNER if nobody is capturing. */ public func GetCapturingPlayer() { return capturingPlayer; } /* Function: GetCapturePercentage Returns: The current capture progress in percent. */ public func GetCapturePercentage() { return Min(100, 100 * captureTime / CaptureTime()); } /* Function: CaptureStarting Called when someone starts capping the point. */ private func CaptureStarting() { Sound("koth_startcapture"); Sound("koth_capturing", 0, 0, 0, 0, 1); } /* Function: Captured Called when the point is captured, will output a message to the log and play a sound. */ private func Captured() { var team = GetPlayerTeam(GetOwner()); Log("<c %x>$Capture$</c>", GetTeamColor(team), GetTeamName(team), GetName()); PointOut(GetPlrColorDw(GetOwner())); Sound("koth_captured"); Sound("koth_sign", true); Sound("koth_capturing", 0, 0, 0, 0, -1); } /* Function: CaptureEnding Called when the point's capture time runs out. */ private func CaptureEnding() { Sound("koth_captured"); Sound("koth_capturing", 0, 0, 0, 0, -1); } /* Function: OvertimeStarting Called when the point switches to overtime, will output a message to the log. */ private func OvertimeStarting() { var team = GetPlayerTeam(GetOwner()); Log("<c %x>$Overtime$</c>", GetTeamColor(team)); PointOut(GetColorDw()); Sound("koth_overtime"); }
722,200
./clinfinity/Clinfinity.c4d/Helpers.c4d/Pointer.c4d/Script.c
/* Script: Pointer Provides a pointer highlighting an object for a player. */ #strict 2 static const PT0D_Distance = 200; static const PT0D_Duration = 255; local alphaEase; func Initialize() { SetVisibility(VIS_None, this); alphaEase = CreateEaseFunction("circle-out", PT0D_Duration); return true; } /* Constructor: CreatePointer Creates a pointer. Parameters: plr - The player who will see the pointer. target - The object the pointer will point at. color - Pointer's color modulation. message - A message shown above the pointer. Returns: The created pointer. */ global func CreatePointer(int plr, object target, int color, string message) { if(!target) return false; if(!color) color = GetPlrColorDw(plr); if(!message) message = ""; var pointer = CreateObject(PT0D, 0, 0, plr); pointer->SetClrModulation(color); AddEffect("Pointing", pointer, 100, 1, pointer, 0, plr, target, message); return pointer; } /* Function: PointOut Creates a pointer for every player pointing to the calling object. Parameters: color - Pointer's color modulation. message - A message shown above the pointer. */ global func PointOut(int color, string message) { for(var count = GetPlayerCount(), i = 0; i < count; i++) { var p = GetPlayerByIndex(i); CreatePointer(p, this, color, message); } return count; } func FxPointingStart(object target, int index, int temp, int plr, object obj, string msg) { SetVisibility(VIS_Owner, target); CreateParticle("PSpark", 0, 0, 0, 0, 500, GetClrModulation(), this, true); EffectVar(0, target, index) = plr; EffectVar(1, target, index) = obj; EffectVar(2, target, index) = msg; return true; } func FxPointingTimer(object target, int index, int time) { if(time > PT0D_Duration) { RemoveObject(target); return -1; } var clonk = GetCursor(EffectVar(0, target, index)); var obj = EffectVar(1, target, index); var msg = EffectVar(2, target, index); // Zeiger hat kein Ziel mehr? L÷schen. if(!obj) { RemoveObject(target); return -1; } var ang = Angle(GetX(clonk), GetY(clonk), GetX(obj), GetY(obj)) - 90; var dst = Min(PT0D_Distance, Distance(GetX(clonk), GetY(clonk), GetX(obj), GetY(obj)) / 2); SetR(ang + 90, target); SetPosition(GetX(clonk) + Cos(ang, dst), GetY(clonk) + Sin(ang, dst), target); var r, g, b, a; SplitRGBaValue(GetClrModulation(target), r, g, b, a); a = EvalEase(alphaEase, Min(254, time)); SetClrModulation(RGBa(r, g, b, a), target); Message("<c %x>%s</c>", target, RGBa(r, g, b, 255 - a), msg); return true; }