id
int64
1
722k
file_path
stringlengths
8
177
funcs
stringlengths
1
35.8M
501
./exodriver/examples/U6/u6Stream.c
//Author: LabJack //April 5, 2011 //This example program reads analog inputs AI0-AI4 using stream mode. #include "u6.h" int ConfigIO_example(HANDLE hDevice); int StreamConfig_example(HANDLE hDevice); int StreamStart(HANDLE hDevice); int StreamData_example(HANDLE hDevice, u6CalibrationInfo *caliInfo); int StreamStop(HANDLE hDevice); const uint8 NumChannels = 5; //For this example to work proper, SamplesPerPacket needs //to be a multiple of NumChannels. const uint8 SamplesPerPacket = 25; //Needs to be 25 to read multiple StreamData responses //in one large packet, otherwise can be any value between //1-25 for 1 StreamData response per packet. int main(int argc, char **argv) { HANDLE hDevice; u6CalibrationInfo caliInfo; //Opening first found U6 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U6 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( ConfigIO_example(hDevice) != 0 ) goto close; //Stopping any previous streams StreamStop(hDevice); if( StreamConfig_example(hDevice) != 0 ) goto close; if( StreamStart(hDevice) != 0 ) goto close; StreamData_example(hDevice, &caliInfo); StreamStop(hDevice); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ConfigIO low-level command to turn off timers/counters int ConfigIO_example(HANDLE hDevice) { uint8 sendBuff[16], recBuff[16]; uint16 checksumTotal; int sendChars, recChars, i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 1; //Writemask : Setting writemask for TimerCounterConfig (bit 0) sendBuff[7] = 0; //NumberTimersEnabled : Setting to zero to disable all timers. sendBuff[8] = 0; //CounterEnable: Setting bit 0 and bit 1 to zero to disable both counters sendBuff[9] = 0; //TimerCounterPinOffset for( i = 10; i < 16; i++ ) sendBuff[i] = 0; //Reserved extendedChecksum(sendBuff, 16); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 16)) < 16 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 16)) < 16 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 15); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LSB)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x05) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[8] != 0 ) { printf("ConfigIO error : NumberTimersEnabled was not set to 0\n"); return -1; } if( recBuff[9] != 0 ) { printf("ConfigIO error : CounterEnable was not set to 0\n"); return -1; } return 0; } //Sends a StreamConfig low-level command to configure the stream. int StreamConfig_example(HANDLE hDevice) { int sendBuffSize; sendBuffSize = 14+NumChannels*2; uint8 sendBuff[sendBuffSize], recBuff[8]; int sendChars, recChars; uint16 checksumTotal; uint16 scanInterval; int i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 4 + NumChannels; //Number of data words = NumChannels + 4 sendBuff[3] = (uint8)(0x11); //Extended command number sendBuff[6] = NumChannels; //NumChannels sendBuff[7] = 1; //ResolutionIndex sendBuff[8] = SamplesPerPacket; //SamplesPerPacket sendBuff[9] = 0; //Reserved sendBuff[10] = 0; //SettlingFactor: 0 sendBuff[11] = 0; //ScanConfig: // Bit 3: Internal stream clock frequency = b0: 4 MHz // Bit 1: Divide Clock by 256 = b0 scanInterval = 4000; sendBuff[12] = (uint8)(scanInterval&(0x00FF)); //scan interval (low byte) sendBuff[13] = (uint8)(scanInterval/256); //scan interval (high byte) for( i = 0; i < NumChannels; i++ ) { sendBuff[14 + i*2] = i; //ChannelNumber (Positive) = i sendBuff[15 + i*2] = 0; //ChannelOptions: // Bit 7: Differential = 0 // Bit 5-4: GainIndex = 0 (+-10V) } extendedChecksum(sendBuff, sendBuffSize); //Sending command to U6 sendChars = LJUSB_Write(hDevice, sendBuff, sendBuffSize); if( sendChars < sendBuffSize ) { if( sendChars == 0 ) printf("Error : write failed (StreamConfig).\n"); else printf("Error : did not write all of the buffer (StreamConfig).\n"); return -1; } for( i = 0; i < 8; i++ ) recBuff[i] = 0; //Reading response from U6 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) printf("Error : read failed (StreamConfig).\n"); else printf("Error : did not read all of the buffer, %d (StreamConfig).\n", recChars); for( i = 0; i < 8; i++) printf("%d ", recBuff[i]); return -1; } checksumTotal = extendedChecksum16(recBuff, 8); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5]) { printf("Error : read buffer has bad checksum16(MSB) (StreamConfig).\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Error : read buffer has bad checksum16(LSB) (StreamConfig).\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamConfig).\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x01) || recBuff[3] != (uint8)(0x11) || recBuff[7] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes (StreamConfig).\n"); return -1; } if( recBuff[6] != 0 ) { printf("Errorcode # %d from StreamConfig read.\n", (unsigned int)recBuff[6]); return -1; } return 0; } //Sends a StreamStart low-level command to start streaming. int StreamStart(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xA8); //Checksum8 sendBuff[1] = (uint8)(0xA8); //Command byte //Sending command to U6 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed.\n"); else printf("Error : did not write all of the buffer.\n"); return -1; } //Reading response from U6 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed.\n"); else printf("Error : did not read all of the buffer.\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStart).\n"); return -1; } if( recBuff[1] != (uint8)(0xA9) || recBuff[3] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStart read.\n", (unsigned int)recBuff[2]); return -1; } return 0; } //Reads the StreamData low-level function response in a loop. //All voltages from the stream are stored in the voltages 2D array. int StreamData_example(HANDLE hDevice, u6CalibrationInfo *caliInfo) { int recBuffSize; recBuffSize = 14 + SamplesPerPacket*2; int recChars, backLog; int i, j, k, m, packetCounter, currChannel, scanNumber; int totalPackets; //The total number of StreamData responses read uint16 voltageBytes, checksumTotal; long startTime, endTime; int autoRecoveryOn; int numDisplay; //Number of times to display streaming information int numReadsPerDisplay; //Number of packets to read before displaying streaming information int readSizeMultiplier; //Multiplier for the StreamData receive buffer size int responseSize; //The number of bytes in a StreamData response (differs with SamplesPerPacket) numDisplay = 6; numReadsPerDisplay = 24; readSizeMultiplier = 5; responseSize = 14 + SamplesPerPacket*2; /* Each StreamData response contains (SamplesPerPacket / NumChannels) * readSizeMultiplier * samples for each channel. * Total number of scans = (SamplesPerPacket / NumChannels) * readSizeMultiplier * numReadsPerDisplay * numDisplay */ double voltages[(SamplesPerPacket/NumChannels)*readSizeMultiplier*numReadsPerDisplay*numDisplay][NumChannels]; uint8 recBuff[responseSize*readSizeMultiplier]; packetCounter = 0; currChannel = 0; scanNumber = 0; totalPackets = 0; recChars = 0; autoRecoveryOn = 0; printf("Reading Samples...\n"); startTime = getTickCount(); for( i = 0; i < numDisplay; i++ ) { for( j = 0; j < numReadsPerDisplay; j++ ) { /* For USB StreamData, use Endpoint 3 for reads. You can read the multiple * StreamData responses of 64 bytes only if SamplesPerPacket is 25 to help * improve streaming performance. In this example this multiple is adjusted * by the readSizeMultiplier variable. */ //Reading stream response from U6 recChars = LJUSB_Stream(hDevice, recBuff, responseSize*readSizeMultiplier); if( recChars < responseSize*readSizeMultiplier ) { if(recChars == 0) printf("Error : read failed (StreamData).\n"); else printf("Error : did not read all of the buffer, expected %d bytes but received %d(StreamData).\n", responseSize*readSizeMultiplier, recChars); return -1; } //Checking for errors and getting data out of each StreamData response for( m = 0; m < readSizeMultiplier; m++ ) { totalPackets++; checksumTotal = extendedChecksum16(recBuff + m*recBuffSize, recBuffSize); if( (uint8)((checksumTotal >> 8) & 0xff) != recBuff[m*recBuffSize + 5] ) { printf("Error : read buffer has bad checksum16(MSB) (StreamData).\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[m*recBuffSize + 4] ) { printf("Error : read buffer has bad checksum16(LSB) (StreamData).\n"); return -1; } checksumTotal = extendedChecksum8(recBuff + m*recBuffSize); if( checksumTotal != recBuff[m*recBuffSize] ) { printf("Error : read buffer has bad checksum8 (StreamData).\n"); return -1; } if( recBuff[m*recBuffSize + 1] != (uint8)(0xF9) || recBuff[m*recBuffSize + 2] != 4 + SamplesPerPacket || recBuff[m*recBuffSize + 3] != (uint8)(0xC0) ) { printf("Error : read buffer has wrong command bytes (StreamData).\n"); return -1; } if( recBuff[m*recBuffSize + 11] == 59 ) { if( !autoRecoveryOn ) { printf("\nU6 data buffer overflow detected in packet %d.\nNow using auto-recovery and reading buffered samples.\n", totalPackets); autoRecoveryOn = 1; } } else if( recBuff[m*recBuffSize + 11] == 60 ) { printf("Auto-recovery report in packet %d: %d scans were dropped.\nAuto-recovery is now off.\n", totalPackets, recBuff[m*recBuffSize + 6] + recBuff[m*recBuffSize + 7]*256); autoRecoveryOn = 0; } else if( recBuff[m*recBuffSize + 11] != 0 ) { printf("Errorcode # %d from StreamData read.\n", (unsigned int)recBuff[11]); return -1; } if( packetCounter != (int)recBuff[m*recBuffSize + 10] ) { printf("PacketCounter (%d) does not match with with current packet count (%d)(StreamData).\n", recBuff[m*recBuffSize + 10], packetCounter); return -1; } backLog = (int)recBuff[m*48 + 12 + SamplesPerPacket*2]; for( k = 12; k < (12 + SamplesPerPacket*2); k += 2 ) { voltageBytes = (uint16)recBuff[m*recBuffSize + k] + (uint16)recBuff[m*recBuffSize + k+1]*256; getAinVoltCalibrated(caliInfo, 1, 0, 0, voltageBytes, &(voltages[scanNumber][currChannel])); currChannel++; if( currChannel >= NumChannels ) { currChannel = 0; scanNumber++; } } if(packetCounter >= 255) packetCounter = 0; else packetCounter++; } } printf("\nNumber of scans: %d\n", scanNumber); printf("Total packets read: %d\n", totalPackets); printf("Current PacketCounter: %d\n", ((packetCounter == 0) ? 255 : packetCounter-1)); printf("Current BackLog: %d\n", backLog); for( k = 0; k < NumChannels; k++ ) printf(" AI%d: %.4f V\n", k, voltages[scanNumber - 1][k]); } endTime = getTickCount(); printf("\nRate of samples: %.0lf samples per second\n", (scanNumber*NumChannels)/((endTime - startTime)/1000.0)); printf("Rate of scans: %.0lf scans per second\n\n", scanNumber/((endTime - startTime)/1000.0)); return 0; } //Sends a StreamStop low-level command to stop streaming. int StreamStop(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xB0); //Checksum8 sendBuff[1] = (uint8)(0xB0); //Command byte //Sending command to U6 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed (StreamStop).\n"); else printf("Error : did not write all of the buffer (StreamStop).\n"); return -1; } //Reading response from U6 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed (StreamStop).\n"); else printf("Error : did not read all of the buffer (StreamStop).\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStop).\n"); return -1; } if( recBuff[1] != (uint8)(0xB1) || recBuff[3] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes (StreamStop).\n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStop read.\n", (unsigned int)recBuff[2]); return -1; } /* //Reading left over data in stream endpoint. Only needs to be done with firmwares //less than 0.94. uint8 recBuffS[64]; int recCharsS = 64; printf("Reading left over data from stream endpoint.\n"); while( recCharsS > 0 ) recCharsS = LJUSB_Stream(hDevice, recBuffS, 64); */ return 0; }
502
./exodriver/examples/U6/u6BasicConfigU6.c
/* An example that shows a minimal use of Exodriver without the use of functions hidden in header files. You can compile this example with the following command: $ g++ -lm -llabjackusb u6BasicConfigU6.c It is also included in the Makefile. */ /* Includes */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "labjackusb.h" // Defines how long the command is #define CONFIGU6_COMMAND_LENGTH 26 // Defines how long the response is #define CONFIGU6_RESPONSE_LENGTH 38 /* Buffer Helper Functions Protypes */ // Takes a buffer and an offset, and turns it into a 32-bit integer int makeInt(BYTE * buffer, int offset); // Takes a buffer and an offset, and turns it into a 16-bit integer int makeShort(BYTE * buffer, int offset); // Takes a buffer and calculates the checksum8 of it. BYTE calculateChecksum8(BYTE* buffer); // Takes a buffer and length, and calculates the checksum16 of the buffer. int calculateChecksum16(BYTE* buffer, int len); /* LabJack Related Helper Functions Protoypes */ // Demonstrates how to build the ConfigU6 packet. void buildConfigU6Bytes(BYTE * sendBuffer); // Demonstrates how to check a response for errors. int checkResponseForErrors(BYTE * recBuffer); // Demonstrates how to parse the response of ConfigU6. void parseConfigU6Bytes(BYTE * recBuffer); int main() { // Setup the variables we will need. int r = 0; // For checking return values HANDLE devHandle = 0; BYTE sendBuffer[CONFIGU6_COMMAND_LENGTH], recBuffer[CONFIGU6_RESPONSE_LENGTH]; // Open the U6 devHandle = LJUSB_OpenDevice(1, 0, U6_PRODUCT_ID); if( devHandle == NULL ) { printf("Couldn't open U6. Please connect one and try again.\n"); exit(-1); } // Builds the ConfigU6 command buildConfigU6Bytes(sendBuffer); // Write the command to the device. // LJUSB_Write( handle, sendBuffer, length of sendBuffer ) r = LJUSB_Write( devHandle, sendBuffer, CONFIGU6_COMMAND_LENGTH ); if( r != CONFIGU6_COMMAND_LENGTH ) { printf("An error occurred when trying to write the buffer. The error was: %d\n", errno); // *Always* close the device when you error out. LJUSB_CloseDevice(devHandle); exit(-1); } // Read the result from the device. // LJUSB_Read( handle, recBuffer, number of bytes to read) r = LJUSB_Read( devHandle, recBuffer, CONFIGU6_RESPONSE_LENGTH ); if( r != CONFIGU6_RESPONSE_LENGTH ) { printf("An error occurred when trying to read from the U6. The error was: %d\n", errno); LJUSB_CloseDevice(devHandle); exit(-1); } // Check the command for errors if( checkResponseForErrors(recBuffer) != 0 ){ LJUSB_CloseDevice(devHandle); exit(-1); } // Parse the response into something useful parseConfigU6Bytes(recBuffer); //Close the device. LJUSB_CloseDevice(devHandle); return 0; } /* ------------- LabJack Related Helper Functions Definitions ------------- */ // Uses information from section 5.2.2 of the U6 User's Guide to make a ConfigU6 // packet. // http://labjack.com/support/u6/users-guide/5.2.2 void buildConfigU6Bytes(BYTE * sendBuffer) { int i; // For loops int checksum = 0; // Build up the bytes //sendBuffer[0] = Checksum8 sendBuffer[1] = 0xF8; sendBuffer[2] = 0x0A; sendBuffer[3] = 0x08; //sendBuffer[4] = Checksum16 (LSB) //sendBuffer[5] = Checksum16 (MSB) // We just want to read, so we set the WriteMask to zero, and zero out the // rest of the bytes. sendBuffer[6] = 0; for( i = 7; i < CONFIGU6_COMMAND_LENGTH; i++){ sendBuffer[i] = 0; } // Calculate and set the checksum16 checksum = calculateChecksum16(sendBuffer, CONFIGU6_COMMAND_LENGTH); sendBuffer[4] = (BYTE)( checksum & 0xff ); sendBuffer[5] = (BYTE)( (checksum / 256) & 0xff ); // Calculate and set the checksum8 sendBuffer[0] = calculateChecksum8(sendBuffer); // The bytes have been set, and the checksum calculated. We are ready to // write to the U6. } // Checks the response for any errors. int checkResponseForErrors(BYTE * recBuffer) { if(recBuffer[0] == 0xB8 && recBuffer[1] == 0xB8) { // If the packet is [ 0xB8, 0xB8 ], that's a bad checksum. printf("The U6 detected a bad checksum. Double check your checksum calculations and try again.\n"); return -1; } else if (recBuffer[1] == 0xF8 && recBuffer[2] == 0x10 && recBuffer[2] == 0x08) { // Make sure the command bytes match what we expect. printf("Got the wrong command bytes back from the U6.\n"); return -1; } // Calculate the checksums. int checksum16 = calculateChecksum16(recBuffer, CONFIGU6_RESPONSE_LENGTH); BYTE checksum8 = calculateChecksum8(recBuffer); if ( checksum8 != recBuffer[0] || recBuffer[4] != (BYTE)( checksum16 & 0xff ) || recBuffer[5] != (BYTE)( (checksum16 / 256) & 0xff ) ) { // Check the checksum printf("Response had invalid checksum.\n%d != %d, %d != %d, %d != %d\n", checksum8, recBuffer[0], (BYTE)( checksum16 & 0xff ), recBuffer[4], (BYTE)( (checksum16 / 256) & 0xff ), recBuffer[5] ); return -1; } else if ( recBuffer[6] != 0 ) { // Check the error code in the packet. See section 5.3 of the U6 // User's Guide for errorcode descriptions. printf("Command returned with an errorcode = %d\n", recBuffer[6]); return -1; } return 0; } // Parses the ConfigU6 packet into something useful. void parseConfigU6Bytes(BYTE * recBuffer){ printf("Results of ConfigU6:\n"); printf(" FirmwareVersion = %d.%02d\n", recBuffer[10], recBuffer[9]); printf(" BootloaderVersion = %d.%02d\n", recBuffer[12], recBuffer[11]); printf(" HardwareVersion = %d.%02d\n", recBuffer[14], recBuffer[13]); printf(" SerialNumber = %d\n", makeInt(recBuffer, 15)); printf(" ProductID = %d\n", makeShort(recBuffer, 19)); printf(" LocalID = %d\n", recBuffer[21]); printf(" VersionInfo = %d\n", recBuffer[37]); if( recBuffer[37] == 4 ){ printf(" DeviceName = U6\n"); } else if(recBuffer[37] == 12) { printf(" DeviceName = U6-Pro\n"); } } /* ---------------- Buffer Helper Functions Definitions ---------------- */ // Takes a buffer and an offset, and turns into an 32-bit integer int makeInt(BYTE * buffer, int offset){ return (buffer[offset+3] << 24) + (buffer[offset+2] << 16) + (buffer[offset+1] << 8) + buffer[offset]; } // Takes a buffer and an offset, and turns into an 16-bit integer int makeShort(BYTE * buffer, int offset) { return (buffer[offset+1] << 8) + buffer[offset]; } // Calculates the checksum8 BYTE calculateChecksum8(BYTE* buffer){ int i; // For loops int temp; // For holding a value while we working. int checksum = 0; for( i = 1; i < 6; i++){ checksum += buffer[i]; } temp = checksum/256; checksum = ( checksum - 256 * temp ) + temp; temp = checksum/256; return (BYTE)( ( checksum - 256 * temp ) + temp ); } // Calculates the checksum16 int calculateChecksum16(BYTE* buffer, int len){ int i; int checksum = 0; for( i = 6; i < len; i++){ checksum += buffer[i]; } return checksum; }
503
./exodriver/examples/U6/u6.c
//Author: LabJack //April 6, 2011 //Example U6 helper functions. Function descriptions are in the u6.h file. #include "u6.h" #include <stdlib.h> u6CalibrationInfo U6_CALIBRATION_INFO_DEFAULT = { 6, 1, //Nominal Values {0.00031580578, -10.5869565220, 0.000031580578, -1.05869565220, 0.0000031580578, -0.105869565220, 0.00000031580578, -0.0105869565220, -.000315805800, 33523.0, -.0000315805800, 33523.0, -.00000315805800, 33523.0, -.000000315805800, 33523.0, 13200.0, 0.0, 13200.0, 0.0, 0.00001, 0.0002, -92.379, 465.129, 0.00031580578, -10.5869565220, 0.000031580578, -1.05869565220, 0.0000031580578, -0.105869565220, 0.00000031580578, -0.0105869565220, -.000315805800, 33523.0, -.0000315805800, 33523.0, -.00000315805800, 33523.0, -.000000315805800, 33523.0} }; void normalChecksum(uint8 *b, int n) { b[0] = normalChecksum8(b,n); } void extendedChecksum(uint8 *b, int n) { uint16 a; a = extendedChecksum16(b,n); b[4] = (uint8)(a & 0xff); b[5] = (uint8)((a/256) & 0xff); b[0] = extendedChecksum8(b); } uint8 normalChecksum8(uint8 *b, int n) { int i; uint16 a, bb; //Sums bytes 1 to n-1 unsigned to a 2 byte value. Sums quotient and //remainder of 256 division. Again, sums quotient and remainder of //256 division. for( i = 1, a = 0; i < n; i++ ) a += (uint16)b[i]; bb = a/256; a = (a-256*bb)+bb; bb = a/256; return (uint8)((a-256*bb)+bb); } uint16 extendedChecksum16(uint8 *b, int n) { int i, a = 0; //Sums bytes 6 to n-1 to a unsigned 2 byte value for( i = 6; i < n; i++ ) a += (uint16)b[i]; return a; } uint8 extendedChecksum8(uint8 *b) { int i, a, bb; //Sums bytes 1 to 5. Sums quotient and remainder of 256 division. Again, sums //quotient and remainder of 256 division. for( i = 1, a = 0; i < 6; i++ ) a += (uint16)b[i]; bb = a/256; a = (a-256*bb)+bb; bb = a/256; return (uint8)((a-256*bb)+bb); } HANDLE openUSBConnection(int localID) { BYTE sendBuffer[26], recBuffer[38]; uint16 checksumTotal = 0; uint32 dev, numDevices = 0; int i; HANDLE hDevice = 0; numDevices = LJUSB_GetDevCount(U6_PRODUCT_ID); if( numDevices == 0 ) { printf("Open error: No U6 devices could be found\n"); return NULL; } for( dev = 1; dev <= numDevices; dev++ ) { hDevice = LJUSB_OpenDevice(dev, 0, U6_PRODUCT_ID); if( hDevice != NULL ) { if( localID < 0 ) { return hDevice; } else { checksumTotal = 0; //setting up a U6Config sendBuffer[1] = (uint8)(0xF8); sendBuffer[2] = (uint8)(0x0A); sendBuffer[3] = (uint8)(0x08); for( i = 6; i < 26; i++ ) sendBuffer[i] = (uint8)(0x00); extendedChecksum(sendBuffer, 26); if( LJUSB_Write(hDevice, sendBuffer, 26) != 26 ) goto locid_error; if( LJUSB_Read(hDevice, recBuffer, 38) != 38 ) goto locid_error; checksumTotal = extendedChecksum16(recBuffer, 38); if( (uint8)((checksumTotal / 256) & 0xff) != recBuffer[5] ) goto locid_error; if( (uint8)(checksumTotal & 0xff) != recBuffer[4] ) goto locid_error; if( extendedChecksum8(recBuffer) != recBuffer[0] ) goto locid_error; if( recBuffer[1] != (uint8)(0xF8) || recBuffer[2] != (uint8)(0x10) || recBuffer[3] != (uint8)(0x08) ) goto locid_error; if( recBuffer[6] != 0 ) goto locid_error; //Check locasl ID and serial number if( (int)recBuffer[21] == localID || (int)(recBuffer[15] + recBuffer[16]*256 + recBuffer[17]*65536 + recBuffer[18]*16777216) == localID ) return hDevice; //No matches, not our device LJUSB_CloseDevice(hDevice); } //else localID >= 0 end } //if hDevice != NULL end } //for end printf("Open error: could not find a U6 with a local ID or serial number of %d\n", localID); return NULL; locid_error: printf("Open error: problem when checking local ID\n"); return NULL; } void closeUSBConnection(HANDLE hDevice) { LJUSB_CloseDevice(hDevice); } long getTickCount() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } long isCalibrationInfoValid(u6CalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 6 ) goto invalid; return 1; invalid: printf("Error: Invalid calibration info.\n"); return 0; } long isTdacCalibrationInfoValid(u6TdacCalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 6 ) goto invalid; return 1; invalid: printf("Error: Invalid LJTDAC calibration info.\n"); return 0; } long getCalibrationInfo(HANDLE hDevice, u6CalibrationInfo *caliInfo) { uint8 sendBuffer[64], recBuffer[64]; int sentRec = 0, offset = 0, i = 0; /* sending ConfigU6 command to get see if hi res */ sendBuffer[1] = (uint8)(0xF8); //command byte sendBuffer[2] = (uint8)(0x0A); //number of data words sendBuffer[3] = (uint8)(0x08); //extended command number //setting WriteMask0 and all other bytes to 0 since we only want to read the response for( i = 6; i < 26; i++ ) sendBuffer[i] = 0; extendedChecksum(sendBuffer, 26); sentRec = LJUSB_Write(hDevice, sendBuffer, 26); if( sentRec < 26 ) { if( sentRec == 0 ) goto writeError0; else goto writeError1; } sentRec = LJUSB_Read(hDevice, recBuffer, 38); if( sentRec < 38 ) { if( sentRec == 0 ) goto readError0; else goto readError1; } if( recBuffer[1] != (uint8)(0xF8) || recBuffer[2] != (uint8)(0x10) || recBuffer[3] != (uint8)(0x08) ) goto commandByteError; caliInfo->hiRes = (((recBuffer[37]&8) == 8)?1:0); for( i = 0; i < 10; i++ ) { /* reading block i from memory */ sendBuffer[1] = (uint8)(0xF8); //command byte sendBuffer[2] = (uint8)(0x01); //number of data words sendBuffer[3] = (uint8)(0x2D); //extended command number sendBuffer[6] = 0; sendBuffer[7] = (uint8)i; //Blocknum = i extendedChecksum(sendBuffer, 8); sentRec = LJUSB_Write(hDevice, sendBuffer, 8); if( sentRec < 8 ) { if( sentRec == 0 ) goto writeError0; else goto writeError1; } sentRec = LJUSB_Read(hDevice, recBuffer, 40); if( sentRec < 40 ) { if( sentRec == 0 ) goto readError0; else goto readError1; } if( recBuffer[1] != (uint8)(0xF8) || recBuffer[2] != (uint8)(0x11) || recBuffer[3] != (uint8)(0x2D) ) goto commandByteError; offset = i*4; //block data starts on byte 8 of the buffer caliInfo->ccConstants[offset] = FPuint8ArrayToFPDouble(recBuffer + 8, 0); caliInfo->ccConstants[offset + 1] = FPuint8ArrayToFPDouble(recBuffer + 8, 8); caliInfo->ccConstants[offset + 2] = FPuint8ArrayToFPDouble(recBuffer + 8, 16); caliInfo->ccConstants[offset + 3] = FPuint8ArrayToFPDouble(recBuffer + 8, 24); } caliInfo->prodID = 6; return 0; writeError0: printf("Error : getCalibrationInfo write failed\n"); return -1; writeError1: printf("Error : getCalibrationInfo did not write all of the buffer\n"); return -1; readError0: printf("Error : getCalibrationInfo read failed\n"); return -1; readError1: printf("Error : getCalibrationInfo did not read all of the buffer\n"); return -1; commandByteError: printf("Error : getCalibrationInfo received wrong command bytes for ReadMem\n"); return -1; } long getTdacCalibrationInfo(HANDLE hDevice, u6TdacCalibrationInfo *caliInfo, uint8 DIOAPinNum) { int err; uint8 options, speedAdjust, sdaPinNum, sclPinNum; uint8 address, numByteToSend, numBytesToReceive, errorcode; uint8 bytesCommand[1], bytesResponse[32], ackArray[4]; err = 0; //Setting up I2C command for LJTDAC options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about 130 kHz) sdaPinNum = DIOAPinNum+1; //SDAPinNum : FIO channel connected to pin DIOB sclPinNum = DIOAPinNum; //SCLPinNum : FIO channel connected to pin DIOA address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numByteToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 32; //NumI2CBytesToReceive : getting 32 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 64; //I2CByte0 : Memory Address (starting at address 64 (DACA Slope) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numByteToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( errorcode != 0 ) { printf("Getting LJTDAC calibration info error : received errorcode %d in response\n", errorcode); err = -1; } if( err == -1 ) return err; caliInfo->ccConstants[0] = FPuint8ArrayToFPDouble(bytesResponse, 0); caliInfo->ccConstants[1] = FPuint8ArrayToFPDouble(bytesResponse, 8); caliInfo->ccConstants[2] = FPuint8ArrayToFPDouble(bytesResponse, 16); caliInfo->ccConstants[3] = FPuint8ArrayToFPDouble(bytesResponse, 24); caliInfo->prodID = 6; return err; } double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) { uint32 resultDec = 0, resultWh = 0; resultDec = (uint32)buffer[startIndex] | ((uint32)buffer[startIndex + 1] << 8) | ((uint32)buffer[startIndex + 2] << 16) | ((uint32)buffer[startIndex + 3] << 24); resultWh = (uint32)buffer[startIndex + 4] | ((uint32)buffer[startIndex + 5] << 8) | ((uint32)buffer[startIndex + 6] << 16) | ((uint32)buffer[startIndex + 7] << 24); return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); } long getAinVoltCalibrated(u6CalibrationInfo *caliInfo, int resolutionIndex, int gainIndex, int bits24, uint32 bytesVolt, double *analogVolt) { double value = 0; int indexAdjust = 0; if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; value = (double)bytesVolt; if( bits24) value = value/256.0; if( gainIndex > 4 ) { printf("getAinVoltCalibrated error: invalid gain index.\n"); return -1; } if( resolutionIndex > 8 ) indexAdjust = 24; if( value < caliInfo->ccConstants[indexAdjust + gainIndex*2 + 9] ) *analogVolt = (caliInfo->ccConstants[indexAdjust + gainIndex*2 + 9] - value) * caliInfo->ccConstants[indexAdjust + gainIndex*2 + 8]; else *analogVolt = (value - caliInfo->ccConstants[indexAdjust + gainIndex*2 + 9]) * caliInfo->ccConstants[indexAdjust + gainIndex*2]; return 0; } long getDacBinVoltCalibrated8Bit(u6CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint8 *bytesVolt8) { uint16 u16BytesVolt = 0; if( getDacBinVoltCalibrated16Bit(caliInfo, dacNumber, analogVolt, &u16BytesVolt) != -1 ) { *bytesVolt8 = (uint8)(u16BytesVolt/256); return 0; } return -1; } long getDacBinVoltCalibrated16Bit(u6CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt16) { uint32 dBytesVolt; if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getDacBinVoltCalibrated error: invalid channelNumber.\n"); return -1; } dBytesVolt = analogVolt*caliInfo->ccConstants[16 + dacNumber*2] + caliInfo->ccConstants[17 + dacNumber*2]; //Checking to make sure bytesVolt will be a value between 0 and 65535. if( dBytesVolt > 65535 ) dBytesVolt = 65535; *bytesVolt16 = (uint16)dBytesVolt; return 0; } long getTempKCalibrated(u6CalibrationInfo *caliInfo, int resolutionIndex, int gainIndex, int bits24, uint32 bytesTemp, double *kelvinTemp) { double value; //convert to voltage first if( getAinVoltCalibrated(caliInfo, resolutionIndex, gainIndex, bits24, bytesTemp, &value) == -1 ) return -1; *kelvinTemp = caliInfo->ccConstants[22]*value + caliInfo->ccConstants[23]; return 0; } long getTdacBinVoltCalibrated(u6TdacCalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt) { uint32 dBytesVolt; if( isTdacCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getTdacBinVoltCalibrated error: invalid channelNumber.\n"); return -1; } dBytesVolt = analogVolt*caliInfo->ccConstants[dacNumber*2] + caliInfo->ccConstants[dacNumber*2 + 1]; //Checking to make sure bytesVolt will be a value between 0 and 65535. if( dBytesVolt > 65535 ) dBytesVolt = 65535; *bytesVolt = (uint16)dBytesVolt; return 0; } long getAinVoltUncalibrated(int resolutionIndex, int gainIndex, int bits24, uint32 bytesVolt, double *analogVolt) { return getAinVoltCalibrated(&U6_CALIBRATION_INFO_DEFAULT, resolutionIndex, gainIndex, bits24, bytesVolt, analogVolt); } long getDacBinVoltUncalibrated8Bit(int dacNumber, double analogVolt, uint8 *bytesVolt8) { return getDacBinVoltCalibrated8Bit(&U6_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt8); } long getDacBinVoltUncalibrated16Bit(int dacNumber, double analogVolt, uint16 *bytesVolt16) { return getDacBinVoltCalibrated16Bit(&U6_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt16); } long getTempKUncalibrated(int resolutionIndex, int gainIndex, int bits24, uint32 bytesTemp, double *kelvinTemp) { return getTempKCalibrated(&U6_CALIBRATION_INFO_DEFAULT, resolutionIndex, gainIndex, bits24, bytesTemp, kelvinTemp); } long I2C(HANDLE hDevice, uint8 I2COptions, uint8 SpeedAdjust, uint8 SDAPinNum, uint8 SCLPinNum, uint8 Address, uint8 NumI2CBytesToSend, uint8 NumI2CBytesToReceive, uint8 *I2CBytesCommand, uint8 *Errorcode, uint8 *AckArray, uint8 *I2CBytesResponse) { uint8 *sendBuff, *recBuff; uint16 checksumTotal = 0; uint32 ackArrayTotal, expectedAckArray; int sendChars, recChars, sendSize, recSize, i, ret; *Errorcode = 0; ret = 0; sendSize = 6 + 8 + ((NumI2CBytesToSend%2 != 0)?(NumI2CBytesToSend + 1):(NumI2CBytesToSend)); recSize = 6 + 6 + ((NumI2CBytesToReceive%2 != 0)?(NumI2CBytesToReceive + 1):(NumI2CBytesToReceive)); sendBuff = (uint8 *)malloc(sizeof(uint8)*sendSize); recBuff = (uint8 *)malloc(sizeof(uint8)*recSize); sendBuff[sendSize - 1] = 0; //I2C command sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (sendSize - 6)/2; //Number of data words = 4 + NumI2CBytesToSend sendBuff[3] = (uint8)(0x3B); //Extended command number sendBuff[6] = I2COptions; //I2COptions sendBuff[7] = SpeedAdjust; //SpeedAdjust sendBuff[8] = SDAPinNum; //SDAPinNum sendBuff[9] = SCLPinNum; //SCLPinNum sendBuff[10] = Address; //Address sendBuff[11] = 0; //Reserved sendBuff[12] = NumI2CBytesToSend; //NumI2CByteToSend sendBuff[13] = NumI2CBytesToReceive; //NumI2CBytesToReceive for( i = 0; i < NumI2CBytesToSend; i++ ) sendBuff[14 + i] = I2CBytesCommand[i]; //I2CByte extendedChecksum(sendBuff, sendSize); //Sending command to U6 sendChars = LJUSB_Write(hDevice, sendBuff, sendSize); if( sendChars < sendSize ) { if( sendChars == 0 ) printf("I2C Error : write failed\n"); else printf("I2C Error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U6 recChars = LJUSB_Read(hDevice, recBuff, recSize); if( recChars < recSize ) { if( recChars == 0 ) printf("I2C Error : read failed\n"); else { printf("I2C Error : did not read all of the buffer\n"); if( recChars >= 12 ) *Errorcode = recBuff[6]; } ret = -1; goto cleanmem; } *Errorcode = recBuff[6]; AckArray[0] = recBuff[8]; AckArray[1] = recBuff[9]; AckArray[2] = recBuff[10]; AckArray[3] = recBuff[11]; for( i = 0; i < NumI2CBytesToReceive; i++ ) I2CBytesResponse[i] = recBuff[12 + i]; if( (uint8)(extendedChecksum8(recBuff)) != recBuff[0] ) { printf("I2C Error : read buffer has bad checksum (%d)\n", recBuff[0]); ret = -1; } if( recBuff[1] != (uint8)(0xF8) ) { printf("I2C Error : read buffer has incorrect command byte (%d)\n", recBuff[1]); ret = -1; } if( recBuff[2] != (uint8)((recSize - 6)/2) ) { printf("I2C Error : read buffer has incorrect number of data words (%d)\n", recBuff[2]); ret = -1; } if( recBuff[3] != (uint8)(0x3B) ) { printf("I2C Error : read buffer has incorrect extended command number (%d)\n", recBuff[3]); ret = -1; } checksumTotal = extendedChecksum16(recBuff, recSize); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] || (uint8)(checksumTotal & 255) != recBuff[4] ) { printf("I2C error : read buffer has bad checksum16 (%u)\n", checksumTotal); ret = -1; } //ackArray should ack the Address byte in the first ack bit ackArrayTotal = AckArray[0] + AckArray[1]*256 + AckArray[2]*65536 + AckArray[3]*16777216; expectedAckArray = pow(2.0, NumI2CBytesToSend+1)-1; if( ackArrayTotal != expectedAckArray ) printf("I2C error : expected an ack of %u, but received %u\n", expectedAckArray, ackArrayTotal); cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; } long eAIN(HANDLE Handle, u6CalibrationInfo *CalibrationInfo, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2) { uint8 diff, gain, Errorcode, ErrorFrame; uint8 sendDataBuff[4], recDataBuff[5]; uint32 bytesV; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eAIN error: Invalid calibration information.\n"); return -1; } //Checking if acceptable positive channel if( ChannelP < 0 || ChannelP > 143 ) { printf("eAIN error: Invalid ChannelP value.\n"); return -1; } //Checking if single ended or differential readin if( ChannelN == 0 || ChannelN == 15 ) { //Single ended reading diff = 0; } else if( (ChannelN&1) == 1 && ChannelN == ChannelP + 1 ) { //Differential reading diff = 1; } else { printf("eAIN error: Invalid ChannelN value.\n"); return -1; } if( Range == LJ_rgAUTO ) gain = 15; else if( Range == LJ_rgBIP10V ) gain = 0; else if( Range == LJ_rgBIP1V ) gain = 1; else if( Range == LJ_rgBIPP1V ) gain = 2; else if( Range == LJ_rgBIPP01V ) gain = 3; else { printf("eAIN error: Invalid Range value\n"); return -1; } if( Resolution < 0 || Resolution > 13 ) { printf("eAIN error: Invalid Resolution value\n"); return -1; } if( Settling < 0 && Settling > 4 ) { printf("eAIN error: Invalid Settling value\n"); return -1; } /* Setting up Feedback command to read analog input */ sendDataBuff[0] = 3; //IOType is AIN24AR sendDataBuff[1] = (uint8)ChannelP; //Positive channel sendDataBuff[2] = (uint8)Resolution + gain*16; //Res Index (0-3), Gain Index (4-7) sendDataBuff[3] = (uint8)Settling + diff*128; //Settling factor (0-2), Differential (7) if( ehFeedback(Handle, sendDataBuff, 4, &Errorcode, &ErrorFrame, recDataBuff, 5) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; bytesV = recDataBuff[0] + ((uint32)recDataBuff[1])*256 + ((uint32)recDataBuff[2])*65536; gain = recDataBuff[3]/16; if( Binary != 0 ) { *Voltage = (double)bytesV; } else { if( ChannelP == 14 ) { if( getTempKCalibrated(CalibrationInfo, Resolution, gain, 1, bytesV, Voltage) < 0 ) return -1; } else { gain = recDataBuff[3]/16; if( getAinVoltCalibrated(CalibrationInfo, Resolution, gain, 1, bytesV, Voltage) < 0 ) return -1; } } return 0; } long eDAC(HANDLE Handle, u6CalibrationInfo *CalibrationInfo, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2) { uint8 Errorcode, ErrorFrame; uint8 sendDataBuff[3]; uint16 bytesV; long sendSize; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eDAC error: Invalid calibration information.\n"); return -1; } if( Channel < 0 || Channel > 1 ) { printf("eDAC error: Invalid Channel.\n"); return -1; } sendSize = 3; sendDataBuff[0] = 38 + Channel; //IOType is DAC0/1 (16 bit) if( getDacBinVoltCalibrated16Bit(CalibrationInfo, (int)Channel, Voltage, &bytesV) < 0 ) return -1; sendDataBuff[1] = (uint8)(bytesV&255); //Value LSB sendDataBuff[2] = (uint8)((bytesV&65280)/256); //Value MSB if( ehFeedback(Handle, sendDataBuff, sendSize, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; return 0; } long eDI(HANDLE Handle, long Channel, long *State) { uint8 sendDataBuff[4], recDataBuff[1]; uint8 Errorcode, ErrorFrame; if( Channel < 0 || Channel > 19 ) { printf("eDI error: Invalid Channel.\n"); return -1; } /* Setting up Feedback command to set digital Channel to input and to read from it */ sendDataBuff[0] = 13; //IOType is BitDirWrite sendDataBuff[1] = Channel; //IONumber(bits 0-4) + Direction (bit 7) sendDataBuff[2] = 10; //IOType is BitStateRead sendDataBuff[3] = Channel; //IONumber if( ehFeedback(Handle, sendDataBuff, 4, &Errorcode, &ErrorFrame, recDataBuff, 1) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; *State = recDataBuff[0]; return 0; } long eDO(HANDLE Handle, long Channel, long State) { uint8 Errorcode, ErrorFrame; uint8 sendDataBuff[4]; if( Channel < 0 || Channel > 19 ) { printf("eD0 error: Invalid Channel\n"); return -1; } /* Setting up Feedback command to set digital Channel to output and to set the state */ sendDataBuff[0] = 13; //IOType is BitDirWrite sendDataBuff[1] = Channel + 128; //IONumber(bits 0-4) + Direction (bit 7) sendDataBuff[2] = 11; //IOType is BitStateWrite sendDataBuff[3] = Channel + 128*((State > 0) ? 1 : 0); //IONumber(bits 0-4) + State (bit 7) if( ehFeedback(Handle, sendDataBuff, 4, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; return 0; } long eTCConfig(HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2) { uint8 sendDataBuff[20]; uint8 numTimers, counters, cNumTimers, cCounters, cPinOffset, Errorcode, ErrorFrame; int sendDataBuffSize, i; long error; if( TCPinOffset < 0 && TCPinOffset > 8) { printf("eTCConfig error: Invalid TCPinOffset.\n"); return -1; } /* ConfigTimerClock */ if( TimerClockBaseIndex == LJ_tc4MHZ || TimerClockBaseIndex == LJ_tc12MHZ || TimerClockBaseIndex == LJ_tc48MHZ || TimerClockBaseIndex == LJ_tc1MHZ_DIV || TimerClockBaseIndex == LJ_tc4MHZ_DIV || TimerClockBaseIndex == LJ_tc12MHZ_DIV || TimerClockBaseIndex == LJ_tc48MHZ_DIV ) TimerClockBaseIndex = TimerClockBaseIndex - 20; error = ehConfigTimerClock(Handle, (uint8)(TimerClockBaseIndex + 128), (uint8)TimerClockDivisor, NULL, NULL); if( error != 0 ) return error; numTimers = 0; counters = 0; for( i = 0; i < 4; i++ ) { if( aEnableTimers[i] != 0 ) numTimers++; else i = 999; } for( i = 0; i < 2; i++ ) { if( aEnableCounters[i] != 0 ) { counters += pow(2, i); } } error = ehConfigIO(Handle, 1, numTimers, counters, TCPinOffset, &cNumTimers, &cCounters, &cPinOffset); if( error != 0 ) return error; if( numTimers > 0 ) { /* Feedback */ for( i = 0; i < 8; i++ ) sendDataBuff[i] = 0; for( i = 0; i < numTimers; i++ ) { sendDataBuff[i*4] = 43 + i*2; //TimerConfig sendDataBuff[1 + i*4] = (uint8)aTimerModes[i]; //TimerMode sendDataBuff[2 + i*4] = (uint8)(((long)aTimerValues[i])&0x00ff); //Value LSB sendDataBuff[3 + i*4] = (uint8)((((long)aTimerValues[i])&0xff00)/256); //Value MSB } sendDataBuffSize = 4*numTimers; if( ehFeedback(Handle, sendDataBuff, sendDataBuffSize, &Errorcode, &ErrorFrame, NULL, 0) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; } return 0; } long eTCValues(HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2) { uint8 Errorcode, ErrorFrame; uint8 sendDataBuff[20], recDataBuff[24]; int sendDataBuffSize, recDataBuffSize, i, j; int numTimers, dataCountCounter, dataCountTimer; /* Feedback */ numTimers = 0; dataCountCounter = 0; dataCountTimer = 0; sendDataBuffSize = 0; recDataBuffSize = 0; for( i = 0; i < 4; i++ ) { if( aReadTimers[i] != 0 || aUpdateResetTimers[i] != 0 ) { sendDataBuff[sendDataBuffSize] = 42 + i*2; //Timer sendDataBuff[1 + sendDataBuffSize] = ((aUpdateResetTimers[i] != 0) ? 1 : 0); //UpdateReset sendDataBuff[2 + sendDataBuffSize] = (uint8)(((long)aTimerValues[i])&0x00ff); //Value LSB sendDataBuff[3 + sendDataBuffSize] = (uint8)((((long)aTimerValues[i])&0xff00)/256); //Value MSB sendDataBuffSize += 4; recDataBuffSize += 4; numTimers++; } } for( i = 0; i < 2; i++ ) { if( aReadCounters[i] != 0 || aResetCounters[i] != 0 ) { sendDataBuff[sendDataBuffSize] = 54 + i; //Counter sendDataBuff[1 + sendDataBuffSize] = ((aResetCounters[i] != 0) ? 1 : 0); //Reset sendDataBuffSize += 2; recDataBuffSize += 4; } } if( ehFeedback(Handle, sendDataBuff, sendDataBuffSize, &Errorcode, &ErrorFrame, recDataBuff, recDataBuffSize) < 0 ) return -1; if( Errorcode ) return (long)Errorcode; for( i = 0; i < 4; i++ ) { aTimerValues[i] = 0; if( aReadTimers[i] != 0 ) { for( j = 0; j < 4; j++ ) aTimerValues[i] += (double)((long)recDataBuff[j + dataCountTimer*4]*pow(2, 8*j)); } if( aReadTimers[i] != 0 || aUpdateResetTimers[i] != 0 ) dataCountTimer++; if( i < 2 ) { aCounterValues[i] = 0; if( aReadCounters[i] != 0 ) { for( j = 0; j < 4; j++ ) aCounterValues[i] += (double)((long)recDataBuff[j + numTimers*4 + dataCountCounter*4]*pow(2, 8*j)); } if( aReadCounters[i] != 0 || aResetCounters[i] != 0 ) dataCountCounter++; } } return 0; } long ehConfigIO(HANDLE hDevice, uint8 inWriteMask, uint8 inNumberTimersEnabled, uint8 inCounterEnable, uint8 inPinOffset, uint8 *outNumberTimersEnabled, uint8 *outCounterEnable, uint8 *outPinOffset) { uint8 sendBuff[16], recBuff[16]; uint16 checksumTotal; int sendChars, recChars, i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x05); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = inWriteMask; //Writemask sendBuff[7] = inNumberTimersEnabled; sendBuff[8] = inCounterEnable; sendBuff[9] = inPinOffset; for( i = 10; i < 16; i++ ) sendBuff[i] = 0; extendedChecksum(sendBuff, 16); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 16)) < 16 ) { if( sendChars == 0 ) printf("ehConfigIO error : write failed\n"); else printf("ehConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 16)) < 16 ) { if( recChars == 0 ) printf("ehConfigIO error : read failed\n"); else printf("ehConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 16); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x05) || recBuff[3] != (uint8)(0x0B) ) { printf("ehConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ehConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return (int)recBuff[6]; } if( outNumberTimersEnabled != NULL ) *outNumberTimersEnabled = recBuff[7]; if( outCounterEnable != NULL ) *outCounterEnable = recBuff[8]; if( outPinOffset != NULL) *outPinOffset = recBuff[9]; return 0; } long ehConfigTimerClock(HANDLE hDevice, uint8 inTimerClockConfig, uint8 inTimerClockDivisor, uint8 *outTimerClockConfig, uint8 *outTimerClockDivisor) { uint8 sendBuff[10], recBuff[10]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x02); //Number of data words sendBuff[3] = (uint8)(0x0A); //Extended command number sendBuff[6] = 0; //Reserved sendBuff[7] = 0; //Reserved sendBuff[8] = inTimerClockConfig; //TimerClockConfig sendBuff[9] = inTimerClockDivisor; //TimerClockDivisor extendedChecksum(sendBuff, 10); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 10)) < 10 ) { if( sendChars == 0 ) printf("ehConfigTimerClock error : write failed\n"); else printf("ehConfigTimerClock error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) printf("ehConfigTimerClock error : read failed\n"); else printf("ehConfigTimerClock error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehConfigTimerClock error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehConfigTimerClock error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehConfigTimerClock error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x02) || recBuff[3] != (uint8)(0x0A) ) { printf("ehConfigTimerClock error : read buffer has wrong command bytes\n"); return -1; } if( outTimerClockConfig != NULL ) *outTimerClockConfig = recBuff[8]; if( outTimerClockDivisor != NULL ) *outTimerClockDivisor = recBuff[9]; if( recBuff[6] != 0 ) { printf("ehConfigTimerClock error : read buffer received errorcode %d\n", recBuff[6]); return recBuff[6]; } return 0; } long ehFeedback(HANDLE hDevice, uint8 *inIOTypesDataBuff, long inIOTypesDataSize, uint8 *outErrorcode, uint8 *outErrorFrame, uint8 *outDataBuff, long outDataSize) { uint8 *sendBuff, *recBuff; uint16 checksumTotal; int sendChars, recChars, i, sendDWSize, recDWSize, commandBytes, ret; ret = 0; commandBytes = 6; if( ((sendDWSize = inIOTypesDataSize + 1)%2) != 0 ) sendDWSize++; if( ((recDWSize = outDataSize + 3)%2) != 0 ) recDWSize++; sendBuff = (uint8 *)malloc(sizeof(uint8)*(commandBytes + sendDWSize)); recBuff = (uint8 *)malloc(sizeof(uint8)*(commandBytes + recDWSize)); if( sendBuff == NULL || recBuff == NULL ) { ret = -1; goto cleanmem; } sendBuff[sendDWSize + commandBytes - 1] = 0; /* Setting up Feedback command */ sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = sendDWSize/2; //Number of data words (.5 word for echo, 1.5 //words for IOTypes) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo for( i = 0; i < inIOTypesDataSize; i++ ) sendBuff[i+commandBytes+1] = inIOTypesDataBuff[i]; extendedChecksum(sendBuff, (sendDWSize+commandBytes)); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, (sendDWSize+commandBytes))) < sendDWSize+commandBytes ) { if( sendChars == 0 ) printf("ehFeedback error : write failed\n"); else printf("ehFeedback error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, (commandBytes+recDWSize))) < commandBytes+recDWSize ) { if( recChars == -1 ) { printf("ehFeedback error : read failed\n"); ret = -1; goto cleanmem; } else if( recChars < 8 ) { printf("ehFeedback error : response buffer is too small\n"); for( i = 0; i < recChars; i++ ) printf("%d ", recBuff[i]); ret = -1; goto cleanmem; } else printf("ehFeedback error : did not read all of the expected buffer (received %d, expected %d )\n", recChars, commandBytes+recDWSize); } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ehFeedback error : read buffer has bad checksum16(MSB)\n"); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ehFeedback error : read buffer has bad checksum16(LBS)\n"); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehFeedback error : read buffer has bad checksum8\n"); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("ehFeedback error : read buffer has wrong command bytes \n"); ret = -1; goto cleanmem; } *outErrorcode = recBuff[6]; *outErrorFrame = recBuff[7]; for( i = 0; i+commandBytes+3 < recChars && i < outDataSize; i++ ) outDataBuff[i] = recBuff[i+commandBytes+3]; cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; }
504
./exodriver/examples/U6/u6EFunctions.c
//Author: LabJack //April 5, 2011 //This examples demonstrates how to read from analog inputs (AIN) and digital inputs(FIO), //set analog outputs (DAC) and digital outputs (FIO), and how to configure and enable //timers and counters and read input timers and counters values using the "easy" functions. #include "u6.h" #include <unistd.h> int main(int argc, char **argv) { HANDLE hDevice; u6CalibrationInfo caliInfo; int localID; long error; //Open first found U6 over USB localID = -1; if( (hDevice = openUSBConnection(localID)) == NULL ) goto done; //Get calibration information from U6 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; //Set DAC0 to 3.1 volts. printf("Calling eDAC to set DAC0 to 3.1 V\n"); if( (error = eDAC(hDevice, &caliInfo, 0, 3.1, 0, 0, 0)) != 0 ) goto close; //Read the single-ended voltage from AIN3 printf("\nCalling eAIN to read voltage from AIN3\n"); double dblVoltage; if( (error = eAIN(hDevice, &caliInfo, 3, 15, &dblVoltage, 0, 0, 0, 0, 0, 0)) != 0 ) goto close; printf("AIN3 value = %.3f\n", dblVoltage); //Set FIO2 to output-high printf("\nCalling eDO to set FIO2 to output-high\n"); if( (error = eDO(hDevice, 2, 1)) != 0 ) goto close; //Read state of FIO3 printf("\nCalling eDI to read the state of FIO3\n"); long lngState; if( (error = eDI(hDevice, 3, &lngState)) != 0 ) goto close; printf("FIO3 state = %ld\n", lngState); //Enable and configure 1 output timer and 1 input timer, and enable counter0 printf("\nCalling eTCConfig to enable and configure 1 output timer (Timer0) and 1 input timer (Timer1), and enable counter0\n"); long alngEnableTimers[4] = {1, 1, 0, 0}; //Enable Timer0-Timer1 long alngTimerModes[4] = {LJ_tmPWM8, LJ_tmRISINGEDGES32, 0, 0}; //Set timer modes double adblTimerValues[4] = {16384, 0, 0, 0}; //Set PWM8 duty-cycles to 75% long alngEnableCounters[2] = {1, 0}; //Enable Counter0 if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 0, LJ_tc48MHZ, 0, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nWaiting for 1 second...\n"); sleep(1); //Read and reset the input timer (Timer1), read and reset Counter0, and update the //value (duty-cycle) of the output timer (Timer0) printf("\nCalling eTCValues to read and reset the input Timer1 and Counter0, and update the value (duty-cycle) of the output Timer0\n"); long alngReadTimers[4] = {0, 1, 0, 0}; //Read Timer1 long alngUpdateResetTimers[4] = {1, 0, 0, 0}; //Update timer0 long alngReadCounters[2] = {1, 0}; //Read Counter0 long alngResetCounters[2] = {1, 0}; //Reset Counter 1 double adblCounterValues[2] = {0, 0}; adblTimerValues[0] = 32768; //Change Timer0 duty-cycle to 50% adblTimerValues[1] = 0; if( (error = eTCValues(hDevice, alngReadTimers, alngUpdateResetTimers, alngReadCounters, alngResetCounters, adblTimerValues, adblCounterValues, 0, 0)) != 0 ) goto close; printf("Timer1 value = %.0f\n", adblTimerValues[1]); printf("Counter0 value = %.0f\n", adblCounterValues[0]); //Disable all timers and counters alngEnableTimers[0] = 0; alngEnableTimers[1] = 0; alngEnableTimers[2] = 0; alngEnableTimers[3] = 0; alngEnableCounters[0] = 0; alngEnableCounters[1] = 0; if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 0, LJ_tc48MHZ, 0, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nCalling eTCConfig to disable all timers and counters\n"); close: if( error > 0 ) printf("Received an error code of %ld\n", error); closeUSBConnection(hDevice); done: return 0; }
505
./exodriver/examples/U6/u6LJTDAC.c
//Author: LabJack //April 5, 2011 //Communicates with an LJTick-DAC using low level functions. The LJTDAC should //be plugged into FIO2/FIO3 for this example. #include "u6.h" #include <unistd.h> int configIO_example(HANDLE hDevice); int checkI2CErrorcode(uint8 errorcode); int tdac_example(HANDLE hDevice, u6TdacCalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; u6TdacCalibrationInfo caliInfo; //Opening first found U6 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; if( configIO_example(hDevice) != 0 ) goto close; //Getting calibration information from LJTDAC if( getTdacCalibrationInfo(hDevice, &caliInfo, 2) < 0 ) goto close; tdac_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ConfigIO low-level command to turn off timers/counters int configIO_example(HANDLE hDevice) { uint8 sendBuff[16], recBuff[16]; uint16 checksumTotal; int sendChars, recChars, i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x03); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 1; //Writemask : Setting writemask for TimerCounterConfig (bit 0) sendBuff[7] = 0; //NumberTimersEnabled : Setting to zero to disable all timers. sendBuff[8] = 0; //CounterEnable: Setting bit 0 and bit 1 to zero to disable both counters sendBuff[9] = 0; //TimerCounterPinOffset for( i = 10; i < 16; i++ ) sendBuff[i] = 0; //Reserved extendedChecksum(sendBuff, 16); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 16)) < 16 ) { if( sendChars == 0 ) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 16)) < 16 ) { if( recChars == 0 ) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 15); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x05) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } if( recBuff[8] != 0 ) { printf("ConfigIO error : NumberTimersEnabled was not set to 0\n"); return -1; } if( recBuff[9] != 0 ) { printf("ConfigIO error : CounterEnable was not set to 0\n"); return -1; } return 0; } int checkI2CErrorcode(uint8 errorcode) { if( errorcode != 0 ) { printf("I2C error : received errorcode %d in response\n", errorcode); return -1; } return 0; } int tdac_example(HANDLE hDevice, u6TdacCalibrationInfo *caliInfo) { int err; uint8 options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, errorcode; uint16 binaryVoltage; uint8 bytesCommand[5]; uint8 bytesResponse[64]; uint8 ackArray[4]; int i; err = 0; //Setting up parts I2C command that will remain the same throughout this example options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about 130 kHz) sdaPinNum = 3; //SDAPinNum : FIO3 connected to pin DIOB sclPinNum = 2; //SCLPinNum : FIO2 connected to pin DIOA /* Set DACA to 1.2 volts. */ //Setting up I2C command //Make note that the I2C command can only update 1 DAC channel at a time. address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACA and the value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting the value of the DAC bytesCommand[0] = (uint8)(0x30); //LJTDAC command byte : h0x30 (DACA) getTdacBinVoltCalibrated(caliInfo, 0, 1.2, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACA set to 1.2 volts\n\n"); /* Set DACB to 2.3 volts. */ //Setting up I2C command address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACB and the value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting the value of the DAC bytesCommand[0] = (uint8)(0x31); //LJTDAC command byte : h0x31 (DACB) getTdacBinVoltCalibrated(caliInfo, 1, 2.3, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACB set to 2.3 volts\n\n"); /* More advanced operations. */ /* Display LJTDAC calibration constants. Code for getting the calibration constants is in the * getLJTDACCalibrationInfo function in the u6.c file. */ printf("DACA Slope = %.1f bits/volt\n", caliInfo->ccConstants[0]); printf("DACA Offset = %.1f bits\n", caliInfo->ccConstants[1]); printf("DACB Slope = %.1f bits/volt\n", caliInfo->ccConstants[2]); printf("DACB Offset = %.1f bits\n\n", caliInfo->ccConstants[3]); /* Read the serial number. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 4; //NumI2CBytesToReceive : getting 4 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 96; //I2CByte0 : Memory Address (starting at address 96 (Serial Number) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("LJTDAC Serial Number = %u\n\n", (bytesResponse[0] + bytesResponse[1]*256 + bytesResponse[2]*65536 + bytesResponse[3]*16777216)); /* User memory example. We will read the memory, update a few elements, * and write the memory. The user memory is just stored as bytes, so almost * any information can be put in there such as integers, doubles, or strings. */ /* Read the user memory : need to perform 2 I2C calls since command/response packets can only be 64 bytes in size */ //Setting up 1st I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 52; //NumI2CBytesToReceive : getting 52 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Setting up 2nd I2C command numBytesToReceive = 12; //NumI2CBytesToReceive : getting 12 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 52; //I2CByte0 : Memory Address, starting at address 52 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse + 52); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); /* Create 4 new pseudo-random numbers to write. We will update the first * 4 elements of user memory, but the rest will be unchanged. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 5; //NumI2CByteToSend : 1 byte for the EEPROM address and the rest for the bytes to write numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only writing to memory bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) srand((unsigned int)getTickCount()); for( i = 1; i < 5; i++ ) bytesCommand[i] = (uint8)(255*((float)rand()/RAND_MAX));; //I2CByte : byte in user memory printf("Write User Mem [0-3] = %d, %d, %d, %d\n", bytesCommand[1], bytesCommand[2], bytesCommand[3], bytesCommand[4]); //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Delay for 2 ms to allow the EEPROM to finish writing. //Re-read the user memory. usleep(2000); //Setting up 1st I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 52; //NumI2CBytesToReceive : getting 52 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Setting up 2nd I2C command numBytesToReceive = 12; //NumI2CBytesToReceive : getting 12 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 52; //I2CByte0 : Memory Address, starting at address 52 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse + 52); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); return err; }
506
./exodriver/examples/U6/u6ConfigU6.c
//Author : LabJack //April 6, 2011 //This example calls the ConfigU6 low-level function and reads back //configuration settings. #include "u6.h" int configU6_example(HANDLE hDevice); int main(int argc, char **argv) { HANDLE hDevice; //Opening first found U6 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) return 1; configU6_example(hDevice); closeUSBConnection(hDevice); return 0; } //Sends a ConfigU3 low-level command to read back configuration settings int configU6_example(HANDLE hDevice) { uint8 sendBuff[26]; uint8 recBuff[38]; uint16 checksumTotal; int sendChars, recChars, i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x0A); //Number of data words sendBuff[3] = (uint8)(0x08); //Extended command number //Setting all bytes to zero since we only want to read back the U6 //configuration settings for( i = 6; i < 26; i++ ) sendBuff[i] = 0; /* The commented out code below sets the U6's local ID to 3. After setting the local ID, reset the device for this change to take effect. */ //sendBuff[6] = 8; //WriteMask : setting bit 3 //sendBuff[8] = 3; //LocalID : setting local ID to 3 extendedChecksum(sendBuff, 26); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 26)) < 26 ) { if( sendChars == 0 ) printf("ConfigU6 error : write failed\n"); else printf("ConfigU6 error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 38)) < 38 ) { if( recChars == 0 ) printf("ConfigU6 error : read failed\n"); else printf("ConfigU6 error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 38); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("ConfigU6 error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ConfigU6 error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigU6 error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x10) || recBuff[3] != (uint8)(0x08) ) { printf("ConfigU6 error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigU6 error : read buffer received errorcode %d\n", recBuff[6]); return -1; } printf("U6 Configuration Settings:\n"); printf("FirmwareVersion: %.3f\n", recBuff[10] + recBuff[9]/100.0); printf("BootloaderVersion: %.3f\n", recBuff[12] + recBuff[11]/100.0); printf("HardwareVersion: %.3f\n", recBuff[14] + recBuff[13]/100.0); printf("SerialNumber: %u\n", recBuff[15] + recBuff[16]*256 + recBuff[17]*65536 + recBuff[18]*16777216); printf("ProductID: %d\n", recBuff[19] + recBuff[20]*256); printf("LocalID: %d\n", recBuff[21]); printf("Version Info: %d\n", recBuff[37]); printf(" U6 (bit 2): %d\n", ((recBuff[37]/4)&1)); printf(" U6-Pro (bit 3): %d\n", ((recBuff[37]/8)&1)); return 0; }
507
./exodriver/examples/U6/u6allio.c
//Author : LabJack //April 5, 2011 //This example demonstrates how to write and read some or all analog I/O. //By default, it records the time for 1000 iterations and divides by 1000, //to allow measurement of the basic command/response communication times. These //times should be comparable to the Windows command/response communication //times documented in Section 3.1 of the U6 User's Guide. #include <stdlib.h> #include "u6.h" const int numIterations = 1000; //Number of Feedback calls that will be performed. Default 1000. const uint8 numChannels = 8; //Number of AIN channels, 0-14. Default 8. const uint8 settlingFactor = 0; //0=5us, 1=10us, 2=100us, 3=1ms, 4=10ms. Default 0. const uint8 gainIndex = 0; //0 = +-10V, 1 = +-1V, 2 = +-100mV, 3 = +-10mV, 15=autorange. Default 0. const uint8 resolution = 1; //1=default, 1-8 for high-speed ADC, 9-13 for high-res ADC on U6-Pro. Default 1. const uint8 differential = 0; //Indicates whether to do differential readings. Default 0 (false). int allIO(HANDLE hDevice, u6CalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; u6CalibrationInfo caliInfo; //Opening first found U6 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U6 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; allIO(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Calls the Feedback low-level command numIterations times and calculates the //time per iteration. int allIO(HANDLE hDevice, u6CalibrationInfo *caliInfo) { uint8 *sendBuff, *recBuff; uint16 checksumTotal, bits16; uint32 bits32; int sendChars, recChars, i, j, sendSize, recSize; double valueAIN[14]; long time; int ret = 0; for( i = 0; i < 14; i++ ) valueAIN[i] = 9999; //Setting up a Feedback command that will set CIO0-3 as input, and //set DAC0 voltage sendBuff = (uint8 *)malloc(18*sizeof(uint8)); //Creating an array of size 18 recBuff = (uint8 *)malloc(10*sizeof(uint8)); //Creating an array of size 10 sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 6; //Number of data words (.5 word for echo, 5.5 //words for IOTypes and data) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 29; //IOType is PortDirWrite sendBuff[8] = 0; //Writemask (for FIO) sendBuff[9] = 0; //Writemask (for EIO) sendBuff[10] = 15; //Writemask (for CIO) sendBuff[11] = 0; //Direction (for FIO) sendBuff[12] = 0; //Direction (for EIO) sendBuff[13] = 0; //Direction (for CIO) //Setting DAC0 with 2.5 volt output sendBuff[14] = 38; //IOType is DAC0(16-bit) //Value is 2.5 volts (in binary) getDacBinVoltCalibrated16Bit(caliInfo, 0, 2.5, &bits16); sendBuff[15] = (uint8)(bits16&255); sendBuff[16] = (uint8)(bits16/256); sendBuff[17] = 0; //extra padding byte extendedChecksum(sendBuff, 18); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 18)) < 18 ) { if(sendChars == 0) printf("Feedback (CIO input) error : write failed\n"); else printf("Feedback (CIO input) error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) { printf("Feedback (CIO input) error : read failed\n"); ret = -1; goto cleanmem; } else printf("Feedback (CIO input) error : did not read all of the buffer\n"); } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("Feedback (CIO input) error : read buffer has bad checksum16(MSB)\n"); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Feedback (CIO input) error : read buffer has bad checksum16(LBS)\n"); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback (CIO input) error : read buffer has bad checksum8\n"); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback (CIO input) error : read buffer has wrong command bytes \n"); ret = -1; goto cleanmem; } if( recBuff[6] != 0 ) { printf("Feedback (CIO input) error : received errorcode %d for frame %d in Feedback response. \n", recBuff[6], recBuff[7]); ret = -1; goto cleanmem; } free(sendBuff); free(recBuff); //Setting up Feedback command that will run numIterations times if( ((sendSize = 7+numChannels*4) % 2) != 0 ) sendSize++; sendBuff = malloc(sendSize*sizeof(uint8)); //Creating an array of size sendSize if( ((recSize = 9+numChannels*3) % 2) != 0 ) recSize++; recBuff = malloc(recSize*sizeof(uint8)); //Creating an array of size recSize sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (sendSize - 6)/2; //Number of data words sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo //Setting AIN read commands for( j = 0; j < numChannels; j++ ) { sendBuff[7 + j*4] = 2; //IOType is AIN24 //Positive Channel (bits 0 - 4), LongSettling (bit 6) and QuickSample (bit 7) sendBuff[8 + j*4] = j; //Positive Channel sendBuff[9 + j*4] = (uint8)(resolution&15) + (uint8)((gainIndex&15)*16); //ResolutionIndex(Bits 0-3), GainIndex(Bits 4-7) sendBuff[10 + j*4] = (uint8)(settlingFactor&7); //SettlingFactor(Bits 0-2) if( j%2 == 0 ) sendBuff[10 + j*4] += (uint8)((differential&1)*128); //Differential(Bits 7) } extendedChecksum(sendBuff, sendSize); time = getTickCount(); for( i = 0; i < numIterations; i++ ) { //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, sendSize)) < sendSize ) { if(sendChars == 0) printf("Feedback error (Iteration %d): write failed\n", i); else printf("Feedback error (Iteration %d): did not write all of the buffer\n", i); ret = -1; goto cleanmem; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, recSize)) < recSize ) { if( recChars == 0 ) { printf("Feedback error (Iteration %d): read failed\n", i); ret = -1; goto cleanmem; } } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum16(MSB)\n", i); ret = -1; goto cleanmem; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum16(LBS)\n", i); ret = -1; goto cleanmem; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback error (Iteration %d): read buffer has bad checksum8\n", i); ret = -1; goto cleanmem; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback error (Iteration %d): read buffer has wrong command bytes \n", i); ret = -1; goto cleanmem; } if( recBuff[6] != 0 ) { printf("Feedback error (Iteration %d): received errorcode %d for frame %d in Feedback response. \n", i, recBuff[6], recBuff[7]); ret = -1; goto cleanmem; } if( recChars != recSize ) { printf("Feedback error (Iteration %d): received packet if %d size when expecting %d\n", i, recChars, recSize); ret = -1; goto cleanmem; } //Getting AIN voltages for(j = 0; j < numChannels; j++) { bits32 = recBuff[9+j*3] + recBuff[10+j*3]*256 + recBuff[11+j*3]*65536; getAinVoltCalibrated(caliInfo, resolution, gainIndex, 1, bits32, &valueAIN[j]); } } time = getTickCount() - time; printf("Milliseconds per iteration = %.3f\n", (double)time / (double)numIterations); printf("\nAIN readings from last iteration:\n"); for( j = 0; j < numChannels; j++ ) printf("%.3f\n", valueAIN[j]); cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; }
508
./exodriver/examples/U6/u6Feedback.c
//Author : LabJack //April 5, 2011 //This example does the following: // Sets DAC0 to 3.5 volts. // Reads AIN0-AIN1, and AIN0 differential voltage. // Sets FIO0 to digital input. // Sets FIO1 and FIO2 to Timers 0 and 1 with modes PMW8 and PMW16. // Sets and reads FIO3 as Counter 1 // Reads the temperature. #include <unistd.h> #include <termios.h> #include "u6.h" static struct termios termNew, termOrig; static int peek = -1; int configIO_example(HANDLE hDevice, int enable); int configTimerClock_example(HANDLE hDevice); int feedback_setup_example(HANDLE hDevice, u6CalibrationInfo *caliInfo); int feedback_loop_example(HANDLE hDevice, u6CalibrationInfo *caliInfo); void setTerm(); int kbhit(); void unsetTerm(); int main(int argc, char **argv) { HANDLE hDevice; u6CalibrationInfo caliInfo; //setting terminal settings setTerm(); //Opening first found U6 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from U6 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( configIO_example(hDevice, 1) != 0 ) goto close; if( configTimerClock_example(hDevice) != 0 ) goto close; if( feedback_setup_example(hDevice, &caliInfo) != 0 ) goto close; if( feedback_loop_example(hDevice, &caliInfo) != 0 ) goto close; configIO_example(hDevice, 0); close: closeUSBConnection(hDevice); done: printf("\nDone\n"); //Setting terminal settings to previous settings unsetTerm(); return 0; } //Sends a ConfigIO low-level command that configures the FIOs, DAC, Timers and //Counters for this example int configIO_example(HANDLE hDevice, int enable) { uint8 sendBuff[16], recBuff[16]; uint16 checksumTotal; int sendChars, recChars, i; uint8 numTimers, counterEnable; if( enable == 0 ) { numTimers = 0; //Setting NumberTimersEnabled byte to zero to turn off all Timers counterEnable = 0 + 0*2; //Setting CounterEnable bits 0 and 1 to zero to disabled //Counters 0 and 1 } else { numTimers = 2; //Setting NumberTimersEnabled byte to 2 to indicate we are enabling //2 timers (Timers 0 and 1) counterEnable = 0 + 1*2; //Setting CounterEnable bit 1 to enable Counter 1 } sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x05); //Number of data words sendBuff[3] = (uint8)(0x0B); //Extended command number sendBuff[6] = 1; //Writemask : Setting writemask for timerCounterConfig (bit 0) sendBuff[7] = numTimers; //NumberTimersEnabled sendBuff[8] = counterEnable; //CounterEnable: Bit 0 is Counter 0, Bit 1 is Counter 1 sendBuff[9] = 1; //TimerCounterPinOffset: Setting to 1 so Timer/Counters start on FIO1 for( i = 10; i < 16; i++ ) sendBuff[i] = 0; //Reserved extendedChecksum(sendBuff, 16); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 16)) < 16 ) { if(sendChars == 0) printf("ConfigIO error : write failed\n"); else printf("ConfigIO error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 16)) < 16 ) { if(recChars == 0) printf("ConfigIO error : read failed\n"); else printf("ConfigIO error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 16); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ConfigIO error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ConfigIO error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigIO error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x05) || recBuff[3] != (uint8)(0x0B) ) { printf("ConfigIO error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigIO error : read buffer received errorcode %d\n", recBuff[6]); return -1; } return 0; } //Sends a ConfigTimerClock low-level command that configures the timer clock //for this example int configTimerClock_example(HANDLE hDevice) { uint8 sendBuff[10], recBuff[10]; uint16 checksumTotal; int sendChars, recChars; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x02); //Number of data words sendBuff[3] = (uint8)(0x0A); //Extended command number sendBuff[6] = 0; //Reserved sendBuff[7] = 0; //Reserved sendBuff[8] = 6 + 1*128; //TimerClockConfig : Configuring the clock (bit 7) and //setting the TimerClockBase (bits 0-2) to //48MHz/TimerClockDivisor sendBuff[9] = 2; //TimerClockDivisor : Setting to 2, so the actual timer //clock is 24 MHz extendedChecksum(sendBuff, 10); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 10)) < 10 ) { if(sendChars == 0) printf("ConfigTimerClock error : write failed\n"); else printf("ConfigTimerClock error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 10)) < 10 ) { if( recChars == 0 ) printf("ConfigTimerClock error : read failed\n"); else printf("ConfigTimerClock error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 10); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("ConfigTimerClock error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("ConfigTimerClock error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ConfigTimerClock error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x02) || recBuff[3] != (uint8)(0x0A) ) { printf("ConfigTimerClock error : read buffer has wrong command bytes\n"); return -1; } if( recBuff[6] != 0 ) { printf("ConfigTimerClock error : read buffer received errorcode %d\n", recBuff[6]); return -1; } return 0; } //Sends a Feedback low-level command that configures digital directions, //states, timer modes and DAC0 for this example. int feedback_setup_example(HANDLE hDevice, u6CalibrationInfo *caliInfo) { uint8 sendBuff[28], recBuff[18]; int sendChars, recChars; uint16 binVoltage16, checksumTotal; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 11; //Number of data words (.5 word for echo, 10.5 //words for IOTypes and data) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 13; //IOType is BitDirWrite sendBuff[8] = 0 + 128*0; //IONumber (bits 0 - 4) is 0 (FIO0) and Direction (bit 7) is //input sendBuff[9] = 43; //IOType is Timer0Config sendBuff[10] = 0; //TimerMode is 16 bit PWM output (mode 0) sendBuff[11] = 0; //Value LSB sendBuff[12] = 0; //Value MSB, Whole value is 32768 sendBuff[13] = 42; //IOType is Timer0 sendBuff[14] = 1; //UpdateReset sendBuff[15] = 0; //Value LSB sendBuff[16] = 128; //Value MSB, Whole Value is 32768 sendBuff[17] = 45; //IOType is Timer1Config sendBuff[18] = 1; //TimerMode is 8 bit PWM output (mode 1) sendBuff[19] = 0; //Value LSB sendBuff[20] = 0; //Value MSB, Whole value is 32768 sendBuff[21] = 44; //IOType is Timer1 sendBuff[22] = 1; //UpdateReset sendBuff[23] = 0; //Value LSB sendBuff[24] = 128; //Value MSB, Whole Value is 32768 sendBuff[25] = 38; //IOType is DAC0 (16-bit) //Value is 3.5 volts (in binary form) getDacBinVoltCalibrated16Bit(caliInfo, 0, 3.5, &binVoltage16); sendBuff[26] = (uint8)(binVoltage16&255); //Value LSB sendBuff[27] = (uint8)((binVoltage16&65280)/256); //Value MSB extendedChecksum(sendBuff, 28); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 28)) < 28 ) { if( sendChars == 0 ) printf("Feedback setup error : write failed\n"); else printf("Feedback setup error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 18)) < 18 ) { if( recChars == 0 ) { printf("Feedback setup error : read failed\n"); return -1; } else printf("Feedback setup error : did not read all of the buffer\n"); } checksumTotal = extendedChecksum16(recBuff, 18); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("Feedback setup error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Feedback setup error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback setup error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != 6 || recBuff[3] != (uint8)(0x00) ) { printf("Feedback setup error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback setup error : received errorcode %d for frame %d in Feedback response. \n", recBuff[6], recBuff[7]); return -1; } return 0; } //Calls a Feedback low-level call to read AIN0, AIN1, AIN2, AIN0 differential, //FIO0, Counter1(FIO3) and temperature. int feedback_loop_example(HANDLE hDevice, u6CalibrationInfo *caliInfo) { long count; uint8 sendBuff[28], recBuff[26]; int sendChars, recChars; uint16 checksumTotal; double voltage, temperature; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = 11; //Number of data words (.5 word for echo, 10.5 //words for IOTypes) sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 0; //Echo sendBuff[7] = 2; //IOType is AIN24 sendBuff[8] = 0; //Positive channel sendBuff[9] = 8 + 0*16; //ResolutionIndex(Bits 0-3) = 8, //GainIndex(Bits 4-7) = 0 (+-10V) sendBuff[10] = 0 + 0*128; //SettlingFactor(Bits 0-2) = 0 (5 microseconds), // Differential(Bit 7) = 0 sendBuff[11] = 2; //IOType is AIN24 sendBuff[12] = 1; //Positive channel sendBuff[13] = 8 + 0*16; //ResolutionIndex(Bits 0-3) = 8, //GainIndex(Bits 4-7) = 0 (+-10V) sendBuff[14] = 0 + 0*128; //SettlingFactor(Bits 0-2) = 0 (5 microseconds), //Differential(Bit 7) = 0 sendBuff[15] = 2; //IOType is AIN24 sendBuff[16] = 0; //Positive channel sendBuff[17] = 8 + 0*16; //ResolutionIndex(Bits 0-3) = 8, //GainIndex(Bits 4-7) = 0 (+-10V) sendBuff[18] = 0 + 1*128; //SettlingFactor(Bits 0-2) = 0 (5 microseconds), //Differential(Bit 7) = 1 sendBuff[19] = 10; //IOType is BitStateRead sendBuff[20] = 0; //IO number is 0 (FIO0) sendBuff[21] = 55; //IOType is Counter1 sendBuff[22] = 0; //Reset (bit 0) is not set sendBuff[23] = 2; //IOType is AIN24 sendBuff[24] = 14; //Positive channel = 14 (temperature sensor) sendBuff[25] = 8 + 0*16; //ResolutionIndex(Bits 0-3) = 8, //GainIndex(Bits 4-7) = 0 (+-10V) sendBuff[26] = 0 + 0*128; //SettlingFactor(Bits 0-2) = 0 (5 microseconds), Differential(Bit 7) = 0 sendBuff[27] = 0; //Padding byte extendedChecksum(sendBuff, 28); printf("Running Feedback calls in a loop\n"); count = 0; while( !kbhit() ) { count++; printf("Iteration %ld\n", count); //Sending command to U6 if( (sendChars = LJUSB_Write(hDevice, sendBuff, 28)) < 28 ) { if(sendChars == 0) printf("Feedback loop error : write failed\n"); else printf("Feedback loop error : did not write all of the buffer\n"); return -1; } //Reading response from U6 if( (recChars = LJUSB_Read(hDevice, recBuff, 26)) < 26 ) { if( recChars == 0 ) { printf("Feedback loop error : read failed\n"); return -1; } else printf("Feedback loop error : did not read all of the expected buffer\n"); } if( recChars < 10 ) { printf("Feedback loop error : response is not large enough\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, recChars); if( (uint8)((checksumTotal / 256 ) & 0xff) != recBuff[5] ) { printf("Feedback loop error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Feedback loop error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback loop error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback loop error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Feedback loop error : received errorcode %d for frame %d ", recBuff[6], recBuff[7]); switch( recBuff[7] ) { case 1: printf("(AIN0(SE))\n"); break; case 2: printf("(AIN1(SE))\n"); break; case 3: printf("(AIN0(Diff))\n"); break; case 4: printf("(BitStateRead for FIO7)\n"); break; case 5: printf("(Counter1)\n"); break; case 6: printf("(Temp. Sensor\n"); break; default: printf("(Unknown)\n"); break; } return -1; } getAinVoltCalibrated(caliInfo, 8, 0, 1, recBuff[9] + recBuff[10]*256 + recBuff[11]*65536, &voltage); printf("AIN0(SE) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, 8, 0, 1, recBuff[12] + recBuff[13]*256 + recBuff[14]*65536, &voltage); printf("AIN1(SE) : %.3f volts\n", voltage); getAinVoltCalibrated(caliInfo, 8, 0, 1, recBuff[15] + recBuff[16]*256 + recBuff[17]*65536, &voltage); printf("AIN0(Diff) : %.3f volts\n", voltage); printf("FIO0 state : %d\n", recBuff[18]); printf("Counter1(FIO3) : %u\n\n", recBuff[19] + recBuff[20]*256 + recBuff[21]*65536 + recBuff[22]*16777216); getTempKCalibrated(caliInfo, 8, 0, 1, recBuff[23] + recBuff[24]*256 + recBuff[25]*65536, &temperature); printf("Temperature : %.3f K\n\n", temperature); sleep(1); } return 0; } void setTerm() { tcgetattr(0, &termOrig); termNew = termOrig; termNew.c_lflag &= ~ICANON; termNew.c_lflag &= ~ECHO; termNew.c_lflag &= ~ISIG; termNew.c_cc[VMIN] = 1; termNew.c_cc[VTIME] = 0; tcsetattr(0, TCSANOW, &termNew); } int kbhit() { char ch; int nread; if( peek != -1 ) return 1; termNew.c_cc[VMIN]=0; tcsetattr(0, TCSANOW, &termNew); nread = read(0,&ch,1); termNew.c_cc[VMIN]=1; tcsetattr(0, TCSANOW, &termNew); if( nread == 1 ) { peek = ch; return 1; } return 0; } void unsetTerm() { tcsetattr(0, TCSANOW, &termOrig); }
509
./exodriver/examples/UE9/ue9SingleIO.c
//Author: LabJack //May 25, 2011 //This example program makes 3 SingleIO low-level function calls. One call sets //DAC0 to 2.500 V. One call reads voltage from AIN0. One call reads the //temperature from the internal temperature sensor. Control firmware version //1.03 and above needed for SingleIO. #include "ue9.h" int singleIO_AV_example(HANDLE handle, ue9CalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from UE9 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; singleIO_AV_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends 3 SingleIO low-level commands to set DAC0, read AIN0 and read the //temperature int singleIO_AV_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { uint8 sendBuff[8], recBuff[8], ainResolution; uint16 bytesVoltage, bytesTemperature; int sendChars, recChars; double voltage; double temperature; //in Kelvins ainResolution = 12; //ainResolution = 18; //high-res mode for UE9 Pro only /* Setting voltage of DAC0 to 2.500 V */ //if( getDacBinVoltUncalibrated(0, 2.500, &bytesVoltage) < 0 ) if( getDacBinVoltCalibrated(caliInfo, 0, 2.500, &bytesVoltage) < 0 ) return -1; sendBuff[1] = (uint8)(0xA3); //Command byte sendBuff[2] = (uint8)(0x05); //IOType = 5 (analog out) sendBuff[3] = (uint8)(0x00); //Channel = 0 (DAC0) sendBuff[4] = (uint8)( bytesVoltage & (0x00FF) ); //low bits of voltage sendBuff[5] = (uint8)( bytesVoltage /256 ) + 192; //high bits of voltage //(bit 7 : Enable, // bit 6: Update) sendBuff[6] = (uint8)(0x00); //Settling time - does not apply to analog output sendBuff[7] = (uint8)(0x00); //Reserved sendBuff[0] = normalChecksum8(sendBuff, 8); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 8); if( sendChars < 8 ) { if( sendChars == 0 ) goto sendError0; else goto sendError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) goto recvError0; else goto recvError1; } if( (uint8)(normalChecksum8(recBuff, 8)) != recBuff[0] ) goto chksumError; if( recBuff[1] != (uint8)(0xA3) ) goto commandByteError; if( recBuff[2] != (uint8)(0x05) ) goto IOTypeError; if( recBuff[3] != 0 ) goto channelError; printf("Set DAC0 voltage to 2.500 V ...\n"); /* Reading voltage from AIN0 */ sendBuff[1] = (uint8)(0xA3); //Command byte sendBuff[2] = (uint8)(0x04); //IOType = 4 (analog in) sendBuff[3] = (uint8)(0x00); //Channel = 0 (AIN0) sendBuff[4] = (uint8)(0x00); //BipGain (Bip = unipolar, Gain = 1) sendBuff[5] = ainResolution; //Resolution sendBuff[6] = (uint8)(0x00); //SettlingTime = 0 sendBuff[7] = (uint8)(0x00); //Reserved sendBuff[0] = normalChecksum8(sendBuff, 8); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 8); if( sendChars < 8 ) { if( sendChars == 0 ) goto sendError0; else goto sendError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) goto recvError0; else goto recvError1; } if( (uint8)(normalChecksum8(recBuff, 8)) != recBuff[0] ) goto chksumError; if( recBuff[1] != (uint8)(0xA3) ) goto commandByteError; if( recBuff[2] != (uint8)(0x04) ) goto IOTypeError; if( recBuff[3] != 0 ) goto channelError; bytesVoltage = recBuff[5] + recBuff[6]*256; //if( getAinVoltUncalibrated(sendBuff[4], ainResolution, bytesVoltage, &voltage) < 0 ) if( getAinVoltCalibrated(caliInfo, sendBuff[4], ainResolution, bytesVoltage, &voltage) < 0 ) return -1; printf("Voltage read from AI0: %.4f V\n", voltage); /* Reading temperature from internal temperature sensor */ sendBuff[1] = (uint8)(0xA3); //Command byte sendBuff[2] = (uint8)(0x04); //IOType = 4 (analog in) sendBuff[3] = (uint8)(0x85); //Channel = 133 (tempSensor) sendBuff[4] = (uint8)(0x00); //Gain = 1 (Bip does not apply) sendBuff[5] = (uint8)(0x0C); //Resolution = 12 sendBuff[6] = (uint8)(0x00); //SettlingTime = 0 sendBuff[7] = (uint8)(0x00); //Reserved sendBuff[0] = normalChecksum8(sendBuff, 8); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 8); if( sendChars < 8 ) { if( sendChars == 0 ) goto sendError0; else goto sendError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) goto recvError0; else goto recvError1; } if( (uint8)(normalChecksum8(recBuff, 8)) != recBuff[0] ) goto chksumError; if( recBuff[1] != (uint8)(0xA3) ) goto commandByteError; if( recBuff[2] != (uint8)(0x04) ) goto IOTypeError; if( recBuff[3] != (uint8)(0x85) ) goto channelError; bytesTemperature = recBuff[5] + recBuff[6]*256; //Assuming high power level //if( getTempKUncalibrated(0, bytesTemperature, &temperature) < 0 ) if( getTempKCalibrated(caliInfo, 0, bytesTemperature, &temperature) < 0 ) return -1; printf("Temperature read internal temperature sensor (channel 133): %.1f K\n\n", temperature); return 0; //error printouts sendError0: printf("Error : write failed\n"); return -1; sendError1: printf("Error : did not write all of the buffer\n"); return -1; recvError0: printf("Error : read failed\n"); return -1; recvError1: printf("Error : did not read all of the buffer\n"); return -1; chksumError: printf("Error : read buffer has bad checksum\n"); return -1; commandByteError: printf("Error : read buffer has wrong command byte\n"); return -1; IOTypeError: printf("Error : read buffer has wrong IOType\n"); return -1; channelError: printf("Error : read buffer has wrong channel\n"); return -1; }
510
./exodriver/examples/UE9/ue9Stream.c
//Author: LabJack //April 17, 2012 //This example program reads analog inputs AI0-AI3 using stream mode. #include "ue9.h" #include <math.h> #include <stdio.h> int StreamConfig_example(HANDLE hDevice); int StreamStart(HANDLE hDevice); int StreamData_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo); int StreamStop(HANDLE hDevice); int flushStream(HANDLE hDevice); int doFlush(HANDLE hDevice); const int AIN_RESOLUTION = 12; const uint8 NUM_CHANNELS = 4; //Set this to a value between 1-16. Readings //are performed on AIN channels 0-(NUM_CHANNELS-1). int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; doFlush(hDevice); //Getting calibration information from UE9 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; if( StreamConfig_example(hDevice) != 0 ) goto close; if( StreamStart(hDevice) != 0 ) goto close; StreamData_example(hDevice, &caliInfo); StreamStop(hDevice); close: closeUSBConnection(hDevice); done: return 0; } //Sends a StreamConfig low-level command to configure the stream to read only 4 //analog inputs (AI0 - AI3). int StreamConfig_example(HANDLE hDevice) { int sendBuffSize; sendBuffSize = 12 + 2*NUM_CHANNELS; uint8 sendBuff[sendBuffSize], recBuff[8]; uint16 checksumTotal, scanInterval; int sendChars, recChars, i; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = NUM_CHANNELS + 3; //Number of data words : NUM_CHANNELS + 3 sendBuff[3] = (uint8)(0x11); //Extended command number sendBuff[6] = (uint8)NUM_CHANNELS; //NumChannels sendBuff[7] = AIN_RESOLUTION; //Resolution sendBuff[8] = 0; //SettlingTime = 0 sendBuff[9] = 0; //ScanConfig: scan pulse and external scan //trigger disabled stream clock //frequency = 4 MHz scanInterval = 4000; sendBuff[10] = (uint8)(scanInterval&0x00FF); //Scan interval (low byte) sendBuff[11] = (uint8)(scanInterval/256); //Scan interval (high byte) for( i = 0; i < NUM_CHANNELS; i++ ) { sendBuff[12 + i*2] = i; //channel # = i sendBuff[13 + i*2] = 0; //BipGain (Bip = unipolar, Gain = 1) } extendedChecksum(sendBuff, sendBuffSize); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, sendBuffSize); if( sendChars < sendBuffSize ) { if( sendChars == 0 ) printf("Error : write failed (StreamConfig).\n"); else printf("Error : did not write all of the buffer (StreamConfig).\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) printf("Error : read failed (StreamConfig).\n"); else printf("Error : did not read all of the buffer (StreamConfig).\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 8); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("Error : read buffer has bad checksum16(MSB) (StreamConfig).\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Error : read buffer has bad checksum16(LSB) (StreamConfig).\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamConfig).\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x01) || recBuff[3] != (uint8)(0x11) ) { printf("Error : read buffer has wrong command bytes (StreamConfig).\n"); return -1; } if( recBuff[6] != 0 ) { printf("Errorcode # %d from StreamConfig read.\n", (unsigned int)recBuff[6]); return -1; } return 0; } //Sends a StreamStart low-level command to start streaming. int StreamStart(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xA8); //CheckSum8 sendBuff[1] = (uint8)(0xA8); //Command byte //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed (StreamStart).\n"); else printf("Error : did not write all of the buffer (StreamStart).\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed (StreamStart).\n"); else printf("Error : did not read all of the buffer (StreamStart).\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStart).\n"); return -1; } if( recBuff[1] != (uint8)(0xA9) ) { printf("Error : read buffer has wrong command byte (StreamStart).\n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStart read.\n", (unsigned int)recBuff[2]); return -1; } return 0; } //Reads the StreamData low-level function response in a loop. All voltages //from the stream are stored in the voltages 2D array. int StreamData_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { uint16 voltageBytes, checksumTotal; int recChars, backLog, overflow; int i, j, k, m, packetCounter, currChannel, scanNumber; int totalPackets; //The total number of StreamData responses read int numDisplay; //Number of times to display streaming information int numReadsPerDisplay; //Number of packets to read before displaying //streaming information int readSizeMultiplier; //Multiplier for the StreamData receive buffer size int totalScans; //Total scans that will be read Meant for calculating the //size of the voltages array. long startTime, endTime; packetCounter = 0; currChannel = 0; scanNumber = 0; totalPackets = 0; recChars = 0; numDisplay = 6; numReadsPerDisplay = 3; readSizeMultiplier = 10; /* Each StreamData response contains (16/NUM_CHANNELS) * readSizeMultiplier * samples for each channel. * Total number of scans = (16 / NUM_CHANNELS) * 4 * readSizeMultiplier * numReadsPerDisplay * numDisplay */ totalScans = ceil((16.0/NUM_CHANNELS)*4.0*readSizeMultiplier*numReadsPerDisplay*numDisplay); double voltages[totalScans][NUM_CHANNELS]; uint8 recBuff[192*readSizeMultiplier]; printf("Reading Samples...\n"); startTime = getTickCount(); for( i = 0; i < numDisplay; i++ ) { for( j = 0; j < numReadsPerDisplay; j++ ) { /* For USB StreamData, use Endpoint 2 for reads and 192 byte * packets instead of the 46. The 192 byte response is 4 * StreamData packet responses of 48 bytes. * You can read the multiple StreamData responses of 192 bytes to * help improve streaming performance. In this example this * multiple is adjusted by the readSizeMultiplier variable. */ //Reading response from UE9 recChars = LJUSB_Stream(hDevice, recBuff, 192*readSizeMultiplier); if( recChars < 192*readSizeMultiplier ) { if( recChars == 0 ) printf("Error : read failed (StreamData).\n"); else printf("Error : did not read all of the buffer %d (StreamData).\n", recChars); return -1; } overflow = 0; //Checking for errors and getting data out of each StreamData response for( m = 0; m < 4*readSizeMultiplier; m++ ) { totalPackets++; checksumTotal = extendedChecksum16(recBuff + m*48, 46); if( (uint8)((checksumTotal >> 8) & 0xff) != recBuff[m*48 + 5] ) { printf("Error : read buffer has bad checksum16(MSB) (StreamData).\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[m*48 + 4] ) { printf("Error : read buffer has bad checksum16(LSB) (StreamData).\n"); return -1; } checksumTotal = extendedChecksum8(recBuff + m*48); if( checksumTotal != recBuff[m*48] ) { printf("Error : read buffer has bad checksum8 (StreamData).\n"); return -1; } if( recBuff[m*48 + 1] != (uint8)(0xF9) || recBuff[m*48 + 2] != (uint8)(0x14) || recBuff[m*48 + 3] != (uint8)(0xC0) ) { printf("Error : read buffer has wrong command bytes (StreamData).\n"); return -1; } if( recBuff[m*48 + 11] != 0 ) { printf("Errorcode # %d from StreamData read.\n", (unsigned int)recBuff[11]); return -1; } if( packetCounter != (int) recBuff[m*48 + 10] ) { printf("PacketCounter does not match with with current packet count (StreamData).\n"); return -1; } backLog = recBuff[m*48 + 45]&0x7F; //Checking MSB for Comm buffer overflow if( (recBuff[m*48 + 45] & 128) == 128 ) { printf("\nComm buffer overflow detected in packet %d\n", totalPackets); printf("Current Comm backlog: %d\n", recBuff[m*48 + 45]&0x7F); overflow = 1; } for( k = 12; k < 43; k += 2 ) { voltageBytes = (uint16)recBuff[m*48 + k] + (uint16)recBuff[m*48 + k+1]*256; getAinVoltCalibrated(caliInfo, (uint8)(0x00), AIN_RESOLUTION, voltageBytes, &(voltages[scanNumber][currChannel])); currChannel++; if( currChannel >= NUM_CHANNELS ) { currChannel = 0; scanNumber++; } } if( packetCounter >= 255 ) packetCounter = 0; else packetCounter++; //Handle Comm buffer overflow by stopping, flushing and restarting stream if( overflow == 1 ) { printf("\nRestarting stream...\n"); doFlush(hDevice); if( StreamConfig_example(hDevice) != 0 ) { printf("Error restarting StreamConfig.\n"); return -1; } if( StreamStart(hDevice) != 0 ) { printf("Error restarting StreamStart.\n"); return -1; } packetCounter = 0; break; } } } printf("\nNumber of scans: %d\n", scanNumber); printf("Total packets read: %d\n", totalPackets); printf("Current PacketCounter: %d\n", ((packetCounter == 0) ? 255 : packetCounter-1)); printf("Current Comm backlog: %d\n", backLog); for( k = 0; k < NUM_CHANNELS; k++ ) printf(" AIN%d: %.4f V\n", k, voltages[scanNumber - 1][k]); } endTime = getTickCount(); printf("\nRate of samples: %.0lf samples per second\n", (scanNumber*NUM_CHANNELS)/((endTime - startTime)/1000.0)); printf("Rate of scans: %.0lf scans per second\n\n", scanNumber/((endTime - startTime)/1000.0)); return 0; } //Sends a StreamStop low-level command to stop streaming. int StreamStop(HANDLE hDevice) { uint8 sendBuff[2], recBuff[4]; int sendChars, recChars; sendBuff[0] = (uint8)(0xB0); //CheckSum8 sendBuff[1] = (uint8)(0xB0); //Command byte //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed (StreamStop).\n"); else printf("Error : did not write all of the buffer (StreamStop).\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 4); if( recChars < 4 ) { if( recChars == 0 ) printf("Error : read failed (StreamStop).\n"); else printf("Error : did not read all of the buffer (StreamStop).\n"); return -1; } if( normalChecksum8(recBuff, 4) != recBuff[0] ) { printf("Error : read buffer has bad checksum8 (StreamStop).\n"); return -1; } if( recBuff[1] != (uint8)(0xB1) ) { printf("Error : read buffer has wrong command byte (StreamStop).\n"); return -1; } if( recBuff[2] != 0 ) { printf("Errorcode # %d from StreamStop read.\n", (unsigned int)recBuff[2]); return -1; } return 0; } //Sends a FlushBuffer low-level command to clear the stream buffer. int flushStream(HANDLE hDevice) { uint8 sendBuff[2], recBuff[2]; int sendChars, recChars; sendBuff[0] = (uint8)(0x08); //CheckSum8 sendBuff[1] = (uint8)(0x08); //Command byte //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 2); if( sendChars < 2 ) { if( sendChars == 0 ) printf("Error : write failed (flushStream).\n"); else printf("Error : did not write all of the buffer (flushStream).\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 2); if( recChars < 2 ) { if( recChars == 0 ) printf("Error : read failed (flushStream).\n"); else printf("Error : did not read all of the buffer (flushStream).\n"); return -1; } if( recBuff[0] != (uint8)(0x08) || recBuff[1] != (uint8)(0x08) ) { printf("Error : read buffer has wrong command byte (flushStream).\n"); return -1; } return 0; } //Runs StreamStop and flushStream low-level functions to flush out the //streaming buffer. Also reads 128 bytes from streaming endpoint to clear any //left over data. If there is nothing to read from the streaming endpoint, //then there will be a timeout delay. This function is useful for stopping //streaming and clearing it after a Comm buffer overflow. int doFlush(HANDLE hDevice) { uint8 recBuff[192]; printf("Flushing stream and reading left over data.\n"); StreamStop(hDevice); flushStream(hDevice); LJUSB_Stream(hDevice, recBuff, 192); return 0; }
511
./exodriver/examples/UE9/ue9ControlConfig.c
//Author: LabJack //May 25, 2011 //This example program sends a ControlConfig low-level command, and reads the //various parameters associated with the Control processor. #include "ue9.h" int controlConfig_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from UE9 if(getCalibrationInfo(hDevice, &caliInfo) < 0) goto close; controlConfig_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends a ControlConfig low-level command to read the configuration settings //associated with the Control chip. int controlConfig_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { uint8 sendBuff[18], recBuff[24]; uint16 checksumTotal; int sendChars, recChars, i; double dac; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x06); //Number of data words sendBuff[3] = (uint8)(0x08); //Extended command number //WriteMask, PowerLevel, FIODir, etc. are all passed a value of zero since //we only want to read Control configuration settings, not change them. for( i = 6; i < 18; i++ ) sendBuff[i] = (uint8)(0x00); extendedChecksum(sendBuff,18); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 18); if( sendChars < 18 ) { if( sendChars == 0 ) printf("Error : write failed\n"); else printf("Error : did not write all of the buffer\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 24); if( recChars < 24 ) { if( recChars == 0 ) printf("Error : read failed\n"); else printf("Error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 24); if( (uint8)((checksumTotal >> 8) & 0xff) != recBuff[5] ) { printf("Error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4] ) { printf("Error : read buffer has bad checksum16(LSB)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x09) || recBuff[3] != (uint8)(0x08) ) { printf("Error : read buffer has wrong command bytes \n"); return -1; } if( recBuff[6] != 0 ) { printf("Errorcode (byte 6): %d\n", (unsigned int)recBuff[6]); return -1; } printf("PowerLevel default (byte 7): %d\n", (unsigned int)recBuff[7]); printf("ResetSource (byte 8): %d\n", (unsigned int)recBuff[8]); printf("ControlFW Version (bytes 9 and 10): %.3f\n", (unsigned int)recBuff[10] + (double)recBuff[9]/100.0); printf("ControlBL Version (bytes 11 and 12): %.3f\n", (unsigned int)recBuff[12] + (double)recBuff[11]/100.0); printf("FIO default directions and states (bytes 14 and 15):\n"); for( i = 0; i < 8; i++ ) printf(" FIO%d: %d and %d\n", i,( (unsigned int)recBuff[14] << (31 - i) ) >> 31, ( (unsigned int)recBuff[15] << (31 - i) ) >> 31); printf("EIO default directions and states (bytes 16 and 17):\n"); for( i = 0; i < 8; i++ ) printf(" EIO%d: %d and %d\n", i, ( (unsigned int)recBuff[16] << (31 - i) ) >> 31, ( (unsigned int)recBuff[17] << (31 - i) ) >> 31); printf("CIO default directions and states (byte 18):\n"); for( i = 0; i <= 3; i++ ) printf(" CIO%d: %d and %d\n", i, ( (unsigned int)recBuff[18] << (27 - i) ) >> 31, ( (unsigned int)recBuff[18] << (31 - i) ) >> 31); printf("MIO default directions and states (byte 19):\n"); for( i = 0; i <= 2; i++ ) printf(" MIO%d: %d and %d\n", i, ( (unsigned int)recBuff[19] << (27 - i) ) >> 31, ( (unsigned int)recBuff[19] << (31 - i) ) >> 31); printf("DAC0 default (bytes 20 and 21):\n Enabled: %d\n Update: %d\n", ( (unsigned int)recBuff[21] << 24 ) >> 31, ( (unsigned int)recBuff[21] << 25 ) >> 31); //Getting DAC0 binary value dac = (double)( (unsigned int)recBuff[20] + (( (unsigned int)recBuff[21] << 28 ) >> 20) ); //Getting DAC0 analog value ( Volts = (Bits - Offset)/Slope ) dac = (dac - caliInfo->ccConstants[11])/caliInfo->ccConstants[10]; printf(" Voltage: %.3f V\n", dac); printf("DAC1 default (bytes 22 and 23):\n Enabled: %d\n Update: %d\n", ( (unsigned int)recBuff[23] << 24 ) >> 31, ( (unsigned int)recBuff[23] << 25 ) >> 31); //getting DAC1 binary value dac = (double)( (unsigned int)recBuff[22] + (( (unsigned int)recBuff[23] << 28 ) >> 20) ); //getting DAC1 analog value ( Volts = (Bits - Offset)/Slope ) dac = (dac - caliInfo->ccConstants[13])/caliInfo->ccConstants[12]; printf(" Voltage: %.3f V\n", dac); return 0; }
512
./exodriver/examples/UE9/ue9.c
//Author: LabJack //May 25, 2011 //Example UE9 helper functions. Function descriptions are in ue9.h. #include "ue9.h" ue9CalibrationInfo UE9_CALIBRATION_INFO_DEFAULT = { 9, //Nominal Values { 0.000077503, -0.012, 0.000038736, -0.012, 0.000019353, -0.012, 0.0000096764, -0.012, 0.00015629, -5.176, 842.59, 0.0, 842.259, 0.0, 0.012968, 0.012968, 298.15, 2.43, 0.0, 1.215, 0.00009272, 0.000077503, -0.012, 0.00015629, -5.176} }; void normalChecksum(uint8 *b, int n) { b[0] = normalChecksum8(b,n); } void extendedChecksum(uint8 *b, int n) { uint16 a; a = extendedChecksum16(b,n); b[4] = (uint8)(a & 0xFF); b[5] = (uint8)((a/256) & 0xFF); b[0] = extendedChecksum8(b); } uint8 normalChecksum8(uint8 *b, int n) { int i; uint16 a, bb; //Sums bytes 1 to n-1 unsigned to a 2 byte value. Sums quotient and //remainder of 256 division. Again, sums quotient and remainder of //256 division. for( i = 1, a = 0; i < n; i++ ) a += (uint16)b[i]; bb = a/256; a = (a - 256*bb) + bb; bb = a/256; return (uint8)((a - 256*bb) + bb); } uint16 extendedChecksum16(uint8 *b, int n) { int i, a = 0; //Sums bytes 6 to n-1 to a unsigned 2 byte value for( i = 6; i < n; i++ ) a += (uint16)b[i]; return a; } uint8 extendedChecksum8(uint8 *b) { int i, a, bb; //Sums bytes 1 to 5. Sums quotient and remainder of 256 division. Again, sums //quotient and remainder of 256 division. for( i = 1, a = 0; i < 6; i++ ) a += (uint16)b[i]; bb = a/256; a = (a - 256*bb) + bb; bb = a/256; return (uint8)((a - 256*bb) + bb); } HANDLE openUSBConnection(int localID) { BYTE buffer[38]; uint16 checksumTotal = 0; uint32 numDevices = 0; uint32 dev; int i, serial; HANDLE hDevice = 0; numDevices = LJUSB_GetDevCount(UE9_PRODUCT_ID); if( numDevices == 0 ) { printf("Open error: No UE9 devices could be found\n"); return NULL; } for( dev = 1; dev <= numDevices; dev++ ) { hDevice = LJUSB_OpenDevice(dev, 0, UE9_PRODUCT_ID); if( hDevice != NULL ) { if( localID < 0 ) { return hDevice; } else { checksumTotal = 0; //Setting up a CommConfig command buffer[1] = (BYTE)(0x78); buffer[2] = (BYTE)(0x10); buffer[3] = (BYTE)(0x01); for( i = 6; i < 38; i++ ) buffer[i] = (BYTE)(0x00); extendedChecksum(buffer,38); if( LJUSB_Write(hDevice, buffer, 38) != 38 ) goto locid_error; for( i = 0; i < 38; i++ ) buffer[i] = 0; if( LJUSB_Read(hDevice, buffer, 38) != 38 ) goto locid_error; checksumTotal = extendedChecksum16(buffer, 38); if( (BYTE)((checksumTotal / 256) & 0xFF) != buffer[5] ) goto locid_error; if( (BYTE)(checksumTotal & 0xFF) != buffer[4] ) goto locid_error; if( extendedChecksum8(buffer) != buffer[0] ) goto locid_error; if( buffer[1] != (BYTE)(0x78) || buffer[2] != (BYTE)(0x10) || buffer[3] != (BYTE)(0x01) ) goto locid_error; //Check local ID if( (int)buffer[8] == localID ) return hDevice; //Check serial number serial = buffer[28] + buffer[29]*256 + buffer[30]*65536 + 0x10000000; if( serial == localID ) return hDevice; //No matches. Not our device. LJUSB_CloseDevice(hDevice); } //else localID >= 0 end } //if hDevice != NULL end } //for end printf("Open error: could not find a UE9 with a local ID or serial number of %d\n", localID); return NULL; locid_error: printf("Open error: problem when checking local ID and serial number\n"); return NULL; } void closeUSBConnection(HANDLE hDevice) { LJUSB_CloseDevice(hDevice); } long getTickCount() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); } long getCalibrationInfo(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { BYTE sendBuffer[8], recBuffer[136]; int sentRec = 0, i = 0, j = 0, ccTotal = 0, count = 0; /* Setting up command */ sendBuffer[1] = (BYTE)(0xF8); //command byte sendBuffer[2] = (BYTE)(0x01); //number of data words sendBuffer[3] = (BYTE)(0x2A); //extended command number sendBuffer[6] = (BYTE)(0x00); for( i = 0; i < 5; i++ ) { /* Reading block 1 from memory */ sendBuffer[7] = (BYTE)i; //Blocknum = i extendedChecksum(sendBuffer, 8); sentRec = LJUSB_Write(hDevice, sendBuffer, 8); if( sentRec < 8 ) { if( sentRec == 0 ) printf("getCalibrationInfo error : write failed\n"); else printf("getCalibrationInfo error : did not write all of the buffer\n"); return -1; } sentRec = LJUSB_Read(hDevice, recBuffer, 136); if( sentRec < 136 ) { if( sentRec == 0 ) printf("getCalibrationInfo Error : read failed\n"); else printf("getCalibrationInfo Error : did not read all of the buffer\n"); } if( recBuffer[1] != (BYTE)(0xF8) || recBuffer[2] != (BYTE)(0x41) || recBuffer[3] != (BYTE)(0x2A) ) { printf("getCalibrationInfo error: incorrect command bytes for ReadMem response"); return -1; } //Reading out calbration constants if( i == 0 ) ccTotal = 8; if( i == 1 ) ccTotal = 2; if( i == 2 ) ccTotal = 13; if( i == 3 ) ccTotal = 2; if( i == 4 ) ccTotal = 2; for( j = 0; j < ccTotal; j++ ) { if( i != 2 || (i == 2 && j != 5 && j != 7) ) { //Block data starts on byte 8 of the buffer caliInfo->ccConstants[count] = FPuint8ArrayToFPDouble(recBuffer + 8, j*8); count++; } } } caliInfo->prodID = 9; return 0; } long getTdacCalibrationInfo(HANDLE hDevice, ue9TdacCalibrationInfo *caliInfo, uint8 DIOAPinNum) { int err; uint8 options, speedAdjust, sdaPinNum, sclPinNum; uint8 address, numByteToSend, numBytesToReceive, errorcode; uint8 bytesCommand[1]; uint8 bytesResponse[32]; uint8 ackArray[4]; err = 0; //Setting up I2C command for LJTDAC options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about 130 kHz) sdaPinNum = DIOAPinNum+1; //SDAPinNum : FIO channel connected to pin DIOB sclPinNum = DIOAPinNum; //SCLPinNum : FIO channel connected to pin DIOA address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numByteToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 32; //NumI2CBytesToReceive : getting 32 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 64; //I2CByte0 : Memory Address (starting at address 64 (DACA Slope) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numByteToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( errorcode != 0 ) { printf("Getting LJTDAC calibration info error : received errorcode %d in response\n", errorcode); err = -1; } if( err == -1 ) return err; caliInfo->ccConstants[0] = FPuint8ArrayToFPDouble(bytesResponse, 0); caliInfo->ccConstants[1] = FPuint8ArrayToFPDouble(bytesResponse, 8); caliInfo->ccConstants[2] = FPuint8ArrayToFPDouble(bytesResponse, 16); caliInfo->ccConstants[3] = FPuint8ArrayToFPDouble(bytesResponse, 24); caliInfo->prodID = 9; return err; } double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) { uint32 resultDec = 0, resultWh = 0; resultDec = (uint32)buffer[startIndex] | ((uint32)buffer[startIndex + 1] << 8) | ((uint32)buffer[startIndex + 2] << 16) | ((uint32)buffer[startIndex + 3] << 24); resultWh = (uint32)buffer[startIndex + 4] | ((uint32)buffer[startIndex + 5] << 8) | ((uint32)buffer[startIndex + 6] << 16) | ((uint32)buffer[startIndex + 7] << 24); return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); } long isCalibrationInfoValid(ue9CalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 9 ) goto invalid; return 1; invalid: printf("Error: Invalid calibration info.\n"); return 0; } long isTdacCalibrationInfoValid(ue9TdacCalibrationInfo *caliInfo) { if( caliInfo == NULL ) goto invalid; if( caliInfo->prodID != 9 ) goto invalid; return 1; invalid: printf("Error: Invalid LJTDAC calibration info.\n"); return 0; } long getAinVoltCalibrated(ue9CalibrationInfo *caliInfo, uint8 gainBip, uint8 resolution, uint16 bytesVolt, double *analogVolt) { if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( resolution < 18 ) { if( gainBip <= 3 || gainBip == 8 ) { if( gainBip == 8 ) gainBip = 4; //setting this for index purposes *analogVolt = (caliInfo->ccConstants[gainBip*2]*bytesVolt) + caliInfo->ccConstants[gainBip*2 + 1]; return 0; } else goto invalidGainBip; } else //UE9 Pro high res { if( gainBip == 0 || gainBip == 8 ) { if( gainBip == 8 ) gainBip = 1; //setting this for index purposes *analogVolt = (caliInfo->ccConstants[gainBip*2 + 21]*bytesVolt) + caliInfo->ccConstants[gainBip*2 + 22]; return 0; } else goto invalidGainBip; } invalidGainBip: printf("getAinVoltCalibrated error: invalid GainBip.\n"); return -1; } long getDacBinVoltCalibrated(ue9CalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt) { double tBytesVolt; if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getDacBinVoltCalibrated error: invalid channelNumber.\n"); return -1; } tBytesVolt = analogVolt*caliInfo->ccConstants[10 + dacNumber*2] + caliInfo->ccConstants[11 + dacNumber*2]; //Checking to make sure bytesVoltage will be a value between 0 and 4095, or //that a uint16 overflow does not occur. A too high analogVoltage (above 5 //volts) or too low analogVoltage (below 0 volts) will cause a value not //between 0 and 4095. if( tBytesVolt < 0 ) tBytesVolt = 0; if( tBytesVolt > 4095 ) tBytesVolt = 4095; *bytesVolt = (uint16)tBytesVolt; return 0; } long getTdacBinVoltCalibrated(ue9TdacCalibrationInfo *caliInfo, int dacNumber, double analogVolt, uint16 *bytesVolt) { uint32 tBytesVolt; if( isTdacCalibrationInfoValid(caliInfo) == 0 ) return -1; if( dacNumber < 0 || dacNumber > 2 ) { printf("getTdacBinVoltCalibrated error: invalid channelNumber.\n"); return -1; } tBytesVolt = analogVolt*caliInfo->ccConstants[dacNumber*2] + caliInfo->ccConstants[dacNumber*2 + 1]; //Checking to make sure bytesVolt will be a value between 0 and 65535. if( tBytesVolt > 65535 ) tBytesVolt = 65535; *bytesVolt = (uint16)tBytesVolt; return 0; } long getTempKCalibrated(ue9CalibrationInfo *caliInfo, int powerLevel, uint16 bytesTemp, double *kelvinTemp) { if( isCalibrationInfoValid(caliInfo) == 0 ) return -1; if( powerLevel == 0 || powerLevel == 1 ) { *kelvinTemp = caliInfo->ccConstants[14 + powerLevel]*bytesTemp; return 0; } else { printf("getTempKCalibrated error: invalid powerLevel.\n"); return -1; } } long getAinVoltUncalibrated(uint8 gainBip, uint8 resolution, uint16 bytesVolt, double *analogVolt) { return getAinVoltCalibrated(&UE9_CALIBRATION_INFO_DEFAULT, gainBip, resolution, bytesVolt, analogVolt); } long getDacBinVoltUncalibrated(int dacNumber, double analogVolt, uint16 *bytesVolt) { return getDacBinVoltCalibrated(&UE9_CALIBRATION_INFO_DEFAULT, dacNumber, analogVolt, bytesVolt); } long getTempKUncalibrated(int powerLevel, uint16 bytesTemp, double *kelvinTemp) { return getTempKCalibrated(&UE9_CALIBRATION_INFO_DEFAULT, powerLevel, bytesTemp, kelvinTemp); } long I2C(HANDLE hDevice, uint8 I2COptions, uint8 SpeedAdjust, uint8 SDAPinNum, uint8 SCLPinNum, uint8 Address, uint8 NumI2CBytesToSend, uint8 NumI2CBytesToReceive, uint8 *I2CBytesCommand, uint8 *Errorcode, uint8 *AckArray, uint8 *I2CBytesResponse) { uint8 *sendBuff, *recBuff; uint16 checksumTotal = 0; uint32 ackArrayTotal, expectedAckArray; int sendChars, recChars, sendSize, recSize, i, ret; *Errorcode = 0; ret = 0; sendSize = 6 + 8 + ((NumI2CBytesToSend%2 != 0)?(NumI2CBytesToSend + 1):(NumI2CBytesToSend)); recSize = 6 + 6 + ((NumI2CBytesToReceive%2 != 0)?(NumI2CBytesToReceive + 1):(NumI2CBytesToReceive)); sendBuff = (uint8 *)malloc(sizeof(uint8)*sendSize); recBuff = (uint8 *)malloc(sizeof(uint8)*recSize); sendBuff[sendSize - 1] = 0; //I2C command sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (sendSize - 6)/2; //Number of data words = 4 + NumI2CBytesToSend sendBuff[3] = (uint8)(0x3B); //Extended command number sendBuff[6] = I2COptions; //I2COptions sendBuff[7] = SpeedAdjust; //SpeedAdjust sendBuff[8] = SDAPinNum; //SDAPinNum sendBuff[9] = SCLPinNum; //SCLPinNum sendBuff[10] = Address; //Address sendBuff[11] = 0; //Reserved sendBuff[12] = NumI2CBytesToSend; //NumI2CByteToSend sendBuff[13] = NumI2CBytesToReceive; //NumI2CBytesToReceive for( i = 0; i < NumI2CBytesToSend; i++ ) sendBuff[14 + i] = I2CBytesCommand[i]; //I2CByte extendedChecksum(sendBuff, sendSize); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, sendSize); if( sendChars < sendSize ) { if( sendChars == 0 ) printf("I2C Error : write failed\n"); else printf("I2C Error : did not write all of the buffer\n"); ret = -1; goto cleanmem; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, recSize); if( recChars < recSize ) { if( recChars == 0 ) printf("I2C Error : read failed\n"); else { printf("I2C Error : did not read all of the buffer\n"); if( recChars >= 12 ) *Errorcode = recBuff[6]; } ret = -1; goto cleanmem; } *Errorcode = recBuff[6]; AckArray[0] = recBuff[8]; AckArray[1] = recBuff[9]; AckArray[2] = recBuff[10]; AckArray[3] = recBuff[11]; for( i = 0; i < NumI2CBytesToReceive; i++ ) I2CBytesResponse[i] = recBuff[12 + i]; if( (uint8)(extendedChecksum8(recBuff)) != recBuff[0] ) { printf("I2C Error : read buffer has bad checksum (%d)\n", recBuff[0]); ret = -1; } if( recBuff[1] != (uint8)(0xF8) ) { printf("I2C Error : read buffer has incorrect command byte (%d)\n", recBuff[1]); ret = -1; } if( recBuff[2] != (uint8)((recSize - 6)/2) ) { printf("I2C Error : read buffer has incorrect number of data words (%d)\n", recBuff[2]); ret = -1; } if( recBuff[3] != (uint8)(0x3B) ) { printf("I2C Error : read buffer has incorrect extended command number (%d)\n", recBuff[3]); ret = -1; } checksumTotal = extendedChecksum16(recBuff, recSize); if( (uint8)((checksumTotal / 256) & 0xFF) != recBuff[5] || (uint8)(checksumTotal & 0xFF) != recBuff[4] ) { printf("I2C error : read buffer has bad checksum16 (%u)\n", checksumTotal); ret = -1; } //ackArray should ack the Address byte in the first ack bit, but did not until control firmware 1.84 ackArrayTotal = AckArray[0] + AckArray[1]*256 + AckArray[2]*65536 + AckArray[3]*16777216; expectedAckArray = pow(2.0, NumI2CBytesToSend+1) - 1; if( ackArrayTotal != expectedAckArray ) printf("I2C error : expected an ack of %u, but received %u\n", expectedAckArray, ackArrayTotal); cleanmem: free(sendBuff); free(recBuff); sendBuff = NULL; recBuff = NULL; return ret; } long eAIN(HANDLE Handle, ue9CalibrationInfo *CalibrationInfo, long ChannelP, long ChannelN, double *Voltage, long Range, long Resolution, long Settling, long Binary, long Reserved1, long Reserved2) { uint8 IOType, Channel, AINM, AINH, ainGain; uint16 bytesVT; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eAIN error: calibration information is required"); return -1; } if( Range == LJ_rgBIP5V ) ainGain = 8; else if( Range == LJ_rgUNI5V ) ainGain = 0; else if( Range == LJ_rgUNI2P5V ) ainGain = 1; else if( Range == LJ_rgUNI1P25V ) ainGain = 2; else if( Range == LJ_rgUNIP625V ) ainGain = 3; else { printf("eAIN error: Invalid Range\n"); return -1; } if( ehSingleIO(Handle, 4, (uint8)ChannelP, ainGain, (uint8)Resolution, (uint8)Settling, &IOType, &Channel, NULL, &AINM, &AINH) < 0 ) return -1; bytesVT = AINM + AINH*256; if( Binary != 0 ) { *Voltage = (double)bytesVT; } else { if( ChannelP == 133 || ChannelP == 141 ) { if( getTempKCalibrated(CalibrationInfo, 0, bytesVT, Voltage) < 0 ) return -1; } else { if( getAinVoltCalibrated(CalibrationInfo, ainGain, (uint8)Resolution, bytesVT, Voltage) < 0 ) return -1; } } return 0; } long eDAC(HANDLE Handle, ue9CalibrationInfo *CalibrationInfo, long Channel, double Voltage, long Binary, long Reserved1, long Reserved2) { uint8 IOType, channel; uint16 bytesVoltage; if( isCalibrationInfoValid(CalibrationInfo) == 0 ) { printf("eDAC error: calibration information is required"); return -1; } if( getDacBinVoltCalibrated(CalibrationInfo, (uint8)Channel, Voltage, &bytesVoltage) < 0 ) return -1; return ehSingleIO(Handle, 5, (uint8)Channel, (uint8)( bytesVoltage & (0x00FF) ), (uint8)(( bytesVoltage /256 ) + 192), 0, &IOType, &channel, NULL, NULL, NULL); } long eDI(HANDLE Handle, long Channel, long *State) { uint8 state; if( Channel > 22 ) { printf("eDI error: Invalid Channel"); return -1; } if( ehDIO_Feedback(Handle, (uint8)Channel, 0, &state) < 0 ) return -1; *State = state; return 0; } long eDO(HANDLE Handle, long Channel, long State) { uint8 state; state = (uint8)State; if( Channel > 22 ) { printf("eDO error: Invalid Channel"); return -1; } return ehDIO_Feedback(Handle, (uint8)Channel, 1, &state); } long eTCConfig(HANDLE Handle, long *aEnableTimers, long *aEnableCounters, long TCPinOffset, long TimerClockBaseIndex, long TimerClockDivisor, long *aTimerModes, double *aTimerValues, long Reserved1, long Reserved2) { uint8 enableMask, timerMode[6], counterMode[2]; uint16 timerValue[6]; int numTimers, numTimersStop, i; //Setting EnableMask enableMask = 128; //Bit 7: UpdateConfig if(aEnableCounters[1] != 0) enableMask += 16; //Bit 4: Enable Counter1 if(aEnableCounters[0] |= 0) enableMask += 8; //Bit 3: Enable Counter0 numTimers = 0; numTimersStop = 0; for( i = 0; i < 6; i++ ) { if( aEnableTimers[i] != 0 && numTimersStop == 0 ) { numTimers++; timerMode[i] = (uint8)aTimerModes[i]; //TimerMode timerValue[i] = (uint16)aTimerValues[i]; //TimerValue } else { numTimersStop = 1; timerMode[i] = 0; timerValue[i] = 0; } } enableMask += numTimers; //Bits 2-0: Number of Timers counterMode[0] = 0; //Counter0Mode counterMode[1] = 0; //Counter1Mode return ehTimerCounter(Handle, (uint8)TimerClockDivisor, enableMask, (uint8)TimerClockBaseIndex, 0, timerMode, timerValue, counterMode, NULL, NULL); } long eTCValues(HANDLE Handle, long *aReadTimers, long *aUpdateResetTimers, long *aReadCounters, long *aResetCounters, double *aTimerValues, double *aCounterValues, long Reserved1, long Reserved2) { uint8 updateReset, timerMode[6], counterMode[2]; uint16 timerValue[6]; uint32 timer[6], counter[2]; int i; long errorcode; //UpdateReset updateReset = 0; for( i = 0; i < 6; i++ ) { updateReset += ((aUpdateResetTimers[i] != 0) ? pow(2, i) : 0); timerMode[i] = 0; timerValue[i] = 0; } for( i = 0; i < 2; i++ ) { updateReset += ((aResetCounters[i] != 0) ? pow(2, 6 + i) : 0); counterMode[i] = 0; } if( (errorcode = ehTimerCounter(Handle, 0, 0, 0, updateReset, timerMode, timerValue, counterMode, timer, counter)) != 0 ) return errorcode; for( i = 0; i < 6; i++ ) aTimerValues[i] = timer[i]; for( i = 0; i < 2; i++ ) aCounterValues[i] = counter[i]; return 0; } long ehSingleIO(HANDLE hDevice, uint8 inIOType, uint8 inChannel, uint8 inDirBipGainDACL, uint8 inStateResDACH, uint8 inSettlingTime, uint8 *outIOType, uint8 *outChannel, uint8 *outDirAINL, uint8 *outStateAINM, uint8 *outAINH) { BYTE sendBuff[8], recBuff[8]; int sendChars, recChars; sendBuff[1] = (BYTE)(0xA3); //Command byte sendBuff[2] = inIOType; //IOType sendBuff[3] = inChannel; //Channel sendBuff[4] = inDirBipGainDACL; //Dir/BipGain/DACL sendBuff[5] = inStateResDACH; //State/Resolution/DACH sendBuff[6] = inSettlingTime; //Settling time sendBuff[7] = 0; //Reserved sendBuff[0] = normalChecksum8(sendBuff, 8); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 8); if( sendChars < 8 ) { if( sendChars == 0 ) printf("SingleIO error : write failed\n"); else printf("SingleIO error : did not write all of the buffer\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 8); if( recChars < 8 ) { if( recChars == 0 ) printf("SingleIO error : read failed\n"); else printf("SingleIO error : did not read all of the buffer\n"); return -1; } if( (BYTE)(normalChecksum8(recBuff, 8)) != recBuff[0] ) { printf("SingleIO error : read buffer has bad checksum\n"); return -1; } if( recBuff[1] != (BYTE)(0xA3) ) { printf("SingleIO error : read buffer has wrong command byte\n"); return -1; } if( outIOType != NULL ) *outIOType = recBuff[2]; if( outChannel != NULL ) *outChannel = recBuff[3]; if( outDirAINL != NULL ) *outDirAINL = recBuff[4]; if( outStateAINM != NULL ) *outStateAINM = recBuff[5]; if( outAINH != NULL ) *outAINH = recBuff[6]; return 0; } long ehDIO_Feedback(HANDLE hDevice, uint8 channel, uint8 direction, uint8 *state) { BYTE sendBuff[34], recBuff[64]; BYTE tempDir, tempState, tempByte; uint16 checksumTotal; int sendChars, recChars, i; sendBuff[1] = (BYTE)(0xF8); //Command byte sendBuff[2] = (BYTE)(0x0E); //Number of data words sendBuff[3] = (BYTE)(0x00); //Extended command number for( i = 6; i < 34; i++ ) sendBuff[i] = 0; tempDir = ((direction < 1) ? 0 : 1); tempState = ((*state < 1) ? 0 : 1); if( channel <= 7 ) { tempByte = pow(2, channel); sendBuff[6] = tempByte; if( tempDir ) sendBuff[7] = tempByte; if( tempState ) sendBuff[8] = tempByte; } else if( channel <= 15 ) { tempByte = pow(2, (channel - 8)); sendBuff[9] = tempByte; if( tempDir ) sendBuff[10] = tempByte; if( tempState ) sendBuff[11] = tempByte; } else if( channel <= 19 ) { tempByte = pow(2, (channel - 16)); sendBuff[12] = tempByte; if( tempDir ) sendBuff[13] = tempByte*16; if( tempState ) sendBuff[13] += tempByte; } else if( channel <= 22 ) { tempByte = pow(2, (channel - 20)); sendBuff[14] = tempByte; if( tempDir ) sendBuff[15] = tempByte*16; if( tempState ) sendBuff[15] += tempByte; } else { printf("DIO Feedback error: Invalid Channel\n"); return -1; } extendedChecksum(sendBuff, 34); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 34); if( sendChars < 34 ) { if( sendChars == 0 ) printf("DIO Feedback error : write failed\n"); else printf("DIO Feedback error : did not write all of the buffer\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 64); if( recChars < 64 ) { if( recChars == 0 ) printf("DIO Feedback error : read failed\n"); else printf("DIO Feedback error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 64); if( (BYTE)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("DIO Feedback error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (BYTE)(checksumTotal & 0xFF) != recBuff[4] ) { printf("DIO Feedback error : read buffer has bad checksum16(LSB)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("DIO Feedback error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (BYTE)(0xF8) || recBuff[2] != (BYTE)(0x1D) || recBuff[3] != (BYTE)(0x00) ) { printf("DIO Feedback error : read buffer has wrong command bytes\n"); return -1; } if( channel <= 7 ) *state = ((recBuff[7] & tempByte) ? 1 : 0); else if( channel <= 15 ) *state = ((recBuff[9] & tempByte) ? 1 : 0); else if( channel <= 19 ) *state = ((recBuff[10] & tempByte) ? 1 : 0); else if( channel <= 22 ) *state = ((recBuff[11] & tempByte) ? 1 : 0); return 0; } long ehTimerCounter(HANDLE hDevice, uint8 inTimerClockDivisor, uint8 inEnableMask, uint8 inTimerClockBase, uint8 inUpdateReset, uint8 *inTimerMode, uint16 *inTimerValue, uint8 *inCounterMode, uint32 *outTimer, uint32 *outCounter) { BYTE sendBuff[30], recBuff[40]; uint16 checksumTotal; int sendChars, recChars, i, j; sendBuff[1] = (BYTE)(0xF8); //Command byte sendBuff[2] = (BYTE)(0x0C); //Number of data words sendBuff[3] = (BYTE)(0x18); //Extended command number sendBuff[6] = inTimerClockDivisor; //TimerClockDivisor sendBuff[7] = inEnableMask; //EnableMask sendBuff[8] = inTimerClockBase; //TimerClockBase sendBuff[9] = inUpdateReset; //UpdateReset for( i = 0; i < 6; i++ ) { sendBuff[10 + i*3] = inTimerMode[i]; //TimerMode sendBuff[11 + i*3] = (BYTE)(inTimerValue[i] & 0x00FF); //TimerValue (low byte) sendBuff[12 + i*3] = (BYTE)((inTimerValue[i] & 0xFF00)/256); //TimerValue (high byte) } for( i = 0; i < 2; i++ ) sendBuff[28 + i] = inCounterMode[i]; //CounterMode extendedChecksum(sendBuff, 30); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 30); if( sendChars < 30 ) { if( sendChars == 0 ) printf("ehTimerCounter error : write failed\n"); else printf("ehTimerCounter error : did not write all of the buffer\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 40); if( recChars < 40 ) { if( recChars == 0 ) printf("ehTimerCounter error : read failed\n"); else printf("ehTimerCounter error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 40); if( (BYTE)((checksumTotal / 256) & 0xFF) != recBuff[5] ) { printf("ehTimerCounter error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (BYTE)(checksumTotal & 0xFF) != recBuff[4] ) { printf("ehTimerCounter error : read buffer has bad checksum16(LBS)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("ehTimerCounter error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (BYTE)(0xF8) || recBuff[2] != (BYTE)(0x11) || recBuff[3] != (BYTE)(0x18) ) { printf("ehTimerCounter error : read buffer has wrong command bytes for TimerCounter\n"); return -1; } if( outTimer != NULL ) { for( i = 0; i < 6; i++ ) { outTimer[i] = 0; for( j = 0; j < 4; j++ ) outTimer[i] += recBuff[8 + j + i*4] * pow(2, 8*j); } } if( outCounter != NULL ) { for( i = 0; i < 2; i++ ) { outCounter[i] = 0; for( j = 0; j < 4; j++ ) outCounter[i] += recBuff[32 + j + i*4] * pow(2, 8*j); } } return recBuff[6]; }
513
./exodriver/examples/UE9/ue9allio.c
//Author : LabJack //May 25, 2011 //This example demonstrates how to write and read some or all analog and digital //I/O. It records the time for 1000 iterations and divides by 1000, to allow //measurement of the basic command/response communication times. These times //should be comparable to the Windows command/response communication times //documented in Section 3.1 of the UE9 User's Guide. #include "ue9.h" int allIO(HANDLE hDevice, ue9CalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from UE9 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; allIO(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends 1000 Feedback low-level commands to read digital IO and analog inputs. //On the first send, the following are set: DAC0 to 2.5 volts, DAC1 to 3.5 //volts, and digital IOs to inputs. int allIO(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { uint8 sendBuff[34], recBuff[64], settlingTime; uint8 numChannels; //Number of AIN channels, 0-16. uint16 checksumTotal, bytesVoltage, ainMask; int sendChars, recChars, i, j; int initialize; //boolean to init. DAC and digital IO settings int numIterations, valueDIPort; long time, ainResolution; double valueAIN[16]; numIterations = 1000; initialize = 1; time = 0; numChannels = 8; ainResolution = 12; for( i = 0; i < 16; i++ ) valueAIN[i] = 9999.0; settlingTime = 0; ainMask = pow(2.0, numChannels) - 1; sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x0E); //Number of data words sendBuff[3] = (uint8)(0x00); //Extended command number sendBuff[6] = 255; //FIOMask : setting the mask of all FIOs sendBuff[7] = 0; //FIODir : setting all FIO directions to input sendBuff[8] = 0; //FIOState : all FIO directions are input, so // state writes do not apply sendBuff[9] = 255; //EIOMask : setting the mask of all EIOs sendBuff[10] = 0; //EIODir : setting all EIO directions to input sendBuff[11] = 0; //EIOState : all EIO directions are input, so // state writes do not apply sendBuff[12] = 15; //CIOMask : setting the mask of all CIOs sendBuff[13] = 0; //CIODirState : setting all CIO directions to input, // state writes do not apply sendBuff[14] = 7; //MIOMask : setting the mask of all MIOs sendBuff[15] = 0; //MIODirState : setting all MIO directions to input, // state writes do not apply //Getting binary DAC0 value of 2.5 volts if( getDacBinVoltCalibrated(caliInfo, 0, 2.500, &bytesVoltage) < 0 ) return -1; //Setting the voltage of DAC0 to 2.5 sendBuff[16] = (uint8)(bytesVoltage & 255); //low bits of DAC0 sendBuff[17] = (uint8)(bytesVoltage/256) + 192; //high bits of DAC0 //(bit 7 : Enable, // bit 6: Update) //Getting binary DAC1 value of 3.5 volts if( getDacBinVoltCalibrated(caliInfo, 1, 3.500, &bytesVoltage) < 0 ) return -1; //Setting the voltage of DAC1 to 3.5 volts sendBuff[18] = (uint8)(bytesVoltage & 255); //low bits of DAC1 sendBuff[19] = (uint8)(bytesVoltage/256) + 192; //high bits of DAC1 //(bit 7 : Enable, // bit 6: Update) //AINMask - reading the number of AINs specified by numChannels sendBuff[20] = ainMask & 255; //AINMask (low byte) sendBuff[21] = ainMask/256; //AINMask (high byte) sendBuff[22] = 14; //AIN14ChannelNumber : setting to channel 14 sendBuff[23] = 15; //AIN15ChannelNumber : setting to channel 15 sendBuff[24] = ainResolution; //Resolution : Resolution specified by // ainResolution sendBuff[25] = settlingTime; //SettlingTime //Setting all BipGains (Gain = 1, Bipolar = 1) for( i = 26; i < 34; i++ ) sendBuff[i] = (uint8)(0x00); extendedChecksum(sendBuff, 34); time = getTickCount(); for( i = 0; i < numIterations; i++ ) { //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 34); if( sendChars < 34 ) { if( sendChars == 0 ) printf("Feedback error (Iteration %d) : write failed\n", i); else printf("Feedback error (Iteration %d) : did not write all of the buffer\n", i); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 64); if( recChars < 64 ) { if( recChars == 0 ) printf("Feedback error (Iteration %d) : read failed\n", i); else printf("Feedback error (Iteration %d) : did not read all of the buffer\n", i); return -1; } checksumTotal = extendedChecksum16(recBuff, 64); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("Feedback error (Iteration %d) : read buffer has bad checksum16(MSB)\n", i); return -1; } if( (uint8)(checksumTotal & 255) != recBuff[4] ) { printf("Feedback error (Iteration %d) : read buffer has bad checksum16(LSB)\n", i); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Feedback error (Iteration %d) : read buffer has bad checksum8\n", i); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x1D) || recBuff[3] != (uint8)(0x00) ) { printf("Feedback error (Iteration %d) : read buffer has wrong command bytes\n", i); return -1; } for( j = 0; j < numChannels && j < 16; j++ ) getAinVoltCalibrated(caliInfo, 0x00, (uint8)ainResolution, recBuff[12 + j*2] + recBuff[13 + j*2]*256, &valueAIN[j]); valueDIPort = recBuff[7] + recBuff[9]*256 + (recBuff[10] & 15)*65536 + (recBuff[11] & 7)*1048576; if( initialize == 1 ) { //Unsetting digital IO bit masks since we only want to read states now sendBuff[6] = 0; //FIOMask sendBuff[9] = 0; //EIOMask sendBuff[12] = 0; //CIOMask sendBuff[14] = 0; //MIOMask //Turning off Update bit of DACs sendBuff[17] = sendBuff[17] - 64; //high bits of DAC0 sendBuff[19] = sendBuff[19] - 64; //high bits of DAC1 extendedChecksum(sendBuff, 34); initialize = 0; } } time = getTickCount() - time; printf("Milleseconds per iteration = %.3f\n", (double)time / (double)numIterations); printf("\nDigital Input (FIO0-7, EIO0-7, CIO0-3, MIO0-2) = %d\n",valueDIPort); printf("\nAIN readings from last iteration:\n"); for( j = 0; j < numChannels; j++ ) printf("%.3f\n", valueAIN[j]); return 0; }
514
./exodriver/examples/UE9/ue9BasicCommConfig.c
/* An example that shows a minimal use of Exodriver without the use of functions hidden in header files. You can compile this example with the following command: $ g++ -lm -llabjackusb ue9BasicCommConfig.c It is also included in the Makefile. */ /* Includes */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "labjackusb.h" // Defines how long the command is #define COMMCONFIG_COMMAND_LENGTH 38 // Defines how long the response is #define COMMCONFIG_RESPONSE_LENGTH 38 /* Buffer Helper Functions Protypes */ // Takes a buffer and an offset, and turns it into a 32-bit integer int makeInt(BYTE * buffer, int offset); // Takes a buffer and an offset, and turns it into a 16-bit integer int makeShort(BYTE * buffer, int offset); // Takes a buffer and calculates the checksum8 of it. BYTE calculateChecksum8(BYTE* buffer); // Takes a buffer and length, and calculates the checksum16 of the buffer. int calculateChecksum16(BYTE* buffer, int len); /* LabJack Related Helper Functions Protoypes */ // Demonstrates how to build the CommConfig packet. void buildCommConfigBytes(BYTE * sendBuffer); // Demonstrates how to check a response for errors. int checkResponseForErrors(BYTE * recBuffer); // Demonstrates how to parse the response of CommConfig. void parseCommConfigBytes(BYTE * recBuffer); int main() { // Setup the variables we will need. int r = 0; // For checking return values HANDLE devHandle = 0; BYTE sendBuffer[COMMCONFIG_COMMAND_LENGTH], recBuffer[COMMCONFIG_RESPONSE_LENGTH]; // Open the UE9 devHandle = LJUSB_OpenDevice(1, 0, UE9_PRODUCT_ID); if( devHandle == NULL ) { printf("Couldn't open UE9. Please connect one and try again.\n"); exit(-1); } // Builds the CommConfig command buildCommConfigBytes(sendBuffer); // Write the command to the device. // LJUSB_Write( handle, sendBuffer, length of sendBuffer ) r = LJUSB_Write( devHandle, sendBuffer, COMMCONFIG_COMMAND_LENGTH ); if( r != COMMCONFIG_COMMAND_LENGTH ) { printf("An error occurred when trying to write the buffer. The error was: %d\n", errno); // *Always* close the device when you error out. LJUSB_CloseDevice(devHandle); exit(-1); } // Read the result from the device. // LJUSB_Read( handle, recBuffer, number of bytes to read) r = LJUSB_Read( devHandle, recBuffer, COMMCONFIG_RESPONSE_LENGTH ); if( r != COMMCONFIG_RESPONSE_LENGTH ) { printf("An error occurred when trying to read from the UE9. The error was: %d\n", errno); LJUSB_CloseDevice(devHandle); exit(-1); } // Check the command for errors if( checkResponseForErrors(recBuffer) != 0 ){ LJUSB_CloseDevice(devHandle); exit(-1); } // Parse the response into something useful parseCommConfigBytes(recBuffer); //Close the device. LJUSB_CloseDevice(devHandle); return 0; } /* ------------- LabJack Related Helper Functions Definitions ------------- */ // Uses information from section 5.2.1 of the UE9 User's Guide to make a CommConfig // packet. // http://labjack.com/support/ue9/users-guide/5.2.1 void buildCommConfigBytes(BYTE * sendBuffer) { int i; // For loops int checksum = 0; // Build up the bytes //sendBuffer[0] = Checksum8 sendBuffer[1] = 0x78; sendBuffer[2] = 0x10; sendBuffer[3] = 0x01; //sendBuffer[4] = Checksum16 (LSB) //sendBuffer[5] = Checksum16 (MSB) // We just want to read, so we set the WriteMask to zero, and zero out the // rest of the bytes. sendBuffer[6] = 0; for( i = 7; i < COMMCONFIG_COMMAND_LENGTH; i++){ sendBuffer[i] = 0; } // Calculate and set the checksum16 checksum = calculateChecksum16(sendBuffer, COMMCONFIG_COMMAND_LENGTH); sendBuffer[4] = (BYTE)( checksum & 0xff ); sendBuffer[5] = (BYTE)( (checksum / 256) & 0xff ); // Calculate and set the checksum8 sendBuffer[0] = calculateChecksum8(sendBuffer); // The bytes have been set, and the checksum calculated. We are ready to // write to the UE9. } // Checks the response for any errors. int checkResponseForErrors(BYTE * recBuffer) { if(recBuffer[0] == 0xB8 && recBuffer[1] == 0xB8) { // If the packet is [ 0xB8, 0xB8 ], that's a bad checksum. printf("The UE9 detected a bad checksum. Double check your checksum calculations and try again.\n"); return -1; } else if (recBuffer[1] == 0x78 && recBuffer[2] == 0x10 && recBuffer[2] == 0x01) { // Make sure the command bytes match what we expect. printf("Got the wrong command bytes back from the UE9.\n"); return -1; } // Normally, we would check byte 6 for errorcodes. CommConfig is an // exception to that rule. // Calculate the checksums. int checksum16 = calculateChecksum16(recBuffer, COMMCONFIG_RESPONSE_LENGTH); BYTE checksum8 = calculateChecksum8(recBuffer); if ( checksum8 != recBuffer[0] || recBuffer[4] != (BYTE)( checksum16 & 0xff ) || recBuffer[5] != (BYTE)( (checksum16 / 256) & 0xff ) ) { // Check the checksum printf("Response had invalid checksum.\n%d != %d, %d != %d, %d != %d\n", checksum8, recBuffer[0], (BYTE)( checksum16 & 0xff ), recBuffer[4], (BYTE)( (checksum16 / 256) & 0xff ), recBuffer[5] ); return -1; } return 0; } // Parses the CommConfig packet into something useful. void parseCommConfigBytes(BYTE * recBuffer){ printf("Results of CommConfig:\n"); printf(" LocalID = %d\n", recBuffer[8]); printf(" PowerLevel = %d\n", recBuffer[9]); printf(" IPAddress = %d.%d.%d.%d\n", recBuffer[13], recBuffer[12], recBuffer[11], recBuffer[10] ); printf(" Gateway = %d.%d.%d.%d\n", recBuffer[17], recBuffer[16], recBuffer[15], recBuffer[14] ); printf(" Subnet = %d.%d.%d.%d\n", recBuffer[21], recBuffer[20], recBuffer[19], recBuffer[18] ); printf(" PortA = %d\n", makeShort(recBuffer, 22)); printf(" PortB = %d\n", makeShort(recBuffer, 24)); printf(" DHCPEnabled = %d\n", recBuffer[26]); printf(" ProductID = %d\n", recBuffer[27]); printf(" MACAddress = %02X:%02X:%02X:%02X:%02X:%02X\n", recBuffer[33], recBuffer[32], recBuffer[31], recBuffer[30], recBuffer[29], recBuffer[28]); BYTE serialBytes[4]; serialBytes[0] = recBuffer[28]; serialBytes[1] = recBuffer[29]; serialBytes[2] = recBuffer[30]; serialBytes[3] = 0x10; printf(" SerialNumber = %d\n", makeInt(serialBytes, 0)); printf(" HardwareVersion = %d.%02d\n", recBuffer[35], recBuffer[34]); printf(" FirmwareVersion = %d.%02d\n", recBuffer[37], recBuffer[36]); } /* ---------------- Buffer Helper Functions Definitions ---------------- */ // Takes a buffer and an offset, and turns into an 32-bit integer int makeInt(BYTE * buffer, int offset){ return (buffer[offset+3] << 24) + (buffer[offset+2] << 16) + (buffer[offset+1] << 8) + buffer[offset]; } // Takes a buffer and an offset, and turns into an 16-bit integer int makeShort(BYTE * buffer, int offset) { return (buffer[offset+1] << 8) + buffer[offset]; } // Calculates the checksum8 BYTE calculateChecksum8(BYTE* buffer){ int i; // For loops int temp; // For holding a value while we working. int checksum = 0; for( i = 1; i < 6; i++){ checksum += buffer[i]; } temp = checksum/256; checksum = ( checksum - 256 * temp ) + temp; temp = checksum/256; return (BYTE)( ( checksum - 256 * temp ) + temp ); } // Calculates the checksum16 int calculateChecksum16(BYTE* buffer, int len){ int i; int checksum = 0; for( i = 6; i < len; i++){ checksum += buffer[i]; } return checksum; }
515
./exodriver/examples/UE9/ue9EthernetExample.c
/* An example that shows how to use sockets to talk with the UE9. You may notice that the code is VERY similar to ue9BasicCommConfig.c. The only difference is using socket calls instead of calls to the Exodriver. You can compile this example with the following command: $ g++ -o ue9EthernetExample ue9EthernetExample.c To run it: $ ./ue9EthernetExample <IP Address> It is also included in the Makefile. */ //Because that is what an unsigned char is. typedef unsigned char BYTE; /* Includes */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> // Defines how long the command is #define COMMCONFIG_COMMAND_LENGTH 38 // Defines how long the response is #define COMMCONFIG_RESPONSE_LENGTH 38 /* Buffer Helper Functions Protypes */ // Takes a buffer and an offset, and turns it into a 32-bit integer int makeInt(BYTE * buffer, int offset); // Takes a buffer and an offset, and turns it into a 16-bit integer int makeShort(BYTE * buffer, int offset); // Takes a buffer and calculates the checksum8 of it. BYTE calculateChecksum8(BYTE* buffer); // Takes a buffer and length, and calculates the checksum16 of the buffer. int calculateChecksum16(BYTE* buffer, int len); /* LabJack Related Helper Functions Protoypes */ // Demonstrates how to build the CommConfig packet. void buildCommConfigBytes(BYTE * sendBuffer); // Demonstrates how to check a response for errors. int checkResponseForErrors(BYTE * recBuffer); // Demonstrates how to parse the response of CommConfig. void parseCommConfigBytes(BYTE * recBuffer); int main(int argc, char *argv[]) { // Setup the variables we will need. int r = 0; // For checking return values int devHandle = 0; BYTE sendBuffer[COMMCONFIG_COMMAND_LENGTH], recBuffer[COMMCONFIG_RESPONSE_LENGTH]; struct addrinfo hints, *res; if(argc < 2) { fprintf(stderr,"Usage: %s <IP Address>\n", argv[0]); exit(-1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; printf("Getting IP Info... "); r = getaddrinfo(argv[1], "52360", &hints, &res); if( r != 0 ){ perror("Couldn't parse address info. Error: "); exit(-1); } printf("Done\n"); printf("Getting socket FD... "); // Open the UE9, through a socket. devHandle = socket(AF_INET, SOCK_STREAM, 0); if( devHandle < 0 ) { perror("Couldn't open socket."); exit(-1); } printf("Done\n"); printf("Connecting (time out after a minute)... "); fflush(stdout); r = connect(devHandle, res->ai_addr, res->ai_addrlen); if( r < 0 ){ perror("\nCouldn't connect to UE9. The error was"); close(devHandle); exit(-1); } printf("Done\n"); // Builds the CommConfig command buildCommConfigBytes(sendBuffer); // Write the command to the device. // LJUSB_Write( handle, sendBuffer, length of sendBuffer ) r = write( devHandle, sendBuffer, COMMCONFIG_COMMAND_LENGTH ); if( r != COMMCONFIG_COMMAND_LENGTH ) { printf("An error occurred when trying to write the buffer. The error was: %d\n", errno); // *Always* close the device when you error out. close(devHandle); exit(-1); } // Read the result from the device. // LJUSB_Read( handle, recBuffer, number of bytes to read) r = read( devHandle, recBuffer, COMMCONFIG_RESPONSE_LENGTH ); if( r != COMMCONFIG_RESPONSE_LENGTH ) { printf("An error occurred when trying to read from the UE9. The error was: %d\n", errno); close(devHandle); exit(-1); } // Check the command for errors if( checkResponseForErrors(recBuffer) != 0 ){ close(devHandle); exit(-1); } // Parse the response into something useful parseCommConfigBytes(recBuffer); //Close the device. close(devHandle); return 0; } /* ------------- LabJack Related Helper Functions Definitions ------------- */ // Uses information from section 5.2.1 of the UE9 User's Guide to make a CommConfig // packet. // http://labjack.com/support/ue9/users-guide/5.2.1 void buildCommConfigBytes(BYTE * sendBuffer) { int i; // For loops int checksum = 0; // Build up the bytes //sendBuffer[0] = Checksum8 sendBuffer[1] = 0x78; sendBuffer[2] = 0x10; sendBuffer[3] = 0x01; //sendBuffer[4] = Checksum16 (LSB) //sendBuffer[5] = Checksum16 (MSB) // We just want to read, so we set the WriteMask to zero, and zero out the // rest of the bytes. sendBuffer[6] = 0; for( i = 7; i < COMMCONFIG_COMMAND_LENGTH; i++){ sendBuffer[i] = 0; } // Calculate and set the checksum16 checksum = calculateChecksum16(sendBuffer, COMMCONFIG_COMMAND_LENGTH); sendBuffer[4] = (BYTE)( checksum & 0xff ); sendBuffer[5] = (BYTE)( (checksum / 256) & 0xff ); // Calculate and set the checksum8 sendBuffer[0] = calculateChecksum8(sendBuffer); // The bytes have been set, and the checksum calculated. We are ready to // write to the UE9. } // Checks the response for any errors. int checkResponseForErrors(BYTE * recBuffer) { if(recBuffer[0] == 0xB8 && recBuffer[1] == 0xB8) { // If the packet is [ 0xB8, 0xB8 ], that's a bad checksum. printf("The UE9 detected a bad checksum. Double check your checksum calculations and try again.\n"); return -1; } else if (recBuffer[1] == 0x78 && recBuffer[2] == 0x10 && recBuffer[2] == 0x01) { // Make sure the command bytes match what we expect. printf("Got the wrong command bytes back from the UE9.\n"); return -1; } // Normally, we would check byte 6 for errorcodes. CommConfig is an // exception to that rule. // Calculate the checksums. int checksum16 = calculateChecksum16(recBuffer, COMMCONFIG_RESPONSE_LENGTH); BYTE checksum8 = calculateChecksum8(recBuffer); if ( checksum8 != recBuffer[0] || recBuffer[4] != (BYTE)( checksum16 & 0xff ) || recBuffer[5] != (BYTE)( (checksum16 / 256) & 0xff ) ) { // Check the checksum printf("Response had invalid checksum.\n%d != %d, %d != %d, %d != %d\n", checksum8, recBuffer[0], (BYTE)( checksum16 & 0xff ), recBuffer[4], (BYTE)( (checksum16 / 256) & 0xff ), recBuffer[5] ); return -1; } return 0; } // Parses the CommConfig packet into something useful. void parseCommConfigBytes(BYTE * recBuffer){ printf("Results of CommConfig:\n"); printf(" LocalID = %d\n", recBuffer[8]); printf(" PowerLevel = %d\n", recBuffer[9]); printf(" IPAddress = %d.%d.%d.%d\n", recBuffer[13], recBuffer[12], recBuffer[11], recBuffer[10] ); printf(" Gateway = %d.%d.%d.%d\n", recBuffer[17], recBuffer[16], recBuffer[15], recBuffer[14] ); printf(" Subnet = %d.%d.%d.%d\n", recBuffer[21], recBuffer[20], recBuffer[19], recBuffer[18] ); printf(" PortA = %d\n", makeShort(recBuffer, 22)); printf(" PortB = %d\n", makeShort(recBuffer, 24)); printf(" DHCPEnabled = %d\n", recBuffer[26]); printf(" ProductID = %d\n", recBuffer[27]); printf(" MACAddress = %02X:%02X:%02X:%02X:%02X:%02X\n", recBuffer[33], recBuffer[32], recBuffer[31], recBuffer[30], recBuffer[29], recBuffer[28]); BYTE serialBytes[4]; serialBytes[0] = recBuffer[28]; serialBytes[1] = recBuffer[29]; serialBytes[2] = recBuffer[30]; serialBytes[3] = 0x10; printf(" SerialNumber = %d\n", makeInt(serialBytes, 0)); printf(" HardwareVersion = %d.%02d\n", recBuffer[35], recBuffer[34]); printf(" FirmwareVersion = %d.%02d\n", recBuffer[37], recBuffer[36]); } /* ---------------- Buffer Helper Functions Definitions ---------------- */ // Takes a buffer and an offset, and turns into an 32-bit integer int makeInt(BYTE * buffer, int offset){ return (buffer[offset+3] << 24) + (buffer[offset+2] << 16) + (buffer[offset+1] << 8) + buffer[offset]; } // Takes a buffer and an offset, and turns into an 16-bit integer int makeShort(BYTE * buffer, int offset) { return (buffer[offset+1] << 8) + buffer[offset]; } // Calculates the checksum8 BYTE calculateChecksum8(BYTE* buffer){ int i; // For loops int temp; // For holding a value while we working. int checksum = 0; for( i = 1; i < 6; i++){ checksum += buffer[i]; } temp = checksum/256; checksum = ( checksum - 256 * temp ) + temp; temp = checksum/256; return (BYTE)( ( checksum - 256 * temp ) + temp ); } // Calculates the checksum16 int calculateChecksum16(BYTE* buffer, int len){ int i; int checksum = 0; for( i = 6; i < len; i++){ checksum += buffer[i]; } return checksum; }
516
./exodriver/examples/UE9/ue9EFunctions.c
//Author: LabJack //March 2, 2007 //This examples demonstrates how to read from analog inputs (AIN) and digital inputs(FIO), //set analog outputs (DAC) and digital outputs (FIO), and how to configure and enable //timers and counters and read input timers and counters values using the "easy" functions. #include "ue9.h" #include <unistd.h> int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; int localID, i; long error; //Open first found UE9 over USB localID = -1; if( (hDevice = openUSBConnection(localID)) == NULL ) goto done; //Get calibration information from UE9 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; //Set DAC0 to 3.1 volts. printf("Calling eDAC to set DAC0 to 3.1 V\n"); if( (error = eDAC(hDevice, &caliInfo, 0, 3.1, 0, 0, 0)) != 0 ) goto close; //Read the voltage from AIN3 using 0-5 volt range at 12 bit resolution printf("Calling eAIN to read voltage from AIN3\n"); double dblVoltage; if( (error = eAIN(hDevice, &caliInfo, 3, 0, &dblVoltage, LJ_rgUNI5V, 12, 0, 0, 0, 0)) != 0 ) goto close; printf("\nAIN3 value = %.3f\n", dblVoltage); //Set FIO3 to output-high printf("\nCalling eDO to set FIO3 to output-high\n"); if((error = eDO(hDevice, 3, 1)) != 0) goto close; //Read state of FIO2 printf("\nCalling eDI to read the state of FIO2\n"); long lngState; if( (error = eDI(hDevice, 2, &lngState)) != 0 ) goto close; printf("FIO2 state = %ld\n", lngState); //Enable and configure 1 output timer and 1 input timer, and enable counter0 printf("\nCalling eTCConfig to enable and configure 1 output timer (Timer0) and 1 input timer (Timer1), and enable counter0\n"); long alngEnableTimers[6] = {1, 1, 0, 0, 0, 0}; //Enable Timer0-Timer1 long alngTimerModes[6] = {LJ_tmPWM8, LJ_tmRISINGEDGES32, 0, 0, 0, 0}; //Set timer modes double adblTimerValues[6] = {16384, 0, 0, 0, 0, 0}; //Set PWM8 duty-cycles to 75% long alngEnableCounters[2] = {1, 0}; //Enable Counter0 if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 0, LJ_tc750KHZ, 3, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nWaiting for 1 second...\n"); sleep(1); //Read and reset the input timer (Timer1), read and reset Counter0, and update the //value (duty-cycle) of the output timer (Timer0) printf("\nCalling eTCValues to read and reset the input Timer1 and Counter0, and update the value (duty-cycle) of the output Timer0\n"); long alngReadTimers[6] = {0, 1, 0, 0, 0, 0}; //Read Timer1 long alngUpdateResetTimers[6] = {1, 0, 0, 0, 0, 0}; //Update timer0 long alngReadCounters[2] = {1, 0}; //Read Counter0 long alngResetCounters[2] = {0, 0}; //Reset Counter0 double adblCounterValues[2] = {0, 0}; adblTimerValues[0] = 32768; //Change Timer0 duty-cycle to 50% if( (error = eTCValues(hDevice, alngReadTimers, alngUpdateResetTimers, alngReadCounters, alngResetCounters, adblTimerValues, adblCounterValues, 0, 0)) != 0 ) goto close; printf("Timer1 value = %.0f\n", adblTimerValues[1]); printf("Counter0 value = %.0f\n", adblCounterValues[0]); //Disable all timers and counters for(i = 0; i < 6; i++) alngEnableTimers[i] = 0; alngEnableCounters[0] = 0; alngEnableCounters[1] = 0; if( (error = eTCConfig(hDevice, alngEnableTimers, alngEnableCounters, 0, 0, 0, alngTimerModes, adblTimerValues, 0, 0)) != 0 ) goto close; printf("\nCalling eTCConfig to disable all timers and counters\n"); close: if( error > 0 ) printf("Received an error code of %ld\n", error); closeUSBConnection(hDevice); done: return 0; }
517
./exodriver/examples/UE9/ue9Feedback.c
//Author: LabJack //May 25, 2011 //This example program calls the Feedback low-level function. DAC0 will be set //to 2.5 volts and DAC1 will be set to 3.5 volts. The states and directions //will be read from FIO0 - FIO3 and the voltages (calibrated) from AI0-AI3. #include "ue9.h" int feedback_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo); int main(int argc, char **argv) { HANDLE hDevice; ue9CalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from UE9 if( getCalibrationInfo(hDevice, &caliInfo) < 0 ) goto close; feedback_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } //Sends a Feedback low-level command to set DAC0, DAC1, read FIO0-FIO3 and //AI0-AI3. int feedback_example(HANDLE hDevice, ue9CalibrationInfo *caliInfo) { uint8 sendBuff[34], recBuff[64], ainResolution, gainBip; uint16 checksumTotal, bytesVoltage; uint32 tempDir, tempState; int sendChars, recChars, i; double voltage; ainResolution = 12; //ainResolution = 18; //high-res mode for UE9 Pro only gainBip = 0; //(Gain = 1, Bipolar = 0) sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x0E); //Number of data words sendBuff[3] = (uint8)(0x00); //Extended command number //All these bytes are set to zero since we are not changing the FIO, EIO, CIO //and MIO directions and states for( i = 6; i <= 15; i++ ) sendBuff[i] = (uint8)(0x00); if( getDacBinVoltCalibrated(caliInfo, 0, 2.500, &bytesVoltage) < 0 ) return -1; //setting the voltage of DAC0 sendBuff[16] = (uint8)( bytesVoltage & (0x00FF) ); //low bits of DAC0 sendBuff[17] = (uint8)( bytesVoltage / 256 ) + 192; //high bits of DAC0 //(bit 7 : Enable, // bit 6: Update) if( getDacBinVoltCalibrated(caliInfo, 1, 3.500, &bytesVoltage) < 0 ) return -1; //setting the voltage of DAC1 sendBuff[18] = (uint8)( bytesVoltage & (0x00FF) ); //low bits of DAC1 sendBuff[19] = (uint8)( bytesVoltage / 256 ) + 192; //high bits of DAC1 //(bit 7 : Enable, // bit 6: Update) sendBuff[20] = (uint8)(0x0f); //AINMask - reading AIN0-AIN3, not AIN4-AIN7 sendBuff[21] = (uint8)(0x00); //AINMask - not reading AIN8-AIN15 sendBuff[22] = (uint8)(0x00); //AIN14ChannelNumber - not using sendBuff[23] = (uint8)(0x00); //AIN15ChannelNumber - not using sendBuff[24] = ainResolution; //Resolution = 12 //Setting BipGains for( i = 25; i < 34; i++ ) sendBuff[i] = gainBip; extendedChecksum(sendBuff, 34); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 34); if( sendChars < 34 ) { if( sendChars == 0 ) printf("Error : write failed\n"); else printf("Error : did not write all of the buffer\n"); return -1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 64); if( recChars < 64 ) { if( recChars == 0 ) printf("Error : read failed\n"); else printf("Error : did not read all of the buffer\n"); return -1; } checksumTotal = extendedChecksum16(recBuff, 64); if( (uint8)((checksumTotal / 256) & 0xff) != recBuff[5] ) { printf("Error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xff) != recBuff[4]) { printf("Error : read buffer has bad checksum16(LSB)\n"); return -1; } if( extendedChecksum8(recBuff) != recBuff[0] ) { printf("Error : read buffer has bad checksum8\n"); return -1; } if( recBuff[1] != (uint8)(0xF8) || recBuff[2] != (uint8)(0x1D) || recBuff[3] != (uint8)(0x00) ) { printf("Error : read buffer has wrong command bytes \n"); return -1; } printf("Set DAC0 to 2.500 volts and DAC1 to 3.500 volts.\n\n"); printf("Flexible digital I/O directions and states (FIO0 - FIO3):\n"); for( i = 0; i < 4; i++ ) { tempDir = ( (uint32)(recBuff[6] / pow(2, i)) & (0x01) ); tempState = ( (uint32)(recBuff[7] / pow(2, i)) & (0x01) ); printf(" FI%d: %u and %u\n", i, tempDir, tempState); } printf("\nAnalog Inputs (AI0 - AI3):\n"); for( i = 0; i < 4; i++ ) { bytesVoltage = recBuff[12 + 2*i] + recBuff[13 + 2*i]*256; //getting analog voltage if( getAinVoltCalibrated(caliInfo, gainBip, ainResolution, bytesVoltage, &voltage) < 0 ) return -1; printf(" AI%d: %.4f V\n", i, voltage); } printf("\n"); return 0; }
518
./exodriver/examples/UE9/ue9TimerCounter.c
//Author: LabJack //May 25, 2011 //This example program calls the TimerCounter function, and reads both counters //and enables 2 timers with PWM output. Connect FIO0/FIO1 to FIO2/FIO3 to have //the counter read something. After 1 second the counters' counts are outputted //to the screen. #include <unistd.h> #include "ue9.h" int timerCounter_example(HANDLE hDevice); int errorCheck(uint8 *buffer); int main(int argc, char **argv) { HANDLE hDevice; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) return 1; timerCounter_example(hDevice); closeUSBConnection(hDevice); return 0; } //Sends a TimerCounter low-level command to enable and set two Timers //(FIO0, FIO1) and two Counters (FIO2, FIO3), then sends a TimerCounter //command a second later to read from the Counters and last sends a //TimerCounter command to disable the Timers and Counters. int timerCounter_example(HANDLE hDevice) { //Note: If using the quadrature input timer mode, the returned 32 bit // integer is signed uint8 sendBuff[30], recBuff[40]; uint32 cnt; int sendChars, recChars, i; //Enable timers and counters sendBuff[1] = (uint8)(0xF8); //Command byte sendBuff[2] = (uint8)(0x0C); //Number of data words sendBuff[3] = (uint8)(0x18); //Extended command number sendBuff[6] = (uint8)(0x03); //TimerClockDivisor = 3 sendBuff[7] = (uint8)(0x9A); //Updating: 2 Timers enabled, Counter0 and //Counter1 enabled sendBuff[8] = (uint8)(0x00); //TimerClockConfig = 750 kHz (if using system //clock, call ControlConfig first and set the //PowerLevel to a fixed state) sendBuff[9] = (uint8)(0x00); //UpdateReset - not resetting anything sendBuff[10] = (uint8)(0x00); //Timer0Mode = 16-Bit PWM //Timer0Value = 32768 sendBuff[11] = (uint8)(0x00); //Timer0Value (low byte) sendBuff[12] = (uint8)(0x80); //Timer0Value (high byte) //Timer1Value = 32768 sendBuff[13] = (uint8)(0x01); //Timer1Mode = 8-Bit PWM sendBuff[14] = (uint8)(0x00); //Timer1Value (low byte) sendBuff[15] = (uint8)(0x80); //Timer1Value (high byte) //timer modes and values for timers 2 - 5, which are not enabled for( i = 16; i < 28; i++ ) sendBuff[i] = (uint8)(0x00); sendBuff[28] = (uint8)(0x00); //Counter0Mode (pass 0) sendBuff[29] = (uint8)(0x00); //Counter1Mode (pass 0) extendedChecksum(sendBuff, 30); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 30); if( sendChars < 30 ) { if( sendChars == 0 ) goto writeError0; else goto writeError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 40); if( recChars < 40 ) { if( recChars == 0 ) goto readError0; else goto readError1; } if( errorCheck(recBuff) == -1 ) return -1; //Wait 1 sec and read counters sleep(1); sendBuff[1] = (uint8)(0xF8); //Command bytes sendBuff[2] = (uint8)(0x0C); //Number of data words sendBuff[3] = (uint8)(0x18); //Extended command number //Not updating our configuration. We only want to read the counter values. for( i = 6; i < 30; i++ ) sendBuff[i] = (uint8)(0x00); extendedChecksum(sendBuff, 30); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 30); if( sendChars < 30 ) { if( sendChars == 0 ) goto writeError0; else goto writeError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 40); if( recChars < 40 ) { if( recChars == 0 ) goto readError0; else goto readError1; } if( errorCheck(recBuff) == -1 ) return -1; printf("Current counts from counters after 1 second:\n"); for( i = 0; i < 2; i++ ) { cnt = (unsigned int)recBuff[32 + 4*i] + (unsigned int)recBuff[33 + 4*i]*256 + (unsigned int)recBuff[34 + 4*i]*65536 + (unsigned int)recBuff[35 + 4*i]*16777216; printf(" Counter%d : %u\n", i, cnt); } //Disable timers and counters sendBuff[1] = (uint8)(0xF8); //Command bytes sendBuff[2] = (uint8)(0x0C); //Number of data words sendBuff[3] = (uint8)(0x18); //Extended command number sendBuff[6] = (uint8)(0x00); //TimerClockDivisor = 0 sendBuff[7] = (uint8)(0x80); //Updating: 0 Timers enabled, Counter0 and //Counter1 disabled //Setting bytes 8 - 30 to zero since nothing is enabled for( i = 8; i < 30; i++ ) sendBuff[i] = (uint8)(0x00); extendedChecksum(sendBuff, 30); //Sending command to UE9 sendChars = LJUSB_Write(hDevice, sendBuff, 30); if( sendChars < 30 ) { if( sendChars == 0 ) goto writeError0; else goto writeError1; } //Reading response from UE9 recChars = LJUSB_Read(hDevice, recBuff, 40); if( recChars < 40 ) { if( recChars == 0 ) goto readError0; else goto readError1; } if( errorCheck(recBuff) == -1 ) return -1; return 0; writeError0: printf("Error : write failed\n"); return -1; writeError1: printf("Error : did not write all of the buffer\n"); return -1; readError0: printf("Error : read failed\n"); return -1; readError1: printf("Error : did not read all of the buffer\n"); return -1; } int errorCheck(uint8 *buffer) { uint16 checksumTotal; checksumTotal = extendedChecksum16(buffer, 40); if( (uint8)((checksumTotal / 256) & 0xFF) != buffer[5] ) { printf("Error : read buffer has bad checksum16(MSB)\n"); return -1; } if( (uint8)(checksumTotal & 0xFF) != buffer[4] ) { printf("Error : read buffer has bad checksum16(LSB)\n"); return -1; } if( extendedChecksum8(buffer) != buffer[0] ) { printf("Error : read buffer has bad checksum8\n"); return -1; } if( buffer[1] != (uint8)(0xF8) || buffer[2] != (uint8)(0x11) || buffer[3] != (uint8)(0x18) ) { printf("Error : read buffer has wrong command bytes \n"); return -1; } if( buffer[6] != 0 ) { printf("Errorcode (byte 6): %d\n", (unsigned int)buffer[6]); return -1; } return 0; }
519
./exodriver/examples/UE9/ue9LJTDAC.c
//Author: LabJack //June 23, 2009 //Communicates with an LJTick-DAC using low level functions. The LJTDAC should //be plugged into FIO0/FIO1 for this example. //Tested with UE9 Comm firmware V1.43 and Control firmware V1.84. #include "ue9.h" #include <unistd.h> int checkI2CErrorcode(uint8 errorcode); int LJTDAC_example(HANDLE hDevice, ue9TdacCalibrationInfo *caliInfo); const uint8 SCLPinNum = 0; int main(int argc, char **argv) { HANDLE hDevice; ue9TdacCalibrationInfo caliInfo; //Opening first found UE9 over USB if( (hDevice = openUSBConnection(-1)) == NULL ) goto done; //Getting calibration information from LJTDAC if( getTdacCalibrationInfo(hDevice, &caliInfo, SCLPinNum) < 0 ) goto close; LJTDAC_example(hDevice, &caliInfo); close: closeUSBConnection(hDevice); done: return 0; } int checkI2CErrorcode(uint8 errorcode) { if( errorcode != 0 ) { printf("I2C error : received errorcode %d in response\n", errorcode); return -1; } return 0; } int LJTDAC_example( HANDLE hDevice, ue9TdacCalibrationInfo *caliInfo ) { uint8 options, speedAdjust, sdaPinNum, sclPinNum; uint8 address, numBytesToSend, numBytesToReceive, errorcode; uint8 bytesCommand[5], bytesResponse[64], ackArray[4]; uint16 binaryVoltage; int i, err; err = 0; //Setting up parts I2C command that will remain the same throughout this example options = 0; //I2COptions : 0 speedAdjust = 0; //SpeedAdjust : 0 (for max communication speed of about 130 kHz) sdaPinNum = SCLPinNum + 1; //SDAPinNum : FIO1 connected to pin DIOB sclPinNum = SCLPinNum; //SCLPinNum : FIO0 connected to pin DIOA /* Set DACA to 1.2 volts. */ //Setting up I2C command //Make note that the I2C command can only update 1 DAC channel at a time. address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACA and the value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting the value of the DAC bytesCommand[0] = (uint8)(0x30); //LJTDAC command byte : h0x30 (DACA) getTdacBinVoltCalibrated(caliInfo, 0, 1.2, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACA set to 1.2 volts\n\n"); /* Set DACB to 2.3 volts. */ //Setting up I2C command address = (uint8)(0x24); //Address : h0x24 is the address for DAC numBytesToSend = 3; //NumI2CByteToSend : 3 bytes to specify DACB and the value numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only setting the value of the DAC bytesCommand[0] = (uint8)(0x31); //LJTDAC command byte : h0x31 (DACB) getTdacBinVoltCalibrated(caliInfo, 1, 2.3, &binaryVoltage); bytesCommand[1] = (uint8)(binaryVoltage/256); //value (high) bytesCommand[2] = (uint8)(binaryVoltage & (0x00FF)); //value (low) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("DACB set to 2.3 volts\n\n"); /* More advanced operations. */ /* Display LJTDAC calibration constants. Code for getting the calibration constants is in the * getLJTDACCalibrationInfo function in the ue9.c file. */ printf("DACA Slope = %.1f bits/volt\n", caliInfo->ccConstants[0]); printf("DACA Offset = %.1f bits\n", caliInfo->ccConstants[1]); printf("DACB Slope = %.1f bits/volt\n", caliInfo->ccConstants[2]); printf("DACB Offset = %.1f bits\n\n", caliInfo->ccConstants[3]); /* Read the serial number. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 4; //NumI2CBytesToReceive : getting 4 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 96; //I2CByte0 : Memory Address, starting at address 96 (Serial Number) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; printf("LJTDAC Serial Number = %u\n\n", (bytesResponse[0] + bytesResponse[1]*256 + bytesResponse[2]*65536 + bytesResponse[3]*16777216)); /* User memory example. We will read the memory, update a few elements, * and write the memory. The user memory is just stored as bytes, so almost * any information can be put in there such as integers, doubles, or strings. */ /* Read the user memory */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 64; //NumI2CBytesToReceive : getting 64 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); /* Create 4 new pseudo-random numbers to write. We will update the first * 4 elements of user memory, but the rest will be unchanged. */ //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 5; //NumI2CByteToSend : 1 byte for the EEPROM address and the rest for the bytes to write numBytesToReceive = 0; //NumI2CBytesToReceive : 0 since we are only writing to memory bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) srand((unsigned int)getTickCount()); for( i = 1; i < 5; i++ ) bytesCommand[i] = (uint8)(255*((float)rand()/RAND_MAX));; //I2CByte : byte in user memory printf("Write User Mem [0-3] = %d, %d, %d, %d\n", bytesCommand[1], bytesCommand[2], bytesCommand[3], bytesCommand[4]); //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Delay for 2 ms to allow the EEPROM to finish writing. //Re-read the user memory. usleep(2000); //Setting up I2C command address = (uint8)(0xA0); //Address : h0xA0 is the address for EEPROM numBytesToSend = 1; //NumI2CByteToSend : 1 byte for the EEPROM address numBytesToReceive = 64; //NumI2CBytesToReceive : getting 64 bytes starting at EEPROM address specified in I2CByte0 bytesCommand[0] = 0; //I2CByte0 : Memory Address, starting at address 0 (User Area) //Performing I2C low-level call err = I2C(hDevice, options, speedAdjust, sdaPinNum, sclPinNum, address, numBytesToSend, numBytesToReceive, bytesCommand, &errorcode, ackArray, bytesResponse); if( checkI2CErrorcode(errorcode) == -1 || err == -1 ) return -1; //Display the first 4 elements. printf("Read User Mem [0-3] = %d, %d, %d, %d\n", bytesResponse[0], bytesResponse[1], bytesResponse[2], bytesResponse[3]); return err; }
520
./exodriver/examples/Modbus/readModbusExample.c
/* * A simple example that shows how to used modbus.h with the Exodriver by * reading AIN0 and printing it to stdout. * * The most important thing to get right are your buffer lengths. In the case of * read register, it's easy. The command to be written is always 14 bytes. The * response is 9 + (2 * number of registers being read). So, if you are reading * three registers, your receive buffer needs to be 9 + (3 * 2), or 15 bytes. * What those bytes mean will depend on the register. Make sure to check out the * Modbus support page: * http://labjack.com/support/modbus */ #include <stdio.h> #include "modbus.h" #include "labjackusb.h" // Set to 3 (U3), 6 (U6), or 9 (UE9). #define DEVICE_TYPE 3 // Read Holding Register Packets are always 14 bytes over USB #define READ_REGISTER_SEND_LENGTH 14 int main() { HANDLE devHandle; int i; int r = 0; // For checking return values int startReg = 0; // Start at register 0 int numRegs = 2; // AIN0 is floating point, so need to read 2 registers int unitId = 0; // For UD family devices, always 0 int prependZeros = 1; // For UD family devices on USB, always 1 BYTE sendBuffer[READ_REGISTER_SEND_LENGTH]; // 2 (for extra zeros) + 12 int numBytesToRead = 13; // 9 + (2*numReg) BYTE recBuffer[13]; // Same as numBytesToRead float value; // Will hold parsed result // Open the device devHandle = LJUSB_OpenDevice(1, 0, DEVICE_TYPE); if(devHandle <= 0){ printf("ERROR: Couldn't find a LabJack to open.\n"); return -1; } if(DEVICE_TYPE == 3){ printf("Opened first found U3.\n"); } else if(DEVICE_TYPE == 6) { printf("Opened first found U6.\n"); } else { printf("Opened first found UE9.\n"); } // Build the packet. numBytesToRead = buildReadHoldingRegistersPacket(sendBuffer, startReg, numRegs, unitId, prependZeros); printf("Built Read Holding Registers Packet to read register 0 (AIN0).\n"); // Send packet to the device. r = LJUSB_Write(devHandle, sendBuffer, READ_REGISTER_SEND_LENGTH); if( r != READ_REGISTER_SEND_LENGTH ){ printf("ERROR: An error occurred while writing to the device."); LJUSB_CloseDevice(devHandle); return -1; } printf("Wrote command to device.\n"); printf("Sent = ["); for( i = 0; i < READ_REGISTER_SEND_LENGTH-1; i++){ printf("0x%X, ", sendBuffer[i]); } printf("0x%X]\n\n", sendBuffer[READ_REGISTER_SEND_LENGTH-1]); // Read the response from the device. r = LJUSB_Read(devHandle, recBuffer, numBytesToRead); if( r != numBytesToRead ){ printf("ERROR: An error occurred while reading from the device."); LJUSB_CloseDevice(devHandle); return -1; } printf("Read the response.\n"); printf("Read = ["); for( i = 0; i < numBytesToRead-1; i++){ printf("0x%X, ", recBuffer[i]); } printf("0x%X]\n\n", recBuffer[numBytesToRead-1]); // Parse out the value. value = parseFPRegisterResponse(recBuffer, 9); printf("AIN0: %f\n\n", value); // Close the device. LJUSB_CloseDevice(devHandle); printf("Closed Device.\n"); return 0; }
521
./exodriver/examples/Modbus/testModbusFunctions.c
/* * This file shows how to uses the functions in modbus.h without requiring a * LabJack, the Exodriver, or libusb. */ #include <stdio.h> #include "modbus.h" int main() { int i; printf("Modbus Function tests:\n\n"); // Build a packet to read register 0 (AIN0) and store it in sendBuffer unsigned char sendBuffer[14]; int startReg = 0; // Start at register 0 int numRegs = 2; // AIN0 is floating point, so need to read 2 registers int unitId = 0; // For UD family devices, always 0 int prependZeros = 1; // For UD family devices on USB, always 1 int numBytesToRead; numBytesToRead = buildReadHoldingRegistersPacket( sendBuffer, startReg, numRegs, unitId, prependZeros ); printf("buildReadHoldingRegistersPacket:\n sendBuffer: ["); for(i = 0; i < 13; i++) { printf("0x%X, ", sendBuffer[i]); } printf("0x%X]\n numBytesToRead: %d\n\n", sendBuffer[13], numBytesToRead); // Parse a float from a byte array. unsigned char recBuffer[] = { 0x40, 0x0, 0x0, 0x0 }; float fValue = parseFPRegisterResponse(recBuffer, 0); printf("parseFPRegister: [0x40, 0x0, 0x0, 0x0] => %f\n\n", fValue); // Parse an int from a byte array. recBuffer[0] = 0x0; recBuffer[1] = 0x84; recBuffer[2] = 0x5F; recBuffer[3] = 0xED; int iValue = parseIntRegisterResponse(recBuffer, 0); printf("parseIntRegister: [0x0, 0x84, 0x5F, 0xED] => %i\n\n", iValue); // Parse a short from a byte array. recBuffer[0] = 0x2; recBuffer[1] = 0x10; short sValue = parseShortRegisterResponse(recBuffer, 0); printf("parseShortRegister: [0x2, 0x10] => %i\n\n", sValue); // Start Write Functions // Build an array of bytes to write 2.0, 8675309, and 528 starting at 0 startReg = 0; // Start at register 0 numRegs = 5; // 1 float (2 registers), 1 int (2 registers), 1 short (1 reg) unitId = 0; // For UD family devices, always 0 prependZeros = 1; // For UD family devices on USB, always 1 unsigned char writeBuffer[25]; // 13 + (2*5) + 2 = 25 numBytesToRead = buildWriteHoldingRegistersPacket(writeBuffer, startReg, numRegs, unitId, prependZeros); printf("buildWriteHoldingRegistersPacket:\n writeBuffer: ["); for(i = 0; i < 24; i++) { printf("0x%X, ", writeBuffer[i]); } printf("0x%X]\n numBytesToRead: %d\n\n", writeBuffer[24], numBytesToRead); putFPIntoBuffer(writeBuffer, 15, 2.0); printf("putFPIntoBuffer: Appended 2.0 to packet.\n\n"); putIntIntoBuffer(writeBuffer, 19, 8675309); printf("putIntIntoBuffer: Appended 8675309 to packet.\n\n"); putShortIntoBuffer(writeBuffer, 23, 528); printf("putShortIntoBuffer: Appended 528 to packet.\n\n"); printf("Result:\n writeBuffer: ["); for(i = 0; i < 24; i++) { printf("0x%X, ", writeBuffer[i]); } printf("0x%X]\n\n", writeBuffer[24]); return 0; }
522
./exodriver/examples/Modbus/modbus.c
/* * A library to help you build modbus functions for LabJack devices. */ /* --------- Static Variables --------- */ static short nextTransactionId = 0x37; /* --------- Read Functions --------- */ int buildReadHoldingRegistersPacket( unsigned char* sendBuffer, int startReg, int numRegs, int unitId, int prependZeros ) { int offset = 0; if(prependZeros != 0){ sendBuffer[0] = 0; sendBuffer[1] = 0; offset = 2; } // Bytes 0 and 1 are TransID sendBuffer[0+offset] = (unsigned char)((nextTransactionId >> 8) & 0xff); sendBuffer[1+offset] = (unsigned char)(nextTransactionId & 0xff); nextTransactionId++; // Bytes 2 and 3 are ProtocolID, set to 0 sendBuffer[2+offset] = 0; sendBuffer[3+offset] = 0; // Bytes 4 and 5 are length. sendBuffer[4+offset] = 0; sendBuffer[5+offset] = 6; // Byte 6 is Unit ID. sendBuffer[6+offset] = unitId; // Byte 7 is Read Holding Registers ( function # 3 ) sendBuffer[7+offset] = 3; // Bytes 8 and 9 are Address sendBuffer[8+offset] = (unsigned char)((startReg >> 8) & 0xff); sendBuffer[9+offset] = (unsigned char)(startReg & 0xff); //Bytes 10 and 11 are NumRegs sendBuffer[10+offset] = (unsigned char)((numRegs >> 8) & 0xff); sendBuffer[11+offset] = (unsigned char)(numRegs & 0xff); return 9+(numRegs*2); } float parseFPRegisterResponse(unsigned char* recBuffer, int offset) { unsigned char fBuffer[4]; float* fPointer; fBuffer[0] = recBuffer[offset + 3]; fBuffer[1] = recBuffer[offset + 2]; fBuffer[2] = recBuffer[offset + 1]; fBuffer[3] = recBuffer[offset]; fPointer = (float*)fBuffer; return *fPointer; } int parseIntRegisterResponse(unsigned char* recBuffer, int offset) { unsigned char iBuffer[4]; int* iPointer; iBuffer[0] = recBuffer[offset + 3]; iBuffer[1] = recBuffer[offset + 2]; iBuffer[2] = recBuffer[offset + 1]; iBuffer[3] = recBuffer[offset]; iPointer = (int*)iBuffer; return *iPointer; } short parseShortRegisterResponse(unsigned char* recBuffer, int offset) { unsigned char sBuffer[4]; short* sPointer; sBuffer[0] = recBuffer[offset + 1]; sBuffer[1] = recBuffer[offset]; sPointer = (short*)sBuffer; return *sPointer; } int buildWriteHoldingRegistersPacket(unsigned char* sendBuffer, int startReg, int numRegs, int unitId, int prependZeros) { int offset = 0; if(prependZeros != 0){ sendBuffer[0] = 0; sendBuffer[1] = 0; offset = 2; } // Bytes 0 and 1 are TransID sendBuffer[0+offset] = (unsigned char)((nextTransactionId >> 8) & 0xff); sendBuffer[1+offset] = (unsigned char)(nextTransactionId & 0xff); nextTransactionId++; // Bytes 2 and 3 are ProtocolID, set to 0 sendBuffer[2+offset] = 0; sendBuffer[3+offset] = 0; // Bytes 4 and 5 are length. sendBuffer[4+offset] = 0; sendBuffer[5+offset] = 7 + (numRegs * 2); // Byte 6 is Unit ID. sendBuffer[6+offset] = unitId; // Byte 7 is Read Holding Registers ( function # 3 ) sendBuffer[7+offset] = 16; // Bytes 8 and 9 are Address sendBuffer[8+offset] = (unsigned char)((startReg >> 8) & 0xff); sendBuffer[9+offset] = (unsigned char)(startReg & 0xff); // Bytes 10 and 11 are NumRegs sendBuffer[10+offset] = (unsigned char)((numRegs >> 8) & 0xff); sendBuffer[11+offset] = (unsigned char)(numRegs & 0xff); // Byte 12 is Byte Count, or 2 * numReg sendBuffer[12+offset] = (unsigned char)((numRegs * 2) & 0xff); // The rest of the bytes are up to the user. return 12; // Write Registers always return 12 bytes. } int putFPIntoBuffer( unsigned char* sendBuffer, int offset, float value) { unsigned char* bPointer; bPointer = (unsigned char*)&value; sendBuffer[offset] = bPointer[3]; sendBuffer[offset+1] = bPointer[2]; sendBuffer[offset+2] = bPointer[1]; sendBuffer[offset+3] = bPointer[0]; return 0; } int putIntIntoBuffer( unsigned char* sendBuffer, int offset, int value ) { unsigned char* bPointer; bPointer = (unsigned char*)&value; sendBuffer[offset] = bPointer[3]; sendBuffer[offset+1] = bPointer[2]; sendBuffer[offset+2] = bPointer[1]; sendBuffer[offset+3] = bPointer[0]; return 0; } int putShortIntoBuffer( unsigned char* sendBuffer, int offset, short value ) { unsigned char* bPointer; bPointer = (unsigned char*)&value; sendBuffer[offset] = bPointer[1]; sendBuffer[offset+1] = bPointer[0]; return 0; }
523
./exodriver/examples/Modbus/writeModbusExample.c
/* * A simple example that shows how to used modbus.h with the Exodriver by * writing 2.0 to DAC0. * * The most important thing to get right are your buffer lengths. With write * register, it can be a little tricky. The base packet is 13 bytes, then 2 * extra bytes for every register you're going to write to. Because of a weird * quirk with LabJacks, you need to prepend two bytes of zeros. This makes the * equation as follows: send buffer length = 2 + 13 + (2 * number of registers). * * The response is always 12 bytes, so that part is easy. * * Another possible point of confusion with writing is that you have to setup * the basic bytes with buildWriteHoldingRegistersPacket then insert the values * with put*IntoBuffer functions. Your first value should always go in offset * 15. If you are putting multiple values in one packet, the offset of the * second value will depend on the type of the first value. Floats and Integers * will both take 4 bytes, and Shorts will only take 2. So, if you are writing a * Float then a Short, the Float will go in offset 15, the Short in offset 19. * If it's a Short than a Float, the Short will have offset 15, and the Float * should be put in offset 17. * * For more information about Modbus, please see the support page: * http://labjack.com/support/modbus */ #include <stdio.h> #include "modbus.h" #include "labjackusb.h" // Set to 3 (U3), 6 (U6), or 9 (UE9). #define DEVICE_TYPE 3 // Set to what you want the DAC to output. #define DAC_VALUE 2.0f // 13 + (2*numReg) + 2 = 13 + (2*2) + 2 = 19 #define WRITE_REGISTER_SEND_LENGTH 19 // Write Holding Register Response Packets are always 12 bytes #define WRITE_REGISTER_REC_LENGTH 12 int main() { HANDLE devHandle; int i; int r = 0; // For checking return values int startReg = 5000; // Start at register 5000 int numRegs = 2; // DAC0 is floating point, so need to write 2 registers int unitId = 0; // For UD family devices, always 0 int prependZeros = 1; // For UD family devices on USB, always 1 int numBytesToRead = WRITE_REGISTER_REC_LENGTH; BYTE sendBuffer[WRITE_REGISTER_SEND_LENGTH]; BYTE recBuffer[WRITE_REGISTER_REC_LENGTH]; // Same as numBytesToRead // Open the device devHandle = LJUSB_OpenDevice(1, 0, DEVICE_TYPE); if(devHandle <= 0){ printf("ERROR: Couldn't find a LabJack to open."); return -1; } if(DEVICE_TYPE == 3){ printf("Opened first found U3.\n"); } else if(DEVICE_TYPE == 6) { printf("Opened first found U6.\n"); } else { printf("Opened first found UE9.\n"); } // Build the packet. numBytesToRead = buildWriteHoldingRegistersPacket(sendBuffer, startReg, numRegs, unitId, prependZeros); printf("Built Write Holding Registers Packet to write register 5000 (DAC0).\n"); // Puts DAC_VALUE into the buffer. putFPIntoBuffer(sendBuffer, 15, DAC_VALUE); printf("Added value %.2f to buffer.\n", DAC_VALUE); // Send packet to the device. r = LJUSB_Write(devHandle, sendBuffer, WRITE_REGISTER_SEND_LENGTH); if( r != WRITE_REGISTER_SEND_LENGTH ){ printf("ERROR: An error occurred while writing to the device."); LJUSB_CloseDevice(devHandle); return -1; } printf("Wrote command to device.\n"); printf("Sent = ["); for( i = 0; i < WRITE_REGISTER_SEND_LENGTH-1; i++){ printf("0x%X, ", sendBuffer[i]); } printf("0x%X]\n\n", sendBuffer[WRITE_REGISTER_SEND_LENGTH-1]); // Read the response from the device. r = LJUSB_Read(devHandle, recBuffer, numBytesToRead); if( r != numBytesToRead ){ printf("ERROR: An error occurred while reading from the device.\n r = %i", r); LJUSB_CloseDevice(devHandle); return -1; } printf("Read the response.\n"); printf("Read = ["); for( i = 0; i < numBytesToRead-1; i++){ printf("0x%X, ", recBuffer[i]); } printf("0x%X]\n\n", recBuffer[numBytesToRead-1]); // Close the device. LJUSB_CloseDevice(devHandle); printf("Closed Device.\n"); return 0; }
524
./exodriver/examples/U12/u12AISample.c
/* An example that shows a minimal use of Exodriver without the use of functions hidden in header files. You can compile this example with the following command: $ g++ -lm -llabjackusb u12AISample.c It is also included in the Makefile. */ /* Includes */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "labjackusb.h" #include <libusb-1.0/libusb.h> // All U12 commands are 8 bytes. #define U12_COMMAND_LENGTH 8 /* LabJack Related Helper Functions Protoypes */ int writeRead(HANDLE devHandle, BYTE * sendBuffer, BYTE * recBuffer ); // Demonstrates how to build the AIStream packet. void buildAISampleBytes(BYTE * sendBuffer); // Demonstrates how to parse the response of AIStream. void parseAISampleBytes(BYTE * recBuffer); int main() { // Setup the variables we will need. int r = 0; // For checking return values HANDLE devHandle = 0; BYTE sendBuffer[U12_COMMAND_LENGTH], recBuffer[U12_COMMAND_LENGTH]; // Open the U12 devHandle = LJUSB_OpenDevice(1, 0, U12_PRODUCT_ID); if( devHandle == NULL ) { printf("Couldn't open U12. Please connect one and try again.\n"); exit(-1); } // Builds the AISample command buildAISampleBytes(sendBuffer); // Write the command, and read the response. r = writeRead(devHandle, sendBuffer, recBuffer ); // If the U12 is freshly plugged in, then it will not respond to the // first command. Write it again. if( r == -1){ r = writeRead(devHandle, sendBuffer, recBuffer ); if(r != 0){ // If you still have errors after the first try, then you have // bigger problems. printf("Command timed out twice. Exiting..."); LJUSB_CloseDevice(devHandle); exit(-1); } } // Parse the response into something useful parseAISampleBytes(recBuffer); //Close the device. LJUSB_CloseDevice(devHandle); return 0; } /* ------------- LabJack Related Helper Functions Definitions ------------- */ int writeRead(HANDLE devHandle, BYTE * sendBuffer, BYTE * recBuffer ) { int r = 0; // Write the command to the device. // LJUSB_Write( handle, sendBuffer, length of sendBuffer ) r = LJUSB_Write( devHandle, sendBuffer, U12_COMMAND_LENGTH ); if( r != U12_COMMAND_LENGTH ) { printf("An error occurred when trying to write the buffer. The error was: %d\n", errno); // *Always* close the device when you error out. LJUSB_CloseDevice(devHandle); exit(-1); } // Read the result from the device. // LJUSB_Read( handle, recBuffer, number of bytes to read) r = LJUSB_Read( devHandle, recBuffer, U12_COMMAND_LENGTH ); if( r != U12_COMMAND_LENGTH ) { if(errno == LIBUSB_ERROR_TIMEOUT) { return -1; } printf("An error occurred when trying to read from the U12. The error was: %d\n", errno); LJUSB_CloseDevice(devHandle); exit(-1); } return 0; } // Uses information from section 5.1 of the U12 User's Guide to make a AISample // packet. // http://labjack.com/support/u12/users-guide/5.1 void buildAISampleBytes(BYTE * sendBuffer) { // Build up the bytes sendBuffer[0] = 8; // Set PGAMUX for single-ended AI0 sendBuffer[1] = 9; // Set PGAMUX for single-ended AI1 sendBuffer[2] = 10; // Set PGAMUX for single-ended AI2 sendBuffer[3] = 11; // Set PGAMUX for single-ended AI3 sendBuffer[4] = 1; // UpdateIO = 0, LEDState = 1 sendBuffer[5] = 192; // 0b11000000 = (AISample) sendBuffer[6] = 0; // XXXXXXXX sendBuffer[7] = 0; // Echo Value // The bytes have been set. We are ready to write to the U12. } // Parses the AISample packet into something useful. void parseAISampleBytes(BYTE * recBuffer){ int temp; double ai0, ai1, ai2, ai3; // Apply the single-ended conversion to results temp = (recBuffer[2] >> 4) & 0xf; temp = (temp << 8) + recBuffer[3]; ai0 = ((double)temp * 20.0 / 4096.0) - 10; temp = recBuffer[2] & 0xf; temp = (temp << 8) + recBuffer[4]; ai1 = ((double)temp * 20.0 / 4096.0) - 10; temp = (recBuffer[5] >> 4) & 0xf; temp = (temp << 8) + recBuffer[6]; ai2 = ((double)temp * 20.0 / 4096.0) - 10; temp = recBuffer[5] & 0xf; temp = (temp << 8) + recBuffer[7]; ai3 = ((double)temp * 20.0 / 4096.0) - 10; printf("Results of AISample:\n"); printf(" AI0 = %f\n", ai0); printf(" AI1 = %f\n", ai1); printf(" AI2 = %f\n", ai2); printf(" AI3 = %f\n", ai3); printf(" PGA Overvoltage = %d\n", (recBuffer[0] >> 4) & 1); printf(" IO3 to IO0 States = %d\n", recBuffer[0] & 15); printf(" TimerCounterMask = %d\n", recBuffer[22]); }
525
./jsonrpc-c/example/server.c
/* * server.c * * Created on: Oct 9, 2012 * Author: hmng */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include "jsonrpc-c.h" #define PORT 1234 // the port users will be connecting to struct jrpc_server my_server; cJSON * say_hello(jrpc_context * ctx, cJSON * params, cJSON *id) { return cJSON_CreateString("Hello!"); } cJSON * exit_server(jrpc_context * ctx, cJSON * params, cJSON *id) { jrpc_server_stop(&my_server); return cJSON_CreateString("Bye!"); } int main(void) { jrpc_server_init(&my_server, PORT); jrpc_register_procedure(&my_server, say_hello, "sayHello", NULL ); jrpc_register_procedure(&my_server, exit_server, "exit", NULL ); jrpc_server_run(&my_server); jrpc_server_destroy(&my_server); return 0; }
526
./jsonrpc-c/src/jsonrpc-c.c
/* * jsonrpc-c.c * * Created on: Oct 11, 2012 * Author: hmng */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include "jsonrpc-c.h" struct ev_loop *loop; // get sockaddr, IPv4 or IPv6: static void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*) sa)->sin_addr); } return &(((struct sockaddr_in6*) sa)->sin6_addr); } static int send_response(struct jrpc_connection * conn, char *response) { int fd = conn->fd; if (conn->debug_level > 1) printf("JSON Response:\n%s\n", response); write(fd, response, strlen(response)); write(fd, "\n", 1); return 0; } static int send_error(struct jrpc_connection * conn, int code, char* message, cJSON * id) { int return_value = 0; cJSON *result_root = cJSON_CreateObject(); cJSON *error_root = cJSON_CreateObject(); cJSON_AddNumberToObject(error_root, "code", code); cJSON_AddStringToObject(error_root, "message", message); cJSON_AddItemToObject(result_root, "error", error_root); cJSON_AddItemToObject(result_root, "id", id); char * str_result = cJSON_Print(result_root); return_value = send_response(conn, str_result); free(str_result); cJSON_Delete(result_root); free(message); return return_value; } static int send_result(struct jrpc_connection * conn, cJSON * result, cJSON * id) { int return_value = 0; cJSON *result_root = cJSON_CreateObject(); if (result) cJSON_AddItemToObject(result_root, "result", result); cJSON_AddItemToObject(result_root, "id", id); char * str_result = cJSON_Print(result_root); return_value = send_response(conn, str_result); free(str_result); cJSON_Delete(result_root); return return_value; } static int invoke_procedure(struct jrpc_server *server, struct jrpc_connection * conn, char *name, cJSON *params, cJSON *id) { cJSON *returned = NULL; int procedure_found = 0; jrpc_context ctx; ctx.error_code = 0; ctx.error_message = NULL; int i = server->procedure_count; while (i--) { if (!strcmp(server->procedures[i].name, name)) { procedure_found = 1; ctx.data = server->procedures[i].data; returned = server->procedures[i].function(&ctx, params, id); break; } } if (!procedure_found) return send_error(conn, JRPC_METHOD_NOT_FOUND, strdup("Method not found."), id); else { if (ctx.error_code) return send_error(conn, ctx.error_code, ctx.error_message, id); else return send_result(conn, returned, id); } } static int eval_request(struct jrpc_server *server, struct jrpc_connection * conn, cJSON *root) { cJSON *method, *params, *id; method = cJSON_GetObjectItem(root, "method"); if (method != NULL && method->type == cJSON_String) { params = cJSON_GetObjectItem(root, "params"); if (params == NULL|| params->type == cJSON_Array || params->type == cJSON_Object) { id = cJSON_GetObjectItem(root, "id"); if (id == NULL|| id->type == cJSON_String || id->type == cJSON_Number) { //We have to copy ID because using it on the reply and deleting the response Object will also delete ID cJSON * id_copy = NULL; if (id != NULL) id_copy = (id->type == cJSON_String) ? cJSON_CreateString( id->valuestring) : cJSON_CreateNumber(id->valueint); if (server->debug_level) printf("Method Invoked: %s\n", method->valuestring); return invoke_procedure(server, conn, method->valuestring, params, id_copy); } } } send_error(conn, JRPC_INVALID_REQUEST, strdup("The JSON sent is not a valid Request object."), NULL); return -1; } static void close_connection(struct ev_loop *loop, ev_io *w) { ev_io_stop(loop, w); close(((struct jrpc_connection *) w)->fd); free(((struct jrpc_connection *) w)->buffer); free(((struct jrpc_connection *) w)); } static void connection_cb(struct ev_loop *loop, ev_io *w, int revents) { struct jrpc_connection *conn; struct jrpc_server *server = (struct jrpc_server *) w->data; size_t bytes_read = 0; //get our 'subclassed' event watcher conn = (struct jrpc_connection *) w; int fd = conn->fd; if (conn->pos == (conn->buffer_size - 1)) { char * new_buffer = realloc(conn->buffer, conn->buffer_size *= 2); if (new_buffer == NULL) { perror("Memory error"); return close_connection(loop, w); } conn->buffer = new_buffer; memset(conn->buffer + conn->pos, 0, conn->buffer_size - conn->pos); } // can not fill the entire buffer, string must be NULL terminated int max_read_size = conn->buffer_size - conn->pos - 1; if ((bytes_read = read(fd, conn->buffer + conn->pos, max_read_size)) == -1) { perror("read"); return close_connection(loop, w); } if (!bytes_read) { // client closed the sending half of the connection if (server->debug_level) printf("Client closed connection.\n"); return close_connection(loop, w); } else { cJSON *root; char *end_ptr; conn->pos += bytes_read; if ((root = cJSON_Parse_Stream(conn->buffer, &end_ptr)) != NULL) { if (server->debug_level > 1) { char * str_result = cJSON_Print(root); printf("Valid JSON Received:\n%s\n", str_result); free(str_result); } if (root->type == cJSON_Object) { eval_request(server, conn, root); } //shift processed request, discarding it memmove(conn->buffer, end_ptr, strlen(end_ptr) + 2); conn->pos = strlen(end_ptr); memset(conn->buffer + conn->pos, 0, conn->buffer_size - conn->pos - 1); cJSON_Delete(root); } else { // did we parse the all buffer? If so, just wait for more. // else there was an error before the buffer's end if (cJSON_GetErrorPtr() != (conn->buffer + conn->pos)) { if (server->debug_level) { printf("INVALID JSON Received:\n---\n%s\n---\n", conn->buffer); } send_error(conn, JRPC_PARSE_ERROR, strdup( "Parse error. Invalid JSON was received by the server."), NULL); return close_connection(loop, w); } } } } static void accept_cb(struct ev_loop *loop, ev_io *w, int revents) { char s[INET6_ADDRSTRLEN]; struct jrpc_connection *connection_watcher; connection_watcher = malloc(sizeof(struct jrpc_connection)); struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; sin_size = sizeof their_addr; connection_watcher->fd = accept(w->fd, (struct sockaddr *) &their_addr, &sin_size); if (connection_watcher->fd == -1) { perror("accept"); free(connection_watcher); } else { if (((struct jrpc_server *) w->data)->debug_level) { inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *) &their_addr), s, sizeof s); printf("server: got connection from %s\n", s); } ev_io_init(&connection_watcher->io, connection_cb, connection_watcher->fd, EV_READ); //copy pointer to struct jrpc_server connection_watcher->io.data = w->data; connection_watcher->buffer_size = 1500; connection_watcher->buffer = malloc(1500); memset(connection_watcher->buffer, 0, 1500); connection_watcher->pos = 0; //copy debug_level, struct jrpc_connection has no pointer to struct jrpc_server connection_watcher->debug_level = ((struct jrpc_server *) w->data)->debug_level; ev_io_start(loop, &connection_watcher->io); } } int jrpc_server_init(struct jrpc_server *server, int port_number) { loop = EV_DEFAULT; return jrpc_server_init_with_ev_loop(server, port_number, loop); } int jrpc_server_init_with_ev_loop(struct jrpc_server *server, int port_number, struct ev_loop *loop) { memset(server, 0, sizeof(struct jrpc_server)); server->loop = loop; server->port_number = port_number; char * debug_level_env = getenv("JRPC_DEBUG"); if (debug_level_env == NULL) server->debug_level = 0; else { server->debug_level = strtol(debug_level_env, NULL, 10); printf("JSONRPC-C Debug level %d\n", server->debug_level); } return __jrpc_server_start(server); } static int __jrpc_server_start(struct jrpc_server *server) { int sockfd; struct addrinfo hints, *servinfo, *p; int yes = 1; int rv; char PORT[6]; sprintf(PORT, "%d", server->port_number); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); return 2; } freeaddrinfo(servinfo); // all done with this structure if (listen(sockfd, 5) == -1) { perror("listen"); exit(1); } if (server->debug_level) printf("server: waiting for connections...\n"); ev_io_init(&server->listen_watcher, accept_cb, sockfd, EV_READ); server->listen_watcher.data = server; ev_io_start(server->loop, &server->listen_watcher); return 0; } // Make the code work with both the old (ev_loop/ev_unloop) // and new (ev_run/ev_break) versions of libev. #ifdef EVUNLOOP_ALL #define EV_RUN ev_loop #define EV_BREAK ev_unloop #define EVBREAK_ALL EVUNLOOP_ALL #else #define EV_RUN ev_run #define EV_BREAK ev_break #endif void jrpc_server_run(struct jrpc_server *server){ EV_RUN(server->loop, 0); } int jrpc_server_stop(struct jrpc_server *server) { EV_BREAK(server->loop, EVBREAK_ALL); return 0; } void jrpc_server_destroy(struct jrpc_server *server){ /* Don't destroy server */ int i; for (i = 0; i < server->procedure_count; i++){ jrpc_procedure_destroy( &(server->procedures[i]) ); } free(server->procedures); } static void jrpc_procedure_destroy(struct jrpc_procedure *procedure){ if (procedure->name){ free(procedure->name); procedure->name = NULL; } if (procedure->data){ free(procedure->data); procedure->data = NULL; } } int jrpc_register_procedure(struct jrpc_server *server, jrpc_function function_pointer, char *name, void * data) { int i = server->procedure_count++; if (!server->procedures) server->procedures = malloc(sizeof(struct jrpc_procedure)); else { struct jrpc_procedure * ptr = realloc(server->procedures, sizeof(struct jrpc_procedure) * server->procedure_count); if (!ptr) return -1; server->procedures = ptr; } if ((server->procedures[i].name = strdup(name)) == NULL) return -1; server->procedures[i].function = function_pointer; server->procedures[i].data = data; return 0; } int jrpc_deregister_procedure(struct jrpc_server *server, char *name) { /* Search the procedure to deregister */ int i; int found = 0; if (server->procedures){ for (i = 0; i < server->procedure_count; i++){ if (found) server->procedures[i-1] = server->procedures[i]; else if(!strcmp(name, server->procedures[i].name)){ found = 1; jrpc_procedure_destroy( &(server->procedures[i]) ); } } if (found){ server->procedure_count--; if (server->procedure_count){ struct jrpc_procedure * ptr = realloc(server->procedures, sizeof(struct jrpc_procedure) * server->procedure_count); if (!ptr){ perror("realloc"); return -1; } server->procedures = ptr; }else{ server->procedures = NULL; } } } else { fprintf(stderr, "server : procedure '%s' not found\n", name); return -1; } return 0; }
527
./jsonrpc-c/src/cJSON.c
/* Copyright (c) 2009 Dave Gamble 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. */ /* cJSON */ /* JSON parser in C. */ #include <string.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <float.h> #include <limits.h> #include <ctype.h> #include "cJSON.h" static const char *ep; //static const char *end_ptr; const char *cJSON_GetErrorPtr() {return ep;} static int cJSON_strcasecmp(const char *s1,const char *s2) { if (!s1) return (s1==s2)?0:1;if (!s2) return 1; for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } static void *(*cJSON_malloc)(size_t sz) = malloc; static void (*cJSON_free)(void *ptr) = free; static char* cJSON_strdup(const char* str) { size_t len; char* copy; len = strlen(str) + 1; if (!(copy = (char*)cJSON_malloc(len))) return 0; memcpy(copy,str,len); return copy; } void cJSON_InitHooks(cJSON_Hooks* hooks) { if (!hooks) { /* Reset hooks */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; cJSON_free = (hooks->free_fn)?hooks->free_fn:free; } /* Internal constructor. */ static cJSON *cJSON_New_Item() { cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); if (node) memset(node,0,sizeof(cJSON)); return node; } /* Delete a cJSON structure. */ void cJSON_Delete(cJSON *c) { cJSON *next; while (c) { next=c->next; if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); if (c->string) cJSON_free(c->string); cJSON_free(c); c=next; } } /* Parse the input text to generate a number, and populate the result into item. */ static const char *parse_number(cJSON *item,const char *num) { double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; /* Could use sscanf for this? */ if (*num=='-') sign=-1,num++; /* Has sign? */ if (*num=='0') num++; /* is zero */ if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ if (*num=='e' || *num=='E') /* Exponent? */ { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ } n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ item->valuedouble=n; item->valueint=(int)n; item->type=cJSON_Number; return num; } /* Render the number nicely from the given item into a string. */ static char *print_number(cJSON *item) { char *str; double d=item->valuedouble; if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) { str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ if (str) sprintf(str,"%d",item->valueint); } else { str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ if (str) { if (fabs(floor(d)-d)<=DBL_EPSILON) sprintf(str,"%.0f",d); else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); else sprintf(str,"%f",d); } } return str; } /* Parse the input text into an unescaped cstring, and populate item. */ static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; static const char *parse_string(cJSON *item,const char *str) { const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; if (*str!='\"') {ep=str;return 0;} /* not a string! */ while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ if (!out) return 0; ptr=str+1;ptr2=out; while (*ptr!='\"' && *ptr) { if (*ptr!='\\') *ptr2++=*ptr++; else { ptr++; switch (*ptr) { case 'b': *ptr2++='\b'; break; case 'f': *ptr2++='\f'; break; case 'n': *ptr2++='\n'; break; case 'r': *ptr2++='\r'; break; case 't': *ptr2++='\t'; break; case 'u': /* transcode utf16 to utf8. */ sscanf(ptr+1,"%4x",&uc);ptr+=4; /* get the unicode char. */ if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; // check for invalid. if (uc>=0xD800 && uc<=0xDBFF) // UTF16 surrogate pairs. { if (ptr[1]!='\\' || ptr[2]!='u') break; // missing second-half of surrogate. sscanf(ptr+3,"%4x",&uc2);ptr+=6; if (uc2<0xDC00 || uc2>0xDFFF) break; // invalid second-half of surrogate. uc=0x10000 | ((uc&0x3FF)<<10) | (uc2&0x3FF); } len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; switch (len) { case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; case 1: *--ptr2 =(uc | firstByteMark[len]); } ptr2+=len; break; default: *ptr2++=*ptr; break; } ptr++; } } *ptr2=0; if (*ptr=='\"') ptr++; item->valuestring=out; item->type=cJSON_String; return ptr; } /* Render the cstring provided to an escaped version that can be printed. */ static char *print_string_ptr(const char *str) { const char *ptr;char *ptr2,*out;int len=0;unsigned char token; if (!str) return cJSON_strdup(""); ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;ptr=str; *ptr2++='\"'; while (*ptr) { if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; else { *ptr2++='\\'; switch (token=*ptr++) { case '\\': *ptr2++='\\'; break; case '\"': *ptr2++='\"'; break; case '\b': *ptr2++='b'; break; case '\f': *ptr2++='f'; break; case '\n': *ptr2++='n'; break; case '\r': *ptr2++='r'; break; case '\t': *ptr2++='t'; break; default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ } } } *ptr2++='\"';*ptr2++=0; return out; } /* Invote print_string_ptr (which is useful) on an item. */ static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);} /* Predeclare these prototypes. */ static const char *parse_value(cJSON *item,const char *value); static char *print_value(cJSON *item,int depth,int fmt); static const char *parse_array(cJSON *item,const char *value); static char *print_array(cJSON *item,int depth,int fmt); static const char *parse_object(cJSON *item,const char *value); static char *print_object(cJSON *item,int depth,int fmt); /* Utility to jump whitespace and cr/lf */ static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} /* Parse an object - create a new root, and populate. */ cJSON *cJSON_Parse(const char *value) { cJSON *c=cJSON_New_Item(); ep=0; if (!c) return 0; /* memory fail */ if (!parse_value(c,skip(value))) {cJSON_Delete(c);return 0;} return c; } /* Parse an object - create a new root, and populate * Also indicates where in the stream the Object ends. */ cJSON *cJSON_Parse_Stream(const char *value, char **end_ptr) { if(!end_ptr) return NULL; cJSON *c=cJSON_New_Item(); ep=0; if (!c) return 0; /* memory fail */ if (!(*end_ptr=parse_value(c,skip(value)))) {cJSON_Delete(c);return 0;} return c; } /* Render a cJSON item/entity/structure to text. */ char *cJSON_Print(cJSON *item) {return print_value(item,0,1);} char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0);} /* Parser core - when encountering text, process appropriately. */ static const char *parse_value(cJSON *item,const char *value) { if (!value) return 0; /* Fail on null. */ if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } if (*value=='\"') { return parse_string(item,value); } if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } if (*value=='[') { return parse_array(item,value); } if (*value=='{') { return parse_object(item,value); } ep=value;return 0; /* failure. */ } /* Render a value to text. */ static char *print_value(cJSON *item,int depth,int fmt) { char *out=0; if (!item) return 0; switch ((item->type)&255) { case cJSON_NULL: out=cJSON_strdup("null"); break; case cJSON_False: out=cJSON_strdup("false");break; case cJSON_True: out=cJSON_strdup("true"); break; case cJSON_Number: out=print_number(item);break; case cJSON_String: out=print_string(item);break; case cJSON_Array: out=print_array(item,depth,fmt);break; case cJSON_Object: out=print_object(item,depth,fmt);break; } return out; } /* Build an array from input text. */ static const char *parse_array(cJSON *item,const char *value) { cJSON *child; if (*value!='[') {ep=value;return 0;} /* not an array! */ item->type=cJSON_Array; value=skip(value+1); if (*value==']') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; /* memory fail */ value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { const char *nextch = skip(value+1); if (nextch!=0 && *nextch==']') {value=nextch;break;} cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_value(child,nextch)); if (!value) return 0; /* memory fail */ } if (*value==']') return value+1; /* end of array */ ep=value;return 0; /* malformed. */ } /* Render an array to text */ static char *print_array(cJSON *item,int depth,int fmt) { char **entries; char *out=0,*ptr,*ret;int len=5; cJSON *child=item->child; int numentries=0,i=0,fail=0; /* How many entries in the array? */ while (child) numentries++,child=child->next; /* Allocate an array to hold the values for each */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; memset(entries,0,numentries*sizeof(char*)); /* Retrieve all the results: */ child=item->child; while (child && !fail) { ret=print_value(child,depth+1,fmt); entries[i++]=ret; if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; child=child->next; } /* If we didn't fail, try to malloc the output string */ if (!fail) out=(char*)cJSON_malloc(len); /* If that fails, we fail. */ if (!out) fail=1; /* Handle failure. */ if (fail) { for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]); cJSON_free(entries); return 0; } /* Compose the output array. */ *out='['; ptr=out+1;*ptr=0; for (i=0;i<numentries;i++) { strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;} cJSON_free(entries[i]); } cJSON_free(entries); *ptr++=']';*ptr++=0; return out; } /* Build an object from the text. */ static const char *parse_object(cJSON *item,const char *value) { cJSON *child; if (*value!='{') {ep=value;return 0;} /* not an object! */ item->type=cJSON_Object; value=skip(value+1); if (*value=='}') return value+1; /* empty array. */ item->child=child=cJSON_New_Item(); if (!item->child) return 0; value=skip(parse_string(child,skip(value))); if (!value) return 0; child->string=child->valuestring;child->valuestring=0; if (*value!=':') {ep=value;return 0;} /* fail! */ value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ if (!value) return 0; while (*value==',') { const char *nextch = skip(value+1); if (nextch!=0 && *nextch=='}') {value=nextch;break;} cJSON *new_item; if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ child->next=new_item;new_item->prev=child;child=new_item; value=skip(parse_string(child,nextch)); if (!value) return 0; child->string=child->valuestring;child->valuestring=0; if (*value!=':') {ep=value;return 0;} /* fail! */ value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ if (!value) return 0; } if (*value=='}') return value+1; /* end of array */ ep=value;return 0; /* malformed. */ } /* Render an object to text. */ static char *print_object(cJSON *item,int depth,int fmt) { char **entries=0,**names=0; char *out=0,*ptr,*ret,*str;int len=7,i=0,j; cJSON *child=item->child; int numentries=0,fail=0; /* Count the number of entries. */ while (child) numentries++,child=child->next; /* Allocate space for the names and the objects */ entries=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!entries) return 0; names=(char**)cJSON_malloc(numentries*sizeof(char*)); if (!names) {cJSON_free(entries);return 0;} memset(entries,0,sizeof(char*)*numentries); memset(names,0,sizeof(char*)*numentries); /* Collect all the results into our arrays: */ child=item->child;depth++;if (fmt) len+=depth; while (child) { names[i]=str=print_string_ptr(child->string); entries[i++]=ret=print_value(child,depth,fmt); if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; child=child->next; } /* Try to allocate the output string */ if (!fail) out=(char*)cJSON_malloc(len); if (!out) fail=1; /* Handle failure */ if (fail) { for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);} cJSON_free(names);cJSON_free(entries); return 0; } /* Compose the output: */ *out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0; for (i=0;i<numentries;i++) { if (fmt) for (j=0;j<depth;j++) *ptr++='\t'; strcpy(ptr,names[i]);ptr+=strlen(names[i]); *ptr++=':';if (fmt) *ptr++='\t'; strcpy(ptr,entries[i]);ptr+=strlen(entries[i]); if (i!=numentries-1) *ptr++=','; if (fmt) *ptr++='\n';*ptr=0; cJSON_free(names[i]);cJSON_free(entries[i]); } cJSON_free(names);cJSON_free(entries); if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t'; *ptr++='}';*ptr++=0; return out; } /* Get Array size/item / object item. */ int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;} cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} /* Utility for array list handling. */ static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} /* Utility for handling references. */ static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} /* Add item to array/object. */ void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} /* Replace array/object items with new ones. */ void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} /* Create basic types: */ cJSON *cJSON_CreateNull() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} cJSON *cJSON_CreateTrue() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} cJSON *cJSON_CreateFalse() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} cJSON *cJSON_CreateArray() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} cJSON *cJSON_CreateObject() {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} /* Create Arrays: */ cJSON *cJSON_CreateIntArray(int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateFloatArray(float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateDoubleArray(double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;} cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
528
./aq2-tng/source/a_cmds.c
//----------------------------------------------------------------------------- // zucc // File for our new commands. // // laser sight patch, by Geza Beladi // // $Id: a_cmds.c,v 1.33 2003/06/15 15:34:32 igor Exp $ // //----------------------------------------------------------------------------- // $Log: a_cmds.c,v $ // Revision 1.33 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.32 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.31 2002/09/04 11:23:09 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.30 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.29 2002/03/28 13:30:36 freud // Included time played in ghost. // // Revision 1.28 2002/03/25 23:35:19 freud // Ghost code, use_ghosts and more stuff.. // // Revision 1.27 2002/03/25 18:32:11 freud // I'm being too productive.. New ghost command needs testing. // // Revision 1.26 2002/03/25 16:34:39 freud // Cmd_Time changes. When timelimit is 0 it says timelimit disables instead of // displaying 0 minutes 0 seconds left. // // Revision 1.25 2002/03/24 19:38:05 ra // Securityfix // // Revision 1.24 2002/01/24 11:29:34 ra // Cleanup's in stats code // // Revision 1.23 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.22 2002/01/24 01:40:40 deathwatch // Freud's AutoRecord // // Revision 1.21 2001/11/25 19:09:25 slicerdw // Fixed Matchtime // // Revision 1.20 2001/11/03 17:21:57 deathwatch // Fixed something in the time command, removed the .. message from the voice command, fixed the vote spamming with mapvote, removed addpoint command (old pb command that wasnt being used). Some cleaning up of the source at a few points. // // Revision 1.19 2001/10/26 00:40:07 ra // Minor fix to time command // // Revision 1.18 2001/10/18 12:55:35 deathwatch // Added roundtimeleft // // Revision 1.17 2001/10/18 12:45:47 ra // Disable time command in matchmode // // Revision 1.16 2001/09/30 03:09:34 ra // Removed new stats at end of rounds and created a new command to // do the same functionality. Command is called "time" // // Revision 1.15 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.14 2001/09/02 20:33:34 deathwatch // Added use_classic and fixed an issue with ff_afterround, also updated version // nr and cleaned up some commands. // // Updated the VC Project to output the release build correctly. // // Revision 1.13 2001/08/18 18:45:19 deathwatch // Edited the Flashlight movement code to the Lasersight's movement code, its probably better // and I added checks for darkmatch/being dead/being a spectator for its use // // Revision 1.12 2001/08/17 21:31:37 deathwatch // Added support for stats // // Revision 1.11 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.10 2001/08/06 12:13:07 slicerdw // Fixed the Sniper Weapon plus reloading bug // // Revision 1.9 2001/07/30 16:04:37 igor_rock // - changed the message for disallowed items (it said "Weapon not...") // // Revision 1.8 2001/07/28 19:30:05 deathwatch // Fixed the choose command (replaced weapon for item when it was working with items) // and fixed some tabs on other documents to make it more readable // // Revision 1.7 2001/07/25 23:02:02 slicerdw // Fixed the source, added the weapons and items capping to choose command // // Revision 1.6 2001/07/16 19:02:06 ra // Fixed compilerwarnings (-g -Wall). Only one remains. // // Revision 1.5 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.4.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.4 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.3 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.2 2001/05/07 02:05:36 ra // // // Added tkok command to forgive teamkills. // // Revision 1.1.1.1 2001/05/06 17:24:14 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" extern void P_ProjectSource(gclient_t * client, vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result); /*---------------------------------------- * SP_LaserSight * * Create/remove the laser sight entity *---------------------------------------*/ void SP_LaserSight(edict_t * self, gitem_t * item) { vec3_t start, forward, right, end; if (!INV_AMMO(self, LASER_NUM)) { if (self->lasersight) { // laser is on G_FreeEdict(self->lasersight); self->lasersight = NULL; } return; } //zucc code to make it be used with the right weapons switch (self->client->curr_weap) { case MK23_NUM: case MP5_NUM: case M4_NUM: break; default: // laser is on but we want it off if (self->lasersight) { G_FreeEdict(self->lasersight); self->lasersight = NULL; } return; } AngleVectors(self->client->v_angle, forward, right, NULL); VectorSet(end, 100, 0, 0); G_ProjectSource(self->s.origin, end, forward, right, start); self->lasersight = G_Spawn(); self->lasersight->owner = self; self->lasersight->movetype = MOVETYPE_NOCLIP; self->lasersight->solid = SOLID_NOT; self->lasersight->classname = "lasersight"; self->lasersight->s.modelindex = gi.modelindex("sprites/lsight.sp2"); self->lasersight->s.renderfx = RF_TRANSLUCENT; self->lasersight->think = LaserSightThink; self->lasersight->nextthink = level.time + 0.01; } /*--------------------------------------------- * LaserSightThink * * Updates the sights position, angle, and shape * is the lasersight entity *-------------------------------------------*/ void LaserSightThink(edict_t * self) { vec3_t start, end, endp, offset; vec3_t forward, right, up, angles; trace_t tr; int height = 0; // zucc compensate for weapon ride up VectorAdd(self->owner->client->v_angle, self->owner->client->kick_angles, angles); AngleVectors(angles, forward, right, up); if (self->owner->lasersight != self) { self->think = G_FreeEdict; } if (self->owner->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; VectorSet(offset, 24, 8, self->owner->viewheight - height); P_ProjectSource(self->owner->client, self->owner->s.origin, offset, forward, right, start); VectorMA(start, 8192, forward, end); PRETRACE(); tr = gi.trace(start, NULL, NULL, end, self->owner, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER); POSTTRACE(); if (tr.fraction != 1) { VectorMA(tr.endpos, -4, forward, endp); VectorCopy(endp, tr.endpos); } vectoangles(tr.plane.normal, self->s.angles); VectorCopy(tr.endpos, self->s.origin); gi.linkentity(self); self->nextthink = level.time + 0.1; } void Cmd_New_Reload_f(edict_t * ent) { //FB 6/1/99 - refuse to reload during LCA if (lights_camera_action) return; ent->client->reload_attempts++; } // Handles weapon reload requests void Cmd_Reload_f(edict_t * ent) { //+BD - If the player is dead, don't bother if (ent->deadflag == DEAD_DEAD) { //gi.centerprintf(ent, "I know you're a hard ass,\nBUT YOU'RE FUCKING DEAD!!\n"); return; } if (ent->client->weaponstate == WEAPON_BANDAGING || ent->client->bandaging == 1 || ent->client->bandage_stopped == 1 || ent->client->weaponstate == WEAPON_ACTIVATING || ent->client->weaponstate == WEAPON_DROPPING || ent->client->weaponstate == WEAPON_FIRING) { return; } if (!ent->client->fast_reload) ent->client->reload_attempts--; if (ent->client->reload_attempts < 0) ent->client->reload_attempts = 0; //First, grab the current magazine max count... //Set the weaponstate... switch(ent->client->curr_weap) { case M3_NUM: if (ent->client->shot_rds >= ent->client->shot_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } // already in the process of reloading! if (ent->client->weaponstate == WEAPON_RELOADING && (ent->client->shot_rds < (ent->client->shot_max - 1)) && !(ent->client->fast_reload) && ((ent->client->pers.inventory[ent->client->ammo_index] - 1) > 0)) { // don't let them start fast reloading until far enough into the firing sequence // this gives them a chance to break off from reloading to fire the weapon - zucc if (ent->client->ps.gunframe >= 48) { ent->client->fast_reload = 1; (ent->client->pers.inventory[ent->client->ammo_index])--; } else { ent->client->reload_attempts++; } } break; case HC_NUM: if (ent->client->cannon_rds >= ent->client->cannon_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } if(hc_single->value) { if(ent->client->resp.hc_mode || ent->client->cannon_rds == 1) { if(ent->client->pers.inventory[ent->client->ammo_index] < 1) return; } else if(ent->client->pers.inventory[ent->client->ammo_index] < 2) return; } else if (ent->client->pers.inventory[ent->client->ammo_index] < 2) return; break; case SNIPER_NUM: if (ent->client->sniper_rds >= ent->client->sniper_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } // already in the process of reloading! if (ent->client->weaponstate == WEAPON_RELOADING && (ent->client->sniper_rds < (ent->client->sniper_max - 1)) && !(ent->client->fast_reload) && ((ent->client->pers.inventory[ent->client->ammo_index] - 1) > 0)) { // don't let them start fast reloading until far enough into the firing sequence // this gives them a chance to break off from reloading to fire the weapon - zucc if (ent->client->ps.gunframe >= 72) { ent->client->fast_reload = 1; (ent->client->pers.inventory[ent->client->ammo_index])--; } else { ent->client->reload_attempts++; } } ent->client->ps.fov = 90; if (ent->client->pers.weapon) ent->client->ps.gunindex = gi.modelindex(ent->client->pers.weapon->view_model); break; case DUAL_NUM: if (ent->client->dual_rds == ent->client->dual_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } //TempFile change to pistol, then reload if (ent->client->pers.inventory[ent->client->ammo_index] == 1) { gitem_t *it; it = GET_ITEM(MK23_NUM); it->use(ent, it); ent->client->autoreloading = true; return; } break; case MP5_NUM: if (ent->client->mp5_rds == ent->client->mp5_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } break; case M4_NUM: if (ent->client->m4_rds == ent->client->m4_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } break; case MK23_NUM: if (ent->client->mk23_rds == ent->client->mk23_max) return; if(ent->client->pers.inventory[ent->client->ammo_index] <= 0) { gi.cprintf(ent, PRINT_HIGH, "Out of ammo\n"); return; } break; default: //We should never get here, but... //BD 5/26 - Actually we get here quite often right now. Just exit for weaps that we // don't want reloaded or that never reload (grenades) return; } ent->client->weaponstate = WEAPON_RELOADING; } //+BD END CODE BLOCK //tempfile BEGIN /* Function _SetSniper (move to g_weapon.c?) Arguments: ent: client edict for which to set sniper mode zoom: zoom level to set. Set to 1, 2, 4 or 6. Return value: none */ void _SetSniper(edict_t * ent, int zoom) { int desired_fov, sniper_mode, oldmode; switch (zoom) { default: case 1: desired_fov = SNIPER_FOV1; sniper_mode = SNIPER_1X; break; case 2: desired_fov = SNIPER_FOV2; sniper_mode = SNIPER_2X; break; case 4: desired_fov = SNIPER_FOV4; sniper_mode = SNIPER_4X; break; case 6: desired_fov = SNIPER_FOV6; sniper_mode = SNIPER_6X; break; } oldmode = ent->client->resp.sniper_mode; if (sniper_mode == oldmode) return; //Moved here, no need to make sound if zoom isnt changed -M gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/lensflik.wav"), 1, ATTN_NORM, 0); ent->client->resp.sniper_mode = sniper_mode; ent->client->desired_fov = desired_fov; if (sniper_mode == SNIPER_1X && ent->client->pers.weapon) ent->client->ps.gunindex = gi.modelindex(ent->client->pers.weapon->view_model); //show the model if switching to 1x if (oldmode == SNIPER_1X && ent->client->weaponstate != WEAPON_RELOADING) { //do idleness stuff when switching from 1x, see function below ent->client->weaponstate = WEAPON_BUSY; ent->client->idle_weapon = 6; ent->client->ps.gunframe = 22; } } //tempfile END void Cmd_New_Weapon_f(edict_t * ent) { ent->client->weapon_attempts++; if (ent->client->weapon_attempts == 1) Cmd_Weapon_f(ent); } int _SniperMode(edict_t *ent) { switch (ent->client->desired_zoom) { //lets update old desired zoom case 1: return SNIPER_1X; case 2: return SNIPER_2X; case 4: return SNIPER_4X; case 6: return SNIPER_6X; } return ent->client->resp.sniper_mode; } //TempFile BEGIN void _ZoomIn(edict_t * ent, qboolean overflow) { switch (_SniperMode(ent)) { case SNIPER_1X: ent->client->desired_zoom = 2; break; case SNIPER_2X: ent->client->desired_zoom = 4; break; case SNIPER_4X: ent->client->desired_zoom = 6; break; case SNIPER_6X: if (overflow) ent->client->desired_zoom = 1; break; } } void _ZoomOut(edict_t * ent, qboolean overflow) { switch (_SniperMode(ent)) { case SNIPER_1X: if (overflow) ent->client->desired_zoom = 6; break; case SNIPER_2X: ent->client->desired_zoom = 1; break; case SNIPER_4X: ent->client->desired_zoom = 2; break; case SNIPER_6X: ent->client->desired_zoom = 4; break; } } void Cmd_NextMap_f(edict_t * ent) { if (level.nextmap[0]) { gi.cprintf (ent, PRINT_HIGH, "Next map in rotation is %s (%d/%d).\n", level.nextmap, cur_map+1, num_maps); return; } if ((cur_map+1) >= num_maps) gi.cprintf (ent, PRINT_HIGH, "Next map in rotation is %s (%d/%d).\n", map_rotation[0], 1, num_maps); else gi.cprintf (ent, PRINT_HIGH, "Next map in rotation is %s (%d/%d).\n", map_rotation[cur_map+1], cur_map+2, num_maps); } void Cmd_Lens_f(edict_t * ent) { int nArg; char args[8]; if (ent->client->curr_weap != SNIPER_NUM) return; nArg = atoi(gi.args()); if (nArg == 0) { Q_strncpyz(args, gi.args(), sizeof(args)); //perhaps in or out? let's see. if (Q_stricmp(args, "in") == 0) _ZoomIn(ent, false); else if (Q_stricmp(args, "out") == 0) _ZoomOut(ent, false); else _ZoomIn(ent, true); if(!ent->client->desired_zoom) return; } else if ((nArg == 1) || (!(nArg % 2) && (nArg <= 6))) ent->client->desired_zoom = nArg; else _ZoomIn(ent, true); if(ent->client->weapon_attempts > 0) return; //Already waiting to change the zoom, otherwise it //first change to desired zoom and then usual zoomin -M ent->client->weapon_attempts++; if (ent->client->weapon_attempts == 1) Cmd_Weapon_f(ent); } //TempFile END // function to change the firing mode of weapons (when appropriate) void Cmd_Weapon_f(edict_t * ent) { int dead; dead = (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD); ent->client->weapon_attempts--; if (ent->client->weapon_attempts < 0) ent->client->weapon_attempts = 0; if (ent->client->bandaging || ent->client->bandage_stopped) { if (!(ent->client->resp.weapon_after_bandage_warned)) { ent->client->resp.weapon_after_bandage_warned = true; gi.cprintf(ent, PRINT_HIGH, "You'll get to your weapon when you're done bandaging!\n"); } ent->client->weapon_attempts++; return; } ent->client->resp.weapon_after_bandage_warned = false; if (ent->client->weaponstate == WEAPON_FIRING || ent->client->weaponstate == WEAPON_BUSY) { //gi.cprintf(ent, PRINT_HIGH, "Try again when you aren't using your weapon.\n"); ent->client->weapon_attempts++; return; } switch(ent->client->curr_weap) { case MK23_NUM: if (!dead) gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/click.wav"), 1, ATTN_NORM, 0); ent->client->resp.mk23_mode = !(ent->client->resp.mk23_mode); if (ent->client->resp.mk23_mode) gi.cprintf(ent, PRINT_HIGH, "MK23 Pistol set for semi-automatic action\n"); else gi.cprintf(ent, PRINT_HIGH, "MK23 Pistol set for automatic action\n"); break; case MP5_NUM: if (!dead) gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/click.wav"), 1, ATTN_NORM, 0); ent->client->resp.mp5_mode = !(ent->client->resp.mp5_mode); if (ent->client->resp.mp5_mode) gi.cprintf(ent, PRINT_HIGH, "MP5 set to 3 Round Burst mode\n"); else gi.cprintf(ent, PRINT_HIGH, "MP5 set to Full Automatic mode\n"); break; case M4_NUM: if (!dead) gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/click.wav"), 1, ATTN_NORM, 0); ent->client->resp.m4_mode = !(ent->client->resp.m4_mode); if (ent->client->resp.m4_mode) gi.cprintf(ent, PRINT_HIGH, "M4 set to 3 Round Burst mode\n"); else gi.cprintf(ent, PRINT_HIGH, "M4 set to Full Automatic mode\n"); break; case SNIPER_NUM: if (dead) return; if (!ent->client->desired_zoom) _ZoomIn(ent, true); // standard behaviour _SetSniper(ent, ent->client->desired_zoom); ent->client->desired_zoom = 0; break; case HC_NUM: // AQ2:TNG Deathwatch - Single Barreled HC if(!hc_single->value) return; if (!dead) gi.sound(ent, CHAN_ITEM, gi.soundindex("misc/click.wav"), 1, ATTN_NORM, 0); ent->client->resp.hc_mode = !(ent->client->resp.hc_mode); if (ent->client->resp.hc_mode) gi.cprintf(ent, PRINT_HIGH, "Single Barreled Handcannon\n"); else gi.cprintf(ent, PRINT_HIGH, "Double Barreled Handcannon\n"); // AQ2:TNG End break; case KNIFE_NUM: if (dead) return; if (ent->client->weaponstate == WEAPON_READY) { ent->client->resp.knife_mode = !(ent->client->resp.knife_mode); ent->client->weaponstate = WEAPON_ACTIVATING; if (ent->client->resp.knife_mode) { gi.cprintf(ent, PRINT_HIGH, "Switching to throwing\n"); ent->client->ps.gunframe = 0; } else { gi.cprintf(ent, PRINT_HIGH, "Switching to slashing\n"); ent->client->ps.gunframe = 106; } } break; case GRENADE_NUM: if (ent->client->resp.grenade_mode == 0) { gi.cprintf(ent, PRINT_HIGH, "Prepared to make a medium range throw\n"); ent->client->resp.grenade_mode = 1; } else if (ent->client->resp.grenade_mode == 1) { gi.cprintf(ent, PRINT_HIGH, "Prepared to make a long range throw\n"); ent->client->resp.grenade_mode = 2; } else { gi.cprintf(ent, PRINT_HIGH, "Prepared to make a short range throw\n"); ent->client->resp.grenade_mode = 0; } break; } } // sets variable to toggle nearby door status void Cmd_OpenDoor_f(edict_t * ent) { ent->client->doortoggle = 1; return; } void Cmd_Bandage_f(edict_t * ent) { if ((ent->client->bleeding != 0 || ent->client->leg_damage != 0) && ent->client->bandaging != 1) ent->client->reload_attempts = 0; // prevent any further reloading if ((ent->client->weaponstate == WEAPON_READY || ent->client->weaponstate == WEAPON_END_MAG) && (ent->client->bleeding != 0 || ent->client->leg_damage != 0) && ent->client->bandaging != 1) { // zucc - check if they have a primed grenade if (ent->client->curr_weap == GRENADE_NUM && ((ent->client->ps.gunframe >= GRENADE_IDLE_FIRST && ent->client->ps.gunframe <= GRENADE_IDLE_LAST) || (ent->client->ps.gunframe >= GRENADE_THROW_FIRST && ent->client->ps.gunframe <= GRENADE_THROW_LAST))) { int damage; ent->client->ps.gunframe = 0; if (use_classic->value) damage = 170; else damage = GRENADE_DAMRAD; if(ent->client->quad_framenum > level.framenum) damage *= 1.5f; fire_grenade2(ent, ent->s.origin, vec3_origin, damage, 0, 2, damage * 2, false); INV_AMMO(ent, GRENADE_NUM)--; if (INV_AMMO(ent, GRENADE_NUM) <= 0) { ent->client->newweapon = GET_ITEM(MK23_NUM); } } ent->client->bandaging = 1; ent->client->resp.sniper_mode = SNIPER_1X; ent->client->ps.fov = 90; ent->client->desired_fov = 90; if (ent->client->pers.weapon) ent->client->ps.gunindex = gi.modelindex(ent->client->pers.weapon->view_model); gi.cprintf(ent, PRINT_HIGH, "You've started bandaging\n"); } else if (ent->client->bandaging == 1) gi.cprintf(ent, PRINT_HIGH, "Already bandaging\n"); //FIREBLADE 12/26/98 - fix inappropriate message else if (ent->client->bleeding == 0 && ent->client->leg_damage == 0) gi.cprintf(ent, PRINT_HIGH, "No need to bandage\n"); else gi.cprintf(ent, PRINT_HIGH, "Can't bandage now\n"); //FIREBLADE } // function called in generic_weapon function that does the bandaging void Bandage(edict_t * ent) { ent->client->leg_noise = 0; ent->client->leg_damage = 0; ent->client->leghits = 0; ent->client->bleeding = 0; ent->client->bleed_remain = 0; ent->client->bandaging = 0; ent->client->leg_dam_count = 0; ent->client->attacker = NULL; ent->client->bandage_stopped = 1; ent->client->idle_weapon = BANDAGE_TIME; } void Cmd_ID_f(edict_t * ent) { if (!ent->client->resp.id) { gi.cprintf(ent, PRINT_HIGH, "Disabling player identification display.\n"); ent->client->resp.id = 1; } else { gi.cprintf(ent, PRINT_HIGH, "Activating player identification display.\n"); ent->client->resp.id = 0; } return; } static void loc_buildboxpoints(vec3_t p[8], vec3_t org, vec3_t mins, vec3_t maxs) { VectorAdd(org, mins, p[0]); VectorCopy(p[0], p[1]); p[1][0] -= mins[0]; VectorCopy(p[0], p[2]); p[2][1] -= mins[1]; VectorCopy(p[0], p[3]); p[3][0] -= mins[0]; p[3][1] -= mins[1]; VectorAdd(org, maxs, p[4]); VectorCopy(p[4], p[5]); p[5][0] -= maxs[0]; VectorCopy(p[0], p[6]); p[6][1] -= maxs[1]; VectorCopy(p[0], p[7]); p[7][0] -= maxs[0]; p[7][1] -= maxs[1]; } qboolean loc_CanSee(edict_t * targ, edict_t * inflictor) { trace_t trace; vec3_t targpoints[8]; int i; vec3_t viewpoint; // bmodels need special checking because their origin is 0,0,0 if (targ->movetype == MOVETYPE_PUSH) return false; // bmodels not supported loc_buildboxpoints(targpoints, targ->s.origin, targ->mins, targ->maxs); VectorCopy(inflictor->s.origin, viewpoint); viewpoint[2] += inflictor->viewheight; for (i = 0; i < 8; i++) { PRETRACE(); trace = gi.trace(viewpoint, vec3_origin, vec3_origin, targpoints[i], inflictor, MASK_SOLID); POSTTRACE(); if (trace.fraction == 1.0) return true; } return false; } // originally from Zoid's CTF void SetIDView(edict_t * ent) { vec3_t forward, dir; trace_t tr; edict_t *who, *best; //FIREBLADE, suggested by hal[9k] 3/11/1999 float bd = 0.9f; float d; int i; ent->client->ps.stats[STAT_ID_VIEW] = 0; //FIREBLADE if (ent->solid != SOLID_NOT && !teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // won't ever work in non-teams so don't run the code... } if (ent->client->chase_mode) { if (ent->client->chase_target && ent->client->chase_target->inuse) { ent->client->ps.stats[STAT_ID_VIEW] = CS_PLAYERSKINS + (ent->client->chase_target - g_edicts - 1); } return; } //FIREBLADE if (ent->client->resp.id == 1) return; AngleVectors(ent->client->v_angle, forward, NULL, NULL); VectorScale(forward, 8192, forward); VectorAdd(ent->s.origin, forward, forward); PRETRACE(); tr = gi.trace(ent->s.origin, NULL, NULL, forward, ent, MASK_SOLID); POSTTRACE(); if (tr.fraction < 1 && tr.ent && tr.ent->client) { ent->client->ps.stats[STAT_ID_VIEW] = CS_PLAYERSKINS + (ent - g_edicts - 1); return; } AngleVectors(ent->client->v_angle, forward, NULL, NULL); best = NULL; for (i = 1; i <= maxclients->value; i++) { who = g_edicts + i; if (!who->inuse) continue; VectorSubtract(who->s.origin, ent->s.origin, dir); VectorNormalize(dir); d = DotProduct(forward, dir); if (d > bd && loc_CanSee(ent, who) && //FIREBLADE (who->solid != SOLID_NOT || who->deadflag == DEAD_DEAD) && (ent->solid == SOLID_NOT || OnSameTeam(ent, who))) { //FIREBLADE bd = d; best = who; } } if (best != NULL && bd > 0.90) { ent->client->ps.stats[STAT_ID_VIEW] = CS_PLAYERSKINS + (best - g_edicts - 1); } } void Cmd_IR_f(edict_t * ent) { int band = 0; if (!ir->value) { gi.cprintf(ent, PRINT_HIGH, "IR vision not enabled on this server.\n"); return; } if (INV_AMMO(ent, BAND_NUM)) band = 1; if (ent->client->resp.ir == 0) { ent->client->resp.ir = 1; if (band) gi.cprintf(ent, PRINT_HIGH, "IR vision disabled.\n"); else gi.cprintf(ent, PRINT_HIGH, "IR vision will be disabled when you get a bandolier.\n"); } else { ent->client->resp.ir = 0; if (band) gi.cprintf(ent, PRINT_HIGH, "IR vision enabled.\n"); else gi.cprintf(ent, PRINT_HIGH, "IR vision will be enabled when you get a bandolier.\n"); } } // zucc choose command, avoids using the menus in teamplay void Cmd_Choose_f(edict_t * ent) { char *s; int itemNum = NO_NUM; // only works in teamplay if ((!teamplay->value && !dm_choose->value) || teamdm->value || ctf->value == 2) return; s = gi.args(); // convert names a player might try (DW added a few) if (!Q_stricmp(s, "A 2nd pistol") || !Q_stricmp(s, "railgun") || !Q_stricmp(s, "akimbo") || !Q_stricmp(s, DUAL_NAME)) itemNum = DUAL_NUM; else if (!Q_stricmp(s, "shotgun") || !Q_stricmp(s, M3_NAME)) itemNum = M3_NUM; else if (!Q_stricmp(s, "machinegun") || !Q_stricmp(s, HC_NAME)) itemNum = HC_NUM; else if (!Q_stricmp(s, "super shotgun") || !Q_stricmp(s, "mp5") || !Q_stricmp(s, MP5_NAME)) itemNum = MP5_NUM; else if (!Q_stricmp(s, "chaingun") || !Q_stricmp(s, "sniper") || !Q_stricmp(s, SNIPER_NAME)) itemNum = SNIPER_NUM; else if (!Q_stricmp(s, "bfg10k") || !Q_stricmp(s, KNIFE_NAME)) itemNum = KNIFE_NUM; else if (!Q_stricmp(s, "grenade launcher") || !Q_stricmp(s, "m4") || !Q_stricmp(s, M4_NAME)) itemNum = M4_NUM; else if (!Q_stricmp(s, "laser") || !Q_stricmp(s, LASER_NAME)) itemNum = LASER_NUM; else if (!Q_stricmp(s, "vest") || !Q_stricmp(s, KEV_NAME)) itemNum = KEV_NUM; else if (!Q_stricmp(s, "slippers") || !Q_stricmp(s, SLIP_NAME)) itemNum = SLIP_NUM; else if (!Q_stricmp(s, SIL_NAME)) itemNum = SIL_NUM; else if (!Q_stricmp(s, "helmet") || !Q_stricmp(s, HELM_NAME)) itemNum = HELM_NUM; else if (!Q_stricmp(s, BAND_NAME)) itemNum = BAND_NUM; switch(itemNum) { case DUAL_NUM: case M3_NUM: case HC_NUM: case MP5_NUM: case SNIPER_NUM: case KNIFE_NUM: case M4_NUM: if (!((int)wp_flags->value & items[itemNum].flag)) { gi.cprintf(ent, PRINT_HIGH, "Weapon disabled on this server.\n"); return; } ent->client->resp.weapon = GET_ITEM(itemNum); break; case LASER_NUM: case KEV_NUM: case SLIP_NUM: case SIL_NUM: case HELM_NUM: case BAND_NUM: if (!((int)itm_flags->value & items[itemNum].flag)) { gi.cprintf(ent, PRINT_HIGH, "Item disabled on this server.\n"); return; } ent->client->resp.item = GET_ITEM(itemNum); break; default: gi.cprintf(ent, PRINT_HIGH, "Invalid weapon or item choice.\n"); return; } gi.cprintf(ent, PRINT_HIGH, "Weapon selected: %s\nItem selected: %s\n", (ent->client->resp.weapon)->pickup_name, (ent->client->resp.item)->pickup_name); } // AQ:TNG - JBravo adding tkok void Cmd_TKOk(edict_t * ent) { if (!ent->enemy || !ent->enemy->inuse || !ent->enemy->client || (ent == ent->enemy)) { gi.cprintf(ent, PRINT_HIGH, "Nothing to forgive\n"); } else if (ent->client->resp.team == ent->enemy->client->resp.team) { if (ent->enemy->client->team_kills) { gi.cprintf(ent, PRINT_HIGH, "You forgave %s\n", ent->enemy->client->pers.netname); gi.cprintf(ent->enemy, PRINT_HIGH, "%s forgave you\n", ent->client->pers.netname); ent->enemy->client->team_kills--; if (ent->enemy->client->team_wounds) ent->enemy->client->team_wounds /= 2; } } else { gi.cprintf(ent, PRINT_HIGH, "That's very noble of you...\n"); gi.bprintf(PRINT_HIGH, "%s turned the other cheek\n", ent->client->pers.netname); } ent->enemy = NULL; return; } void Cmd_Time(edict_t * ent) { int mins, secs, remaining, rmins, rsecs; float gametime; if (!timelimit->value) { gi.cprintf(ent, PRINT_HIGH, "Timelimit disabled\n"); return; } if (matchmode->value) gametime = matchtime; else gametime = level.time; mins = gametime / 60; secs = gametime - (mins * 60); remaining = (timelimit->value * 60) - gametime; rmins = remaining / 60; rsecs = remaining - (rmins * 60); if (rmins < 0) rmins = 0; if (rsecs < 0) rsecs = 0; gi.cprintf(ent, PRINT_HIGH, "Elapsed time: %d:%02d. Remaining time: %d:%02d\n", mins, secs, rmins, rsecs); } void Cmd_Roundtimeleft_f(edict_t * ent) { int remaining; if(!teamplay->value) { gi.cprintf(ent, PRINT_HIGH, "This command need teamplay to be enabled\n"); return; } if (ctf->value || teamdm->value || team_round_going != 1) return; if ((int)roundtimelimit->value <= 0) return; remaining = (roundtimelimit->value * 60) - (current_round_length/10); gi.cprintf(ent, PRINT_HIGH, "There is %d:%02i left in this round\n", remaining / 60, remaining % 60); } /* Freud's AutoRecord This will automatically record a new demo for every map if the client turns it on */ void RemoveSpaces(char *s) { char *p; p = strchr(s, ' '); if(!p) return; for(s = p+1; *s; s++) { if(*s != ' ') *p++ = *s; } *p = 0; } void Cmd_AutoRecord_f(edict_t * ent) { char rec_date[20], recstr[MAX_QPATH]; time_t clock; time( &clock ); strftime( rec_date, sizeof(rec_date)-1, "%Y_%b_%d_%H%M", localtime(&clock)); if (matchmode->value) { if(use_3teams->value) Com_sprintf(recstr, sizeof(recstr), "%s-%s_vs_%s_vs_%s-%s", rec_date, teams[TEAM1].name, teams[TEAM2].name, teams[TEAM3].name, level.mapname); else Com_sprintf(recstr, sizeof(recstr), "%s-%s_vs_%s-%s", rec_date, teams[TEAM1].name, teams[TEAM2].name, level.mapname); RemoveSpaces(recstr); //Remove spaces -M } else { Com_sprintf(recstr, sizeof(recstr), "%s-%s", rec_date, level.mapname); } stuffcmd(ent, va("record \"%s\"\n", recstr)); } /* TNG:Freud Cmd_Ghost_f Person gets frags/kills/damage/weapon/item/team/stats back if he disconnected */ void Cmd_Ghost_f(edict_t * ent) { int x, frames_since; qboolean found = false; if (!use_ghosts->value) { gi.cprintf(ent, PRINT_HIGH, "Ghosting is not enabled on this server\n"); return; } if (num_ghost_players == 0) { gi.cprintf(ent, PRINT_HIGH, "No ghost match found\n"); return; } for (x = 0; x < num_ghost_players; x++) { if (found == true) { ghost_players[x - 1] = ghost_players[x]; } else if (strcmp(ghost_players[x].ipaddr, ent->client->ipaddr) == 0 && strcmp(ghost_players[x].netname, ent->client->pers.netname) == 0) { found = true; gi.cprintf(ent, PRINT_HIGH, "Welcome back %s\n", ent->client->pers.netname); frames_since = level.framenum - ghost_players[x].disconnect_frame; ent->client->resp.enterframe = ghost_players[x].enterframe + frames_since; ent->client->resp.score = ghost_players[x].score; ent->client->resp.kills = ghost_players[x].kills; ent->client->resp.damage_dealt = ghost_players[x].damage_dealt; if (teamplay->value) { if (ghost_players[x].team && ghost_players[x].team != NOTEAM) JoinTeam(ent, ghost_players[x].team, 1); ent->client->resp.weapon = ghost_players[x].weapon; ent->client->resp.item = ghost_players[x].item; } ent->client->resp.stats_shots_t = ghost_players[x].stats_shots_t; ent->client->resp.stats_shots_h = ghost_players[x].stats_shots_h; memcpy(ent->client->resp.stats_locations, ghost_players[x].stats_locations, sizeof(ghost_players[x].stats_locations)); memcpy(ent->client->resp.stats_shots, ghost_players[x].stats_shots, sizeof(ghost_players[x].stats_shots)); memcpy(ent->client->resp.stats_hits, ghost_players[x].stats_hits, sizeof(ghost_players[x].stats_hits)); memcpy(ent->client->resp.stats_headshot, ghost_players[x].stats_headshot, sizeof(ghost_players[x].stats_headshot)); } } if (found == true) { num_ghost_players--; } else { gi.cprintf(ent, PRINT_HIGH, "No ghost match found\n"); } }
529
./aq2-tng/source/g_misc.c
//----------------------------------------------------------------------------- // g_misc.c // // $Id: g_misc.c,v 1.3 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_misc.c,v $ // Revision 1.3 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.2 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.1.1.1.2.2 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.1.1.1.2.1 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.1.1.1 2001/05/06 17:31:21 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" /*QUAKED func_group (0 0 0) ? Used to group brushes together just for editor convenience. */ //===================================================== void Use_Areaportal (edict_t * ent, edict_t * other, edict_t * activator) { ent->count ^= 1; // toggle state // gi.dprintf ("portalstate: %i = %i\n", ent->style, ent->count); gi.SetAreaPortalState (ent->style, ent->count); } /*QUAKED func_areaportal (0 0 0) ? This is a non-visible object that divides the world into areas that are seperated when this portal is not activated. Usually enclosed in the middle of a door. */ void SP_func_areaportal (edict_t * ent) { ent->use = Use_Areaportal; ent->count = 0; // always start closed; } //===================================================== /* ================= Misc functions ================= */ void VelocityForDamage (int damage, vec3_t v) { v[0] = 100.0 * crandom (); v[1] = 100.0 * crandom (); v[2] = 200.0 + 100.0 * random (); if (damage < 50) VectorScale (v, 0.7, v); else VectorScale (v, 1.2, v); } void ClipGibVelocity (edict_t * ent) { if (ent->velocity[0] < -300) ent->velocity[0] = -300; else if (ent->velocity[0] > 300) ent->velocity[0] = 300; if (ent->velocity[1] < -300) ent->velocity[1] = -300; else if (ent->velocity[1] > 300) ent->velocity[1] = 300; if (ent->velocity[2] < 200) ent->velocity[2] = 200; // always some upwards else if (ent->velocity[2] > 500) ent->velocity[2] = 500; } /* ================= gibs ================= */ void gib_think (edict_t * self) { self->s.frame++; self->nextthink = level.time + FRAMETIME; if (self->s.frame == 10) { self->think = G_FreeEdict; self->nextthink = level.time + 8 + random () * 10; } } void gib_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { vec3_t normal_angles, right; if (!self->groundentity) return; self->touch = NULL; if (plane) { gi.sound (self, CHAN_VOICE, gi.soundindex ("misc/fhit3.wav"), 1, ATTN_NORM, 0); vectoangles (plane->normal, normal_angles); AngleVectors (normal_angles, NULL, right, NULL); vectoangles (right, self->s.angles); if (self->s.modelindex == sm_meat_index) { self->s.frame++; self->think = gib_think; self->nextthink = level.time + FRAMETIME; } } } void gib_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { G_FreeEdict (self); } void ThrowGib (edict_t * self, char *gibname, int damage, int type) { edict_t *gib; vec3_t vd; vec3_t origin; vec3_t size; float vscale; gib = G_Spawn (); VectorScale (self->size, 0.5, size); VectorAdd (self->absmin, size, origin); gib->s.origin[0] = origin[0] + crandom () * size[0]; gib->s.origin[1] = origin[1] + crandom () * size[1]; gib->s.origin[2] = origin[2] + crandom () * size[2]; gi.setmodel (gib, gibname); gib->solid = SOLID_NOT; gib->s.effects |= EF_GIB; gib->flags |= FL_NO_KNOCKBACK; gib->takedamage = DAMAGE_YES; gib->die = gib_die; if (type == GIB_ORGANIC) { gib->movetype = MOVETYPE_TOSS; gib->touch = gib_touch; vscale = 0.5; } else { gib->movetype = MOVETYPE_BOUNCE; vscale = 1.0; } VelocityForDamage (damage, vd); VectorMA (self->velocity, vscale, vd, gib->velocity); ClipGibVelocity (gib); gib->avelocity[0] = random () * 600; gib->avelocity[1] = random () * 600; gib->avelocity[2] = random () * 600; gib->think = G_FreeEdict; gib->nextthink = level.time + 10 + random () * 10; gi.linkentity (gib); } void ThrowHead (edict_t * self, char *gibname, int damage, int type) { vec3_t vd; float vscale; self->s.skinnum = 0; self->s.frame = 0; VectorClear (self->mins); VectorClear (self->maxs); self->s.modelindex2 = 0; gi.setmodel (self, gibname); self->solid = SOLID_NOT; self->s.effects |= EF_GIB; self->s.effects &= ~EF_FLIES; self->s.sound = 0; self->flags |= FL_NO_KNOCKBACK; self->svflags &= ~SVF_MONSTER; self->takedamage = DAMAGE_YES; self->die = gib_die; if (type == GIB_ORGANIC) { self->movetype = MOVETYPE_TOSS; self->touch = gib_touch; vscale = 0.5; } else { self->movetype = MOVETYPE_BOUNCE; vscale = 1.0; } VelocityForDamage (damage, vd); VectorMA (self->velocity, vscale, vd, self->velocity); ClipGibVelocity (self); self->avelocity[YAW] = crandom () * 600; self->think = G_FreeEdict; self->nextthink = level.time + 10 + random () * 10; gi.linkentity (self); } void ThrowClientHead (edict_t * self, int damage) { vec3_t vd; char *gibname; if (rand () & 1) { gibname = "models/objects/gibs/head2/tris.md2"; self->s.skinnum = 1; // second skin is player } else { gibname = "models/objects/gibs/skull/tris.md2"; self->s.skinnum = 0; } self->s.origin[2] += 32; self->s.frame = 0; gi.setmodel (self, gibname); VectorSet (self->mins, -16, -16, 0); VectorSet (self->maxs, 16, 16, 16); self->takedamage = DAMAGE_NO; self->solid = SOLID_NOT; self->s.effects = EF_GIB; self->s.sound = 0; self->flags |= FL_NO_KNOCKBACK; self->movetype = MOVETYPE_BOUNCE; VelocityForDamage (damage, vd); VectorAdd (self->velocity, vd, self->velocity); if (self->client) // bodies in the queue don't have a client anymore { self->client->anim_priority = ANIM_DEATH; self->client->anim_end = self->s.frame; } gi.linkentity (self); } /* ================= debris ================= */ void debris_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { G_FreeEdict (self); } void ThrowDebris (edict_t * self, char *modelname, float speed, vec3_t origin) { edict_t *chunk; vec3_t v; chunk = G_Spawn (); VectorCopy (origin, chunk->s.origin); gi.setmodel (chunk, modelname); v[0] = 100 * crandom (); v[1] = 100 * crandom (); v[2] = 100 + 100 * crandom (); VectorMA (self->velocity, speed, v, chunk->velocity); chunk->movetype = MOVETYPE_BOUNCE; chunk->solid = SOLID_NOT; chunk->avelocity[0] = random () * 600; chunk->avelocity[1] = random () * 600; chunk->avelocity[2] = random () * 600; chunk->think = G_FreeEdict; chunk->nextthink = level.time + 5 + random () * 5; chunk->s.frame = 0; chunk->flags = 0; chunk->classname = "debris"; chunk->takedamage = DAMAGE_YES; chunk->die = debris_die; gi.linkentity (chunk); } void BecomeExplosion1 (edict_t * self) { //flags are important if (ctf->value) { if (strcmp (self->classname, "item_flag_team1") == 0) { CTFResetFlag (TEAM1); // this will free self! gi.bprintf (PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName (TEAM1)); return; } if (strcmp (self->classname, "item_flag_team2") == 0) { CTFResetFlag (TEAM2); // this will free self! gi.bprintf (PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName (TEAM1)); return; } } gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_EXPLOSION1); gi.WritePosition (self->s.origin); gi.multicast (self->s.origin, MULTICAST_PVS); G_FreeEdict (self); } void BecomeExplosion2 (edict_t * self) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_EXPLOSION2); gi.WritePosition (self->s.origin); gi.multicast (self->s.origin, MULTICAST_PVS); G_FreeEdict (self); } /*QUAKED path_corner (.5 .3 0) (-8 -8 -8) (8 8 8) TELEPORT Target: next path corner Pathtarget: gets used when an entity that has this path_corner targeted touches it */ void path_corner_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { vec3_t v; edict_t *next; if (other->movetarget != self) return; if (other->enemy) return; if (self->pathtarget) { char *savetarget; savetarget = self->target; self->target = self->pathtarget; G_UseTargets (self, other); self->target = savetarget; } if (self->target) next = G_PickTarget (self->target); else next = NULL; if ((next) && (next->spawnflags & 1)) { VectorCopy (next->s.origin, v); v[2] += next->mins[2]; v[2] -= other->mins[2]; VectorCopy (v, other->s.origin); next = G_PickTarget (next->target); } other->goalentity = other->movetarget = next; if (self->wait) { other->monsterinfo.pausetime = level.time + self->wait; other->monsterinfo.stand (other); return; } if (!other->movetarget) { other->monsterinfo.pausetime = level.time + 100000000; other->monsterinfo.stand (other); } else { VectorSubtract (other->goalentity->s.origin, other->s.origin, v); other->ideal_yaw = vectoyaw (v); } } void SP_path_corner (edict_t * self) { if (!self->targetname) { gi.dprintf ("path_corner with no targetname at %s\n", vtos (self->s.origin)); G_FreeEdict (self); return; } self->solid = SOLID_TRIGGER; self->touch = path_corner_touch; VectorSet (self->mins, -8, -8, -8); VectorSet (self->maxs, 8, 8, 8); self->svflags |= SVF_NOCLIENT; gi.linkentity (self); } /*QUAKED point_combat (0.5 0.3 0) (-8 -8 -8) (8 8 8) Hold Makes this the target of a monster and it will head here when first activated before going after the activator. If hold is selected, it will stay here. */ void point_combat_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { edict_t *activator; if (other->movetarget != self) return; if (self->target) { other->target = self->target; other->goalentity = other->movetarget = G_PickTarget (other->target); if (!other->goalentity) { gi.dprintf ("%s at %s target %s does not exist\n", self->classname, vtos (self->s.origin), self->target); other->movetarget = self; } self->target = NULL; } else if ((self->spawnflags & 1) && !(other->flags & (FL_SWIM | FL_FLY))) { other->monsterinfo.pausetime = level.time + 100000000; other->monsterinfo.aiflags |= AI_STAND_GROUND; other->monsterinfo.stand (other); } if (other->movetarget == self) { other->target = NULL; other->movetarget = NULL; other->goalentity = other->enemy; other->monsterinfo.aiflags &= ~AI_COMBAT_POINT; } if (self->pathtarget) { char *savetarget; savetarget = self->target; self->target = self->pathtarget; if (other->enemy && other->enemy->client) activator = other->enemy; else if (other->oldenemy && other->oldenemy->client) activator = other->oldenemy; else if (other->activator && other->activator->client) activator = other->activator; else activator = other; G_UseTargets (self, activator); self->target = savetarget; } } void SP_point_combat (edict_t * self) { if (deathmatch->value) { G_FreeEdict (self); return; } self->solid = SOLID_TRIGGER; self->touch = point_combat_touch; VectorSet (self->mins, -8, -8, -16); VectorSet (self->maxs, 8, 8, 16); self->svflags = SVF_NOCLIENT; gi.linkentity (self); }; /*QUAKED viewthing (0 .5 .8) (-8 -8 -8) (8 8 8) Just for the debugging level. Don't use */ void TH_viewthing (edict_t * ent) { ent->s.frame = (ent->s.frame + 1) % 7; ent->nextthink = level.time + FRAMETIME; } void SP_viewthing (edict_t * ent) { gi.dprintf ("viewthing spawned\n"); ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; ent->s.renderfx = RF_FRAMELERP; VectorSet (ent->mins, -16, -16, -24); VectorSet (ent->maxs, 16, 16, 32); ent->s.modelindex = gi.modelindex ("models/objects/banner/tris.md2"); gi.linkentity (ent); ent->nextthink = level.time + 0.5; ent->think = TH_viewthing; return; } /*QUAKED info_null (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for spotlights, etc. */ void SP_info_null (edict_t * self) { G_FreeEdict (self); }; /*QUAKED info_notnull (0 0.5 0) (-4 -4 -4) (4 4 4) Used as a positional target for lightning. */ void SP_info_notnull (edict_t * self) { VectorCopy (self->s.origin, self->absmin); VectorCopy (self->s.origin, self->absmax); }; /*QUAKED light (0 1 0) (-8 -8 -8) (8 8 8) START_OFF Non-displayed light. Default light value is 300. Default style is 0. If targeted, will toggle between on and off. Default _cone value is 10 (used to set size of light for spotlights) */ #define START_OFF 1 static void light_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->spawnflags & START_OFF) { gi.configstring (CS_LIGHTS + self->style, "m"); self->spawnflags &= ~START_OFF; } else { gi.configstring (CS_LIGHTS + self->style, "a"); self->spawnflags |= START_OFF; } } void SP_light (edict_t * self) { // no targeted lights in deathmatch, because they cause global messages if (!self->targetname || deathmatch->value) { G_FreeEdict (self); return; } if (self->style >= 32) { self->use = light_use; if (self->spawnflags & START_OFF) gi.configstring (CS_LIGHTS + self->style, "a"); else gi.configstring (CS_LIGHTS + self->style, "m"); } } /*QUAKED func_wall (0 .5 .8) ? TRIGGER_SPAWN TOGGLE START_ON ANIMATED ANIMATED_FAST This is just a solid wall if not inhibited TRIGGER_SPAWN the wall will not be present until triggered it will then blink in to existance; it will kill anything that was in it's way TOGGLE only valid for TRIGGER_SPAWN walls this allows the wall to be turned on and off START_ON only valid for TRIGGER_SPAWN walls the wall will initially be present */ void func_wall_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->solid == SOLID_NOT) { self->solid = SOLID_BSP; self->svflags &= ~SVF_NOCLIENT; KillBox (self); } else { self->solid = SOLID_NOT; self->svflags |= SVF_NOCLIENT; } gi.linkentity (self); if (!(self->spawnflags & 2)) self->use = NULL; } void SP_func_wall (edict_t * self) { self->movetype = MOVETYPE_PUSH; gi.setmodel (self, self->model); if (self->spawnflags & 8) self->s.effects |= EF_ANIM_ALL; if (self->spawnflags & 16) self->s.effects |= EF_ANIM_ALLFAST; // just a wall if ((self->spawnflags & 7) == 0) { self->solid = SOLID_BSP; gi.linkentity (self); return; } // it must be TRIGGER_SPAWN if (!(self->spawnflags & 1)) { // gi.dprintf("func_wall missing TRIGGER_SPAWN\n"); self->spawnflags |= 1; } // yell if the spawnflags are odd if (self->spawnflags & 4) { if (!(self->spawnflags & 2)) { gi.dprintf ("func_wall START_ON without TOGGLE\n"); self->spawnflags |= 2; } } self->use = func_wall_use; if (self->spawnflags & 4) { self->solid = SOLID_BSP; } else { self->solid = SOLID_NOT; self->svflags |= SVF_NOCLIENT; } gi.linkentity (self); } /*QUAKED func_object (0 .5 .8) ? TRIGGER_SPAWN ANIMATED ANIMATED_FAST This is solid bmodel that will fall if it's support it removed. */ void func_object_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { // only squash thing we fall on top of if (!plane) return; if (plane->normal[2] < 1.0) return; if (other->takedamage == DAMAGE_NO) return; T_Damage (other, self, self, vec3_origin, self->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); } void func_object_release (edict_t * self) { self->movetype = MOVETYPE_TOSS; self->touch = func_object_touch; } void func_object_use (edict_t * self, edict_t * other, edict_t * activator) { self->solid = SOLID_BSP; self->svflags &= ~SVF_NOCLIENT; self->use = NULL; KillBox (self); func_object_release (self); } void SP_func_object (edict_t * self) { gi.setmodel (self, self->model); self->mins[0] += 1; self->mins[1] += 1; self->mins[2] += 1; self->maxs[0] -= 1; self->maxs[1] -= 1; self->maxs[2] -= 1; if (!self->dmg) self->dmg = 100; if (self->spawnflags == 0) { self->solid = SOLID_BSP; self->movetype = MOVETYPE_PUSH; self->think = func_object_release; self->nextthink = level.time + 2 * FRAMETIME; } else { self->solid = SOLID_NOT; self->movetype = MOVETYPE_PUSH; self->use = func_object_use; self->svflags |= SVF_NOCLIENT; } if (self->spawnflags & 2) self->s.effects |= EF_ANIM_ALL; if (self->spawnflags & 4) self->s.effects |= EF_ANIM_ALLFAST; self->clipmask = MASK_MONSTERSOLID; gi.linkentity (self); } /*QUAKED func_explosive (0 .5 .8) ? Trigger_Spawn ANIMATED ANIMATED_FAST Any brush that you want to explode or break apart. If you want an ex0plosion, set dmg and it will do a radius explosion of that amount at the center of the bursh. If targeted it will not be shootable. health defaults to 100. mass defaults to 75. This determines how much debris is emitted when it explodes. You get one large chunk per 100 of mass (up to 8) and one small chunk per 25 of mass (up to 16). So 800 gives the most. */ void func_explosive_explode (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { vec3_t origin; vec3_t chunkorigin; vec3_t size; int count; int mass; // bmodel origins are (0 0 0), we need to adjust that here VectorScale (self->size, 0.5, size); VectorAdd (self->absmin, size, origin); VectorCopy (origin, self->s.origin); self->takedamage = DAMAGE_NO; if (self->dmg) T_RadiusDamage (self, attacker, self->dmg, NULL, self->dmg + 40, MOD_EXPLOSIVE); VectorSubtract (self->s.origin, inflictor->s.origin, self->velocity); VectorNormalize (self->velocity); VectorScale (self->velocity, 150, self->velocity); // start chunks towards the center VectorScale (size, 0.5, size); mass = self->mass; if (!mass) mass = 75; // big chunks if (mass >= 100) { count = mass / 100; if (count > 8) count = 8; while (count--) { chunkorigin[0] = origin[0] + crandom () * size[0]; chunkorigin[1] = origin[1] + crandom () * size[1]; chunkorigin[2] = origin[2] + crandom () * size[2]; ThrowDebris (self, "models/objects/debris1/tris.md2", 1, chunkorigin); } } // small chunks count = mass / 25; if (count > 16) count = 16; while (count--) { chunkorigin[0] = origin[0] + crandom () * size[0]; chunkorigin[1] = origin[1] + crandom () * size[1]; chunkorigin[2] = origin[2] + crandom () * size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", 2, chunkorigin); } G_UseTargets (self, attacker); if (self->dmg) BecomeExplosion1 (self); else G_FreeEdict (self); } void func_explosive_use (edict_t * self, edict_t * other, edict_t * activator) { func_explosive_explode (self, self, other, self->health, vec3_origin); } void func_explosive_spawn (edict_t * self, edict_t * other, edict_t * activator) { self->solid = SOLID_BSP; self->svflags &= ~SVF_NOCLIENT; self->use = NULL; KillBox (self); gi.linkentity (self); } void SP_func_explosive (edict_t * self) { /* removed for glass fx if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (self); return; } */ self->movetype = MOVETYPE_PUSH; gi.modelindex ("models/objects/debris1/tris.md2"); gi.modelindex ("models/objects/debris2/tris.md2"); gi.setmodel (self, self->model); if (self->spawnflags & 1) { self->svflags |= SVF_NOCLIENT; self->solid = SOLID_NOT; self->use = func_explosive_spawn; } else { self->solid = SOLID_BSP; if (self->targetname) self->use = func_explosive_use; } if (self->spawnflags & 2) self->s.effects |= EF_ANIM_ALL; if (self->spawnflags & 4) self->s.effects |= EF_ANIM_ALLFAST; if (self->use != func_explosive_use) { if (!self->health) self->health = 100; self->die = func_explosive_explode; self->takedamage = DAMAGE_YES; } gi.linkentity (self); self->think = CGF_SFX_TestBreakableGlassAndRemoveIfNot_Think; self->nextthink = level.time + FRAMETIME; } /*QUAKED misc_explobox (0 .5 .8) (-16 -16 0) (16 16 40) Large exploding box. You can override its mass (100), health (80), and dmg (150). */ void barrel_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { float ratio; vec3_t v; if ((!other->groundentity) || (other->groundentity == self)) return; ratio = (float) other->mass / (float) self->mass; VectorSubtract (self->s.origin, other->s.origin, v); M_walkmove (self, vectoyaw (v), 20 * ratio * FRAMETIME); } void barrel_explode (edict_t * self) { vec3_t org; float spd; vec3_t save; T_RadiusDamage (self, self->activator, self->dmg, NULL, self->dmg + 40, MOD_BARREL); VectorCopy (self->s.origin, save); VectorMA (self->absmin, 0.5, self->size, self->s.origin); // a few big chunks spd = 1.5 * (float) self->dmg / 200.0; org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris1/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris1/tris.md2", spd, org); // bottom corners spd = 1.75 * (float) self->dmg / 200.0; VectorCopy (self->absmin, org); ThrowDebris (self, "models/objects/debris3/tris.md2", spd, org); VectorCopy (self->absmin, org); org[0] += self->size[0]; ThrowDebris (self, "models/objects/debris3/tris.md2", spd, org); VectorCopy (self->absmin, org); org[1] += self->size[1]; ThrowDebris (self, "models/objects/debris3/tris.md2", spd, org); VectorCopy (self->absmin, org); org[0] += self->size[0]; org[1] += self->size[1]; ThrowDebris (self, "models/objects/debris3/tris.md2", spd, org); // a bunch of little chunks spd = 2 * self->dmg / 200; org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); org[0] = self->s.origin[0] + crandom () * self->size[0]; org[1] = self->s.origin[1] + crandom () * self->size[1]; org[2] = self->s.origin[2] + crandom () * self->size[2]; ThrowDebris (self, "models/objects/debris2/tris.md2", spd, org); VectorCopy (save, self->s.origin); if (self->groundentity) BecomeExplosion2 (self); else BecomeExplosion1 (self); } void barrel_delay (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { self->takedamage = DAMAGE_NO; self->nextthink = level.time + 2 * FRAMETIME; self->think = barrel_explode; self->activator = attacker; } void SP_misc_explobox (edict_t * self) { if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (self); return; } gi.modelindex ("models/objects/debris1/tris.md2"); gi.modelindex ("models/objects/debris2/tris.md2"); gi.modelindex ("models/objects/debris3/tris.md2"); self->solid = SOLID_BBOX; self->movetype = MOVETYPE_STEP; self->model = "models/objects/barrels/tris.md2"; self->s.modelindex = gi.modelindex (self->model); VectorSet (self->mins, -16, -16, 0); VectorSet (self->maxs, 16, 16, 40); if (!self->mass) self->mass = 400; if (!self->health) self->health = 10; if (!self->dmg) self->dmg = 150; self->die = barrel_delay; self->takedamage = DAMAGE_YES; self->monsterinfo.aiflags = AI_NOSTEP; self->touch = barrel_touch; self->think = M_droptofloor; self->nextthink = level.time + 2 * FRAMETIME; gi.linkentity (self); } // // miscellaneous specialty items // /*QUAKED misc_blackhole (1 .5 0) (-8 -8 -8) (8 8 8) */ void misc_blackhole_use (edict_t * ent, edict_t * other, edict_t * activator) { /* gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BOSSTPORT); gi.WritePosition (ent->s.origin); gi.multicast (ent->s.origin, MULTICAST_PVS); */ G_FreeEdict (ent); } void misc_blackhole_think (edict_t * self) { if (++self->s.frame < 19) self->nextthink = level.time + FRAMETIME; else { self->s.frame = 0; self->nextthink = level.time + FRAMETIME; } } void SP_misc_blackhole (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_NOT; VectorSet (ent->mins, -64, -64, 0); VectorSet (ent->maxs, 64, 64, 8); ent->s.modelindex = gi.modelindex ("models/objects/black/tris.md2"); ent->s.renderfx = RF_TRANSLUCENT; ent->use = misc_blackhole_use; ent->think = misc_blackhole_think; ent->nextthink = level.time + 2 * FRAMETIME; gi.linkentity (ent); } /*QUAKED misc_eastertank (1 .5 0) (-32 -32 -16) (32 32 32) */ void misc_eastertank_think (edict_t * self) { if (++self->s.frame < 293) self->nextthink = level.time + FRAMETIME; else { self->s.frame = 254; self->nextthink = level.time + FRAMETIME; } } void SP_misc_eastertank (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; VectorSet (ent->mins, -32, -32, -16); VectorSet (ent->maxs, 32, 32, 32); ent->s.modelindex = gi.modelindex ("models/monsters/tank/tris.md2"); ent->s.frame = 254; ent->think = misc_eastertank_think; ent->nextthink = level.time + 2 * FRAMETIME; gi.linkentity (ent); } /*QUAKED misc_easterchick (1 .5 0) (-32 -32 0) (32 32 32) */ void misc_easterchick_think (edict_t * self) { if (++self->s.frame < 247) self->nextthink = level.time + FRAMETIME; else { self->s.frame = 208; self->nextthink = level.time + FRAMETIME; } } void SP_misc_easterchick (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; VectorSet (ent->mins, -32, -32, 0); VectorSet (ent->maxs, 32, 32, 32); ent->s.modelindex = gi.modelindex ("models/monsters/bitch/tris.md2"); ent->s.frame = 208; ent->think = misc_easterchick_think; ent->nextthink = level.time + 2 * FRAMETIME; gi.linkentity (ent); } /*QUAKED misc_easterchick2 (1 .5 0) (-32 -32 0) (32 32 32) */ void misc_easterchick2_think (edict_t * self) { if (++self->s.frame < 287) self->nextthink = level.time + FRAMETIME; else { self->s.frame = 248; self->nextthink = level.time + FRAMETIME; } } void SP_misc_easterchick2 (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; VectorSet (ent->mins, -32, -32, 0); VectorSet (ent->maxs, 32, 32, 32); ent->s.modelindex = gi.modelindex ("models/monsters/bitch/tris.md2"); ent->s.frame = 248; ent->think = misc_easterchick2_think; ent->nextthink = level.time + 2 * FRAMETIME; gi.linkentity (ent); } /*QUAKED monster_commander_body (1 .5 0) (-32 -32 0) (32 32 48) Not really a monster, this is the Tank Commander's decapitated body. There should be a item_commander_head that has this as it's target. */ void commander_body_think (edict_t * self) { if (++self->s.frame < 24) self->nextthink = level.time + FRAMETIME; else self->nextthink = 0; if (self->s.frame == 22) gi.sound (self, CHAN_BODY, gi.soundindex ("tank/thud.wav"), 1, ATTN_NORM, 0); } void commander_body_use (edict_t * self, edict_t * other, edict_t * activator) { self->think = commander_body_think; self->nextthink = level.time + FRAMETIME; gi.sound (self, CHAN_BODY, gi.soundindex ("tank/pain.wav"), 1, ATTN_NORM, 0); } void commander_body_drop (edict_t * self) { self->movetype = MOVETYPE_TOSS; self->s.origin[2] += 2; } void SP_monster_commander_body (edict_t * self) { self->movetype = MOVETYPE_NONE; self->solid = SOLID_BBOX; self->model = "models/monsters/commandr/tris.md2"; self->s.modelindex = gi.modelindex (self->model); VectorSet (self->mins, -32, -32, 0); VectorSet (self->maxs, 32, 32, 48); self->use = commander_body_use; self->takedamage = DAMAGE_YES; self->flags = FL_GODMODE; self->s.renderfx |= RF_FRAMELERP; gi.linkentity (self); gi.soundindex ("tank/thud.wav"); gi.soundindex ("tank/pain.wav"); self->think = commander_body_drop; self->nextthink = level.time + 5 * FRAMETIME; } /*QUAKED misc_banner (1 .5 0) (-4 -4 -4) (4 4 4) The origin is the bottom of the banner. The banner is 128 tall. */ void misc_banner_think (edict_t * ent) { ent->s.frame = (ent->s.frame + 1) % 16; ent->nextthink = level.time + FRAMETIME; } void SP_misc_banner (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_NOT; ent->s.modelindex = gi.modelindex ("models/objects/banner/tris.md2"); ent->s.frame = rand () % 16; gi.linkentity (ent); ent->think = misc_banner_think; ent->nextthink = level.time + FRAMETIME; } /*QUAKED misc_deadsoldier (1 .5 0) (-16 -16 0) (16 16 16) ON_BACK ON_STOMACH BACK_DECAP FETAL_POS SIT_DECAP IMPALED This is the dead player model. Comes in 6 exciting different poses! */ void misc_deadsoldier_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { int n; if (self->health > -80) return; gi.sound (self, CHAN_BODY, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0); for (n = 0; n < 4; n++) ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); ThrowHead (self, "models/objects/gibs/head2/tris.md2", damage, GIB_ORGANIC); } void SP_misc_deadsoldier (edict_t * ent) { if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (ent); return; } ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; ent->s.modelindex = gi.modelindex ("models/deadbods/dude/tris.md2"); // Defaults to frame 0 if (ent->spawnflags & 2) ent->s.frame = 1; else if (ent->spawnflags & 4) ent->s.frame = 2; else if (ent->spawnflags & 8) ent->s.frame = 3; else if (ent->spawnflags & 16) ent->s.frame = 4; else if (ent->spawnflags & 32) ent->s.frame = 5; else ent->s.frame = 0; VectorSet (ent->mins, -16, -16, 0); VectorSet (ent->maxs, 16, 16, 16); ent->deadflag = DEAD_DEAD; ent->takedamage = DAMAGE_YES; ent->svflags |= SVF_MONSTER | SVF_DEADMONSTER; ent->die = misc_deadsoldier_die; ent->monsterinfo.aiflags |= AI_GOOD_GUY; gi.linkentity (ent); } /*QUAKED misc_viper (1 .5 0) (-16 -16 0) (16 16 32) This is the Viper for the flyby bombing. It is trigger_spawned, so you must have something use it for it to show up. There must be a path for it to follow once it is activated. "speed" How fast the Viper should fly */ extern void train_use (edict_t * self, edict_t * other, edict_t * activator); extern void func_train_find (edict_t * self); void misc_viper_use (edict_t * self, edict_t * other, edict_t * activator) { self->svflags &= ~SVF_NOCLIENT; self->use = train_use; train_use (self, other, activator); } void SP_misc_viper (edict_t * ent) { if (!ent->target) { gi.dprintf ("misc_viper without a target at %s\n", vtos (ent->absmin)); G_FreeEdict (ent); return; } if (!ent->speed) ent->speed = 300; ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_NOT; ent->s.modelindex = gi.modelindex ("models/ships/viper/tris.md2"); VectorSet (ent->mins, -16, -16, 0); VectorSet (ent->maxs, 16, 16, 32); ent->think = func_train_find; ent->nextthink = level.time + FRAMETIME; ent->use = misc_viper_use; ent->svflags |= SVF_NOCLIENT; ent->moveinfo.accel = ent->moveinfo.decel = ent->moveinfo.speed = ent->speed; gi.linkentity (ent); } /*QUAKED misc_bigviper (1 .5 0) (-176 -120 -24) (176 120 72) This is a large stationary viper as seen in Paul's intro */ void SP_misc_bigviper (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; VectorSet (ent->mins, -176, -120, -24); VectorSet (ent->maxs, 176, 120, 72); ent->s.modelindex = gi.modelindex ("models/ships/bigviper/tris.md2"); gi.linkentity (ent); } /*QUAKED misc_viper_bomb (1 0 0) (-8 -8 -8) (8 8 8) "dmg" how much boom should the bomb make? */ void misc_viper_bomb_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { G_UseTargets (self, self->activator); self->s.origin[2] = self->absmin[2] + 1; T_RadiusDamage (self, self, self->dmg, NULL, self->dmg + 40, MOD_BOMB); BecomeExplosion2 (self); } void misc_viper_bomb_prethink (edict_t * self) { vec3_t v; float diff; self->groundentity = NULL; diff = self->timestamp - level.time; if (diff < -1.0) diff = -1.0; VectorScale (self->moveinfo.dir, 1.0 + diff, v); v[2] = diff; diff = self->s.angles[2]; vectoangles (v, self->s.angles); self->s.angles[2] = diff + 10; } void misc_viper_bomb_use (edict_t * self, edict_t * other, edict_t * activator) { edict_t *viper; self->solid = SOLID_BBOX; self->svflags &= ~SVF_NOCLIENT; self->s.effects |= EF_ROCKET; self->use = NULL; self->movetype = MOVETYPE_TOSS; self->prethink = misc_viper_bomb_prethink; self->touch = misc_viper_bomb_touch; self->activator = activator; viper = G_Find (NULL, FOFS (classname), "misc_viper"); VectorScale (viper->moveinfo.dir, viper->moveinfo.speed, self->velocity); self->timestamp = level.time; VectorCopy (viper->moveinfo.dir, self->moveinfo.dir); } void SP_misc_viper_bomb (edict_t * self) { self->movetype = MOVETYPE_NONE; self->solid = SOLID_NOT; VectorSet (self->mins, -8, -8, -8); VectorSet (self->maxs, 8, 8, 8); self->s.modelindex = gi.modelindex ("models/objects/bomb/tris.md2"); if (!self->dmg) self->dmg = 1000; self->use = misc_viper_bomb_use; self->svflags |= SVF_NOCLIENT; gi.linkentity (self); } /*QUAKED misc_strogg_ship (1 .5 0) (-16 -16 0) (16 16 32) This is a Storgg ship for the flybys. It is trigger_spawned, so you must have something use it for it to show up. There must be a path for it to follow once it is activated. "speed" How fast it should fly */ extern void train_use (edict_t * self, edict_t * other, edict_t * activator); extern void func_train_find (edict_t * self); void misc_strogg_ship_use (edict_t * self, edict_t * other, edict_t * activator) { self->svflags &= ~SVF_NOCLIENT; self->use = train_use; train_use (self, other, activator); } void SP_misc_strogg_ship (edict_t * ent) { if (!ent->target) { gi.dprintf ("%s without a target at %s\n", ent->classname, vtos (ent->absmin)); G_FreeEdict (ent); return; } if (!ent->speed) ent->speed = 300; ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_NOT; ent->s.modelindex = gi.modelindex ("models/ships/strogg1/tris.md2"); VectorSet (ent->mins, -16, -16, 0); VectorSet (ent->maxs, 16, 16, 32); ent->think = func_train_find; ent->nextthink = level.time + FRAMETIME; ent->use = misc_strogg_ship_use; ent->svflags |= SVF_NOCLIENT; ent->moveinfo.accel = ent->moveinfo.decel = ent->moveinfo.speed = ent->speed; gi.linkentity (ent); } /*QUAKED misc_satellite_dish (1 .5 0) (-64 -64 0) (64 64 128) */ void misc_satellite_dish_think (edict_t * self) { self->s.frame++; if (self->s.frame < 38) self->nextthink = level.time + FRAMETIME; } void misc_satellite_dish_use (edict_t * self, edict_t * other, edict_t * activator) { self->s.frame = 0; self->think = misc_satellite_dish_think; self->nextthink = level.time + FRAMETIME; } void SP_misc_satellite_dish (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; VectorSet (ent->mins, -64, -64, 0); VectorSet (ent->maxs, 64, 64, 128); ent->s.modelindex = gi.modelindex ("models/objects/satellite/tris.md2"); ent->use = misc_satellite_dish_use; gi.linkentity (ent); } /*QUAKED light_mine1 (0 1 0) (-2 -2 -12) (2 2 12) */ void SP_light_mine1 (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; ent->s.modelindex = gi.modelindex ("models/objects/minelite/light1/tris.md2"); gi.linkentity (ent); } /*QUAKED light_mine2 (0 1 0) (-2 -2 -12) (2 2 12) */ void SP_light_mine2 (edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_BBOX; ent->s.modelindex = gi.modelindex ("models/objects/minelite/light2/tris.md2"); gi.linkentity (ent); } /*QUAKED misc_gib_arm (1 0 0) (-8 -8 -8) (8 8 8) Intended for use with the target_spawner */ void SP_misc_gib_arm (edict_t * ent) { gi.setmodel (ent, "models/objects/gibs/arm/tris.md2"); ent->solid = SOLID_NOT; ent->s.effects |= EF_GIB; ent->takedamage = DAMAGE_YES; ent->die = gib_die; ent->movetype = MOVETYPE_TOSS; ent->svflags |= SVF_MONSTER; ent->deadflag = DEAD_DEAD; ent->avelocity[0] = random () * 200; ent->avelocity[1] = random () * 200; ent->avelocity[2] = random () * 200; ent->think = G_FreeEdict; ent->nextthink = level.time + 30; gi.linkentity (ent); } /*QUAKED misc_gib_leg (1 0 0) (-8 -8 -8) (8 8 8) Intended for use with the target_spawner */ void SP_misc_gib_leg (edict_t * ent) { gi.setmodel (ent, "models/objects/gibs/leg/tris.md2"); ent->solid = SOLID_NOT; ent->s.effects |= EF_GIB; ent->takedamage = DAMAGE_YES; ent->die = gib_die; ent->movetype = MOVETYPE_TOSS; ent->svflags |= SVF_MONSTER; ent->deadflag = DEAD_DEAD; ent->avelocity[0] = random () * 200; ent->avelocity[1] = random () * 200; ent->avelocity[2] = random () * 200; ent->think = G_FreeEdict; ent->nextthink = level.time + 30; gi.linkentity (ent); } /*QUAKED misc_gib_head (1 0 0) (-8 -8 -8) (8 8 8) Intended for use with the target_spawner */ void SP_misc_gib_head (edict_t * ent) { gi.setmodel (ent, "models/objects/gibs/head/tris.md2"); ent->solid = SOLID_NOT; ent->s.effects |= EF_GIB; ent->takedamage = DAMAGE_YES; ent->die = gib_die; ent->movetype = MOVETYPE_TOSS; ent->svflags |= SVF_MONSTER; ent->deadflag = DEAD_DEAD; ent->avelocity[0] = random () * 200; ent->avelocity[1] = random () * 200; ent->avelocity[2] = random () * 200; ent->think = G_FreeEdict; ent->nextthink = level.time + 30; gi.linkentity (ent); } //===================================================== /*QUAKED target_character (0 0 1) ? used with target_string (must be on same "team") "count" is position in the string (starts at 1) */ void SP_target_character (edict_t * self) { self->movetype = MOVETYPE_PUSH; gi.setmodel (self, self->model); self->solid = SOLID_BSP; self->s.frame = 12; gi.linkentity (self); return; } /*QUAKED target_string (0 0 1) (-8 -8 -8) (8 8 8) */ void target_string_use (edict_t * self, edict_t * other, edict_t * activator) { edict_t *e; int n, l; char c; l = strlen (self->message); for (e = self->teammaster; e; e = e->teamchain) { if (!e->count) continue; n = e->count - 1; if (n > l) { e->s.frame = 12; continue; } c = self->message[n]; if (c >= '0' && c <= '9') e->s.frame = c - '0'; else if (c == '-') e->s.frame = 10; else if (c == ':') e->s.frame = 11; else e->s.frame = 12; } } void SP_target_string (edict_t * self) { if (!self->message) self->message = ""; self->use = target_string_use; } /*QUAKED func_clock (0 0 1) (-8 -8 -8) (8 8 8) TIMER_UP TIMER_DOWN START_OFF MULTI_USE target a target_string with this The default is to be a time of day clock TIMER_UP and TIMER_DOWN run for "count" seconds and the fire "pathtarget" If START_OFF, this entity must be used before it starts "style" 0 "xx" 1 "xx:xx" 2 "xx:xx:xx" */ #define CLOCK_MESSAGE_SIZE 16 // don't let field width of any clock messages change, or it // could cause an overwrite after a game load static void func_clock_reset (edict_t * self) { self->activator = NULL; if (self->spawnflags & 1) { self->health = 0; self->wait = self->count; } else if (self->spawnflags & 2) { self->health = self->count; self->wait = 0; } } static void func_clock_format_countdown (edict_t * self) { if (self->style == 0) { Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i", self->health); return; } if (self->style == 1) { Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i:%2i", self->health / 60, self->health % 60); if (self->message[3] == ' ') self->message[3] = '0'; return; } if (self->style == 2) { Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i:%2i:%2i", self->health / 3600, (self->health - (self->health / 3600) * 3600) / 60, self->health % 60); if (self->message[3] == ' ') self->message[3] = '0'; if (self->message[6] == ' ') self->message[6] = '0'; return; } } void func_clock_think (edict_t * self) { if (!self->enemy) { self->enemy = G_Find (NULL, FOFS (targetname), self->target); if (!self->enemy) return; } if (self->spawnflags & 1) { func_clock_format_countdown (self); self->health++; } else if (self->spawnflags & 2) { func_clock_format_countdown (self); self->health--; } else { struct tm *ltime; time_t gmtime; time (&gmtime); ltime = localtime (&gmtime); Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i:%2i:%2i", ltime->tm_hour, ltime->tm_min, ltime->tm_sec); if (self->message[3] == ' ') self->message[3] = '0'; if (self->message[6] == ' ') self->message[6] = '0'; } self->enemy->message = self->message; self->enemy->use (self->enemy, self, self); if (((self->spawnflags & 1) && (self->health > self->wait)) || ((self->spawnflags & 2) && (self->health < self->wait))) { if (self->pathtarget) { char *savetarget; char *savemessage; savetarget = self->target; savemessage = self->message; self->target = self->pathtarget; self->message = NULL; G_UseTargets (self, self->activator); self->target = savetarget; self->message = savemessage; } if (!(self->spawnflags & 8)) return; func_clock_reset (self); if (self->spawnflags & 4) return; } self->nextthink = level.time + 1; } void func_clock_use (edict_t * self, edict_t * other, edict_t * activator) { if (!(self->spawnflags & 8)) self->use = NULL; if (self->activator) return; self->activator = activator; self->think (self); } void SP_func_clock (edict_t * self) { if (!self->target) { gi.dprintf ("%s with no target at %s\n", self->classname, vtos (self->s.origin)); G_FreeEdict (self); return; } if ((self->spawnflags & 2) && (!self->count)) { gi.dprintf ("%s with no count at %s\n", self->classname, vtos (self->s.origin)); G_FreeEdict (self); return; } if ((self->spawnflags & 1) && (!self->count)) self->count = 60 * 60;; func_clock_reset (self); self->message = gi.TagMalloc (CLOCK_MESSAGE_SIZE, TAG_LEVEL); self->think = func_clock_think; if (self->spawnflags & 4) self->use = func_clock_use; else self->nextthink = level.time + 1; } //================================================================================= void teleporter_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { edict_t *dest; int i; if (!other->client) return; dest = G_Find (NULL, FOFS (targetname), self->target); if (!dest) { gi.dprintf ("Couldn't find destination\n"); return; } // let's be safe, if grapple was disabled but the player has it CTFPlayerResetGrapple(other); // unlink to make sure it can't possibly interfere with KillBox gi.unlinkentity (other); VectorCopy (dest->s.origin, other->s.origin); VectorCopy (dest->s.origin, other->s.old_origin); other->s.origin[2] += 10; // clear the velocity and hold them in place briefly VectorClear (other->velocity); other->client->ps.pmove.pm_time = 160 >> 3; // hold time other->client->ps.pmove.pm_flags |= PMF_TIME_TELEPORT; // draw the teleport splash at source and on the player self->owner->s.event = EV_PLAYER_TELEPORT; other->s.event = EV_PLAYER_TELEPORT; // set angles for (i = 0; i < 3; i++) other->client->ps.pmove.delta_angles[i] = ANGLE2SHORT (dest->s.angles[i] - other->client->resp.cmd_angles[i]); VectorClear (other->s.angles); VectorClear (other->client->ps.viewangles); VectorClear (other->client->v_angle); // kill anything at the destination KillBox (other); gi.linkentity (other); } /*QUAKED misc_teleporter (1 0 0) (-32 -32 -24) (32 32 -16) Stepping onto this disc will teleport players to the targeted misc_teleporter_dest object. */ void SP_misc_teleporter (edict_t * ent) { edict_t *trig; if (!ent->target) { gi.dprintf ("teleporter without a target.\n"); G_FreeEdict (ent); return; } gi.setmodel (ent, "models/objects/dmspot/tris.md2"); ent->s.skinnum = 1; ent->s.effects = EF_TELEPORTER; ent->s.sound = gi.soundindex ("world/amb10.wav"); ent->solid = SOLID_BBOX; VectorSet (ent->mins, -32, -32, -24); VectorSet (ent->maxs, 32, 32, -16); gi.linkentity (ent); trig = G_Spawn (); trig->touch = teleporter_touch; trig->solid = SOLID_TRIGGER; trig->target = ent->target; trig->owner = ent; VectorCopy (ent->s.origin, trig->s.origin); VectorSet (trig->mins, -8, -8, 8); VectorSet (trig->maxs, 8, 8, 24); gi.linkentity (trig); } /*QUAKED misc_teleporter_dest (1 0 0) (-32 -32 -24) (32 32 -16) Point teleporters at these. */ void SP_misc_teleporter_dest (edict_t * ent) { // zucc modified to remove visible teleporter/dm start //gi.setmodel (ent, "models/objects/dmspot/tris.md2"); ent->s.skinnum = 0; ent->solid = SOLID_NOT; //ent->solid = SOLID_BBOX; // ent->s.effects |= EF_FLIES; // VectorSet (ent->mins, -32, -32, -24); // VectorSet (ent->maxs, 32, 32, -16); VectorSet (ent->mins, 0, 0, 0); VectorSet (ent->maxs, 0, 0, 0); gi.linkentity (ent); }
530
./aq2-tng/source/a_game.c
//----------------------------------------------------------------------------- // a_game.c // General game code for Action (formerly Axshun). // // Zucchini ([email protected]) and Fireblade ([email protected]) // (splat/bullethole/shell ejection code from original Action source) // // $Id: a_game.c,v 1.14 2003/06/15 15:34:32 igor Exp $ // //----------------------------------------------------------------------------- // $Log: a_game.c,v $ // Revision 1.14 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.13 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.12 2002/12/30 12:58:16 igor_rock // - Corrected some comments (now it looks better) // - allweapon mode now recognizes wp_flags // // Revision 1.11 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.10 2001/08/22 14:40:14 deathwatch // Updated the MOTD to use less lines // // Revision 1.9 2001/07/06 13:10:35 deathwatch // Fixed a broken if/then/else statement in MOTD // // Revision 1.8 2001/06/28 14:36:40 deathwatch // Updated the Credits Menu a slight bit (added Kobra) // // Revision 1.7 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.6.2.2 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.6.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.6 2001/05/13 11:29:25 igor_rock // corrected spelling error in inernet address (www, instead www.) // // Revision 1.5 2001/05/12 18:38:27 deathwatch // Tweaked MOTD and Menus some more // // Revision 1.4 2001/05/12 17:36:33 deathwatch // Edited the version variables and updated the menus. Added variables: // ACTION_VERSION, TNG_VERSION and TNG_VERSION2 // // Revision 1.3 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.2 2001/05/11 12:21:18 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.1.1.1 2001/05/06 17:24:23 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" #define MAX_MAP_ROTATION 1000 // just in case... #define MAX_STR_LEN 1000 #define MAX_TOTAL_MOTD_LINES 30 char *map_rotation[MAX_MAP_ROTATION]; int num_maps, cur_map, num_allvotes; // num_allvotes added by Igor[Rock] char motd_lines[MAX_TOTAL_MOTD_LINES][40]; int motd_num_lines; /* * ReadConfigFile() * Config file format is backwards compatible with Action's, but doesn't need * the "###" designator at end of sections. * -Fireblade */ void ReadConfigFile() { FILE *config_file; char buf[MAX_STR_LEN], reading_section[MAX_STR_LEN], inipath[MAX_STR_LEN]; int lines_into_section = -1; cvar_t *ininame; ininame = gi.cvar("ininame", "action.ini", 0); if (ininame->string && *(ininame->string)) sprintf(inipath, "%s/%s", GAMEVERSION, ininame->string); else sprintf(inipath, "%s/%s", GAMEVERSION, "action.ini"); config_file = fopen(inipath, "r"); if (config_file == NULL) { gi.dprintf("Unable to read %s\n", inipath); return; } while (fgets(buf, MAX_STR_LEN - 10, config_file) != NULL) { int bs; bs = strlen(buf); while (buf[bs - 1] == '\r' || buf[bs - 1] == '\n') { buf[bs - 1] = 0; bs--; } if ((buf[0] == '/' && buf[1] == '/') || buf[0] == 0) { continue; } if (buf[0] == '[') { char *p; p = strchr(buf, ']'); if (p == NULL) continue; *p = 0; strcpy(reading_section, buf + 1); lines_into_section = 0; continue; } if (buf[0] == '#' && buf[1] == '#' && buf[2] == '#') { lines_into_section = -1; continue; } if (lines_into_section > -1) { if (!strcmp(reading_section, "team1")) { if (lines_into_section == 0) { Q_strncpyz(teams[TEAM1].name, buf, sizeof(teams[TEAM1].name)); } else if (lines_into_section == 1) { Q_strncpyz(teams[TEAM1].skin, buf, sizeof(teams[TEAM1].skin)); } } else if (!strcmp(reading_section, "team2")) { if (lines_into_section == 0) { Q_strncpyz(teams[TEAM2].name, buf, sizeof(teams[TEAM2].name)); } else if (lines_into_section == 1) { Q_strncpyz(teams[TEAM2].skin, buf, sizeof(teams[TEAM2].skin)); } } else if (!strcmp(reading_section, "team3")) { if (lines_into_section == 0) { Q_strncpyz(teams[TEAM3].name, buf, sizeof(teams[TEAM3].name)); } else if (lines_into_section == 1) { Q_strncpyz(teams[TEAM3].skin, buf, sizeof(teams[TEAM3].skin)); } } else if (!strcmp(reading_section, "maplist")) { map_rotation[num_maps] = (char *) gi.TagMalloc(strlen(buf) + 1, TAG_GAME); strcpy(map_rotation[num_maps], buf); num_maps++; } lines_into_section++; } } Com_sprintf(teams[TEAM1].skin_index, sizeof(teams[TEAM1].skin_index), "../players/%s_i", teams[TEAM1].skin); Com_sprintf(teams[TEAM2].skin_index, sizeof(teams[TEAM2].skin_index), "../players/%s_i", teams[TEAM2].skin); Com_sprintf(teams[TEAM3].skin_index, sizeof(teams[TEAM3].skin_index), "../players/%s_i", teams[TEAM3].skin); cur_map = 0; fclose(config_file); } void ReadMOTDFile() { FILE *motd_file; char buf[1000]; char motdpath[MAX_STR_LEN]; int lbuf; cvar_t *motdname; motdname = gi.cvar("motdname", "motd.txt", 0); if (motdname->string && *(motdname->string)) sprintf(motdpath, "%s/%s", GAMEVERSION, motdname->string); else sprintf(motdpath, "%s/%s", GAMEVERSION, "motd.txt"); motd_file = fopen(motdpath, "r"); if (motd_file == NULL) return; motd_num_lines = 0; while (fgets(buf, 900, motd_file) != NULL) { lbuf = strlen(buf); while (lbuf > 0 && (buf[lbuf - 1] == '\r' || buf[lbuf - 1] == '\n')) { buf[lbuf - 1] = 0; lbuf--; } if(!lbuf) continue; if (lbuf > 39) buf[39] = 0; strcpy(motd_lines[motd_num_lines++], buf); if (motd_num_lines >= MAX_TOTAL_MOTD_LINES) break; } fclose(motd_file); } // AQ2:TNG Deathwatch - Ohh, lovely MOTD - edited it void PrintMOTD(edict_t * ent) { int mapnum, i, lines = 0; int max_lines = MAX_TOTAL_MOTD_LINES; char msg_buf[1024], *server_type; //Welcome Message. This shows the Version Number and website URL, followed by an empty line strcpy(msg_buf, TNG_VERSION2 "\n" "http://aq2-tng.sourceforge.net/\n" "\n"); lines = 3; /* As long as we don't skip the MOTD, we want to print all information */ if (!skipmotd->value) { // This line will show the hostname. If not set, the default name will be "Unnamed TNG Server" (used to be "unnamed") if (hostname->string[0] && strcmp(hostname->string, "Unnamed TNG Server")) { Q_strncatz(msg_buf, hostname->string, strlen(msg_buf)+40); strcat(msg_buf, "\n"); lines++; } /* Now all the settings */ // Check what game type it is if (teamplay->value) { if (ctf->value) // Is it CTF? server_type = "Capture the Flag"; else if (matchmode->value) // Is it Matchmode? server_type = "Matchmode"; else if (use_3teams->value) // Is it 3 Teams? server_type = "3 Team Teamplay"; else if (teamdm->value) // Is it TeamDM? server_type = "Team Deathmatch"; else if (use_tourney->value) // Is it Tourney? server_type = "Tourney"; else // No? Then it must be Teamplay server_type = "Teamplay"; } else // So it's not Teamplay? { // Set the appropiate Deathmatch mode if ((int)dmflags->value & DF_MODELTEAMS) server_type = "Deathmatch (Teams by Model)"; else if ((int)dmflags->value & DF_SKINTEAMS) server_type = "Deathmatch (Teams by Skin)"; else server_type = "Deathmatch (No Teams)"; } sprintf(msg_buf + strlen(msg_buf), "Game Type: %s\n", server_type); lines++; /* new CTF settings added here for better readability */ if(ctf->value) { strcat(msg_buf, "\n"); lines++; if(ctfgame.type == 0) sprintf(msg_buf + strlen(msg_buf), "CTF Type: Normal\n"); else if(ctfgame.type == 1) sprintf(msg_buf + strlen(msg_buf), "CTF Type: Balanced\n"); else if(ctfgame.type == 2) sprintf(msg_buf + strlen(msg_buf), "CTF Type: Off/Def, attacker is %s\n", CTFTeamName(ctfgame.offence)); else strcat(msg_buf, "\n"); lines++; if(ctfgame.spawn_red > -1 || ctfgame.spawn_blue > -1) { sprintf(msg_buf + strlen(msg_buf), "Spawn times: "); if(ctfgame.spawn_red > -1) sprintf(msg_buf + strlen(msg_buf), "RED: %ds ", ctfgame.spawn_red); if(ctfgame.spawn_blue > -1) sprintf(msg_buf + strlen(msg_buf), "BLUE: %ds", ctfgame.spawn_blue); strcat(msg_buf, "\n"); lines++; } sprintf(msg_buf + strlen(msg_buf), "Using %s spawns\n", (ctfgame.custom_spawns ? "CUSTOM" : "ORIGINAL")); lines++; sprintf(msg_buf + strlen(msg_buf), "Grapple %s available\n", (use_grapple->value ? "IS" : "IS NOT")); lines++; if(ctfgame.author) { strcat(msg_buf, "\n"); lines++; sprintf(msg_buf + strlen(msg_buf), "CTF configuration by %s\n", ctfgame.author); lines++; /* no comment without author, grr */ if(ctfgame.comment) { /* max line length is 39 chars + new line */ strncat(msg_buf + strlen(msg_buf), ctfgame.comment, 39); strcat(msg_buf, "\n"); lines++; } } } /* Darkmatch */ if ((darkmatch->value == 1) || (darkmatch->value == 2) || (darkmatch->value == 3)) { if (darkmatch->value == 1) sprintf(msg_buf + strlen(msg_buf), "Playing in Total Darkness\n"); else if (darkmatch->value == 2) sprintf(msg_buf + strlen(msg_buf), "Playing in Near Darkness\n"); else if (darkmatch->value == 3) sprintf(msg_buf + strlen(msg_buf), "Playing in Day and Nighttime\n"); lines++; } // Adding an empty line strcat(msg_buf, "\n"); lines++; /* Now for the map rules, such as Timelimit, Roundlimit, etc */ if ((int)fraglimit->value) // What is the fraglimit? sprintf(msg_buf + strlen(msg_buf), "Fraglimit: %d", (int) fraglimit->value); else strcat(msg_buf, "Fraglimit: none"); if ((int) timelimit->value) // What is the timelimit? sprintf(msg_buf + strlen(msg_buf), " Timelimit: %d\n", (int) timelimit->value); else strcat(msg_buf, " Timelimit: none\n"); lines++; // If we're in Teamplay, and not CTF, we want to see what the roundlimit and roundtimelimit is if (teamplay->value && !ctf->value && !teamdm->value) { if ((int)roundlimit->value) // What is the roundlimit? sprintf(msg_buf + strlen(msg_buf), "Roundlimit: %d", (int)roundlimit->value); else strcat(msg_buf, "Roundlimit: none"); if ((int)roundtimelimit->value) // What is the roundtimelimit? sprintf(msg_buf + strlen(msg_buf), " Roundtimelimit: %d\n", (int)roundtimelimit->value); else strcat(msg_buf, " Roundtimelimit: none\n"); lines++; } else if (ctf->value) // If we're in CTF, we want to know the capturelimit { if ((int) capturelimit->value) // What is the capturelimit? sprintf(msg_buf + strlen(msg_buf), " Capturelimit: %d\n", (int) capturelimit->value); else strcat(msg_buf, " Capturelimit: none\n"); lines++; } /* Check for the number of weapons and items people can carry */ if ((int)unique_weapons->value != 1 || (int)unique_items->value != 1) { sprintf(msg_buf + strlen(msg_buf), "Max number of spec weapons: %d items: %d\n", (int) unique_weapons->value, (int) unique_items->value); lines++; } /* What can we use with the Bandolier? */ if (tgren->value > 0 || !(ir->value)) { char grenade_num[32]; // Show the number of grenades with the Bandolier if (tgren->value > 0) sprintf(grenade_num, "%d grenade%s", (int)tgren->value, (int)tgren->value == 1 ? "" : "s"); sprintf(msg_buf + strlen(msg_buf), "Bandolier w/ %s%s%s\n", !(ir->value) ? "no IR" : "", (tgren->value > 0 && !(ir->value)) ? " & " : "", tgren->value > 0 ? grenade_num : ""); lines++; } /* Is allitem and/or allweapon enabled? */ if (allitem->value || allweapon->value) { sprintf(msg_buf + strlen(msg_buf), "Players receive %s%s%s\n", allweapon->value ? "all weapons" : "", (allweapon->value && allitem->value) ? " & " : "", allitem->value ? "all items" : ""); lines++; } /* * Are we using limchasecam? */ if (limchasecam->value) { if ((int) limchasecam->value == 2) sprintf(msg_buf + strlen(msg_buf), "Chase Cam Disallowed\n"); else sprintf(msg_buf + strlen(msg_buf), "Chase Cam Restricted\n"); lines++; } /* * Are the dmflags set to disallow Friendly Fire? */ if (teamplay->value && !((int) dmflags->value & DF_NO_FRIENDLY_FIRE)) { sprintf(msg_buf + strlen(msg_buf), "Friendly Fire Enabled\n"); lines++; } /* Are we using any types of voting? */ if (use_mapvote->value || use_cvote->value || use_kickvote->value) { sprintf(msg_buf + strlen(msg_buf), "Vote Types: %s%s%s%s%s\n", use_mapvote->value ? "Map" : "", (use_mapvote->value && use_cvote->value) ? " & " : "", use_cvote->value ? "Config" : "", ((use_mapvote->value && use_kickvote->value) || (use_cvote->value && use_kickvote->value)) ? " & " : "", use_kickvote->value ? "Kick" : ""); lines++; // lines+=3; } /* Map Locations */ if (ml_count != 0) { sprintf(msg_buf + strlen(msg_buf), "\n%d Locations, by: %s\n", ml_count, ml_creator); lines++; } /* If actionmaps, put a blank line then the maps list */ if (actionmaps->value && num_maps > 0) { int chars_on_line = 0, len_mr; if (vrot->value) // Using Vote Rotation? strcat(msg_buf, "\nRunning these maps in vote order:\n"); else if (rrot->value) // Using Random Rotation? strcat(msg_buf, "\nRunning the following maps randomly:\n"); else strcat(msg_buf, "\nRunning the following maps in order:\n"); lines += 2; for (mapnum = 0; mapnum < num_maps; mapnum++) { len_mr = strlen(*(map_rotation + mapnum)); if ((chars_on_line + len_mr + 2) > 39) { Q_strncatz(msg_buf, "\n", sizeof(msg_buf)); lines++; if (lines >= max_lines) break; chars_on_line = 0; } Q_strncatz(msg_buf, *(map_rotation + mapnum), sizeof(msg_buf)); chars_on_line += len_mr; if (mapnum < (num_maps - 1)) { Q_strncatz(msg_buf, ", ", sizeof(msg_buf)); chars_on_line += 2; } } if (lines < max_lines) { Q_strncatz(msg_buf, "\n", sizeof(msg_buf)); lines++; } } //If we're in teamplay, we want to inform people that they can open the menu with TAB if (teamplay->value && lines < max_lines && !auto_menu->value) { Q_strncatz(msg_buf, "\nHit TAB to open the Team selection menu", sizeof(msg_buf)); lines++; } } /* Insert action/motd.txt contents (whole MOTD gets truncated after 30 lines) */ if (motd_num_lines && lines < max_lines-1) { Q_strncatz(msg_buf, "\n", sizeof(msg_buf)); lines++; for (i = 0; i < motd_num_lines; i++) { Q_strncatz(msg_buf, motd_lines[i], sizeof(msg_buf)); lines++; if (lines >= max_lines) break; Q_strncatz(msg_buf, "\n", sizeof(msg_buf)); } } if (!auto_menu->value || ent->client->resp.menu_shown) { gi.centerprintf(ent, "%s", msg_buf); } else { gi.cprintf(ent, PRINT_LOW, "%s", msg_buf); } } // stuffcmd: forces a player to execute a command. void stuffcmd(edict_t * ent, char *c) { gi.WriteByte(svc_stufftext); gi.WriteString(c); gi.unicast(ent, true); } void unicastSound(edict_t *ent, int soundIndex, float volume) { int mask = MASK_ENTITY_CHANNEL; if (volume != 1.0) mask |= MASK_VOLUME; gi.WriteByte(svc_sound); gi.WriteByte((byte)mask); gi.WriteByte((byte)soundIndex); if (mask & MASK_VOLUME) gi.WriteByte((byte)(volume * 255)); gi.WriteShort(((ent - g_edicts - 1) << 3) + CHAN_NO_PHS_ADD); gi.unicast (ent, true); } // AQ2:TNG END /******************************************************************************** * * zucc: following are EjectBlooder, EjectShell, AddSplat, and AddDecal * code. All from actionquake, some had to be modified to fit Axshun or fix * bugs. * */ int decals = 0; int shells = 0; int splats = 0; //blooder used for bleeding void BlooderDie(edict_t * self) { G_FreeEdict(self); } void BlooderTouch(edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { G_FreeEdict(self); } void EjectBlooder(edict_t * self, vec3_t start, vec3_t veloc) { edict_t *blooder; vec3_t forward; int spd = 0; blooder = G_Spawn(); VectorCopy(veloc, forward); VectorCopy(start, blooder->s.origin); spd = 0; VectorScale(forward, spd, blooder->velocity); blooder->solid = SOLID_NOT; blooder->movetype = MOVETYPE_TOSS; blooder->s.modelindex = gi.modelindex("sprites/null.sp2"); blooder->s.effects |= EF_GIB; blooder->owner = self; blooder->touch = BlooderTouch; blooder->nextthink = level.time + 3.2; blooder->think = BlooderDie; blooder->classname = "blooder"; gi.linkentity(blooder); } // zucc - Adding EjectShell code from action quake, modified for Axshun. /********* SHELL EJECTION **************/ void ShellTouch(edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (self->owner->client->curr_weap == M3_NUM) gi.sound(self, CHAN_WEAPON, gi.soundindex("weapons/shellhit1.wav"), 1, ATTN_STATIC, 0); else if (random() < 0.5) gi.sound(self, CHAN_WEAPON, gi.soundindex("weapons/tink1.wav"), 0.2, ATTN_STATIC, 0); else gi.sound(self, CHAN_WEAPON, gi.soundindex("weapons/tink2.wav"), 0.2, ATTN_STATIC, 0); } void ShellDie(edict_t * self) { G_FreeEdict(self); --shells; } // zucc fixed this so it works with the sniper rifle and checks handedness // had to add the toggle feature to handle the akimbos correctly, if 1 // it sets up for ejecting the shell from the left akimbo weapon, if 2 // it fires right handed akimbo void EjectShell(edict_t * self, vec3_t start, int toggle) { edict_t *shell; vec3_t forward, right, up; float r; float fix = 1.0; int left = 0; if (sv_shelloff->value) return; shell = G_Spawn(); ++shells; AngleVectors(self->client->v_angle, forward, right, up); if (self->client->pers.hand == LEFT_HANDED) { left = 1; fix = -1.0; } else if (self->client->pers.hand == CENTER_HANDED) fix = 0; // zucc spent a fair amount of time hacking these until they look ok, // several of them could be improved however. if (self->client->curr_weap == MK23_NUM) { VectorMA(start, left ? -7 : .4, right, start); VectorMA(start, left ? 5 : 2, forward, start); VectorMA(start, left ? -10 : -8, up, start); } else if (self->client->curr_weap == M4_NUM) { VectorMA(start, left ? -10 : 5, right, start); VectorMA(start, left ? 6 : 12, forward, start); VectorMA(start, left ? -9 : -11, up, start); } else if (self->client->curr_weap == MP5_NUM) { VectorMA(start, left ? -10 : 6, right, start); VectorMA(start, left ? 6 : 8, forward, start); VectorMA(start, left ? -9 : -10, up, start); } else if (self->client->curr_weap == SNIPER_NUM) { VectorMA(start, fix * 11, right, start); VectorMA(start, 2, forward, start); VectorMA(start, -11, up, start); } else if (self->client->curr_weap == M3_NUM) { VectorMA(start, left ? -9 : 3, right, start); VectorMA(start, left ? 4 : 4, forward, start); VectorMA(start, left ? -1 : -1, up, start); } else if (self->client->curr_weap == DUAL_NUM) { if (self->client->pers.hand == LEFT_HANDED) VectorMA(start, ((toggle == 1) ? 8 : -8), right, start); else VectorMA(start, ((toggle == 1) ? -4 : 4), right, start); VectorMA(start, 6, forward, start); VectorMA(start, -9, up, start); } if ((forward[2] >= -1) && (forward[2] < -0.99)) { VectorMA(start, 5, forward, start); VectorMA(start, -0.5, up, start); } else if ((forward[2] >= -0.99) && (forward[2] < -0.98)) { VectorMA(start, 5, forward, start); VectorMA(start, -.1, up, start); } else if ((forward[2] >= -0.98) && (forward[2] < -0.97)) { VectorMA(start, 5.1, forward, start); VectorMA(start, 0.3, up, start); } else if ((forward[2] >= -0.97) && (forward[2] < -0.96)) { VectorMA(start, 5.2, forward, start); VectorMA(start, 0.7, up, start); } else if ((forward[2] >= -0.96) && (forward[2] < -0.95)) { VectorMA(start, 5.2, forward, start); VectorMA(start, 1.1, up, start); } else if ((forward[2] >= -0.95) && (forward[2] < -0.94)) { VectorMA(start, 5.3, forward, start); VectorMA(start, 1.5, up, start); } else if ((forward[2] >= -0.94) && (forward[2] < -0.93)) { VectorMA(start, 5.4, forward, start); VectorMA(start, 1.9, up, start); } else if ((forward[2] >= -0.93) && (forward[2] < -0.92)) { VectorMA(start, 5.5, forward, start); VectorMA(start, 2.3, up, start); } else if ((forward[2] >= -0.92) && (forward[2] < -0.91)) { VectorMA(start, 5.6, forward, start); VectorMA(start, 2.7, up, start); } else if ((forward[2] >= -0.91) && (forward[2] < -0.9)) { VectorMA(start, 5.7, forward, start); VectorMA(start, 3.1, up, start); } else if ((forward[2] >= -0.9) && (forward[2] < -0.85)) { VectorMA(start, 5.8, forward, start); VectorMA(start, 3.5, up, start); } else if ((forward[2] >= -0.85) && (forward[2] < -0.8)) { VectorMA(start, 6, forward, start); VectorMA(start, 4, up, start); } else if ((forward[2] >= -0.8) && (forward[2] < -0.6)) { VectorMA(start, 6.5, forward, start); VectorMA(start, 4.5, up, start); } else if ((forward[2] >= -0.6) && (forward[2] < -0.4)) { VectorMA(start, 8, forward, start); VectorMA(start, 5.5, up, start); } else if ((forward[2] >= -0.4) && (forward[2] < -0.2)) { VectorMA(start, 9.5, forward, start); VectorMA(start, 6, up, start); } else if ((forward[2] >= -0.2) && (forward[2] < 0)) { VectorMA(start, 11, forward, start); VectorMA(start, 6.5, up, start); } else if ((forward[2] >= 0) && (forward[2] < 0.2)) { VectorMA(start, 12, forward, start); VectorMA(start, 7, up, start); } else if ((forward[2] >= 0.2) && (forward[2] < 0.4)) { VectorMA(start, 14, forward, start); VectorMA(start, 6.5, up, start); } else if ((forward[2] >= 0.4) && (forward[2] < 0.6)) { VectorMA(start, 16, forward, start); VectorMA(start, 6, up, start); } else if ((forward[2] >= 0.6) && (forward[2] < 0.8)) { VectorMA(start, 18, forward, start); VectorMA(start, 5, up, start); } else if ((forward[2] >= 0.8) && (forward[2] < 0.85)) { VectorMA(start, 18, forward, start); VectorMA(start, 4, up, start); } else if ((forward[2] >= 0.85) && (forward[2] < 0.9)) { VectorMA(start, 18, forward, start); VectorMA(start, 2.5, up, start); } else if ((forward[2] >= 0.9) && (forward[2] < 0.91)) { VectorMA(start, 18.2, forward, start); VectorMA(start, 2.2, up, start); } else if ((forward[2] >= 0.91) && (forward[2] < 0.92)) { VectorMA(start, 18.4, forward, start); VectorMA(start, 1.9, up, start); } else if ((forward[2] >= 0.92) && (forward[2] < 0.93)) { VectorMA(start, 18.6, forward, start); VectorMA(start, 1.6, up, start); } else if ((forward[2] >= 0.93) && (forward[2] < 0.94)) { VectorMA(start, 18.8, forward, start); VectorMA(start, 1.3, up, start); } else if ((forward[2] >= 0.94) && (forward[2] < 0.95)) { VectorMA(start, 19, forward, start); VectorMA(start, 1, up, start); } else if ((forward[2] >= 0.95) && (forward[2] < 0.96)) { VectorMA(start, 19.2, forward, start); VectorMA(start, 0.7, up, start); } else if ((forward[2] >= 0.96) && (forward[2] < 0.97)) { VectorMA(start, 19.4, forward, start); VectorMA(start, 0.4, up, start); } else if ((forward[2] >= 0.97) && (forward[2] < 0.98)) { VectorMA(start, 19.6, forward, start); VectorMA(start, -0.2, up, start); } else if ((forward[2] >= 0.98) && (forward[2] < 0.99)) { VectorMA(start, 19.8, forward, start); VectorMA(start, -0.6, up, start); } else if ((forward[2] >= 0.99) && (forward[2] <= 1)) { VectorMA(start, 20, forward, start); VectorMA(start, -1, up, start); } VectorCopy(start, shell->s.origin); if (fix == 0) // we want some velocity on those center handed ones fix = 1; if (self->client->curr_weap == SNIPER_NUM) VectorMA(shell->velocity, fix * (-35 + random() * -60), right, shell->velocity); else if (self->client->curr_weap == DUAL_NUM) { if (self->client->pers.hand == LEFT_HANDED) VectorMA(shell->velocity, (toggle == 1 ? 1 : -1) * (35 + random() * 60), right, shell->velocity); else VectorMA(shell->velocity, (toggle == 1 ? -1 : 1) * (35 + random() * 60), right, shell->velocity); } else VectorMA(shell->velocity, fix * (35 + random() * 60), right, shell->velocity); VectorMA(shell->avelocity, 500, right, shell->avelocity); if (self->client->curr_weap == SNIPER_NUM) VectorMA(shell->velocity, 60 + 40, up, shell->velocity); else VectorMA(shell->velocity, 60 + random() * 90, up, shell->velocity); shell->movetype = MOVETYPE_BOUNCE; shell->solid = SOLID_BBOX; if (self->client->curr_weap == M3_NUM) shell->s.modelindex = gi.modelindex("models/weapons/shell/tris2.md2"); else if (self->client->curr_weap == SNIPER_NUM) shell->s.modelindex = gi.modelindex("models/weapons/shell/tris3.md2"); else shell->s.modelindex = gi.modelindex("models/weapons/shell/tris.md2"); r = random(); if (r < 0.1) shell->s.frame = 0; else if (r < 0.2) shell->s.frame = 1; else if (r < 0.3) shell->s.frame = 2; else if (r < 0.5) shell->s.frame = 3; else if (r < 0.6) shell->s.frame = 4; else if (r < 0.7) shell->s.frame = 5; else if (r < 0.8) shell->s.frame = 6; else if (r < 0.9) shell->s.frame = 7; else shell->s.frame = 8; shell->owner = self; shell->touch = ShellTouch; shell->nextthink = level.time + 1.2 - (shells * .05); shell->think = ShellDie; shell->classname = "shell"; gi.linkentity(shell); } /* ================== FindEdictByClassnum ================== */ edict_t *FindEdictByClassnum(char *classname, int classnum) { int i; edict_t *it; for (i = 0; i < globals.num_edicts; i++) { it = &g_edicts[i]; if (!it->classname) continue; if (!it->classnum) continue; if (Q_stricmp(it->classname, classname) == 0) { if (it->classnum == classnum) return it; } } return NULL; } /********* Bulletholes/wall stuff ***********/ void DecalDie(edict_t * self) { G_FreeEdict(self); } void AddDecal(edict_t * self, trace_t * tr) { edict_t *decal, *dec; if (bholelimit->value < 1) return; decal = G_Spawn(); ++decals; if (decals > bholelimit->value) decals = 1; dec = FindEdictByClassnum("decal", decals); if (dec) { dec->nextthink = level.time + .1; } decal->solid = SOLID_NOT; decal->movetype = MOVETYPE_NONE; decal->s.modelindex = gi.modelindex("models/objects/holes/hole1/hole.md2"); VectorCopy(tr->endpos, decal->s.origin); vectoangles(tr->plane.normal, decal->s.angles); decal->owner = self; decal->classnum = decals; decal->touch = NULL; decal->nextthink = level.time + 20; decal->think = DecalDie; decal->classname = "decal"; gi.linkentity(decal); if ((tr->ent) && (0 == Q_stricmp("func_explosive", tr->ent->classname))) { CGF_SFX_AttachDecalToGlass(tr->ent, decal); } } void SplatDie(edict_t * self) { G_FreeEdict(self); } void AddSplat(edict_t * self, vec3_t point, trace_t * tr) { edict_t *splat, *spt; float r; if (splatlimit->value < 1) return; splat = G_Spawn(); ++splats; if (splats > splatlimit->value) splats = 1; spt = FindEdictByClassnum("splat", splats); if (spt) { spt->nextthink = level.time + .1; } splat->solid = SOLID_NOT; splat->movetype = MOVETYPE_NONE; r = random(); if (r > .67) splat->s.modelindex = gi.modelindex("models/objects/splats/splat1/splat.md2"); else if (r > .33) splat->s.modelindex = gi.modelindex("models/objects/splats/splat2/splat.md2"); else splat->s.modelindex = gi.modelindex("models/objects/splats/splat3/splat.md2"); VectorCopy(point, splat->s.origin); vectoangles(tr->plane.normal, splat->s.angles); splat->owner = self; splat->touch = NULL; splat->nextthink = level.time + 25; // - (splats * .05); splat->think = SplatDie; splat->classname = "splat"; splat->classnum = splats; gi.linkentity(splat); if ((tr->ent) && (0 == Q_stricmp("func_explosive", tr->ent->classname))) { CGF_SFX_AttachDecalToGlass(tr->ent, splat); } } /* %-variables for chat msgs */ void GetWeaponName(edict_t * ent, char *buf) { if (ent->client->pers.weapon) { strcpy(buf, ent->client->pers.weapon->pickup_name); return; } strcpy(buf, "No Weapon"); } void GetItemName(edict_t * ent, char *buf) { int i; for(i = 0; i<ITEM_COUNT; i++) { if (INV_AMMO(ent, tnums[i])) { strcpy(buf, GET_ITEM(tnums[i])->pickup_name); return; } } strcpy(buf, "No Item"); } void GetHealth(edict_t * ent, char *buf) { sprintf(buf, "%d", ent->health); } void GetAmmo(edict_t * ent, char *buf) { int ammo; if (ent->client->pers.weapon) { switch (ent->client->curr_weap) { case MK23_NUM: sprintf(buf, "%d rounds (%d extra clips)", ent->client->mk23_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case MP5_NUM: sprintf(buf, "%d rounds (%d extra clips)", ent->client->mp5_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case M4_NUM: sprintf(buf, "%d rounds (%d extra clips)", ent->client->m4_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case M3_NUM: sprintf(buf, "%d shells (%d extra shells)", ent->client->shot_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case HC_NUM: sprintf(buf, "%d shells (%d extra shells)", ent->client->cannon_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case SNIPER_NUM: sprintf(buf, "%d rounds (%d extra rounds)", ent->client->sniper_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case DUAL_NUM: sprintf(buf, "%d rounds (%d extra clips)", ent->client->dual_rds, ent->client->pers.inventory[ent->client->ammo_index]); return; case KNIFE_NUM: ammo = INV_AMMO(ent, KNIFE_NUM); sprintf(buf, "%d kni%s", ammo, (ammo == 1) ? "fe" : "ves"); return; case GRENADE_NUM: ammo = INV_AMMO(ent, GRENADE_NUM); sprintf(buf, "%d grenade%s", ammo, (ammo == 1) ? "" : "s"); return; } } strcpy(buf, "no ammo"); } void GetNearbyTeammates(edict_t * self, char *buf) { unsigned char nearby_teammates[8][16]; int nearby_teammates_num = 0, l; edict_t *ent = NULL; nearby_teammates_num = 0; while ((ent = findradius(ent, self->s.origin, 1500)) != NULL) { if (ent == self || !ent->client || !CanDamage(ent, self) || !OnSameTeam(ent, self)) continue; Q_strncpyz(nearby_teammates[nearby_teammates_num], ent->client->pers.netname, sizeof(nearby_teammates[0])); nearby_teammates_num++; if (nearby_teammates_num >= 8) break; } if (nearby_teammates_num == 0) { strcpy(buf, "nobody"); return; } strcpy(buf, nearby_teammates[0]); for (l = 1; l < nearby_teammates_num; l++) { if (l == nearby_teammates_num - 1) Q_strncatz(buf, " and ", PARSE_BUFSIZE); else Q_strncatz(buf, ", ", PARSE_BUFSIZE); Q_strncatz(buf, nearby_teammates[l], PARSE_BUFSIZE); } }
531
./aq2-tng/source/a_tourney.c
//----------------------------------------------------------------------------- // a_tourney.c // // $Id: a_tourney.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: a_tourney.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:24:40 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" int NextOpponent = 2; int LastOpponent = 0; tourneyindex_t t_eventlist[TOURNEYMAXEVENTS]; int t_eventcount = 0; int _istourneysection (char *atoken) { if (Q_stricmp (atoken, "[START]") == 0) return 1; if (Q_stricmp (atoken, "[END]") == 0) return 2; if (Q_stricmp (atoken, "[SPAWN]") == 0) return 3; return 0; } void _tourneyparseerror (parse_t parse, char *msg, char *atoken) { char buf[512]; if (atoken) Com_sprintf (buf, sizeof(buf), msg, atoken); else Q_strncpyz (buf, msg, sizeof(buf)); gi.dprintf ("Error in " TOURNEYINI " at line %i: %s.\n", parse.lnumber, buf); } void _tourneysetsection (tourneyindex_t * ti, int clevel) { switch (clevel) { case 1: ti->ttime = T_START; break; case 2: ti->ttime = T_END; break; case 3: ti->ttime = T_SPAWN; break; default: ti->ttime = T_NONE; } } //format: set [starttime/startspawn/endtime] at [time] qboolean _tourneyset (parse_t parse, int clevel, int cevent) { char *mytok; int toknr; tourneyindex_t ti; toknr = 0; ti.taction = A_SET; while (toknr < 3 && (mytok = ParseNextToken (&parse, STDSEPERATOR))) { switch (toknr) { case 0: //"starttime" or "roundstart" expected if (Q_stricmp (mytok, "starttime") == 0) { toknr++; _tourneysetsection (&ti, clevel); } else if (Q_stricmp (mytok, "roundstart") == 0) { if (clevel != 1) { _tourneyparseerror (parse, "%s is only supported in section [START]", mytok); toknr = 1000; } else { ti.ttime = T_RSTART; toknr++; } } else { _tourneyparseerror (parse, "not supported set option %s", mytok); toknr = 1000; } break; case 1: if (Q_stricmp (mytok, "at") == 0) toknr++; else { _tourneyparseerror (parse, "\"at\" expected, %s found", mytok); toknr = 1000; } break; case 2: ti.attime = atoi (mytok); toknr++; break; } } if (toknr == 3) { //anything was ok memcpy (&t_eventlist[cevent], &ti, sizeof (tourneyindex_t)); return true; } if (toknr < 3) { _tourneyparseerror (parse, "unexpected end of file in SET", NULL); } return false; } //format: play [sound] at [time] qboolean _tourneyplay (parse_t parse, int clevel, int cevent) { char *mytok; int toknr; tourneyindex_t ti; toknr = 0; ti.taction = A_PLAY; _tourneysetsection (&ti, clevel); while (toknr < 3 && (mytok = ParseNextToken (&parse, STDSEPERATOR))) { switch (toknr) { case 0: strcpy (ti.info, mytok); toknr++; break; case 1: if (Q_stricmp (mytok, "at") == 0) toknr++; else { _tourneyparseerror (parse, "\"at\" expected, %s found", mytok); toknr = 1000; } break; case 2: ti.attime = atoi (mytok); toknr++; break; } } if (toknr == 3) { //anything was ok memcpy (&t_eventlist[cevent], &ti, sizeof (tourneyindex_t)); return true; } if (toknr < 3) { _tourneyparseerror (parse, "unexpected end of file in PLAY", NULL); } return false; } //format: print ["text"] at [time] qboolean _tourneyprint (parse_t parse, int clevel, int cevent) { char *mytok; int toknr; tourneyindex_t ti; toknr = 0; ti.taction = A_PRINT; _tourneysetsection (&ti, clevel); // mytok = ParseNextToken (&parse, "\""); strcpy (ti.info, mytok); strcat (ti.info, "\n"); while (toknr < 2 && (mytok = ParseNextToken (&parse, STDSEPERATOR))) { switch (toknr) { case 0: if (Q_stricmp (mytok, "at") == 0) toknr++; else { _tourneyparseerror (parse, "\"at\" expected, %s found", mytok); toknr = 1000; } break; case 1: ti.attime = atoi (mytok); toknr++; break; } } if (toknr == 2) { //anything was ok memcpy (&t_eventlist[cevent], &ti, sizeof (tourneyindex_t)); return true; } if (toknr < 2) { _tourneyparseerror (parse, "unexpected end of file in PRINT", NULL); } return false; } // void TourneyTimeEvent (TOURNEYTIME ttime, int attime) { int i; for (i = 0; i < t_eventcount; i++) { if (t_eventlist[i].ttime == ttime && t_eventlist[i].attime == attime) { if (t_eventlist[i].taction == A_PLAY) { gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex (t_eventlist[i].info), 1.0, ATTN_NONE, 0.0); } else if (t_eventlist[i].taction == A_PRINT) { CenterPrintAll (t_eventlist[i].info); } /* else { if (t_eventlist[i].taction == A_SET) } */ } } } // int TourneySetTime (TOURNEYTIME ttime) { int i, j; j = -1; for (i = 0; i < t_eventcount; i++) { if (t_eventlist[i].ttime == ttime && t_eventlist[i].taction == A_SET) { j = t_eventlist[i].attime; break; } } if (j <= 0) j = 71; return j; } void TourneyReadIni (void) { parse_t parse; int clevel; char *mytok; qboolean inevent; t_eventcount = 0; clevel = 0; inevent = false; if (ParseStartFile (GAMEVERSION "/" TOURNEYINI, &parse) == true) { while ((mytok = ParseNextToken (&parse, STDSEPERATOR))) { switch (clevel) { case 0: //we're not in any section clevel = _istourneysection (mytok); if (!clevel) _tourneyparseerror (parse, "unknown command %s", mytok); break; default: // we're are in any other section if (Q_stricmp (mytok, "set") == 0) { if (_tourneyset (parse, clevel, t_eventcount) == true) t_eventcount++; } else if (Q_stricmp (mytok, "play") == 0) { if (_tourneyplay (parse, clevel, t_eventcount) == true) t_eventcount++; } else if (Q_stricmp (mytok, "print") == 0) { if (_tourneyprint (parse, clevel, t_eventcount) == true) t_eventcount++; } else if (_istourneysection (mytok)) clevel = _istourneysection (mytok); else _tourneyparseerror (parse, "unknown command %s", mytok); } } ParseEndFile (&parse); } gi.dprintf ("%i tourney events...\n", t_eventcount); } //Inits TourneyMode void TourneyInit (void) { NextOpponent = 2; LastOpponent = 0; TourneyReadIni (); if (use_tourney->value) gi.dprintf ("Tourney mode enabled.\n"); } //gives a new connected player a new Tourney number. //The first Tourney number is 1. void TourneyNewPlayer (edict_t * player) { player->client->resp.tourneynumber = ++LastOpponent; // gi.cprintf(player, PRINT_HIGH,"Player %s, number %i\n", player->client->pers.netname, // player->client->resp.tourneynumber); // gi.dprintf("Player %s, number %i\n", player->client->pers.netname, // player->client->resp.tourneynumber); } //returns the player with Tourney number "number". //if "number" is not found, it returns NULL edict_t * TourneyFindPlayer (int number) { edict_t *player; int i; for (i = 1; i <= maxclients->value; i++) { player = g_edicts + i; if (player->inuse) { // gi.dprintf(">Player %s, number %i\n", player->client->pers.netname, // player->client->resp.tourneynumber); if (player->client->resp.tourneynumber == number) return (player); } } gi.dprintf ("Tourney Error: Player not found (%i)\n", number); return NULL; } //removes number of player void TourneyRemovePlayer (edict_t * player) { edict_t *dummy; int i; LastOpponent--; for (i = 1; i <= maxclients->value; i++) { dummy = g_edicts + i; if (dummy->inuse) { if (dummy->client->resp.tourneynumber > player->client->resp.tourneynumber) dummy->client->resp.tourneynumber--; } } if (NextOpponent == player->client->resp.tourneynumber) NextOpponent--; } //sets winner to #1 and determs next opponent void TourneyWinner (edict_t * player) { edict_t *oldnumberone, *dummy; dummy = TourneyFindPlayer (1); if (dummy) dummy->client->resp.team = NOTEAM; dummy = TourneyFindPlayer (NextOpponent); if (dummy) dummy->client->resp.team = NOTEAM; if (player->client->resp.tourneynumber != 1) { //new winner, so we have to cycle the numbers oldnumberone = TourneyFindPlayer (1); oldnumberone->client->resp.tourneynumber = player->client->resp.tourneynumber; player->client->resp.tourneynumber = 1; } NextOpponent++; if (NextOpponent > LastOpponent || NextOpponent < 2) NextOpponent = 2; } //sets new round, returns wether enough players are available //or not qboolean TourneyNewRound (void) { char buf[128]; edict_t *dummy; // gi.bprintf(PRINT_HIGH,"LastOpponent: %i\n", LastOpponent); if (LastOpponent < 2) return (false); strcpy (buf, "Next game: "); dummy = TourneyFindPlayer (1); if (dummy) { dummy->client->resp.team = TEAM1; strcat (buf, dummy->client->pers.netname); } else { gi.dprintf ("Tourney Error: cannot find player #1!\n"); strcat (buf, "(unknown)"); } strcat (buf, " vs "); dummy = TourneyFindPlayer (NextOpponent); if (dummy) { dummy->client->resp.team = TEAM2; strcat (buf, dummy->client->pers.netname); } else { gi.dprintf ("Tourney Error: cannot find NextOpponent (%i)!\n", NextOpponent); strcat (buf, "(unknown)"); } CenterPrintAll (buf); return (true); }
532
./aq2-tng/source/g_weapon.c
//----------------------------------------------------------------------------- // g_weapon.c // // $Id: g_weapon.c,v 1.15 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: g_weapon.c,v $ // Revision 1.15 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.14 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.13 2002/02/19 10:28:43 freud // Added to %D hit in the kevlar vest and kevlar helmet, also body for handcannon // and shotgun. // // Revision 1.12 2002/02/18 18:25:51 ra // Bumped version to 2.6, fixed ctf falling and kicking of players in ctf // uvtime // // Revision 1.11 2002/02/18 13:55:35 freud // Added last damaged players %P // // Revision 1.10 2002/02/01 17:49:56 freud // Heavy changes in stats code. Removed lots of variables and replaced them // with int arrays of MODs. This cleaned tng_stats.c up a whole lots and // everything looks well, might need more testing. // // Revision 1.9 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.8 2001/12/23 16:30:50 ra // 2.5 ready. New stats from Freud. HC and shotgun gibbing seperated. // // Revision 1.7 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.6 2001/08/18 01:28:06 deathwatch // Fixed some stats stuff, added darkmatch + day_cycle, cleaned up several files, restructured ClientCommand // // Revision 1.5 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.4 2001/08/06 03:00:49 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.3 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.2.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.2.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.2 2001/05/11 16:07:26 mort // Various CTF bits and pieces... // // Revision 1.1.1.1 2001/05/06 17:30:24 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" #include "a_game.h" //zucc for KickDoor void knife_touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf); void Zylon_Grenade (edict_t * ent); void setFFState (edict_t * ent); //FIREBLADE qboolean ap_already_hit[1000]; // 1000 = a number much larger than the possible max # of clients int *took_damage; //FB 6/2/99, to keep track of shotgun damage //FIREBLADE /* ================= check_dodge This is a support routine used when a client is firing a non-instant attack weapon. It checks to see if a monster's dodge function should be called. ================= */ static void check_dodge (edict_t * self, vec3_t start, vec3_t dir, int speed) { vec3_t end; vec3_t v; trace_t tr; float eta; // easy mode only ducks one quarter the time if (skill->value == 0) { if (random () > 0.25) return; } VectorMA (start, 8192, dir, end); PRETRACE (); tr = gi.trace (start, NULL, NULL, end, self, MASK_SHOT); POSTTRACE (); if ((tr.ent) && (tr.ent->svflags & SVF_MONSTER) && (tr.ent->health > 0) && (tr.ent->monsterinfo.dodge) && infront (tr.ent, self)) { VectorSubtract (tr.endpos, start, v); eta = (VectorLength (v) - tr.ent->maxs[0]) / speed; tr.ent->monsterinfo.dodge (tr.ent, self, eta); } } /* zucc - bulletholes for testing spread patterns */ void BulletHoleThink (edict_t * self) { G_FreeEdict (self); } void SpawnHole (trace_t * tr, vec3_t dir) { vec3_t origin; edict_t *lss; lss = G_Spawn (); lss->movetype = MOVETYPE_NOCLIP; lss->solid = SOLID_TRIGGER; lss->classname = "bhole"; //lss->s.modelindex = gi.modelindex ("models/weapons/g_m4/tris.md2" ); //lss->s.modelindex = gi.modelindex ("models/objects/holes/hole1/tris.md2" ); // bhole model doesn't want to show up, so be it lss->s.modelindex = gi.modelindex ("sprites/lsight.sp2"); lss->s.renderfx = RF_GLOW; lss->gravity = 0; lss->think = BulletHoleThink; lss->nextthink = level.time + 1000; vectoangles (tr->plane.normal, lss->s.angles); VectorNormalize (dir); VectorMA (tr->endpos, 0, dir, origin); VectorCopy (origin, lss->s.origin); gi.linkentity (lss); } /* ================= fire_hit Used for all impact (hit/punch/slash) attacks ================= */ qboolean fire_hit (edict_t * self, vec3_t aim, int damage, int kick) { trace_t tr; vec3_t forward, right, up; vec3_t v; vec3_t point; float range; vec3_t dir; //see if enemy is in range VectorSubtract (self->enemy->s.origin, self->s.origin, dir); range = VectorLength (dir); if (range > aim[0]) return false; if (aim[1] > self->mins[0] && aim[1] < self->maxs[0]) { // the hit is straight on so back the range up to the edge of their bbox range -= self->enemy->maxs[0]; } else { // this is a side hit so adjust the "right" value out to the edge of their bbox if (aim[1] < 0) aim[1] = self->enemy->mins[0]; else aim[1] = self->enemy->maxs[0]; } VectorMA (self->s.origin, range, dir, point); PRETRACE (); tr = gi.trace (self->s.origin, NULL, NULL, point, self, MASK_SHOT); POSTTRACE (); if (tr.fraction < 1) { if (!tr.ent->takedamage) return false; // if it will hit any client/monster then hit the one we wanted to hit if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client)) tr.ent = self->enemy; } AngleVectors (self->s.angles, forward, right, up); VectorMA (self->s.origin, range, forward, point); VectorMA (point, aim[1], right, point); VectorMA (point, aim[2], up, point); VectorSubtract (point, self->enemy->s.origin, dir); setFFState (self); // do the damage T_Damage (tr.ent, self, self, dir, point, vec3_origin, damage, kick / 2, DAMAGE_NO_KNOCKBACK, MOD_HIT); if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client)) return false; // do our special form of knockback here VectorMA (self->enemy->absmin, 0.5, self->enemy->size, v); VectorSubtract (v, point, v); VectorNormalize (v); VectorMA (self->enemy->velocity, kick, v, self->enemy->velocity); if (self->enemy->velocity[2] > 0) self->enemy->groundentity = NULL; return true; } /* ================= fire_lead This is an internal support routine used for bullet/pellet based weapons. ================= */ static void fire_lead (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int te_impact, int hspread, int vspread, int mod) { trace_t tr; vec3_t dir; vec3_t forward, right, up; vec3_t end; float r; float u; vec3_t water_start; qboolean water = false; int content_mask = MASK_SHOT | MASK_WATER; PRETRACE (); tr = gi.trace (self->s.origin, NULL, NULL, start, self, MASK_SHOT); POSTTRACE (); if (!(tr.fraction < 1.0)) { vectoangles (aimdir, dir); AngleVectors (dir, forward, right, up); r = crandom () * hspread; u = crandom () * vspread; VectorMA (start, 8192, forward, end); VectorMA (end, r, right, end); VectorMA (end, u, up, end); if (gi.pointcontents (start) & MASK_WATER) { water = true; VectorCopy (start, water_start); content_mask &= ~MASK_WATER; } PRETRACE (); tr = gi.trace (start, NULL, NULL, end, self, content_mask); POSTTRACE (); // glass fx // catch case of firing thru one or breakable glasses while ((tr.fraction < 1.0) && (tr.surface->flags & (SURF_TRANS33 | SURF_TRANS66)) && (tr.ent) && (0 == Q_stricmp (tr.ent->classname, "func_explosive"))) { // break glass CGF_SFX_ShootBreakableGlass (tr.ent, self, &tr, mod); // continue trace from current endpos to start PRETRACE (); tr = gi.trace (tr.endpos, NULL, NULL, end, tr.ent, content_mask); POSTTRACE (); } // --- // see if we hit water if (tr.contents & MASK_WATER) { int color; water = true; VectorCopy (tr.endpos, water_start); if (!VectorCompare (start, tr.endpos)) { if (tr.contents & CONTENTS_WATER) { if (strcmp (tr.surface->name, "*brwater") == 0) color = SPLASH_BROWN_WATER; else color = SPLASH_BLUE_WATER; } else if (tr.contents & CONTENTS_SLIME) color = SPLASH_SLIME; else if (tr.contents & CONTENTS_LAVA) color = SPLASH_LAVA; else color = SPLASH_UNKNOWN; if (color != SPLASH_UNKNOWN) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPLASH); gi.WriteByte (8); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.WriteByte (color); gi.multicast (tr.endpos, MULTICAST_PVS); } // change bullet's course when it enters water VectorSubtract (end, start, dir); vectoangles (dir, dir); AngleVectors (dir, forward, right, up); r = crandom () * hspread * 2; u = crandom () * vspread * 2; VectorMA (water_start, 8192, forward, end); VectorMA (end, r, right, end); VectorMA (end, u, up, end); } // re-trace ignoring water this time PRETRACE (); tr = gi.trace (water_start, NULL, NULL, end, self, MASK_SHOT); POSTTRACE (); } } // send gun puff / flash if (!((tr.surface) && (tr.surface->flags & SURF_SKY))) { if (tr.fraction < 1.0) { if (tr.ent->takedamage) { T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, DAMAGE_BULLET, mod); } else { if (mod != MOD_M3 && mod != MOD_HC) { AddDecal (self, &tr); } //zucc remove spawnhole for real release // SpawnHole( &tr, dir ); if (strncmp (tr.surface->name, "sky", 3) != 0) { gi.WriteByte (svc_temp_entity); gi.WriteByte (te_impact); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.multicast (tr.endpos, MULTICAST_PVS); if (self->client) PlayerNoise (self, tr.endpos, PNOISE_IMPACT); } } } } // if went through water, determine where the end and make a bubble trail if (water) { vec3_t pos; VectorSubtract (tr.endpos, water_start, dir); VectorNormalize (dir); VectorMA (tr.endpos, -2, dir, pos); if (gi.pointcontents (pos) & MASK_WATER) VectorCopy (pos, tr.endpos); else { PRETRACE (); tr = gi.trace (pos, NULL, NULL, water_start, tr.ent, MASK_WATER); POSTTRACE (); } VectorAdd (water_start, tr.endpos, pos); VectorScale (pos, 0.5, pos); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BUBBLETRAIL); gi.WritePosition (water_start); gi.WritePosition (tr.endpos); gi.multicast (pos, MULTICAST_PVS); } } /* ================= fire_bullet Fires a single round. Used for machinegun and chaingun. Would be fine for pistols, rifles, etc.... ================= */ void fire_bullet (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int mod) { setFFState (self); fire_lead (self, start, aimdir, damage, kick, TE_GUNSHOT, hspread, vspread, mod); } // zucc fire_load_ap for rounds that pass through soft targets and keep going static void fire_lead_ap (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int te_impact, int hspread, int vspread, int mod) { trace_t tr; vec3_t dir; vec3_t forward, right, up; vec3_t end; float r; float u; vec3_t water_start; qboolean water = false; int content_mask = MASK_SHOT | MASK_WATER; vec3_t from; edict_t *ignore; //FIREBLADE memset (ap_already_hit, 0, game.maxclients * sizeof (qboolean)); //FIREBLADE // setup stopAP = 0; vectoangles (aimdir, dir); AngleVectors (dir, forward, right, up); r = crandom () * hspread; u = crandom () * vspread; VectorMA (start, 8192, forward, end); VectorMA (end, r, right, end); VectorMA (end, u, up, end); VectorCopy (start, from); if (gi.pointcontents (start) & MASK_WATER) { water = true; VectorCopy (start, water_start); content_mask &= ~MASK_WATER; } ignore = self; // PRETRACE(); // tr = gi.trace (self->s.origin, NULL, NULL, start, self, MASK_SHOT); // POSTTRACE(); while (ignore) //if (!(tr.fraction < 1.0)) { PRETRACE (); //tr = gi.trace (from, NULL, NULL, end, ignore, mask); tr = gi.trace (from, NULL, NULL, end, ignore, content_mask); POSTTRACE (); // glass fx // catch case of firing thru one or breakable glasses while ((tr.fraction < 1.0) && (tr.surface->flags & (SURF_TRANS33 | SURF_TRANS66)) && (tr.ent) && (0 == Q_stricmp (tr.ent->classname, "func_explosive"))) { // break glass CGF_SFX_ShootBreakableGlass (tr.ent, self, &tr, mod); // continue trace from current endpos to start PRETRACE (); tr = gi.trace (tr.endpos, NULL, NULL, end, tr.ent, content_mask); POSTTRACE (); } // --- // see if we hit water if (tr.contents & MASK_WATER) { int color; water = true; VectorCopy (tr.endpos, water_start); if (!VectorCompare (from, tr.endpos)) { if (tr.contents & CONTENTS_WATER) { if (strcmp (tr.surface->name, "*brwater") == 0) color = SPLASH_BROWN_WATER; else color = SPLASH_BLUE_WATER; } else if (tr.contents & CONTENTS_SLIME) color = SPLASH_SLIME; else if (tr.contents & CONTENTS_LAVA) color = SPLASH_LAVA; else color = SPLASH_UNKNOWN; if (color != SPLASH_UNKNOWN) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPLASH); gi.WriteByte (8); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.WriteByte (color); gi.multicast (tr.endpos, MULTICAST_PVS); } // change bullet's course when it enters water VectorSubtract (end, from, dir); vectoangles (dir, dir); AngleVectors (dir, forward, right, up); r = crandom () * hspread * 2; u = crandom () * vspread * 2; VectorMA (water_start, 8192, forward, end); VectorMA (end, r, right, end); VectorMA (end, u, up, end); } // re-trace ignoring water this time PRETRACE (); tr = gi.trace (water_start, NULL, NULL, end, ignore, MASK_SHOT); POSTTRACE (); } // send gun puff / flash ignore = NULL; if (!((tr.surface) && (tr.surface->flags & SURF_SKY))) { if (tr.fraction < 1.0) { if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client)) { ignore = tr.ent; VectorCopy (tr.endpos, from); //FIREBLADE // Advance the "from" point a few units // towards "end" here if (tr.ent->client) { vec3_t tempv; vec3_t out; if (ap_already_hit[tr.ent - g_edicts - 1]) { VectorSubtract (end, from, tempv); VectorNormalize (tempv); VectorScale (tempv, 8, out); VectorAdd (out, from, from); continue; } ap_already_hit[tr.ent - g_edicts - 1] = true; } //FIREBLADE } if ((tr.ent != self) && (tr.ent->takedamage)) { T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, 0, mod); if (stopAP) // the AP round hit something that would stop it (kevlar) ignore = NULL; } else if (tr.ent != self && !water) { //zucc remove spawnhole for real release // SpawnHole( &tr, dir ); if (strncmp (tr.surface->name, "sky", 3) != 0) { AddDecal (self, &tr); gi.WriteByte (svc_temp_entity); gi.WriteByte (te_impact); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.multicast (tr.endpos, MULTICAST_PVS); if (self->client) PlayerNoise (self, tr.endpos, PNOISE_IMPACT); } } } } } // if went through water, determine where the end and make a bubble trail if (water) { vec3_t pos; VectorSubtract (tr.endpos, water_start, dir); VectorNormalize (dir); VectorMA (tr.endpos, -2, dir, pos); if (gi.pointcontents (pos) & MASK_WATER) VectorCopy (pos, tr.endpos); else { PRETRACE (); tr = gi.trace (pos, NULL, NULL, water_start, tr.ent, MASK_WATER); POSTTRACE (); } VectorAdd (water_start, tr.endpos, pos); VectorScale (pos, 0.5, pos); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BUBBLETRAIL); gi.WritePosition (water_start); gi.WritePosition (tr.endpos); gi.multicast (pos, MULTICAST_PVS); } } // zucc - for the M4 void fire_bullet_sparks (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int mod) { setFFState (self); fire_lead_ap (self, start, aimdir, damage, kick, TE_BULLET_SPARKS, hspread, vspread, mod); } // zucc - for sniper void fire_bullet_sniper (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int mod) { setFFState (self); fire_lead_ap (self, start, aimdir, damage, kick, TE_GUNSHOT, hspread, vspread, mod); } /* * Init and ProduceShotgunDamageReport */ void InitShotgunDamageReport () { memset (took_damage, 0, game.maxclients * sizeof (int)); } void ProduceShotgunDamageReport (edict_t * self) { int l; int total = 0, total_to_print, printed = 0; char *textbuf; //FB 6/2/99 - shotgun/handcannon damage notification for (l = 1; l <= game.maxclients; l++) { if (took_damage[l - 1]) total++; } if (!total) return; if (total > 10) total_to_print = 10; else total_to_print = total; //256 is enough, its limited to 10 nicks textbuf = self->client->resp.last_damaged_players; *textbuf = '\0'; for (l = 1; l <= game.maxclients; l++) { if (took_damage[l - 1]) { if (printed == total_to_print - 1) { if (total_to_print == 2) strcat(textbuf, " and "); else if (total_to_print != 1) strcat(textbuf, ", and "); } else if (printed) { strcat (textbuf, ", "); } strcat (textbuf, g_edicts[l].client->pers.netname); printed++; } if (printed == total_to_print) break; } gi.cprintf (self, PRINT_HIGH, "You hit %s\n", textbuf); self->client->resp.last_damaged_part = LOC_NO; // TNG Stats if (!teamplay->value || team_round_going || stats_afterround->value) { self->client->resp.stats_shots_h += total; if (self->client->curr_weap == M3_NUM) self->client->resp.stats_hits[MOD_M3] += total; else if (self->client->curr_weap == HC_NUM) self->client->resp.stats_hits[MOD_HC] += total; /* if (self->client->curr_weap == M3_NUM) self->client->resp.stats_shotgun_shots_h += total_to_print; if (self->client->curr_weap == HC_NUM) self->client->resp.stats_hc_shots_h += total_to_print; */ } /* self->client->resp.stats_shots_h += total_to_print; if (self->client->curr_weap == M3_NUM) self->client->resp.stats_shotgun_shots_h += total_to_print; if (self->client->curr_weap == HC_NUM) self->client->resp.stats_hc_shots_h += total_to_print; if (mod == MOD_M3) self->client->resp.stats_shotgun_shots_h += total_to_print; if (mod == MOD_HC) self->client->resp.stats_hc_shots_h += total_to_print; */ //FB 6/2/99 } /* ================= fire_shotgun Shoots shotgun pellets. Used by shotgun and super shotgun. ================= */ void fire_shotgun (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int count, int mod) { int i; for (i = 0; i < count; i++) fire_lead (self, start, aimdir, damage, kick, TE_SHOTGUN, hspread, vspread, mod); } /* ================= fire_blaster Fires a single blaster bolt. Used by the blaster and hyperb blaster. ================= */ void blaster_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { int mod; if (other == self->owner) return; if (surf && (surf->flags & SURF_SKY)) { G_FreeEdict (self); return; } if (self->owner->client) PlayerNoise (self->owner, self->s.origin, PNOISE_IMPACT); if (other->takedamage) { if (self->spawnflags & 1) mod = MOD_HYPERBLASTER; else mod = MOD_BLASTER; T_Damage (other, self, self->owner, self->velocity, self->s.origin, plane->normal, self->dmg, 1, DAMAGE_ENERGY, mod); } else { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BLASTER); gi.WritePosition (self->s.origin); if (!plane) gi.WriteDir (vec3_origin); else gi.WriteDir (plane->normal); gi.multicast (self->s.origin, MULTICAST_PVS); } G_FreeEdict (self); } //SLIC2 changed argument name hyper to hyperb void fire_blaster (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed, int effect, qboolean hyperb) { edict_t *bolt; trace_t tr; VectorNormalize (dir); bolt = G_Spawn (); // 3.20 ANTI-LAG FIX, just in case we end up using this code for something... -FB bolt->svflags = SVF_DEADMONSTER; // ^^^ VectorCopy (start, bolt->s.origin); VectorCopy (start, bolt->s.old_origin); vectoangles (dir, bolt->s.angles); VectorScale (dir, speed, bolt->velocity); bolt->movetype = MOVETYPE_FLYMISSILE; bolt->clipmask = MASK_SHOT; bolt->solid = SOLID_BBOX; bolt->s.effects |= effect; VectorClear (bolt->mins); VectorClear (bolt->maxs); bolt->s.modelindex = gi.modelindex ("models/objects/laser/tris.md2"); bolt->s.sound = gi.soundindex ("misc/lasfly.wav"); bolt->owner = self; bolt->touch = blaster_touch; bolt->nextthink = level.time + 2; bolt->think = G_FreeEdict; bolt->dmg = damage; bolt->classname = "bolt"; if (hyperb) bolt->spawnflags = 1; gi.linkentity (bolt); if (self->client) check_dodge (self, bolt->s.origin, dir, speed); PRETRACE (); tr = gi.trace (self->s.origin, NULL, NULL, bolt->s.origin, bolt, MASK_SHOT); POSTTRACE (); if (tr.fraction < 1.0) { VectorMA (bolt->s.origin, -10, dir, bolt->s.origin); bolt->touch (bolt, tr.ent, NULL, NULL); } } qboolean G_EntExists (edict_t * ent) { return ((ent) && (ent->client)); //(ent->inuse)); } /* ================= fire_grenade ================= */ static void Grenade_Explode (edict_t * ent) { vec3_t origin; int mod; if (ent->owner->client) PlayerNoise (ent->owner, ent->s.origin, PNOISE_IMPACT); //FIXME: if we are onground then raise our Z just a bit since we are a point? if (ent->enemy) { float points; vec3_t v; vec3_t dir; VectorAdd (ent->enemy->mins, ent->enemy->maxs, v); VectorMA (ent->enemy->s.origin, 0.5, v, v); VectorSubtract (ent->s.origin, v, v); points = ent->dmg - 0.5 * VectorLength (v); VectorSubtract (ent->enemy->s.origin, ent->s.origin, dir); if (ent->spawnflags & 1) mod = MOD_HANDGRENADE; else mod = MOD_GRENADE; T_Damage (ent->enemy, ent, ent->owner, dir, ent->s.origin, vec3_origin, (int) points, (int) points, DAMAGE_RADIUS, mod); } if (ent->spawnflags & 2) mod = MOD_HELD_GRENADE; else if (ent->spawnflags & 1) mod = MOD_HG_SPLASH; else mod = MOD_G_SPLASH; T_RadiusDamage (ent, ent->owner, ent->dmg, ent->enemy, ent->dmg_radius, mod); VectorMA (ent->s.origin, -0.02, ent->velocity, origin); gi.WriteByte (svc_temp_entity); if (ent->waterlevel) { if (ent->groundentity) gi.WriteByte (TE_GRENADE_EXPLOSION_WATER); else gi.WriteByte (TE_ROCKET_EXPLOSION_WATER); } else { if (ent->groundentity) gi.WriteByte (TE_GRENADE_EXPLOSION); else gi.WriteByte (TE_ROCKET_EXPLOSION); } gi.WritePosition (origin); gi.multicast (ent->s.origin, MULTICAST_PHS); G_FreeEdict (ent); } static void Grenade_Touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other == ent->owner) return; if (surf && (surf->flags & SURF_SKY)) { G_FreeEdict (ent); return; } if (!other->takedamage) { /*FIREBLADE if (ent->spawnflags & 1) { if (random() > 0.5) gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb1a.wav"), 1, ATTN_NORM, 0); else gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb2a.wav"), 1, ATTN_NORM, 0); } else FIREBLADE*/ { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/grenlb1b.wav"), 1, ATTN_NORM, 0); } return; } // zucc not needed since grenades don't blow up on contact //ent->enemy = other; //Grenade_Explode (ent); } void fire_grenade (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int speed, float timer, float damage_radius) { edict_t *grenade; vec3_t dir; vec3_t forward, right, up; vectoangles (aimdir, dir); AngleVectors (dir, forward, right, up); grenade = G_Spawn (); VectorCopy (start, grenade->s.origin); VectorScale (aimdir, speed, grenade->velocity); VectorMA (grenade->velocity, 200 + crandom () * 10.0, up, grenade->velocity); VectorMA (grenade->velocity, crandom () * 10.0, right, grenade->velocity); VectorSet (grenade->avelocity, 300, 300, 300); grenade->movetype = MOVETYPE_BOUNCE; grenade->clipmask = MASK_SHOT; grenade->solid = SOLID_BBOX; grenade->s.effects |= EF_GRENADE; VectorClear (grenade->mins); VectorClear (grenade->maxs); grenade->s.modelindex = gi.modelindex ("models/objects/grenade/tris.md2"); grenade->owner = self; grenade->touch = Grenade_Touch; grenade->nextthink = level.time + timer; grenade->think = Grenade_Explode; grenade->dmg = damage; grenade->dmg_radius = damage_radius; grenade->classname = "grenade"; gi.linkentity (grenade); } void fire_grenade2 (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int speed, float timer, float damage_radius, qboolean held) { edict_t *grenade; vec3_t dir; vec3_t forward, right, up; vectoangles (aimdir, dir); AngleVectors (dir, forward, right, up); grenade = G_Spawn (); VectorCopy (start, grenade->s.origin); VectorScale (aimdir, speed, grenade->velocity); VectorMA (grenade->velocity, 200 + crandom () * 10.0, up, grenade->velocity); VectorMA (grenade->velocity, crandom () * 10.0, right, grenade->velocity); VectorSet (grenade->avelocity, 300, 300, 300); grenade->movetype = MOVETYPE_BOUNCE; grenade->clipmask = MASK_SHOT; grenade->solid = SOLID_BBOX; //grenade->s.effects |= EF_GRENADE; VectorClear (grenade->mins); VectorClear (grenade->maxs); grenade->s.modelindex = gi.modelindex ("models/objects/grenade2/tris.md2"); grenade->owner = self; grenade->touch = Grenade_Touch; grenade->nextthink = level.time + timer; grenade->think = Grenade_Explode; grenade->dmg = damage; grenade->dmg_radius = damage_radius; grenade->classname = "hgrenade"; if (held) grenade->spawnflags = 3; else grenade->spawnflags = 1; //grenade->s.sound = gi.soundindex("weapons/hgrenc1b.wav"); if (timer <= 0.0) Grenade_Explode (grenade); else { gi.sound (self, CHAN_WEAPON, gi.soundindex ("weapons/hgrent1a.wav"), 1, ATTN_NORM, 0); gi.linkentity (grenade); } } /* ================= fire_rocket ================= */ void rocket_touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { vec3_t origin; int n; if (other == ent->owner) return; if (surf && (surf->flags & SURF_SKY)) { G_FreeEdict (ent); return; } if (ent->owner->client) PlayerNoise (ent->owner, ent->s.origin, PNOISE_IMPACT); // calculate position for the explosion entity VectorMA (ent->s.origin, -0.02, ent->velocity, origin); if (other->takedamage) { T_Damage (other, ent, ent->owner, ent->velocity, ent->s.origin, plane->normal, ent->dmg, 0, 0, MOD_ROCKET); } else { // don't throw any debris in net games if (!deathmatch->value && !coop->value) { if ((surf) && !(surf-> flags & (SURF_WARP | SURF_TRANS33 | SURF_TRANS66 | SURF_FLOWING))) { n = rand () % 5; while (n--) ThrowDebris (ent, "models/objects/debris2/tris.md2", 2, ent->s.origin); } } } T_RadiusDamage (ent, ent->owner, ent->radius_dmg, other, ent->dmg_radius, MOD_R_SPLASH); gi.WriteByte (svc_temp_entity); if (ent->waterlevel) gi.WriteByte (TE_ROCKET_EXPLOSION_WATER); else gi.WriteByte (TE_ROCKET_EXPLOSION); gi.WritePosition (origin); gi.multicast (ent->s.origin, MULTICAST_PHS); G_FreeEdict (ent); } void fire_rocket (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed, float damage_radius, int radius_damage) { edict_t *rocket; rocket = G_Spawn (); VectorCopy (start, rocket->s.origin); VectorCopy (dir, rocket->movedir); vectoangles (dir, rocket->s.angles); VectorScale (dir, speed, rocket->velocity); rocket->movetype = MOVETYPE_FLYMISSILE; rocket->clipmask = MASK_SHOT; rocket->solid = SOLID_BBOX; rocket->s.effects |= EF_ROCKET; VectorClear (rocket->mins); VectorClear (rocket->maxs); rocket->s.modelindex = gi.modelindex ("models/objects/rocket/tris.md2"); rocket->owner = self; rocket->touch = rocket_touch; rocket->nextthink = level.time + 8000 / speed; rocket->think = G_FreeEdict; rocket->dmg = damage; rocket->radius_dmg = radius_damage; rocket->dmg_radius = damage_radius; rocket->s.sound = gi.soundindex ("weapons/rockfly.wav"); rocket->classname = "rocket"; if (self->client) check_dodge (self, rocket->s.origin, dir, speed); gi.linkentity (rocket); } /* ================= fire_rail ================= */ void fire_rail (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick) { vec3_t from; vec3_t end; trace_t tr; edict_t *ignore; int mask; qboolean water; VectorMA (start, 8192, aimdir, end); VectorCopy (start, from); ignore = self; water = false; mask = MASK_SHOT | CONTENTS_SLIME | CONTENTS_LAVA; while (ignore) { PRETRACE (); tr = gi.trace (from, NULL, NULL, end, ignore, mask); POSTTRACE (); if (tr.contents & (CONTENTS_SLIME | CONTENTS_LAVA)) { mask &= ~(CONTENTS_SLIME | CONTENTS_LAVA); water = true; } else { // FROM 3.20, just in case we ever end up using this code for something... -FB //ZOID--added so rail goes through SOLID_BBOX entities (gibs, etc) if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client) || (tr.ent->solid == SOLID_BBOX)) // ^^^ ignore = tr.ent; else ignore = NULL; if ((tr.ent != self) && (tr.ent->takedamage)) T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_RAILGUN); } VectorCopy (tr.endpos, from); } // send gun puff / flash gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_RAILTRAIL); gi.WritePosition (start); gi.WritePosition (tr.endpos); gi.multicast (self->s.origin, MULTICAST_PHS); // gi.multicast (start, MULTICAST_PHS); if (water) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_RAILTRAIL); gi.WritePosition (start); gi.WritePosition (tr.endpos); gi.multicast (tr.endpos, MULTICAST_PHS); } if (self->client) PlayerNoise (self, tr.endpos, PNOISE_IMPACT); } /* ================= fire_bfg ================= */ void bfg_explode (edict_t * self) { edict_t *ent; float points; vec3_t v; float dist; if (self->s.frame == 0) { // the BFG effect ent = NULL; while ((ent = findradius (ent, self->s.origin, self->dmg_radius)) != NULL) { if (!ent->takedamage) continue; if (ent == self->owner) continue; if (!CanDamage (ent, self)) continue; if (!CanDamage (ent, self->owner)) continue; VectorAdd (ent->mins, ent->maxs, v); VectorMA (ent->s.origin, 0.5, v, v); VectorSubtract (self->s.origin, v, v); dist = VectorLength (v); points = self->radius_dmg * (1.0 - sqrt (dist / self->dmg_radius)); if (ent == self->owner) points = points * 0.5; gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BFG_EXPLOSION); gi.WritePosition (ent->s.origin); gi.multicast (ent->s.origin, MULTICAST_PHS); T_Damage (ent, self, self->owner, self->velocity, ent->s.origin, vec3_origin, (int) points, 0, DAMAGE_ENERGY, MOD_BFG_EFFECT); } } self->nextthink = level.time + FRAMETIME; self->s.frame++; if (self->s.frame == 5) self->think = G_FreeEdict; } void bfg_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other == self->owner) return; if (surf && (surf->flags & SURF_SKY)) { G_FreeEdict (self); return; } if (self->owner->client) PlayerNoise (self->owner, self->s.origin, PNOISE_IMPACT); // core explosion - prevents firing it into the wall/floor if (other->takedamage) T_Damage (other, self, self->owner, self->velocity, self->s.origin, plane->normal, 200, 0, 0, MOD_BFG_BLAST); T_RadiusDamage (self, self->owner, 200, other, 100, MOD_BFG_BLAST); gi.sound (self, CHAN_VOICE, gi.soundindex ("weapons/bfg__x1b.wav"), 1, ATTN_NORM, 0); self->solid = SOLID_NOT; self->touch = NULL; VectorMA (self->s.origin, -1 * FRAMETIME, self->velocity, self->s.origin); VectorClear (self->velocity); self->s.modelindex = gi.modelindex ("sprites/s_bfg3.sp2"); self->s.frame = 0; self->s.sound = 0; self->s.effects &= ~EF_ANIM_ALLFAST; self->think = bfg_explode; self->nextthink = level.time + FRAMETIME; self->enemy = other; gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BFG_BIGEXPLOSION); gi.WritePosition (self->s.origin); gi.multicast (self->s.origin, MULTICAST_PVS); } void bfg_think (edict_t * self) { edict_t *ent; edict_t *ignore; vec3_t point; vec3_t dir; vec3_t start; vec3_t end; int dmg; trace_t tr; if (deathmatch->value) dmg = 5; else dmg = 10; ent = NULL; while ((ent = findradius (ent, self->s.origin, 256)) != NULL) { if (ent == self) continue; if (ent == self->owner) continue; if (!ent->takedamage) continue; if (!(ent->svflags & SVF_MONSTER) && (!ent->client) && (strcmp (ent->classname, "misc_explobox") != 0)) continue; //AQ2:TNG Igor not quite sure about this (FIXME) //don't target players in CTF if (ctf->value && ent->client && self->owner->client && ent->client->resp.team == self->owner->client->resp.team) continue; //AQ2:TNG End VectorMA (ent->absmin, 0.5, ent->size, point); VectorSubtract (point, self->s.origin, dir); VectorNormalize (dir); ignore = self; VectorCopy (self->s.origin, start); VectorMA (start, 2048, dir, end); while (1) { PRETRACE (); tr = gi.trace (start, NULL, NULL, end, ignore, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER); POSTTRACE (); if (!tr.ent) break; // hurt it if we can if ((tr.ent->takedamage) && !(tr.ent->flags & FL_IMMUNE_LASER) && (tr.ent != self->owner)) T_Damage (tr.ent, self, self->owner, dir, tr.endpos, vec3_origin, dmg, 1, DAMAGE_ENERGY, MOD_BFG_LASER); // if we hit something that's not a monster or player we're done if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client)) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_LASER_SPARKS); gi.WriteByte (4); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.WriteByte (self->s.skinnum); gi.multicast (tr.endpos, MULTICAST_PVS); break; } ignore = tr.ent; VectorCopy (tr.endpos, start); } gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_BFG_LASER); gi.WritePosition (self->s.origin); gi.WritePosition (tr.endpos); gi.multicast (self->s.origin, MULTICAST_PHS); } self->nextthink = level.time + FRAMETIME; } void fire_bfg (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed, float damage_radius) { edict_t *bfg; bfg = G_Spawn (); VectorCopy (start, bfg->s.origin); VectorCopy (dir, bfg->movedir); vectoangles (dir, bfg->s.angles); VectorScale (dir, speed, bfg->velocity); bfg->movetype = MOVETYPE_FLYMISSILE; bfg->clipmask = MASK_SHOT; bfg->solid = SOLID_BBOX; bfg->s.effects |= EF_BFG | EF_ANIM_ALLFAST; VectorClear (bfg->mins); VectorClear (bfg->maxs); bfg->s.modelindex = gi.modelindex ("sprites/s_bfg1.sp2"); bfg->owner = self; bfg->touch = bfg_touch; bfg->nextthink = level.time + 8000 / speed; bfg->think = G_FreeEdict; bfg->radius_dmg = damage; bfg->dmg_radius = damage_radius; bfg->classname = "bfg blast"; bfg->s.sound = gi.soundindex ("weapons/bfg__l1a.wav"); bfg->think = bfg_think; bfg->nextthink = level.time + FRAMETIME; bfg->teammaster = bfg; bfg->teamchain = NULL; if (self->client) check_dodge (self, bfg->s.origin, dir, speed); gi.linkentity (bfg); } void P_ProjectSource (gclient_t * client, vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result); qboolean IsFemale (edict_t * ent); void kick_attack (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; int damage = 20; int kick = 400; trace_t tr; vec3_t end; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, 0, ent->client->kick_origin); VectorSet (offset, 0, 0, ent->viewheight - 20); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); VectorMA (start, 25, forward, end); PRETRACE (); tr = gi.trace (ent->s.origin, NULL, NULL, end, ent, MASK_SHOT); POSTTRACE (); // don't need to check for water if ((tr.surface) && (tr.surface->flags & SURF_SKY)) return; if (tr.fraction >= 1.0) return; if (tr.ent->takedamage || KickDoor (&tr, ent, forward)) { if (tr.ent->health <= 0) return; if (teamplay->value) { // AQ2:TNG - JBravo adding UVtime if (tr.ent->client && tr.ent->client->ctf_uvtime) return; // if (tr.ent != ent && tr.ent->client && ent->client && // tr.ent->client->resp.team == ent->client->resp.team) // AQ:TNG - JBravo adding FF after rounds if ((tr.ent != ent) && (tr.ent->client && ent->client) && (tr.ent->client->resp.team == ent->client->resp.team) && team_round_going) return; if (!ff_afterround->value) return; // AQ:TNG } else if (((tr.ent != ent) && ((deathmatch->value && ((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) || coop->value) && OnSameTeam (tr.ent, ent))) return; // zucc stop powerful upwards kicking //forward[2] = 0; // glass fx if (Q_stricmp (tr.ent->classname, "func_explosive") == 0) CGF_SFX_ShootBreakableGlass (tr.ent, ent, &tr, MOD_KICK); else T_Damage (tr.ent, ent, ent, forward, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_KICK); gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/kick.wav"), 1, ATTN_NORM, 0); PlayerNoise (ent, ent->s.origin, PNOISE_SELF); ent->client->jumping = 0; // only 1 jumpkick per jump if (tr.ent->client && (tr.ent->client->curr_weap == M4_NUM || tr.ent->client->curr_weap == MP5_NUM || tr.ent->client->curr_weap == M3_NUM || tr.ent->client->curr_weap == SNIPER_NUM || tr.ent->client->curr_weap == HC_NUM)) // crandom() > .8 ) { // zucc fix this so reloading won't happen on the new gun! tr.ent->client->reload_attempts = 0; DropSpecialWeapon (tr.ent); gi.cprintf (ent, PRINT_HIGH, "You kick %s's %s from %s hands!\n", tr.ent->client->pers.netname,(tr.ent->client->pers.weapon)->pickup_name, IsFemale(tr.ent) ? "her" : "his"); gi.cprintf (tr.ent, PRINT_HIGH, "%s kicked your weapon from your hands!\n", ent->client->pers.netname); } else if(tr.ent->client && tr.ent->client->ctf_grapple && tr.ent->client->ctf_grapplestate == CTF_GRAPPLE_STATE_FLY) { // hifi: if the player is shooting a grapple, lose it's focus CTFPlayerResetGrapple(tr.ent); } } } // zucc // return values // 0 - missed // 1 - hit player // 2 - hit wall int knife_attack (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick) { trace_t tr; vec3_t end; VectorMA (start, 45, aimdir, end); PRETRACE (); tr = gi.trace (self->s.origin, NULL, NULL, end, self, MASK_SHOT); POSTTRACE (); // don't need to check for water if (!((tr.surface) && (tr.surface->flags & SURF_SKY))) { if (tr.fraction < 1.0) { //glass fx if (0 == Q_stricmp (tr.ent->classname, "func_explosive")) { CGF_SFX_ShootBreakableGlass (tr.ent, self, &tr, MOD_KNIFE); } else // --- if (tr.ent->takedamage) { setFFState (self); T_Damage (tr.ent, self, self, aimdir, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_KNIFE); return -2; } else { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPARKS); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.multicast (tr.endpos, MULTICAST_PVS); return -1; } } else return 0; } return 0; // we hit the sky, call it a miss } static int knives = 0; void knife_touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { vec3_t origin; // int n; edict_t *dropped; edict_t *knife; // vec3_t forward, right, up; vec3_t move_angles; gitem_t *item; if (other == ent->owner) return; if (surf && (surf->flags & SURF_SKY)) { G_FreeEdict (ent); return; } if (ent->owner->client) { gi.positioned_sound (ent->s.origin, ent, CHAN_WEAPON, gi.soundindex ("weapons/clank.wav"), 1, ATTN_NORM, 0); PlayerNoise (ent->owner, ent->s.origin, PNOISE_IMPACT); } // calculate position for the explosion entity VectorMA (ent->s.origin, -0.02, ent->velocity, origin); //glass fx if (0 == Q_stricmp (other->classname, "func_explosive")) { // ignore it, so it can bounce return; } else // --- if (other->takedamage) { T_Damage (other, ent, ent->owner, ent->velocity, ent->s.origin, plane->normal, ent->dmg, 0, 0, MOD_KNIFE_THROWN); } else { // code to manage excess knives in the game, guarantees that // no more than knifelimit knives will be stuck in walls. // if knifelimit == 0 then it won't be in effect and it can // start removing knives even when less than the limit are // out there. if (knifelimit->value != 0) { knives++; if (knives > knifelimit->value) knives = 1; knife = FindEdictByClassnum ("weapon_Knife", knives); if (knife) { knife->nextthink = level.time + .1; } } dropped = G_Spawn (); item = GET_ITEM(KNIFE_NUM); dropped->classname = item->classname; dropped->typeNum = item->typeNum; dropped->item = item; dropped->spawnflags = DROPPED_ITEM; dropped->s.effects = item->world_model_flags; dropped->s.renderfx = RF_GLOW; VectorSet (dropped->mins, -15, -15, -15); VectorSet (dropped->maxs, 15, 15, 15); gi.setmodel (dropped, dropped->item->world_model); dropped->solid = SOLID_TRIGGER; dropped->movetype = MOVETYPE_TOSS; dropped->touch = Touch_Item; dropped->owner = ent; dropped->gravity = 0; dropped->classnum = knives; vectoangles (ent->velocity, move_angles); //AngleVectors (ent->s.angles, forward, right, up); VectorCopy (ent->s.origin, dropped->s.origin); VectorCopy (move_angles, dropped->s.angles); //VectorScale (forward, 100, dropped->velocity); //dropped->velocity[2] = 300; //dropped->think = drop_make_touchable; //dropped->nextthink = level.time + 1; dropped->nextthink = level.time + 120; dropped->think = G_FreeEdict; gi.linkentity (dropped); if (!(ent->waterlevel)) { /*gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_WELDING_SPARKS); gi.WritePosition (origin); gi.multicast (ent->s.origin, MULTICAST_PHS); */ gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPARKS); gi.WritePosition (origin); gi.WriteDir (plane->normal); gi.multicast (ent->s.origin, MULTICAST_PVS); } } G_FreeEdict (ent); } void knife_throw (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed) { edict_t *knife; // vec3_t forward, right, up; trace_t tr; knife = G_Spawn (); VectorNormalize (dir); VectorCopy (start, knife->s.origin); VectorCopy (start, knife->s.old_origin); vectoangles (dir, knife->s.angles); VectorScale (dir, speed, knife->velocity); knife->movetype = MOVETYPE_TOSS; /* VectorCopy (start, knife->s.origin); VectorCopy (dir, knife->movedir); vectoangles (dir, knife->s.angles); VectorScale (dir, speed, knife->velocity); */ // gi.cprintf(self, PRINT_HIGH, "speed %d\n", speed); // below add upwards trajectory, not in action though // AngleVectors (knife->s.angles, forward, right, up); // VectorMA (knife->velocity, 210, up, knife->velocity); VectorSet (knife->avelocity, 1200, 0, 0); knife->movetype = MOVETYPE_TOSS; knife->clipmask = MASK_SHOT; knife->solid = SOLID_BBOX; knife->s.effects = 0; //EF_ROTATE? VectorClear (knife->mins); VectorClear (knife->maxs); knife->s.modelindex = gi.modelindex ("models/objects/knife/tris.md2"); knife->owner = self; knife->touch = knife_touch; knife->nextthink = level.time + 8000 / speed; knife->think = G_FreeEdict; knife->dmg = damage; knife->s.sound = gi.soundindex ("misc/flyloop.wav"); knife->classname = "thrown_knife"; // used by dodging monsters, skip // if (self->client) // check_dodge (self, rocket->s.origin, dir, speed); PRETRACE (); tr = gi.trace (self->s.origin, NULL, NULL, knife->s.origin, knife, MASK_SHOT); POSTTRACE (); if (tr.fraction < 1.0) { VectorMA (knife->s.origin, -10, dir, knife->s.origin); knife->touch (knife, tr.ent, NULL, NULL); } gi.linkentity (knife); } /* ===================================================================== setFFState: Save team wound count & warning state before an attack The purpose of this is so that we can increment team_wounds by 1 for each real attack instead of just counting each bullet/pellet/shrapnel as a wound. The ff_warning flag is so that we don't overflow the clients from repeated FF warnings. Hopefully the overhead on this will be low enough to not affect things. ===================================================================== */ void setFFState (edict_t * ent) { if (ent && ent->client) { ent->client->team_wounds_before = ent->client->team_wounds; ent->client->ff_warning = 0; } }
533
./aq2-tng/source/tng_irc.c
//----------------------------------------------------------------------------- // IRC related functions // // $Id: tng_irc.c,v 1.2 2003/06/19 15:53:26 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: tng_irc.c,v $ // Revision 1.2 2003/06/19 15:53:26 igor_rock // changed a lot of stuff because of windows stupid socket implementation // // Revision 1.1 2003/06/15 21:45:11 igor // added IRC client // //----------------------------------------------------------------------------- #define DEBUG 1 //----------------------------------------------------------------------------- #ifdef WIN32 #include <io.h> #include <winsock2.h> #define bzero(a,b) memset(a,0,b) #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #endif #include <errno.h> #include <string.h> #include <fcntl.h> #include <stdarg.h> #define TNG_IRC_C #include "g_local.h" #define IRC_DISABLED 0 #define IRC_CONNECTING 2 #define IRC_CONNECTED 3 #define IRC_JOINED 4 #define IRC_ST_DISABLED "disabled" #define IRC_ST_CONNECTING "connecting..." #define IRC_ST_CONNECTED "connected..." #define IRC_ST_JOINED "channel joined" #define IRC_QUIT "QUIT :I'll be back!\n" tng_irc_t irc_data; #ifdef WIN32 // Windows junk int IRCstartWinsock() { WSADATA wsa; return WSAStartup(MAKEWORD(2,0),&wsa); } #define set_nonblocking(sok) { \ unsigned long one = 1; \ ioctlsocket (sok, FIONBIO, &one); \ } static int IRC_identd_is_running = FALSE; static int IRC_identd (void *unused) { int sok, read_sok, len; char *p; char buf[256]; char outbuf[256]; struct sockaddr_in addr; sok = socket (AF_INET, SOCK_STREAM, 0); if (sok == INVALID_SOCKET) return 0; len = 1; setsockopt (sok, SOL_SOCKET, SO_REUSEADDR, (char *) &len, sizeof (len)); memset (&addr, 0, sizeof (addr)); addr.sin_family = AF_INET; addr.sin_port = htons (113); if (bind (sok, (struct sockaddr *) &addr, sizeof (addr)) == SOCKET_ERROR) { closesocket (sok); return 0; } if (listen (sok, 1) == SOCKET_ERROR) { closesocket (sok); return 0; } len = sizeof (addr); read_sok = accept (sok, (struct sockaddr *) &addr, &len); closesocket (sok); if (read_sok == INVALID_SOCKET) return 0; if (ircdebug->value) { gi.dprintf ("IRC: identd: Servicing ident request from %s\n", inet_ntoa (addr.sin_addr)); } recv (read_sok, buf, sizeof (buf) - 1, 0); buf[sizeof (buf) - 1] = 0; /* ensure null termination */ p = strchr (buf, ','); if (p) { sprintf (outbuf, "%d, %d : USERID : UNIX : %s\r\n", atoi (buf), atoi (p + 1), irc_data.ircuser); outbuf[sizeof (outbuf) - 1] = 0; /* ensure null termination */ send (read_sok, outbuf, strlen (outbuf), 0); } //sleep (1); closesocket (read_sok); IRC_identd_is_running = FALSE; return 0; } static void IRC_identd_start (void) { DWORD tid; if (IRC_identd_is_running == FALSE) { IRC_identd_is_running = TRUE; CloseHandle (CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE) IRC_identd, NULL, 0, &tid)); } } #endif void IRC_init ( void ) { // init all cvars ircserver = gi.cvar ("ircserver", IRC_SERVER, 0); ircport = gi.cvar ("ircport", "6667", 0); ircchannel = gi.cvar ("ircchannel", IRC_CHANNEL, 0); ircuser = gi.cvar ("ircuser", IRC_USER, 0); ircpasswd = gi.cvar ("ircpasswd", IRC_PASSWD, 0); irctopic = gi.cvar ("irctopic", IRC_TOPIC, 0); ircbot = gi.cvar ("ircbot", "0", 0); ircstatus = gi.cvar ("ircstatus", IRC_ST_DISABLED, 0); ircop = gi.cvar ("ircop", "", 0); ircmlevel = gi.cvar ("ircmlevel", "6", 0); ircdebug = gi.cvar ("ircdebug", "0", 0); ircadminpwd = gi.cvar ("ircadminpwd", "off", 0); // init our internal structure irc_data.ircstatus = IRC_DISABLED; bzero(irc_data.input, sizeof(irc_data.input)); #ifdef WIN32 IRCstartWinsock(); #endif } void IRC_exit ( void ) { if (irc_data.ircstatus != IRC_DISABLED) { send (irc_data.ircsocket, IRC_QUIT, strlen(IRC_QUIT), 0); if (ircdebug->value) gi.dprintf ("IRC: %s", IRC_QUIT); irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); close (irc_data.ircsocket); } } void irc_connect ( void ) { char outbuf[IRC_BUFLEN]; struct sockaddr_in hostaddress; struct in_addr ipnum; struct hostent *hostdata; #ifndef WIN32 int flags; #else IRC_identd_start (); #endif irc_data.ircstatus = IRC_CONNECTING; strcpy (ircstatus->string, IRC_ST_CONNECTING); irc_data.ircsocket = -1; irc_data.ircport = htons((unsigned short) ircport->value); strncpy (irc_data.ircserver, ircserver->string, IRC_BUFLEN); strncpy (irc_data.ircuser, ircuser->string, IRC_BUFLEN); strncpy (irc_data.ircpasswd, ircpasswd->string, IRC_BUFLEN); strncpy (irc_data.ircchannel, ircchannel->string, IRC_BUFLEN); if ((ipnum.s_addr = inet_addr(irc_data.ircserver)) == -1) { /* Maybe it's a FQDN */ hostdata = gethostbyname(irc_data.ircserver); if (hostdata==NULL) { gi.dprintf ("IRC: invalid hostname or wrong address! Please use an existing hostname or,the xxx.xxx.xxx.xxx format.\n"); ircbot->value = 0; irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); } else { ipnum.s_addr = inet_addr(inet_ntoa(*(struct in_addr *)(hostdata->h_addr_list[0]))); } } if (ircbot->value) { gi.dprintf ("IRC: using server %s:%i\n", inet_ntoa(ipnum), ntohs((unsigned short) irc_data.ircport)); bzero((char *) &hostaddress, sizeof(hostaddress)); hostaddress.sin_family = AF_INET; hostaddress.sin_addr.s_addr = ipnum.s_addr; hostaddress.sin_port = irc_data.ircport; if ((irc_data.ircsocket = socket (AF_INET, SOCK_STREAM, 0)) == -1) { gi.dprintf ("IRC: couldn't open socket.\n"); ircbot->value = 0; irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); } else { if (connect(irc_data.ircsocket, (struct sockaddr *)&hostaddress, sizeof(hostaddress)) == -1) { gi.dprintf ("IRC: couldn't connect socket.\n"); ircbot->value = 0; irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); } else { gi.dprintf ("IRC: connected to %s:%d\n", irc_data.ircserver, ntohs((unsigned short) irc_data.ircport)); #ifdef WIN32 set_nonblocking(irc_data.ircsocket); #else flags = fcntl(irc_data.ircsocket, F_GETFL); flags |= O_NONBLOCK; if (fcntl(irc_data.ircsocket, F_SETFL, (long) flags)) { gi.dprintf ("IRC: couldn't switch to non-blocking\n"); close (irc_data.ircsocket); ircbot->value = 0; irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); } else { #endif sprintf (outbuf, "NICK %s\nUSER tng-mbot * * :%s\n", irc_data.ircuser, hostname->string); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); if (ircdebug->value) gi.dprintf("IRC: >> NICK %s\nIRC: >> USER tng-mbot * * :%s\n", irc_data.ircuser, hostname->string); #ifndef WIN32 } #endif } } } } void irc_parse ( void ) { int i; int pos; char *cp; char outbuf[IRC_BUFLEN]; char wer[256]; bzero(outbuf, sizeof(outbuf)); if (strlen (irc_data.input)) { if (ircdebug->value) gi.dprintf ("IRC: << %s\n", irc_data.input); if (*irc_data.input == ':') { for ( pos=1; irc_data.input[pos]; pos++) { if (irc_data.input[pos] == ' ') { break; } else { wer[pos-1] = irc_data.input[pos]; } } wer[pos-1] = 0; pos++; if (Q_strnicmp (wer, irc_data.ircuser, strlen(irc_data.ircuser)) == 0) { cp = strchr(irc_data.input, ' '); cp++; // skip the space if (Q_strnicmp (cp, "JOIN :", 6) == 0) { // channel JOINED cp += 6; gi.dprintf ("IRC: joined channel %s\n", cp); if (Q_strnicmp(cp, irc_data.ircchannel, strlen(irc_data.ircchannel)) == 0) { // joined our channel irc_data.ircstatus = IRC_JOINED; strcpy (ircstatus->string, IRC_ST_JOINED); if (*ircop->string) { if (ircdebug->value) gi.dprintf ("IRC: >> %s\n", ircop->string); sprintf (outbuf, "%s\n", ircop->string); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } } else { // joined another channel } } else { // Maybe Future Extesion } } else if (Q_strnicmp (&irc_data.input[pos], "004 ", 4) == 0) { sprintf(outbuf, "mode %s +i\n", irc_data.ircuser); if (ircdebug->value) gi.dprintf("IRC: >> mode %s +i set\n", irc_data.ircuser); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); if (irc_data.ircpasswd[0]) { sprintf(outbuf, "join %s %s\n", irc_data.ircchannel, irc_data.ircpasswd); gi.dprintf ("IRC: trying to join channel %s %s\n", irc_data.ircchannel, irc_data.ircpasswd); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); sprintf (outbuf, "mode %s +mntk %s\n", irc_data.ircchannel, irc_data.ircpasswd); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } else { sprintf(outbuf, "join %s\n", irc_data.ircchannel); gi.dprintf ("IRC: trying to join channel %s\n", irc_data.ircchannel); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); sprintf (outbuf, "mode %s +mnt\n", irc_data.ircchannel); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } irc_data.ircstatus = IRC_CONNECTED; strcpy (ircstatus->string, IRC_ST_CONNECTED); } else if (Q_strnicmp (&irc_data.input[pos], "PRIVMSG ", 8) == 0) { pos += 8; if (Q_strnicmp (&irc_data.input[pos], irc_data.ircuser, strlen(irc_data.ircuser)) == 0) { pos += strlen(irc_data.ircuser) + 2; if ((Q_strnicmp (&irc_data.input[pos], ircadminpwd->string, strlen(ircadminpwd->string)) == 0) && (Q_strnicmp (ircadminpwd->string, "off", 3) != 0)) { pos += strlen(ircadminpwd->string) + 1; for (i=0; i < strlen(wer); i++) { if (wer[i] == '!') { wer[i] = 0; } } if (Q_strnicmp (&irc_data.input[pos], "op", 2) == 0) { gi.dprintf ("IRC: set +o %s\n", wer); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } else if (Q_strnicmp (&irc_data.input[pos], "say", 3) == 0) { pos += 4; if (strlen(&irc_data.input[pos]) > 225) { irc_data.input[pos+225] = 0; } sprintf (outbuf, "say %s\n", &irc_data.input[pos]); gi.AddCommandString (outbuf); IRC_printf (IRC_T_TALK, "console: %s\n", &irc_data.input[pos]); } } } else if (Q_strnicmp (&irc_data.input[pos], irc_data.ircchannel, strlen(irc_data.ircchannel)) == 0) { pos += strlen(irc_data.ircchannel) + 1; // Maybe Future Extesion } } else if (Q_strnicmp (&irc_data.input[pos], "NOTICE ", 7) == 0) { pos += 7; // Maybe Future Extesion } else if (strstr (irc_data.input, irc_data.ircuser)) { if (strstr (irc_data.input, " KICK ") || strstr (irc_data.input, "kick")) { if (irc_data.ircpasswd[0]) { sprintf(outbuf, "join %s %s\n", irc_data.ircchannel, irc_data.ircpasswd); gi.dprintf ("IRC: trying to join channel %s %s (got kicked)\n", irc_data.ircchannel, irc_data.ircpasswd); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } else { sprintf(outbuf, "join %s\n", irc_data.ircchannel); gi.dprintf ("IRC: trying to join channel %s (got kicked)\n", irc_data.ircchannel); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } } } } else if (Q_strnicmp(irc_data.input, "PING :", 6) == 0) { /* answer with a pong */ sprintf(outbuf, "PONG %s\n", &irc_data.input[6]); if (ircdebug->value) gi.dprintf ("IRC: >> %s\n", outbuf); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } } } // // puffered IO for asynchronous IRC socket // void irc_getinput ( void ) { size_t length; int anz_net = 0; char *anfang; char *ende; char *abs_ende; char inbuf[IRC_BUFLEN]; bzero(inbuf, sizeof(inbuf)); anz_net = recv (irc_data.ircsocket, inbuf, sizeof(inbuf), 0); if (anz_net <= 0) { #ifdef WIN32 if ((anz_net == 0) || ((anz_net == -1) && (WSAGetLastError() != WSAEWOULDBLOCK))) { #else if ((anz_net == 0) || ((anz_net == -1) && (errno != EAGAIN))) { #endif gi.dprintf ("IRC: connection terminated!\n"); close (irc_data.ircsocket); irc_data.ircstatus = IRC_DISABLED; strcpy (ircstatus->string, IRC_ST_DISABLED); } } else if (anz_net > 0) { anfang = inbuf; abs_ende = inbuf + strlen(inbuf); if ((abs_ende - inbuf ) > sizeof(inbuf)) { abs_ende = inbuf + sizeof(inbuf); } while (anfang < abs_ende) { ende = memchr(anfang, 13, abs_ende - anfang); if (ende != NULL) { // Zeilenende gefunden *ende = 0; if (strlen(irc_data.input)) { // schon etwas im Puffer, also anhaengen strcat (irc_data.input, anfang); } else { // Puffer leer, also nur kopieren strcpy (irc_data.input, anfang); } irc_parse(); // danach Puffer leeren bzero(irc_data.input, sizeof(irc_data.input)); anfang = ende + 1; if ((*anfang == 13) || (*anfang == 10)) { anfang++; } } else { length = abs_ende - anfang; if (memchr(anfang, 0, length) != NULL) { length = strlen(anfang); } if (strlen(irc_data.input)) { // schon etwas im Puffer, also anhaengen strncat (irc_data.input, anfang, length); } else { // Puffer leer, also nur kopieren strncpy (irc_data.input, anfang, length); } irc_data.input[length] = 0; anfang += length; } } } } void IRC_poll (void) { if (ircbot->value == 0) { if (irc_data.ircstatus != IRC_DISABLED) { IRC_exit (); } } else { if (irc_data.ircstatus == IRC_DISABLED) { irc_connect (); } else { irc_getinput (); } } } // // this function is a little bit more complex. // in the format string you can have the following parameters: // %n -> names (nicks, teams, server) // %w -> weapon/item // %v -> vote item // %k -> kills/frags/rounds // %s -> normal string void IRC_printf (int type, char *fmt, ... ) { char outbuf[IRC_BUFLEN]; char message[IRC_BUFLEN-128]; char topic[IRC_BUFLEN-128]; char *s; int i; int std_col; int mpos; int tpos; int normal = 0; va_list ap; bzero(message, sizeof(message)); bzero(topic, sizeof(topic)); if (irc_data.ircstatus == IRC_JOINED) { if ((type <= ircmlevel->value) || ((type == IRC_T_TOPIC) && (ircmlevel->value >= IRC_T_GAME))) { switch (type) { case IRC_T_SERVER: { std_col = IRC_C_ORANGE; break; } case IRC_T_TOPIC: { // set the topic // no break, so we use GAME settings for the colors } case IRC_T_GAME: { std_col = IRC_C_DRED; break; } case IRC_T_DEATH: { std_col = IRC_C_GREY75; break; } case IRC_T_KILL: { std_col = IRC_C_GREY25; break; } case IRC_T_VOTE: { std_col = IRC_C_GREY50; break; } case IRC_T_TALK: { std_col = IRC_C_GREY50; break; } default: { std_col = IRC_C_GREY50; break; } } mpos = 0; tpos = 0; va_start (ap, fmt); while (*fmt) { if (*fmt == '%') { fmt++; switch (*fmt) { case 'n': { s = va_arg(ap, char *); sprintf (&message[mpos], "%c%d%s", IRC_CMCOLORS, IRC_C_DBLUE, s); mpos += strlen (&message[mpos]); sprintf (&topic[tpos], "%s", s); tpos += strlen (&topic[tpos]); normal = 0; break; } case 'w': { s = va_arg(ap, char *); sprintf (&message[mpos], "%c%d%s", IRC_CMCOLORS, IRC_C_BLUE, s); mpos += strlen (&message[mpos]); sprintf (&topic[tpos], "%s", s); tpos += strlen (&topic[tpos]); normal = 0; break; } case 'v': { s = va_arg(ap, char *); sprintf (&message[mpos], "%c%d%s", IRC_CMCOLORS, IRC_C_DGREEN, s); mpos += strlen (&message[mpos]); sprintf (&topic[tpos], "%s", s); tpos += strlen (&topic[tpos]); normal = 0; break; } case 'k': { i = va_arg(ap, int); sprintf (&message[mpos], "%c%d%c", IRC_CBOLD, i, IRC_CBOLD); mpos += strlen (&message[mpos]); sprintf (&topic[tpos], "%d", i); tpos += strlen (&topic[tpos]); normal = 0; break; } case 's': { s = va_arg(ap, char *); sprintf (&message[mpos], "%s", s); mpos += strlen (&message[mpos]); sprintf (&topic[tpos], "%s", s); tpos += strlen (&topic[tpos]); normal = 0; break; } default: { message[mpos++] = '%'; topic[tpos++] = '%'; break; } } } else { if (!normal) { message[mpos++] = IRC_CMCOLORS; sprintf (&message[mpos], "%d", std_col); mpos += strlen (&message[mpos]); normal = 1; } message[mpos++] = *fmt; topic[tpos++] = *fmt; } fmt++; } message[mpos] = 0; topic[tpos] = 0; va_end(ap); // print it sprintf (outbuf, "PRIVMSG %s :%s\n", irc_data.ircchannel, message); if (ircdebug->value) gi.dprintf ("IRC: >> %s", outbuf); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); if ((type == IRC_T_TOPIC) && (ircmlevel->value >= IRC_T_TOPIC)) { sprintf (outbuf, "TOPIC %s :%s %s\n", irc_data.ircchannel, irctopic->string, topic); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } } } else if (irc_data.ircstatus == IRC_CONNECTED) { if (irc_data.ircpasswd[0]) { sprintf(outbuf, "join %s %s\n", irc_data.ircchannel, irc_data.ircpasswd); gi.dprintf ("IRC: trying to join channel %s %s\n", irc_data.ircchannel, irc_data.ircpasswd); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); sprintf (outbuf, "mode %s +mntk %s\n", irc_data.ircchannel, irc_data.ircpasswd); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } else { sprintf(outbuf, "join %s\n", irc_data.ircchannel); gi.dprintf ("IRC: trying to join channel %s\n", irc_data.ircchannel); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); sprintf (outbuf, "mode %s +mnt\n", irc_data.ircchannel); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } } } void SVCmd_ircraw_f (void) { int i; char outbuf[IRC_BUFLEN]; bzero (outbuf, sizeof(outbuf)); if (irc_data.ircstatus == IRC_DISABLED) { gi.cprintf (NULL, PRINT_HIGH, "IRC: Not connected to IRC\n"); } else { for (i = 2; i < gi.argc(); i++) { strcat (outbuf, gi.argv(i)); strcat (outbuf, " "); } strcat (outbuf, "\n"); if (ircdebug->value) gi.cprintf (NULL, PRINT_HIGH, "IRC: >> %s\n", outbuf); send (irc_data.ircsocket, outbuf, strlen(outbuf), 0); } }
534
./aq2-tng/source/tng_flashlight.c
#include "g_local.h" /* =============== FL_make make the flashlight =============== */ void FL_make (edict_t * self) { vec3_t start, forward, right, end; if (!darkmatch->value) return; if ((self->deadflag == DEAD_DEAD) || (self->solid == SOLID_NOT)) { if (self->flashlight) { G_FreeEdict (self->flashlight); self->flashlight = NULL; } return; } gi.sound (self, CHAN_VOICE, gi.soundindex ("misc/flashlight.wav"), 1, ATTN_NORM, 0); if (self->flashlight) { G_FreeEdict (self->flashlight); self->flashlight = NULL; return; } AngleVectors (self->client->v_angle, forward, right, NULL); VectorSet (end, 100, 0, 0); G_ProjectSource (self->s.origin, end, forward, right, start); self->flashlight = G_Spawn (); self->flashlight->owner = self; self->flashlight->movetype = MOVETYPE_NOCLIP; self->flashlight->solid = SOLID_NOT; self->flashlight->classname = "flashlight"; self->flashlight->s.modelindex = gi.modelindex ("sprites/null.sp2"); self->flashlight->s.skinnum = 0; self->flashlight->s.effects |= EF_HYPERBLASTER; // Other effects can be used here, such as flag1, but these look corney and dull. Try stuff and tell me if you find anything cool (EF_HYPERBLASTER) self->flashlight->think = FL_think; self->flashlight->nextthink = level.time + 0.1; } /* 8===============> FL_think Moving the flashlight <===============8 */ void FL_think (edict_t * self) { vec3_t start, end, endp, offset; vec3_t forward, right, up; vec3_t angles; trace_t tr; int height = 0; /*vec3_t start,end,endp,offset; vec3_t forward,right,up; trace_t tr; */ //AngleVectors (self->owner->client->v_angle, forward, right, up); VectorAdd (self->owner->client->v_angle, self->owner->client->kick_angles, angles); AngleVectors ( /*self->owner->client->v_angle */ angles, forward, right, up); /* VectorSet(offset,24 , 6, self->owner->viewheight-7); G_ProjectSource (self->owner->s.origin, offset, forward, right, start); VectorMA(start,8192,forward,end); tr = gi.trace (start,NULL,NULL, end,self->owner,CONTENTS_SOLID|CONTENTS_MONSTER|CONTENTS_DEADMONSTER); if (tr.fraction != 1) { VectorMA(tr.endpos,-4,forward,endp); VectorCopy(endp,tr.endpos); } if ((tr.ent->svflags & SVF_MONSTER) || (tr.ent->client)) { if ((tr.ent->takedamage) && (tr.ent != self->owner)) { self->s.skinnum = 1; } } else self->s.skinnum = 0; vectoangles(tr.plane.normal,self->s.angles); VectorCopy(tr.endpos,self->s.origin); gi.linkentity (self); self->nextthink = level.time + 0.1; */ if (self->owner->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; VectorSet (offset, 24, 8, self->owner->viewheight - height); P_ProjectSource (self->owner->client, self->owner->s.origin, offset, forward, right, start); VectorMA (start, 8192, forward, end); PRETRACE (); tr = gi.trace (start, NULL, NULL, end, self->owner, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER); POSTTRACE (); if (tr.fraction != 1) { VectorMA (tr.endpos, -4, forward, endp); VectorCopy (endp, tr.endpos); } vectoangles (tr.plane.normal, self->s.angles); VectorCopy (tr.endpos, self->s.origin); gi.linkentity (self); self->nextthink = level.time + 0.1; }
535
./aq2-tng/source/a_team.c
//----------------------------------------------------------------------------- // Teamplay-related code for Action (formerly Axshun). // Some of this is borrowed from Zoid's CTF (thanks Zoid) // -Fireblade // // $Id: a_team.c,v 1.88 2003/06/15 21:43:53 igor Exp $ // //----------------------------------------------------------------------------- // $Log: a_team.c,v $ // Revision 1.88 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.87 2002/04/01 14:00:08 freud // After extensive checking I think I have found the spawn bug in the new // system. // // Revision 1.86 2002/03/28 20:53:45 deathwatch // updated credits (forgot QNI in the clan list) // // Revision 1.85 2002/03/28 13:34:01 deathwatch // updated credits // // Revision 1.84 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.83 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.82 2002/03/27 15:16:56 freud // Original 1.52 spawn code implemented for use_newspawns 0. // Teamplay, when dropping bandolier, your drop the grenades. // Teamplay, cannot pick up grenades unless wearing bandolier. // // Revision 1.81 2002/03/26 21:49:01 ra // Bufferoverflow fixes // // Revision 1.80 2002/03/25 17:44:17 freud // Small fix // // Revision 1.79 2002/03/24 22:45:53 freud // New spawn code again, bad commit last time.. // // Revision 1.77 2002/02/27 16:07:13 deathwatch // Updated Credits menu // // Revision 1.76 2002/02/23 18:52:36 freud // Added myself to the credits menu :) // // Revision 1.75 2002/02/23 18:33:52 freud // Fixed newline bug with announcer (EXCELLENT.. 1 FRAG LEFT) for logfiles // // Revision 1.74 2002/02/23 18:12:14 freud // Added newlines back to the CenterPrintAll for IMPRESSIVE, EXCELLENT, // ACCURACY and X FRAGS Left, it was screwing up the logfile. // // Revision 1.73 2002/02/18 13:55:35 freud // Added last damaged players %P // // Revision 1.72 2002/02/17 23:25:29 freud // Fixed a small bug where stats were sent twice on votes and roundlimits // // Revision 1.71 2002/02/17 19:04:14 freud // Possible bugfix for overflowing clients with stat_mode set. // // Revision 1.70 2002/02/03 01:07:28 freud // more fixes with stats // // Revision 1.69 2002/02/01 12:54:08 ra // messin with stat_mode // // Revision 1.68 2002/01/24 10:39:32 ra // Removed an old debugging statement // // Revision 1.67 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.66 2001/12/30 04:00:09 ra // Players that switch between teams before dying should also be punished. // // Revision 1.65 2001/12/30 03:39:52 ra // Added to punishkills system if people do team none just before dieing // // Revision 1.64 2001/12/27 23:29:46 slicerdw // Reset sub and captain vars when doing "team none" // // Revision 1.63 2001/12/05 15:27:35 igor_rock // improved my english (actual -> current :) // // Revision 1.62 2001/12/02 16:41:52 igor_rock // corrected the teamscores (they where switched) // // Revision 1.61 2001/12/02 16:16:16 igor_rock // added "Actual Score" message after Round // // Revision 1.60 2001/11/25 19:09:25 slicerdw // Fixed Matchtime // // Revision 1.59 2001/11/16 13:01:39 deathwatch // Fixed 'no team wins' sound - it wont play now with use_warnings 0 // Precaching misc/flashlight.wav // // Revision 1.58 2001/11/03 17:33:06 ra // Yes another warning gone // // Revision 1.57 2001/11/03 17:21:57 deathwatch // Fixed something in the time command, removed the .. message from the voice command, fixed the vote spamming with mapvote, removed addpoint command (old pb command that wasnt being used). Some cleaning up of the source at a few points. // // Revision 1.56 2001/11/02 16:07:47 ra // Changed teamplay spawn code so that teams dont spawn in the same place // often in a row // // Revision 1.55 2001/09/30 03:09:34 ra // Removed new stats at end of rounds and created a new command to // do the same functionality. Command is called "time" // // Revision 1.54 2001/09/29 20:18:26 ra // Its boo boo day today // // Revision 1.53 2001/09/29 19:54:04 ra // Made a CVAR to turn off extratimingstats // // Revision 1.52 2001/09/29 19:16:47 ra // Made a boo boo in the timing stuff. // // Revision 1.51 2001/09/29 19:15:38 ra // Added some more timing stuff // // Revision 1.50 2001/09/29 17:21:04 ra // Fix a small 3teams bug // // Revision 1.49 2001/09/28 16:24:19 deathwatch // use_rewards now silences the teamX wins sounds and added gibbing for the Shotgun // // Revision 1.48 2001/09/28 15:03:26 ra // replacing itoa with a sprintf() call 'cause itoa is MIA on Linux // // Revision 1.47 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.46 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.45 2001/09/26 18:13:48 slicerdw // Fixed the roundtimelimit thingy which was ending the game ( confused with roundlimit ) // // Revision 1.44 2001/08/08 12:42:22 slicerdw // Ctf Should finnaly be fixed now, lets hope so // // Revision 1.43 2001/08/06 14:38:44 ra // Adding UVtime for ctf // // Revision 1.42 2001/08/01 13:54:26 ra // Hack to keep scoreboard from revealing whos alive during matches // // Revision 1.41 2001/07/30 10:17:59 igor_rock // added some parenthesis in the 3 minutes warning clause // // Revision 1.40 2001/07/28 19:30:05 deathwatch // Fixed the choose command (replaced weapon for item when it was working with items) // and fixed some tabs on other documents to make it more readable // // Revision 1.39 2001/07/16 19:02:06 ra // Fixed compilerwarnings (-g -Wall). Only one remains. // // Revision 1.38 2001/07/15 02:08:40 slicerdw // Added the "Team" section on scoreboard2 using matchmode // // Revision 1.37 2001/07/10 13:16:57 ra // Fixed bug where the "3 MINUTES LEFT" warning gets printed at the begining // of rounds that are only 2 minutes long. // // Revision 1.36 2001/07/09 17:55:50 slicerdw // Small change on the Board // // Revision 1.35 2001/06/28 20:29:58 igor_rock // changed the scoreboard to redruce length (and changed the debug output to report at 1023 lenght) // // Revision 1.34 2001/06/28 14:36:40 deathwatch // Updated the Credits Menu a slight bit (added Kobra) // // Revision 1.33 2001/06/27 20:24:03 igor_rock // changed the matchmode scoreboard completly (did a new one) // // Revision 1.32 2001/06/27 17:50:09 igor_rock // fixed the vote reached bug in teamplay and matchmode // // Revision 1.31 2001/06/27 16:58:14 igor_rock // corrected some limchasecam bugs // // Revision 1.30 2001/06/25 20:59:17 ra // // Adding my clantag. // // Revision 1.29 2001/06/22 18:37:01 igor_rock // fixed than damn limchasecam bug - eentually :) // // Revision 1.28 2001/06/20 19:23:19 igor_rock // added vcehckvotes for ctf mode "in game" ;) // // Revision 1.27 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.26 2001/06/19 20:56:45 igor_rock // fixed the matchmode scoreboard - finally :-) // // Revision 1.25 2001/06/19 18:56:38 deathwatch // New Last killed target system // // Revision 1.24 2001/06/18 20:29:42 igor_rock // subs don't respawn (says slicer :) // splitted the scoreboard for matchmode (new if/else branch) // // Revision 1.23 2001/06/06 18:57:14 slicerdw // Some tweaks on Ctf and related things // // Revision 1.21 2001/06/05 20:00:14 deathwatch // Added ICE-M to credits, fixed some stuff // // Revision 1.20 2001/06/05 18:47:11 slicerdw // Small tweaks to matchmode // // Revision 1.18 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.17 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.16.2.4 2001/05/27 11:47:53 igor_rock // added .flg file support and timelimit bug fix // // Revision 1.16.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.16.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.16.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.16 2001/05/20 12:54:18 igor_rock // Removed newlines from Centered Messages like "Impressive" // // Revision 1.15 2001/05/17 16:18:13 igor_rock // added wp_flags and did some itm_flags and other corrections // // Revision 1.14 2001/05/17 14:54:47 igor_rock // added itm_flags for teamplay and ctf // // Revision 1.13 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.12 2001/05/12 19:17:03 slicerdw // Changed The Join and Weapon choosing Menus // // Revision 1.11 2001/05/12 18:38:27 deathwatch // Tweaked MOTD and Menus some more // // Revision 1.10 2001/05/12 17:36:33 deathwatch // Edited the version variables and updated the menus. Added variables: // ACTION_VERSION, TNG_VERSION and TNG_VERSION2 // // Revision 1.9 2001/05/12 14:52:47 mort // Fixed bug of people being able to respawn when choosing a new item // // Revision 1.8 2001/05/12 13:48:58 mort // Fixed CTF ForceSpawn bug // // Revision 1.7 2001/05/12 08:20:01 mort // CTF bug fix, makes sure flags have actually spawned before certain functions attempt to use them // // Revision 1.6 2001/05/11 16:12:03 mort // Updated path locations for CTF flag loading and CTF hacked spawns // // Revision 1.5 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.4 2001/05/11 12:21:18 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.2 2001/05/07 20:06:45 igor_rock // changed sound dir from sound/rock to sound/tng // // Revision 1.1.1.1 2001/05/06 17:24:38 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" qboolean team_game_going = false; // is a team game going right now? qboolean team_round_going = false; // is an actual round of a team game going right now? int team_round_countdown = 0; // countdown variable for start of a round int rulecheckfrequency = 0; // accumulator variable for checking rules every 1.5 secs int lights_camera_action = 0; // countdown variable for "lights...camera...action!" int timewarning = 0; // countdown variable for "x Minutes left" int fragwarning = 0; // countdown variable for "x Frags left" int holding_on_tie_check = 0; // when a team "wins", countdown for a bit and wait... int current_round_length = 0; // frames that the current team round has lasted int round_delay_time = 0; // time gap between round end and new round team_t teams[TEAM_TOP]; int teamCount = 2; #define MAX_SPAWNS 512 // max DM spawn points supported edict_t *potential_spawns[MAX_SPAWNS]; int num_potential_spawns; edict_t *teamplay_spawns[MAX_TEAMS]; trace_t trace_t_temp; // used by our trace replace macro in ax_team.h int num_teams = 3; // teams in current game, fixed at 2 for now... // <TNG:Freud New spawning variables> int NS_num_used_farteamplay_spawns[MAX_TEAMS]; int NS_num_potential_spawns[MAX_TEAMS]; edict_t *NS_potential_spawns[MAX_TEAMS][MAX_SPAWNS]; edict_t *NS_used_farteamplay_spawns[MAX_TEAMS][MAX_SPAWNS]; int NS_randteam; // </TNG:Freud> transparent_list_t *transparent_list = NULL; void CreditsMenu (edict_t * ent, pmenu_t * p); void InitTransparentList () { if (transparent_list != NULL) { transparent_list_t *p, *q; p = transparent_list; while (p != NULL) { q = p->next; gi.TagFree(p); p = q; } transparent_list = NULL; } } void AddToTransparentList (edict_t * ent) { transparent_list_t *p, *n; n = (transparent_list_t *) gi.TagMalloc (sizeof (transparent_list_t), TAG_GAME); if (n == NULL) { gi.dprintf ("Out of memory\n"); exit (1); } n->ent = ent; n->next = NULL; if (transparent_list == NULL) { transparent_list = n; } else { p = transparent_list; while (p->next != NULL) { p = p->next; } p->next = n; } } void RemoveFromTransparentList (edict_t * ent) { transparent_list_t *p, *q, *r; if (transparent_list != NULL) { if (transparent_list->ent == ent) { q = transparent_list->next; gi.TagFree (transparent_list); transparent_list = q; return; } else { p = transparent_list; q = p->next; while (q != NULL) { if (q->ent == ent) { r = q->next; gi.TagFree (q); p->next = r; return; } p = p->next; q = p->next; } } } gi.dprintf("Warning: attempt to RemoveFromTransparentList when not in it\n"); } void TransparentListSet (solid_t solid_type) { transparent_list_t *p = transparent_list; while (p != NULL) { p->ent->solid = solid_type; gi.linkentity (p->ent); p = p->next; } } void ReprintMOTD (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); PrintMOTD (ent); } void JoinTeamAuto (edict_t * ent, pmenu_t * p) { int i, team = TEAM1, num1 = 0, num2 = 0, num3 = 0, score1, score2, score3; for (i = 0; i < (int)maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].resp.team == TEAM1) num1++; else if (game.clients[i].resp.team == TEAM2) num2++; else if (game.clients[i].resp.team == TEAM3) num3++; } score1 = teams[TEAM1].score; score2 = teams[TEAM2].score; score3 = teams[TEAM3].score; if(ctf->value) { CTFCalcScores(); GetCTFScores(&score1, &score2); } /* there are many different things to consider when selecting a team */ if (num1 > num2 || (num1 == num2 && score1 > score2)) team = TEAM2; if (use_3teams->value) { if (team == TEAM1) { if (num1 > num3 || (num1 == num3 && score1 > score3)) team = TEAM3; } else { if (num2 > num3 || (num2 == num3 && score2 > score3)) team = TEAM3; } } JoinTeam(ent, team, 0); } void JoinTeam1 (edict_t * ent, pmenu_t * p) { JoinTeam (ent, TEAM1, 0); } void JoinTeam2 (edict_t * ent, pmenu_t * p) { JoinTeam (ent, TEAM2, 0); } void JoinTeam3 (edict_t * ent, pmenu_t * p) { if (use_3teams->value) JoinTeam (ent, TEAM3, 0); } void LeaveTeams (edict_t * ent, pmenu_t * p) { LeaveTeam (ent); PMenu_Close (ent); OpenJoinMenu (ent); } void SelectWeapon2 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(MP5_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/mp5slide.wav"), 1.0); } void SelectWeapon3 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(M3_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/m3in.wav"), 1.0); } void SelectWeapon4 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(HC_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/cclose.wav"), 1.0); } void SelectWeapon5 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(SNIPER_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/ssgbolt.wav"), 1.0); } void SelectWeapon6 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(M4_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/m4a1slide.wav"), 1.0); } void SelectWeapon0 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(KNIFE_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/stab.wav"), 1.0); } void SelectWeapon9 (edict_t * ent, pmenu_t * p) { ent->client->resp.weapon = GET_ITEM(DUAL_NUM); PMenu_Close (ent); OpenItemMenu (ent); //PG BUND unicastSound(ent, gi.soundindex("weapons/mk23slide.wav"), 1.0); } void SelectItem1 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(KEV_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/veston.wav"), 1.0); } void SelectItem2 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(LASER_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/lasersight.wav"), 1.0); } void SelectItem3 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(SLIP_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/veston.wav"), 1.0); } void SelectItem4 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(SIL_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/screw.wav"), 1.0); } void SelectItem5 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(BAND_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/veston.wav"), 1.0); } void SelectItem6 (edict_t * ent, pmenu_t * p) { ent->client->resp.item = GET_ITEM(HELM_NUM); PMenu_Close (ent); //PG BUND unicastSound(ent, gi.soundindex("misc/veston.wav"), 1.0); } void CreditsReturnToMain (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); if (teamplay->value) { OpenJoinMenu (ent); } } //PG BUND BEGIN void DoAGoodie (edict_t * ent, pmenu_t * p) { //PG BUND unicastSound(ent, gi.soundindex("boss3/bs3idle1.wav"), 1.0); //stuffcmd (ent, "play boss3/bs3idle1.wav"); } //PG BUND END // AQ2:TNG - Igor adding the Rock-Sound ;-) void RockClan (edict_t * ent, pmenu_t * p) { gi.cprintf (ent, PRINT_HIGH, "Let's Rock! http://www.rock-clan.de/\n"); //PG BUND unicastSound(ent, gi.soundindex("user/letsrock.wav"), 1.0); //stuffcmd (ent, "play user/letsrock.wav"); } // AQ2:TNG - End Rock-Sound // AQ2:TNG Deathwatch - Just for slicer :) void SlicersCat (edict_t * ent, pmenu_t * p) { gi.cprintf (ent, PRINT_HIGH, "sLiCeR [dW] couldn't have done it without his cat!\n"); //PG BUND unicastSound(ent, gi.soundindex("makron/laf4.wav"), 1.0); //stuffcmd (ent, "play makron/laf4.wav"); } // AQ2:TNG End // AQ2:TNG Deathwatch - Just for QNI ppl void QuakeNigguhz (edict_t * ent, pmenu_t * p) { gi.cprintf (ent, PRINT_HIGH, "For all the homies!\n"); //PG BUND unicastSound(ent, gi.soundindex("world/xian1.wav"), 1.0); //stuffcmd (ent, "play world/xian1.wav"); } // AQ2:TNG Deathwatch - Editing all menus to show the correct credits, version, names, locations, urls, etc pmenu_t creditsmenu[] = { {"*" TNG_VERSION, PMENU_ALIGN_CENTER, NULL, NULL}, {"¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ", PMENU_ALIGN_CENTER, NULL, NULL}, {"*Design Team", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"Deathwatch", PMENU_ALIGN_LEFT, NULL, DoAGoodie}, {"Elviz", PMENU_ALIGN_LEFT, NULL, DoAGoodie}, {"Freud [QNI]", PMENU_ALIGN_LEFT, NULL, QuakeNigguhz}, {"Igor[Rock]", PMENU_ALIGN_LEFT, NULL, RockClan}, {"JBravo[QNI]", PMENU_ALIGN_LEFT, NULL, QuakeNigguhz}, {"sLiCeR [dW]", PMENU_ALIGN_LEFT, NULL, SlicersCat}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"*Credits", PMENU_ALIGN_LEFT, NULL, NULL}, {"(in no particular order)", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"Clan Rock, dW, QNI & DP,", PMENU_ALIGN_LEFT, NULL, NULL}, {"Kobra, Zarjazz,", PMENU_ALIGN_LEFT, NULL, NULL}, {"Killerbee, Rookie[Rock],", PMENU_ALIGN_LEFT, NULL, NULL}, {"PG Bund[Rock], Mort,", PMENU_ALIGN_LEFT, NULL, NULL}, {"ICE-M, Palmtree,", PMENU_ALIGN_LEFT, NULL, NULL}, {"Tempfile, Blackmonk,", PMENU_ALIGN_LEFT, NULL, NULL}, {"Dome, Papst, Apr/ Maniac", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"Return to main menu", PMENU_ALIGN_LEFT, NULL, CreditsReturnToMain}, {"TAB to exit menu", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"v" ACTION_VERSION, PMENU_ALIGN_RIGHT, NULL, NULL}, //PG BUND END }; pmenu_t weapmenu[] = { {"*" TNG_VERSION, PMENU_ALIGN_CENTER, NULL, NULL}, {"¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ", PMENU_ALIGN_CENTER, NULL, NULL}, {"Select your Weapon", PMENU_ALIGN_CENTER, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, //AQ2:TNG - Igor adding wp_flags {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "MP5/10 Submachinegun", SelectWeapon2 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "M3 Super90 Assault Shotgun", SelectWeapon3 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Handcannon", SelectWeapon4 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "SSG 3000 Sniper Rifle", SelectWeapon5 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "M4 Assault Rifle", SelectWeapon6 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Combat Knives", SelectWeapon0 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Akimbo Pistols", SelectWeapon9 //AQ2:TNG End adding wp_flags {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, //AQ2:TNG - Slicer: changing this //{"Leave Team", PMENU_ALIGN_LEFT, NULL, LeaveTeams}, {"Return to Main Menu", PMENU_ALIGN_LEFT, NULL, CreditsReturnToMain}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, //AQ2:TNG END {"Use [ and ] to move cursor", PMENU_ALIGN_LEFT, NULL, NULL}, {"ENTER to select", PMENU_ALIGN_LEFT, NULL, NULL}, {"TAB to exit menu", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"v" ACTION_VERSION, PMENU_ALIGN_RIGHT, NULL, NULL}, }; pmenu_t itemmenu[] = { {"*" TNG_VERSION, PMENU_ALIGN_CENTER, NULL, NULL}, {"¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ", PMENU_ALIGN_CENTER, NULL, NULL}, {"Select your Item", PMENU_ALIGN_CENTER, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, //AQ2:TNG Igor adding itm_flags {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Kevlar Vest", SelectItem1 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Laser Sight", SelectItem2 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Stealth Slippers", SelectItem3 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Silencer", SelectItem4 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Bandolier", SelectItem5 {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, // "Kevlar Helmet", SelectItem6 //AQ2:TNG end adding itm_flags {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"Use [ and ] to move cursor", PMENU_ALIGN_LEFT, NULL, NULL}, {"ENTER to select", PMENU_ALIGN_LEFT, NULL, NULL}, {"TAB to exit menu", PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"v" ACTION_VERSION, PMENU_ALIGN_RIGHT, NULL, NULL}, }; //AQ2:TNG - slicer void VotingMenu (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); vShowMenu (ent, ""); } //AQ2:TNG END pmenu_t joinmenu[] = { {"*" TNG_VERSION, PMENU_ALIGN_CENTER, NULL, NULL}, {"¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ", PMENU_ALIGN_CENTER, NULL, NULL}, {NULL /* lvl name */ , PMENU_ALIGN_CENTER, NULL, NULL}, {NULL, PMENU_ALIGN_CENTER, NULL, NULL}, {NULL /* team 1 */ , PMENU_ALIGN_LEFT, NULL, JoinTeam1}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {NULL /* team 2 */ , PMENU_ALIGN_LEFT, NULL, JoinTeam2}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {NULL /* team 3 */ , PMENU_ALIGN_LEFT, NULL, JoinTeam3}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {NULL /* auto-join */ , PMENU_ALIGN_LEFT, NULL, JoinTeamAuto}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, //AQ2:TNG - Slicer {"Voting & Ignoring Menus", PMENU_ALIGN_LEFT, NULL, VotingMenu}, //AQ2:TNG END {"MOTD", PMENU_ALIGN_LEFT, NULL, ReprintMOTD}, {"Credits", PMENU_ALIGN_LEFT, NULL, CreditsMenu}, {NULL, PMENU_ALIGN_LEFT, NULL, NULL}, {"Use [ and ] to move cursor", PMENU_ALIGN_LEFT, NULL, NULL}, {"ENTER to select", PMENU_ALIGN_LEFT, NULL, NULL}, {"TAB to exit menu", PMENU_ALIGN_LEFT, NULL, NULL}, {"v" ACTION_VERSION, PMENU_ALIGN_RIGHT, NULL, NULL}, }; // AQ2:TNG End void CreditsMenu (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); PMenu_Open (ent, creditsmenu, 4, sizeof (creditsmenu) / sizeof (pmenu_t)); unicastSound(ent, gi.soundindex("world/elv.wav"), 1.0); } char *TeamName (int team) { if (team >= TEAM1 && team <= TEAM3) return teams[team].name; else return "None"; } void AssignSkin (edict_t * ent, const char *s, qboolean nickChanged) { int playernum = ent - g_edicts - 1; char *p; char t[MAX_SKINLEN], skin[64] = "\0"; if (ctf->value && !matchmode->value) { Q_strncpyz(t, s, sizeof(t)); // forcing CTF model if(ctf_model->string[0]) { /* copy at most bytes that the skin name itself fits in with the delimieter and NULL */ strncpy(t, ctf_model->string, MAX_SKINLEN-strlen(CTF_TEAM1_SKIN)-2); strcat(t, "/"); } if ((p = strrchr (t, '/')) != NULL) p[1] = 0; else strcpy (t, "male/"); switch (ent->client->resp.team) { case TEAM1: Com_sprintf(skin, sizeof(skin), "%s\\%s%s", ent->client->pers.netname, t, CTF_TEAM1_SKIN); break; case TEAM2: Com_sprintf(skin, sizeof(skin), "%s\\%s%s", ent->client->pers.netname, t, CTF_TEAM2_SKIN); break; default: Com_sprintf(skin, sizeof(skin), "%s\\%s", ent->client->pers.netname, "male/grunt"); break; } } else { switch (ent->client->resp.team) { case TEAM1: case TEAM2: case TEAM3: Com_sprintf(skin, sizeof(skin), "%s\\%s", ent->client->pers.netname, teams[ent->client->resp.team].skin); break; default: Com_sprintf(skin, sizeof(skin), "%s\\%s", ent->client->pers.netname, (teamplay->value ? "male/grunt" : s)); break; } } gi.configstring(CS_PLAYERSKINS + playernum, skin); } void Team_f (edict_t * ent) { char *t; int desired_team = NOTEAM; char team[24]; //PG BUND - BEGIN (Tourney extension) if (use_tourney->value) { gi.cprintf (ent, PRINT_MEDIUM, "Currently running tourney mod, team selection is disabled."); return; } //PG BUND - END (Tourney extension) Q_strncpyz(team, gi.args(), sizeof(team)); t = team; // t = gi.args (); if (!*t) { if (ctf->value) { gi.cprintf (ent, PRINT_HIGH, "You are on %s.\n", CTFTeamName (ent->client->resp.team)); return; } else { gi.cprintf (ent, PRINT_HIGH, "You are on %s.\n", TeamName (ent->client->resp.team)); return; } } if ((int)(realLtime*10.0f) < (ent->client->resp.joined_team + 50)) { gi.cprintf (ent, PRINT_HIGH, "You must wait 5 seconds before changing teams again.\n"); return; } if (Q_stricmp (t, "none") == 0) { if (ent->client->resp.team == NOTEAM) gi.cprintf (ent, PRINT_HIGH, "You're not on a team.\n"); else LeaveTeam (ent); return; } if (Q_stricmp (t, "1") == 0) desired_team = TEAM1; else if (Q_stricmp (t, "2") == 0) desired_team = TEAM2; else if (Q_stricmp (t, teams[TEAM1].name) == 0) desired_team = TEAM1; else if (Q_stricmp (t, teams[TEAM2].name) == 0) desired_team = TEAM2; else if (use_3teams->value) { if (Q_stricmp (t, "3") == 0) desired_team = TEAM3; else if (Q_stricmp (t, teams[TEAM3].name) == 0) desired_team = TEAM3; } else if (ctf->value) { if (Q_stricmp (t, "red") == 0) desired_team = TEAM1; else if (Q_stricmp (t, "blue") == 0) desired_team = TEAM2; } if(desired_team == NOTEAM) { gi.cprintf (ent, PRINT_HIGH, "Unknown team %s.\n", t); return; } if (ent->client->resp.team == desired_team) { gi.cprintf (ent, PRINT_HIGH, "You are already on %s.\n", TeamName (ent->client->resp.team)); return; } JoinTeam (ent, desired_team, 1); } void JoinTeam (edict_t * ent, int desired_team, int skip_menuclose) { char *s, *a; char temp[128]; if (!skip_menuclose) PMenu_Close (ent); if (ent->client->resp.team == desired_team) return; if (matchmode->value && mm_allowlock->value && teams[desired_team].locked) { if (skip_menuclose) gi.cprintf(ent, PRINT_HIGH, "Cannot join %s (locked)\n", TeamName(desired_team)); else gi.centerprintf(ent, "Cannot join %s (locked)", TeamName(desired_team)); return; } if(!matchmode->value && eventeams->value && desired_team != NOTEAM) { if(!IsAllowedToJoin(ent, desired_team)) { gi.centerprintf(ent, "Cannot join %s (has too many players)", TeamName(desired_team)); return; } } a = (ent->client->resp.team == NOTEAM) ? "joined" : "changed to"; ent->client->resp.team = desired_team; s = Info_ValueForKey (ent->client->pers.userinfo, "skin"); AssignSkin (ent, s, false); if (ent->solid != SOLID_NOT) // alive, in game { if (punishkills->value) { if (ent->client->attacker && ent->client->attacker->client && (ent->client->attacker->client != ent->client)) { char deathmsg[64]; Com_sprintf(deathmsg, sizeof(deathmsg), "%s ph34rs %s so much %s committed suicide! :)\n", ent->client->pers.netname, ent->client->attacker->client->pers.netname, ent->client->resp.radio_gender ? "she" : "he"); PrintDeathMessage(deathmsg, ent); IRC_printf (IRC_T_DEATH, deathmsg); if(team_round_going || !OnSameTeam(ent, ent->client->attacker)) { Add_Frag (ent->client->attacker); Subtract_Frag (ent); ent->client->resp.deaths++; } } } ent->health = 0; player_die (ent, ent, ent, 100000, vec3_origin); ent->deadflag = DEAD_DEAD; } if (ctf->value) { ent->flags &= ~FL_GODMODE; ent->client->resp.ctf_state = CTF_STATE_START; gi.bprintf (PRINT_HIGH, "%s %s %s.\n", ent->client->pers.netname, a, CTFTeamName (desired_team)); IRC_printf (IRC_T_GAME, "%n %s %n.", ent->client->pers.netname, a, CTFTeamName (desired_team)); } else { if(teamdm->value) ent->flags &= ~FL_GODMODE; gi.bprintf (PRINT_HIGH, "%s %s %s.\n", ent->client->pers.netname, a, TeamName (desired_team)); IRC_printf (IRC_T_GAME, "%n %s %n.", ent->client->pers.netname, a, TeamName (desired_team)); } ent->client->resp.joined_team = (int)(realLtime*10.0f); //AQ2:TNG - Slicer added the ctf->value coz teamplay people were spawning.... if ((ctf->value || teamdm->value) && team_round_going && (ent->inuse && ent->client->resp.team != NOTEAM)) { // ent->client->resp.last_killed_target = NULL; ResetKills (ent); //AQ2:TNG Slicer Last Damage Location ent->client->resp.last_damaged_part = 0; ent->client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END PutClientInServer (ent); AddToTransparentList (ent); } //AQ2:TNG - Slicer Matchmode if (matchmode->value) { if (ent->client->resp.captain) { if(teamdm->value || ctf->value) { if(!team_round_going) teams[ent->client->resp.captain].ready = 0; teams[ent->client->resp.captain].locked = 0; } else { Com_sprintf(temp, sizeof(temp),"%s is no longer ready to play!", teams[ent->client->resp.captain].name); CenterPrintAll(temp); teams[ent->client->resp.captain].ready = 0; } } ent->client->resp.subteam = 0; //SLICER: If a player joins or changes teams, the subteam resets.... ent->client->resp.captain = 0; //SLICER: Same here } //AQ2:TNG END if (!skip_menuclose && (!teamdm->value || dm_choose->value) && ctf->value != 2) OpenWeaponMenu (ent); } void LeaveTeam (edict_t * ent) { char *g; char temp[128]; if (ent->client->resp.team == NOTEAM) return; if (ent->solid != SOLID_NOT) // alive, in game { if (punishkills->value) { if (ent->client->attacker && ent->client->attacker->client && (ent->client->attacker->client != ent->client)) { char deathmsg[64]; Com_sprintf(deathmsg, sizeof(deathmsg), "%s ph34rs %s so much %s committed suicide! :)\n", ent->client->pers.netname, ent->client->attacker->client->pers.netname, ent->client->resp.radio_gender ? "she" : "he"); PrintDeathMessage(deathmsg, ent); IRC_printf (IRC_T_DEATH, deathmsg); if(team_round_going || !OnSameTeam(ent, ent->client->attacker)) { Add_Frag (ent->client->attacker); Subtract_Frag (ent); ent->client->resp.deaths++; } } } ent->health = 0; player_die (ent, ent, ent, 100000, vec3_origin); ent->deadflag = DEAD_DEAD; } if (IsNeutral (ent)) g = "its"; else if (IsFemale (ent)) g = "her"; else g = "his"; gi.bprintf (PRINT_HIGH, "%s left %s team.\n", ent->client->pers.netname, g); IRC_printf (IRC_T_GAME, "%n left %n team.", ent->client->pers.netname, g); ent->client->resp.joined_team = 0; ent->client->resp.team = NOTEAM; //AQ2:TNG Slicer if (matchmode->value) { if (ent->client->resp.captain) { if(teamdm->value || ctf->value) { if(!team_round_going) teams[ent->client->resp.captain].ready = 0; teams[ent->client->resp.captain].locked = 0; } else { Com_sprintf(temp, sizeof(temp),"%s is no longer ready to play!", teams[ent->client->resp.captain].name); CenterPrintAll(temp); teams[ent->client->resp.captain].ready = 0; } } ent->client->resp.subteam = 0; //SLICER: If a player joins or changes teams, the subteam resets.... ent->client->resp.captain = 0; //SLICER: Same here } //AQ2:TNG END } void ReturnToMain (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); OpenJoinMenu (ent); } void OpenItemMenu (edict_t * ent) { //AQ2:TNG - Igor adding itm_flags static char *menu_itemnames[] = { "Kevlar Vest", "Laser Sight", "Stealth Slippers", "Silencer", "Bandolier", "Kevlar Helmet" }; int pos; if (itm_flags->value != 0) { pos = 4; if ((int)itm_flags->value & ITF_KEV) { itemmenu[pos].text = menu_itemnames[0]; itemmenu[pos].SelectFunc = SelectItem1; pos++; } if ((int)itm_flags->value & ITF_LASER) { itemmenu[pos].text = menu_itemnames[1]; itemmenu[pos].SelectFunc = SelectItem2; pos++; } if ((int)itm_flags->value & ITF_SLIP) { itemmenu[pos].text = menu_itemnames[2]; itemmenu[pos].SelectFunc = SelectItem3; pos++; } if ((int)itm_flags->value & ITF_SIL) { itemmenu[pos].text = menu_itemnames[3]; itemmenu[pos].SelectFunc = SelectItem4; pos++; } if ((int)itm_flags->value & ITF_BAND) { itemmenu[pos].text = menu_itemnames[4]; itemmenu[pos].SelectFunc = SelectItem5; pos++; } if ((int)itm_flags->value & ITF_HELM) { itemmenu[pos].text = menu_itemnames[5]; itemmenu[pos].SelectFunc = SelectItem6; pos++; } for (; pos < 10; pos++) { itemmenu[pos].text = NULL; itemmenu[pos].SelectFunc = NULL; } //AQ2:TNG End adding itm_flags PMenu_Open (ent, itemmenu, 4, sizeof (itemmenu) / sizeof (pmenu_t)); } else { PMenu_Close (ent); } } void OpenWeaponMenu (edict_t * ent) { //AQ2:TNG - Igor adding wp_flags static char *menu_weapnames[] = { "MP5/10 Submachinegun", "M3 Super90 Assault Shotgun", "Handcannon", "SSG 3000 Sniper Rifle", "M4 Assault Rifle", "Combat Knives", "Akimbo Pistols" }; int pos; if ((int) wp_flags->value & ~(WPF_MK23 | WPF_GRENADE)) { pos = 4; if ((int) wp_flags->value & WPF_MP5) { weapmenu[pos].text = menu_weapnames[0]; weapmenu[pos].SelectFunc = SelectWeapon2; pos++; } if ((int) wp_flags->value & WPF_M3) { weapmenu[pos].text = menu_weapnames[1]; weapmenu[pos].SelectFunc = SelectWeapon3; pos++; } if ((int) wp_flags->value & WPF_HC) { weapmenu[pos].text = menu_weapnames[2]; weapmenu[pos].SelectFunc = SelectWeapon4; pos++; } if ((int) wp_flags->value & WPF_SNIPER) { weapmenu[pos].text = menu_weapnames[3]; weapmenu[pos].SelectFunc = SelectWeapon5; pos++; } if ((int) wp_flags->value & WPF_M4) { weapmenu[pos].text = menu_weapnames[4]; weapmenu[pos].SelectFunc = SelectWeapon6; pos++; } if ((int) wp_flags->value & WPF_KNIFE) { weapmenu[pos].text = menu_weapnames[5]; weapmenu[pos].SelectFunc = SelectWeapon0; pos++; } if ((int) wp_flags->value & WPF_DUAL) { weapmenu[pos].text = menu_weapnames[6]; weapmenu[pos].SelectFunc = SelectWeapon9; pos++; } for (; pos < 11; pos++) { weapmenu[pos].text = NULL; weapmenu[pos].SelectFunc = NULL; } PMenu_Open (ent, weapmenu, 4, sizeof (weapmenu) / sizeof (pmenu_t)); } else { OpenItemMenu (ent); } //AQ2:TNG End adding wp_flags } // AQ2:TNG Deathwatch - Updated this for the new menu int UpdateJoinMenu (edict_t * ent) { static char levelname[28]; static char team1players[28]; static char team2players[28]; static char team3players[28]; int num1 = 0, num2 = 0, num3 = 0, i; if (ctf->value) { joinmenu[4].text = "Join Red Team"; joinmenu[4].SelectFunc = JoinTeam1; joinmenu[6].text = "Join Blue Team"; joinmenu[6].SelectFunc = JoinTeam2; joinmenu[8].text = NULL; joinmenu[8].SelectFunc = NULL; if (ctf_forcejoin->string && *ctf_forcejoin->string) { if (Q_stricmp (ctf_forcejoin->string, "red") == 0) { joinmenu[6].text = NULL; joinmenu[6].SelectFunc = NULL; } else if (Q_stricmp (ctf_forcejoin->string, "blue") == 0) { joinmenu[4].text = NULL; joinmenu[4].SelectFunc = NULL; } } } else { joinmenu[4].text = teams[TEAM1].name; joinmenu[4].SelectFunc = JoinTeam1; joinmenu[6].text = teams[TEAM2].name; joinmenu[6].SelectFunc = JoinTeam2; if (use_3teams->value) { joinmenu[8].text = teams[TEAM3].name; joinmenu[8].SelectFunc = JoinTeam3; } else { joinmenu[8].text = NULL; joinmenu[8].SelectFunc = NULL; } } joinmenu[11].text = "Auto-join team"; joinmenu[11].SelectFunc = JoinTeamAuto; levelname[0] = '*'; if (g_edicts[0].message) Q_strncpyz(levelname + 1, g_edicts[0].message, sizeof(levelname) - 1); else Q_strncpyz(levelname + 1, level.mapname, sizeof(levelname) - 1); for (i = 0; i < (int)maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].resp.team == TEAM1) num1++; else if (game.clients[i].resp.team == TEAM2) num2++; else if (game.clients[i].resp.team == TEAM3) num3++; } sprintf (team1players, " (%d players)", num1); sprintf (team2players, " (%d players)", num2); sprintf (team3players, " (%d players)", num3); joinmenu[2].text = levelname; if (joinmenu[4].text) joinmenu[5].text = team1players; else joinmenu[5].text = NULL; if (joinmenu[6].text) joinmenu[7].text = team2players; else joinmenu[7].text = NULL; if (joinmenu[8].text && use_3teams->value) joinmenu[9].text = team3players; else joinmenu[9].text = NULL; } // AQ2:TNG END void OpenJoinMenu (edict_t * ent) { //PG BUND - BEGIN (Tourney extension) if (use_tourney->value) { OpenWeaponMenu (ent); return; } //PG BUND - END (Tourney extension) UpdateJoinMenu (ent); PMenu_Open (ent, joinmenu, 11 /* magic for Auto-join menu item */, sizeof (joinmenu) / sizeof (pmenu_t)); } int member_array (char *str, char *arr[], int num_elems) { int l; for (l = 0; l < num_elems; l++) { if (!strcmp (str, arr[l])) return l; } return -1; } void CleanLevel () { char *remove_classnames[] = { "weapon_Mk23", "weapon_MP5", "weapon_M4", "weapon_M3", "weapon_HC", "weapon_Sniper", "weapon_Dual", "weapon_Knife", "weapon_Grenade", "ammo_sniper", "ammo_clip", "ammo_mag", "ammo_m4", "ammo_m3", "item_quiet", "item_slippers", "item_band", "item_lasersight", "item_vest", "thrown_knife", "hgrenade", "item_helmet" }; int i; int base; edict_t *ent; base = 1 + maxclients->value + BODY_QUEUE_SIZE; ent = g_edicts + base; for (i = 1 + maxclients->value + BODY_QUEUE_SIZE; i < globals.num_edicts; i++, ent++) { if (!ent->classname) continue; if (member_array (ent->classname, remove_classnames, sizeof (remove_classnames) / sizeof (char *)) > -1) { G_FreeEdict (ent); } } CleanBodies (); // fix glass CGF_SFX_RebuildAllBrokenGlass (); } void MakeAllLivePlayersObservers(void); void ResetScores (qboolean playerScores) { int i; edict_t *ent; team_round_going = team_round_countdown = team_game_going = 0; current_round_length = matchtime = 0; pause_time = 0; num_ghost_players = 0; MakeAllLivePlayersObservers (); for(i = TEAM1; i < TEAM_TOP; i++) { teams[i].score = teams[i].total = 0; teams[i].ready = teams[i].locked = 0; teams[i].pauses_used = teams[i].wantReset = 0; gi.cvar_forceset(teams[i].teamscore->name, "0"); } if(!playerScores) return; for (i = 0; i < game.maxclients; i++) { ent = g_edicts + 1 + i; if (!ent->inuse) continue; ent->client->resp.score = 0; ent->client->resp.kills = 0; ent->client->resp.damage_dealt = 0; ent->client->resp.hs_streak = 0; ent->client->resp.streak = 0; ent->client->resp.ctf_capstreak = 0; ent->client->resp.last_damaged_part = 0; ent->client->resp.last_damaged_players[0] = '\0'; ent->client->resp.deaths = 0; ent->client->resp.killed_teammates = 0; ent->enemy = NULL; ResetKills(ent); ResetStats(ent); } } qboolean StartClient (edict_t * ent) { if (ent->client->resp.team != NOTEAM) return false; // start as 'observer' ent->movetype = MOVETYPE_NOCLIP; ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->client->resp.team = NOTEAM; ent->client->ps.gunindex = 0; gi.linkentity (ent); // Disabled so people can read the motd // OpenJoinMenu(ent); return true; } void CenterPrintAll (const char *msg) { int i; edict_t *ent; gi.cprintf (NULL, PRINT_HIGH, "%s\n", msg); // so it goes to the server console... for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (ent->inuse) gi.centerprintf (ent, "%s", msg); } } int TeamHasPlayers (int team) { int i, players; edict_t *ent; players = 0; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse) continue; if (game.clients[i].resp.team == team) players++; } return players; } qboolean BothTeamsHavePlayers () { int players[TEAM_TOP] = {0}, i; edict_t *ent; //AQ2:TNG Slicer Matchmode if (matchmode->value && !TeamsReady()) return false; //AQ2:TNG END if (use_tourney->value) return (LastOpponent > 1); for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse || game.clients[i].resp.team == NOTEAM) continue; if (!game.clients[i].resp.subteam) players[game.clients[i].resp.team]++; } if (use_3teams->value) return ((players[1] && players[2]) || (players[1] && players[3]) || (players[2] && players[3])); return (players[1] && players[2]); } // CheckForWinner: Checks for a winner (or not). int CheckForWinner () { int players[TEAM_TOP] = {0}, i; edict_t *ent; if(ctf->value || teamdm->value) return WINNER_NONE; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse || game.clients[i].resp.team == NOTEAM) continue; if (ent->solid != SOLID_NOT) players[game.clients[i].resp.team]++; } if (players[1] && players[2]) return WINNER_NONE; if (use_3teams->value && ((players[1] && players[3]) || (players[2] && players[3]))) return WINNER_NONE; for(i=TEAM1; i<=teamCount; i++) if(players[i]) return i; return WINNER_TIE; } // CheckForForcedWinner: A winner is being forced, find who it is. int CheckForForcedWinner() { int onteam1 = 0, onteam2 = 0, onteam3 = 0, i; int health1 = 0, health2 = 0, health3 = 0; edict_t *ent; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse) continue; if (game.clients[i].resp.team == TEAM1 && ent->solid != SOLID_NOT) { onteam1++; health1 += ent->health; } else if (game.clients[i].resp.team == TEAM2 && ent->solid != SOLID_NOT) { onteam2++; health2 += ent->health; } else if (game.clients[i].resp.team == TEAM3 && ent->solid != SOLID_NOT) { onteam3++; health3 += ent->health; } } if (use_3teams->value) { if (onteam1 > onteam2) { if (onteam1 > onteam3) return WINNER_TEAM1; else if (onteam3 > onteam1) return WINNER_TEAM3; else if (health1 > health3) return WINNER_TEAM1; else if (health3 > health1) return WINNER_TEAM3; else return WINNER_TIE; } else if (onteam2 > onteam1) { if (onteam2 > onteam3) return WINNER_TEAM2; else if (onteam3 > onteam2) return WINNER_TEAM3; else if (health2 > health3) return WINNER_TEAM2; else if (health3 > health2) return WINNER_TEAM3; else return WINNER_TIE; } else if (onteam1 == onteam2 && onteam1 > onteam3) { if (health1 > health2) return WINNER_TEAM1; else if (health2 > health1) return WINNER_TEAM2; else return WINNER_TIE; } else if (onteam3 > onteam1) return WINNER_TEAM3; if (health1 > health2) { if (health1 > health3) return WINNER_TEAM1; else if (health3 > health1) return WINNER_TEAM3; } else if (health2 > health1) { if (health2 > health3) return WINNER_TEAM2; else if (health3 > health2) return WINNER_TEAM3; } else if (health3 > health1) return WINNER_TEAM3; } else { if (onteam1 > onteam2) return WINNER_TEAM1; else if (onteam2 > onteam1) return WINNER_TEAM2; if (health1 > health2) return WINNER_TEAM1; else if (health2 > health1) return WINNER_TEAM2; } return WINNER_TIE; } void SpawnPlayers () { int i; edict_t *ent; if(!ctf->value && !teamdm->value) { if (!use_oldspawns->value) NS_SetupTeamSpawnPoints (); else SetupTeamSpawnPoints (); } InitTransparentList (); for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (ent->inuse && ent->client->resp.team != NOTEAM && ent->client->resp.subteam == 0) { // ent->client->resp.last_killed_target = NULL; ResetKills (ent); //AQ2:TNG Slicer Last Damage Location ent->client->resp.last_damaged_part = 0; ent->client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END PutClientInServer (ent); AddToTransparentList (ent); } } if(matchmode->value && limchasecam->value) { for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (ent->inuse && ent->client->resp.team != NOTEAM && ent->client->resp.subteam) { ent->client->chase_target = NULL; GetChaseTarget (ent); if (ent->client->chase_target != NULL) { if (limchasecam->value == 2) { ent->client->chase_mode = 1; UpdateChaseCam (ent); ent->client->chase_mode = 2; } else { ent->client->chase_mode = 1; } UpdateChaseCam (ent); } } } } } void StartRound () { team_round_going = 1; current_round_length = 0; } void StartLCA () { if(!teamdm->value && ctf->value != 2) CleanLevel (); if (use_tourney->value) { lights_camera_action = TourneySetTime (T_SPAWN); TourneyTimeEvent (T_SPAWN, lights_camera_action); } else { CenterPrintAll ("LIGHTS..."); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("atl/lights.wav"), 1.0, ATTN_NONE, 0.0); lights_camera_action = 43; // TempFile changed from 41 } SpawnPlayers (); } // FindOverlap: Find the first (or next) overlapping player for ent. edict_t *FindOverlap (edict_t * ent, edict_t * last_overlap) { int i; edict_t *other; vec3_t diff; for (i = last_overlap ? last_overlap - g_edicts : 0; i < game.maxclients; i++) { other = &g_edicts[i + 1]; if (!other->inuse || other->client->resp.team == NOTEAM || other == ent || other->solid == SOLID_NOT || other->deadflag == DEAD_DEAD) continue; VectorSubtract (ent->s.origin, other->s.origin, diff); if (diff[0] >= -33 && diff[0] <= 33 && diff[1] >= -33 && diff[1] <= 33 && diff[2] >= -65 && diff[2] <= 65) return other; } return NULL; } void ContinueLCA () { if (use_tourney->value) { TourneyTimeEvent (T_SPAWN, lights_camera_action); if (lights_camera_action == 1) { StartRound (); } } else { if (lights_camera_action == 23) { CenterPrintAll ("CAMERA..."); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("atl/camera.wav"), 1.0, ATTN_NONE, 0.0); } else if (lights_camera_action == 3) { CenterPrintAll ("ACTION!"); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("atl/action.wav"), 1.0, ATTN_NONE, 0.0); } else if (lights_camera_action == 1) { StartRound (); } } lights_camera_action--; } void MakeAllLivePlayersObservers () { edict_t *ent; int saveteam, i; /* if someone is carrying a flag it will disappear */ if(ctf->value) CTFResetFlags(); for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse) continue; if(ent->solid == SOLID_NOT && ((!teamdm->value && !ctf->value) || ent->client->resp.team == NOTEAM || ent->client->resp.subteam)) continue; saveteam = ent->client->resp.team; ent->client->resp.team = NOTEAM; PutClientInServer (ent); ent->client->resp.team = saveteam; } } // PrintScores: Prints the current score on the console void PrintScores (void) { if (use_3teams->value) { gi.bprintf (PRINT_HIGH, "Current score is %s: %d to %s: %d to %s: %d\n", TeamName (TEAM1), teams[TEAM1].score, TeamName (TEAM2), teams[TEAM2].score, TeamName (TEAM3), teams[TEAM3].score); IRC_printf (IRC_T_TOPIC, "Current score on map %n is %n: %k to %n: %k to %n: %k", level.mapname, TeamName (TEAM1), teams[TEAM1].score, TeamName (TEAM2), teams[TEAM2].score, TeamName (TEAM3), teams[TEAM3].score); } else { gi.bprintf (PRINT_HIGH, "Current score is %s: %d to %s: %d\n", TeamName (TEAM1), teams[TEAM1].score, TeamName (TEAM2), teams[TEAM2].score); IRC_printf (IRC_T_TOPIC, "Current score on map %n is %n: %k to %n: %k", level.mapname, TeamName (TEAM1), teams[TEAM1].score, TeamName (TEAM2), teams[TEAM2].score); } } // WonGame: returns true if we're exiting the level. int WonGame (int winner) { edict_t *player, *cl_ent; // was: edict_t *player; int i; char arg[64]; gi.bprintf (PRINT_HIGH, "The round is over:\n"); IRC_printf (IRC_T_GAME, "The round is over:"); if (winner == WINNER_TIE) { gi.bprintf (PRINT_HIGH, "It was a tie, no points awarded!\n"); IRC_printf (IRC_T_GAME, "It was a tie, no points awarded!"); if(use_warnings->value) gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("tng/no_team_wins.wav"), 1.0, ATTN_NONE, 0.0); PrintScores (); } else { if (use_tourney->value) { if(winner == TEAM1) player = TourneyFindPlayer(1); else player = TourneyFindPlayer(NextOpponent); if (player) { gi.bprintf (PRINT_HIGH, "%s was victorious!\n", player->client->pers.netname); IRC_printf (IRC_T_GAME, "%n was victorious!", player->client->pers.netname); TourneyWinner (player); } } else { gi.bprintf (PRINT_HIGH, "%s won!\n", TeamName(winner)); IRC_printf (IRC_T_GAME, "%n won!", TeamName(winner)); // AQ:TNG Igor[Rock] changing sound dir if(use_warnings->value) gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex (va("tng/team%i_wins.wav", winner)), 1.0, ATTN_NONE, 0.0); // end of changing sound dir teams[winner].score++; gi.cvar_forceset(teams[winner].teamscore->name, va("%i", teams[winner].score)); PrintScores (); } } if (timelimit->value) { // AQ2:M - Matchmode if (matchmode->value) { if (matchtime >= timelimit->value * 60) { SendScores (); teams[TEAM1].ready = teams[TEAM2].ready = teams[TEAM3].ready = 0; team_round_going = team_round_countdown = team_game_going = matchtime = 0; MakeAllLivePlayersObservers (); return 1; } } else if (level.time >= timelimit->value * 60) { gi.bprintf (PRINT_HIGH, "Timelimit hit.\n"); IRC_printf (IRC_T_GAME, "Timelimit hit."); EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return 1; } } if (roundlimit->value && !ctf->value) { if (teams[TEAM1].score >= roundlimit->value || teams[TEAM2].score >= roundlimit->value || teams[TEAM3].score >= roundlimit->value) { if (matchmode->value) { SendScores (); teams[TEAM1].ready = teams[TEAM2].ready = teams[TEAM3].ready = matchtime = 0; team_round_going = team_round_countdown = team_game_going = 0; MakeAllLivePlayersObservers (); return 1; } else { gi.bprintf (PRINT_HIGH, "Roundlimit hit.\n"); IRC_printf (IRC_T_GAME, "Roundlimit hit."); EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return 1; } } } //PG BUND - BEGIN if (vCheckVote () == true) { EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return 1; } vNewRound (); //PG BUND - END if(teamplay->value && (!timelimit->value || level.time <= ((timelimit->value * 60) - 5))) { arg[0] = '\0'; for (i = 0; i < game.maxclients; i++) { cl_ent = &g_edicts[1 + i]; if (cl_ent->inuse && cl_ent->client->resp.stat_mode == 2) Cmd_Stats_f(cl_ent, arg); } } return 0; } void CheckTeamRules (void) { int winner, i; int checked_tie = 0; char buf[1024]; if (round_delay_time && use_tourney->value) { TourneyTimeEvent (T_END, round_delay_time); round_delay_time--; if (!round_delay_time) { TourneyNewRound (); team_round_countdown = TourneySetTime (T_RSTART); TourneyTimeEvent (T_START, team_round_countdown); } return; } // works like old CTF shield for TDM if (dm_shield->value && (!teamplay->value || (teamdm->value && lights_camera_action == 0)) && !ctf->value) { for (i = 0; i < maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].ctf_uvtime > 0) { game.clients[i].ctf_uvtime--; if (!game.clients[i].ctf_uvtime && team_round_going) { gi.centerprintf (&g_edicts[i + 1], "ACTION!"); } else if (game.clients[i].ctf_uvtime % 10 == 0) { gi.centerprintf (&g_edicts[i + 1], "Shield %d", game.clients[i].ctf_uvtime / 10); } } } } // AQ2:TNG - JBravo adding UVtime if(ctf->value) { for (i = 0; i < maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].ctf_uvtime > 0) { game.clients[i].ctf_uvtime--; if (!game.clients[i].ctf_uvtime && team_round_going) { if(ctfgame.type == 2) { gi.centerprintf (&g_edicts[i + 1], "ACTION!\n" "\n" "You are %s the %s base!", (game.clients[i].resp.team == ctfgame.offence ? "ATTACKING" : "DEFENDING"), CTFOtherTeamName(ctfgame.offence)); } else { gi.centerprintf (&g_edicts[i + 1], "ACTION!"); } } else if (game.clients[i].ctf_uvtime % 10 == 0) { if(ctfgame.type == 2) { gi.centerprintf (&g_edicts[i + 1], "Shield %d\n" "\n" "You are %s the %s base!", game.clients[i].ctf_uvtime / 10, (game.clients[i].resp.team == ctfgame.offence ? "ATTACKING" : "DEFENDING"), CTFOtherTeamName(ctfgame.offence)); } else { gi.centerprintf (&g_edicts[i + 1], "Shield %d", game.clients[i].ctf_uvtime / 10); } } } } } if (matchmode->value) { if(team_game_going) matchtime += 0.1f; if(mm_allowlock->value) { for(i=TEAM1; i <= teamCount; i++) { if (teams[i].locked && !TeamHasPlayers(i)) { teams[i].locked = 0; sprintf(buf, "%s unlocked (no players)", TeamName(i)); CenterPrintAll(buf); } } } } if (lights_camera_action) { ContinueLCA (); return; } if (team_round_going) current_round_length++; if (holding_on_tie_check) { holding_on_tie_check--; if (holding_on_tie_check > 0) return; holding_on_tie_check = 0; checked_tie = 1; } if (team_round_countdown) { team_round_countdown--; if(!team_round_countdown) { if (BothTeamsHavePlayers ()) { team_game_going = 1; StartLCA (); } else { if (!matchmode->value || TeamsReady()) CenterPrintAll ("Not enough players to play!"); else CenterPrintAll ("Both Teams Must Be Ready!"); team_round_going = team_round_countdown = team_game_going = 0; MakeAllLivePlayersObservers (); } } else if(use_tourney->value) { TourneyTimeEvent (T_START, team_round_countdown); } else { if (team_round_countdown == 101) { gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("world/10_0.wav"), 1.0, ATTN_NONE, 0.0); } } if(team_round_countdown == 41 && !matchmode->value) { while(CheckForUnevenTeams(NULL)); } } // check these rules every 1.5 seconds... if (++rulecheckfrequency % 15 && !checked_tie) return; if (!team_round_going) { if (timelimit->value) { // AQ2:TNG - Slicer : Matchmode if (matchmode->value) { if (matchtime >= timelimit->value * 60) { SendScores (); teams[TEAM1].ready = teams[TEAM2].ready = teams[TEAM3].ready = 0; team_round_going = team_round_countdown = team_game_going = matchtime = 0; MakeAllLivePlayersObservers (); return; } } //AQ2:TNG END else if (level.time >= timelimit->value * 60) { gi.bprintf (PRINT_HIGH, "Timelimit hit.\n"); IRC_printf (IRC_T_GAME, "Timelimit hit."); if (ctf->value) ResetPlayers (); EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return; } } //PG BUND - BEGIN if (vCheckVote () == true) { EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return; } //PG BUND - END if (!team_round_countdown) { if (BothTeamsHavePlayers ()) { if (use_tourney->value) { TourneyNewRound (); team_round_countdown = TourneySetTime (T_START); TourneyTimeEvent (T_START, team_round_countdown); } else { CenterPrintAll ("The round will begin in 20 seconds!"); team_round_countdown = 201; } } } } else /* team_round_going */ { if (ctf->value || teamdm->value) { if (vCheckVote () == true) { EndDMLevel (); team_round_going = team_round_countdown = team_game_going = 0; return; } } if ((winner = CheckForWinner ()) != WINNER_NONE) { if (!checked_tie) { holding_on_tie_check = 50; return; } if (WonGame(winner)) return; team_round_going = 0; lights_camera_action = 0; holding_on_tie_check = 0; if (use_tourney->value) round_delay_time = TourneySetTime (T_END); else team_round_countdown = 71; return; } if (roundtimelimit->value && !ctf->value && !teamdm->value) { if (current_round_length > roundtimelimit->value * 600) { gi.bprintf (PRINT_HIGH, "Round timelimit hit.\n"); IRC_printf (IRC_T_GAME, "Round timelimit hit."); winner = CheckForForcedWinner (); if (WonGame (winner)) return; team_round_going = 0; timewarning = fragwarning = 0; lights_camera_action = 0; holding_on_tie_check = 0; team_round_countdown = 71; return; } // AQ:TNG Igor[Rock] changing sound dir if(use_warnings->value) { if (current_round_length > (roundtimelimit->value - 1) * 600) { if (timewarning < 2) { CenterPrintAll ("1 MINUTE LEFT..."); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("tng/1_minute.wav"), 1.0, ATTN_NONE, 0.0); timewarning = 2; } } else if (current_round_length > (roundtimelimit->value - 3) * 600 && roundtimelimit->value > 3) { if (timewarning < 1) { CenterPrintAll ("3 MINUTES LEFT..."); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("tng/3_minutes.wav"), 1.0, ATTN_NONE, 0.0); timewarning = 1; } } } // end of changing sound dir } if (ctf->value || teamdm->value) { if(timelimit->value) { float gametime; if(matchmode->value) gametime = matchtime; else gametime = level.time; if (gametime >= timelimit->value * 60) { gi.bprintf (PRINT_HIGH, "Timelimit hit.\n"); IRC_printf (IRC_T_GAME, "Timelimit hit."); teams[TEAM1].ready = teams[TEAM2].ready = teams[TEAM3].ready = 0; team_round_going = team_round_countdown = team_game_going = 0; if(matchmode->value) { SendScores (); MakeAllLivePlayersObservers (); } else { ResetPlayers (); EndDMLevel (); } matchtime = 0; return; } } if (!BothTeamsHavePlayers ()) { if (!matchmode->value || TeamsReady()) CenterPrintAll ("Not enough players to play!"); else CenterPrintAll ("Both Teams Must Be Ready!"); team_round_going = team_round_countdown = team_game_going = 0; MakeAllLivePlayersObservers (); /* try to restart the game */ while(CheckForUnevenTeams(NULL)); } } } } void A_Scoreboard (edict_t * ent) { int wteam = 0; if (ent->client->showscores && ent->client->scoreboardnum == 1) { // blink header of the winning team during intermission if (level.intermissiontime && (level.framenum & 8)) { // blink 1/8th second if (teams[TEAM1].score > teams[TEAM2].score) wteam = TEAM1; else if (teams[TEAM2].score > teams[TEAM1].score) wteam = TEAM2; else if (teams[TEAM1].total > teams[TEAM2].total) // frag tie breaker wteam = TEAM1; else if (teams[TEAM2].total > teams[TEAM1].total) wteam = TEAM2; if(use_3teams->value) { if(wteam) { if (teams[TEAM3].score > teams[wteam].score) wteam = TEAM3; else if (teams[TEAM3].score == teams[wteam].score) { if(teams[TEAM3].total > teams[wteam].total) wteam = TEAM3; else if (teams[TEAM3].total == teams[wteam].total) wteam = 0; } } else { if(teams[TEAM3].score > teams[TEAM1].score) wteam = TEAM3; else if (teams[TEAM3].total > teams[TEAM1].total) wteam = TEAM3; } } if (wteam == 1) ent->client->ps.stats[STAT_TEAM1_PIC] = 0; else if (wteam == 2) ent->client->ps.stats[STAT_TEAM2_PIC] = 0; else if (wteam == 3 && use_3teams->value) ent->client->ps.stats[STAT_TEAM3_PIC] = 0; else // tie game! { ent->client->ps.stats[STAT_TEAM1_PIC] = 0; ent->client->ps.stats[STAT_TEAM2_PIC] = 0; if(use_3teams->value) ent->client->ps.stats[STAT_TEAM3_PIC] = 0; } } else { ent->client->ps.stats[STAT_TEAM1_PIC] = gi.imageindex(teams[TEAM1].skin_index); ent->client->ps.stats[STAT_TEAM2_PIC] = gi.imageindex(teams[TEAM2].skin_index); if (use_3teams->value) ent->client->ps.stats[STAT_TEAM3_PIC] = gi.imageindex (teams[TEAM3].skin_index); } ent->client->ps.stats[STAT_TEAM1_SCORE] = teams[TEAM1].score; ent->client->ps.stats[STAT_TEAM2_SCORE] = teams[TEAM2].score; if (use_3teams->value) ent->client->ps.stats[STAT_TEAM3_SCORE] = teams[TEAM3].score; } } #define MAX_PLAYERS_PER_TEAM 8 void A_NewScoreboardMessage(edict_t * ent) { char buf[1024]; char string[1024] = { '\0' }; int sorted[TEAM_TOP][MAX_CLIENTS]; int total[TEAM_TOP] = {0,0,0,0}; int i, j, k, line = 0, lineh = 8; // show alive players when dead int dead = (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD || !team_round_going); if (limchasecam->value != 0) dead = 0; for (i = 0; i < game.maxclients; i++) { edict_t *cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (game.clients[i].resp.team == NOTEAM) continue; int team = game.clients[i].resp.team; int score = game.clients[i].resp.score; for (j = 0; j < total[team]; j++) { if (score > game.clients[sorted[team][j]].resp.score) break; if (score == game.clients[sorted[team][j]].resp.score && game.clients[i].resp.damage_dealt > game.clients[sorted[team][j]].resp.damage_dealt) break; } for (k = total[team]; k > j; k--) sorted[team][k] = sorted[team][k - 1]; sorted[team][j] = i; total[team]++; } // print teams for (i = TEAM1; i <= TEAM2; i++) { sprintf(buf, "xv 44 yv %d string2 \" %-15s %3d Tim Png\"", line++ * lineh, teams[i].name, teams[i].score); strcat(string, buf); sprintf(buf, "xv 44 yv %d string2 \"%s\" ", line++ * lineh, "\x9D\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9E\x9F" ); strcat(string, buf); for (j = 0; j < MAX_PLAYERS_PER_TEAM; j++) { // show the amount of excess players if (total[i] > MAX_PLAYERS_PER_TEAM && j == MAX_PLAYERS_PER_TEAM - 1) { sprintf(buf, "xv 44 yv %d string \" ..and %d more\"", line++ * lineh, total[i] - MAX_PLAYERS_PER_TEAM + 1); strcat(string, buf); break; } if (j >= total[i]) { line++; continue; } gclient_t *cl = &game.clients[sorted[i][j]]; edict_t *cl_ent = g_edicts + 1 + sorted[i][j]; int alive = (cl_ent->solid != SOLID_NOT && cl_ent->deadflag != DEAD_DEAD); sprintf(buf, "xv 44 yv %d string \"%c %-15s %3d %3d %3d\"", line++ * lineh, (alive && dead ? '*' : ' '), cl->pers.netname, cl->resp.score, (level.framenum - cl->resp.enterframe) / 600, (cl->ping > 999 ? 999 : cl->ping)); strcat(string, buf); } line++; } string[1024] = '\0'; gi.WriteByte (svc_layout); gi.WriteString (string); } // Maximum number of lines of scores to put under each team's header. #define MAX_SCORES_PER_TEAM 9 //AQ2:TNG - Slicer Modified Scores for Match Mode void A_ScoreboardMessage (edict_t * ent, edict_t * killer) { char string[1400], damage[50]; gclient_t *cl; edict_t *cl_ent; int maxsize = 1000, i, j, k; if (ent->client->scoreboardnum == 1) { int team, len, deadview; int sorted[TEAM_TOP][MAX_CLIENTS]; int score; int total[TEAM_TOP] = {0,0,0,0}; int totalsubs[TEAM_TOP] = {0,0,0,0}, subs[TEAM_TOP] = {0,0,0,0}; int totalscore[TEAM_TOP] = {0,0,0,0}; int totalalive[TEAM_TOP] = {0,0,0,0}; int totalaliveprinted[TEAM_TOP] = {0,0,0,0}; int stoppedat[TEAM_TOP] = {-1,-1,-1,-1}; int name_pos[TEAM_TOP]; int secs, mins; int offset[TEAM_TOP], tpic[TEAM_TOP][2] = {{0,0},{24,26},{25,27},{30,31}}; char temp[16]; int otherLines, scoreWidth = 3; // new scoreboard for regular teamplay up to 16 players if (use_newscore->value && teamplay->value && !use_3teams->value && !matchmode->value && !ctf->value) { return A_NewScoreboardMessage(ent); } if(use_3teams->value) { offset[TEAM1] = -80; offset[TEAM2] = 80; offset[TEAM3] = 240; } else { offset[TEAM1] = 0; offset[TEAM2] = 160; if(ctf->value) { tpic[TEAM1][0] = 30; tpic[TEAM2][0] = 31; } else if(teamdm->value) { scoreWidth = 3; } } deadview = (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD || !team_round_going); // AQ:TNG - Hack to keep scoreboard from revealing whos alive during matches - JBravo if (limchasecam->value != 0) deadview = 0; ent->client->ps.stats[STAT_TEAM_HEADER] = gi.imageindex ("tag3"); for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (game.clients[i].resp.team == NOTEAM) continue; team = game.clients[i].resp.team; if (!matchmode->value || !game.clients[i].resp.subteam) { score = game.clients[i].resp.score; if (noscore->value) { j = total[team]; } else { for (j = 0; j < total[team]; j++) { if (score > game.clients[sorted[team][j]].resp.score) break; if (score == game.clients[sorted[team][j]].resp.score && game.clients[i].resp.damage_dealt > game.clients[sorted[team][j]].resp.damage_dealt) break; } for (k = total[team]; k > j; k--) sorted[team][k] = sorted[team][k - 1]; } sorted[team][j] = i; totalscore[team] += score; total[team]++; } else { totalsubs[team]++; } if (cl_ent->solid != SOLID_NOT && cl_ent->deadflag != DEAD_DEAD) totalalive[team]++; } // I've shifted the scoreboard position 8 pixels to the left in Axshun so it works // correctly in 320x240 (Action's does not)--any problems with this? -FB // Also going to center the team names. for(i=TEAM1; i<= teamCount; i++) { name_pos[i] = ((20 - strlen (teams[i].name)) / 2) * 8; if (name_pos[i] < 0) name_pos[i] = 0; } len = 0; for(i=TEAM1; i<= teamCount; i++) { if(matchmode->value) Com_sprintf(temp, sizeof(temp), "%4i/%2i/%-2d", totalscore[i], total[i], totalsubs[i]); else Com_sprintf(temp, sizeof(temp), "%4i/%2i", totalscore[i], total[i]); if(ctf->value) { sprintf(string + len, "if %i xv %i yv 8 pic %i endif " "xv %i yv 28 string \"%s\" " "xv %i yv 12 num 2 %i ", tpic[i][0], offset[i]+8, tpic[i][0], offset[i]+40, temp, offset[i]+98, tpic[i][1]); offset[i]+=8; } else { sprintf (string + len, "if %i xv %i yv 8 pic %i endif " "if 22 xv %i yv 8 pic 22 endif " "xv %i yv 28 string \"%s\" " "xv %i yv 12 num %i %i " "xv %d yv 0 string \"%s\" ", tpic[i][0], offset[i], tpic[i][0], offset[i]+32, offset[i]+32, temp, offset[i]+96, scoreWidth, tpic[i][1], name_pos[i] + offset[i], teams[i].name); } len = strlen (string); } if(matchmode->value) otherLines = 3; //for subs else otherLines = 0; for (i = 0; i < (MAX_SCORES_PER_TEAM + 1 - otherLines); i++) { if (i >= total[TEAM1] && i >= total[TEAM2]) { if(teamCount == 2 || i >= total[TEAM3]) break; } // ok, if we're approaching the "maxsize", then let's stop printing members of each // teams (if there's more than one member left to print in that team...) if (len > (maxsize - 100)) { for(j=TEAM1; j<= teamCount; j++) { if (i < (total[j] - 1)) stoppedat[j] = i; } } if (i == MAX_SCORES_PER_TEAM - 1 - otherLines) { for(j=TEAM1; j<= teamCount; j++) { if (total[j] > MAX_SCORES_PER_TEAM - otherLines) stoppedat[j] = i; } } for(j=TEAM1; j<= teamCount; j++) { if (i < total[j] && stoppedat[j] == -1) // print next team member... { cl = &game.clients[sorted[j][i]]; cl_ent = g_edicts + 1 + sorted[j][i]; if (cl_ent->solid != SOLID_NOT && cl_ent->deadflag != DEAD_DEAD) totalaliveprinted[j]++; // AQ truncates names at 12, not sure why, except maybe to conserve scoreboard // string space? skipping that "feature". -FB sprintf (string + len, "xv %i yv %i string%s \"%s%s\" ", offset[j], 42 + i * 8, (deadview && cl_ent->solid != SOLID_NOT) ? "2" : "", (matchmode->value && game.clients[sorted[j][i]].resp.captain) ? "@" : "", game.clients[sorted[j][i]].pers.netname); len = strlen (string); if(ctf->value){ if((j == TEAM1 && game.clients[sorted[j][i]].pers.inventory[ITEM_INDEX(flag2_item)]) || (j == TEAM2 && game.clients[sorted[j][i]].pers.inventory[ITEM_INDEX(flag1_item)])) { sprintf(string + len, "xv %i yv %i picn sbfctf%s ", offset[j]-8, 42 + i * 8, j == TEAM1 ? "2" : "1"); len = strlen(string); } } } } } // Print remaining players if we ran out of room... if (!deadview) // live player viewing scoreboard... { for(i=TEAM1; i<= teamCount; i++) { if (stoppedat[i] > -1) { sprintf (string + len, "xv %i yv %i string \"..and %i more\" ", offset[i], 42 + (stoppedat[i] * 8), total[i] - stoppedat[i]); len = strlen (string); } } } else // dead player viewing scoreboard... { for(i=TEAM1; i<= teamCount; i++) { if (stoppedat[i] > -1) { sprintf (string + len, "xv %i yv %i string%s \"..and %i/%i more\" ", offset[i], 42 + (stoppedat[i] * 8), (totalalive[i] - totalaliveprinted[i]) ? "2" : "", totalalive[i] - totalaliveprinted[i], total[i] - stoppedat[i]); len = strlen (string); } } } if(matchmode->value) //Subs { for(i=TEAM1; i<= teamCount; i++) { sprintf (string + len, "xv %i yv 96 string2 \"Subs\" ", offset[i]); len = strlen (string); } for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (!game.clients[i].resp.subteam) continue; j = game.clients[i].resp.subteam; if (totalsubs[j] < 3 || !subs[j]) { sprintf (string + strlen (string), "xv %i yv %d string \"%s%s\" ", offset[j], 104 + subs[j] * 8, game.clients[i].resp.captain ? "@" : "", game.clients[i].pers.netname); } else if (subs[j] < 2) { sprintf (string + strlen (string), "xv %i yv %i string \" + %i more\" ", offset[j], 104 + subs[j] * 8, totalsubs[j] - 1); } subs[j]++; } for(i=TEAM1; i<= teamCount; i++) { sprintf (string + strlen(string), "xv %i yv 128 string2 \"%s\" ", offset[i]+39, teams[i].ready ? "Ready" : "Not Ready"); } mins = matchtime / 60; secs = matchtime - (mins * 60); sprintf (string + strlen (string), "xv 112 yv 144 string \"Time: %d:%02d\" ", mins, secs); } } else if (ent->client->scoreboardnum == 2) { int total = 0, score = 0, ping; int sorted[MAX_CLIENTS]; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; score = game.clients[i].resp.score; if (noscore->value) { j = total; } else { for (j = 0; j < total; j++) { if (score > game.clients[sorted[j]].resp.score) break; if (score == game.clients[sorted[j]].resp.score && game.clients[i].resp.damage_dealt > game.clients[sorted[j]].resp.damage_dealt) break; } for (k = total; k > j; k--) sorted[k] = sorted[k - 1]; } sorted[j] = i; total++; } if (noscore->value) // AQ2:TNG Deathwatch - Nice little bar { strcpy (string, "xv 0 yv 32 string2 \"Player Time Ping\" " "xv 0 yv 40 string2 \"¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ\" "); } else if (teamdm->value) { if(matchmode->value) { strcpy(string, "xv 0 yv 32 string2 \"Frags Player Time Ping Deaths Team\" " "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧ƒ\" "); } else { strcpy(string, "xv 0 yv 32 string2 \"Frags Player Time Ping Deaths Kills\" " "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧₧ƒ\" "); } } else if (matchmode->value) { strcpy (string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Team \" " "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧ƒ\" "); } else { strcpy (string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Kills\" " "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧₧ƒ\" "); } /* { strcpy (string, "xv 0 yv 32 string2 \"Player Time Ping\" " "xv 0 yv 40 string2 \"--------------- ---- ----\" "); } else { strcpy (string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Kills\" " "xv 0 yv 40 string2 \"----- --------------- ---- ---- ------ -----\" "); } */ // AQ2:TNG END for (i = 0; i < total; i++) { ping = game.clients[sorted[i]].ping; if (ping > 999) ping = 999; if (noscore->value) { sprintf(string + strlen(string), "xv 0 yv %d string \"%-15s %4d %4d\" ", 48 + i * 8, game.clients[sorted[i]].pers.netname, (level.framenum - game.clients[sorted[i]].resp.enterframe) / 600, ping); } else { if(teamdm->value) { if (game.clients[sorted[i]].resp.deaths < 1000000) sprintf (damage, "%i", game.clients[sorted[i]].resp.deaths); else strcpy (damage, "999999"); } else { if (game.clients[sorted[i]].resp.damage_dealt < 1000000) sprintf (damage, "%i", game.clients[sorted[i]].resp.damage_dealt); else strcpy (damage, "999999"); } sprintf(string + strlen(string), "xv 0 yv %d string \"%5d %-15s %4d %4d %6s", 48 + i * 8, game.clients[sorted[i]].resp.score, game.clients[sorted[i]].pers.netname, (level.framenum - game.clients[sorted[i]].resp.enterframe) / 600, ping, damage); if(matchmode->value) { sprintf (string + strlen(string), " %i%s%s \" ", game.clients[sorted[i]].resp.team, game.clients[sorted[i]].resp.captain == 0 ? "" : "C", game.clients[sorted[i]].resp.subteam == 0 ? "" : "S"); } else { sprintf(string + strlen(string), " %5i\" ", game.clients[sorted[i]].resp.kills); } } if (strlen(string) > (maxsize - 100) && i < (total - 2)) { sprintf (string + strlen (string), "xv 0 yv %d string \"..and %d more\" ", 48 + (i + 1) * 8, (total - i - 1)); break; } } } if (strlen(string) > 1023) // for debugging... { gi.dprintf ("Warning: scoreboard string neared or exceeded max length\nDump:\n%s\n---\n", string); string[1023] = '\0'; } gi.WriteByte (svc_layout); gi.WriteString (string); } // called when we enter the intermission void TallyEndOfLevelTeamScores (void) { int i; gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("world/xian1.wav"), 1.0, ATTN_NONE, 0.0); teams[TEAM1].total = teams[TEAM2].total = teams[TEAM3].total = 0; for (i = 0; i < maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].resp.team == NOTEAM) continue; teams[game.clients[i].resp.team].total += game.clients[i].resp.score; } } /* * Teamplay spawning functions... */ edict_t *SelectTeamplaySpawnPoint (edict_t * ent) { return teamplay_spawns[ent->client->resp.team - 1]; } // SpawnPointDistance: // Returns the distance between two spawn points (or any entities, actually...) float SpawnPointDistance (edict_t * spot1, edict_t * spot2) { return Distance(spot1->s.origin, spot2->s.origin); } spawn_distances_t *spawn_distances; // GetSpawnPoints: // Put the spawn points into our potential_spawns array so we can work with them easily. void GetSpawnPoints (void) { edict_t *spot = NULL; num_potential_spawns = 0; if ((spot = G_Find (spot, FOFS (classname), "info_player_team1")) != NULL) { potential_spawns[num_potential_spawns] = spot; num_potential_spawns++; } if ((spot = G_Find (spot, FOFS (classname), "info_player_team2")) != NULL) { potential_spawns[num_potential_spawns] = spot; num_potential_spawns++; } spot = NULL; while ((spot = G_Find (spot, FOFS (classname), "info_player_deathmatch")) != NULL) { potential_spawns[num_potential_spawns] = spot; num_potential_spawns++; if (num_potential_spawns >= MAX_SPAWNS) { gi.dprintf ("Warning: MAX_SPAWNS exceeded\n"); break; } } if(spawn_distances) gi.TagFree (spawn_distances); spawn_distances = (spawn_distances_t *)gi.TagMalloc (num_potential_spawns * sizeof (spawn_distances_t), TAG_GAME); } // newrand returns n, where 0 >= n < top int newrand (int top) { return (int) (random () * top); } // compare_spawn_distances is used by the qsort() call int compare_spawn_distances (const void *sd1, const void *sd2) { if (((spawn_distances_t *)sd1)->distance < ((spawn_distances_t *)sd2)->distance) return -1; else if (((spawn_distances_t *)sd1)->distance > ((spawn_distances_t *)sd2)->distance) return 1; else return 0; } void SelectRandomTeamplaySpawnPoint (int team, qboolean teams_assigned[]) { teamplay_spawns[team] = potential_spawns[newrand(num_potential_spawns)]; teams_assigned[team] = true; } void SelectFarTeamplaySpawnPoint (int team, qboolean teams_assigned[]) { int x, y, spawn_to_use, preferred_spawn_points, num_already_used, total_good_spawn_points; float closest_spawn_distance, distance; num_already_used = 0; for (x = 0; x < num_potential_spawns; x++) { closest_spawn_distance = 2000000000; for (y = 0; y < teamCount; y++) { if (teams_assigned[y]) { distance = SpawnPointDistance (potential_spawns[x], teamplay_spawns[y]); if (distance < closest_spawn_distance) closest_spawn_distance = distance; } } if (closest_spawn_distance == 0) num_already_used++; spawn_distances[x].s = potential_spawns[x]; spawn_distances[x].distance = closest_spawn_distance; } qsort (spawn_distances, num_potential_spawns, sizeof (spawn_distances_t), compare_spawn_distances); total_good_spawn_points = num_potential_spawns - num_already_used; if (total_good_spawn_points <= 4) preferred_spawn_points = 1; else if (total_good_spawn_points <= 10) preferred_spawn_points = 2; else preferred_spawn_points = 3; //FB 6/1/99 - make DF_SPAWN_FARTHEST force far spawn points in TP if ((int) dmflags->value & DF_SPAWN_FARTHEST) preferred_spawn_points = 1; //FB 6/1/99 spawn_to_use = newrand (preferred_spawn_points); if (team < 0 || team >= MAX_TEAMS) { gi.dprintf("Out-of-range teams value in SelectFarTeamplaySpawnPoint, skipping...\n"); } else { teams_assigned[team] = true; teamplay_spawns[team] = spawn_distances[num_potential_spawns - spawn_to_use - 1].s; } } // SetupTeamSpawnPoints: // // Setup the points at which the teams will spawn. // void SetupTeamSpawnPoints () { qboolean teams_assigned[MAX_TEAMS]; int i, l; for (l = 0; l < teamCount; l++) { teamplay_spawns[l] = NULL; teams_assigned[l] = false; } l = newrand(teamCount); SelectRandomTeamplaySpawnPoint(l, teams_assigned); for(i=l+1; i<teamCount+l; i++) SelectFarTeamplaySpawnPoint(i % teamCount, teams_assigned); } // TNG:Freud New Spawning system // NS_GetSpawnPoints: // Put the potential spawns into arrays for each team. void NS_GetSpawnPoints () { int x, i; NS_randteam = newrand(2); for (x = 0; x < teamCount; x++) { NS_num_used_farteamplay_spawns[x] = 0; NS_num_potential_spawns[x] = num_potential_spawns; for(i = 0; i < num_potential_spawns; i++) NS_potential_spawns[x][i] = potential_spawns[i]; } } // TNG:Freud // NS_SelectRandomTeamplaySpawnPoint // Select a random spawn point for the team from remaining spawns. // returns false if no spawns left. qboolean NS_SelectRandomTeamplaySpawnPoint (int team, qboolean teams_assigned[]) { int spawn_point, z; if (NS_num_potential_spawns[team] < 1) { gi.dprintf("New Spawncode: gone through all spawns, re-reading spawns\n"); NS_GetSpawnPoints (); NS_SetupTeamSpawnPoints (); return false; } spawn_point = newrand (NS_num_potential_spawns[team]); NS_num_potential_spawns[team]--; teamplay_spawns[team] = NS_potential_spawns[team][spawn_point]; teams_assigned[team] = true; for (z = spawn_point;z < NS_num_potential_spawns[team];z++) { NS_potential_spawns[team][z] = NS_potential_spawns[team][z + 1]; } return true; } // TNG:Freud // NS_SelectFarTeamplaySpawnPoint // Selects farthest teamplay spawn point from available spawns. qboolean NS_SelectFarTeamplaySpawnPoint (int team, qboolean teams_assigned[]) { int u, x, y, z, spawn_to_use, preferred_spawn_points, num_already_used, total_good_spawn_points; float closest_spawn_distance, distance; edict_t *usable_spawns[3]; qboolean used; int num_usable; num_already_used = 0; for (x = 0; x < NS_num_potential_spawns[team]; x++) { closest_spawn_distance = 2000000000; for (y = 0; y < teamCount; y++) { if (teams_assigned[y]) { distance = SpawnPointDistance (NS_potential_spawns[team][x], teamplay_spawns[y]); if (distance < closest_spawn_distance) closest_spawn_distance = distance; } } if (closest_spawn_distance == 0) num_already_used++; spawn_distances[x].s = NS_potential_spawns[team][x]; spawn_distances[x].distance = closest_spawn_distance; } qsort (spawn_distances, NS_num_potential_spawns[team], sizeof (spawn_distances_t), compare_spawn_distances); total_good_spawn_points = NS_num_potential_spawns[team] - num_already_used; if (total_good_spawn_points <= 4) preferred_spawn_points = 1; else if (total_good_spawn_points <= 10) preferred_spawn_points = 2; else preferred_spawn_points = 3; //FB 6/1/99 - make DF_SPAWN_FARTHEST force far spawn points in TP if ((int) dmflags->value & DF_SPAWN_FARTHEST) preferred_spawn_points = 1; //FB 6/1/99 num_usable = 0; for (z = 0;z < preferred_spawn_points;z++) { used = false; for (u = 0;u < NS_num_used_farteamplay_spawns[team];u++) { if (NS_used_farteamplay_spawns[team][u] == spawn_distances[NS_num_potential_spawns[team] - z - 1].s) { used = true; break; } } if (used == false) { usable_spawns[num_usable] = spawn_distances[NS_num_potential_spawns[team] - z - 1].s; num_usable++; } } if (num_usable < 1) { NS_SetupTeamSpawnPoints (); return false; } spawn_to_use = newrand (num_usable); NS_used_farteamplay_spawns[team][NS_num_used_farteamplay_spawns[team]] = usable_spawns[spawn_to_use]; NS_num_used_farteamplay_spawns[team]++; if (team < 0 || team >= MAX_TEAMS) { gi.dprintf("Out-of-range teams value in SelectFarTeamplaySpawnPoint, skipping...\n"); } else { teams_assigned[team] = true; teamplay_spawns[team] = usable_spawns[spawn_to_use]; } return true; } // TNG:Freud // NS_SetupTeamSpawnPoints // Finds and assigns spawn points to each team. void NS_SetupTeamSpawnPoints () { qboolean teams_assigned[MAX_TEAMS]; int l; for (l = 0; l < teamCount; l++) { teamplay_spawns[l] = NULL; teams_assigned[l] = false; } if (NS_SelectRandomTeamplaySpawnPoint (NS_randteam, teams_assigned) == false) return; for (l = 0;l < teamCount;l++) { // TNG:Freud disabled 3teams for new spawning system. if (l != NS_randteam && NS_SelectFarTeamplaySpawnPoint (l, teams_assigned) == false) return; } }
536
./aq2-tng/source/g_utils.c
//----------------------------------------------------------------------------- // g_utils.c -- misc utility functions for game module // // $Id: g_utils.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_utils.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:31:54 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" void G_ProjectSource (vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result) { result[0] = point[0] + forward[0] * distance[0] + right[0] * distance[1]; result[1] = point[1] + forward[1] * distance[0] + right[1] * distance[1]; result[2] = point[2] + forward[2] * distance[0] + right[2] * distance[1] + distance[2]; } /* ============= G_Find Searches all active entities for the next one that holds the matching string at fieldofs (use the FOFS() macro) in the structure. Searches beginning at the edict after from, or the beginning if NULL NULL will be returned if the end of the list is reached. ============= */ edict_t *G_Find (edict_t * from, int fieldofs, char *match) { char *s; if (!from) from = g_edicts; else from++; for (; from < &g_edicts[globals.num_edicts]; from++) { if (!from->inuse) continue; s = *(char **) ((byte *) from + fieldofs); if (!s) continue; if (!Q_stricmp (s, match)) return from; } return NULL; } /* ================= findradius Returns entities that have origins within a spherical area findradius (origin, radius) ================= */ edict_t *findradius (edict_t * from, vec3_t org, float rad) { vec3_t eorg; int j; if (!from) from = g_edicts; else from++; for (; from < &g_edicts[globals.num_edicts]; from++) { if (!from->inuse) continue; if (from->solid == SOLID_NOT) continue; for (j = 0; j < 3; j++) eorg[j] = org[j] - (from->s.origin[j] + (from->mins[j] + from->maxs[j]) * 0.5); if (VectorLength (eorg) > rad) continue; return from; } return NULL; } /* ============= G_PickTarget Searches all active entities for the next one that holds the matching string at fieldofs (use the FOFS() macro) in the structure. Searches beginning at the edict after from, or the beginning if NULL NULL will be returned if the end of the list is reached. ============= */ #define MAXCHOICES 8 edict_t *G_PickTarget (char *targetname) { edict_t *ent = NULL; int num_choices = 0; edict_t *choice[MAXCHOICES]; if (!targetname) { gi.dprintf ("G_PickTarget called with NULL targetname\n"); return NULL; } while (1) { ent = G_Find (ent, FOFS (targetname), targetname); if (!ent) break; choice[num_choices++] = ent; if (num_choices == MAXCHOICES) break; } if (!num_choices) { gi.dprintf ("G_PickTarget: target %s not found\n", targetname); return NULL; } return choice[rand () % num_choices]; } void Think_Delay (edict_t * ent) { G_UseTargets (ent, ent->activator); G_FreeEdict (ent); } /* ============================== G_UseTargets the global "activator" should be set to the entity that initiated the firing. If self.delay is set, a DelayedUse entity will be created that will actually do the SUB_UseTargets after that many seconds have passed. Centerprints any self.message to the activator. Search for (string)targetname in all entities that match (string)self.target and call their .use function ============================== */ void G_UseTargets (edict_t * ent, edict_t * activator) { edict_t *t; // // check for a delay // if (ent->delay) { // create a temp object to fire at a later time t = G_Spawn (); t->classname = "DelayedUse"; t->nextthink = level.time + ent->delay; t->think = Think_Delay; t->activator = activator; if (!activator) gi.dprintf ("Think_Delay with no activator\n"); t->message = ent->message; t->target = ent->target; t->killtarget = ent->killtarget; return; } // // print the message // if ((ent->message) && !(activator->svflags & SVF_MONSTER)) { gi.centerprintf (activator, "%s", ent->message); if (ent->noise_index) gi.sound (activator, CHAN_AUTO, ent->noise_index, 1, ATTN_NORM, 0); else gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } // // kill killtargets // if (ent->killtarget) { t = NULL; while ((t = G_Find (t, FOFS (targetname), ent->killtarget))) { G_FreeEdict (t); if (!ent->inuse) { gi.dprintf ("entity was removed while using killtargets\n"); return; } } } // // fire targets // if (ent->target) { t = NULL; while ((t = G_Find (t, FOFS (targetname), ent->target))) { // doors fire area portals in a specific way if (!Q_stricmp(t->classname, "func_areaportal") && (!Q_stricmp(ent->classname, "func_door") || !Q_stricmp(ent->classname, "func_door_rotating"))) continue; if (t == ent) { gi.dprintf ("WARNING: Entity used itself.\n"); } else { if (t->use) t->use(t, ent, activator); } if (!ent->inuse) { gi.dprintf ("entity was removed while using targets\n"); return; } } } } /* ============= TempVector This is just a convenience function for making temporary vectors for function calls ============= */ /*float *tv (float x, float y, float z) { static int index; static vec3_t vecs[8]; float *v; // use an array so that multiple tempvectors won't collide // for a while v = vecs[index]; index = (index + 1) & 7; v[0] = x; v[1] = y; v[2] = z; return v; }*/ /* ============= VectorToString This is just a convenience function for printing vectors ============= */ char *vtos (vec3_t v) { static int index; static char str[8][32]; char *s; // use an array so that multiple vtos won't collide s = str[index]; index = (index + 1) & 7; Com_sprintf (s, 32, "(%i %i %i)", (int) v[0], (int) v[1], (int) v[2]); return s; } vec3_t VEC_UP = { 0, -1, 0 }; vec3_t MOVEDIR_UP = { 0, 0, 1 }; vec3_t VEC_DOWN = { 0, -2, 0 }; vec3_t MOVEDIR_DOWN = { 0, 0, -1 }; void G_SetMovedir (vec3_t angles, vec3_t movedir) { if (VectorCompare (angles, VEC_UP)) { VectorCopy (MOVEDIR_UP, movedir); } else if (VectorCompare (angles, VEC_DOWN)) { VectorCopy (MOVEDIR_DOWN, movedir); } else { AngleVectors (angles, movedir, NULL, NULL); } VectorClear (angles); } float vectoyaw (vec3_t vec) { float yaw; // FIXES HERE FROM 3.20 -FB if ( /*vec[YAW] == 0 && */ vec[PITCH] == 0) { yaw = 0; if (vec[YAW] > 0) yaw = 90; else if (vec[YAW] < 0) yaw = -90; } // ^^^ else { yaw = (int) (atan2 (vec[YAW], vec[PITCH]) * 180 / M_PI); if (yaw < 0) yaw += 360; } return yaw; } void vectoangles (vec3_t value1, vec3_t angles) { float forward; float yaw, pitch; if (value1[1] == 0 && value1[0] == 0) { yaw = 0; if (value1[2] > 0) pitch = 90; else pitch = 270; } else { // FIXES HERE FROM 3.20 -FB // zucc changing casts to floats if (value1[0]) yaw = (float) (atan2 (value1[1], value1[0]) * 180 / M_PI); else if (value1[1] > 0) yaw = 90; else yaw = -90; // ^^^ if (yaw < 0) yaw += 360; forward = sqrt (value1[0] * value1[0] + value1[1] * value1[1]); pitch = (float) (atan2 (value1[2], forward) * 180 / M_PI); if (pitch < 0) pitch += 360; } angles[PITCH] = -pitch; angles[YAW] = yaw; angles[ROLL] = 0; } char *G_CopyString (char *in) { char *out; out = gi.TagMalloc (strlen(in) + 1, TAG_LEVEL); strcpy (out, in); return out; } void G_InitEdict (edict_t * e) { e->inuse = true; e->classname = "noclass"; e->gravity = 1.0; e->s.number = e - g_edicts; e->typeNum = NO_NUM; } /* ================= G_Spawn Either finds a free edict, or allocates a new one. Try to avoid reusing an entity that was recently freed, because it can cause the client to think the entity morphed into something else instead of being removed and recreated, which can cause interpolated angles and bad trails. ================= */ edict_t *G_Spawn (void) { int i; edict_t *e; e = &g_edicts[(int) maxclients->value + 1]; for (i = maxclients->value + 1; i < globals.num_edicts; i++, e++) { // the first couple seconds of server time can involve a lot of // freeing and allocating, so relax the replacement policy if (!e->inuse && (e->freetime < 2 || level.time - e->freetime > 0.5)) { G_InitEdict (e); return e; } } if (i == game.maxentities) gi.error ("ED_Alloc: no free edicts"); globals.num_edicts++; G_InitEdict (e); return e; } /* ================= G_FreeEdict Marks the edict as free ================= */ void G_FreeEdict (edict_t * ed) { gi.unlinkentity (ed); // unlink from world if ((ed - g_edicts) <= (maxclients->value + BODY_QUEUE_SIZE)) { // gi.dprintf("tried to free special edict\n"); return; } memset (ed, 0, sizeof (*ed)); ed->classname = "freed"; ed->freetime = level.time; ed->inuse = false; ed->typeNum = NO_NUM; } /* ============ G_TouchTriggers ============ */ void G_TouchTriggers (edict_t * ent) { int i, num; edict_t *touch[MAX_EDICTS], *hit; // dead things don't activate triggers! if ((ent->client || (ent->svflags & SVF_MONSTER)) && (ent->health <= 0)) return; num = gi.BoxEdicts (ent->absmin, ent->absmax, touch, MAX_EDICTS, AREA_TRIGGERS); // be careful, it is possible to have an entity in this // list removed before we get to it (killtriggered) for (i = 0; i < num; i++) { hit = touch[i]; if (!hit->inuse) continue; if (!hit->touch) continue; hit->touch (hit, ent, NULL, NULL); } } /* ============ G_TouchSolids Call after linking a new trigger in during gameplay to force all entities it covers to immediately touch it ============ */ void G_TouchSolids (edict_t * ent) { int i, num; edict_t *touch[MAX_EDICTS], *hit; num = gi.BoxEdicts (ent->absmin, ent->absmax, touch, MAX_EDICTS, AREA_SOLID); // be careful, it is possible to have an entity in this // list removed before we get to it (killtriggered) for (i = 0; i < num; i++) { hit = touch[i]; if (!hit->inuse) continue; if (ent->touch) ent->touch (hit, ent, NULL, NULL); if (!ent->inuse) break; } } /* ============================================================================== Kill box ============================================================================== */ /* ================= KillBox Kills all entities that would touch the proposed new positioning of ent. Ent should be unlinked before calling this! ================= */ qboolean KillBox (edict_t * ent) { trace_t tr; while (1) { tr = gi.trace (ent->s.origin, ent->mins, ent->maxs, ent->s.origin, NULL, MASK_PLAYERSOLID); if (!tr.ent) break; // nail it T_Damage (tr.ent, ent, ent, vec3_origin, ent->s.origin, vec3_origin, 100000, 0, DAMAGE_NO_PROTECTION, MOD_TELEFRAG); // if we didn't kill it, fail if (tr.ent->solid) return false; } return true; // all clear }
537
./aq2-tng/source/g_spawn.c
//----------------------------------------------------------------------------- // g_spawn.c // // $Id: g_spawn.c,v 1.38 2002/03/28 12:10:11 freud Exp $ // //----------------------------------------------------------------------------- // $Log: g_spawn.c,v $ // Revision 1.38 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.37 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.36 2002/03/27 15:16:56 freud // Original 1.52 spawn code implemented for use_newspawns 0. // Teamplay, when dropping bandolier, your drop the grenades. // Teamplay, cannot pick up grenades unless wearing bandolier. // // Revision 1.35 2002/03/25 23:35:19 freud // Ghost code, use_ghosts and more stuff.. // // Revision 1.34 2002/03/25 18:32:11 freud // I'm being too productive.. New ghost command needs testing. // // Revision 1.33 2002/03/24 22:45:54 freud // New spawn code again, bad commit last time.. // // Revision 1.31 2002/01/24 01:47:17 ra // Further fixes to M$ files // // Revision 1.30 2002/01/24 01:32:34 ra // Enabling .aqg files to be in either M$ form or real text files. // // Revision 1.29 2001/11/27 23:23:40 igor_rock // Bug fixed: day_cycle_at wasn't reset at mapchange // // Revision 1.28 2001/11/16 13:01:39 deathwatch // Fixed 'no team wins' sound - it wont play now with use_warnings 0 // Precaching misc/flashlight.wav // // Revision 1.27 2001/11/10 14:00:14 deathwatch // Fixed resetting of teamXscores // // Revision 1.26 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.25 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.24 2001/08/18 01:28:06 deathwatch // Fixed some stats stuff, added darkmatch + day_cycle, cleaned up several files, restructured ClientCommand // // Revision 1.23 2001/07/15 16:02:18 slicerdw // Added checks for teamplay on when using 3teams or tourney // // Revision 1.22 2001/06/26 11:41:39 igor_rock // removed the debug messages for flag and playerstart positions in ctf // // Revision 1.21 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.20 2001/06/22 16:34:05 slicerdw // Finished Matchmode Basics, now with admins, Say command tweaked... // // Revision 1.19 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.16 2001/06/13 09:43:49 igor_rock // if ctf is enabled, friendly fire automatically set to off (ff doesn't make any sense in ctf) // // Revision 1.15 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.14 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.13.2.8 2001/05/31 15:15:52 igor_rock // added a parameter check for sscanf // // Revision 1.13.2.7 2001/05/31 06:47:51 igor_rock // - removed crash bug with non exisitng flag files // - added new commands "setflag1", "setflag2" and "saveflags" to create // .flg files // // Revision 1.13.2.6 2001/05/27 17:24:10 igor_rock // changed spawnpoint behavior in CTF // // Revision 1.13.2.5 2001/05/27 16:11:10 igor_rock // added function to replace nearest spawnpoint to flag through info_player_teamX // // Revision 1.13.2.4 2001/05/27 11:47:53 igor_rock // added .flg file support and timelimit bug fix // // Revision 1.13.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.13.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.13.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.13 2001/05/15 15:49:14 igor_rock // added itm_flags for deathmatch // // Revision 1.12 2001/05/14 21:10:16 igor_rock // added wp_flags support (and itm_flags skeleton - doesn't disturb in the moment) // // Revision 1.11 2001/05/14 14:08:51 igor_rock // added tng sounds for precaching // // Revision 1.10 2001/05/12 19:29:28 mort // Fixed more various map change bugs // // Revision 1.9 2001/05/12 19:27:17 mort // Fixed various map change bugs // // Revision 1.8 2001/05/12 17:20:27 mort // Reset started variable in SP_worldspawn // // Revision 1.7 2001/05/12 13:45:59 mort // CTF status bar now sends correctly // // Revision 1.6 2001/05/12 13:15:04 mort // Forces teamplay on when ctf is enabled // // Revision 1.5 2001/05/12 08:20:01 mort // CTF bug fix, makes sure flags have actually spawned before certain functions attempt to use them // // Revision 1.4 2001/05/12 00:37:03 ra // // // Fixing various compilerwarnings. // // Revision 1.3 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.2 2001/05/11 12:21:19 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.1.1.1 2001/05/06 17:31:52 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" typedef struct { char *name; void (*spawn) (edict_t * ent); } spawn_t; void SP_item_health (edict_t * self); void SP_item_health_small (edict_t * self); void SP_item_health_large (edict_t * self); void SP_item_health_mega (edict_t * self); void SP_info_player_start (edict_t * ent); void SP_info_player_deathmatch (edict_t * ent); void SP_info_player_coop (edict_t * ent); void SP_info_player_intermission (edict_t * ent); void SP_func_plat (edict_t * ent); void SP_func_rotating (edict_t * ent); void SP_func_button (edict_t * ent); void SP_func_door (edict_t * ent); void SP_func_door_secret (edict_t * ent); void SP_func_door_rotating (edict_t * ent); void SP_func_water (edict_t * ent); void SP_func_train (edict_t * ent); void SP_func_conveyor (edict_t * self); void SP_func_wall (edict_t * self); void SP_func_object (edict_t * self); void SP_func_explosive (edict_t * self); void SP_func_timer (edict_t * self); void SP_func_areaportal (edict_t * ent); void SP_func_clock (edict_t * ent); void SP_func_killbox (edict_t * ent); void SP_trigger_always (edict_t * ent); void SP_trigger_once (edict_t * ent); void SP_trigger_multiple (edict_t * ent); void SP_trigger_relay (edict_t * ent); void SP_trigger_push (edict_t * ent); void SP_trigger_hurt (edict_t * ent); void SP_trigger_key (edict_t * ent); void SP_trigger_counter (edict_t * ent); void SP_trigger_elevator (edict_t * ent); void SP_trigger_gravity (edict_t * ent); void SP_trigger_monsterjump (edict_t * ent); void SP_target_temp_entity (edict_t * ent); void SP_target_speaker (edict_t * ent); void SP_target_explosion (edict_t * ent); void SP_target_changelevel (edict_t * ent); void SP_target_secret (edict_t * ent); void SP_target_goal (edict_t * ent); void SP_target_splash (edict_t * ent); void SP_target_spawner (edict_t * ent); void SP_target_blaster (edict_t * ent); void SP_target_crosslevel_trigger (edict_t * ent); void SP_target_crosslevel_target (edict_t * ent); void SP_target_laser (edict_t * self); void SP_target_help (edict_t * ent); void SP_target_actor (edict_t * ent); void SP_target_lightramp (edict_t * self); void SP_target_earthquake (edict_t * ent); void SP_target_character (edict_t * ent); void SP_target_string (edict_t * ent); void SP_worldspawn (edict_t * ent); void SP_viewthing (edict_t * ent); void SP_light (edict_t * self); void SP_light_mine1 (edict_t * ent); void SP_light_mine2 (edict_t * ent); void SP_info_null (edict_t * self); void SP_info_notnull (edict_t * self); void SP_path_corner (edict_t * self); void SP_point_combat (edict_t * self); void SP_misc_explobox (edict_t * self); void SP_misc_banner (edict_t * self); void SP_misc_satellite_dish (edict_t * self); void SP_misc_actor (edict_t * self); void SP_misc_gib_arm (edict_t * self); void SP_misc_gib_leg (edict_t * self); void SP_misc_gib_head (edict_t * self); void SP_misc_insane (edict_t * self); void SP_misc_deadsoldier (edict_t * self); void SP_misc_viper (edict_t * self); void SP_misc_viper_bomb (edict_t * self); void SP_misc_bigviper (edict_t * self); void SP_misc_strogg_ship (edict_t * self); void SP_misc_teleporter (edict_t * self); void SP_misc_teleporter_dest (edict_t * self); void SP_misc_blackhole (edict_t * self); void SP_misc_eastertank (edict_t * self); void SP_misc_easterchick (edict_t * self); void SP_misc_easterchick2 (edict_t * self); void SP_monster_berserk (edict_t * self); void SP_monster_gladiator (edict_t * self); void SP_monster_gunner (edict_t * self); void SP_monster_infantry (edict_t * self); void SP_monster_soldier_light (edict_t * self); void SP_monster_soldier (edict_t * self); void SP_monster_soldier_ss (edict_t * self); void SP_monster_tank (edict_t * self); void SP_monster_medic (edict_t * self); void SP_monster_flipper (edict_t * self); void SP_monster_chick (edict_t * self); void SP_monster_parasite (edict_t * self); void SP_monster_flyer (edict_t * self); void SP_monster_brain (edict_t * self); void SP_monster_floater (edict_t * self); void SP_monster_hover (edict_t * self); void SP_monster_mutant (edict_t * self); void SP_monster_supertank (edict_t * self); void SP_monster_boss2 (edict_t * self); void SP_monster_jorg (edict_t * self); void SP_monster_boss3_stand (edict_t * self); void SP_monster_commander_body (edict_t * self); void SP_turret_breach (edict_t * self); void SP_turret_base (edict_t * self); void SP_turret_driver (edict_t * self); //zucc - item replacement function void CheckItem (edict_t * ent); int LoadFlagsFromFile (char *mapname); void ChangePlayerSpawns (); //AQ2:TNG - Slicer New location code int ml_count = 0; char ml_build[6]; char ml_creator[101]; //AQ2:TNG END placedata_t locationbase[MAX_LOCATIONS_IN_BASE]; //AQ2:M spawn_t spawns[] = { {"item_health", SP_item_health}, {"item_health_small", SP_item_health_small}, {"item_health_large", SP_item_health_large}, {"item_health_mega", SP_item_health_mega}, {"info_player_start", SP_info_player_start}, {"info_player_deathmatch", SP_info_player_deathmatch}, {"info_player_coop", SP_info_player_coop}, {"info_player_intermission", SP_info_player_intermission}, {"info_player_team1", SP_info_player_team1}, {"info_player_team2", SP_info_player_team2}, {"func_plat", SP_func_plat}, {"func_button", SP_func_button}, {"func_door", SP_func_door}, {"func_door_secret", SP_func_door_secret}, {"func_door_rotating", SP_func_door_rotating}, {"func_rotating", SP_func_rotating}, {"func_train", SP_func_train}, {"func_water", SP_func_water}, {"func_conveyor", SP_func_conveyor}, {"func_areaportal", SP_func_areaportal}, {"func_clock", SP_func_clock}, {"func_wall", SP_func_wall}, {"func_object", SP_func_object}, {"func_timer", SP_func_timer}, {"func_explosive", SP_func_explosive}, {"func_killbox", SP_func_killbox}, {"trigger_always", SP_trigger_always}, {"trigger_once", SP_trigger_once}, {"trigger_multiple", SP_trigger_multiple}, {"trigger_relay", SP_trigger_relay}, {"trigger_push", SP_trigger_push}, {"trigger_hurt", SP_trigger_hurt}, {"trigger_key", SP_trigger_key}, {"trigger_counter", SP_trigger_counter}, {"trigger_elevator", SP_trigger_elevator}, {"trigger_gravity", SP_trigger_gravity}, {"trigger_monsterjump", SP_trigger_monsterjump}, {"target_temp_entity", SP_target_temp_entity}, {"target_speaker", SP_target_speaker}, {"target_explosion", SP_target_explosion}, {"target_changelevel", SP_target_changelevel}, {"target_secret", SP_target_secret}, {"target_goal", SP_target_goal}, {"target_splash", SP_target_splash}, {"target_spawner", SP_target_spawner}, {"target_blaster", SP_target_blaster}, {"target_crosslevel_trigger", SP_target_crosslevel_trigger}, {"target_crosslevel_target", SP_target_crosslevel_target}, {"target_laser", SP_target_laser}, {"target_help", SP_target_help}, // monster {"target_actor", SP_target_actor}, {"target_lightramp", SP_target_lightramp}, {"target_earthquake", SP_target_earthquake}, {"target_character", SP_target_character}, {"target_string", SP_target_string}, {"worldspawn", SP_worldspawn}, {"viewthing", SP_viewthing}, {"light", SP_light}, {"light_mine1", SP_light_mine1}, {"light_mine2", SP_light_mine2}, {"info_null", SP_info_null}, {"func_group", SP_info_null}, {"info_notnull", SP_info_notnull}, {"path_corner", SP_path_corner}, {"point_combat", SP_point_combat}, {"misc_explobox", SP_misc_explobox}, {"misc_banner", SP_misc_banner}, {"misc_ctf_banner", SP_misc_ctf_banner}, {"misc_ctf_small_banner", SP_misc_ctf_small_banner}, {"misc_satellite_dish", SP_misc_satellite_dish}, // monster {"misc_actor", SP_misc_actor}, {"misc_gib_arm", SP_misc_gib_arm}, {"misc_gib_leg", SP_misc_gib_leg}, {"misc_gib_head", SP_misc_gib_head}, // monster {"misc_insane", SP_misc_insane}, {"misc_deadsoldier", SP_misc_deadsoldier}, {"misc_viper", SP_misc_viper}, {"misc_viper_bomb", SP_misc_viper_bomb}, {"misc_bigviper", SP_misc_bigviper}, {"misc_strogg_ship", SP_misc_strogg_ship}, {"misc_teleporter", SP_misc_teleporter}, {"misc_teleporter_dest", SP_misc_teleporter_dest}, {"trigger_teleport", SP_trigger_teleport}, {"info_teleport_destination", SP_info_teleport_destination}, {"misc_blackhole", SP_misc_blackhole}, {"misc_eastertank", SP_misc_eastertank}, {"misc_easterchick", SP_misc_easterchick}, {"misc_easterchick2", SP_misc_easterchick2}, /* // monsters {"monster_berserk", SP_monster_berserk}, {"monster_gladiator", SP_monster_gladiator}, {"monster_gunner", SP_monster_gunner}, {"monster_infantry", SP_monster_infantry}, {"monster_soldier_light", SP_monster_soldier_light}, {"monster_soldier", SP_monster_soldier}, {"monster_soldier_ss", SP_monster_soldier_ss}, {"monster_tank", SP_monster_tank}, {"monster_tank_commander", SP_monster_tank}, {"monster_medic", SP_monster_medic}, {"monster_flipper", SP_monster_flipper}, {"monster_chick", SP_monster_chick}, {"monster_parasite", SP_monster_parasite}, {"monster_flyer", SP_monster_flyer}, {"monster_brain", SP_monster_brain}, {"monster_floater", SP_monster_floater}, {"monster_hover", SP_monster_hover}, {"monster_mutant", SP_monster_mutant}, {"monster_supertank", SP_monster_supertank}, {"monster_boss2", SP_monster_boss2}, {"monster_boss3_stand", SP_monster_boss3_stand}, {"monster_jorg", SP_monster_jorg}, {"monster_commander_body", SP_monster_commander_body}, {"turret_breach", SP_turret_breach}, {"turret_base", SP_turret_base}, {"turret_driver", SP_turret_driver}, */ {NULL, NULL} }; /* =============== ED_CallSpawn Finds the spawn function for the entity and calls it =============== */ void ED_CallSpawn (edict_t * ent) { spawn_t *s; gitem_t *item; int i; if (!ent->classname) { gi.dprintf ("ED_CallSpawn: NULL classname\n"); return; } // zucc - BD's item replacement idea CheckItem (ent); // check item spawn functions for (i = 0, item = itemlist; i < game.num_items; i++, item++) { if (!item->classname) continue; if (!strcmp (item->classname, ent->classname)) { // found it //FIREBLADE if ((!teamplay->value || teamdm->value || ctf->value == 2) && !dm_choose->value) { //FIREBLADE if (item->flags == IT_AMMO || item->flags == IT_WEAPON || item->flags == IT_FLAG /*|| item->flags == IT_ITEM || item->flags == IT_POWERUP*/) SpawnItem (ent, item); } else if (ctf->value && item->flags == IT_FLAG) { SpawnItem (ent, item); } return; } } // check normal spawn functions for (s = spawns; s->name; s++) { if (!strcmp (s->name, ent->classname)) { // found it s->spawn (ent); return; } } //AQ2:TNG - Igor adding wp_flags/itm_flags if (strcmp (ent->classname, "freed") != 0) { gi.dprintf ("%s doesn't have a spawn function\n", ent->classname); } //AQ2:TNG End adding flags } // zucc BD's checkitem function //An 2D array of items to look for and replace with... //item[i][0] = the Q2 item to look for //item[i][1] = the NS2 item to actually spawn #define ITEM_SWITCH_COUNT 15 char *sp_item[ITEM_SWITCH_COUNT][2] = { {"weapon_machinegun", "weapon_MP5"}, //{"weapon_supershotgun","weapon_HC"}, {"weapon_bfg", "weapon_M4"}, {"weapon_shotgun", "weapon_M3"}, //{"weapon_grenadelauncher","weapon_M203"}, {"weapon_chaingun", "weapon_Sniper"}, {"weapon_rocketlauncher", "weapon_HC"}, {"weapon_railgun", "weapon_Dual"}, {"ammo_bullets", "ammo_clip"}, {"ammo_rockets", "ammo_mag"}, {"ammo_cells", "ammo_m4"}, {"ammo_slugs", "ammo_sniper"}, {"ammo_shells", "ammo_m3"}, {"ammo_grenades", "weapon_Grenade"} , {"ammo_box", "ammo_m3"}, {"weapon_cannon", "weapon_HC"}, {"weapon_sniper", "weapon_Sniper"} }; void CheckItem (edict_t * ent) { int i; for (i = 0; i < ITEM_SWITCH_COUNT; i++) { //If it's a null entry, bypass it if (!sp_item[i][0]) continue; //Do the passed ent and our list match? if (strcmp (ent->classname, sp_item[i][0]) == 0) { //Yep. Replace the Q2 entity with our own. ent->classname = sp_item[i][1]; return; } } } /* ============= ED_NewString ============= */ char *ED_NewString (char *string) { char *newb, *new_p; int i, l; l = strlen (string) + 1; newb = gi.TagMalloc (l, TAG_LEVEL); new_p = newb; for (i = 0; i < l; i++) { if (string[i] == '\\' && i < l - 1) { i++; if (string[i] == 'n') *new_p++ = '\n'; else *new_p++ = '\\'; } else *new_p++ = string[i]; } return newb; } /* =============== ED_ParseField Takes a key/value pair and sets the binary values in an edict =============== */ void ED_ParseField (char *key, char *value, edict_t * ent) { field_t *f; byte *b; float v; vec3_t vec; for (f = fields; f->name; f++) { // FFL_NOSPAWN check in the following added in 3.20. Adding here. -FB if (!(f->flags & FFL_NOSPAWN) && !Q_stricmp (f->name, key)) { // found it if (f->flags & FFL_SPAWNTEMP) b = (byte *) & st; else b = (byte *) ent; switch (f->type) { case F_LSTRING: *(char **) (b + f->ofs) = ED_NewString (value); break; case F_VECTOR: sscanf (value, "%f %f %f", &vec[0], &vec[1], &vec[2]); ((float *) (b + f->ofs))[0] = vec[0]; ((float *) (b + f->ofs))[1] = vec[1]; ((float *) (b + f->ofs))[2] = vec[2]; break; case F_INT: *(int *) (b + f->ofs) = atoi (value); break; case F_FLOAT: *(float *) (b + f->ofs) = atof (value); break; case F_ANGLEHACK: v = atof (value); ((float *) (b + f->ofs))[0] = 0; ((float *) (b + f->ofs))[1] = v; ((float *) (b + f->ofs))[2] = 0; break; case F_IGNORE: break; // AQ:TNG JBravo fixing compiler warning. Still not sure 'bout this default: return; // End compiler warning fix } return; } } gi.dprintf ("%s is not a field\n", key); } /* ==================== ED_ParseEdict Parses an edict out of the given string, returning the new position ed should be a properly initialized empty edict. ==================== */ char * ED_ParseEdict (char *data, edict_t * ent) { qboolean init; char keyname[256]; char *com_token; init = false; memset (&st, 0, sizeof (st)); // go through all the dictionary pairs while (1) { // parse key com_token = COM_Parse (&data); if (com_token[0] == '}') break; if (!data) gi.error ("ED_ParseEntity: EOF without closing brace"); Q_strncpyz(keyname, com_token, sizeof(keyname)); // parse value com_token = COM_Parse (&data); if (!data) gi.error ("ED_ParseEntity: EOF without closing brace"); if (com_token[0] == '}') gi.error ("ED_ParseEntity: closing brace without data"); init = true; // keynames with a leading underscore are used for utility comments, // and are immediately discarded by quake if (keyname[0] == '_') continue; ED_ParseField (keyname, com_token, ent); } if (!init) memset (ent, 0, sizeof (*ent)); return data; } /* ================ G_FindTeams Chain together all entities with a matching team field. All but the first will have the FL_TEAMSLAVE flag set. All but the last will have the teamchain field set to the next one ================ */ void G_FindTeams (void) { edict_t *e, *e2, *chain; int i, j; int c, c2; c = 0; c2 = 0; for (i = 1, e = g_edicts + i; i < globals.num_edicts; i++, e++) { if (!e->inuse) continue; if (!e->team) continue; if (e->flags & FL_TEAMSLAVE) continue; chain = e; e->teammaster = e; c++; c2++; for (j = i + 1, e2 = e + 1; j < globals.num_edicts; j++, e2++) { if (!e2->inuse) continue; if (!e2->team) continue; if (e2->flags & FL_TEAMSLAVE) continue; if (!strcmp (e->team, e2->team)) { c2++; chain->teamchain = e2; e2->teammaster = e; chain = e2; e2->flags |= FL_TEAMSLAVE; } } } gi.dprintf ("%i teams with %i entities\n", c, c2); } /* ============== SpawnEntities Creates a server's entity / program execution context by parsing textual entity definitions out of an ent file. ============== */ void SpawnEntities (char *mapname, char *entities, char *spawnpoint) { edict_t *ent = NULL; int inhibit = 0; char *com_token; int i; float skill_level; //AQ2:TNG New Location Code char locfile[MAX_QPATH], line[256]; FILE *f; int readmore, x, y, z, rx, ry, rz, count; char *locationstr, *param; cvar_t *game_cvar; int u; // placedata_t temp; // Reset teamplay stuff for(i = TEAM1; i < TEAM_TOP; i++) { teams[i].score = teams[i].total = 0; teams[i].ready = teams[i].locked = 0; teams[i].pauses_used = teams[i].wantReset = 0; gi.cvar_forceset(teams[i].teamscore->name, "0"); } matchtime = 0; day_cycle_at = 0; team_round_going = team_game_going = team_round_countdown = 0; lights_camera_action = holding_on_tie_check = 0; timewarning = fragwarning = 0; teamCount = 2; if (ctf->value) { // Make sure teamplay is enabled if (!teamplay->value) { gi.dprintf ("CTF Enabled - Forcing teamplay on\n"); gi.cvar_forceset(teamplay->name, "1"); } if (use_3teams->value) { gi.dprintf ("CTF Enabled - Forcing 3Teams off\n"); gi.cvar_forceset(use_3teams->name, "0"); } if(teamdm->value) { gi.dprintf ("CTF Enabled - Forcing Team DM off\n"); gi.cvar_forceset(teamdm->name, "0"); } if (use_tourney->value) { gi.dprintf ("CTF Enabled - Forcing Tourney off\n"); gi.cvar_forceset(use_tourney->name, "0"); } if (!((int) (dmflags->value) & DF_NO_FRIENDLY_FIRE)) { gi.dprintf ("CTF Enabled - Forcing Friendly Fire off\n"); gi.cvar_forceset(dmflags->name, va("%i", (int)dmflags->value | DF_NO_FRIENDLY_FIRE)); } strcpy(teams[TEAM1].name, "RED"); strcpy(teams[TEAM2].name, "BLUE"); strcpy(teams[TEAM1].skin, "male/ctf_r"); strcpy(teams[TEAM2].skin, "male/ctf_b"); strcpy(teams[TEAM1].skin_index, "../players/male/ctf_r_i"); strcpy(teams[TEAM2].skin_index, "../players/male/ctf_b_i"); if(ctf->value == 2) gi.cvar_forceset(ctf->name, "1"); //for now } else if(teamdm->value) { if (!teamplay->value) { gi.dprintf ("Team Deathmatch Enabled - Forcing teamplay on\n"); gi.cvar_forceset(teamplay->name, "1"); } if (use_3teams->value) { gi.dprintf ("Team Deathmatch Enabled - Forcing 3Teams off\n"); gi.cvar_forceset(use_3teams->name, "0"); } if (use_tourney->value) { gi.dprintf ("Team Deathmatch Enabled - Forcing Tourney off\n"); gi.cvar_forceset(use_tourney->name, "0"); } } else if (use_3teams->value) { teamCount = 3; if (!teamplay->value) { gi.dprintf ("3 Teams Enabled - Forcing teamplay on\n"); gi.cvar_forceset(teamplay->name, "1"); } if (use_tourney->value) { gi.dprintf ("3 Teams Enabled - Forcing Tourney off\n"); gi.cvar_forceset(use_tourney->name, "0"); } if (!use_oldspawns->value) { gi.dprintf ("3 Teams Enabled - Forcing use_oldspawns on\n"); gi.cvar_forceset(use_oldspawns->name, "1"); } } else if (matchmode->value) { if (!teamplay->value) { gi.dprintf ("Matchmode Enabled - Forcing teamplay on\n"); gi.cvar_forceset(teamplay->name, "1"); } if (use_tourney->value) { gi.dprintf ("Matchmode Enabled - Forcing Tourney off\n"); gi.cvar_forceset(use_tourney->name, "0"); } } else if (use_tourney->value) { if (!teamplay->value) { gi.dprintf ("Tourney Enabled - Forcing teamplay on\n"); gi.cvar_forceset(teamplay->name, "1"); } } skill_level = floor (skill->value); if (skill_level < 0) skill_level = 0; if (skill_level > 3) skill_level = 3; if (skill->value != skill_level) gi.cvar_forceset ("skill", va("%f", skill_level)); SaveClientData (); gi.FreeTags (TAG_LEVEL); memset (&level, 0, sizeof (level)); memset (g_edicts, 0, game.maxentities * sizeof (g_edicts[0])); Q_strncpyz(level.mapname, mapname, sizeof(level.mapname)); Q_strncpyz(game.spawnpoint, spawnpoint, sizeof(game.spawnpoint)); // set client fields on player ents for (i = 0; i < game.maxclients; i++) g_edicts[i + 1].client = game.clients + i; // parse ents while (1) { // parse the opening brace com_token = COM_Parse (&entities); if (!entities) break; if (com_token[0] != '{') gi.error ("ED_LoadFromFile: found %s when expecting {", com_token); if (!ent) ent = g_edicts; else ent = G_Spawn (); entities = ED_ParseEdict (entities, ent); // yet another map hack if (!Q_stricmp (level.mapname, "command") && !Q_stricmp (ent->classname, "trigger_once") && !Q_stricmp (ent->model, "*27")) ent->spawnflags &= ~SPAWNFLAG_NOT_HARD; // remove things (except the world) from different skill levels or deathmatch if (ent != g_edicts) { if (deathmatch->value) { if (ent->spawnflags & SPAWNFLAG_NOT_DEATHMATCH) { G_FreeEdict (ent); inhibit++; continue; } } else { if ( /* ((coop->value) && (ent->spawnflags & SPAWNFLAG_NOT_COOP)) || */ ((skill->value == 0) && (ent->spawnflags & SPAWNFLAG_NOT_EASY)) || ((skill->value == 1) && (ent->spawnflags & SPAWNFLAG_NOT_MEDIUM)) || (((skill->value == 2) || (skill->value == 3)) && (ent->spawnflags & SPAWNFLAG_NOT_HARD))) { G_FreeEdict (ent); inhibit++; continue; } } ent->spawnflags &= ~(SPAWNFLAG_NOT_EASY | SPAWNFLAG_NOT_MEDIUM | SPAWNFLAG_NOT_HARD | SPAWNFLAG_NOT_COOP | SPAWNFLAG_NOT_DEATHMATCH); } ED_CallSpawn (ent); } gi.dprintf ("%i entities inhibited\n", inhibit); // AQ2:TNG Igor adding .flg files // CTF configuration if(ctf->value) { if(!CTFLoadConfig(level.mapname)) { if ((!G_Find(NULL, FOFS (classname), "item_flag_team1") || !G_Find(NULL, FOFS (classname), "item_flag_team2"))) { gi.dprintf ("No native CTF map, loading flag positions from file\n"); if (LoadFlagsFromFile (level.mapname)) ChangePlayerSpawns (); } } } // AQ2:TNG End adding .flg files G_FindTeams (); PlayerTrail_Init (); // TNG:Freud - Ghosts num_ghost_players = 0; //FIREBLADE if ((!teamplay->value || teamdm->value || ctf->value == 2) && !dm_choose->value) { //FIREBLADE //zucc for special items SetupSpecSpawn (); } else if (teamplay->value) { GetSpawnPoints (); //TNG:Freud - New spawning system if(!use_oldspawns->value) NS_GetSpawnPoints(); } //AQ2:TNG Slicer - New location code memset (ml_build, 0, sizeof (ml_build)); memset (ml_creator, 0, sizeof (ml_creator)); game_cvar = gi.cvar ("game", "", 0); if (!*game_cvar->string) Com_sprintf(locfile, sizeof(locfile), "%s/tng/%s.aqg", GAMEVERSION, level.mapname); else Com_sprintf(locfile, sizeof(locfile), "%s/tng/%s.aqg", game_cvar->string, level.mapname); f = fopen (locfile, "rt"); if (!f) { ml_count = 0; gi.dprintf ("No location file for %s\n", level.mapname); return; } gi.dprintf ("Location file: %s\n", level.mapname); readmore = 1; count = 0; while (readmore) { readmore = (fgets (line, 256, f) != NULL); param = strtok (line, " :\r\n\0"); if (line[0] == '#' && line[2] == 'C') { u = 0; for (i = 10; line[i] != '\n'; i++) { if (line[i] == '\r') continue; ml_creator[u] = line[i]; u++; } } if (line[0] == '#' && line[2] == 'B') { u = 0; for (i = 8; line[i] != '\n'; i++) { if (line[i] != ' ' && line[i] != '\r') { ml_build[u] = line[i]; u++; } } } ml_build[5] = 0; ml_creator[100] = 0; // TODO: better support for file comments if (!param || param[0] == '#') continue; x = atoi (param); param = strtok (NULL, " :\r\n\0"); if (!param) continue; y = atoi (param); param = strtok (NULL, " :\r\n\0"); if (!param) continue; z = atoi (param); param = strtok (NULL, " :\r\n\0"); if (!param) continue; rx = atoi (param); param = strtok (NULL, " :\r\n\0"); if (!param) continue; ry = atoi (param); param = strtok (NULL, " :\r\n\0"); if (!param) continue; rz = atoi (param); param = strtok (NULL, "\r\n\0"); if (!param) continue; locationstr = param; locationbase[count].x = x; locationbase[count].y = y; locationbase[count].z = z; locationbase[count].rx = rx; locationbase[count].ry = ry; locationbase[count].rz = rz; Q_strncpyz (locationbase[count].desc, locationstr, sizeof(locationbase[count].desc)); count++; if (count >= MAX_LOCATIONS_IN_BASE) { gi.dprintf ("Cannot read more than %d locations.\n", MAX_LOCATIONS_IN_BASE); break; } } ml_count = count; fclose (f); gi.dprintf ("Found %d locations.\n", count); } //=================================================================== #if 0 // cursor positioning xl < value > xr < value > yb < value > yt < value > xv < value > yv < value > // drawing statpic < name > pic < stat > num < fieldwidth > <stat > string < stat > // control if <stat >ifeq < stat > <value > ifbit < stat > <value > endif #endif char *single_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " /* // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " */ // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " // timer "if 9 " " xv 262 " " num 2 10 " " xv 296 " " pic 9 " "endif " // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " // zucc // sniper zoom graphic/icon "if 18 " " xr 0 " " yb 0 " " xv 0 " " yv 0 " " pic 18 " "endif " // clip(s) // puts them all the way on the right side of the screen "if 16 " " xv 0 " " yv 0 " " yb -24 " " xr -60 " " num 2 17 " " xr -24 " " pic 16 " "endif " // zucc special item ( vest etc ) "if 19 " " xv 0 " " yv 0 " " yb -72 " " xr -24 " " pic 19 " "endif " // zucc special weapon "if 20 " " xv 0 " " yv 0 " " yb -48 " " xr -24 " " pic 20 " "endif " // zucc grenades "if 28 " " xv 0 " " yv 0 " " yb -96 " " xr -60 " " num 2 29 " " xr -24 " " pic 28 " "endif " "if 21 " "xv 0 " "yb -58 " "string \"Viewing\" " "xv 64 " "stat_string 21 " "endif "; char *dm_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " /* // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " */ // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " /* // timer "if 9 " " xv 246 " " num 2 10 " " xv 296 " " pic 9 " "endif " */ // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " // zucc // clip(s) "if 16 " " xv 0 " " yv 0 " " yb -24 " " xr -60 " " num 2 17 " " xr -24 " " pic 16 " "endif " // zucc special item ( vest etc ) "if 19 " " xv 0 " " yv 0 " " yb -72 " " xr -24 " " pic 19 " "endif " // zucc special weapon "if 20 " " xv 0 " " yv 0 " " yb -48 " " xr -24 " " pic 20 " "endif " // zucc grenades "if 28 " " xv 0 " " yv 0 " " yb -96 " " xr -60 " " num 2 29 " " xr -24 " " pic 28 " "endif " "if 21 " "xv 0 " "yb -58 " "string \"Viewing\" " "xv 64 " "stat_string 21 " "endif " // sniper graphic/icon "if 18 " " xr 0 " " yb 0 " " xv 0 " " yv 0 " " pic 18 " "endif " // frags "xr -50 " "yt 2 " "num 3 14"; /* DM status bar for teamplay without individual scores -FB: */ char *dm_noscore_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " /* // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " */ // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " /* // timer "if 9 " " xv 246 " " num 2 10 " " xv 296 " " pic 9 " "endif " */ // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " // zucc // clip(s) "if 16 " " xv 0 " " yv 0 " " yb -24 " " xr -60 " " num 2 17 " " xr -24 " " pic 16 " "endif " // zucc special item ( vest etc ) "if 19 " " xv 0 " " yv 0 " " yb -72 " " xr -24 " " pic 19 " "endif " // zucc special weapon "if 20 " " xv 0 " " yv 0 " " yb -48 " " xr -24 " " pic 20 " "endif " // zucc grenades "if 28 " " xv 0 " " yv 0 " " yb -96 " " xr -60 " " num 2 29 " " xr -24 " " pic 28 " "endif " "if 21 " "xv 0 " "yb -58 " "string \"Viewing\" " "xv 64 " "stat_string 21 " "endif " // sniper graphic/icon "if 18 " " xr 0 " " yb 0 " " xv 0 " " yv 0 " " pic 18 " "endif " /* // frags "xr -50 " "yt 2 " "num 3 14" */ ; // END FB char *ctf_statusbar = "yb -24 " // health "xv 0 " "hnum " "xv 50 " "pic 0 " // ammo "if 2 " " xv 100 " " anum " " xv 150 " " pic 2 " "endif " /* // armor "if 4 " " xv 200 " " rnum " " xv 250 " " pic 4 " "endif " */ // selected item "if 6 " " xv 296 " " pic 6 " "endif " "yb -50 " // picked up item "if 7 " " xv 0 " " pic 7 " " xv 26 " " yb -42 " " stat_string 8 " " yb -50 " "endif " /* // timer "if 9 " " xv 246 " " num 2 10 " " xv 296 " " pic 9 " "endif " */ // help / weapon icon "if 11 " " xv 148 " " pic 11 " "endif " // zucc // clip(s) "if 16 " " xv 0 " " yv 0 " " yb -24 " " xr -60 " " num 2 17 " " xr -24 " " pic 16 " "endif " // zucc special item ( vest etc ) "if 19 " " xv 0 " " yv 0 " " yb -72 " " xr -24 " " pic 19 " "endif " // zucc special weapon "if 20 " " xv 0 " " yv 0 " " yb -48 " " xr -24 " " pic 20 " "endif " // zucc grenades "if 28 " " xv 0 " " yv 0 " " yb -96 " " xr -60 " " num 2 29 " " xr -24 " " pic 28 " "endif " "if 21 " "xv 0 " "yb -58 " "string \"Viewing\" " "xv 64 " "stat_string 21 " "endif " // sniper graphic/icon "if 18 " " xr 0 " " yb 0 " " xv 0 " " yv 0 " " pic 18 " "endif " // frags "xr -50 " "yt 2 " "num 3 14 " // Red Team "yb -164 " "if 24 " "xr -24 " "pic 24 " "endif " "xr -60 " "num 2 26 " // Blue Team "yb -140 " "if 25 " "xr -24 " "pic 25 " "endif " "xr -60 " "num 2 27 " // Flag carried "if 23 " "yt 26 " "xr -24 " "pic 23 " "endif "; /*QUAKED worldspawn (0 0 0) ? Only used for the world. "sky" environment map name "skyaxis" vector axis for rotating sky "skyrotate" speed of rotation in degrees/second "sounds" music cd track number "gravity" 800 is default gravity "message" text to print at user logon */ void SP_worldspawn (edict_t * ent) { int i; ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_BSP; ent->inuse = true; // since the world doesn't use G_Spawn() ent->s.modelindex = 1; // world model is always index 1 // reserve some spots for dead player bodies for coop / deathmatch InitBodyQue (); // set configstrings for items SetItemNames (); if (st.nextmap) strcpy (level.nextmap, st.nextmap); // make some data visible to the server if (ent->message && ent->message[0]) { Q_strncpyz(level.level_name, ent->message, sizeof(level.level_name)); gi.configstring (CS_NAME, level.level_name); } else { strcpy(level.level_name, level.mapname); } if (st.sky && st.sky[0]) gi.configstring (CS_SKY, st.sky); else gi.configstring (CS_SKY, "unit1_"); gi.configstring(CS_SKYROTATE, va("%f", st.skyrotate)); gi.configstring(CS_SKYAXIS, va("%f %f %f", st.skyaxis[0], st.skyaxis[1], st.skyaxis[2])); gi.configstring(CS_CDTRACK, va("%i", ent->sounds)); gi.configstring(CS_MAXCLIENTS, va("%i", (int)(maxclients->value))); //FIREBLADE if (nohud->value) { gi.configstring (CS_STATUSBAR, ""); } else //FIREBLADE { // status bar program if (!deathmatch->value) { gi.configstring (CS_STATUSBAR, single_statusbar); } else if (ctf->value) { gi.configstring (CS_STATUSBAR, ctf_statusbar); //precaches gi.imageindex ("sbfctf1"); gi.imageindex ("sbfctf2"); gi.imageindex ("i_ctf1"); gi.imageindex ("i_ctf2"); gi.imageindex ("i_ctf1d"); gi.imageindex ("i_ctf2d"); gi.imageindex ("i_ctf1t"); gi.imageindex ("i_ctf2t"); } else if (noscore->value && teamplay->value) { gi.configstring (CS_STATUSBAR, dm_noscore_statusbar); } else { gi.configstring (CS_STATUSBAR, dm_statusbar); } } //--------------- // help icon for statusbar gi.imageindex ("i_help"); level.pic_health = gi.imageindex ("i_health"); gi.imageindex ("help"); gi.imageindex ("field_3"); // zucc - preload sniper stuff gi.imageindex ("scope2x"); gi.imageindex ("scope4x"); gi.imageindex ("scope6x"); //FIREBLADE gi.soundindex ("atl/lights.wav"); gi.soundindex ("atl/camera.wav"); gi.soundindex ("atl/action.wav"); gi.imageindex ("tag1"); gi.imageindex ("tag2"); gi.imageindex ("tag3"); if (teamplay->value) { for(i = TEAM1; i < TEAM_TOP; i++) { if (teams[i].skin_index[0] == 0) { gi.dprintf ("No skin was specified for team %i in config file. Exiting.\n", i); exit (1); } gi.imageindex (teams[i].skin_index); } } // AQ2:TNG - Igor adding precache for sounds gi.soundindex ("tng/no_team_wins.wav"); gi.soundindex ("tng/team1_wins.wav"); gi.soundindex ("tng/team2_wins.wav"); gi.soundindex ("tng/team3_wins.wav"); gi.soundindex ("tng/1_minute.wav"); gi.soundindex ("tng/3_minutes.wav"); gi.soundindex ("tng/1_frag.wav"); gi.soundindex ("tng/2_frags.wav"); gi.soundindex ("tng/3_frags.wav"); gi.soundindex ("tng/impressive.wav"); gi.soundindex ("tng/excellent.wav"); gi.soundindex ("tng/accuracy.wav"); gi.soundindex ("tng/clanwar.wav"); gi.soundindex ("tng/disabled.wav"); gi.soundindex ("tng/enabled.wav"); gi.soundindex ("misc/flashlight.wav"); // Caching Flashlight // AQ2:TNG - end of precache sounds // disabled these because they are seriously silly to precache -hifi /* gi.soundindex("boss3/bs3idle1.wav"); gi.soundindex("user/letsrock.wav"); gi.soundindex("makron/laf4.wav"); gi.soundindex("world/elv.wav"); */ gi.soundindex("world/10_0.wav"); // countdown gi.soundindex("world/xian1.wav"); // intermission music gi.soundindex("misc/secret.wav"); // used for ctf swap sound gi.soundindex("misc/silencer.wav"); // all silencer weapons gi.soundindex("misc/headshot.wav"); // headshot sound gi.soundindex("misc/vest.wav"); // kevlar hit gi.soundindex("misc/flyloop.wav"); // throwing knife gi.soundindex("weapons/kick.wav"); // not loaded by any item, kick sound gi.soundindex("weapons/grenlf1a.wav"); // respawn sound PrecacheItems (); PrecacheRadioSounds (); //PG BUND - Begin PrecacheUserSounds (); //AQ2:TNG - Slicer Old location support //DescListInit(level.mapname); //AQ2:TNG END TourneyInit (); vInitLevel (); //PG BUND - End if (!st.gravity) gi.cvar_set ("sv_gravity", "800"); else gi.cvar_set ("sv_gravity", st.gravity); snd_fry = gi.soundindex ("player/fry.wav"); // standing in lava / slime gi.soundindex ("player/lava1.wav"); gi.soundindex ("player/lava2.wav"); gi.soundindex ("misc/pc_up.wav"); gi.soundindex ("misc/talk1.wav"); gi.soundindex ("misc/udeath.wav"); gi.soundindex ("misc/glurp.wav"); // gibs gi.soundindex ("items/respawn1.wav"); // sexed sounds gi.soundindex ("*death1.wav"); gi.soundindex ("*death2.wav"); gi.soundindex ("*death3.wav"); gi.soundindex ("*death4.wav"); gi.soundindex ("*fall1.wav"); gi.soundindex ("*fall2.wav"); gi.soundindex ("*gurp1.wav"); // drowning damage gi.soundindex ("*gurp2.wav"); gi.soundindex ("*jump1.wav"); // player jump gi.soundindex ("*pain25_1.wav"); gi.soundindex ("*pain25_2.wav"); gi.soundindex ("*pain50_1.wav"); gi.soundindex ("*pain50_2.wav"); gi.soundindex ("*pain75_1.wav"); gi.soundindex ("*pain75_2.wav"); gi.soundindex ("*pain100_1.wav"); gi.soundindex ("*pain100_2.wav"); //------------------- // precache vwep models gi.modelindex ("#w_mk23.md2"); gi.modelindex ("#w_mp5.md2"); gi.modelindex ("#w_m4.md2"); gi.modelindex ("#w_cannon.md2"); gi.modelindex ("#w_super90.md2"); gi.modelindex ("#w_sniper.md2"); gi.modelindex ("#w_akimbo.md2"); gi.modelindex ("#w_knife.md2"); gi.modelindex ("#a_m61frag.md2"); gi.modelindex ("sprites/null.sp2"); // null sprite gi.modelindex ("sprites/lsight.sp2"); // laser sight dot sprite gi.soundindex ("player/gasp1.wav"); // gasping for air gi.soundindex ("player/gasp2.wav"); // head breaking surface, not gasping gi.soundindex ("player/watr_in.wav"); // feet hitting water gi.soundindex ("player/watr_out.wav"); // feet leaving water gi.soundindex ("player/watr_un.wav"); // head going underwater gi.soundindex ("player/u_breath1.wav"); gi.soundindex ("player/u_breath2.wav"); gi.soundindex ("items/pkup.wav"); // bonus item pickup gi.soundindex ("world/land.wav"); // landing thud gi.soundindex ("misc/h2ohit1.wav"); // landing splash gi.soundindex ("items/damage.wav"); gi.soundindex ("items/protect.wav"); gi.soundindex ("items/protect4.wav"); gi.soundindex ("weapons/noammo.wav"); gi.soundindex ("infantry/inflies1.wav"); sm_meat_index = gi.modelindex ("models/objects/gibs/sm_meat/tris.md2"); gi.modelindex ("models/objects/gibs/arm/tris.md2"); gi.modelindex ("models/objects/gibs/bone/tris.md2"); gi.modelindex ("models/objects/gibs/bone2/tris.md2"); gi.modelindex ("models/objects/gibs/chest/tris.md2"); gi.modelindex ("models/objects/gibs/skull/tris.md2"); gi.modelindex ("models/objects/gibs/head2/tris.md2"); // // Setup light animation tables. 'a' is total darkness, 'z' is doublebright. // /* Darkmatch. Darkmatch has three settings: 0 - normal, no changes to lights 1 - all lights are off. 2 - dusk/dawn mode. 3 - using the day_cycle to change the lights every xx seconds as defined by day_cycle */ if (darkmatch->value == 1) gi.configstring (CS_LIGHTS + 0, "a"); // Pitch Black else if (darkmatch->value == 2) gi.configstring (CS_LIGHTS + 0, "b"); // Dusk else gi.configstring (CS_LIGHTS + 0, "m"); // 0 normal gi.configstring (CS_LIGHTS + 1, "mmnmmommommnonmmonqnmmo"); // 1 FLICKER (first variety) gi.configstring (CS_LIGHTS + 2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba"); // 2 SLOW STRONG PULSE gi.configstring (CS_LIGHTS + 3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg"); // 3 CANDLE (first variety) gi.configstring (CS_LIGHTS + 4, "mamamamamama"); // 4 FAST STROBE gi.configstring (CS_LIGHTS + 5, "jklmnopqrstuvwxyzyxwvutsrqponmlkj"); // 5 GENTLE PULSE 1 gi.configstring (CS_LIGHTS + 6, "nmonqnmomnmomomno"); // 6 FLICKER (second variety) gi.configstring (CS_LIGHTS + 7, "mmmaaaabcdefgmmmmaaaammmaamm"); // 7 CANDLE (second variety) gi.configstring (CS_LIGHTS + 8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa"); // 8 CANDLE (third variety) gi.configstring (CS_LIGHTS + 9, "aaaaaaaazzzzzzzz"); // 9 SLOW STROBE (fourth variety) gi.configstring (CS_LIGHTS + 10, "mmamammmmammamamaaamammma"); // 10 FLUORESCENT FLICKER gi.configstring (CS_LIGHTS + 11, "abcdefghijklmnopqrrqponmlkjihgfedcba"); // 11 SLOW PULSE NOT FADE TO BLACK // styles 32-62 are assigned by the light program for switchable lights gi.configstring (CS_LIGHTS + 63, "a"); // 63 testing //FB 6/2/99 if (took_damage != NULL) gi.TagFree (took_damage); took_damage = (int *)gi.TagMalloc (sizeof (int) * game.maxclients, TAG_GAME); //FB 6/2/99 } int LoadFlagsFromFile (char *mapname) { FILE *fp; char buf[1024], *s; // int len; int i; edict_t *ent; vec3_t position; sprintf (buf, "%s/tng/%s.flg", GAMEVERSION, mapname); fp = fopen (buf, "r"); if (!fp) { gi.dprintf ("Warning: No flag definition file for map %s.\n", mapname); return 0; } // FIXME: remove this functionality completely in the future gi.dprintf ("Warning: .flg files are deprecated, use .ctf ones for more control!\n"); i = 0; while (fgets(buf, 1000, fp) != NULL) { //first remove trailing spaces s = buf+strlen(buf)-1; for (; *s && (*s == '\r' || *s == '\n' || *s == ' '); s--) *s = '\0'; //check if it's a valid line if (strlen(buf) >= 5 && strncmp(buf, "#", 1) && strncmp(buf, "//", 2) && i < 2) { //a little bit dirty... :) if (sscanf(buf, "<%f %f %f>", &position[0], &position[1], &position[2]) != 3) continue; ent = G_Spawn (); ent->spawnflags &= ~(SPAWNFLAG_NOT_EASY | SPAWNFLAG_NOT_MEDIUM | SPAWNFLAG_NOT_HARD | SPAWNFLAG_NOT_COOP | SPAWNFLAG_NOT_DEATHMATCH); VectorCopy(position, ent->s.origin); if (!i) // Red Flag ent->classname = ED_NewString ("item_flag_team1"); else // Blue Flag ent->classname = ED_NewString ("item_flag_team2"); ED_CallSpawn (ent); i++; } } fclose (fp); if(i < 2) return (0); return (1); } // This function changes the nearest two spawnpoint from each flag // to info_player_teamX, so the other team won't restart // beneath the flag of the other team void ChangePlayerSpawns () { edict_t *flag1 = NULL, *flag2 = NULL; edict_t *spot, *spot1, *spot2, *spot3, *spot4; float range, range1, range2, range3, range4; range1 = range2 = range3 = range4 = 99999; spot = spot1 = spot2 = spot3 = spot4 = NULL; flag1 = G_Find (flag1, FOFS(classname), "item_flag_team1"); flag2 = G_Find (flag2, FOFS(classname), "item_flag_team2"); if(!flag1 || !flag2) { gi.dprintf("Warning: ChangePlayerSpawns() requires both flags!\n"); return; } while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { range = Distance(spot->s.origin, flag1->s.origin); if (range < range1) { range3 = range1; spot3 = spot1; range1 = range; spot1 = spot; } else if (range < range3) { range3 = range; spot3 = spot; } range = Distance(spot->s.origin, flag2->s.origin); if (range < range2) { range4 = range2; spot4 = spot2; range2 = range; spot2 = spot; } else if (range < range4) { range4 = range; spot4 = spot; } } if (spot1) { // gi.dprintf ("Ersetze info_player_deathmatch auf <%f %f %f> durch info_player_team1\n", spot1->s.origin[0], spot1->s.origin[1], spot1->s.origin[2]); strcpy (spot1->classname, "info_player_team1"); } if (spot2) { // gi.dprintf ("Ersetze info_player_deathmatch auf <%f %f %f> durch info_player_team2\n", spot2->s.origin[0], spot2->s.origin[1], spot2->s.origin[2]); strcpy (spot2->classname, "info_player_team2"); } if (spot3) { // gi.dprintf ("Ersetze info_player_deathmatch auf <%f %f %f> durch info_player_team1\n", spot3->s.origin[0], spot3->s.origin[1], spot3->s.origin[2]); strcpy (spot3->classname, "info_player_team1"); } if (spot4) { // gi.dprintf ("Ersetze info_player_deathmatch auf <%f %f %f> durch info_player_team2\n", spot4->s.origin[0], spot4->s.origin[1], spot4->s.origin[2]); strcpy (spot4->classname, "info_player_team2"); } }
538
./aq2-tng/source/g_turret.c
//----------------------------------------------------------------------------- // g_turret.c // // $Id: g_turret.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_turret.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:31:56 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" void AnglesNormalize (vec3_t vec) { while (vec[0] > 360) vec[0] -= 360; while (vec[0] < 0) vec[0] += 360; while (vec[1] > 360) vec[1] -= 360; while (vec[1] < 0) vec[1] += 360; } float SnapToEights (float x) { x *= 8.0; if (x > 0.0) x += 0.5; else x -= 0.5; return 0.125 * (int) x; } void turret_blocked (edict_t * self, edict_t * other) { edict_t *attacker; if (other->takedamage) { if (self->teammaster->owner) attacker = self->teammaster->owner; else attacker = self->teammaster; T_Damage (other, self, attacker, vec3_origin, other->s.origin, vec3_origin, self->teammaster->dmg, 10, 0, MOD_CRUSH); } } /*QUAKED turret_breach (0 0 0) ? This portion of the turret can change both pitch and yaw. The model should be made with a flat pitch. It (and the associated base) need to be oriented towards 0. Use "angle" to set the starting angle. "speed" default 50 "dmg" default 10 "angle" point this forward "target" point this at an info_notnull at the muzzle tip "minpitch" min acceptable pitch angle : default -30 "maxpitch" max acceptable pitch angle : default 30 "minyaw" min acceptable yaw angle : default 0 "maxyaw" max acceptable yaw angle : default 360 */ void turret_breach_fire (edict_t * self) { vec3_t f, r, u; vec3_t start; int damage; int speed; AngleVectors (self->s.angles, f, r, u); VectorMA (self->s.origin, self->move_origin[0], f, start); VectorMA (start, self->move_origin[1], r, start); VectorMA (start, self->move_origin[2], u, start); damage = 100 + random () * 50; speed = 550 + 50 * skill->value; fire_rocket (self->teammaster->owner, start, f, damage, speed, 150, damage); gi.positioned_sound (start, self, CHAN_WEAPON, gi.soundindex ("weapons/rocklf1a.wav"), 1, ATTN_NORM, 0); } void turret_breach_think (edict_t * self) { edict_t *ent; vec3_t current_angles; vec3_t delta; VectorCopy (self->s.angles, current_angles); AnglesNormalize (current_angles); AnglesNormalize (self->move_angles); if (self->move_angles[PITCH] > 180) self->move_angles[PITCH] -= 360; // clamp angles to mins & maxs if (self->move_angles[PITCH] > self->pos1[PITCH]) self->move_angles[PITCH] = self->pos1[PITCH]; else if (self->move_angles[PITCH] < self->pos2[PITCH]) self->move_angles[PITCH] = self->pos2[PITCH]; if ((self->move_angles[YAW] < self->pos1[YAW]) || (self->move_angles[YAW] > self->pos2[YAW])) { float dmin, dmax; dmin = fabs (self->pos1[YAW] - self->move_angles[YAW]); if (dmin < -180) dmin += 360; else if (dmin > 180) dmin -= 360; dmax = fabs (self->pos2[YAW] - self->move_angles[YAW]); if (dmax < -180) dmax += 360; else if (dmax > 180) dmax -= 360; if (fabs (dmin) < fabs (dmax)) self->move_angles[YAW] = self->pos1[YAW]; else self->move_angles[YAW] = self->pos2[YAW]; } VectorSubtract (self->move_angles, current_angles, delta); if (delta[0] < -180) delta[0] += 360; else if (delta[0] > 180) delta[0] -= 360; if (delta[1] < -180) delta[1] += 360; else if (delta[1] > 180) delta[1] -= 360; delta[2] = 0; if (delta[0] > self->speed * FRAMETIME) delta[0] = self->speed * FRAMETIME; if (delta[0] < -1 * self->speed * FRAMETIME) delta[0] = -1 * self->speed * FRAMETIME; if (delta[1] > self->speed * FRAMETIME) delta[1] = self->speed * FRAMETIME; if (delta[1] < -1 * self->speed * FRAMETIME) delta[1] = -1 * self->speed * FRAMETIME; VectorScale (delta, 1.0 / FRAMETIME, self->avelocity); self->nextthink = level.time + FRAMETIME; for (ent = self->teammaster; ent; ent = ent->teamchain) ent->avelocity[1] = self->avelocity[1]; // if we have adriver, adjust his velocities if (self->owner) { float angle; float target_z; float diff; vec3_t target; vec3_t dir; // angular is easy, just copy ours self->owner->avelocity[0] = self->avelocity[0]; self->owner->avelocity[1] = self->avelocity[1]; // x & y angle = self->s.angles[1] + self->owner->move_origin[1]; angle *= (M_PI * 2 / 360); target[0] = SnapToEights (self->s.origin[0] + cos (angle) * self->owner->move_origin[0]); target[1] = SnapToEights (self->s.origin[1] + sin (angle) * self->owner->move_origin[0]); target[2] = self->owner->s.origin[2]; VectorSubtract (target, self->owner->s.origin, dir); self->owner->velocity[0] = dir[0] * 1.0 / FRAMETIME; self->owner->velocity[1] = dir[1] * 1.0 / FRAMETIME; // z angle = self->s.angles[PITCH] * (M_PI * 2 / 360); target_z = SnapToEights (self->s.origin[2] + self->owner->move_origin[0] * tan (angle) + self->owner->move_origin[2]); diff = target_z - self->owner->s.origin[2]; self->owner->velocity[2] = diff * 1.0 / FRAMETIME; if (self->spawnflags & 65536) { turret_breach_fire (self); self->spawnflags &= ~65536; } } } void turret_breach_finish_init (edict_t * self) { // get and save info for muzzle location if (!self->target) { gi.dprintf ("%s at %s needs a target\n", self->classname, vtos (self->s.origin)); } else { self->target_ent = G_PickTarget (self->target); VectorSubtract (self->target_ent->s.origin, self->s.origin, self->move_origin); G_FreeEdict (self->target_ent); } self->teammaster->dmg = self->dmg; self->think = turret_breach_think; self->think (self); } void SP_turret_breach (edict_t * self) { self->solid = SOLID_BSP; self->movetype = MOVETYPE_PUSH; gi.setmodel (self, self->model); if (!self->speed) self->speed = 50; if (!self->dmg) self->dmg = 10; if (!st.minpitch) st.minpitch = -30; if (!st.maxpitch) st.maxpitch = 30; if (!st.maxyaw) st.maxyaw = 360; self->pos1[PITCH] = -1 * st.minpitch; self->pos1[YAW] = st.minyaw; self->pos2[PITCH] = -1 * st.maxpitch; self->pos2[YAW] = st.maxyaw; self->ideal_yaw = self->s.angles[YAW]; self->move_angles[YAW] = self->ideal_yaw; self->blocked = turret_blocked; self->think = turret_breach_finish_init; self->nextthink = level.time + FRAMETIME; gi.linkentity (self); } /*QUAKED turret_base (0 0 0) ? This portion of the turret changes yaw only. MUST be teamed with a turret_breach. */ void SP_turret_base (edict_t * self) { self->solid = SOLID_BSP; self->movetype = MOVETYPE_PUSH; gi.setmodel (self, self->model); self->blocked = turret_blocked; gi.linkentity (self); } /*QUAKED turret_driver (1 .5 0) (-16 -16 -24) (16 16 32) Must NOT be on the team with the rest of the turret parts. Instead it must target the turret_breach. */ void infantry_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage); void infantry_stand (edict_t * self); void monster_use (edict_t * self, edict_t * other, edict_t * activator); void turret_driver_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { edict_t *ent; // level the gun self->target_ent->move_angles[0] = 0; // remove the driver from the end of them team chain for (ent = self->target_ent->teammaster; ent->teamchain != self; ent = ent->teamchain) ; ent->teamchain = NULL; self->teammaster = NULL; self->flags &= ~FL_TEAMSLAVE; self->target_ent->owner = NULL; self->target_ent->teammaster->owner = NULL; //FB infantry_die (self, inflictor, attacker, damage); } qboolean FindTarget (edict_t * self); void turret_driver_think (edict_t * self) { vec3_t target; vec3_t dir; float reaction_time; self->nextthink = level.time + FRAMETIME; if (self->enemy && (!self->enemy->inuse || self->enemy->health <= 0)) self->enemy = NULL; if (!self->enemy) { if (!FindTarget (self)) return; self->monsterinfo.trail_time = level.time; self->monsterinfo.aiflags &= ~AI_LOST_SIGHT; } else { if (visible (self, self->enemy)) { if (self->monsterinfo.aiflags & AI_LOST_SIGHT) { self->monsterinfo.trail_time = level.time; self->monsterinfo.aiflags &= ~AI_LOST_SIGHT; } } else { self->monsterinfo.aiflags |= AI_LOST_SIGHT; return; } } // let the turret know where we want it to aim VectorCopy (self->enemy->s.origin, target); target[2] += self->enemy->viewheight; VectorSubtract (target, self->target_ent->s.origin, dir); vectoangles (dir, self->target_ent->move_angles); // decide if we should shoot if (level.time < self->monsterinfo.attack_finished) return; reaction_time = (3 - skill->value) * 1.0; if ((level.time - self->monsterinfo.trail_time) < reaction_time) return; self->monsterinfo.attack_finished = level.time + reaction_time + 1.0; //FIXME how do we really want to pass this along? self->target_ent->spawnflags |= 65536; } void turret_driver_link (edict_t * self) { vec3_t vec; edict_t *ent; self->think = turret_driver_think; self->nextthink = level.time + FRAMETIME; self->target_ent = G_PickTarget (self->target); self->target_ent->owner = self; self->target_ent->teammaster->owner = self; VectorCopy (self->target_ent->s.angles, self->s.angles); vec[0] = self->target_ent->s.origin[0] - self->s.origin[0]; vec[1] = self->target_ent->s.origin[1] - self->s.origin[1]; vec[2] = 0; self->move_origin[0] = VectorLength (vec); VectorSubtract (self->s.origin, self->target_ent->s.origin, vec); vectoangles (vec, vec); AnglesNormalize (vec); self->move_origin[1] = vec[1]; self->move_origin[2] = self->s.origin[2] - self->target_ent->s.origin[2]; // add the driver to the end of them team chain for (ent = self->target_ent->teammaster; ent->teamchain; ent = ent->teamchain) ; ent->teamchain = self; self->teammaster = self->target_ent->teammaster; self->flags |= FL_TEAMSLAVE; } void SP_turret_driver (edict_t * self) { if (deathmatch->value) { G_FreeEdict (self); return; } self->movetype = MOVETYPE_PUSH; self->solid = SOLID_BBOX; self->s.modelindex = gi.modelindex ("models/monsters/infantry/tris.md2"); VectorSet (self->mins, -16, -16, -24); VectorSet (self->maxs, 16, 16, 32); self->health = 100; self->gib_health = 0; self->mass = 200; self->viewheight = 24; self->die = turret_driver_die; //FB self->monsterinfo.stand = infantry_stand; self->flags |= FL_NO_KNOCKBACK; level.total_monsters++; self->svflags |= SVF_MONSTER; self->s.renderfx |= RF_FRAMELERP; self->takedamage = DAMAGE_AIM; self->use = monster_use; self->clipmask = MASK_MONSTERSOLID; VectorCopy (self->s.origin, self->s.old_origin); self->monsterinfo.aiflags |= AI_STAND_GROUND | AI_DUCKED; if (st.item) { self->item = FindItemByClassname (st.item); if (!self->item) gi.dprintf ("%s at %s has bad item: %s\n", self->classname, vtos (self->s.origin), st.item); } self->think = turret_driver_link; self->nextthink = level.time + FRAMETIME; gi.linkentity (self); }
539
./aq2-tng/source/q_shared.c
//----------------------------------------------------------------------------- // q_shared.c // // $Id: q_shared.c,v 1.4 2001/09/28 14:20:25 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: q_shared.c,v $ // Revision 1.4 2001/09/28 14:20:25 slicerdw // Few tweaks.. // // Revision 1.3 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.2 2001/08/19 01:22:25 deathwatch // cleaned the formatting of some files // // Revision 1.1.1.1 2001/05/06 17:24:20 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "q_shared.h" vec3_t vec3_origin = { 0, 0, 0 }; //============================================================================ void MakeNormalVectors (const vec3_t forward, vec3_t right, vec3_t up) { float d; // this rotate and negat guarantees a vector // not colinear with the original VectorSet (right, forward[2], -forward[0], forward[1] ); d = DotProduct (right, forward); VectorMA (right, -d, forward, right); VectorNormalize (right); CrossProduct (right, forward, up); } void RotatePointAroundVector( vec3_t dst, const vec3_t dir, const vec3_t point, float degrees ) { float t0, t1, c, s; vec3_t vr, vu, vf; s = DEG2RAD (degrees); c = cos (s); s = sin (s); VectorCopy (dir, vf); MakeNormalVectors (vf, vr, vu); t0 = vr[0] * c + vu[0] * -s; t1 = vr[0] * s + vu[0] * c; dst[0] = (t0 * vr[0] + t1 * vu[0] + vf[0] * vf[0]) * point[0] + (t0 * vr[1] + t1 * vu[1] + vf[0] * vf[1]) * point[1] + (t0 * vr[2] + t1 * vu[2] + vf[0] * vf[2]) * point[2]; t0 = vr[1] * c + vu[1] * -s; t1 = vr[1] * s + vu[1] * c; dst[1] = (t0 * vr[0] + t1 * vu[0] + vf[1] * vf[0]) * point[0] + (t0 * vr[1] + t1 * vu[1] + vf[1] * vf[1]) * point[1] + (t0 * vr[2] + t1 * vu[2] + vf[1] * vf[2]) * point[2]; t0 = vr[2] * c + vu[2] * -s; t1 = vr[2] * s + vu[2] * c; dst[2] = (t0 * vr[0] + t1 * vu[0] + vf[2] * vf[0]) * point[0] + (t0 * vr[1] + t1 * vu[1] + vf[2] * vf[1]) * point[1] + (t0 * vr[2] + t1 * vu[2] + vf[2] * vf[2]) * point[2]; } void AngleVectors (const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { float angle; static float sr, sp, sy, cr, cp, cy, t; // static to help MS compiler fp bugs angle = DEG2RAD(angles[YAW]); sy = sin(angle); cy = cos(angle); angle = DEG2RAD(angles[PITCH]); sp = sin(angle); cp = cos(angle); if (forward) { forward[0] = cp*cy; forward[1] = cp*sy; forward[2] = -sp; } if (right || up) { angle = DEG2RAD(angles[ROLL]); sr = sin(angle); cr = cos(angle); if (right) { t = sr*sp; right[0] = (-1*t*cy+-1*cr*-sy); right[1] = (-1*t*sy+-1*cr*cy); right[2] = -1*sr*cp; } if (up) { t = cr*sp; up[0] = (t*cy+-sr*-sy); up[1] = (t*sy+-sr*cy); up[2] = cr*cp; } } } void ProjectPointOnPlane( vec3_t dst, const vec3_t p, const vec3_t normal ) { float d, inv_denom; inv_denom = 1.0F / DotProduct( normal, normal ); d = DotProduct( normal, p ) * inv_denom; dst[0] = p[0] - d * normal[0] * inv_denom; dst[1] = p[1] - d * normal[1] * inv_denom; dst[2] = p[2] - d * normal[2] * inv_denom; } /* ** assumes "src" is normalized */ void PerpendicularVector( vec3_t dst, const vec3_t src ) { int i, pos = 0; float minelem = 1.0F; vec3_t tempvec = {0, 0, 0}; /* ** find the smallest magnitude axially aligned vector */ for ( i = 0; i < 3; i++ ) { if ( fabs( src[i] ) < minelem ) { pos = i; minelem = fabs( src[i] ); } } tempvec[pos] = 1.0F; /* ** project the point onto the plane defined by src */ ProjectPointOnPlane( dst, tempvec, src ); /* ** normalize the result */ VectorNormalize( dst ); } /* ================ R_ConcatRotations ================ */ void R_ConcatRotations (float in1[3][3], float in2[3][3], float out[3][3]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + in1[0][2] * in2[2][2]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + in1[1][2] * in2[2][2]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + in1[2][2] * in2[2][2]; } /* ================ R_ConcatTransforms ================ */ void R_ConcatTransforms (float in1[3][4], float in2[3][4], float out[3][4]) { out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] + in1[0][2] * in2[2][0]; out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] + in1[0][2] * in2[2][1]; out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] + in1[0][2] * in2[2][2]; out[0][3] = in1[0][0] * in2[0][3] + in1[0][1] * in2[1][3] + in1[0][2] * in2[2][3] + in1[0][3]; out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] + in1[1][2] * in2[2][0]; out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] + in1[1][2] * in2[2][1]; out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] + in1[1][2] * in2[2][2]; out[1][3] = in1[1][0] * in2[0][3] + in1[1][1] * in2[1][3] + in1[1][2] * in2[2][3] + in1[1][3]; out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] + in1[2][2] * in2[2][0]; out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] + in1[2][2] * in2[2][1]; out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] + in1[2][2] * in2[2][2]; out[2][3] = in1[2][0] * in2[0][3] + in1[2][1] * in2[1][3] + in1[2][2] * in2[2][3] + in1[2][3]; } //============================================================================ /*float Q_fabs (float f) { int tmp = * ( int * ) &f; tmp &= 0x7FFFFFFF; return * ( float * ) &tmp; }*/ #if defined _M_IX86 && !defined C_ONLY #pragma warning (disable:4035) __declspec( naked ) long Q_ftol( float f ) { static int tmp; __asm fld dword ptr [esp+4] __asm fistp tmp __asm mov eax, tmp __asm ret } #pragma warning (default:4035) #endif /* =============== LerpAngle =============== */ float LerpAngle (float a2, float a1, float frac) { if (a1 - a2 > 180) a1 -= 360; else if (a1 - a2 < -180) a1 += 360; return a2 + frac * (a1 - a2); } float anglemod (float a) { return (360.0 / 65536) * ((int) (a * (65536 / 360.0)) & 65535); } // this is the slow, general version int BoxOnPlaneSide2 (vec3_t emins, vec3_t emaxs, struct cplane_s *p) { int i; float dist1, dist2; int sides; vec3_t corners[2]; for (i = 0; i < 3; i++) { if (p->normal[i] < 0) { corners[0][i] = emins[i]; corners[1][i] = emaxs[i]; } else { corners[1][i] = emins[i]; corners[0][i] = emaxs[i]; } } dist1 = DotProduct (p->normal, corners[0]) - p->dist; dist2 = DotProduct (p->normal, corners[1]) - p->dist; sides = 0; if (dist1 >= 0) sides = 1; if (dist2 < 0) sides |= 2; return sides; } /* ================== BoxOnPlaneSide Returns 1, 2, or 1 + 2 ================== */ #if !id386 || defined __linux__ || defined __FreeBSD__ || defined __sun__ int BoxOnPlaneSide(const vec3_t emins, const vec3_t emaxs, const struct cplane_s *p) { float dist1, dist2; int sides; // fast axial cases if (p->type < 3) { if (p->dist <= emins[p->type]) return 1; if (p->dist >= emaxs[p->type]) return 2; return 3; } // general case switch (p->signbits) { case 0: dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; dist2 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; break; case 1: dist1 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; break; case 2: dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; dist2 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; break; case 3: dist1 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; break; case 4: dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; dist2 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; break; case 5: dist1 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emins[2]; dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emaxs[2]; break; case 6: dist1 = p->normal[0] * emaxs[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; dist2 = p->normal[0] * emins[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; break; case 7: dist1 = p->normal[0] * emins[0] + p->normal[1] * emins[1] + p->normal[2] * emins[2]; dist2 = p->normal[0] * emaxs[0] + p->normal[1] * emaxs[1] + p->normal[2] * emaxs[2]; break; default: dist1 = dist2 = 0; // shut up compiler assert(0); break; } sides = 0; if (dist1 >= p->dist) sides = 1; if (dist2 < p->dist) sides |= 2; assert(sides != 0); return sides; } #else #pragma warning( disable: 4035 ) __declspec( naked ) int BoxOnPlaneSide (const vec3_t emins, const vec3_t emaxs, const struct cplane_s *p) { static int bops_initialized; static int Ljmptab[8]; __asm { push ebx cmp bops_initialized, 1 je initialized mov bops_initialized, 1 mov Ljmptab[0*4], offset Lcase0 mov Ljmptab[1*4], offset Lcase1 mov Ljmptab[2*4], offset Lcase2 mov Ljmptab[3*4], offset Lcase3 mov Ljmptab[4*4], offset Lcase4 mov Ljmptab[5*4], offset Lcase5 mov Ljmptab[6*4], offset Lcase6 mov Ljmptab[7*4], offset Lcase7 initialized: mov edx,ds:dword ptr[4+12+esp] mov ecx,ds:dword ptr[4+4+esp] xor eax,eax mov ebx,ds:dword ptr[4+8+esp] mov al,ds:byte ptr[17+edx] cmp al,8 jge Lerror fld ds:dword ptr[0+edx] fld st(0) jmp dword ptr[Ljmptab+eax*4] Lcase0: fmul ds:dword ptr[ebx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ecx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ebx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ecx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ebx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ecx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase1: fmul ds:dword ptr[ecx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ebx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ebx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ecx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ebx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ecx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase2: fmul ds:dword ptr[ebx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ecx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ecx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ebx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ebx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ecx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase3: fmul ds:dword ptr[ecx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ebx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ecx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ebx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ebx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ecx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase4: fmul ds:dword ptr[ebx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ecx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ebx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ecx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ecx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ebx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase5: fmul ds:dword ptr[ecx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ebx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ebx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ecx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ecx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ebx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase6: fmul ds:dword ptr[ebx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ecx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ecx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ebx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ecx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ebx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) jmp LSetSides Lcase7: fmul ds:dword ptr[ecx] fld ds:dword ptr[0+4+edx] fxch st(2) fmul ds:dword ptr[ebx] fxch st(2) fld st(0) fmul ds:dword ptr[4+ecx] fld ds:dword ptr[0+8+edx] fxch st(2) fmul ds:dword ptr[4+ebx] fxch st(2) fld st(0) fmul ds:dword ptr[8+ecx] fxch st(5) faddp st(3),st(0) fmul ds:dword ptr[8+ebx] fxch st(1) faddp st(3),st(0) fxch st(3) faddp st(2),st(0) LSetSides: faddp st(2),st(0) fcomp ds:dword ptr[12+edx] xor ecx,ecx fnstsw ax fcomp ds:dword ptr[12+edx] and ah,1 xor ah,1 add cl,ah fnstsw ax and ah,1 add ah,ah add cl,ah pop ebx mov eax,ecx ret Lerror: int 3 } } #pragma warning( default: 4035 ) #endif void AddPointToBounds (const vec3_t v, vec3_t mins, vec3_t maxs) { int i; vec_t val; for (i=0 ; i<3 ; i++) { val = v[i]; if (val < mins[i]) mins[i] = val; if (val > maxs[i]) maxs[i] = val; } } vec_t VectorNormalize (vec3_t v) { float length, ilength; length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; if (length) { length = sqrt (length); // FIXME ilength = 1/length; v[0] *= ilength; v[1] *= ilength; v[2] *= ilength; } return length; } vec_t VectorNormalize2 (const vec3_t v, vec3_t out) { float length, ilength; length = v[0]*v[0] + v[1]*v[1] + v[2]*v[2]; if (length) { length = sqrt (length); // FIXME ilength = 1/length; out[0] = v[0]*ilength; out[1] = v[1]*ilength; out[2] = v[2]*ilength; } return length; } int Q_log2(int val) { int answer=0; while (val>>=1) answer++; return answer; } //==================================================================================== /* ============ COM_SkipPath ============ */ char *COM_SkipPath (char *pathname) { char *last; last = pathname; while (*pathname) { if (*pathname == '/') last = pathname + 1; pathname++; } return last; } /* ============ COM_StripExtension ============ */ void COM_StripExtension (char *in, char *out) { while (*in && *in != '.') *out++ = *in++; *out = 0; } /* ============ COM_FileExtension ============ */ char *COM_FileExtension (char *in) { static char exten[8]; int i; while (*in && *in != '.') in++; if (!*in) return ""; in++; for (i = 0; i < 7 && *in; i++, in++) exten[i] = *in; exten[i] = 0; return exten; } /* ============ COM_FileBase ============ */ void COM_FileBase (char *in, char *out) { char *s, *s2; s = in + strlen (in) - 1; while (s != in && *s != '.') s--; for (s2 = s; s2 != in && *s2 != '/'; s2--) ; if (s - s2 < 2) out[0] = 0; else { s--; strncpy (out, s2 + 1, s - s2); out[s - s2] = 0; } } /* ============ COM_FilePath Returns the path up to, but not including the last / ============ */ void COM_FilePath (char *in, char *out) { char *s; s = in + strlen (in) - 1; while (s != in && *s != '/') s--; strncpy (out, in, s - in); out[s - in] = 0; } /* ================== COM_DefaultExtension ================== */ void COM_DefaultExtension (char *path, char *extension) { char *src; // // if path doesn't have a .EXT, append extension // (extension should include the .) // src = path + strlen (path) - 1; while (*src != '/' && src != path) { if (*src == '.') return; // it has an extension src--; } strcat (path, extension); } /* ============ va does a varargs printf into a temp buffer, so I don't need to have varargs versions of all text functions. FIXME: make this buffer size safe someday ============ */ char *va(const char *format, ...) { va_list argptr; static int str_index; static char string[2][1024]; str_index = !str_index; va_start (argptr, format); vsnprintf (string[str_index], sizeof(string[str_index]), format, argptr); va_end (argptr); return string[str_index]; } /* ============== COM_Parse Parse a token out of a string ============== */ char *COM_Parse (char **data_p) { int c, len = 0; char *data; static char com_token[MAX_TOKEN_CHARS]; data = *data_p; com_token[0] = 0; if (!data) { *data_p = NULL; return ""; } // skip whitespace skipwhite: while ((c = *data) <= ' ') { if (c == 0) { *data_p = NULL; return ""; } data++; } // skip // comments if (c == '/' && data[1] == '/') { data += 2; while (*data && *data != '\n') data++; goto skipwhite; } // handle quoted strings specially if (c == '\"') { data++; while (1) { c = *data++; if (c == '\"' || !c) { goto finish; } if (len < MAX_TOKEN_CHARS) { com_token[len] = c; len++; } } } // parse a regular word do { if (len < MAX_TOKEN_CHARS) { com_token[len] = c; len++; } data++; c = *data; } while (c > 32); finish: if (len == MAX_TOKEN_CHARS) { // Com_Printf ("Token exceeded %i chars, discarded.\n", MAX_TOKEN_CHARS); len = 0; } com_token[len] = 0; *data_p = data; return com_token; } /* =============== Com_PageInMemory =============== */ int paged_total = 0; void Com_PageInMemory (byte * buffer, int size) { int i; for (i = size - 1; i > 0; i -= 4096) paged_total += buffer[i]; } /* ============================================================================ LIBRARY REPLACEMENT FUNCTIONS ============================================================================ */ #ifndef Q_strnicmp int Q_strnicmp (const char *s1, const char *s2, size_t size) { int c1, c2; do { c1 = *s1++; c2 = *s2++; if (!size--) return 0; // strings are equal until end point if (c1 != c2) { if (c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A'); if (c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A'); if (c1 != c2) return -1; // strings not equal } } while (c1); return 0; // strings are equal } #endif void Q_strncpyz( char *dest, const char *src, size_t size ) { while( --size && (*dest++ = *src++) ); *dest = '\0'; } /* ============== Q_strncatz ============== */ void Q_strncatz( char *dest, const char *src, size_t size ) { while( --size && *dest++ ); if( size ) { dest--; while( --size && (*dest++ = *src++) ); } *dest = '\0'; } void Com_sprintf (char *dest, size_t size, const char *fmt, ...) { va_list argptr; va_start( argptr, fmt ); vsnprintf( dest, size, fmt, argptr ); va_end( argptr ); } /* ===================================================================== INFO STRINGS ===================================================================== */ /* =============== Info_ValueForKey Searches the string for the given key and returns the associated value, or an empty string. =============== */ char *Info_ValueForKey (const char *s, const char *key) { char pkey[MAX_INFO_STRING]; static char value[2][MAX_INFO_STRING]; // use two buffers so compares // work without stomping on each other static int valueindex = 0; char *o; if ( !s || !key ) { return ""; } valueindex ^= 1; if (*s == '\\') s++; while (1) { o = pkey; while (*s != '\\') { if (!*s) return ""; *o++ = *s++; } *o = 0; s++; o = value[valueindex]; while (*s != '\\' && *s) { if (!*s) return ""; *o++ = *s++; } *o = 0; if (!strcmp (key, pkey) ) return value[valueindex]; if (!*s) return ""; s++; } } void Info_RemoveKey (char *s, const char *key) { char *start; char pkey[MAX_INFO_STRING]; char value[MAX_INFO_STRING]; char *o; if (strchr (key, '\\')) { Com_Printf ("Info_RemoveKey: Tried to remove illegal key '%s'\n", key); return; } while (1) { start = s; if (*s == '\\') s++; o = pkey; while (*s != '\\') { if (!*s) return; *o++ = *s++; } *o = 0; s++; o = value; while (*s != '\\' && *s) { if (!*s) return; *o++ = *s++; } *o = 0; if (!strcmp (key, pkey) ) { //strcpy (start, s); // remove this part size_t memlen; memlen = strlen(s); memmove (start, s, memlen); *(start+memlen) = 0; return; } if (!*s) return; } } /* ================== Info_Validate Some characters are illegal in info strings because they can mess up the server's parsing ================== */ qboolean Info_Validate (const char *s) { if (strchr(s, '"')) return false; if (strchr(s, ';')) return false; return true; } void Info_SetValueForKey (char *s, const char *key, const char *value) { char newi[MAX_INFO_STRING], *v; int c; if (strchr (key, '\\') || strchr (value, '\\') ) { Com_Printf ("Can't use keys or values with a \\ (attempted to set key '%s')\n", key); return; } if (strchr (key, ';') ) { Com_Printf ("Can't use keys or values with a semicolon (attempted to set key '%s')\n", key); return; } if (strchr (key, '"') || strchr (value, '"') ) { Com_Printf ("Can't use keys or values with a \" (attempted to set key '%s')\n", key); return; } if (strlen(key) > MAX_INFO_KEY-1 || strlen(value) > MAX_INFO_KEY-1) { Com_Printf ("Keys and values must be < 64 characters (attempted to set key '%s')\n", key); return; } Info_RemoveKey (s, key); if (!value || !value[0]) return; Com_sprintf (newi, sizeof(newi), "\\%s\\%s", key, value); if (strlen(newi) + strlen(s) > MAX_INFO_STRING) { Com_Printf ("Info string length exceeded while trying to set '%s'\n", newi); return; } // only copy ascii values s += strlen(s); v = newi; while (*v) { c = *v++; c &= 127; // strip high bits if (c >= 32 && c < 127) *s++ = c; } *s = 0; } //====================================================================
540
./aq2-tng/source/a_items.c
//----------------------------------------------------------------------------- // Special item spawning/management code. Mainly hacked from CTF, thanks // Zoid. // - zucc // // $Id: a_items.c,v 1.7 2003/02/10 02:12:25 ra Exp $ // //----------------------------------------------------------------------------- // $Log: a_items.c,v $ // Revision 1.7 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.6 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.5 2001/07/18 15:19:11 slicerdw // Time for weapons and items dissapearing is set to "6" to prevent lag on ctf // // Revision 1.4 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.3.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.3 2001/05/15 15:49:14 igor_rock // added itm_flags for deathmatch // // Revision 1.2 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.1.1.1 2001/05/06 17:24:25 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" // time too wait between failures to respawn? #define SPEC_RESPAWN_TIME 60 // time before they will get respawned #define SPEC_TECH_TIMEOUT 60 int tnums[ITEM_COUNT] = { SIL_NUM, SLIP_NUM, BAND_NUM, KEV_NUM, LASER_NUM, HELM_NUM }; //int tnumspawned[ITEM_COUNT] = { 0 }; void SpecThink(edict_t * spec); static edict_t *FindSpecSpawn(void) { edict_t *spot = NULL; int i = rand() % 16; while (i--) spot = G_Find(spot, FOFS(classname), "info_player_deathmatch"); if (!spot) spot = G_Find(spot, FOFS(classname), "info_player_deathmatch"); return spot; } static void SpawnSpec(gitem_t * item, edict_t * spot) { edict_t *ent; vec3_t forward, right, angles; ent = G_Spawn(); ent->classname = item->classname; ent->typeNum = item->typeNum; ent->item = item; ent->spawnflags = DROPPED_ITEM; ent->s.effects = item->world_model_flags; ent->s.renderfx = RF_GLOW; VectorSet(ent->mins, -15, -15, -15); VectorSet(ent->maxs, 15, 15, 15); // zucc dumb hack to make laser look like it is on the ground if (item->typeNum == LASER_NUM) { VectorSet(ent->mins, -15, -15, -1); VectorSet(ent->maxs, 15, 15, 1); } gi.setmodel(ent, ent->item->world_model); ent->solid = SOLID_TRIGGER; ent->movetype = MOVETYPE_TOSS; ent->touch = Touch_Item; ent->owner = ent; angles[0] = 0; angles[1] = rand() % 360; angles[2] = 0; AngleVectors(angles, forward, right, NULL); VectorCopy(spot->s.origin, ent->s.origin); ent->s.origin[2] += 16; VectorScale(forward, 100, ent->velocity); ent->velocity[2] = 300; ent->nextthink = level.time + SPEC_RESPAWN_TIME; ent->think = SpecThink; gi.linkentity(ent); } void SpawnSpecs(edict_t * ent) { gitem_t *spec; edict_t *spot; int i; if(item_respawnmode->value) return; for(i = 0; i<ITEM_COUNT; i++) { if ((spec = GET_ITEM(tnums[i])) != NULL && (spot = FindSpecSpawn()) != NULL) { //AQ2:TNG - Igor adding itm_flags if ((int)itm_flags->value & items[tnums[i]].flag) { //gi.dprintf("Spawning special item '%s'.\n", tnames[i]); SpawnSpec(spec, spot); } //AQ2:TNG End adding itm_flags } } } void SpecThink(edict_t * spec) { edict_t *spot; if ((spot = FindSpecSpawn()) != NULL) { SpawnSpec(spec->item, spot); G_FreeEdict(spec); } else { spec->nextthink = level.time + SPEC_RESPAWN_TIME; spec->think = SpecThink; } } static void MakeTouchSpecThink(edict_t * ent) { ent->touch = Touch_Item; if (deathmatch->value && (!teamplay->value || teamdm->value || ctf->value == 2) && !allitem->value && !dm_choose->value) { if(item_respawnmode->value) { ent->nextthink = level.time + (item_respawn->value*0.5f); ent->think = G_FreeEdict; } else { ent->nextthink = level.time + item_respawn->value; ent->think = SpecThink; } } else if ((teamplay->value || dm_choose->value) && !allitem->value) { //AQ2:TNG - Slicer This works for Special Items if (ctf->value || dm_choose->value) { ent->nextthink = level.time + 6; ent->think = G_FreeEdict; } else { ent->nextthink = level.time + 60; ent->think = G_FreeEdict; } } else // allitem->value is set { ent->nextthink = level.time + 1; ent->think = G_FreeEdict; } } void Drop_Spec(edict_t * ent, gitem_t * item) { edict_t *spec; spec = Drop_Item(ent, item); //gi.cprintf(ent, PRINT_HIGH, "Dropping special item.\n"); spec->nextthink = level.time + 1; spec->think = MakeTouchSpecThink; //zucc this and the one below should probably be -- not = 0, if // a server turns on multiple item pickup. ent->client->pers.inventory[ITEM_INDEX(item)]--; } void DeadDropSpec(edict_t * ent) { gitem_t *spec; edict_t *dropped; int i; for(i = 0; i<ITEM_COUNT; i++) { if (INV_AMMO(ent, tnums[i]) > 0) { spec = GET_ITEM(tnums[i]); dropped = Drop_Item(ent, spec); // hack the velocity to make it bounce random dropped->velocity[0] = (rand() % 600) - 300; dropped->velocity[1] = (rand() % 600) - 300; dropped->nextthink = level.time + 1; dropped->think = MakeTouchSpecThink; dropped->owner = NULL; dropped->spawnflags = DROPPED_PLAYER_ITEM; ent->client->pers.inventory[ITEM_INDEX(spec)] = 0; } } } // frees the passed edict! void RespawnSpec(edict_t * ent) { edict_t *spot; if ((spot = FindSpecSpawn()) != NULL) SpawnSpec(ent->item, spot); G_FreeEdict(ent); } void SetupSpecSpawn(void) { edict_t *ent; if (level.specspawn) return; ent = G_Spawn(); ent->nextthink = level.time + 4; ent->think = SpawnSpecs; level.specspawn = 1; }
541
./aq2-tng/source/g_svcmds.c
//----------------------------------------------------------------------------- // g_svcmds.c // // $Id: g_svcmds.c,v 1.15 2003/12/09 20:53:35 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: g_svcmds.c,v $ // Revision 1.15 2003/12/09 20:53:35 igor_rock // added player console info if stuffcmd used (to avoid admin cheating) // // Revision 1.14 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.13 2002/03/28 15:32:47 ra // No softmapping during LCA // // Revision 1.12 2002/01/22 16:55:49 deathwatch // fixed a bug with rrot which would make it override sv softmap (moved the dosoft check up in g_main.c // fixed a bug with rrot which would let it go to the same map (added an if near the end of the rrot statement in the EndDMLevel function) // // Revision 1.11 2001/11/04 15:15:19 ra // New server commands: "sv softmap" and "sv map_restart". sv softmap // takes one map as argument and starts is softly without restarting // the server. map_restart softly restarts the current map. // // Revision 1.10 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.9 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.8 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.5 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.4.2.2 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.4.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.4 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.3 2001/05/07 22:03:15 slicerdw // Added sv stuffcmd // // Revision 1.2 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.1.1.1 2001/05/06 17:31:45 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" extern int dosoft; extern int softquit; void SVCmd_ReloadMOTD_f () { ReadMOTDFile (); gi.cprintf (NULL, PRINT_HIGH, "MOTD reloaded.\n"); } /* ============================================================================== PACKET FILTERING You can add or remove addresses from the filter list with: addip <ip> removeip <ip> The ip address is specified in dot format, and any unspecified digits will match any value, so you can specify an entire class C network with "addip 192.246.40". Removeip will only remove an address specified exactly the same way. You cannot addip a subnet, then removeip a single host. listip Prints the current list of filters. writeip Dumps "addip <ip>" commands to listip.cfg so it can be execed at a later date. The filter lists are not saved and restored by default, because I beleive it would cause too much confusion. filterban <0 or 1> If 1 (the default), then ip addresses matching the current list will be prohibited from entering the game. This is the default setting. If 0, then only addresses matching the list will be allowed. This lets you easily set up a private game, or a game that only allows players from your local network. ============================================================================== */ typedef struct { unsigned mask; unsigned compare; //AZEROV int temp_ban_games; //AZEROV } ipfilter_t; #define MAX_IPFILTERS 1024 ipfilter_t ipfilters[MAX_IPFILTERS]; int numipfilters; /* ================= StringToFilter ================= */ static qboolean StringToFilter (char *s, ipfilter_t * f, int temp_ban_games) { char num[128]; int i, j; byte b[4] = {0,0,0,0}; byte m[4] = {0,0,0,0}; for (i = 0; i < 4; i++) { if (*s < '0' || *s > '9') { gi.cprintf (NULL, PRINT_HIGH, "Bad filter address: %s\n", s); return false; } j = 0; while (*s >= '0' && *s <= '9') { num[j++] = *s++; } num[j] = 0; b[i] = atoi (num); if (b[i] != 0) m[i] = 255; if (!*s) break; s++; } f->mask = *(unsigned *) m; f->compare = *(unsigned *) b; f->temp_ban_games = temp_ban_games; return true; } /* ================= SV_FilterPacket ================= */ qboolean SV_FilterPacket (char *from, int *temp) { int i = 0; unsigned in; byte m[4] = {0,0,0,0}; char *p; p = from; while (*p && i < 4) { while (*p >= '0' && *p <= '9') { m[i] = m[i] * 10 + (*p - '0'); p++; } if (!*p || *p == ':') break; i++, p++; } in = *(unsigned *) m; for (i = 0; i < numipfilters; i++) { if ((in & ipfilters[i].mask) == ipfilters[i].compare) { *temp = ipfilters[i].temp_ban_games; return (int)filterban->value; } } return (int)!filterban->value; } /* ================= SV_AddIP_f ================= */ void SVCmd_AddIP_f (void) { int i; if (gi.argc () < 3) { gi.cprintf (NULL, PRINT_HIGH, "Usage: addip <ip-mask>\n"); return; } for (i = 0; i < numipfilters; i++) { if (ipfilters[i].compare == 0xffffffff) break; // free spot } if (i == numipfilters) { if (numipfilters == MAX_IPFILTERS) { gi.cprintf (NULL, PRINT_HIGH, "IP filter list is full\n"); return; } numipfilters++; } if (!StringToFilter (gi.argv (2), &ipfilters[i], 0)) ipfilters[i].compare = 0xffffffff; } /* ================= SV_RemoveIP_f ================= */ void SVCmd_RemoveIP_f (void) { ipfilter_t f; int i, j; if (gi.argc () < 3) { gi.cprintf (NULL, PRINT_HIGH, "Usage: sv removeip <ip-mask>\n"); return; } if (!StringToFilter (gi.argv (2), &f, 0)) return; for (i = 0; i < numipfilters; i++) { if (ipfilters[i].mask == f.mask && ipfilters[i].compare == f.compare) { for (j = i + 1; j < numipfilters; j++) ipfilters[j - 1] = ipfilters[j]; numipfilters--; gi.cprintf (NULL, PRINT_HIGH, "Removed.\n"); return; } } gi.cprintf (NULL, PRINT_HIGH, "Didn't find %s.\n", gi.argv (2)); } /* ================= SV_ListIP_f ================= */ void SVCmd_ListIP_f (void) { int i; byte b[4]; gi.cprintf (NULL, PRINT_HIGH, "Filter list:\n"); for (i = 0; i < numipfilters; i++) { *(unsigned *) b = ipfilters[i].compare; if (!ipfilters[i].temp_ban_games) { gi.cprintf (NULL, PRINT_HIGH, "%3i.%3i.%3i.%3i\n", b[0], b[1], b[2], b[3]); } else { gi.cprintf (NULL, PRINT_HIGH, "%3i.%3i.%3i.%3i (%d more game(s))\n", b[0], b[1], b[2], b[3], ipfilters[i].temp_ban_games); } } } /* ================= SV_WriteIP_f ================= */ void SVCmd_WriteIP_f (void) { FILE *f; char name[MAX_OSPATH]; byte b[4]; int i; cvar_t *game; game = gi.cvar ("game", "", 0); if (!*game->string) sprintf (name, "%s/listip.cfg", GAMEVERSION); else sprintf (name, "%s/listip.cfg", game->string); gi.cprintf (NULL, PRINT_HIGH, "Writing %s.\n", name); f = fopen (name, "wb"); if (!f) { gi.cprintf (NULL, PRINT_HIGH, "Couldn't open %s\n", name); return; } fprintf (f, "set filterban %d\n", (int) filterban->value); for (i = 0; i < numipfilters; i++) { if (!ipfilters[i].temp_ban_games) { *(unsigned *) b = ipfilters[i].compare; fprintf (f, "sv addip %i.%i.%i.%i\n", b[0], b[1], b[2], b[3]); } } fclose (f); } // zucc so it works under vc++ void ExitLevel (void); //Black Cross - Begin /* ================= SV_Nextmap_f ================= */ void SVCmd_Nextmap_f (char *arg) { // end level and go to next map in map rotation gi.bprintf (PRINT_HIGH, "Changing to next map in rotation.\n"); EndDMLevel (); if (arg != NULL && Q_stricmp (arg, "force") == 0) ExitLevel (); return; } //Black Cross - End /* ================= STUFF COMMAND This will stuff a certain command to the client. ================= */ void SVCmd_stuffcmd_f () { int i, u, team = 0; char text[256]; char user[64], tmp[64]; edict_t *ent; if (gi.argc () < 4) { gi.cprintf (NULL, PRINT_HIGH, "Usage: stuffcmd <user id> <text>\n"); return; } i = gi.argc (); Q_strncpyz (user, gi.argv (2), sizeof (user)); text[0] = 0; for (u = 3; u <= i; u++) { Q_strncpyz (tmp, gi.argv (u), sizeof (tmp)); if (tmp[0] == '!') // Checks for "!" and replaces for "$" to see the user info tmp[0] = '$'; if(text[0]) Q_strncatz (text, " ", sizeof(text)-1); Q_strncatz (text, tmp, sizeof(text)-1); } Q_strncatz (text, "\n", sizeof(text)); if(!Q_stricmp (user, "team1")) team = TEAM1; else if(!Q_stricmp (user, "team2")) team = TEAM2; else if(use_3teams->value && !Q_stricmp (user, "team3")) team = TEAM3; if(team && !teamplay->value) { gi.cprintf (NULL, PRINT_HIGH, "Not in Teamplay mode\n"); return; } if (team || !Q_stricmp(user, "all")) { for (i = 1; i <= (int) (maxclients->value); i++) { ent = getEnt (i); if(!ent->inuse) continue; if (!team || ent->client->resp.team == team) { gi.cprintf(ent, PRINT_HIGH, "Console stuffed: %s", text); stuffcmd (ent, text); } } return; } for (u = 0; u < strlen(user); u++) { if (!isdigit(user[u])) { gi.cprintf (NULL, PRINT_HIGH, "Usage: stuffcmd <user id> <text>\n"); return; } } i = atoi(user) + 1; if (i > (int)(maxclients->value)) { /* if is inserted number > server capacity */ gi.cprintf (NULL, PRINT_HIGH, "User id is not valid\n"); return; } ent = getEnt(i); if (ent->inuse) { /* if is inserted a user that exists in the server */ gi.cprintf(ent, PRINT_HIGH, "Console stuffed: %s", text); stuffcmd (ent, text); } else gi.cprintf (NULL, PRINT_HIGH, "User id is not valid\n"); } /* ================= SV_Softmap_f ================= */ void SVCmd_Softmap_f (void) { if (gi.argc() < 3) { gi.cprintf(NULL, PRINT_HIGH, "Usage: sv softmap <map>\n"); return; } if (lights_camera_action) { gi.cprintf(NULL, PRINT_HIGH, "Please dont use sv softmap during LCA\n"); return; } Q_strncpyz(level.nextmap, gi.argv(2), sizeof(level.nextmap)); gi.bprintf(PRINT_HIGH, "Console is setting map: %s\n", level.nextmap); dosoft = 1; EndDMLevel(); return; } /* ================= SV_Map_restart_f ================= */ void SVCmd_Map_restart_f (void) { gi.bprintf(PRINT_HIGH, "Console is restarting map\n"); dosoft = 1; strcpy(level.nextmap, level.mapname); EndDMLevel(); return; } void SVCmd_ResetScores_f (void) { if(!matchmode->value) { gi.cprintf(NULL, PRINT_HIGH, "This command works only in matchmode\n"); return; } ResetScores(true); gi.bprintf(PRINT_HIGH, "Scores and time was resetted by console\n"); } void SVCmd_SoftQuit_f (void) { gi.bprintf(PRINT_HIGH, "The server will exit after this map\n"); softquit = 1; } /* ================= ServerCommand ServerCommand will be called when an "sv" command is issued. The game can issue gi.argc() / gi.argv() commands to get the rest of the parameters ================= */ void ServerCommand (void) { char *cmd; cmd = gi.argv (1); if (Q_stricmp (cmd, "addip") == 0) SVCmd_AddIP_f (); else if (Q_stricmp (cmd, "removeip") == 0) SVCmd_RemoveIP_f (); else if (Q_stricmp (cmd, "listip") == 0) SVCmd_ListIP_f (); else if (Q_stricmp (cmd, "writeip") == 0) SVCmd_WriteIP_f (); else if (Q_stricmp (cmd, "nextmap") == 0) SVCmd_Nextmap_f (gi.argv (2)); // Added by Black Cross else if (Q_stricmp (cmd, "reloadmotd") == 0) SVCmd_ReloadMOTD_f (); //AQ2:TNG - Slicer : CheckCheats & StuffCmd else if (Q_stricmp (cmd, "stuffcmd") == 0) SVCmd_stuffcmd_f (); else if (Q_stricmp (cmd, "ircraw") == 0) SVCmd_ircraw_f (); else if (Q_stricmp (cmd, "softmap") == 0) SVCmd_Softmap_f (); else if (Q_stricmp (cmd, "map_restart") == 0) SVCmd_Map_restart_f (); else if (Q_stricmp (cmd, "resetscores") == 0) SVCmd_ResetScores_f (); else if (Q_stricmp (cmd, "softquit") == 0) SVCmd_SoftQuit_f (); else gi.cprintf (NULL, PRINT_HIGH, "Unknown server command \"%s\"\n", cmd); } /* ========================== Kick a client entity ========================== */ void Kick_Client (edict_t * ent) { int i = 0; char ban_string[32]; edict_t *entL; if (!ent->client) return; // We used to kick on names, but people got crafty and figured // out that putting in a space after their name let them get // around the stupid 'kick' function. So now we kick by number. for (i = 0; i < game.maxclients; i++) { entL = &g_edicts[1 + i]; if (!entL || !entL->inuse) continue; if (entL->client && ent == entL) { Com_sprintf(ban_string, sizeof(ban_string), "kick %d\n", i); gi.AddCommandString (ban_string); break; } } } /* ========================== Ban a client for N rounds ========================== */ qboolean Ban_TeamKiller (edict_t * ent, int rounds) { int i = 0; if (!ent || !ent->client || !ent->client->ipaddr) { gi.cprintf (NULL, PRINT_HIGH, "Unable to determine client->ipaddr for edict\n"); return false; } for (i = 0; i < numipfilters; i++) { if (ipfilters[i].compare == 0xffffffff) break; // free spot } if (i == numipfilters) { if (numipfilters == MAX_IPFILTERS) { gi.cprintf (NULL, PRINT_HIGH, "IP filter list is full\n"); return false; } numipfilters++; } if (!StringToFilter (ent->client->ipaddr, &ipfilters[i], rounds)) { ipfilters[i].compare = 0xffffffff; return false; } return true; } void UnBan_TeamKillers (void) { // We don't directly unban them all - we subtract 1 from temp_ban_games, // and unban them if it's 0. int i, j; for (i = 0; i < numipfilters; i++) { if (ipfilters[i].temp_ban_games > 0) { if (!--ipfilters[i].temp_ban_games) { // re-pack the filters for (j = i + 1; j < numipfilters; j++) ipfilters[j - 1] = ipfilters[j]; numipfilters--; gi.cprintf (NULL, PRINT_HIGH, "Unbanned teamkiller/vote kickked.\n"); // since we removed the current we have to re-process the new current i--; } } } } //AZEROV
542
./aq2-tng/source/g_xmisc.c
//----------------------------------------------------------------------------- // PG BUND // g_xmisc.c // // this module contains all new functions regarding g_misc.c // // $Id: g_xmisc.c,v 1.6 2004/01/02 11:58:08 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: g_xmisc.c,v $ // Revision 1.6 2004/01/02 11:58:08 igor_rock // corrected punch bug, you weren't able to punch teammates even if FF was on // // Revision 1.5 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.4 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.3 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.2 2001/08/06 03:00:49 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.1.1.1 2001/05/06 17:31:34 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" //TempFile for punch animation #ifndef MAX_STR_LEN #define MAX_STR_LEN 1000 #endif // MAX_STR_LEN static char _inipath[MAX_STR_LEN] = ""; //this function belongs to g_weapon.c void punch_attack(edict_t * ent) { vec3_t start, forward, right, offset, end; int damage = 7; int kick = 100; int randmodify; trace_t tr; AngleVectors(ent->client->v_angle, forward, right, NULL); VectorScale(forward, 0, ent->client->kick_origin); VectorSet(offset, 0, 0, ent->viewheight - 20); P_ProjectSource(ent->client, ent->s.origin, offset, forward, right, start); VectorMA(start, 50, forward, end); PRETRACE(); tr = gi.trace(ent->s.origin, NULL, NULL, end, ent, MASK_SHOT); POSTTRACE(); if (!((tr.surface) && (tr.surface->flags & SURF_SKY))) { if (tr.fraction < 1.0 && tr.ent->takedamage) { if (tr.ent->health <= 0) return; if (teamplay->value) { // AQ2:TNG - JBravo adding UVtime if (tr.ent->client && tr.ent->client->ctf_uvtime) return; if ((tr.ent != ent) && tr.ent->client && ent->client && (tr.ent->client->resp.team == ent->client->resp.team) && ((int)dmflags->value & DF_NO_FRIENDLY_FIRE)) { if (team_round_going || !ff_afterround->value) return; } } else if (((tr.ent != ent) && ((deathmatch->value && ((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) || coop->value) && OnSameTeam(tr.ent, ent))) return; // add some random damage, damage range from 8 to 20. randmodify = rand() % 13 + 1; damage += randmodify; // modify kick by damage kick += (randmodify * 10); // reduce damage, if he tries to punch within or out of water if (ent->waterlevel) damage -= rand() % 10 + 1; // reduce kick, if victim is in water if (tr.ent->waterlevel) kick /= 2; T_Damage(tr.ent, ent, ent, forward, tr.endpos, tr.plane.normal, damage, kick, 0, MOD_PUNCH); gi.sound(ent, CHAN_WEAPON, gi.soundindex("weapons/kick.wav"), 1, ATTN_NORM, 0); PlayerNoise(ent, ent->s.origin, PNOISE_SELF); //only hit weapon out of hand if damage >= 15 if (tr.ent->client && (tr.ent->client->curr_weap == M4_NUM || tr.ent->client->curr_weap == MP5_NUM || tr.ent->client->curr_weap == M3_NUM || tr.ent->client->curr_weap == SNIPER_NUM || tr.ent->client->curr_weap == HC_NUM) && damage >= 15) { DropSpecialWeapon(tr.ent); gi.cprintf (ent, PRINT_HIGH, "You hit %s's %s from %s hands!\n", tr.ent->client->pers.netname,(tr.ent->client->pers.weapon)->pickup_name, IsFemale(tr.ent) ? "her" : "his"); gi.cprintf(tr.ent, PRINT_HIGH, "%s hit your weapon from your hands!\n", ent->client->pers.netname); } return; } } gi.sound(ent, CHAN_WEAPON, gi.soundindex("weapons/swish.wav"), 1, ATTN_NORM, 0); // animate the punch // can't animate a punch when ducked if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) return; if (ent->client->anim_priority >= ANIM_WAVE) return; ent->client->anim_priority = ANIM_WAVE; ent->s.frame = FRAME_flip01 - 1; ent->client->anim_end = FRAME_flip03; //TempFile - END } //"colours" a normal string to green - for output via cprintf() without using //PRINT_CHAT - got it by Riviera char *strtostr2(char *s) { unsigned char *p = s; while (*p) { if ((*p >= 0x1b && *p <= 0x7f) || ((*p > 0x0a && *p <= 0x11) && (*p != 0x0d))) *p += 0x80; p++; } return (char *) s; } //plays a random sound/insane sound, insane1-9.wav void PlayRandomInsaneSound(edict_t * ent) { int n; char buffer[32]; n = rand() % 9 + 1; Com_sprintf(buffer, sizeof(buffer), "insane/insane%i.wav", n); gi.sound(ent, CHAN_VOICE, gi.soundindex(buffer), 1, ATTN_NORM, 0); } //determe client entities that are within a cube. //from: start entity //p1,p2: cube description //returns next client entity that is within cube edict_t *findblock(edict_t * from, vec3_t p1, vec3_t p2) { vec3_t eorg; int j; if (!from) from = g_edicts; else from++; for (j = 0; j < 3; j++) if (p2[j] < p1[j]) { eorg[1] = p2[j]; p2[j] = p1[j]; p1[j] = eorg[1]; } for (; from < &g_edicts[globals.num_edicts]; from++) { if (!from->inuse) continue; if (from->solid == SOLID_NOT) continue; for (j = 0; j < 3; j++) eorg[j] = from->s.origin[j] + (from->mins[j] + from->maxs[j]) * 0.5; if (eorg[0] >= p1[0] && eorg[1] >= p1[1] && eorg[2] >= p1[2] && eorg[0] <= p2[0] && eorg[1] <= p2[1] && eorg[2] <= p2[2]) return from; } return NULL; } //Precaches and enables download options for user sounds. All sounds //have to be listed within "sndlist.ini". called from g_spawn.c -> SP_worldspawn void PrecacheUserSounds(void) { int i, bs; FILE *soundlist; char buf[MAX_STR_LEN], fullpath[MAX_STR_LEN]; soundlist = fopen(GAMEVERSION "/sndlist.ini", "r"); if (soundlist == NULL) { // no "sndlist.ini" file... gi.dprintf("Cannot load %s, sound download is disabled.\n", GAMEVERSION "/sndlist.ini"); } else { // read the sndlist.ini file for (i = 0; (fgets(buf, MAX_STR_LEN - 10, soundlist) != NULL) && (i < 100);) { //first remove trailing spaces for (bs = strlen(buf); bs > 0 && (buf[bs - 1] == '\r' || buf[bs - 1] == '\n' || buf[bs - 1] == ' '); bs--) buf[bs - 1] = '\0'; //Comments are marked with # or // at line start if (bs > 0 && strncmp(buf, "#", 1) != 0 && strncmp(buf, "//", 2) != 0) { strcpy(fullpath, PG_SNDPATH); strcat(fullpath, buf); gi.soundindex(fullpath); //gi.dprintf("Sound %s: precache %i",fullpath, gi.soundindex(fullpath)); i++; } } fclose(soundlist); if (!i) gi.dprintf("%s is empty, no sounds to precache.\n", GAMEVERSION "/sndlist.ini"); else gi.dprintf("%i user sounds precached.\n", i); } } //Returns the edict for the given name, not case sensitive, and //only if the edict is a client. edict_t *FindClientByPersName(char *name) { int i; edict_t *other; for (i = 1; i <= game.maxclients; i++) { other = &g_edicts[i]; if (other && other->client && (Q_stricmp(other->client->pers.netname, name) == 0)) { return other; } } return NULL; } //Returns the internal edict # of a client //Attention: you must decrement it to get the right one, 0 means not found! int GetClientInternalNumber(edict_t * ent) { int i; if (!ent || !ent->client) return 0; for (i = 1; i <= game.maxclients; i++) { if (&g_edicts[i] == ent) return i; } return 0; } /* Kicks the given (client) edict out of the server, reason will be printed before */ void KickClient(edict_t * target, char *reason) { int j; char buffer[32]; if (target && target->client && target->inuse) { j = GetClientInternalNumber(target); if (j) { Com_sprintf(buffer, sizeof(buffer), "kick %i\n", --j); gi.bprintf(PRINT_HIGH, "%s has to be KICKED from the server.\n", target->client->pers.netname); gi.bprintf(PRINT_MEDIUM, "Reason: %s\n", reason); gi.AddCommandString(buffer); } else gi.dprintf("Error: %s has to be kicked, cannot determine userid.", target->client->pers.netname); } } // char *StripSpaces(char *astring) { char *p, buf[1024]; p = astring; if (!p || !*p) return astring; while (*p != '\0' && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t')) p++; if (!*p) { *astring = '\0'; return astring; } strcpy(buf, p); p = &buf[strlen(buf) - 1]; while (p != buf && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t')) p--; p++; *p = '\0'; strcpy(astring, buf); return astring; } // qboolean CheckForRemark(char *src) { char *myptr; myptr = StripSpaces(src); if (strlen(myptr) == 0) return (true); if (*myptr == '#') return (true); if (strlen(myptr) > 1 && *myptr == '/') { myptr++; return (*myptr == '/'); } return false; } // qboolean ParseStartFile(char *filename, parse_t * parse) { if (parse->inparsing == true) return false; parse->pfile = fopen(filename, "r"); if (parse->pfile) { parse->inparsing = true; parse->nextline = true; parse->lnumber = 0; return true; } else gi.dprintf("Error opening file %s\n", filename); return false; } // void ParseEndFile(parse_t * parse) { if (parse->pfile) { fclose(parse->pfile); parse->pfile = NULL; parse->inparsing = false; parse->nextline = false; parse->lnumber = 0; } } //due the usage of strtok, only ONE file should be parsed at //the same time...this may change in the future. char *ParseNextToken(parse_t * parse, char *seperator) { char *dummy; if (parse->inparsing == true) { dummy = NULL; while (!dummy) { if (parse->nextline == true) { do { dummy = fgets(parse->cline, 1020, parse->pfile); parse->lnumber++; if (!dummy) //we reached end of file return NULL; } while (CheckForRemark(parse->cline)); dummy = strtok(parse->cline, seperator); if (dummy) //this should always happen :) parse->nextline = false; } else { dummy = strtok(NULL, seperator); if (!dummy) //no more tokens in current line parse->nextline = true; } } //we finally got a new token strcpy(parse->ctoken, dummy); StripSpaces(parse->ctoken); return (parse->ctoken); } return NULL; } // internal use only, ini section must occupy one line // and has the format "[section]". This may be altered // Sections are case insensitive. qboolean _seekinisection(FILE * afile, char *section) { inistr buf, comp; if (!afile) return false; sprintf(comp, "[%s]", section); fseek(afile, 0, SEEK_SET); while (fgets(buf, INI_STR_LEN, afile)) { if (Q_stricmp(StripSpaces(buf), comp) == 0) return true; } return false; } // internal use only, make sure sizeof(value) >= INI_STR_LEN char *_readinivalue(FILE * afile, char *section, char *key, char *value) { inistr buf, akey; char *p; if (!afile) return NULL; if (_seekinisection(afile, section) == true) { while (fgets(buf, INI_STR_LEN, afile)) { //splitting line into key and value p = strrchr(buf, '='); if (p) { *p = '\0'; p++; strcpy(akey, buf); strcpy(value, p); } else { strcpy(akey, buf); value[0] = '\0'; } if (Q_stricmp(StripSpaces(akey), key) == 0) return (StripSpaces(value)); // found! if (akey[0] == '[') return NULL; // another section begins } } return NULL; } int ReadIniSection(ini_t * ini, char *section, char buf[][INI_STR_LEN], int maxarraylen) { int i; char *p; i = 0; if (_seekinisection(ini->pfile, section) == true) { while (i < maxarraylen && fgets(buf[i], 127, ini->pfile)) { buf[i][127] = '\0'; p = buf[i]; StripSpaces(p); if (*p == '[') // next section? { *p = '\0'; return i; } i++; } } return i; } char *ReadIniStr(ini_t * ini, char *section, char *key, char *value, char *defvalue) { if (!_readinivalue(ini->pfile, section, key, value)) strcpy(value, defvalue); return value; } int ReadIniInt(ini_t * ini, char *section, char *key, int defvalue) { inistr value; if (_readinivalue(ini->pfile, section, key, value)) return atoi(value); return defvalue; } char *IniPath(void) { cvar_t *p; if (!*_inipath) { p = gi.cvar("ininame", "action.ini", 0); if (p->string && *(p->string)) sprintf(_inipath, "%s/%s", GAMEVERSION, p->string); else sprintf(_inipath, "%s/%s", GAMEVERSION, "action.ini"); } return _inipath; }
543
./aq2-tng/source/p_view.c
//----------------------------------------------------------------------------- // p_view.c // // $Id: p_view.c,v 1.20 2002/02/18 18:25:51 ra Exp $ // //----------------------------------------------------------------------------- // $Log: p_view.c,v $ // Revision 1.20 2002/02/18 18:25:51 ra // Bumped version to 2.6, fixed ctf falling and kicking of players in ctf // uvtime // // Revision 1.19 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.17 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.16 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.15 2001/08/19 01:22:25 deathwatch // cleaned the formatting of some files // // Revision 1.14 2001/08/18 20:51:55 deathwatch // Messing with the colours of the flashlight and the person using the // flashlight // // Revision 1.13 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.12 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.11 2001/06/21 00:05:31 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.8 2001/06/18 12:36:40 igor_rock // added new irvision mode (with reddish screen and alpha blend) and corresponding // new cvar "new_irvision" to enable the new mode // // Revision 1.7 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.6 2001/05/20 15:00:19 slicerdw // Some minor fixes and changings on Video Checking system // // Revision 1.5.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.5.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.5.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.5 2001/05/11 16:07:26 mort // Various CTF bits and pieces... // // Revision 1.4 2001/05/08 12:54:17 igor_rock // removed another debug message ;) // // Revision 1.3 2001/05/07 21:43:02 slicerdw // Removed Some Debug Messages Left Over // // Revision 1.2 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.1.1.1 2001/05/06 17:24:10 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" static edict_t *current_player; static gclient_t *current_client; static vec3_t forward, right, up; float xyspeed; float bobmove; int bobcycle; // odd cycles are right foot going forward float bobfracsin; // sin(bobfrac*M_PI) /* =============== SV_CalcRoll =============== */ float SV_CalcRoll (vec3_t angles, vec3_t velocity) { float sign, side, value; side = DotProduct (velocity, right); sign = side < 0 ? -1 : 1; side = fabs (side); value = sv_rollangle->value; if (side < sv_rollspeed->value) side = side * value / sv_rollspeed->value; else side = value; return side * sign; } /* =============== P_DamageFeedback Handles color blends and view kicks =============== */ void P_DamageFeedback (edict_t * player) { gclient_t *client; float side; float realcount, count, kick; vec3_t v; int r, l; static const vec3_t power_color = { 0.0, 1.0, 0.0 }; static const vec3_t acolor = { 1.0, 1.0, 1.0 }; static const vec3_t bcolor = { 1.0, 0.0, 0.0 }; client = player->client; // flash the backgrounds behind the status numbers client->ps.stats[STAT_FLASHES] = 0; if (client->damage_blood) client->ps.stats[STAT_FLASHES] |= 1; if (client->damage_armor && !(player->flags & FL_GODMODE) && (client->invincible_framenum <= level.framenum)) client->ps.stats[STAT_FLASHES] |= 2; // total points of damage shot at the player this frame count = client->damage_blood + client->damage_armor + client->damage_parmor; if (count == 0) return; // didn't take any damage // start a pain animation if still in the player model if (client->anim_priority < ANIM_PAIN && player->s.modelindex == 255) { static int i; client->anim_priority = ANIM_PAIN; if (client->ps.pmove.pm_flags & PMF_DUCKED) { player->s.frame = FRAME_crpain1 - 1; client->anim_end = FRAME_crpain4; } else { i = (i + 1) % 3; switch (i) { case 0: player->s.frame = FRAME_pain101 - 1; client->anim_end = FRAME_pain104; break; case 1: player->s.frame = FRAME_pain201 - 1; client->anim_end = FRAME_pain204; break; case 2: player->s.frame = FRAME_pain301 - 1; client->anim_end = FRAME_pain304; break; } } } realcount = count; if (count < 10) count = 10; // always make a visible effect // play an apropriate pain sound if ((level.time > player->pain_debounce_time) && !(player->flags & FL_GODMODE) && (client->invincible_framenum <= level.framenum)) { r = 1 + (rand () & 1); player->pain_debounce_time = level.time + 0.7; if (player->health < 25) l = 25; else if (player->health < 50) l = 50; else if (player->health < 75) l = 75; else l = 100; gi.sound (player, CHAN_VOICE, gi.soundindex (va ("*pain%i_%i.wav", l, r)), 1, ATTN_NORM, 0); } // the total alpha of the blend is always proportional to count if (client->damage_alpha < 0) client->damage_alpha = 0; client->damage_alpha += count * 0.01f; if (client->damage_alpha < 0.2f) client->damage_alpha = 0.2f; if (client->damage_alpha > 0.6f) client->damage_alpha = 0.6f; // don't go too saturated // the color of the blend will vary based on how much was absorbed // by different armors VectorClear (v); if (client->damage_parmor) VectorMA (v, (float) client->damage_parmor / realcount, power_color, v); if (client->damage_armor) VectorMA (v, (float) client->damage_armor / realcount, acolor, v); if (client->damage_blood) VectorMA (v, (float) client->damage_blood / realcount, bcolor, v); VectorCopy (v, client->damage_blend); // // calculate view angle kicks // kick = abs (client->damage_knockback); if (kick && player->health > 0) // kick of 0 means no view adjust at all { kick = kick * 100 / player->health; if (kick < count * 0.5) kick = count * 0.5; if (kick > 50) kick = 50; VectorSubtract (client->damage_from, player->s.origin, v); VectorNormalize (v); side = DotProduct (v, right); client->v_dmg_roll = kick * side * 0.3; side = -DotProduct (v, forward); client->v_dmg_pitch = kick * side * 0.3; client->v_dmg_time = level.time + DAMAGE_TIME; } // // clear totals // client->damage_blood = 0; client->damage_armor = 0; client->damage_parmor = 0; client->damage_knockback = 0; } /* =============== SV_CalcViewOffset Auto pitching on slopes? fall from 128: 400 = 160000 fall from 256: 580 = 336400 fall from 384: 720 = 518400 fall from 512: 800 = 640000 fall from 640: 960 = damage = deltavelocity*deltavelocity * 0.0001 =============== */ void SV_CalcViewOffset (edict_t * ent) { float *angles; float bob; float ratio; float delta; vec3_t v = {0, 0, 0}; //=================================== // base angles angles = ent->client->ps.kick_angles; // if dead, fix the angle and don't add any kick if (ent->deadflag) { VectorClear (angles); ent->client->ps.viewangles[ROLL] = 40; ent->client->ps.viewangles[PITCH] = -15; ent->client->ps.viewangles[YAW] = ent->client->killer_yaw; } else { // add angles based on weapon kick VectorCopy (ent->client->kick_angles, angles); // add angles based on damage kick ratio = (ent->client->v_dmg_time - level.time) / DAMAGE_TIME; if (ratio < 0) { ratio = 0; ent->client->v_dmg_pitch = 0; ent->client->v_dmg_roll = 0; } angles[PITCH] += ratio * ent->client->v_dmg_pitch; angles[ROLL] += ratio * ent->client->v_dmg_roll; // add pitch based on fall kick ratio = (ent->client->fall_time - level.time) / FALL_TIME; if (ratio < 0) ratio = 0; angles[PITCH] += ratio * ent->client->fall_value; // add angles based on velocity delta = DotProduct (ent->velocity, forward); angles[PITCH] += delta * run_pitch->value; delta = DotProduct (ent->velocity, right); angles[ROLL] += delta * run_roll->value; // add angles based on bob delta = bobfracsin * bob_pitch->value * xyspeed; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) delta *= 6; // crouching angles[PITCH] += delta; delta = bobfracsin * bob_roll->value * xyspeed; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) delta *= 6; // crouching if (bobcycle & 1) delta = -delta; angles[ROLL] += delta; } //=================================== // add view height v[2] += ent->viewheight; // add fall height ratio = (ent->client->fall_time - level.time) / FALL_TIME; if (ratio < 0) ratio = 0; v[2] -= ratio * ent->client->fall_value * 0.4; // add bob height bob = bobfracsin * xyspeed * bob_up->value; if (bob > 6) bob = 6; //gi.DebugGraph (bob *2, 255); v[2] += bob; // add kick offset VectorAdd (v, ent->client->kick_origin, v); // absolutely bound offsets // so the view can never be outside the player box clamp(v[0], -14, 14); clamp(v[1], -14, 14); clamp(v[2], -22, 30); VectorCopy (v, ent->client->ps.viewoffset); } /* ============== SV_CalcGunOffset ============== */ void SV_CalcGunOffset (edict_t * ent) { int i; float delta; // gun angles from bobbing ent->client->ps.gunangles[ROLL] = xyspeed * bobfracsin * 0.005; ent->client->ps.gunangles[YAW] = xyspeed * bobfracsin * 0.01; if (bobcycle & 1) { ent->client->ps.gunangles[ROLL] = -ent->client->ps.gunangles[ROLL]; ent->client->ps.gunangles[YAW] = -ent->client->ps.gunangles[YAW]; } ent->client->ps.gunangles[PITCH] = xyspeed * bobfracsin * 0.005; // gun angles from delta movement for (i = 0; i < 3; i++) { delta = ent->client->oldviewangles[i] - ent->client->ps.viewangles[i]; if (delta > 180) delta -= 360; if (delta < -180) delta += 360; if (delta > 45) delta = 45; if (delta < -45) delta = -45; if (i == YAW) ent->client->ps.gunangles[ROLL] += 0.1 * delta; ent->client->ps.gunangles[i] += 0.2 * delta; } // gun height VectorClear (ent->client->ps.gunoffset); // ent->ps->gunorigin[2] += bob; // gun_x / gun_y / gun_z are development tools for (i = 0; i < 3; i++) { ent->client->ps.gunoffset[i] += forward[i] * (gun_y->value); ent->client->ps.gunoffset[i] += right[i] * gun_x->value; ent->client->ps.gunoffset[i] += up[i] * (-gun_z->value); } } /* ============= SV_AddBlend ============= */ void SV_AddBlend (float r, float g, float b, float a, float *v_blend) { float a2, a3; if (a <= 0) return; a2 = v_blend[3] + (1 - v_blend[3]) * a; // new total alpha a3 = v_blend[3] / a2; // fraction of color from old v_blend[0] = v_blend[0] * a3 + r * (1 - a3); v_blend[1] = v_blend[1] * a3 + g * (1 - a3); v_blend[2] = v_blend[2] * a3 + b * (1 - a3); v_blend[3] = a2; } /* ============= SV_CalcBlend ============= */ void SV_CalcBlend (edict_t * ent) { int contents; vec3_t vieworg; int remaining; // enable ir vision if appropriate if (ir->value) { if ((INV_AMMO(ent, BAND_NUM) && ent->client->resp.ir == 0) || (ent->client->chase_target != NULL && ent->client->chase_target->client != NULL && ent->client->chase_mode == 2 && ent->client->chase_target->client->resp.ir == 0 && INV_AMMO(ent->client->chase_target, BAND_NUM))) { ent->client->ps.rdflags |= RDF_IRGOGGLES; } else { ent->client->ps.rdflags &= ~RDF_IRGOGGLES; } } ent->client->ps.blend[0] = ent->client->ps.blend[1] = ent->client->ps.blend[2] = ent->client->ps.blend[3] = 0; // add for contents VectorAdd (ent->s.origin, ent->client->ps.viewoffset, vieworg); contents = gi.pointcontents (vieworg); if (contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) ent->client->ps.rdflags |= RDF_UNDERWATER; else ent->client->ps.rdflags &= ~RDF_UNDERWATER; if (contents & (CONTENTS_SOLID | CONTENTS_LAVA)) SV_AddBlend (1.0f, 0.3f, 0.0f, 0.6f, ent->client->ps.blend); else if (contents & CONTENTS_SLIME) SV_AddBlend (0.0f, 0.1f, 0.05f, 0.6f, ent->client->ps.blend); else if (contents & CONTENTS_WATER) SV_AddBlend (0.5f, 0.3f, 0.2f, 0.4f, ent->client->ps.blend); // AQ2:TNG - Igor[Rock] adding new irvision mode if (new_irvision->value && (ent->client->resp.ir == 0) && INV_AMMO(ent, BAND_NUM)) { SV_AddBlend (0.1f, 0.0f, 0.0f, 0.4f, ent->client->ps.blend); } // AQ2:TNG end of new irvision mode // add for powerups if (ent->client->quad_framenum > level.framenum) { remaining = ent->client->quad_framenum - level.framenum; if (remaining == 30) // beginning to fade gi.sound (ent, CHAN_ITEM, gi.soundindex("items/damage2.wav"), 1, ATTN_NORM, 0); if (remaining > 30 || (remaining & 4)) SV_AddBlend (0, 0, 1, 0.08f, ent->client->ps.blend); } else if (ent->client->invincible_framenum > level.framenum) { remaining = ent->client->invincible_framenum - level.framenum; if (remaining == 30) // beginning to fade gi.sound (ent, CHAN_ITEM, gi.soundindex("items/protect2.wav"), 1, ATTN_NORM, 0); if (remaining > 30 || (remaining & 4)) SV_AddBlend (1, 1, 0, 0.08f, ent->client->ps.blend); } else if (ent->client->enviro_framenum > level.framenum) { remaining = ent->client->enviro_framenum - level.framenum; if (remaining == 30) // beginning to fade gi.sound (ent, CHAN_ITEM, gi.soundindex("items/airout.wav"), 1, ATTN_NORM, 0); if (remaining > 30 || (remaining & 4)) SV_AddBlend (0, 1, 0, 0.08f, ent->client->ps.blend); } else if (ent->client->breather_framenum > level.framenum) { remaining = ent->client->breather_framenum - level.framenum; if (remaining == 30) // beginning to fade gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/airout.wav"), 1, ATTN_NORM, 0); if (remaining > 30 || (remaining & 4)) SV_AddBlend (0.4f, 1, 0.4f, 0.04f, ent->client->ps.blend); } // add for damage if (ent->client->damage_alpha > 0) SV_AddBlend (ent->client->damage_blend[0], ent->client->damage_blend[1], ent->client->damage_blend[2], ent->client->damage_alpha, ent->client->ps.blend); if (ent->client->bonus_alpha > 0) SV_AddBlend (0.85f, 0.7f, 0.3f, ent->client->bonus_alpha, ent->client->ps.blend); // drop the damage value ent->client->damage_alpha -= 0.06f; if (ent->client->damage_alpha < 0) ent->client->damage_alpha = 0; // drop the bonus value ent->client->bonus_alpha -= 0.1f; if (ent->client->bonus_alpha < 0) ent->client->bonus_alpha = 0; } /* ================= P_FallingDamage ================= */ void P_FallingDamage (edict_t * ent) { float delta; int damage; vec3_t dir; if (lights_camera_action || ent->client->ctf_uvtime > 0) return; if (ent->s.modelindex != 255) return; // not in the player model if (ent->movetype == MOVETYPE_NOCLIP) return; if ((ent->client->oldvelocity[2] < 0) && (ent->velocity[2] > ent->client->oldvelocity[2]) && (!ent->groundentity)) { delta = ent->client->oldvelocity[2]; } else { if (!ent->groundentity) return; delta = ent->velocity[2] - ent->client->oldvelocity[2]; ent->client->jumping = 0; } delta = delta * delta * 0.0001; // never take damage if just release grapple or on grapple if (level.time - ent->client->ctf_grapplereleasetime <= FRAMETIME * 2 || (ent->client->ctf_grapple && ent->client->ctf_grapplestate > CTF_GRAPPLE_STATE_FLY)) return; // never take falling damage if completely underwater if (ent->waterlevel == 3) return; else if (ent->waterlevel == 2) delta *= 0.25; else if (ent->waterlevel == 1) delta *= 0.5; if (delta < 1) return; if (delta < 15) { // zucc look for slippers to avoid noise if(!INV_AMMO(ent, SLIP_NUM)) ent->s.event = EV_FOOTSTEP; return; } ent->client->fall_value = delta * 0.5; if (ent->client->fall_value > 40) ent->client->fall_value = 40; ent->client->fall_time = level.time + FALL_TIME; if (delta <= 30) { //zucc added check for slippers, this is just another noise if(!INV_AMMO(ent, SLIP_NUM)) ent->s.event = EV_FALLSHORT; return; } /* when fall damage is disabled, play the normal fall sound */ if((int) dmflags->value & DF_NO_FALLING) { ent->s.event = EV_FALLSHORT; return; } if (ent->health > 0) { if (delta >= 55) ent->s.event = EV_FALLFAR; else // all falls are far ent->s.event = EV_FALLFAR; } ent->pain_debounce_time = level.time; // no normal pain sound if (!deathmatch->value || !((int) dmflags->value & DF_NO_FALLING)) { damage = (int) (((delta - 30) / 2)); if (damage < 1) damage = 1; // zucc scale this up damage *= 10; VectorSet (dir, 0, 0, 1); T_Damage (ent, world, world, dir, ent->s.origin, vec3_origin, damage, 0, 0, MOD_FALLING); } } /* ============= P_WorldEffects ============= */ void P_WorldEffects (void) { qboolean breather; qboolean envirosuit; int waterlevel, old_waterlevel; if (current_player->movetype == MOVETYPE_NOCLIP) { current_player->air_finished = level.time + 12; // don't need air return; } waterlevel = current_player->waterlevel; old_waterlevel = current_client->old_waterlevel; current_client->old_waterlevel = waterlevel; breather = current_client->breather_framenum > level.framenum; envirosuit = current_client->enviro_framenum > level.framenum; // // if just entered a water volume, play a sound // if (!old_waterlevel && waterlevel) { PlayerNoise (current_player, current_player->s.origin, PNOISE_SELF); if (current_player->watertype & CONTENTS_LAVA) gi.sound (current_player, CHAN_BODY, gi.soundindex ("player/lava_in.wav"), 1, ATTN_NORM, 0); else if (current_player->watertype & CONTENTS_SLIME) gi.sound (current_player, CHAN_BODY, gi.soundindex ("player/watr_in.wav"), 1, ATTN_NORM, 0); else if (current_player->watertype & CONTENTS_WATER) gi.sound (current_player, CHAN_BODY, gi.soundindex ("player/watr_in.wav"), 1, ATTN_NORM, 0); current_player->flags |= FL_INWATER; // clear damage_debounce, so the pain sound will play immediately current_player->damage_debounce_time = level.time - 1; } // // if just completely exited a water volume, play a sound // if (old_waterlevel && !waterlevel) { PlayerNoise (current_player, current_player->s.origin, PNOISE_SELF); gi.sound (current_player, CHAN_BODY, gi.soundindex ("player/watr_out.wav"), 1, ATTN_NORM, 0); current_player->flags &= ~FL_INWATER; } // // check for head just going under water // if (old_waterlevel != 3 && waterlevel == 3) { gi.sound (current_player, CHAN_BODY, gi.soundindex ("player/watr_un.wav"), 1, ATTN_NORM, 0); } // // check for head just coming out of water // if (old_waterlevel == 3 && waterlevel != 3) { if (current_player->air_finished < level.time) { // gasp for air gi.sound (current_player, CHAN_VOICE, gi.soundindex ("player/gasp1.wav"), 1, ATTN_NORM, 0); PlayerNoise (current_player, current_player->s.origin, PNOISE_SELF); } else if (current_player->air_finished < level.time + 11) { // just break surface gi.sound (current_player, CHAN_VOICE, gi.soundindex ("player/gasp2.wav"), 1, ATTN_NORM, 0); } } // // check for drowning // if (waterlevel == 3) { // breather or envirosuit give air if (breather || envirosuit) { current_player->air_finished = level.time + 10; if (((int)(current_client->breather_framenum - level.framenum) % 25) == 0) { if (!current_client->breather_sound) gi.sound (current_player, CHAN_AUTO, gi.soundindex("player/u_breath1.wav"), 1, ATTN_NORM, 0); else gi.sound (current_player, CHAN_AUTO, gi.soundindex("player/u_breath2.wav"), 1, ATTN_NORM, 0); current_client->breather_sound ^= 1; PlayerNoise (current_player, current_player->s.origin, PNOISE_SELF); //FIXME: release a bubble? } } // if out of air, start drowning if (current_player->air_finished < level.time) { // drown! if (current_player->client->next_drown_time < level.time && current_player->health > 0) { current_player->client->next_drown_time = level.time + 1; // take more damage the longer underwater current_player->dmg += 2; if (current_player->dmg > 15) current_player->dmg = 15; // play a gurp sound instead of a normal pain sound if (current_player->health <= current_player->dmg) gi.sound (current_player, CHAN_VOICE, gi.soundindex ("player/drown1.wav"), 1, ATTN_NORM, 0); else if (rand () & 1) gi.sound (current_player, CHAN_VOICE, gi.soundindex ("*gurp1.wav"), 1, ATTN_NORM, 0); else gi.sound (current_player, CHAN_VOICE, gi.soundindex ("*gurp2.wav"), 1, ATTN_NORM, 0); current_player->pain_debounce_time = level.time; T_Damage (current_player, world, world, vec3_origin, current_player->s.origin, vec3_origin, current_player->dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER); } } } else { current_player->air_finished = level.time + 12; current_player->dmg = 2; } // // check for sizzle damage // if (waterlevel && (current_player->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) { if (current_player->watertype & CONTENTS_LAVA) { if (current_player->health > 0 && current_player->pain_debounce_time <= level.time && current_client->invincible_framenum < level.framenum) { if (rand () & 1) gi.sound (current_player, CHAN_VOICE, gi.soundindex ("player/burn1.wav"), 1, ATTN_NORM, 0); else gi.sound (current_player, CHAN_VOICE, gi.soundindex ("player/burn2.wav"), 1, ATTN_NORM, 0); current_player->pain_debounce_time = level.time + 1; } if (envirosuit) // take 1/3 damage with envirosuit T_Damage (current_player, world, world, vec3_origin, current_player->s.origin, vec3_origin, 1 * waterlevel, 0, 0, MOD_LAVA); else T_Damage (current_player, world, world, vec3_origin, current_player->s.origin, vec3_origin, 3 * waterlevel, 0, 0, MOD_LAVA); } if (current_player->watertype & CONTENTS_SLIME && !envirosuit) { // no damage from slime with envirosuit T_Damage (current_player, world, world, vec3_origin, current_player->s.origin, vec3_origin, 1 * waterlevel, 0, 0, MOD_SLIME); } } } /* =============== G_SetClientEffects =============== */ void G_SetClientEffects (edict_t * ent) { int pa_type; int remaining; ent->s.effects = 0; // zucc added RF_IR_VISIBLE //FB 6/1/99 - only for live players if (ent->deadflag != DEAD_DEAD) ent->s.renderfx = RF_IR_VISIBLE; else ent->s.renderfx = 0; if (ent->health <= 0 || level.intermissiontime) return; if (ent->powerarmor_time > level.time) { pa_type = PowerArmorType (ent); if (pa_type == POWER_ARMOR_SCREEN) { ent->s.effects |= EF_POWERSCREEN; } else if (pa_type == POWER_ARMOR_SHIELD) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= RF_SHELL_GREEN; } } if (ctf->value) CTFEffects (ent); if (ent->client->quad_framenum > level.framenum) { remaining = ent->client->quad_framenum - level.framenum; if (remaining > 30 || (remaining & 4)) ent->s.effects |= EF_QUAD; } if (ent->client->invincible_framenum > level.framenum) { remaining = ent->client->invincible_framenum - level.framenum; if (remaining > 30 || (remaining & 4)) ent->s.effects |= EF_PENT; } // show cheaters!!! if (ent->flags & FL_GODMODE) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= (RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE); } // AQ2:TNG - JBravo adding UVtime if ((ctf->value || dm_shield->value) && ((ent->client->ctf_uvtime & 4) || (lights_camera_action & 4))) { ent->s.effects |= EF_COLOR_SHELL; if (ent->client->resp.team == TEAM1) ent->s.renderfx |= RF_SHELL_RED; else if (ent->client->resp.team == TEAM2) ent->s.renderfx |= RF_SHELL_BLUE; else ent->s.renderfx |= RF_SHELL_GREEN; } // TNG Flashlight if ((darkmatch->value) && (ent->client) && (ent->flashlight)) { //ent->s.effects |= EF_YELLOWSHELL; // no good one? :/ ent->s.renderfx |= RF_FULLBRIGHT; } } /* =============== G_SetClientEvent =============== */ void G_SetClientEvent (edict_t * ent) { if (ent->s.event) return; if (ent->groundentity && xyspeed > 225) { //zucc added item check to see if they have slippers if ((int)(current_client->bobtime + bobmove) != bobcycle && !INV_AMMO(ent, SLIP_NUM)) ent->s.event = EV_FOOTSTEP; } } /* =============== G_SetClientSound =============== */ void G_SetClientSound (edict_t * ent) { char *weap; if (ent->client->resp.game_helpchanged != game.helpchanged) { ent->client->resp.game_helpchanged = game.helpchanged; ent->client->resp.helpchanged = 1; } // help beep (no more than three times) if (ent->client->resp.helpchanged && ent->client->resp.helpchanged <= 3 && !(level.framenum & 63)) { ent->client->resp.helpchanged++; gi.sound (ent, CHAN_VOICE, gi.soundindex ("misc/pc_up.wav"), 1, ATTN_STATIC, 0); } if (ent->client->pers.weapon) weap = ent->client->pers.weapon->classname; else weap = ""; if (ent->waterlevel && (ent->watertype & (CONTENTS_LAVA | CONTENTS_SLIME))) ent->s.sound = snd_fry; else if (strcmp (weap, "weapon_railgun") == 0) ent->s.sound = gi.soundindex ("weapons/rg_hum.wav"); else if (strcmp (weap, "weapon_bfg") == 0) ent->s.sound = gi.soundindex ("weapons/bfg_hum.wav"); else if (ent->client->weapon_sound) ent->s.sound = ent->client->weapon_sound; else ent->s.sound = 0; } /* =============== G_SetClientFrame =============== */ void G_SetClientFrame (edict_t * ent) { gclient_t *client; qboolean duck, run; if (ent->s.modelindex != 255) return; // not in the player model client = ent->client; if (client->ps.pmove.pm_flags & PMF_DUCKED) duck = true; else duck = false; if (xyspeed) run = true; else run = false; // check for stand/duck and stop/go transitions if (duck != client->anim_duck && client->anim_priority < ANIM_DEATH) goto newanim; if (run != client->anim_run && client->anim_priority == ANIM_BASIC) goto newanim; if (!ent->groundentity && client->anim_priority <= ANIM_WAVE) goto newanim; // zucc vwep if (client->anim_priority == ANIM_REVERSE) { if (ent->s.frame > client->anim_end) { ent->s.frame--; return; } } else if (ent->s.frame < client->anim_end) { // continue an animation ent->s.frame++; return; } if (client->anim_priority == ANIM_DEATH) return; // stay there if (client->anim_priority == ANIM_JUMP) { if (!ent->groundentity) return; // stay there ent->client->anim_priority = ANIM_WAVE; ent->s.frame = FRAME_jump3; ent->client->anim_end = FRAME_jump6; return; } newanim: // return to either a running or standing frame client->anim_priority = ANIM_BASIC; client->anim_duck = duck; client->anim_run = run; if (!ent->groundentity) { // if on grapple, don't go into jump frame, go into standing if (client->ctf_grapple) { ent->s.frame = FRAME_stand01; client->anim_end = FRAME_stand40; } client->anim_priority = ANIM_JUMP; if (ent->s.frame != FRAME_jump2) ent->s.frame = FRAME_jump1; client->anim_end = FRAME_jump2; } else if (run) { // running if (duck) { ent->s.frame = FRAME_crwalk1; client->anim_end = FRAME_crwalk6; } else { ent->s.frame = FRAME_run1; client->anim_end = FRAME_run6; } } else { // standing if (duck) { ent->s.frame = FRAME_crstnd01; client->anim_end = FRAME_crstnd19; } else { ent->s.frame = FRAME_stand01; client->anim_end = FRAME_stand40; } } } void Do_Bleeding (edict_t * ent) { int damage; int temp; //vec3_t norm = {0.0, 0.0, 0.0}; if (!(ent->client->bleeding) || (ent->health <= 0)) return; temp = (int) (ent->client->bleeding * .2); ent->client->bleeding -= temp; if (temp <= 0) temp = 1; ent->client->bleed_remain += temp; damage = (int) (ent->client->bleed_remain / BLEED_TIME); if (ent->client->bleed_remain >= BLEED_TIME) { ent->health -= damage; if (damage > 1) { // action doens't do this //ent->client->damage_blood += damage; // for feedback } if (ent->health <= 0) { meansOfDeath = ent->client->attacker_mod; locOfDeath = ent->client->attacker_loc; Killed (ent, ent->client->attacker, ent->client->attacker, damage, ent->s.origin); } else { ent->client->bleed_remain %= BLEED_TIME; } if (ent->client->bleeddelay <= level.time) { vec3_t pos; ent->client->bleeddelay = level.time + 2; // 2 seconds VectorAdd (ent->client->bleedloc_offset, ent->absmax, pos); //gi.cprintf(ent, PRINT_HIGH, "Bleeding now.\n"); EjectBlooder (ent, pos, pos); // do bleeding } } } int canFire (edict_t * ent) { int result = 0; switch (ent->client->curr_weap) { case MK23_NUM: if (ent->client->mk23_rds > 0) result = 1; break; case MP5_NUM: if (ent->client->mp5_rds > 0) result = 1; break; case M4_NUM: if (ent->client->m4_rds > 0) result = 1; break; case M3_NUM: if (ent->client->shot_rds > 0) result = 1; break; case HC_NUM: if (ent->client->cannon_rds == 2) result = 1; break; case SNIPER_NUM: if (ent->client->sniper_rds > 0) result = 1; break; case DUAL_NUM: if (ent->client->dual_rds > 0) result = 1; break; default: result = 0; break; } return result; } /* ================= ClientEndServerFrame Called for each player at the end of the server frame and right after spawning ================= */ void ClientEndServerFrame (edict_t * ent) { float bobtime; int i; //char player_name[30]; //char temp[40]; // int damage; // zucc for bleeding current_player = ent; current_client = ent->client; //AQ2:TNG - Slicer : Stuffs the client x seconds after he enters the server, needed for Video check if (ent->client->resp.checktime[0] <= level.time) { ent->client->resp.checktime[0] = level.time + video_checktime->value; if (video_check->value || video_check_lockpvs->value || video_check_glclear->value || darkmatch->value) stuffcmd (ent, "%!fc $vid_ref\n"); if (video_force_restart->value && video_check->value && !ent->client->resp.checked) { stuffcmd (ent, "vid_restart\n"); ent->client->resp.checked = true; } } if (ent->client->resp.checktime[1] <= level.time) { ent->client->resp.checktime[1] = level.time + video_checktime->value; ent->client->resp.checktime[2] = level.time + 1; if (video_check->value || video_check_lockpvs->value || video_check_glclear->value || darkmatch->value) { if (ent->client->resp.vidref && Q_stricmp(ent->client->resp.vidref, "soft")) stuffcmd (ent, "%cpsi $gl_modulate $gl_lockpvs $gl_clear $gl_dynamic $gl_driver\n"); } } if (ent->client->resp.checktime[2] <= level.time) { // ent->client->resp.checktime[2] = level.time + video_checktime->value; if (video_check->value || video_check_lockpvs->value || video_check_glclear->value || darkmatch->value) { if (ent->client->resp.vidref && Q_stricmp(ent->client->resp.vidref, "soft")) VideoCheckClient (ent); } } if(pause_time) { G_SetStats (ent); return; } //FIREBLADE - Unstick avoidance stuff. if (ent->solid == SOLID_TRIGGER && !lights_camera_action) { edict_t *overlap; if ((overlap = FindOverlap (ent, NULL)) == NULL) { ent->solid = SOLID_BBOX; gi.linkentity (ent); RemoveFromTransparentList (ent); } else { do { if (overlap->solid == SOLID_BBOX) { overlap->solid = SOLID_TRIGGER; gi.linkentity (overlap); AddToTransparentList (overlap); } overlap = FindOverlap (ent, overlap); } while (overlap != NULL); } } //FIREBLADE // // If the origin or velocity have changed since ClientThink(), // update the pmove values. This will happen when the client // is pushed by a bmodel or kicked by an explosion. // // If it wasn't updated here, the view position would lag a frame // behind the body position when pushed -- "sinking into plats" // for (i = 0; i < 3; i++) { current_client->ps.pmove.origin[i] = ent->s.origin[i] * 8.0; current_client->ps.pmove.velocity[i] = ent->velocity[i] * 8.0; } // // If the end of unit layout is displayed, don't give // the player any normal movement attributes // if (level.intermissiontime) { // FIXME: add view drifting here? current_client->ps.blend[3] = 0; current_client->ps.fov = 90; G_SetStats (ent); return; } AngleVectors (ent->client->v_angle, forward, right, up); // burn from lava, etc P_WorldEffects (); // // set model angles from view angles so other things in // the world can tell which direction you are looking // if (ent->client->v_angle[PITCH] > 180) ent->s.angles[PITCH] = (-360 + ent->client->v_angle[PITCH]) / 3; else ent->s.angles[PITCH] = ent->client->v_angle[PITCH] / 3; ent->s.angles[YAW] = ent->client->v_angle[YAW]; ent->s.angles[ROLL] = 0; ent->s.angles[ROLL] = SV_CalcRoll (ent->s.angles, ent->velocity) * 4; // // calculate speed and cycle to be used for // all cyclic walking effects // xyspeed = sqrt(ent->velocity[0]*ent->velocity[0] + ent->velocity[1]*ent->velocity[1]); if (xyspeed < 5 || ent->solid == SOLID_NOT) { bobmove = 0; current_client->bobtime = 0; // start at beginning of cycle again } else if (ent->groundentity) { // so bobbing only cycles when on ground if (xyspeed > 210) bobmove = 0.25; else if (xyspeed > 100) bobmove = 0.125; else bobmove = 0.0625; } bobtime = (current_client->bobtime += bobmove); if (current_client->ps.pmove.pm_flags & PMF_DUCKED) bobtime *= 4; bobcycle = (int) bobtime; bobfracsin = fabs (sin (bobtime * M_PI)); // detect hitting the floor P_FallingDamage (ent); // zucc handle any bleeding damage here Do_Bleeding (ent); // apply all the damage taken this frame P_DamageFeedback (ent); // determine the view offsets SV_CalcViewOffset (ent); // determine the gun offsets SV_CalcGunOffset (ent); // determine the full screen color blend // must be after viewoffset, so eye contents can be // accurately determined // FIXME: with client prediction, the contents // should be determined by the client SV_CalcBlend (ent); G_SetStats (ent); //FIREBLADE for (i = 1; i <= maxclients->value; i++) { int stats_copy; edict_t *e = g_edicts + i; if (!ent->inuse || e->client->chase_mode == 0 || e->client->chase_target != ent) continue; for (stats_copy = 0; stats_copy < MAX_STATS; stats_copy++) { if (stats_copy >= STAT_TEAM_HEADER && stats_copy <= STAT_TEAM2_SCORE) continue; // protect these if (stats_copy >= STAT_TEAM3_PIC && stats_copy <= STAT_TEAM3_SCORE) continue; // protect these if (stats_copy == STAT_LAYOUTS || stats_copy == STAT_ID_VIEW) continue; // protect these if (stats_copy == STAT_SNIPER_ICON && e->client->chase_mode != 2) continue; // only show sniper lens when in chase mode 2 if (stats_copy == STAT_FRAGS) continue; e->client->ps.stats[stats_copy] = ent->client->ps.stats[stats_copy]; } //FB e->client->ps.stats[STAT_LAYOUTS] = 1; //FB break; } //FIREBLADE G_SetClientEvent (ent); G_SetClientEffects (ent); G_SetClientSound (ent); G_SetClientFrame (ent); VectorCopy (ent->velocity, ent->client->oldvelocity); VectorCopy (ent->client->ps.viewangles, ent->client->oldviewangles); // clear weapon kicks VectorClear (ent->client->kick_origin); VectorClear (ent->client->kick_angles); // zucc - clear the open door command ent->client->doortoggle = 0; if (ent->client->push_timeout > 0) ent->client->push_timeout--; /* else { ent->client->attacker = NULL; ent->client->attacker_mod = MOD_BLEEDING; } */ if (ent->client->reload_attempts > 0) { if (((ent->client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK) && canFire(ent)) { ent->client->reload_attempts = 0; } else { Cmd_Reload_f (ent); } } if (ent->client->weapon_attempts > 0) Cmd_Weapon_f (ent); // if the scoreboard is up, update it if (ent->client->showscores && !(level.framenum & 31)) { //FIREBLADE if (ent->client->menu) { PMenu_Update (ent); } else //FIREBLADE DeathmatchScoreboardMessage (ent, ent->enemy); gi.unicast (ent, false); } //FIREBLADE if(!pause_time) RadioThink (ent); //FIREBLADE }
544
./aq2-tng/source/g_save.c
//----------------------------------------------------------------------------- // g_save.c // // $Id: g_save.c,v 1.65 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: g_save.c,v $ // Revision 1.65 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.64 2004/01/18 11:25:31 igor_rock // added flashgrenades // // Revision 1.63 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.62 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.61 2002/09/04 11:23:10 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.60 2002/03/30 17:20:59 ra // New cvar use_buggy_bandolier to control behavior of dropping bando and grenades // // Revision 1.59 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.58 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.57 2002/03/25 23:35:19 freud // Ghost code, use_ghosts and more stuff.. // // Revision 1.56 2002/03/24 22:45:54 freud // New spawn code again, bad commit last time.. // // Revision 1.55 2002/02/26 23:13:41 freud // Added tgren and use_classic to serverinfo string // // Revision 1.54 2002/02/19 09:32:47 freud // Removed PING PONGs from CVS, not fit for release. // // Revision 1.53 2002/02/18 20:21:36 freud // Added PING PONG mechanism for timely disconnection of clients. This is // based on a similar scheme as the scheme used by IRC. The client has // cvar ping_timeout seconds to reply or will be disconnected. // // Revision 1.52 2002/02/18 18:25:51 ra // Bumped version to 2.6, fixed ctf falling and kicking of players in ctf // uvtime // // Revision 1.51 2002/02/17 20:10:09 freud // Better naming of auto_items is auto_equip, requested by Deathwatch. // // Revision 1.50 2002/02/17 20:01:32 freud // Fixed stat_mode overflows, finally. // Added 2 new cvars: // auto_join (0|1), enables auto joining teams from previous map. // auto_items (0|1), enables weapon and items caching between maps. // // Revision 1.49 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.48 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.46 2001/12/23 16:30:50 ra // 2.5 ready. New stats from Freud. HC and shotgun gibbing seperated. // // Revision 1.45 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.44 2001/11/27 19:09:52 igor_rock // removed tgren, limchasecam and ir from serverinfo // changed the cvarname of the teamscore to t1, t2 and t3 - the c variables are still team1score and so on. // // Revision 1.43 2001/11/08 10:05:09 igor_rock // day/night changing smoothened // changed default for day_cycle to 10 (because of more steps) // // Revision 1.42 2001/11/07 11:03:35 igor_rock // corrected some disformatting (removed linebreak at wrong position) // // Revision 1.41 2001/11/04 15:18:49 ra // Unlatch wpn_flag, itm_flag, rrot, vrot // // Revision 1.40 2001/10/18 12:04:44 deathwatch // Fixed sv_crlf's default (0 == dont allow) // // Revision 1.39 2001/09/30 03:09:34 ra // Removed new stats at end of rounds and created a new command to // do the same functionality. Command is called "time" // // Revision 1.38 2001/09/29 19:54:04 ra // Made a CVAR to turn off extratimingstats // // Revision 1.37 2001/09/28 20:45:55 ra // Switched punching on by default // // Revision 1.36 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.35 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.34 2001/09/02 20:33:34 deathwatch // Added use_classic and fixed an issue with ff_afterround, also updated version // nr and cleaned up some commands. // // Updated the VC Project to output the release build correctly. // // Revision 1.33 2001/08/18 01:28:06 deathwatch // Fixed some stats stuff, added darkmatch + day_cycle, cleaned up several files, restructured ClientCommand // // Revision 1.32 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.31 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.30 2001/08/06 03:00:49 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.29 2001/07/27 00:20:55 deathwatch // Latched wp_flags and itm_flags // // Revision 1.28 2001/07/16 18:28:46 ra // Changed a 40 second hard limit on mapvoting into a cvar. // // Revision 1.27 2001/06/28 14:36:40 deathwatch // Updated the Credits Menu a slight bit (added Kobra) // // Revision 1.26 2001/06/26 18:47:30 igor_rock // added ctf_respawn cvar // // Revision 1.25 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.24 2001/06/22 16:34:05 slicerdw // Finished Matchmode Basics, now with admins, Say command tweaked... // // Revision 1.23 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.22 2001/06/20 07:29:27 igor_rock // corrected typo // // Revision 1.21 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.20 2001/06/19 21:26:20 igor_rock // changed sv_crlf to be 0 as default // // Revision 1.19 2001/06/18 12:36:40 igor_rock // added new irvision mode (with reddish screen and alpha blend) and corresponding // new cvar "new_irvision" to enable the new mode // // Revision 1.18 2001/06/13 08:39:13 igor_rock // changed "cvote" to "use_cvote" (like the other votecvars) // // Revision 1.17 2001/06/06 18:57:14 slicerdw // Some tweaks on Ctf and related things // // Revision 1.14 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.13 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.12.2.5 2001/05/27 13:44:07 igor_rock // corredted the bug with gi.cvar and ctf_dropflag (mixed paremeters) // // Revision 1.12.2.4 2001/05/27 13:41:57 igor_rock // added ctf_dropflag (default: 1) // // Revision 1.12.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.12.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.12.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.12 2001/05/19 19:33:19 igor_rock // changed itm_flags and wp_flags to Non-CVAR_LATCH (so you can change them without restart // // Revision 1.11 2001/05/17 14:54:47 igor_rock // added itm_flags for teamplay and ctf // // Revision 1.10 2001/05/16 13:26:38 slicerdw // Too Many Userinfo Cvars( commented some) & Enabled death messages on CTF // // Revision 1.9 2001/05/15 15:49:14 igor_rock // added itm_flags for deathmatch // // Revision 1.8 2001/05/14 21:10:16 igor_rock // added wp_flags support (and itm_flags skeleton - doesn't disturb in the moment) // // Revision 1.7 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.6 2001/05/12 21:19:51 ra // // // Added punishkills. // // Revision 1.5 2001/05/12 20:58:22 ra // // // Adding public mapvoting and kickvoting. Its controlable via cvar's mv_public // and vk_public (both default off) // // Revision 1.4 2001/05/12 00:37:03 ra // // // Fixing various compilerwarnings. // // Revision 1.3 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.2 2001/05/07 08:32:17 mort // Basic CTF code // No spawns etc // Just the cvars and flag entity // // Revision 1.1.1.1 2001/05/06 17:29:57 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" field_t fields[] = { {"classname", FOFS (classname), F_LSTRING} , {"origin", FOFS (s.origin), F_VECTOR} , {"model", FOFS (model), F_LSTRING} , {"spawnflags", FOFS (spawnflags), F_INT} , {"speed", FOFS (speed), F_FLOAT} , {"accel", FOFS (accel), F_FLOAT} , {"decel", FOFS (decel), F_FLOAT} , {"target", FOFS (target), F_LSTRING} , {"targetname", FOFS (targetname), F_LSTRING} , {"pathtarget", FOFS (pathtarget), F_LSTRING} , {"deathtarget", FOFS (deathtarget), F_LSTRING} , {"killtarget", FOFS (killtarget), F_LSTRING} , {"combattarget", FOFS (combattarget), F_LSTRING} , {"message", FOFS (message), F_LSTRING} , {"team", FOFS (team), F_LSTRING} , {"wait", FOFS (wait), F_FLOAT} , {"delay", FOFS (delay), F_FLOAT} , {"random", FOFS (random), F_FLOAT} , {"move_origin", FOFS (move_origin), F_VECTOR} , {"move_angles", FOFS (move_angles), F_VECTOR} , {"style", FOFS (style), F_INT} , {"count", FOFS (count), F_INT} , {"health", FOFS (health), F_INT} , {"sounds", FOFS (sounds), F_INT} , {"light", 0, F_IGNORE} , {"dmg", FOFS (dmg), F_INT} , {"angles", FOFS (s.angles), F_VECTOR} , {"angle", FOFS (s.angles), F_ANGLEHACK} , {"mass", FOFS (mass), F_INT} , {"volume", FOFS (volume), F_FLOAT} , {"attenuation", FOFS (attenuation), F_FLOAT} , {"map", FOFS (map), F_LSTRING} , // temp spawn vars -- only valid when the spawn function is called {"lip", STOFS (lip), F_INT, FFL_SPAWNTEMP} , {"distance", STOFS (distance), F_INT, FFL_SPAWNTEMP} , {"height", STOFS (height), F_INT, FFL_SPAWNTEMP} , {"noise", STOFS (noise), F_LSTRING, FFL_SPAWNTEMP} , {"pausetime", STOFS (pausetime), F_FLOAT, FFL_SPAWNTEMP} , {"item", STOFS (item), F_LSTRING, FFL_SPAWNTEMP} , {"gravity", STOFS (gravity), F_LSTRING, FFL_SPAWNTEMP} , {"sky", STOFS (sky), F_LSTRING, FFL_SPAWNTEMP} , {"skyrotate", STOFS (skyrotate), F_FLOAT, FFL_SPAWNTEMP} , {"skyaxis", STOFS (skyaxis), F_VECTOR, FFL_SPAWNTEMP} , {"minyaw", STOFS (minyaw), F_FLOAT, FFL_SPAWNTEMP} , {"maxyaw", STOFS (maxyaw), F_FLOAT, FFL_SPAWNTEMP} , {"minpitch", STOFS (minpitch), F_FLOAT, FFL_SPAWNTEMP} , {"maxpitch", STOFS (maxpitch), F_FLOAT, FFL_SPAWNTEMP} , {"nextmap", STOFS (nextmap), F_LSTRING, FFL_SPAWNTEMP} }; // -------- just for savegames ---------- // all pointer fields should be listed here, or savegames // won't work properly (they will crash and burn). // this wasn't just tacked on to the fields array, because // these don't need names, we wouldn't want map fields using // some of these, and if one were accidentally present twice // it would double swizzle (fuck) the pointer. field_t savefields[] = { {"", FOFS (classname), F_LSTRING} , {"", FOFS (target), F_LSTRING} , {"", FOFS (targetname), F_LSTRING} , {"", FOFS (killtarget), F_LSTRING} , {"", FOFS (team), F_LSTRING} , {"", FOFS (pathtarget), F_LSTRING} , {"", FOFS (deathtarget), F_LSTRING} , {"", FOFS (combattarget), F_LSTRING} , {"", FOFS (model), F_LSTRING} , {"", FOFS (map), F_LSTRING} , {"", FOFS (message), F_LSTRING} , {"", FOFS (client), F_CLIENT} , {"", FOFS (item), F_ITEM} , {"", FOFS (goalentity), F_EDICT} , {"", FOFS (movetarget), F_EDICT} , {"", FOFS (enemy), F_EDICT} , {"", FOFS (oldenemy), F_EDICT} , {"", FOFS (activator), F_EDICT} , {"", FOFS (groundentity), F_EDICT} , {"", FOFS (teamchain), F_EDICT} , {"", FOFS (teammaster), F_EDICT} , {"", FOFS (owner), F_EDICT} , {"", FOFS (mynoise), F_EDICT} , {"", FOFS (mynoise2), F_EDICT} , {"", FOFS (target_ent), F_EDICT} , {"", FOFS (chain), F_EDICT} , {NULL, 0, F_INT} }; field_t levelfields[] = { {"", LLOFS (changemap), F_LSTRING} , {"", LLOFS (sight_client), F_EDICT} , {"", LLOFS (sight_entity), F_EDICT} , {"", LLOFS (sound_entity), F_EDICT} , {"", LLOFS (sound2_entity), F_EDICT} , {NULL, 0, F_INT} }; field_t clientfields[] = { {"", CLOFS (pers.weapon), F_ITEM} , {"", CLOFS (pers.lastweapon), F_ITEM} , {"", CLOFS (newweapon), F_ITEM} , {NULL, 0, F_INT} }; /* ============ InitGame This will be called when the dll is first loaded, which only happens when a new game is started or a save game is loaded. ============ */ void InitGame (void) { IRC_init (); gi.dprintf ("==== InitGame ====\n"); ReadConfigFile (); ReadMOTDFile (); gun_x = gi.cvar ("gun_x", "0", 0); gun_y = gi.cvar ("gun_y", "0", 0); gun_z = gi.cvar ("gun_z", "0", 0); //FIXME: sv_ prefix is wrong for these sv_rollspeed = gi.cvar ("sv_rollspeed", "200", 0); sv_rollangle = gi.cvar ("sv_rollangle", "2", 0); sv_maxvelocity = gi.cvar ("sv_maxvelocity", "2000", 0); sv_gravity = gi.cvar ("sv_gravity", "800", 0); // noset vars dedicated = gi.cvar ("dedicated", "0", CVAR_NOSET); // latched vars sv_cheats = gi.cvar ("cheats", "0", CVAR_SERVERINFO | CVAR_LATCH); gi.cvar ("gamename", GAMEVERSION, CVAR_SERVERINFO | CVAR_LATCH); gi.cvar ("gamedate", __DATE__, CVAR_SERVERINFO | CVAR_LATCH); maxclients = gi.cvar ("maxclients", "8", CVAR_SERVERINFO | CVAR_LATCH); deathmatch = gi.cvar ("deathmatch", "1", CVAR_LATCH); coop = gi.cvar ("coop", "0", CVAR_LATCH); skill = gi.cvar ("skill", "1", CVAR_LATCH); maxentities = gi.cvar ("maxentities", "1024", CVAR_LATCH); if (!deathmatch->value) { gi.dprintf("Turning deathmatch on.\n"); gi.cvar_forceset("deathmatch", "1"); } if (coop->value) { gi.dprintf("Turning coop off.\n"); gi.cvar_forceset("coop", "0"); } // change anytime vars dmflags = gi.cvar ("dmflags", "0", CVAR_SERVERINFO); fraglimit = gi.cvar ("fraglimit", "0", CVAR_SERVERINFO); timelimit = gi.cvar ("timelimit", "0", CVAR_SERVERINFO); capturelimit = gi.cvar ("capturelimit", "0", CVAR_SERVERINFO); password = gi.cvar ("password", "", CVAR_USERINFO); filterban = gi.cvar ("filterban", "1", 0); needpass = gi.cvar ("needpass", "0", CVAR_SERVERINFO); radiolog = gi.cvar ("radiolog", "0", 0); teamplay = gi.cvar ("teamplay", "0", CVAR_SERVERINFO | CVAR_LATCH); motd_time = gi.cvar ("motd_time", "2", 0); hostname = gi.cvar ("hostname", "unnamed", CVAR_SERVERINFO); strtwpn = gi.cvar ("dmweapon", MK23_NAME, 0); actionmaps = gi.cvar ("actionmaps", "1", 0); if (actionmaps->value && num_maps < 1) { gi.dprintf("No maps were read from the config file, \"actionmaps\" won't be used.\n"); gi.cvar_forceset("actionmaps", "0"); } nohud = gi.cvar ("nohud", "0", CVAR_LATCH); roundlimit = gi.cvar ("roundlimit", "0", CVAR_SERVERINFO); limchasecam = gi.cvar ("limchasecam", "0", CVAR_LATCH); skipmotd = gi.cvar ("skipmotd", "0", 0); roundtimelimit = gi.cvar ("roundtimelimit", "0", CVAR_SERVERINFO); maxteamkills = gi.cvar ("maxteamkills", "0", 0); twbanrounds = gi.cvar ("twbanrounds", "2", 0); tkbanrounds = gi.cvar ("tkbanrounds", "2", 0); noscore = gi.cvar ("noscore", "0", CVAR_LATCH); // Was serverinfo use_newscore = gi.cvar ("use_newscore", "1", 0); actionversion = gi.cvar ("actionversion", "none set", CVAR_SERVERINFO | CVAR_LATCH); gi.cvar_set ("actionversion", ACTION_VERSION); use_voice = gi.cvar ("use_voice", "1", 0); //slicer ppl_idletime = gi.cvar ("ppl_idletime", "15", 0); use_buggy_bandolier = gi.cvar ("use_buggy_bandolier", "0", 0); use_tourney = gi.cvar ("use_tourney", "0", CVAR_SERVERINFO | CVAR_LATCH); use_3teams = gi.cvar ("use_3teams", "0", CVAR_SERVERINFO | CVAR_LATCH); use_kickvote = gi.cvar ("use_kickvote", "1", 0); //slicer use_mapvote = gi.cvar ("use_mapvote", "1", 0); //slicer use_scramblevote = gi.cvar ("use_scramblevote", "1", 0); //slicer ctf = gi.cvar ("ctf", "0", CVAR_SERVERINFO | CVAR_LATCH); ctf_forcejoin = gi.cvar ("ctf_forcejoin", "", 0); ctf_mode = gi.cvar ("ctf_mode", "0", 0); ctf_dropflag = gi.cvar ("ctf_dropflag", "1", 0); ctf_respawn = gi.cvar ("ctf_respawn", "4", 0); ctf_model = gi.cvar ("ctf_model", "male", CVAR_LATCH); use_grapple = gi.cvar ("use_grapple", "0", 0); mv_public = gi.cvar ("mv_public", "0", 0); //slicer vk_public = gi.cvar ("vk_public", "0", 0); //slicer punishkills = gi.cvar ("punishkills", "1", 0); //slicer mapvote_waittime = gi.cvar ("mapvote_waittime", "8", 0); ff_afterround = gi.cvar ("ff_afterround", "1", 0); uvtime = gi.cvar ("uvtime", "40", 0); sv_gib = gi.cvar ("sv_gib", "1", 0); sv_crlf = gi.cvar ("sv_crlf", "0", CVAR_LATCH); // 0 == DONT ALLOW IT vrot = gi.cvar ("vrot", "0", 0); rrot = gi.cvar ("rrot", "0", 0); llsound = gi.cvar ("llsound", "1", CVAR_LATCH); use_cvote = gi.cvar ("use_cvote", "0", 0); // Removed it from Serverinfo new_irvision = gi.cvar ("new_irvision", "0", 0); use_rewards = gi.cvar ("use_rewards", "1", 0); use_warnings = gi.cvar ("use_warnings", "1", 0); check_time = gi.cvar ("check_time", "3", 0); video_check = gi.cvar ("video_check", "0", 0); video_max_3dfx = gi.cvar ("video_max_3dfx", "1.5", 0); video_max_3dfxam = gi.cvar ("video_max_3dfxam", "1.5", 0); video_max_opengl = gi.cvar ("video_max_opengl", "3.0", 0); video_force_restart = gi.cvar ("video_force_restart", "0", CVAR_LATCH); video_check_lockpvs = gi.cvar ("video_check_lockpvs", "0", 0); video_check_glclear = gi.cvar ("video_check_glclear", "0", 0); video_checktime = gi.cvar ("video_checktime", "15", 0); hc_single = gi.cvar ("hc_single", "1", CVAR_LATCH); //default ON wp_flags = gi.cvar ("wp_flags", "511", 0); // 511 = WPF_MK23 | WPF_MP5 | WPF_M4 | WPF_M3 | WPF_HC | WPF_SNIPER | WPF_DUAL | WPF_KNIFE | WPF_GRENADE itm_flags = gi.cvar ("itm_flags", "63", 0); // 63 = ITF_SIL | ITF_SLIP | ITF_BAND | ITF_KEV | ITF_LASER | ITF_HELM matchmode = gi.cvar ("matchmode", "0", CVAR_SERVERINFO | CVAR_LATCH); hearall = gi.cvar ("hearall", "0", 0); // used in matchmode teamdm = gi.cvar ("teamdm", "0", CVAR_LATCH); teamdm_respawn = gi.cvar ("teamdm_respawn", "2", 0); respawn_effect = gi.cvar("respawn_effect", "0", 0); item_respawnmode = gi.cvar ("item_respawnmode", "0", CVAR_LATCH); item_respawn = gi.cvar ("item_respawn", "59", 0); weapon_respawn = gi.cvar ("weapon_respawn", "74", 0); ammo_respawn = gi.cvar ("ammo_respawn", "30", 0); wave_time = gi.cvar("wave_time", "5", 0); mm_forceteamtalk = gi.cvar ("mm_forceteamtalk", "0", 0); mm_adminpwd = gi.cvar ("mm_adminpwd", "0", 0); mm_allowlock = gi.cvar ("mm_allowlock", "1", CVAR_LATCH); mm_pausecount = gi.cvar ("mm_allowcount", "3", CVAR_LATCH); mm_pausetime = gi.cvar ("mm_pausetime", "2", CVAR_LATCH); teams[TEAM1].teamscore = gi.cvar ("t1", "0", CVAR_SERVERINFO); teams[TEAM2].teamscore = gi.cvar ("t2", "0", CVAR_SERVERINFO); teams[TEAM3].teamscore = gi.cvar ("t3", "0", CVAR_SERVERINFO); stats_endmap = gi.cvar("stats_endmap", "1",0); stats_afterround = gi.cvar ("stats_afterround", "0", 0); auto_join = gi.cvar ("auto_join", "0", 0); auto_equip = gi.cvar ("auto_equip", "0", 0); auto_menu = gi.cvar ("auto_menu", "0", 0); eventeams = gi.cvar ("eventeams", "0", 0); use_balancer = gi.cvar ("use_balancer", "0", 0); dm_choose = gi.cvar ("dm_choose", "0", 0); dm_shield = gi.cvar ("dm_shield", "0", 0); use_punch = gi.cvar ("use_punch", "1", 0); //TNG:Freud - new spawning system use_oldspawns = gi.cvar ("use_oldspawns", "0", CVAR_LATCH); //TNG:Freud - ghosts use_ghosts = gi.cvar ("use_ghosts", "0", CVAR_LATCH); radio_max = gi.cvar ("radio_max", "3", 0); radio_time = gi.cvar ("radio_time", "2", 0); radio_ban = gi.cvar ("radio_ban", "15", 0); //SLIC2 radio_repeat_time = gi.cvar ("radio_repeat_time", "1", 0); radio_repeat = gi.cvar ("radio_repeat", "2", 0); unique_weapons = gi.cvar ("weapons", teamplay->value ? "1" : "1", CVAR_SERVERINFO | CVAR_LATCH); // zucc changed teamplay to 1 unique_items = gi.cvar ("items", "1", CVAR_SERVERINFO | CVAR_LATCH); ir = gi.cvar ("ir", "1", 0); knifelimit = gi.cvar ("knifelimit", "40", 0); allweapon = gi.cvar ("allweapon", "0", CVAR_SERVERINFO); allitem = gi.cvar ("allitem", "0", CVAR_SERVERINFO); tgren = gi.cvar ("tgren", "0", CVAR_SERVERINFO); //SLIC2 /*flashgren = gi.cvar ("flashgren", "1", 0); flashradius = gi.cvar ("flashradius", "300", 0); flashtime = gi.cvar ("flashtime", "100", 0);*/ //SLIC2 sv_shelloff = gi.cvar ("shelloff", "1", 0); bholelimit = gi.cvar ("bholelimit", "0", 0); splatlimit = gi.cvar ("splatlimit", "0", 0); darkmatch = gi.cvar ("darkmatch", "0", CVAR_LATCH); // Darkmatch day_cycle = gi.cvar ("day_cycle", "10", 0); // Darkmatch cycle time. use_classic = gi.cvar ("use_classic", "0", CVAR_SERVERINFO); // Reset Spread and Grenade Strength to 1.52 CGF_SFX_InstallGlassSupport (); // william for CGF (glass fx) g_select_empty = gi.cvar ("g_select_empty", "0", CVAR_ARCHIVE); run_pitch = gi.cvar ("run_pitch", "0.002", 0); run_roll = gi.cvar ("run_roll", "0.005", 0); bob_up = gi.cvar ("bob_up", "0.005", 0); bob_pitch = gi.cvar ("bob_pitch", "0.002", 0); bob_roll = gi.cvar ("bob_roll", "0.002", 0); // flood control flood_msgs = gi.cvar ("flood_msgs", "4", 0); flood_persecond = gi.cvar ("flood_persecond", "4", 0); flood_waitdelay = gi.cvar ("flood_waitdelay", "10", 0); // items InitItems (); game.helpmessage1[0] = '\0'; game.helpmessage2[0] = '\0'; // initialize all entities for this game game.maxentities = maxentities->value; g_edicts = gi.TagMalloc (game.maxentities * sizeof (g_edicts[0]), TAG_GAME); globals.edicts = g_edicts; globals.max_edicts = game.maxentities; // initialize all clients for this game game.maxclients = (int)maxclients->value; game.clients = gi.TagMalloc (game.maxclients * sizeof (game.clients[0]), TAG_GAME); globals.num_edicts = game.maxclients + 1; if (ctf->value) CTFInit (); //PG BUND - must be at end of gameinit: vInitGame (); } //========================================================= void WriteField1 (FILE * f, field_t * field, byte * base) { void *p; int len; int index; p = (void *) (base + field->ofs); switch (field->type) { case F_INT: case F_FLOAT: case F_ANGLEHACK: case F_VECTOR: case F_IGNORE: break; case F_LSTRING: case F_GSTRING: if (*(char **) p) len = strlen (*(char **) p) + 1; else len = 0; *(int *) p = len; break; case F_EDICT: if (*(edict_t **) p == NULL) index = -1; else index = *(edict_t **) p - g_edicts; *(int *) p = index; break; case F_CLIENT: if (*(gclient_t **) p == NULL) index = -1; else index = *(gclient_t **) p - game.clients; *(int *) p = index; break; case F_ITEM: if (*(edict_t **) p == NULL) index = -1; else index = *(gitem_t **) p - itemlist; *(int *) p = index; break; default: gi.error ("WriteEdict: unknown field type"); } } void WriteField2 (FILE * f, field_t * field, byte * base) { int len; void *p; p = (void *) (base + field->ofs); switch (field->type) { case F_LSTRING: case F_GSTRING: if (*(char **) p) { len = strlen (*(char **) p) + 1; fwrite (*(char **) p, len, 1, f); } break; // AQ:TNG JBravo fixing Compiler warning. Im not entirely sure here... default: return; // End Compiler warning fix } } void ReadField (FILE * f, field_t * field, byte * base) { void *p; int len; int index; p = (void *) (base + field->ofs); switch (field->type) { case F_INT: case F_FLOAT: case F_ANGLEHACK: case F_VECTOR: case F_IGNORE: break; case F_LSTRING: len = *(int *) p; if (!len) *(char **) p = NULL; else { *(char **) p = gi.TagMalloc (len, TAG_LEVEL); fread (*(char **) p, len, 1, f); } break; case F_GSTRING: len = *(int *) p; if (!len) *(char **) p = NULL; else { *(char **) p = gi.TagMalloc (len, TAG_GAME); fread (*(char **) p, len, 1, f); } break; case F_EDICT: index = *(int *) p; if (index == -1) *(edict_t **) p = NULL; else *(edict_t **) p = &g_edicts[index]; break; case F_CLIENT: index = *(int *) p; if (index == -1) *(gclient_t **) p = NULL; else *(gclient_t **) p = &game.clients[index]; break; case F_ITEM: index = *(int *) p; if (index == -1) *(gitem_t **) p = NULL; else *(gitem_t **) p = &itemlist[index]; break; default: gi.error ("ReadEdict: unknown field type"); } } //========================================================= /* ============== WriteClient All pointer variables (except function pointers) must be handled specially. ============== */ void WriteClient (FILE * f, gclient_t * client) { field_t *field; gclient_t temp; // all of the ints, floats, and vectors stay as they are temp = *client; // change the pointers to lengths or indexes for (field = clientfields; field->name; field++) { WriteField1 (f, field, (byte *) & temp); } // write the block fwrite (&temp, sizeof (temp), 1, f); // now write any allocated data following the edict for (field = clientfields; field->name; field++) { WriteField2 (f, field, (byte *) client); } } /* ============== ReadClient All pointer variables (except function pointers) must be handled specially. ============== */ void ReadClient (FILE * f, gclient_t * client) { field_t *field; fread (client, sizeof (*client), 1, f); for (field = clientfields; field->name; field++) { ReadField (f, field, (byte *) client); } } /* ============ WriteGame This will be called whenever the game goes to a new level, and when the user explicitly saves the game. Game information include cross level data, like multi level triggers, help computer info, and all client states. A single player death will automatically restore from the last save position. ============ */ void WriteGame (char *filename, qboolean autosave) { FILE *f; int i; char str[16]; if (!autosave) SaveClientData (); f = fopen (filename, "wb"); if (!f) gi.error ("Couldn't open %s", filename); memset (str, 0, sizeof (str)); strcpy (str, __DATE__); fwrite (str, sizeof (str), 1, f); game.autosaved = autosave; fwrite (&game, sizeof (game), 1, f); game.autosaved = false; for (i = 0; i < game.maxclients; i++) WriteClient (f, &game.clients[i]); fclose (f); } void ReadGame (char *filename) { FILE *f; int i; char str[16]; gi.FreeTags (TAG_GAME); f = fopen (filename, "rb"); if (!f) gi.error ("Couldn't open %s", filename); fread (str, sizeof (str), 1, f); if (strcmp (str, __DATE__)) { fclose (f); gi.error ("Savegame from an older version.\n"); } g_edicts = gi.TagMalloc (game.maxentities * sizeof (g_edicts[0]), TAG_GAME); globals.edicts = g_edicts; fread (&game, sizeof (game), 1, f); game.clients = gi.TagMalloc (game.maxclients * sizeof (game.clients[0]), TAG_GAME); for (i = 0; i < game.maxclients; i++) ReadClient (f, &game.clients[i]); fclose (f); } //========================================================== /* ============== WriteEdict All pointer variables (except function pointers) must be handled specially. ============== */ void WriteEdict (FILE * f, edict_t * ent) { field_t *field; edict_t temp; // all of the ints, floats, and vectors stay as they are temp = *ent; // change the pointers to lengths or indexes for (field = savefields; field->name; field++) { WriteField1 (f, field, (byte *) & temp); } // write the block fwrite (&temp, sizeof (temp), 1, f); // now write any allocated data following the edict for (field = savefields; field->name; field++) { WriteField2 (f, field, (byte *) ent); } } /* ============== WriteLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ void WriteLevelLocals (FILE * f) { field_t *field; level_locals_t temp; // all of the ints, floats, and vectors stay as they are temp = level; // change the pointers to lengths or indexes for (field = levelfields; field->name; field++) { WriteField1 (f, field, (byte *) & temp); } // write the block fwrite (&temp, sizeof (temp), 1, f); // now write any allocated data following the edict for (field = levelfields; field->name; field++) { WriteField2 (f, field, (byte *) & level); } } /* ============== ReadEdict All pointer variables (except function pointers) must be handled specially. ============== */ void ReadEdict (FILE * f, edict_t * ent) { field_t *field; fread (ent, sizeof (*ent), 1, f); for (field = savefields; field->name; field++) { ReadField (f, field, (byte *) ent); } } /* ============== ReadLevelLocals All pointer variables (except function pointers) must be handled specially. ============== */ void ReadLevelLocals (FILE * f) { field_t *field; fread (&level, sizeof (level), 1, f); for (field = levelfields; field->name; field++) { ReadField (f, field, (byte *) & level); } } /* ================= WriteLevel ================= */ void WriteLevel (char *filename) { int i; edict_t *ent; FILE *f; void *base; f = fopen (filename, "wb"); if (!f) gi.error ("Couldn't open %s", filename); // write out edict size for checking i = sizeof (edict_t); fwrite (&i, sizeof (i), 1, f); // write out a function pointer for checking base = (void *) InitGame; fwrite (&base, sizeof (base), 1, f); // write out level_locals_t WriteLevelLocals (f); // write out all the entities for (i = 0; i < globals.num_edicts; i++) { ent = &g_edicts[i]; if (!ent->inuse) continue; fwrite (&i, sizeof (i), 1, f); WriteEdict (f, ent); } i = -1; fwrite (&i, sizeof (i), 1, f); fclose (f); } /* ================= ReadLevel SpawnEntities will already have been called on the level the same way it was when the level was saved. That is necessary to get the baselines set up identically. The server will have cleared all of the world links before calling ReadLevel. No clients are connected yet. ================= */ void ReadLevel (char *filename) { int entnum; FILE *f; int i; void *base; edict_t *ent; f = fopen (filename, "rb"); if (!f) gi.error ("Couldn't open %s", filename); // free any dynamic memory allocated by loading the level // base state gi.FreeTags (TAG_LEVEL); // wipe all the entities memset (g_edicts, 0, game.maxentities * sizeof (g_edicts[0])); globals.num_edicts = maxclients->value + 1; // check edict size fread (&i, sizeof (i), 1, f); if (i != sizeof (edict_t)) { fclose (f); gi.error ("ReadLevel: mismatched edict size"); } // check function pointer base address fread (&base, sizeof (base), 1, f); if (base != (void *) InitGame) { fclose (f); gi.error ("ReadLevel: function pointers have moved"); } // load the level locals ReadLevelLocals (f); // load all the entities while (1) { if (fread (&entnum, sizeof (entnum), 1, f) != 1) { fclose (f); gi.error ("ReadLevel: failed to read entnum"); } if (entnum == -1) break; if (entnum >= globals.num_edicts) globals.num_edicts = entnum + 1; ent = &g_edicts[entnum]; ReadEdict (f, ent); // let the server rebuild world links for this ent memset (&ent->area, 0, sizeof (ent->area)); gi.linkentity (ent); } fclose (f); // mark all clients as unconnected for (i = 0; i < maxclients->value; i++) { ent = &g_edicts[i + 1]; ent->client = game.clients + i; ent->client->pers.connected = false; } // do any load time things at this point for (i = 0; i < globals.num_edicts; i++) { ent = &g_edicts[i]; if (!ent->inuse) continue; // fire any cross-level triggers if (ent->classname && strcmp (ent->classname, "target_crosslevel_target") == 0) ent->nextthink = level.time + ent->delay; } }
545
./aq2-tng/source/a_xcmds.c
//----------------------------------------------------------------------------- // PG BUND // a_xcmds.c // // contains all new non standard command functions // // $Id: a_xcmds.c,v 1.15 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: a_xcmds.c,v $ // Revision 1.15 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.14 2004/01/18 11:20:14 igor_rock // added flashgrenades // // Revision 1.13 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.12 2002/03/26 21:49:01 ra // Bufferoverflow fixes // // Revision 1.11 2001/11/08 20:56:24 igor_rock // - changed some things related to wp_flags // - corrected use_punch bug when player only has an empty weapon left // // Revision 1.10 2001/11/08 13:22:18 igor_rock // added missing parenthises (use_punch didn't function correct) // // Revision 1.9 2001/11/03 17:21:57 deathwatch // Fixed something in the time command, removed the .. message from the voice command, fixed the vote spamming with mapvote, removed addpoint command (old pb command that wasnt being used). Some cleaning up of the source at a few points. // // Revision 1.8 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.7 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.6 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.5 2001/07/13 00:34:52 slicerdw // Adjusted Punch command // // Revision 1.4 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.3.2.2 2001/05/31 06:47:51 igor_rock // - removed crash bug with non exisitng flag files // - added new commands "setflag1", "setflag2" and "saveflags" to create // .flg files // // Revision 1.3.2.1 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.3 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.2 2001/05/11 12:21:18 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.1.1.1 2001/05/06 17:25:16 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" //AQ2:TNG - Slicer Old Location support //loccube_t *setcube = NULL; //AQ2:TNG End // void _Cmd_Rules_f (edict_t * self, char *argument) { char section[32], mbuf[1024], *p, buf[30][INI_STR_LEN]; int i, j = 0; ini_t ini; strcpy (mbuf, "\n"); if (*argument) Q_strncpyz(section, argument, sizeof(section)); else strcpy (section, "main"); if (OpenIniFile (GAMEVERSION "/prules.ini", &ini)) { i = ReadIniSection (&ini, section, buf, 30); while (j < i) { p = buf[j++]; if (*p == '.') p++; Q_strncatz(mbuf, p, sizeof(mbuf)); Q_strncatz(mbuf, "\n", sizeof(mbuf)); } CloseIniFile (&ini); } if (!j) gi.cprintf (self, PRINT_MEDIUM, "No rules on %s available\n", section); else gi.cprintf (self, PRINT_MEDIUM, "%s", mbuf); } void Cmd_Rules_f (edict_t * self) { char *s; s = gi.args (); _Cmd_Rules_f (self, s); } // void Cmd_Menu_f (edict_t * self) { char *s; s = gi.args (); vShowMenu (self, s); } // void Cmd_Punch_f (edict_t * self) { if ((!use_punch->value) || (self->deadflag == DEAD_DEAD) || (self->solid == SOLID_NOT) || (self->client->resp.sniper_mode != SNIPER_1X) || ((self->client->weaponstate != WEAPON_READY) && (self->client->weaponstate != WEAPON_END_MAG)) ) return; // animation moved to punch_attack() in a_xgame.c // punch_attack is now called in ClientThink after evaluation punch_desired // for "no punch when firing" stuff - TempFile if (level.framenum > (self->client->resp.fire_time + PUNCH_DELAY)) { self->client->resp.fire_time = level.framenum; // you aren't Bruce Lee! :) self->client->resp.punch_desired = true; } } /* //Adds a point with name to location file - cheats must be enabled! void Cmd_Addpoint_f (edict_t * self) { gi.cprintf (self, PRINT_MEDIUM, "\nLocation point feature was dropped in 1.20 and\n" "replaced by location area cubes.\nSee readme.txt for details.\n"); //FILE *pntlist; char *s, buf[1024]; s = gi.args(); if (!*s) { gi.cprintf(self, PRINT_MEDIUM, "\nCommand needs argument, use addpoint <description>.\n"); return; } sprintf(buf, "%s/maps/%s%s", GAMEVERSION, level.mapname, PG_LOCEXT); pntlist = fopen(buf, "a"); if (pntlist == NULL) { gi.cprintf(self, PRINT_MEDIUM, "\nError accessing loc file %s.\n", buf); return; } sprintf(buf, "%.2f %.2f %.2f %s\n", self->s.origin[0], self->s.origin[1], self->s.origin[2], s); fputs(buf, pntlist); fclose(pntlist); gi.cprintf(self, PRINT_MEDIUM, "\nPoint added.\n"); } */ //Plays a sound file void Cmd_Voice_f (edict_t * self) { char *s; char fullpath[MAX_QPATH]; s = gi.args (); //check if no sound is given if (!*s) { gi.cprintf (self, PRINT_MEDIUM, "\nCommand needs argument, use voice <soundfile.wav>.\n"); return; } if (strlen (s) > 32) { gi.cprintf (self, PRINT_MEDIUM, "\nArgument is too long. Maximum length is 32 characters.\n"); return; } // AQ2:TNG Disabled this message: why? -M if (strstr (s, "..")) { gi.cprintf (self, PRINT_MEDIUM, "\nArgument must not contain \"..\".\n"); return; } //check if player is dead if (self->deadflag == DEAD_DEAD || self->solid == SOLID_NOT) return; strcpy (fullpath, PG_SNDPATH); strcat (fullpath, s); // SLIC2 Taking this out. /*if (radio_repeat->value) { if ((d = CheckForRepeat (self, s)) == false) return; }*/ if (radio_max->value) { if (CheckForFlood (self)== false) return; } // AQ2:TNG Deathwatch - This should be IDLE not NORM gi.sound (self, CHAN_VOICE, gi.soundindex (fullpath), 1, ATTN_IDLE, 0); // AQ2:TNG END } //AQ2:TNG SLicer - Old location support // TempFile - BEGIN /* void Cmd_BeginCube_f (edict_t * self) { if (setcube) { gi.cprintf (self, PRINT_MEDIUM, "There is already a cube allocated at 0x%p.\n", (void *) setcube); return; } setcube = gi.TagMalloc (sizeof (loccube_t), TAG_GAME); if (!setcube) return; gi.cprintf (self, PRINT_MEDIUM, "New cube successfully allocated at 0x%p.\n", (void *) setcube); gi.cprintf (self, PRINT_MEDIUM, "Please set lower left and upper right corner.\n"); } void Cmd_SetCubeLL_f (edict_t * self) { if (!setcube) { gi.cprintf (self, PRINT_MEDIUM, "Please allocate a cube first by executing BeginCube.\n"); return; } memcpy (setcube->lowerleft, self->s.origin, sizeof (vec3_t)); gi.cprintf (self, PRINT_MEDIUM, "Lower left has been set to <%.2f %.2f %.2f>.\n", setcube->lowerleft[0], setcube->lowerleft[1], setcube->lowerleft[2]); } void Cmd_SetCubeUR_f (edict_t * self) { if (!setcube) { gi.cprintf (self, PRINT_MEDIUM, "Please allocate a cube first by executing BeginCube.\n"); return; } memcpy (setcube->upperright, self->s.origin, sizeof (vec3_t)); gi.cprintf (self, PRINT_HIGH, "Upper right has been set to <%.2f %.2f %.2f>.\n", setcube->upperright[0], setcube->upperright[1], setcube->upperright[2]); } void Cmd_AbortCube_f (edict_t * self) { if (!setcube) { gi.cprintf (self, PRINT_MEDIUM, "No cube to deallocate.\n"); return; } gi.TagFree (setcube); gi.cprintf (self, PRINT_MEDIUM, "Cube at 0x%p successfully deallocated.\n", (void *) setcube); setcube = NULL; } //Adds a cube with name to location file - cheats must be enabled! void Cmd_AddCube_f (edict_t * self) { FILE *pntlist; char *s, buf[1024]; if (!setcube) { gi.cprintf (self, PRINT_MEDIUM, "\nPlease allocate a cube first by executing BeginCube.\n"); return; } if (!setcube->lowerleft[0] || !setcube->lowerleft[1] || !setcube->lowerleft[2] || !setcube->upperright[0] || !setcube->upperright[1] || !setcube->upperright[2]) { gi.cprintf (self, PRINT_MEDIUM, "\nPlease set cube corners first using SetCubeLL and SetCubeUR.\n"); return; } FixCubeData (setcube); s = gi.args (); strcpy (setcube->desc, s); if (!*s) { gi.cprintf (self, PRINT_MEDIUM, "\nCommand needs argument, use addcube <description>.\n"); return; } sprintf (buf, "%s/location/%s%s", GAMEVERSION, level.mapname, PG_LOCEXTEX); pntlist = fopen (buf, "a"); if (pntlist == NULL) { gi.cprintf (self, PRINT_MEDIUM, "\nError accessing adf file %s.\n", buf); return; } sprintf (buf, "<%.2f %.2f %.2f> <%.2f %.2f %.2f> %s\n", setcube->lowerleft[0], setcube->lowerleft[1], setcube->lowerleft[2], setcube->upperright[0], setcube->upperright[1], setcube->upperright[2], setcube->desc); fputs (buf, pntlist); fclose (pntlist); memcpy (&mapdescex[num_loccubes], setcube, sizeof (*setcube)); num_loccubes++; gi.TagFree (setcube); setcube = NULL; gi.cprintf (self, PRINT_MEDIUM, "\nCube added.\n"); } void Cmd_PrintCubeState_f (edict_t * self) { if (!setcube) { gi.cprintf (self, PRINT_MEDIUM, "\nPlease allocate a cube first by executing BeginCube.\n"); return; } gi.cprintf (self, PRINT_MEDIUM, "\nTemporary cube allocated at %p.\nLower left corner: " "<%.2f %.2f %.2f>\nUpper right corner: <%.2f %.2f %.2f>\n", (void *) setcube, setcube->lowerleft[0], setcube->lowerleft[1], setcube->lowerleft[2], setcube->upperright[1], setcube->upperright[2], setcube->upperright[2]); } // TempFile - END */ //AQ2:TNG END // Variables for new flags static char flagpos1[64] = { 0 }; static char flagpos2[64] = { 0 }; //sets red flag position - cheats must be enabled! void Cmd_SetFlag1_f (edict_t * self) { Com_sprintf (flagpos1, sizeof(flagpos1), "<%.2f %.2f %.2f>", self->s.origin[0], self->s.origin[1], self->s.origin[2]); gi.cprintf (self, PRINT_MEDIUM, "\nRed Flag added at %s.\n", flagpos1); } //sets blue flag position - cheats must be enabled! void Cmd_SetFlag2_f (edict_t * self) { Com_sprintf (flagpos2, sizeof(flagpos2), "<%.2f %.2f %.2f>", self->s.origin[0], self->s.origin[1], self->s.origin[2]); gi.cprintf (self, PRINT_MEDIUM, "\nBlue Flag added at %s.\n", flagpos2); } //Save flag definition file - cheats must be enabled! void Cmd_SaveFlags_f (edict_t * self) { FILE *fp; char buf[128]; if (!(flagpos1[0] && flagpos2[0])) { gi.cprintf (self, PRINT_MEDIUM, "You only can save flag positions when you've already set them\n"); return; } sprintf (buf, "%s/tng/%s.flg", GAMEVERSION, level.mapname); fp = fopen (buf, "w"); if (fp == NULL) { gi.cprintf (self, PRINT_MEDIUM, "\nError accessing flg file %s.\n", buf); return; } sprintf (buf, "# %s\n", level.mapname); fputs (buf, fp); sprintf (buf, "%s\n", flagpos1); fputs (buf, fp); sprintf (buf, "%s\n", flagpos2); fputs (buf, fp); fclose (fp); flagpos1[0] = 0; flagpos2[0] = 0; gi.cprintf (self, PRINT_MEDIUM, "\nFlag File saved.\n"); } //SLIC2 /* void Cmd_FlashGrenade_f(edict_t *ent) { if (ent->client->grenadeType == GRENADE_NORMAL) { gi.cprintf(ent, PRINT_HIGH, "Flash grenades selected.\n"); ent->client->grenadeType = GRENADE_FLASH; } else { gi.cprintf(ent, PRINT_HIGH, "Standard grenades selected.\n"); ent->client->grenadeType = GRENADE_NORMAL; } }*/
546
./aq2-tng/source/g_cmds.c
//----------------------------------------------------------------------------- // g_cmds.c // // $Id: g_cmds.c,v 1.60 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: g_cmds.c,v $ // Revision 1.60 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.59 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.58 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.57 2002/09/04 11:23:09 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.56 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.55 2002/03/26 21:49:01 ra // Bufferoverflow fixes // // Revision 1.54 2002/03/25 18:32:11 freud // I'm being too productive.. New ghost command needs testing. // // Revision 1.53 2002/02/19 09:32:47 freud // Removed PING PONGs from CVS, not fit for release. // // Revision 1.52 2002/02/18 20:21:36 freud // Added PING PONG mechanism for timely disconnection of clients. This is // based on a similar scheme as the scheme used by IRC. The client has // cvar ping_timeout seconds to reply or will be disconnected. // // Revision 1.51 2002/02/13 12:13:00 deathwatch // INVDROP Weaponfarming fix // // Revision 1.50 2002/02/01 12:54:08 ra // messin with stat_mode // // Revision 1.49 2002/01/24 02:55:58 ra // Fixed the mm_forceteamtalk 2 bug. // // Revision 1.48 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.47 2002/01/24 01:40:40 deathwatch // Freud's AutoRecord // // Revision 1.46 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.44 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.43 2001/11/29 16:04:29 deathwatch // Fixed the playerlist command // // Revision 1.42 2001/11/16 22:45:58 deathwatch // Fixed %me again // // Revision 1.41 2001/11/09 23:58:12 deathwatch // Fiixed the %me command to display '[DEAD]' properly // Added the resetting of the teamXscore cvars at the exitlevel function where the team scores are reset as well. (not sure if that is correct) // // Revision 1.40 2001/11/03 20:10:18 slicerdw // Removed the if that prevented people from talking at the end // // Revision 1.39 2001/11/03 17:43:20 deathwatch // Fixed matchadmin - it should only work when in matchmode and not use say when typing it normally in any other mode (security issue for dumb ppl typing matchadmin password on a server without matchmode) // // Revision 1.38 2001/11/03 17:21:57 deathwatch // Fixed something in the time command, removed the .. message from the voice command, fixed the vote spamming with mapvote, removed addpoint command (old pb command that wasnt being used). Some cleaning up of the source at a few points. // // Revision 1.37 2001/10/18 12:55:35 deathwatch // Added roundtimeleft // // Revision 1.36 2001/09/30 03:09:34 ra // Removed new stats at end of rounds and created a new command to // do the same functionality. Command is called "time" // // Revision 1.35 2001/09/28 22:00:46 deathwatch // changed pheer to ph34rs in the kill denying statement // // Revision 1.34 2001/09/28 21:43:21 deathwatch // Fixed a but caused due to the reformatting of the source making the say stuff not working in non-matchmode modes // // Revision 1.33 2001/09/28 14:20:25 slicerdw // Few tweaks.. // // Revision 1.32 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.31 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.30 2001/08/20 00:41:15 slicerdw // Added a new scoreboard for Teamplay with stats ( when map ends ) // // Revision 1.29 2001/08/18 18:45:19 deathwatch // Edited the Flashlight movement code to the Lasersight's movement code, its probably better // and I added checks for darkmatch/being dead/being a spectator for its use // // Revision 1.28 2001/08/18 17:14:04 deathwatch // Flashlight Added (not done yet, needs to prevent DEAD ppl from using it, // the glow should be white and a bit smaller if possible and the daiper needs // to be gone. Also, it should only work in 'darkmatch' I guess and it should // make a sound when you turn it on/off. // // Revision 1.27 2001/08/17 21:31:37 deathwatch // Added support for stats // // Revision 1.26 2001/08/08 12:42:22 slicerdw // Ctf Should finnaly be fixed now, lets hope so // // Revision 1.25 2001/07/30 16:07:25 igor_rock // added correct gender to "pheer" message // // Revision 1.24 2001/07/28 19:30:05 deathwatch // Fixed the choose command (replaced weapon for item when it was working with items) // and fixed some tabs on other documents to make it more readable // // Revision 1.23 2001/07/20 11:56:04 slicerdw // Added a check for the players spawning during countdown on ctf ( lets hope it works ) // // Revision 1.21 2001/06/25 12:39:38 slicerdw // Cleaning up something i left behind.. // // Revision 1.20 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.19 2001/06/22 16:34:05 slicerdw // Finished Matchmode Basics, now with admins, Say command tweaked... // // Revision 1.18 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.15 2001/06/06 18:57:14 slicerdw // Some tweaks on Ctf and related things // // Revision 1.12 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.11 2001/06/01 08:25:42 igor_rock // Merged New_Ctf-1_0 into main branch - this time hopefuly the whole one... // // Revision 1.10 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.9 2001/05/20 15:00:19 slicerdw // Some minor fixes and changings on Video Checking system // // Revision 1.8.2.4 2001/05/31 06:47:51 igor_rock // - removed crash bug with non exisitng flag files // - added new commands "setflag1", "setflag2" and "saveflags" to create // .flg files // // Revision 1.8.2.3 2001/05/27 13:33:37 igor_rock // added flag drop command ("drop flag") // // Revision 1.8.2.2 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.8.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.8 2001/05/13 14:55:11 igor_rock // corrected the lens command which was commented out in error // // Revision 1.7 2001/05/12 21:19:51 ra // // // Added punishkills. // // Revision 1.6 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.5 2001/05/11 12:21:19 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.4 2001/05/07 21:18:34 slicerdw // Added Video Checking System // // Revision 1.3 2001/05/07 02:05:36 ra // // // Added tkok command to forgive teamkills. // // Revision 1.2 2001/05/07 01:38:51 ra // // // Added fixes for Ammo and Weaponsfarming. // // Revision 1.1.1.1 2001/05/06 17:30:36 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" char *ClientTeam (edict_t * ent) { char *p; static char value[128]; value[0] = 0; if (!ent->client) return value; Q_strncpyz(value, Info_ValueForKey (ent->client->pers.userinfo, "skin"), sizeof(value)); p = strchr (value, '/'); if (!p) return value; if ((int) (dmflags->value) & DF_MODELTEAMS) { *p = 0; return value; } // if ((int)(dmflags->value) & DF_SKINTEAMS) return ++p; } qboolean OnSameTeam (edict_t * ent1, edict_t * ent2) { char ent1Team[128], ent2Team[128]; //FIREBLADE if (!ent1->client || !ent2->client) return false; if (teamplay->value) return ent1->client->resp.team == ent2->client->resp.team; //FIREBLADE if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return false; Q_strncpyz (ent1Team, ClientTeam(ent1), sizeof(ent1Team)); Q_strncpyz (ent2Team, ClientTeam(ent2), sizeof(ent2Team)); if (strcmp (ent1Team, ent2Team) == 0) return true; return false; } void SelectNextItem (edict_t * ent, int itflags) { gclient_t *cl; int i, index; gitem_t *it; cl = ent->client; //FIREBLADE if (cl->menu) { PMenu_Next (ent); return; } //FIREBLADE if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; // scan for the next valid one for (i = 1; i <= MAX_ITEMS; i++) { index = (cl->pers.selected_item + i) % MAX_ITEMS; if (!cl->pers.inventory[index]) continue; it = &itemlist[index]; if (!it->use) continue; if (!(it->flags & itflags)) continue; cl->pers.selected_item = index; return; } cl->pers.selected_item = -1; } void SelectPrevItem (edict_t * ent, int itflags) { gclient_t *cl; int i, index; gitem_t *it; cl = ent->client; //FIREBLADE if (cl->menu) { PMenu_Prev (ent); return; } //FIREBLADE if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; // scan for the next valid one for (i = 1; i <= MAX_ITEMS; i++) { index = (cl->pers.selected_item + MAX_ITEMS - i) % MAX_ITEMS; if (!cl->pers.inventory[index]) continue; it = &itemlist[index]; if (!it->use) continue; if (!(it->flags & itflags)) continue; cl->pers.selected_item = index; return; } cl->pers.selected_item = -1; } void ValidateSelectedItem (edict_t * ent) { gclient_t *cl; cl = ent->client; if (cl->pers.inventory[cl->pers.selected_item]) return; // valid SelectNextItem (ent, -1); } //================================================================================= /* ================== Cmd_Give_f Give items to a client ================== */ void Cmd_Give_f (edict_t * ent) { char *name; char fixedname[32]; gitem_t *it; int index; int i; qboolean give_all; edict_t *it_ent; edict_t etemp; if (deathmatch->value && !sv_cheats->value) { gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n"); return; } if (ent->solid == SOLID_NOT) { gi.cprintf (ent, PRINT_HIGH, "This command can't be used by spectators.\n"); return; } Q_strncpyz(fixedname, gi.args (), sizeof(fixedname)); name = fixedname; // name = gi.args (); if (Q_stricmp (name, "all") == 0) give_all = true; else give_all = false; if (Q_stricmp (gi.argv (1), "health") == 0) { /* if (gi.argc() == 3) ent->health = atoi(gi.argv(2)); else ent->health = ent->max_health; if (!give_all) */ return; } if (give_all || Q_stricmp (name, "weapons") == 0) { for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_WEAPON)) continue; ent->client->pers.inventory[i] += 1; } if (!give_all) return; } if (give_all || Q_stricmp (name, "items") == 0) { for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_ITEM)) continue; etemp.item = it; if (ent->client->unique_item_total >= unique_items->value) ent->client->unique_item_total = unique_items->value - 1; Pickup_Special (&etemp, ent); } if (!give_all) return; } if (give_all || Q_stricmp (name, "ammo") == 0) { ent->client->mk23_rds = ent->client->mk23_max; ent->client->dual_rds = ent->client->dual_max; ent->client->mp5_rds = ent->client->mp5_max; ent->client->m4_rds = ent->client->m4_max; ent->client->shot_rds = ent->client->shot_max; ent->client->sniper_rds = ent->client->sniper_max; ent->client->cannon_rds = ent->client->cannon_max; for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_AMMO)) continue; Add_Ammo (ent, it, 1000); } if (!give_all) return; } if (Q_stricmp (name, "armor") == 0) { /* gitem_armor_t *info; it = FindItem("Jacket Armor"); ent->client->pers.inventory[ITEM_INDEX(it)] = 0; it = FindItem("Combat Armor"); ent->client->pers.inventory[ITEM_INDEX(it)] = 0; it = FindItem("Body Armor"); info = (gitem_armor_t *)it->info; ent->client->pers.inventory[ITEM_INDEX(it)] = info->max_count; if (!give_all) */ return; } if (Q_stricmp (name, "Power Shield") == 0) { /*it = FindItem("Power Shield"); it_ent = G_Spawn(); it_ent->classname = it->classname; SpawnItem (it_ent, it); Touch_Item (it_ent, ent, NULL, NULL); if (it_ent->inuse) G_FreeEdict(it_ent); if (!give_all) */ return; } /*if (give_all) { for (i=0 ; i<game.num_items ; i++) { it = itemlist + i; if (!it->pickup) continue; if (it->flags & (IT_ARMOR|IT_WEAPON|IT_AMMO)) continue; ent->client->pers.inventory[i] = 1; } return; } */ if (give_all) return; it = FindItem (name); if (!it) { Q_strncpyz(fixedname, gi.argv (1), sizeof(fixedname)); name = fixedname; // name = gi.argv (1); it = FindItem (name); if (!it) { gi.dprintf ("unknown item\n"); return; } } if (!(it->flags & (IT_AMMO|IT_WEAPON|IT_ITEM))) return; if (!it->pickup) { gi.dprintf ("non-pickup item\n"); return; } index = ITEM_INDEX (it); if (it->flags & IT_AMMO) { /* if (gi.argc() == 5) ent->client->pers.inventory[index] = atoi(gi.argv(4)); else if ( (gi.argc() == 4) && !(Q_stricmp(it->pickup_name, "12 Gauge Shells")) ) ent->client->pers.inventory[index] = atoi(gi.argv(3)); else */ ent->client->pers.inventory[index] += it->quantity; } else if (it->flags & IT_ITEM) { etemp.item = it; if (ent->client->unique_item_total >= unique_items->value) ent->client->unique_item_total = unique_items->value - 1; Pickup_Special (&etemp, ent); } else { it_ent = G_Spawn (); it_ent->classname = it->classname; it_ent->typeNum = it->typeNum; SpawnItem (it_ent, it); Touch_Item (it_ent, ent, NULL, NULL); if (it_ent->inuse) G_FreeEdict (it_ent); } } /* ================== Cmd_God_f Sets client to godmode argv(0) god ================== */ void Cmd_God_f (edict_t * ent) { char *msg; if (deathmatch->value && !sv_cheats->value) { gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n"); return; } ent->flags ^= FL_GODMODE; if (!(ent->flags & FL_GODMODE)) msg = "godmode OFF\n"; else msg = "godmode ON\n"; gi.cprintf (ent, PRINT_HIGH, msg); } /* ================== Cmd_Notarget_f Sets client to notarget argv(0) notarget ================== */ void Cmd_Notarget_f (edict_t * ent) { char *msg; if (deathmatch->value && !sv_cheats->value) { gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n"); return; } ent->flags ^= FL_NOTARGET; if (!(ent->flags & FL_NOTARGET)) msg = "notarget OFF\n"; else msg = "notarget ON\n"; gi.cprintf (ent, PRINT_HIGH, msg); } /* ================== Cmd_Noclip_f argv(0) noclip ================== */ void Cmd_Noclip_f (edict_t * ent) { char *msg; if (deathmatch->value && !sv_cheats->value) { gi.cprintf (ent, PRINT_HIGH, "You must run the server with '+set cheats 1' to enable this command.\n"); return; } if (ent->movetype == MOVETYPE_NOCLIP) { ent->movetype = MOVETYPE_WALK; msg = "noclip OFF\n"; } else { ent->movetype = MOVETYPE_NOCLIP; msg = "noclip ON\n"; } gi.cprintf (ent, PRINT_HIGH, msg); } /* ================== Cmd_Use_f Use an inventory item ================== */ void Cmd_Use_f (edict_t * ent) { gitem_t *it; char *s; s = gi.args (); //zucc - check for "special" if (Q_stricmp (s, "special") == 0) { ReadySpecialWeapon (ent); return; } //zucc - alias names if (!Q_stricmp (s, "blaster") || !Q_stricmp (s, "mark 23 pistol")) s = MK23_NAME; else if (!Q_stricmp (s, "A 2nd pistol") || !Q_stricmp (s, "railgun")) s = DUAL_NAME; else if (!Q_stricmp (s, "shotgun")) s = M3_NAME; else if (!Q_stricmp (s, "machinegun")) s = HC_NAME; else if (!Q_stricmp (s, "super shotgun")) s = MP5_NAME; else if (!Q_stricmp (s, "chaingun")) s = SNIPER_NAME; else if (!Q_stricmp (s, "bfg10k")) s = KNIFE_NAME; // zucc - let people pull up a knife ready to be thrown else if (!Q_stricmp (s, "throwing combat knife")) { if (ent->client->curr_weap != KNIFE_NUM) { ent->client->resp.knife_mode = 1; } else // switch to throwing mode if a knife is already out { //if(!ent->client->resp.knife_mode) Cmd_New_Weapon_f (ent); } s = KNIFE_NAME; } else if (!Q_stricmp (s, "slashing combat knife")) { if (ent->client->curr_weap != KNIFE_NUM) { ent->client->resp.knife_mode = 0; } else // switch to slashing mode if a knife is already out { //if(ent->client->resp.knife_mode) Cmd_New_Weapon_f (ent); } s = KNIFE_NAME; } else if (!Q_stricmp (s, "grenade launcher")) s = M4_NAME; else if (!Q_stricmp (s, "grenades")) s = GRENADE_NAME; it = FindItem (s); //FIREBLADE if (!it || (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD)) //FIREBLADE { gi.cprintf (ent, PRINT_HIGH, "Unknown item: %s\n", s); // fixed capitalization -FB return; } if (!it->use) { gi.cprintf (ent, PRINT_HIGH, "Item is not usable.\n"); return; } if (!ent->client->pers.inventory[ITEM_INDEX (it)]) { gi.cprintf (ent, PRINT_HIGH, "Out of item: %s\n", s); return; } //TempFile ent->client->autoreloading = false; //TempFile it->use (ent, it); } /* ================== Cmd_Drop_f Drop an inventory item ================== */ void Cmd_Drop_f (edict_t * ent) { int index; gitem_t *it; char *s; if (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD) return; s = gi.args (); //zucc check to see if the string is weapon if (Q_stricmp (s, "weapon") == 0) { DropSpecialWeapon (ent); return; } //zucc now for item if (Q_stricmp (s, "item") == 0) { DropSpecialItem (ent); return; } if (Q_stricmp (s, "flag") == 0) { CTFDrop_Flag (ent, NULL); return; } // AQ:TNG - JBravo fixing ammo clip farming if (ent->client->weaponstate == WEAPON_RELOADING) return; // Ammo clip farming fix end it = FindItem (s); if (!it) { gi.cprintf (ent, PRINT_HIGH, "unknown item: %s\n", s); return; } if (!it->drop) { gi.cprintf (ent, PRINT_HIGH, "Item is not dropable.\n"); return; } index = ITEM_INDEX (it); if (!ent->client->pers.inventory[index]) { gi.cprintf (ent, PRINT_HIGH, "Out of item: %s\n", s); return; } it->drop (ent, it); } /* ================= Cmd_Inven_f ================= */ void Cmd_Inven_f (edict_t * ent) { int i; gclient_t *cl; cl = ent->client; cl->showscores = false; cl->showhelp = false; //FIREBLADE if (ent->client->menu) { PMenu_Close (ent); return; } //FIREBLADE if (cl->showinventory) { cl->showinventory = false; return; } cl->resp.menu_shown = true; //FIREBLADE if (teamdm->value || ctf->value == 2) { if (ent->client->resp.team == NOTEAM) { OpenJoinMenu (ent); return; } } else if (teamplay->value) { cl->resp.menu_shown = true; if (ent->client->resp.team == NOTEAM) OpenJoinMenu (ent); else OpenWeaponMenu (ent); return; } //FIREBLADE if (dm_choose->value) { OpenWeaponMenu (ent); cl->showinventory = false; return; } cl->showinventory = true; gi.WriteByte (svc_inventory); for (i = 0; i < MAX_ITEMS; i++) { gi.WriteShort (cl->pers.inventory[i]); } gi.unicast (ent, true); } /* ================= Cmd_InvUse_f ================= */ void Cmd_InvUse_f (edict_t * ent) { gitem_t *it; //FIREBLADE if (ent->client->menu) { PMenu_Select (ent); return; } //FIREBLADE if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; ValidateSelectedItem (ent); if (ent->client->pers.selected_item == -1) { gi.cprintf (ent, PRINT_HIGH, "No item to use.\n"); return; } it = &itemlist[ent->client->pers.selected_item]; if (!it->use) { gi.cprintf (ent, PRINT_HIGH, "Item is not usable.\n"); return; } it->use (ent, it); } /* ================= Cmd_WeapPrev_f ================= */ void Cmd_WeapPrev_f (edict_t * ent) { gclient_t *cl; int i, index; gitem_t *it; int selected_weapon; if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; cl = ent->client; if (!cl->pers.weapon) return; selected_weapon = ITEM_INDEX (cl->pers.weapon); // scan for the next valid one for (i = 1; i <= MAX_ITEMS; i++) { index = (selected_weapon + i) % MAX_ITEMS; if (!cl->pers.inventory[index]) continue; it = &itemlist[index]; if (!it->use) continue; if (!(it->flags & IT_WEAPON)) continue; it->use (ent, it); if (cl->pers.weapon == it) return; // successful } } /* ================= Cmd_WeapNext_f ================= */ void Cmd_WeapNext_f (edict_t * ent) { gclient_t *cl; int i, index; gitem_t *it; int selected_weapon; if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; cl = ent->client; if (!cl->pers.weapon) return; selected_weapon = ITEM_INDEX (cl->pers.weapon); // scan for the next valid one for (i = 1; i <= MAX_ITEMS; i++) { index = (selected_weapon + MAX_ITEMS - i) % MAX_ITEMS; if (!cl->pers.inventory[index]) continue; it = &itemlist[index]; if (!it->use) continue; if (!(it->flags & IT_WEAPON)) continue; it->use (ent, it); if (cl->pers.weapon == it) return; // successful } } /* ================= Cmd_WeapLast_f ================= */ void Cmd_WeapLast_f (edict_t * ent) { gclient_t *cl; int index; gitem_t *it; if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; cl = ent->client; if (!cl->pers.weapon || !cl->pers.lastweapon) return; index = ITEM_INDEX (cl->pers.lastweapon); if (!cl->pers.inventory[index]) return; it = &itemlist[index]; if (!it->use) return; if (!(it->flags & IT_WEAPON)) return; it->use (ent, it); } /* ================= Cmd_InvDrop_f ================= */ void Cmd_InvDrop_f (edict_t * ent) { gitem_t *it; // TNG: Temp fix for INVDROP weapon farming if(teamplay->value) return; // TNG: End if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; ValidateSelectedItem (ent); if (ent->client->pers.selected_item == -1) { gi.cprintf (ent, PRINT_HIGH, "No item to drop.\n"); return; } it = &itemlist[ent->client->pers.selected_item]; if (!it->drop) { gi.cprintf (ent, PRINT_HIGH, "Item is not dropable.\n"); return; } it->drop (ent, it); } /* ================= Cmd_Kill_f ================= */ void Cmd_Kill_f (edict_t * ent) { //FIREBLADE if (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD) return; //FIREBLADE // AQ:TNG - JBravo adding punishkills if (punishkills->value) { if (ent->client->attacker && ent->client->attacker->client && (ent->client->attacker->client != ent->client)) { char deathmsg[64]; Com_sprintf(deathmsg, sizeof(deathmsg), "%s ph34rs %s so much %s committed suicide! :)\n", ent->client->pers.netname, ent->client->attacker->client->pers.netname, ent->client->resp.radio_gender ? "she" : "he"); PrintDeathMessage(deathmsg, ent); if(team_round_going || !OnSameTeam(ent, ent->client->attacker)) { Add_Frag (ent->client->attacker); Subtract_Frag (ent); ent->client->resp.deaths++; } } } // End punishkills if ((level.time - ent->client->respawn_time) < 5) return; ent->flags &= ~FL_GODMODE; ent->health = 0; meansOfDeath = MOD_SUICIDE; player_die (ent, ent, ent, 100000, vec3_origin); // Forget all this... -FB // // don't even bother waiting for death frames // ent->deadflag = DEAD_DEAD; ////FIREBLADE // if (!teamplay->value) ////FIREBLADE // respawn (ent); } /* ================= Cmd_PutAway_f ================= */ void Cmd_PutAway_f (edict_t * ent) { ent->client->showscores = false; ent->client->showhelp = false; ent->client->showinventory = false; //FIREBLADE if (ent->client->menu) PMenu_Close (ent); //FIREBLADE } int PlayerSort (void const *a, void const *b) { int anum, bnum; anum = *(int *) a; bnum = *(int *) b; anum = game.clients[anum].ps.stats[STAT_FRAGS]; bnum = game.clients[bnum].ps.stats[STAT_FRAGS]; if (anum < bnum) return -1; if (anum > bnum) return 1; return 0; } /* ================= Cmd_Players_f ================= */ void Cmd_Players_f (edict_t * ent) { int i; int count = 0; char small[64]; char large[1024]; int index[256]; for (i = 0; i < maxclients->value; i++) { if (game.clients[i].pers.connected) index[count++] = i; } if (!teamplay->value || !noscore->value) { // sort by frags qsort (index, count, sizeof (index[0]), PlayerSort); } // print information large[0] = 0; for (i = 0; i < count; i++) { if (!teamplay->value || !noscore->value) Com_sprintf (small, sizeof (small), "%3i %s\n", game.clients[index[i]].ps.stats[STAT_FRAGS], game.clients[index[i]].pers.netname); else Com_sprintf (small, sizeof (small), "%s\n", game.clients[index[i]].pers.netname); if (strlen(small) + strlen(large) > sizeof (large) - 20) { // can't print all of them in one packet strcat (large, "...\n"); break; } strcat (large, small); } gi.cprintf (ent, PRINT_HIGH, "%s\n%i players\n", large, count); } /* ================= Cmd_Wave_f ================= */ void Cmd_Wave_f (edict_t * ent) { int i; // can't wave when ducked if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) return; if (ent->client->anim_priority > ANIM_WAVE) return; if(wave_time->value > 0) { if(ent->client->resp.lastWave + ((int)wave_time->value * 10) > level.framenum) return; ent->client->resp.lastWave = level.framenum; } ent->client->anim_priority = ANIM_WAVE; i = atoi (gi.argv (1)); switch (i) { case 0: gi.cprintf (ent, PRINT_HIGH, "flipoff\n"); ent->s.frame = FRAME_flip01 - 1; ent->client->anim_end = FRAME_flip12; break; case 1: gi.cprintf (ent, PRINT_HIGH, "salute\n"); ent->s.frame = FRAME_salute01 - 1; ent->client->anim_end = FRAME_salute11; break; case 2: gi.cprintf (ent, PRINT_HIGH, "taunt\n"); ent->s.frame = FRAME_taunt01 - 1; ent->client->anim_end = FRAME_taunt17; break; case 3: gi.cprintf (ent, PRINT_HIGH, "wave\n"); ent->s.frame = FRAME_wave01 - 1; ent->client->anim_end = FRAME_wave11; break; case 4: default: gi.cprintf (ent, PRINT_HIGH, "point\n"); ent->s.frame = FRAME_point01 - 1; ent->client->anim_end = FRAME_point12; break; } } /* ================== Cmd_Say_f ================== */ void Cmd_Say_f (edict_t * ent, qboolean team, qboolean arg0, qboolean partner_msg) { int j, i, offset_of_text; edict_t *other; char *args, text[256], *s; gclient_t *cl; int meing = 0, isadmin = 0; if (gi.argc() < 2 && !arg0) return; args = gi.args(); if (!sv_crlf->value) { if (strchr(args, '\r') || strchr(args, '\n')) { gi.cprintf (ent, PRINT_HIGH, "No control characters in chat messages!\n"); return; } } //TempFile - BEGIN if (arg0) { if (!Q_stricmp("%me", gi.argv(0))) { meing = 4; if(!args || !*args) return; } } else { if(!args || !*args) return; if (!Q_strnicmp("%me", args, 3)) meing = 4; else if (!Q_strnicmp("%me", args + 1, 3)) meing = 5; if(meing) { if (!*(args+meing-1)) return; if (*(args+meing-1) != ' ') meing = 0; else if(!*(args+meing)) return; } } //TempFile - END if (!teamplay->value) { //FIREBLADE if (!((int)(dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) team = false; } else if (matchmode->value) { if (ent->client->resp.admin) isadmin = 1; if (mm_forceteamtalk->value == 1) { if (!ent->client->resp.captain && !partner_msg && !isadmin) team = true; } else if (mm_forceteamtalk->value == 2) { if (!ent->client->resp.captain && !partner_msg && !isadmin && (TeamsReady() || team_round_going)) team = true; } } if (team) { if (ent->client->resp.team == NOTEAM) { gi.cprintf (ent, PRINT_HIGH, "You're not on a team.\n"); return; } if (!meing) // TempFile Com_sprintf (text, sizeof (text), "%s(%s): ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "[DEAD] " : "", ent->client->pers.netname); //TempFile - BEGIN else Com_sprintf (text, sizeof (text), "(%s%s ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "[DEAD] " : "", ent->client->pers.netname); //TempFile - END } else if (partner_msg) { if (ent->client->resp.radio_partner == NULL) { gi.cprintf (ent, PRINT_HIGH, "You don't have a partner.\n"); return; } if (!meing) //TempFile Com_sprintf (text, sizeof (text), "[%sPARTNER] %s: ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "DEAD " : "", ent->client->pers.netname); //TempFile - BEGIN else Com_sprintf (text, sizeof (text), "%s partner %s ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "[DEAD] " : "", ent->client->pers.netname); //TempFile - END } else { if (!meing) //TempFile { if (isadmin) Com_sprintf (text, sizeof (text), "[ADMIN] %s: ", ent->client->pers.netname); else Com_sprintf (text, sizeof (text), "%s%s: ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "[DEAD] " : "", ent->client->pers.netname); } else Com_sprintf (text, sizeof (text), "%s%s ", (teamplay->value && (ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD)) ? "[DEAD] " : "", ent->client->pers.netname); } //TempFile - END offset_of_text = strlen (text); //FB 5/31/99 if (!meing) //TempFile { if (arg0) { Q_strncatz(text, gi.argv (0), sizeof(text)); if(*args) { Q_strncatz(text, " ", sizeof(text)); Q_strncatz(text, args, sizeof(text)); } } else { if (*args == '"') { args++; args[strlen(args) - 1] = 0; } Q_strncatz(text, args, sizeof(text)); } } else // if meing { if (arg0) { //this one is easy: gi.args() cuts /me off for us! Q_strncatz(text, args, sizeof(text)); } else { // we have to cut off "%me ". args += meing; if (args[strlen(args) - 1] == '"') args[strlen(args) - 1] = 0; Q_strncatz(text, args, sizeof(text)); } if (team) Q_strncatz(text, ")", sizeof(text)); } //TempFile - END // don't let text be too long for malicious reasons if (strlen(text) >= 254) text[254] = 0; if (ent->solid != SOLID_NOT && ent->deadflag != DEAD_DEAD) { s = strchr(text + offset_of_text, '%'); if(s) { // this will parse the % variables, ParseSayText (ent, s, sizeof(text) - (s - text+1) - 2); } } Q_strncatz(text, "\n", sizeof(text)); if (flood_msgs->value) { cl = ent->client; if (realLtime < cl->flood_locktill) { gi.cprintf (ent, PRINT_HIGH, "You can't talk for %d more seconds.\n", (int) (cl->flood_locktill - realLtime)); return; } i = cl->flood_whenhead - flood_msgs->value + 1; if (i < 0) i = (sizeof (cl->flood_when) / sizeof (cl->flood_when[0])) + i; if (cl->flood_when[i] && realLtime - cl->flood_when[i] < flood_persecond->value) { cl->flood_locktill = realLtime + flood_waitdelay->value; gi.cprintf (ent, PRINT_HIGH, "You can't talk for %d seconds.\n", (int) flood_waitdelay->value); return; } cl->flood_whenhead = (cl->flood_whenhead + 1) % (sizeof (cl->flood_when) / sizeof (cl->flood_when[0])); cl->flood_when[cl->flood_whenhead] = realLtime; } if (dedicated->value) { gi.cprintf (NULL, PRINT_CHAT, "%s", text); if ((!team) && (!partner_msg)) { IRC_printf (IRC_T_TALK, "%s", text); } } for (j = 1; j <= game.maxclients; j++) { other = &g_edicts[j]; if (!other->inuse) continue; if (!other->client) continue; if (team) { // if we are the adminent... we might want to hear (if hearall is set) if (!matchmode->value || !hearall->value || !other->client->resp.admin) // hearall isn't set and we aren't adminent if (!OnSameTeam (ent, other)) continue; } if (partner_msg) { if (other != ent->client->resp.radio_partner && other != ent) continue; } //FIREBLADE if (teamplay->value && team_round_going) { if ((ent->solid == SOLID_NOT || ent->deadflag == DEAD_DEAD) && (other->solid != SOLID_NOT && other->deadflag != DEAD_DEAD) && !ctf->value && !teamdm->value) //AQ2:TNG Slicer continue; } //FIREBLADE //PG BUND - BEGIN if (IsInIgnoreList (other, ent)) continue; //PG BUND - END gi.cprintf (other, PRINT_CHAT, "%s", text); } } void Cmd_PlayerList_f (edict_t * ent) { int i; char st[64]; char text[1024] = "\0"; edict_t *e2; // connect time, ping, score, name // Set the lines: for (i = 0, e2 = g_edicts + 1; i < maxclients->value; i++, e2++) { if (!e2->inuse) continue; if(limchasecam->value) Com_sprintf (st, sizeof (st), "%02d:%02d %4d %3d %s\n",(level.framenum - e2->client->resp.enterframe) / 600,((level.framenum - e2->client->resp.enterframe) % 600) / 10, e2->client->ping, e2->client->resp.team, e2->client->pers.netname); // This shouldn't show player's being 'spectators' during games with limchasecam set and/or during matchmode else if (!teamplay->value || !noscore->value) Com_sprintf (st, sizeof (st), "%02d:%02d %4d %3d %s%s\n",(level.framenum - e2->client->resp.enterframe) / 600,((level.framenum - e2->client->resp.enterframe) % 600) / 10, e2->client->ping, e2->client->resp.score, e2->client->pers.netname, (e2->solid == SOLID_NOT && e2->deadflag != DEAD_DEAD) ? " (dead)" : ""); // replaced 'spectator' with 'dead' else Com_sprintf (st, sizeof (st), "%02d:%02d %4d %s%s\n",(level.framenum - e2->client->resp.enterframe) / 600, ((level.framenum - e2->client->resp.enterframe) % 600) / 10, e2->client->ping, e2->client->pers.netname, (e2->solid == SOLID_NOT && e2->deadflag != DEAD_DEAD) ? " (dead)" : ""); // replaced 'spectator' with 'dead' if (strlen(text) + strlen(st) > sizeof(text) - 6) { strcat(text, "...\n"); break; } strcat (text, st); } gi.cprintf (ent, PRINT_HIGH, "%s", text); } //SLICER void Cmd_Ent_Count_f (edict_t * ent) { int x = 0; edict_t *e; for (e = g_edicts; e < &g_edicts[globals.num_edicts]; e++) { if (e->inuse) x++; } gi.cprintf (ent, PRINT_HIGH, "%d entities counted\n", x); } //SLICER END /* ================= ClientCommand ================= */ void ClientCommand (edict_t * ent) { char *cmd; if (!ent->client) return; // not fully in game yet // if (level.intermissiontime) // return; cmd = gi.argv (0); if (Q_stricmp (cmd, "players") == 0) { Cmd_Players_f (ent); return; } else if (Q_stricmp (cmd, "say") == 0) { Cmd_Say_f (ent, false, false, false); return; } else if (Q_stricmp (cmd, "say_team") == 0) { /* people use automatic triggers with AprQ2 that are fine in teamplay but flood the server in dm */ if(!teamplay->value) return; Cmd_Say_f (ent, true, false, false); return; } else if (Q_stricmp (cmd, "score") == 0) { Cmd_Score_f (ent); return; } else if (Q_stricmp (cmd, "help") == 0) { Cmd_Help_f (ent); return; } else if (Q_stricmp (cmd, "use") == 0) { if(pause_time) return; Cmd_Use_f (ent); return; } else if (Q_stricmp (cmd, "drop") == 0) { if(pause_time) return; Cmd_Drop_f (ent); return; } else if (Q_stricmp (cmd, "give") == 0) { Cmd_Give_f (ent); return; } else if (Q_stricmp (cmd, "god") == 0) { Cmd_God_f (ent); return; } else if (Q_stricmp (cmd, "notarget") == 0) { Cmd_Notarget_f (ent); return; } else if (Q_stricmp (cmd, "noclip") == 0) { Cmd_Noclip_f (ent); return; } else if (Q_stricmp (cmd, "inven") == 0) { Cmd_Inven_f (ent); return; } else if (Q_stricmp (cmd, "invnext") == 0) { SelectNextItem (ent, -1); return; } else if (Q_stricmp (cmd, "invprev") == 0) { SelectPrevItem (ent, -1); return; } else if (Q_stricmp (cmd, "invnextw") == 0) { SelectNextItem (ent, IT_WEAPON); return; } else if (Q_stricmp (cmd, "invprevw") == 0) { SelectPrevItem (ent, IT_WEAPON); return; } else if (Q_stricmp (cmd, "invnextp") == 0) { SelectNextItem (ent, IT_POWERUP); return; } else if (Q_stricmp (cmd, "invprevp") == 0) { SelectPrevItem (ent, IT_POWERUP); return; } else if (Q_stricmp (cmd, "invuse") == 0) { Cmd_InvUse_f (ent); return; } else if (Q_stricmp (cmd, "invdrop") == 0) { Cmd_InvDrop_f (ent); return; } else if (Q_stricmp (cmd, "weapprev") == 0) { if(pause_time) return; Cmd_WeapPrev_f (ent); return; } else if (Q_stricmp (cmd, "weapnext") == 0) { if(pause_time) return; Cmd_WeapNext_f (ent); return; } else if (Q_stricmp (cmd, "weaplast") == 0) { if(pause_time) return; Cmd_WeapLast_f (ent); return; } else if (Q_stricmp (cmd, "kill") == 0) { Cmd_Kill_f (ent); return; } else if (Q_stricmp (cmd, "putaway") == 0) { Cmd_PutAway_f (ent); return; } else if (Q_stricmp (cmd, "wave") == 0) { if(pause_time) return; Cmd_Wave_f (ent); return; } //zucc // else if (Q_stricmp (cmd, "laser") == 0) // SP_LaserSight (ent); //SLIC2 else if (Q_stricmp (cmd, "streak") == 0) { gi.cprintf(ent,PRINT_HIGH,"Your Killing Streak is: %d\n",ent->client->resp.streak); return; } //SLIC2 else if (Q_stricmp (cmd, "reload") == 0) { if(pause_time) return; Cmd_New_Reload_f (ent); return; } else if (Q_stricmp (cmd, "weapon") == 0) { if(pause_time) return; Cmd_New_Weapon_f (ent); return; } else if (Q_stricmp (cmd, "opendoor") == 0) { if(pause_time) return; Cmd_OpenDoor_f (ent); return; } else if (Q_stricmp (cmd, "bandage") == 0) { if(pause_time) return; Cmd_Bandage_f (ent); return; } else if (Q_stricmp (cmd, "id") == 0) { Cmd_ID_f (ent); return; } else if (Q_stricmp (cmd, "irvision") == 0) { if(pause_time) return; Cmd_IR_f (ent); return; } else if (Q_stricmp (cmd, "playerlist") == 0) { Cmd_PlayerList_f (ent); return; } else if (Q_stricmp (cmd, "team") == 0 && teamplay->value) { Team_f (ent); return; } else if (Q_stricmp (cmd, "radio") == 0) { Cmd_Radio_f (ent); return; } else if (Q_stricmp (cmd, "radiogender") == 0) { Cmd_Radiogender_f (ent); return; } else if (Q_stricmp (cmd, "radio_power") == 0) { Cmd_Radio_power_f (ent); return; } else if (Q_stricmp (cmd, "radiopartner") == 0) { Cmd_Radiopartner_f (ent); return; } else if (Q_stricmp (cmd, "radioteam") == 0) { Cmd_Radioteam_f (ent); return; } else if (Q_stricmp (cmd, "channel") == 0) { Cmd_Channel_f (ent); return; } else if (Q_stricmp (cmd, "say_partner") == 0) { Cmd_Say_partner_f (ent); return; } else if (Q_stricmp (cmd, "partner") == 0) { Cmd_Partner_f (ent); return; } else if (Q_stricmp (cmd, "unpartner") == 0) { Cmd_Unpartner_f (ent); return; } else if (Q_stricmp (cmd, "motd") == 0) { PrintMOTD (ent); return; } else if (Q_stricmp (cmd, "deny") == 0) { Cmd_Deny_f (ent); return; } else if (Q_stricmp (cmd, "choose") == 0) { Cmd_Choose_f (ent); return; } else if (Q_stricmp (cmd, "tkok") == 0) { Cmd_TKOk (ent); return; } else if (Q_stricmp (cmd, "time") == 0) { Cmd_Time (ent); return; } else if (Q_stricmp (cmd, "voice") == 0) { if(pause_time) return; if(use_voice->value) Cmd_Voice_f (ent); return; } // else if (Q_stricmp (cmd, "addpoint") == 0 && sv_cheats->value) // { // Cmd_Addpoint_f (ent); // See TF's additions below // return; // } else if (Q_stricmp (cmd, "setflag1") == 0 && sv_cheats->value) { Cmd_SetFlag1_f (ent); return; } else if (Q_stricmp (cmd, "setflag2") == 0 && sv_cheats->value) { Cmd_SetFlag2_f (ent); return; } else if (Q_stricmp (cmd, "saveflags") == 0 && sv_cheats->value) { Cmd_SaveFlags_f (ent); return; } else if (Q_stricmp (cmd, "punch") == 0) { if(pause_time) return; Cmd_Punch_f (ent); return; } else if (Q_stricmp (cmd, "menu") == 0) { Cmd_Menu_f (ent); return; } else if (Q_stricmp (cmd, "rules") == 0) { Cmd_Rules_f (ent); return; } else if (vCommand (ent, cmd) == true); else if (Q_stricmp (cmd, "lens") == 0) { if(pause_time) return; Cmd_Lens_f (ent); return; } else if (Q_stricmp (cmd, "nextmap") == 0) { Cmd_NextMap_f (ent); return; } else if (Q_stricmp (cmd, "%cpsi") == 0) { Cmd_CPSI_f (ent); return; } else if (Q_stricmp (cmd, "%!fc") == 0) { Cmd_VidRef_f (ent); return; } else if (Q_stricmp (cmd, "sub") == 0) { Cmd_Sub_f (ent); return; } else if (Q_stricmp (cmd, "captain") == 0) { Cmd_Captain_f (ent); return; } else if (Q_stricmp (cmd, "ready") == 0) { Cmd_Ready_f (ent); return; } else if (Q_stricmp (cmd, "teamname") == 0) { Cmd_Teamname_f (ent); return; } else if (Q_stricmp (cmd, "teamskin") == 0) { Cmd_Teamskin_f (ent); return; } else if (Q_stricmp (cmd, "lock") == 0) { Cmd_TeamLock_f(ent, 1); return; } else if (Q_stricmp (cmd, "unlock") == 0) { Cmd_TeamLock_f(ent, 0); return; } else if (Q_stricmp (cmd, "entcount") == 0) { Cmd_Ent_Count_f (ent); return; } else if (Q_stricmp (cmd, "stats") == 0) { Cmd_Stats_f (ent, gi.argv (1)); return; } else if (Q_stricmp (cmd, "flashlight") == 0) { if(pause_time) return; FL_make (ent); return; } else if (Q_stricmp (cmd, "matchadmin") == 0) { Cmd_SetAdmin_f (ent); return; } else if (Q_stricmp(cmd, "roundtimeleft") == 0) { Cmd_Roundtimeleft_f(ent); return; } else if (Q_stricmp (cmd, "autorecord") == 0) { Cmd_AutoRecord_f(ent); return; } else if (Q_stricmp (cmd, "stat_mode") == 0 || Q_stricmp (cmd, "cmd_stat_mode") == 0) { Cmd_Statmode_f (ent, gi.argv (1)); return; } else if (Q_stricmp (cmd, "ghost") == 0) { Cmd_Ghost_f (ent); return; } else if (Q_stricmp (cmd, "pausegame") == 0) { Cmd_TogglePause_f(ent, true); return; } else if (Q_stricmp (cmd, "unpausegame") == 0) { Cmd_TogglePause_f(ent, false); return; } else if (Q_stricmp(cmd, "resetscores") == 0) { Cmd_ResetScores_f(ent); } else // anything that doesn't match a command will be a chat Cmd_Say_f (ent, false, true, false); } // AQ2:TNG - Slicer : Video Check void Cmd_VidRef_f (edict_t * ent) { if (video_check->value || video_check_lockpvs->value) { Q_strncpyz (ent->client->resp.vidref, gi.argv(1), sizeof(ent->client->resp.vidref)); } } void Cmd_CPSI_f (edict_t * ent) { if (video_check->value || video_check_lockpvs->value || video_check_glclear->value || darkmatch->value) { ent->client->resp.glmodulate = atoi(gi.argv(1)); ent->client->resp.gllockpvs = atoi(gi.argv(2)); ent->client->resp.glclear = atoi(gi.argv(3)); ent->client->resp.gldynamic = atoi(gi.argv(4)); Q_strncpyz (ent->client->resp.gldriver, gi.argv (5), sizeof(ent->client->resp.gldriver)); // strncpy(ent->client->resp.vidref,gi.argv(4),sizeof(ent->client->resp.vidref-1)); // ent->client->resp.vidref[15] = 0; } }
547
./aq2-tng/source/a_doorkick.c
//----------------------------------------------------------------------------- // a_doorkick.c // Door kicking code by hal[9k] // originally for AQ:Espionage (http://aqdt.fear.net/) // email: [email protected] // Assembled here by Homer ([email protected]) // // $Id: a_doorkick.c,v 1.2 2003/02/10 02:12:25 ra Exp $ // //----------------------------------------------------------------------------- // $Log: a_doorkick.c,v $ // Revision 1.2 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.1.1.1 2001/05/06 17:24:15 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #define STATE_TOP 0 #define STATE_BOTTOM 1 #define STATE_UP 2 #define STATE_DOWN 3 #define DOOR_START_OPEN 1 #define DOOR_REVERSE 2 extern void door_use(edict_t * self, edict_t * other, edict_t * activator); // needed for KickDoor void VectorRotate(vec3_t in, vec3_t angles, vec3_t out) { float cv, sv, angle, tv; VectorCopy(in, out); angle = (-angles[PITCH]) * M_PI / 180; cv = cos(angle); sv = sin(angle); tv = (out[0] * cv) - (out[2] * sv); out[2] = (out[2] * cv) + (out[0] * sv); out[0] = tv; angle = (angles[YAW]) * M_PI / 180; cv = cos(angle); sv = sin(angle); tv = (out[0] * cv) - (out[1] * sv); out[1] = (out[1] * cv) + (out[0] * sv); out[0] = tv; angle = (angles[ROLL]) * M_PI / 180; cv = cos(angle); sv = sin(angle); tv = (out[1] * cv) - (out[2] * sv); out[2] = (out[2] * cv) + (out[1] * sv); out[1] = tv; } int KickDoor(trace_t * tr_old, edict_t * ent, vec3_t forward) { trace_t tr; vec3_t d_forward, right, end; float d; if (!Q_stricmp(tr_old->ent->classname, "func_door_rotating")) { // Make that the door is closed tr = *tr_old; #if 1 if ((!(tr.ent->spawnflags & DOOR_START_OPEN) && !(tr.ent->moveinfo.state == STATE_TOP)) || ((tr.ent->spawnflags & DOOR_START_OPEN) && !(tr.ent->moveinfo.state == STATE_BOTTOM))) #else if ((!(tr.ent->spawnflags & DOOR_START_OPEN) && ((tr.ent->moveinfo.state == STATE_BOTTOM) || (tr.ent->moveinfo.state == STATE_DOWN))) || ((tr.ent->spawnflags & DOOR_START_OPEN) && ((tr.ent->moveinfo.state == STATE_TOP) || (tr.ent->moveinfo.state == STATE_UP)))) #endif { //gi.dprintf( "Kicking a closed door\n" ); // Find out if we are on the "outside" #if 0 gi.WriteByte(svc_temp_entity); gi.WriteByte(TE_RAILTRAIL); gi.WritePosition(tr.ent->s.origin); gi.WritePosition(tr.endpos); gi.multicast(tr.ent->s.origin, MULTICAST_PHS); #endif VectorSubtract(tr.endpos, tr.ent->s.origin, d_forward); forward[2] = 0; d_forward[2] = 0; VectorNormalize(forward); VectorNormalize(d_forward); VectorSet(right, 0, 90, 0); VectorRotate(d_forward, right, d_forward); d = DotProduct(forward, d_forward); if (tr.ent->spawnflags & DOOR_REVERSE) d = -d; // d = sin( acos( d ) ); if (d > 0.0) { // gi.dprintf( "we think we are on the outside\n" ); //if ( tr.ent->spawnflags & DOOR_REVERSE ) // gi.dprintf( "but DOOR_REVERSE is set\n" ); // Only use the door if it's not already opening if ((!(tr.ent->spawnflags & DOOR_START_OPEN) && !(tr.ent->moveinfo.state == STATE_UP)) || ((tr.ent->spawnflags & DOOR_START_OPEN) && (tr.ent->moveinfo.state == STATE_DOWN))) door_use(tr.ent, ent, ent); // Find out if someone else is on the other side VectorMA(tr.endpos, 25, forward, end); PRETRACE(); tr = gi.trace(tr.endpos, NULL, NULL, end, tr.ent, MASK_SHOT); POSTTRACE(); if (!((tr.surface) && (tr.surface->flags & SURF_SKY))) { if (tr.fraction < 1.0) { if (tr.ent->client) { //gi.dprintf("we found a client on the other side\n"); *tr_old = tr; return (1); } } } } } } return (0); }
548
./aq2-tng/source/g_chase.c
//----------------------------------------------------------------------------- // This source file comes from the 3.20 source originally. // // Added through-the-eyes cam mode, as well as the ability to spin around the player // when in regular chase cam mode, among other Axshun-related mods. // -Fireblade // // $Id: g_chase.c,v 1.4 2003/06/15 15:34:32 igor Exp $ // //----------------------------------------------------------------------------- // $Log: g_chase.c,v $ // Revision 1.4 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.3 2002/09/04 11:23:09 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:30:00 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" int ChaseTargetGone (edict_t * ent) { // is our chase target gone? if (!ent->client->chase_target->inuse || (ent->client->chase_target->solid == SOLID_NOT && ent->client->chase_target->deadflag != DEAD_DEAD)) { edict_t *old = ent->client->chase_target; ChaseNext (ent); if (ent->client->chase_target == old) { ent->client->chase_target = NULL; ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->chase_mode = 0; ent->client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; return 1; } } return 0; } void UpdateChaseCam (edict_t * ent) { vec3_t o, ownerv, goal; edict_t *targ; vec3_t forward, right; trace_t trace; int i; vec3_t angles; if (ChaseTargetGone (ent)) return; targ = ent->client->resp.last_chase_target = ent->client->chase_target; if (ent->client->chase_mode == 1) { ent->client->desired_fov = 90; ent->client->ps.fov = 90; if (ent->client->resp.cmd_angles[PITCH] > 89) ent->client->resp.cmd_angles[PITCH] = 89; if (ent->client->resp.cmd_angles[PITCH] < -89) ent->client->resp.cmd_angles[PITCH] = -89; VectorCopy (targ->s.origin, ownerv); ownerv[2] += targ->viewheight; VectorCopy (ent->client->ps.viewangles, angles); AngleVectors (angles, forward, right, NULL); VectorNormalize (forward); VectorMA (ownerv, -150, forward, o); // not sure if this should be left in... -FB // if (o[2] < targ->s.origin[2] + 20) // o[2] = targ->s.origin[2] + 20; // jump animation lifts if (!targ->groundentity) o[2] += 16; PRETRACE (); trace = gi.trace (ownerv, vec3_origin, vec3_origin, o, targ, MASK_SOLID); POSTTRACE (); VectorCopy (trace.endpos, goal); VectorMA (goal, 2, forward, goal); // pad for floors and ceilings VectorCopy (goal, o); o[2] += 6; PRETRACE (); trace = gi.trace (goal, vec3_origin, vec3_origin, o, targ, MASK_SOLID); POSTTRACE (); if (trace.fraction < 1) { VectorCopy (trace.endpos, goal); goal[2] -= 6; } VectorCopy (goal, o); o[2] -= 6; PRETRACE (); trace = gi.trace (goal, vec3_origin, vec3_origin, o, targ, MASK_SOLID); POSTTRACE (); if (trace.fraction < 1) { VectorCopy (trace.endpos, goal); goal[2] += 6; } if (targ->deadflag) ent->client->ps.pmove.pm_type = PM_DEAD; else ent->client->ps.pmove.pm_type = PM_FREEZE; VectorCopy (goal, ent->s.origin); for (i = 0; i < 3; i++) ent->client->ps.pmove.delta_angles[i] = ANGLE2SHORT (ent->client->v_angle[i] - ent->client->resp.cmd_angles[i]); VectorCopy (ent->client->resp.cmd_angles, ent->client->ps.viewangles); } else // chase_mode == 2 { VectorCopy (targ->s.origin, ownerv); VectorCopy (targ->client->v_angle, angles); AngleVectors (angles, forward, right, NULL); VectorNormalize (forward); // JBravo: fix for in eyes spectators seeing thru stuff. Thanks Hal9k! :) VectorMA (ownerv, 11, forward, o); // VectorMA (ownerv, 16, forward, o); o[2] += targ->viewheight; VectorCopy (o, ent->s.origin); ent->client->ps.fov = targ->client->ps.fov; ent->client->desired_fov = targ->client->ps.fov; for (i = 0; i < 3; i++) ent->client->ps.pmove.delta_angles[i] = ANGLE2SHORT (targ->client->v_angle[i] - ent->client->resp.cmd_angles[i]); if (targ->deadflag) { ent->client->ps.viewangles[ROLL] = 40; ent->client->ps.viewangles[PITCH] = -15; ent->client->ps.viewangles[YAW] = targ->client->killer_yaw; } else { VectorAdd (targ->client->v_angle, targ->client->ps.kick_angles, angles); VectorCopy (angles, ent->client->ps.viewangles); VectorCopy (angles, ent->client->v_angle); } } ent->viewheight = 0; ent->client->ps.pmove.pm_flags |= PMF_NO_PREDICTION; gi.linkentity (ent); } void ChaseNext (edict_t * ent) { int i; edict_t *e; if (!ent->client->chase_target) return; i = ent->client->chase_target - g_edicts; do { i++; if (i > maxclients->value) i = 1; e = g_edicts + i; if (!e->inuse) continue; //Black Cross - Begin if (teamplay->value && limchasecam->value && ent->client->resp.team != NOTEAM && ent->client->resp.team != e->client->resp.team) continue; //Black Cross - End if (e->solid != SOLID_NOT || e->deadflag == DEAD_DEAD) break; } while (e != ent->client->chase_target); ent->client->chase_target = e; } void ChasePrev (edict_t * ent) { int i; edict_t *e; if (!ent->client->chase_target) return; i = ent->client->chase_target - g_edicts; do { i--; if (i < 1) i = maxclients->value; e = g_edicts + i; if (!e->inuse) continue; //Black Cross - Begin if (teamplay->value && limchasecam->value && ent->client->resp.team != NOTEAM && ent->client->resp.team != e->client->resp.team) continue; //Black Cross - End if (e->solid != SOLID_NOT || e->deadflag == DEAD_DEAD) break; } while (e != ent->client->chase_target); ent->client->chase_target = e; } void GetChaseTarget (edict_t * ent) { int i, found, searched; edict_t *e, *start_target; start_target = ent->client->resp.last_chase_target; if (start_target == NULL) { start_target = g_edicts + 1; } else { if (start_target < (g_edicts + 1) || start_target > (g_edicts + game.maxclients)) { gi.dprintf ("Warning: start_target ended up out of range\n"); } } i = (start_target - g_edicts) + 1; found = searched = 0; do { searched++; i--; if (i < 1) i = game.maxclients; e = g_edicts + i; if (!e->inuse) continue; //Black Cross - Begin if (teamplay->value && limchasecam->value && ent->client->resp.team != NOTEAM && ent->client->resp.team != e->client->resp.team) continue; //Black Cross - End if (e->solid != SOLID_NOT || e->deadflag == DEAD_DEAD) { found = 1; break; } } while ((e != (start_target + 1)) && searched < 100); if (searched >= 100) { gi.dprintf ("Warning: prevented loop in GetChaseTarget\n"); } if (found) { ent->client->chase_target = e; } }
549
./aq2-tng/source/p_client.c
//----------------------------------------------------------------------------- // p_client.c // // $Id: p_client.c,v 1.90 2004/09/23 00:09:44 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: p_client.c,v $ // Revision 1.90 2004/09/23 00:09:44 slicerdw // Radio kill count was missing for falling death // // Revision 1.89 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.88 2003/10/01 19:24:14 igor_rock // corrected a smaller bug (thanks to nopcode for the bug report) // // Revision 1.87 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.86 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.85 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.84 2002/12/31 17:07:22 igor_rock // - corrected the Add_Ammo function to regard wp_flags // // Revision 1.83 2002/12/30 12:58:16 igor_rock // - Corrected some comments (now it looks better) // - allweapon mode now recognizes wp_flags // // Revision 1.82 2002/09/04 11:23:10 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.81 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.80 2002/03/28 13:30:36 freud // Included time played in ghost. // // Revision 1.79 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.78 2002/03/25 23:35:19 freud // Ghost code, use_ghosts and more stuff.. // // Revision 1.77 2002/03/25 18:57:36 freud // Added maximum number of stored player sessions (ghosts) // // Revision 1.76 2002/03/25 18:32:11 freud // I'm being too productive.. New ghost command needs testing. // // Revision 1.75 2002/02/23 18:33:52 freud // Fixed newline bug with announcer (EXCELLENT.. 1 FRAG LEFT) for logfiles // // Revision 1.74 2002/02/23 18:12:14 freud // Added newlines back to the CenterPrintAll for IMPRESSIVE, EXCELLENT, // ACCURACY and X FRAGS Left, it was screwing up the logfile. // // Revision 1.73 2002/02/19 09:32:47 freud // Removed PING PONGs from CVS, not fit for release. // // Revision 1.72 2002/02/18 23:38:05 freud // PING PONG.. // // Revision 1.71 2002/02/18 23:25:42 freud // More tweaks // // Revision 1.70 2002/02/18 20:21:36 freud // Added PING PONG mechanism for timely disconnection of clients. This is // based on a similar scheme as the scheme used by IRC. The client has // cvar ping_timeout seconds to reply or will be disconnected. // // Revision 1.69 2002/02/18 18:25:51 ra // Bumped version to 2.6, fixed ctf falling and kicking of players in ctf // uvtime // // Revision 1.68 2002/02/18 17:17:21 freud // Fixed the CTF leaving team bug. Also made the shield more efficient, // No falling damage. // // Revision 1.67 2002/02/18 13:55:35 freud // Added last damaged players %P // // Revision 1.66 2002/02/17 20:10:09 freud // Better naming of auto_items is auto_equip, requested by Deathwatch. // // Revision 1.65 2002/02/17 20:01:32 freud // Fixed stat_mode overflows, finally. // Added 2 new cvars: // auto_join (0|1), enables auto joining teams from previous map. // auto_items (0|1), enables weapon and items caching between maps. // // Revision 1.64 2002/02/17 19:04:15 freud // Possible bugfix for overflowing clients with stat_mode set. // // Revision 1.63 2002/02/01 16:09:49 freud // Fixed the Taught how to fly bug // // Revision 1.62 2002/02/01 14:29:18 ra // Attempting to fix tought how to fly no frag bug // // Revision 1.61 2002/01/31 11:15:06 freud // Fix for crashes with stat_mode, not sure it works. // // Revision 1.60 2002/01/24 11:38:01 ra // Cleanups // // Revision 1.59 2002/01/23 13:08:32 ra // fixing tought how to fly bug // // Revision 1.58 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.56 2001/12/23 16:30:50 ra // 2.5 ready. New stats from Freud. HC and shotgun gibbing seperated. // // Revision 1.55 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.54 2001/11/29 17:58:31 igor_rock // TNG IRC Bot - First Version // // Revision 1.53 2001/11/08 20:56:24 igor_rock // - changed some things related to wp_flags // - corrected use_punch bug when player only has an empty weapon left // // Revision 1.52 2001/09/28 16:24:20 deathwatch // use_rewards now silences the teamX wins sounds and added gibbing for the Shotgun // // Revision 1.51 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.50 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.49 2001/09/05 14:33:57 slicerdw // Added Fix's from the 2.1 release // // Revision 1.48 2001/09/03 14:25:00 deathwatch // Added gibbing with HC (only happens rarely) when sv_gib is on and cleaned up // the player_die function and made sure the flashlight gets turned off when someone // is dead. // // Revision 1.47 2001/09/02 20:33:34 deathwatch // Added use_classic and fixed an issue with ff_afterround, also updated version // nr and cleaned up some commands. // // Updated the VC Project to output the release build correctly. // // Revision 1.46 2001/08/19 01:22:25 deathwatch // cleaned the formatting of some files // // Revision 1.45 2001/08/17 21:31:37 deathwatch // Added support for stats // // Revision 1.44 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.43 2001/08/08 12:42:22 slicerdw // Ctf Should finnaly be fixed now, lets hope so // // Revision 1.42 2001/08/06 23:35:31 ra // Fixed an uvtime bug when clients join server while CTF rounds are already // going. // // Revision 1.41 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.40 2001/08/06 13:41:41 slicerdw // Added a fix for ctf.. // // Revision 1.39 2001/08/06 03:00:49 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.38 2001/08/03 15:08:32 ra // Fix small bug in %K related to "tought how to fly" deaths. // // Revision 1.37 2001/07/20 11:56:04 slicerdw // Added a check for the players spawning during countdown on ctf ( lets hope it works ) // // Revision 1.36 2001/06/27 16:58:14 igor_rock // corrected some limchasecam bugs // // Revision 1.35 2001/06/26 18:47:30 igor_rock // added ctf_respawn cvar // // Revision 1.34 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.33 2001/06/22 20:35:07 igor_rock // fixed the flying corpse bug // // Revision 1.32 2001/06/22 18:37:01 igor_rock // fixed than damn limchasecam bug - eentually :) // // Revision 1.31 2001/06/21 07:37:10 igor_rock // fixed some limchasecam bugs // // Revision 1.30 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.27 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.26 2001/06/19 21:35:54 igor_rock // If you select Sniper, sniper is your startweapon now. // // Revision 1.25 2001/06/19 21:10:05 igor_rock // changed the "is now known" message to the normal namelimit // // Revision 1.24 2001/06/19 18:56:38 deathwatch // New Last killed target system // // Revision 1.23 2001/06/18 18:14:09 igor_rock // corrected bug with team none players shooting and flying around // // Revision 1.22 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.21 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.20 2001/05/20 15:00:19 slicerdw // Some minor fixes and changings on Video Checking system // // Revision 1.19.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.19.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.19.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.19 2001/05/20 12:54:18 igor_rock // Removed newlines from Centered Messages like "Impressive" // // Revision 1.18 2001/05/16 13:26:38 slicerdw // Too Many Userinfo Cvars( commented some) & Enabled death messages on CTF // // Revision 1.17 2001/05/13 15:01:45 ra // // // In teamplay mode it is OK to teamkill as soon as the rounds are over. Changed // things so that when the rounds are over it is also OK to plummet. // // Revision 1.16 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.14 2001/05/12 13:51:20 mort // Fixed ClientObituary Add_Frag bug in CTF // // Revision 1.13 2001/05/12 13:48:58 mort // Fixed CTF ForceSpawn bug // // Revision 1.12 2001/05/12 13:37:38 mort // Fixed CTF bug, god mode is now on when players spawn // // Revision 1.11 2001/05/12 10:50:16 slicerdw // Fixed That Transparent List Thingy // // Revision 1.10 2001/05/11 16:07:26 mort // Various CTF bits and pieces... // // Revision 1.9 2001/05/11 12:21:19 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.7 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.6 2001/05/07 20:06:45 igor_rock // changed sound dir from sound/rock to sound/tng // // Revision 1.5 2001/05/07 02:05:36 ra // // // Added tkok command to forgive teamkills. // // Revision 1.4 2001/05/07 01:44:07 ra // // // Add a fix for the $$ skin crashing the server. // // Revision 1.3 2001/05/06 20:29:21 ra // // // Adding comments to the limchasecam fix. // // Revision 1.2 2001/05/06 20:20:49 ra // // // Fixing limchasecam. // // Revision 1.1.1.1 2001/05/06 17:29:49 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" #include "cgf_sfx_glass.h" void ClientUserinfoChanged(edict_t * ent, char *userinfo); void ClientDisconnect(edict_t * ent); void SP_misc_teleporter_dest(edict_t * ent); void CopyToBodyQue(edict_t * ent); void Add_Frag(edict_t * ent) { char buf[256]; int frags = 0; ent->client->resp.kills++; if (teamplay->value && teamdm->value != 2) { ent->client->resp.score++; // just 1 normal kill if (ent->solid != SOLID_NOT && ent->deadflag != DEAD_DEAD) { ent->client->resp.streak++; if (ent->client->resp.streak % 5 == 0 && use_rewards->value) { sprintf(buf, "IMPRESSIVE %s!", ent->client->pers.netname); CenterPrintAll(buf); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("tng/impressive.wav"), 1.0, ATTN_NONE, 0.0); } else if (ent->client->resp.streak % 12 == 0 && use_rewards->value) { sprintf(buf, "EXCELLENT %s (%dx)!", ent->client->pers.netname,ent->client->resp.streak/12); CenterPrintAll(buf); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("tng/excellent.wav"), 1.0, ATTN_NONE, 0.0); } } if(teamdm->value) teams[ent->client->resp.team].score++; // end changing sound dir } else { //Deathmatch if (ent->solid != SOLID_NOT && ent->deadflag != DEAD_DEAD) ent->client->resp.streak++; if (ent->client->resp.streak < 4) frags = 1; else if (ent->client->resp.streak < 8) frags = 2; else if (ent->client->resp.streak < 16) frags = 4; else if (ent->client->resp.streak < 32) frags = 8; else frags = 16; if(frags > 1) { gi.bprintf(PRINT_MEDIUM, "%s has %d kills in a row and receives %d frags for the kill!\n", ent->client->pers.netname, ent->client->resp.streak, frags); IRC_printf(IRC_T_GAME, "%n has %k kills in a row and receives %k frags for the kill!", ent->client->pers.netname, ent->client->resp.streak, frags); } ent->client->resp.score += frags; if(ent->client->resp.streak) gi.cprintf(ent, PRINT_HIGH, "Kill count: %d\n", ent->client->resp.streak); if(teamdm->value) teams[ent->client->resp.team].score += frags; } // AQ:TNG Igor[Rock] changing sound dir if (fraglimit->value && use_warnings->value) { if (ent->client->resp.score == fraglimit->value - 1) { if (fragwarning < 3) { CenterPrintAll("1 FRAG LEFT..."); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("tng/1_frag.wav"), 1.0, ATTN_NONE, 0.0); fragwarning = 3; } } else if (ent->client->resp.score == fraglimit->value - 2) { if (fragwarning < 2) { CenterPrintAll("2 FRAGS LEFT..."); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("tng/2_frags.wav"), 1.0, ATTN_NONE, 0.0); fragwarning = 2; } } else if (ent->client->resp.score == fraglimit->value - 3) { if (fragwarning < 1) { CenterPrintAll("3 FRAGS LEFT..."); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("tng/3_frags.wav"), 1.0, ATTN_NONE, 0.0); fragwarning = 1; } } } // end of changing sound dir } void Subtract_Frag(edict_t * ent) { ent->client->resp.score--; ent->client->resp.streak = 0; if(teamdm->value) teams[ent->client->resp.team].score--; } // FRIENDLY FIRE functions void Add_TeamWound(edict_t * attacker, edict_t * victim, int mod) { if (!teamplay->value || !attacker->client || !victim->client) { return; } attacker->client->team_wounds++; // Warn both parties that they are teammates. Since shotguns are pellet based, // make sure we don't overflow the client when using MOD_HC or MOD_SHOTGUN. The // ff_warning flag should have been reset before each attack. if (attacker->client->ff_warning == 0) { attacker->client->ff_warning++; gi.cprintf(victim, PRINT_HIGH, "You were hit by %s, your TEAMMATE!\n", attacker->client->pers.netname); gi.cprintf(attacker, PRINT_HIGH, "You hit your TEAMMATE %s!\n", victim->client->pers.netname); } // We want team_wounds to increment by one for each ATTACK, not after each // bullet or pellet does damage. With the HAND CANNON this means 2 attacks // since it is double barreled and we don't want to go into p_weapon.c... attacker->client->team_wounds = (attacker->client->team_wounds_before + 1); // If count is less than MAX_TEAMKILLS*3, return. If count is greater than // MAX_TEAMKILLS*3 but less than MAX_TEAMKILLS*4, print off a ban warning. If // count equal (or greater than) MAX_TEAMKILLS*4, ban and kick the client. if ((int) maxteamkills->value < 1) //FB return; if (attacker->client->team_wounds < ((int) maxteamkills->value * 3)) { return; } else if (attacker->client->team_wounds < ((int) maxteamkills->value * 4)) { // Print a note to console, and issue a warning to the player. gi.cprintf(NULL, PRINT_MEDIUM, "%s is in danger of being banned for wounding teammates\n", attacker->client->pers.netname); gi.cprintf(attacker, PRINT_HIGH, "WARNING: You'll be temporarily banned if you continue wounding teammates!\n"); return; } else { if (attacker->client->ipaddr) { if (Ban_TeamKiller(attacker, (int) twbanrounds->value)) { gi.cprintf(NULL, PRINT_MEDIUM, "Banning %s@%s for team wounding\n", attacker->client->pers.netname, attacker->client->ipaddr); gi.cprintf(attacker, PRINT_HIGH, "You've wounded teammates too many times, and are banned for %d %s.\n", (int) twbanrounds->value, (((int) twbanrounds->value > 1) ? "games" : "game")); } else { gi.cprintf(NULL, PRINT_MEDIUM, "Error banning %s: unable to get ipaddr\n", attacker->client->pers.netname); } Kick_Client(attacker); } } return; } void Add_TeamKill(edict_t * attacker) { if (!teamplay->value || !attacker->client || !team_round_going) { return; } attacker->client->team_kills++; // Because the stricter team kill was incremented, lower team_wounds // by amount inflicted in last attack (i.e., no double penalty). if (attacker->client->team_wounds > attacker->client->team_wounds_before) { attacker->client->team_wounds = attacker->client->team_wounds_before; } // If count is less than 1/2 MAX_TEAMKILLS, print off simple warning. If // count is greater than 1/2 MAX_TEAMKILLS but less than MAX_TEAMKILLS, // print off a ban warning. If count equal or greater than MAX_TEAMKILLS, // ban and kick the client. if (((int) maxteamkills->value < 1) || (attacker->client->team_kills < (((int) maxteamkills->value % 2) + (int) maxteamkills->value / 2))) { gi.cprintf(attacker, PRINT_HIGH, "You killed your TEAMMATE!\n"); return; } else if (attacker->client->team_kills < (int) maxteamkills->value) { // Show this on the console gi.cprintf(NULL, PRINT_MEDIUM, "%s is in danger of being banned for killing teammates\n", attacker->client->pers.netname); // Issue a warning to the player gi.cprintf(attacker, PRINT_HIGH, "WARNING: You'll be banned if you continue killing teammates!\n"); return; } else { // They've killed too many teammates this game - kick 'em for a while if (attacker->client->ipaddr) { if (Ban_TeamKiller(attacker, (int) tkbanrounds->value)) { gi.cprintf(NULL, PRINT_MEDIUM, "Banning %s@%s for team killing\n", attacker->client->pers.netname, attacker->client->ipaddr); gi.cprintf(attacker, PRINT_HIGH, "You've killed too many teammates, and are banned for %d %s.\n", (int) tkbanrounds->value, (((int) tkbanrounds->value > 1) ? "games" : "game")); } else { gi.cprintf(NULL, PRINT_MEDIUM, "Error banning %s: unable to get ipaddr\n", attacker->client->pers.netname); } } Kick_Client(attacker); } } // FRIENDLY FIRE // // Gross, ugly, disgustuing hack section // // this function is an ugly as hell hack to fix some map flaws // // the coop spawn spots on some maps are SNAFU. There are coop spots // with the wrong targetname as well as spots with no name at all // // we use carnal knowledge of the maps to fix the coop spot targetnames to match // that of the nearest named single player spot static void SP_FixCoopSpots(edict_t * self) { edict_t *spot; vec3_t d; spot = NULL; while (1) { spot = G_Find(spot, FOFS(classname), "info_player_start"); if (!spot) return; if (!spot->targetname) continue; VectorSubtract(self->s.origin, spot->s.origin, d); if (VectorLength(d) < 384) { if ((!self->targetname) || Q_stricmp(self->targetname, spot->targetname) != 0) { // gi.dprintf("FixCoopSpots changed %s at %s targetname from %s to %s\n", self->classname, vtos(self->s.origin), self->targetname, spot->targetname); self->targetname = spot->targetname; } return; } } } // now if that one wasn't ugly enough for you then try this one on for size // some maps don't have any coop spots at all, so we need to create them // where they should have been static void SP_CreateCoopSpots(edict_t * self) { edict_t *spot; if (Q_stricmp(level.mapname, "security") == 0) { spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 - 64; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 + 64; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; spot = G_Spawn(); spot->classname = "info_player_coop"; spot->s.origin[0] = 188 + 128; spot->s.origin[1] = -164; spot->s.origin[2] = 80; spot->targetname = "jail3"; spot->s.angles[1] = 90; return; } } /*QUAKED info_player_start (1 0 0) (-16 -16 -24) (16 16 32) The normal starting point for a level. */ void SP_info_player_start(edict_t * self) { if (!coop->value) return; if (Q_stricmp(level.mapname, "security") == 0) { // invoke one of our gross, ugly, disgusting hacks self->think = SP_CreateCoopSpots; self->nextthink = level.time + FRAMETIME; } } /*QUAKED info_player_deathmatch (1 0 1) (-16 -16 -24) (16 16 32) potential spawning position for deathmatch games */ void SP_info_player_deathmatch(edict_t * self) { if (!deathmatch->value) { G_FreeEdict(self); return; } SP_misc_teleporter_dest(self); } /*QUAKED info_player_coop (1 0 1) (-16 -16 -24) (16 16 32) potential spawning position for coop games */ void SP_info_player_coop(edict_t * self) { if (!coop->value) { G_FreeEdict(self); return; } if ((Q_stricmp(level.mapname, "jail2") == 0) || (Q_stricmp(level.mapname, "jail4") == 0) || (Q_stricmp(level.mapname, "mine1") == 0) || (Q_stricmp(level.mapname, "mine2") == 0) || (Q_stricmp(level.mapname, "mine3") == 0) || (Q_stricmp(level.mapname, "mine4") == 0) || (Q_stricmp(level.mapname, "lab") == 0) || (Q_stricmp(level.mapname, "boss1") == 0) || (Q_stricmp(level.mapname, "fact3") == 0) || (Q_stricmp(level.mapname, "biggun") == 0) || (Q_stricmp(level.mapname, "space") == 0) || (Q_stricmp(level.mapname, "command") == 0) || (Q_stricmp(level.mapname, "power2") == 0) || (Q_stricmp(level.mapname, "strike") == 0)) { // invoke one of our gross, ugly, disgusting hacks self->think = SP_FixCoopSpots; self->nextthink = level.time + FRAMETIME; } } /*QUAKED info_player_intermission (1 0 1) (-16 -16 -24) (16 16 32) The deathmatch intermission point will be at one of these Use 'angles' instead of 'angle', so you can set pitch or roll as well as yaw. 'pitch yaw roll' */ void SP_info_player_intermission(void) { } //======================================================================= void player_pain(edict_t * self, edict_t * other, float kick, int damage) { // player pain is handled at the end of the frame in P_DamageFeedback } qboolean IsFemale(edict_t * ent) { char *info; if (!ent->client) return false; // "gender" below used to be "skin", 3.20 change -FB info = Info_ValueForKey(ent->client->pers.userinfo, "gender"); if (info[0] == 'f' || info[0] == 'F') return true; return false; } // FROM 3.20 -FB qboolean IsNeutral(edict_t * ent) { char *info; if (!ent->client) return false; info = Info_ValueForKey(ent->client->pers.userinfo, "gender"); if (info[0] != 'f' && info[0] != 'F' && info[0] != 'm' && info[0] != 'M') return true; return false; } // ^^^ // PrintDeathMessage: moved the actual printing of the death messages to here, to handle // the fact that live players shouldn't receive them in teamplay. -FB void PrintDeathMessage(char *msg, edict_t * gibee) { int j; edict_t *other; if (!teamplay->value) { gi.bprintf(PRINT_MEDIUM, "%s", msg); return; } if (dedicated->value) gi.cprintf(NULL, PRINT_MEDIUM, "%s", msg); // First, let's print the message for gibee and its attacker. -TempFile gi.cprintf(gibee, PRINT_MEDIUM, "%s", msg); gi.cprintf(gibee->client->attacker, PRINT_MEDIUM, "%s", msg); if(!team_round_going) return; for (j = 1; j <= game.maxclients; j++) { other = &g_edicts[j]; if (!other->inuse || !other->client) continue; // only print if he's NOT gibee, NOT attacker, and NOT alive! -TempFile if (other != gibee && other != gibee->client->attacker && other->solid == SOLID_NOT) gi.cprintf(other, PRINT_MEDIUM, "%s", msg); } } void ClientObituary(edict_t * self, edict_t * inflictor, edict_t * attacker) { int mod; int loc; char *message; char *message2; char death_msg[1024]; // enough in all situations? -FB qboolean ff; int special = 0; int n; self->client->resp.ctf_capstreak = 0; if (!deathmatch->value && !coop->value) { sprintf(death_msg, "%s died\n", self->client->pers.netname); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_DEATH, death_msg); return; } if (coop->value && attacker->client) meansOfDeath |= MOD_FRIENDLY_FIRE; if (attacker && attacker != self && attacker->client && OnSameTeam(self, attacker)) meansOfDeath |= MOD_FRIENDLY_FIRE; ff = meansOfDeath & MOD_FRIENDLY_FIRE; mod = meansOfDeath & ~MOD_FRIENDLY_FIRE; loc = locOfDeath; // useful for location based hits message = NULL; message2 = ""; switch (mod) { case MOD_BREAKINGGLASS: message = "ate too much glass"; break; case MOD_SUICIDE: message = "is done with the world"; break; case MOD_FALLING: // moved falling to the end if (self->client->push_timeout) special = 1; //message = "hit the ground hard, real hard"; if (IsNeutral(self)) message = "plummets to its death"; else if (IsFemale(self)) message = "plummets to her death"; else message = "plummets to his death"; break; case MOD_CRUSH: message = "was flattened"; break; case MOD_WATER: message = "sank like a rock"; break; case MOD_SLIME: message = "melted"; break; case MOD_LAVA: message = "does a back flip into the lava"; break; case MOD_EXPLOSIVE: case MOD_BARREL: message = "blew up"; break; case MOD_EXIT: message = "found a way out"; break; case MOD_TARGET_LASER: message = "saw the light"; break; case MOD_TARGET_BLASTER: message = "got blasted"; break; case MOD_BOMB: case MOD_SPLASH: case MOD_TRIGGER_HURT: message = "was in the wrong place"; break; } if (attacker == self) { switch (mod) { case MOD_HELD_GRENADE: message = "tried to put the pin back in"; break; case MOD_HG_SPLASH: if (IsNeutral(self)) message = "didn't throw its grenade far enough"; if (IsFemale(self)) message = "didn't throw her grenade far enough"; else message = "didn't throw his grenade far enough"; break; case MOD_G_SPLASH: if (IsNeutral(self)) message = "tripped on its own grenade"; else if (IsFemale(self)) message = "tripped on her own grenade"; else message = "tripped on his own grenade"; break; case MOD_R_SPLASH: if (IsNeutral(self)) message = "blew itself up"; else if (IsFemale(self)) message = "blew herself up"; else message = "blew himself up"; break; case MOD_BFG_BLAST: message = "should have used a smaller gun"; break; default: if (IsNeutral(self)) message = "killed itself"; else if (IsFemale(self)) message = "killed herself"; else message = "killed himself"; break; } } if (message && !special) { sprintf(death_msg, "%s %s\n", self->client->pers.netname, message); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_DEATH, death_msg); // AQ:TNG - JBravo: Since it's op to teamkill after rounds, why not plummet? if (deathmatch->value) { if (!teamplay->value || team_round_going || !ff_afterround->value) { Subtract_Frag(self); } } self->enemy = NULL; return; } else if (special) // handle falling with an attacker set { if (self->client->attacker && self->client->attacker->client && (self->client->attacker->client != self->client)) { sprintf(death_msg, "%s was taught how to fly by %s\n", self->client->pers.netname, self->client->attacker->client->pers.netname); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_KILL, death_msg); AddKilledPlayer(self->client->attacker, self); self->client->attacker->client->pers.num_kills++; //MODIFIED FOR FF -FB if (!((int)dmflags->value & DF_NO_FRIENDLY_FIRE) && teamplay->value && OnSameTeam(self, self->client->attacker)) { if (team_round_going || !ff_afterround->value) { // AQ:TNG - JBravo adding tkok self->enemy = self->client->attacker; // End adding tkok Add_TeamKill(self->client->attacker); Subtract_Frag(self->client->attacker); //attacker->client->resp.score--; self->client->resp.deaths++; } } else { if (!teamplay->value || !OnSameTeam(self, self->client->attacker)) { self->client->resp.streak = 0; Add_Frag(self->client->attacker); self->client->resp.deaths++; } } } else { if (IsNeutral(self)) sprintf(death_msg, "%s plummets to its death\n", self->client->pers.netname); else if (IsFemale(self)) sprintf(death_msg, "%s plummets to her death\n", self->client->pers.netname); else sprintf(death_msg, "%s plummets to his death\n", self->client->pers.netname); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_DEATH, death_msg); if (deathmatch->value) Subtract_Frag(self); //self->client->resp.score--; self->enemy = NULL; self->client->resp.deaths++; } return; } #if 0 // handle bleeding, not used because bleeding doesn't get set if (mod == MOD_BLEEDING) { sprintf(death_msg, "%s bleeds to death\n", self->client->pers.netname); PrintDeathMessage(death_msg, self); return; } #endif self->enemy = attacker; if (attacker && attacker->client) { AddKilledPlayer(attacker, self); switch (mod) { case MOD_MK23: // zucc switch (loc) { case LOC_HDAM: if (IsNeutral(self)) message = " has a hole in its head from"; else if (IsFemale(self)) message = " has a hole in her head from"; else message = " has a hole in his head from"; message2 = "'s Mark 23 pistol"; break; case LOC_CDAM: message = " loses a vital chest organ thanks to"; message2 = "'s Mark 23 pistol"; break; case LOC_SDAM: if (IsNeutral(self)) message = " loses its lunch to"; else if (IsFemale(self)) message = " loses her lunch to"; else message = " loses his lunch to"; message2 = "'s .45 caliber pistol round"; break; case LOC_LDAM: message = " is legless because of"; message2 = "'s .45 caliber pistol round"; break; default: message = " was shot by"; message2 = "'s Mark 23 Pistol"; } break; case MOD_MP5: switch (loc) { case LOC_HDAM: message = "'s brains are on the wall thanks to"; message2 = "'s 10mm MP5/10 round"; break; case LOC_CDAM: message = " feels some chest pain via"; message2 = "'s MP5/10 Submachinegun"; break; case LOC_SDAM: message = " needs some Pepto Bismol after"; message2 = "'s 10mm MP5 round"; break; case LOC_LDAM: if (IsNeutral(self)) message = " had its legs blown off thanks to"; else if (IsFemale(self)) message = " had her legs blown off thanks to"; else message = " had his legs blown off thanks to"; message2 = "'s MP5/10 Submachinegun"; break; default: message = " was shot by"; message2 = "'s MP5/10 Submachinegun"; } break; case MOD_M4: switch (loc) { case LOC_HDAM: message = " had a makeover by"; message2 = "'s M4 Assault Rifle"; break; case LOC_CDAM: message = " feels some heart burn thanks to"; message2 = "'s M4 Assault Rifle"; break; case LOC_SDAM: message = " has an upset stomach thanks to"; message2 = "'s M4 Assault Rifle"; break; case LOC_LDAM: message = " is now shorter thanks to"; message2 = "'s M4 Assault Rifle"; break; default: message = " was shot by"; message2 = "'s M4 Assault Rifle"; } break; case MOD_M3: n = rand() % 2 + 1; if (n == 1) { message = " accepts"; message2 = "'s M3 Super 90 Assault Shotgun in hole-y matrimony"; } else { message = " is full of buckshot from"; message2 = "'s M3 Super 90 Assault Shotgun"; } break; case MOD_HC: n = rand() % 2 + 1; if (n == 1) { if (attacker->client->resp.hc_mode) // AQ2:TNG Deathwatch - Single Barreled HC Death Messages { message = " underestimated"; message2 = "'s single barreled handcannon shot"; } else { message = " ate"; message2 = "'s sawed-off 12 gauge"; } } else { if (attacker->client->resp.hc_mode) // AQ2:TNG Deathwatch - Single Barreled HC Death Messages { message = " won't be able to pass a metal detector anymore thanks to"; message2 = "'s single barreled handcannon shot"; } else { message = " is full of buckshot from"; message2 = "'s sawed off shotgun"; } } break; case MOD_SNIPER: switch (loc) { case LOC_HDAM: if (self->client->ps.fov < 90) { if (IsNeutral(self)) message = " saw the sniper bullet go through its scope thanks to"; else if (IsFemale(self)) message = " saw the sniper bullet go through her scope thanks to"; else message = " saw the sniper bullet go through his scope thanks to"; } else message = " caught a sniper bullet between the eyes from"; break; case LOC_CDAM: message = " was picked off by"; break; case LOC_SDAM: message = " was sniped in the stomach by"; break; case LOC_LDAM: message = " was shot in the legs by"; break; default: message = " was sniped by"; //message2 = "'s Sniper Rifle"; } break; case MOD_DUAL: switch (loc) { case LOC_HDAM: message = " was trepanned by"; message2 = "'s akimbo Mark 23 pistols"; break; case LOC_CDAM: message = " was John Woo'd by"; //message2 = "'s .45 caliber pistol round"; break; case LOC_SDAM: message = " needs some new kidneys thanks to"; message2 = "'s akimbo Mark 23 pistols"; break; case LOC_LDAM: message = " was shot in the legs by"; message2 = "'s akimbo Mark 23 pistols"; break; default: message = " was shot by"; message2 = "'s pair of Mark 23 Pistols"; } break; case MOD_KNIFE: switch (loc) { case LOC_HDAM: if (IsNeutral(self)) message = " had its throat slit by"; else if (IsFemale(self)) message = " had her throat slit by"; else message = " had his throat slit by"; break; case LOC_CDAM: message = " had open heart surgery, compliments of"; break; case LOC_SDAM: message = " was gutted by"; break; case LOC_LDAM: message = " was stabbed repeatedly in the legs by"; break; default: message = " was slashed apart by"; message2 = "'s Combat Knife"; } break; case MOD_KNIFE_THROWN: switch (loc) { case LOC_HDAM: message = " caught"; if (IsNeutral(self)) message2 = "'s flying knife with its forehead"; else if (IsFemale(self)) message2 = "'s flying knife with her forehead"; else message2 = "'s flying knife with his forehead"; break; case LOC_CDAM: message = "'s ribs don't help against"; message2 = "'s flying knife"; break; case LOC_SDAM: if (IsNeutral(self)) message = " sees the contents of its own stomach thanks to"; else if (IsFemale(self)) message = " sees the contents of her own stomach thanks to"; else message = " sees the contents of his own stomach thanks to"; message2 = "'s flying knife"; break; case LOC_LDAM: if (IsNeutral(self)) message = " had its legs cut off thanks to"; else if (IsFemale(self)) message = " had her legs cut off thanks to"; else message = " had his legs cut off thanks to"; message2 = "'s flying knife"; break; default: message = " was hit by"; message2 = "'s flying Combat Knife"; } break; case MOD_GAS: message = " sucks down some toxic gas thanks to"; break; case MOD_KICK: n = rand() % 3 + 1; if (n == 1) { if (IsNeutral(self)) message = " got its ass kicked by"; else if (IsFemale(self)) message = " got her ass kicked by"; else message = " got his ass kicked by"; } else if (n == 2) { if (IsNeutral(self)) { message = " couldn't remove"; message2 = "'s boot from its ass"; } else if (IsFemale(self)) { message = " couldn't remove"; message2 = "'s boot from her ass"; } else { message = " couldn't remove"; message2 = "'s boot from his ass"; } } else { if (IsNeutral(self)) { message = " had a Bruce Lee put on it by"; message2 = ", with a quickness"; } else if (IsFemale(self)) { message = " had a Bruce Lee put on her by"; message2 = ", with a quickness"; } else { message = " had a Bruce Lee put on him by"; message2 = ", with a quickness"; } } break; case MOD_PUNCH: n = rand() % 3 + 1; if (n == 1) { message = " got a free facelift by"; } else if (n == 2) { message = " was knocked out by"; } else { message = " caught"; message2 = "'s iron fist"; } break; case MOD_BLASTER: message = "was blasted by"; break; case MOD_SHOTGUN: message = "was gunned down by"; break; case MOD_SSHOTGUN: message = "was blown away by"; message2 = "'s super shotgun"; break; case MOD_MACHINEGUN: message = "was machinegunned by"; break; case MOD_CHAINGUN: message = "was cut in half by"; message2 = "'s chaingun"; break; case MOD_GRENADE: message = "was popped by"; message2 = "'s grenade"; break; case MOD_G_SPLASH: message = "was shredded by"; message2 = "'s shrapnel"; break; case MOD_ROCKET: message = "ate"; message2 = "'s rocket"; break; case MOD_R_SPLASH: message = "almost dodged"; message2 = "'s rocket"; break; case MOD_HYPERBLASTER: message = "was melted by"; message2 = "'s hyperblaster"; break; case MOD_RAILGUN: message = "was railed by"; break; case MOD_BFG_LASER: message = "saw the pretty lights from"; message2 = "'s BFG"; break; case MOD_BFG_BLAST: message = "was disintegrated by"; message2 = "'s BFG blast"; break; case MOD_BFG_EFFECT: message = "couldn't hide from"; message2 = "'s BFG"; break; case MOD_HANDGRENADE: message = " caught"; message2 = "'s handgrenade"; break; case MOD_HG_SPLASH: message = " didn't see"; message2 = "'s handgrenade"; break; case MOD_HELD_GRENADE: message = " feels"; message2 = "'s pain"; break; case MOD_TELEFRAG: message = " tried to invade"; message2 = "'s personal space"; break; case MOD_GRAPPLE: message = " was caught by"; message2 = "'s grapple"; break; } //end of case (mod) if (message) { //FIREBLADE sprintf(death_msg, "%s%s %s%s\n", self->client->pers.netname, message, attacker->client->pers.netname, message2); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_KILL, death_msg); //FIREBLADE if (!deathmatch->value) return; if (ff) { if (!teamplay->value || team_round_going || !ff_afterround->value) { self->enemy = attacker; //tkok Add_TeamKill(attacker); Subtract_Frag(attacker); //attacker->client->resp.score--; self->client->resp.deaths++; } } else { if (!teamplay->value || mod != MOD_TELEFRAG) { Add_Frag(attacker); attacker->client->pers.num_kills++; self->client->resp.streak = 0; self->client->resp.deaths++; } } return; } // if(message) } sprintf(death_msg, "%s died\n", self->client->pers.netname); PrintDeathMessage(death_msg, self); IRC_printf(IRC_T_DEATH, death_msg); if (deathmatch->value){ Subtract_Frag(self); //self->client->resp.score--; self->client->resp.deaths++; } } void Touch_Item(edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf); // zucc used to toss an item on death void EjectItem(edict_t * ent, gitem_t * item) { edict_t *drop; float spread; if (item) { spread = 300.0 * crandom(); ent->client->v_angle[YAW] -= spread; drop = Drop_Item(ent, item); ent->client->v_angle[YAW] += spread; drop->spawnflags = DROPPED_PLAYER_ITEM; } } // unique weapons need to be specially treated so they respawn properly void EjectWeapon(edict_t * ent, gitem_t * item) { edict_t *drop; float spread; if (item) { spread = 300.0 * crandom(); ent->client->v_angle[YAW] -= spread; drop = Drop_Item(ent, item); ent->client->v_angle[YAW] += spread; drop->spawnflags = DROPPED_PLAYER_ITEM; drop->think = temp_think_specweap; } } //zucc toss items on death void TossItemsOnDeath(edict_t * ent) { gitem_t *item; qboolean quad; // don't bother dropping stuff when allweapons/items is active if (allitem->value && allweapon->value) { // remove the lasersight because then the observer might have it item = GET_ITEM(LASER_NUM); ent->client->pers.inventory[ITEM_INDEX(item)] = 0; return; } // don't drop weapons if allweapons is on if (allweapon->value) { DeadDropSpec(ent); return; } // only drop items if allitems is not on if (!allitem->value) DeadDropSpec(ent); else { // remove the lasersight because then the observer might have it item = GET_ITEM(LASER_NUM); ent->client->pers.inventory[ITEM_INDEX(item)] = 0; SP_LaserSight(ent, item); } if (((int) wp_flags->value & WPF_MK23) && ((int) wp_flags->value & WPF_DUAL)) { // give the player a dual pistol so they can be sure to drop one item = GET_ITEM(DUAL_NUM); ent->client->pers.inventory[ITEM_INDEX(item)]++; EjectItem(ent, item); } // check for every item we want to drop when a player dies item = GET_ITEM(MP5_NUM); while (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { ent->client->pers.inventory[ITEM_INDEX(item)]--; EjectWeapon(ent, item); } item = GET_ITEM(M4_NUM); while (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { ent->client->pers.inventory[ITEM_INDEX(item)]--; EjectWeapon(ent, item); } item = GET_ITEM(M3_NUM); while (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { ent->client->pers.inventory[ITEM_INDEX(item)]--; EjectWeapon(ent, item); } item = GET_ITEM(HC_NUM); while (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { ent->client->pers.inventory[ITEM_INDEX(item)]--; EjectWeapon(ent, item); } item = GET_ITEM(SNIPER_NUM); while (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { ent->client->pers.inventory[ITEM_INDEX(item)]--; EjectWeapon(ent, item); } item = GET_ITEM(KNIFE_NUM); if (ent->client->pers.inventory[ITEM_INDEX(item)] > 0) { EjectItem(ent, item); } // special items if (!((int) (dmflags->value) & DF_QUAD_DROP)) quad = false; else quad = (ent->client->quad_framenum > (level.framenum + 10)); if (quad) { edict_t *drop; float spread; spread = 300.0 * crandom(); ent->client->v_angle[YAW] += spread; drop = Drop_Item(ent, FindItemByClassname("item_quad")); ent->client->v_angle[YAW] -= spread; drop->spawnflags |= DROPPED_PLAYER_ITEM; drop->touch = Touch_Item; drop->nextthink = level.time + (ent->client->quad_framenum - level.framenum) * FRAMETIME; drop->think = G_FreeEdict; } #if 0 item = FindItem(SIL_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); item = FindItem(SLIP_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); item = FindItem(BAND_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); item = FindItem(KEV_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); item = FindItem(HELM_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); item = FindItem(LASER_NAME); if (ent->client->pers.inventory[ITEM_INDEX(item)]) EjectItem(ent, item); #endif } void TossClientWeapon(edict_t * self) { gitem_t *item; edict_t *drop; qboolean quad; float spread; if (!deathmatch->value) return; item = self->client->pers.weapon; if (!self->client->pers.inventory[self->client->ammo_index]) item = NULL; if (item && (strcmp(item->pickup_name, "Blaster") == 0)) item = NULL; if (!((int) (dmflags->value) & DF_QUAD_DROP)) quad = false; else quad = (self->client->quad_framenum > (level.framenum + 10)); if (item && quad) spread = 22.5; else spread = 0.0; if (item) { self->client->v_angle[YAW] -= spread; drop = Drop_Item(self, item); self->client->v_angle[YAW] += spread; drop->spawnflags = DROPPED_PLAYER_ITEM; } if (quad) { self->client->v_angle[YAW] += spread; drop = Drop_Item(self, FindItemByClassname("item_quad")); self->client->v_angle[YAW] -= spread; drop->spawnflags |= DROPPED_PLAYER_ITEM; drop->touch = Touch_Item; drop->nextthink = level.time + (self->client->quad_framenum - level.framenum) * FRAMETIME; drop->think = G_FreeEdict; } } /* ================== LookAtKiller ================== */ void LookAtKiller(edict_t * self, edict_t * inflictor, edict_t * attacker) { vec3_t dir; if (attacker && attacker != world && attacker != self) { VectorSubtract(attacker->s.origin, self->s.origin, dir); } else if (inflictor && inflictor != world && inflictor != self) { VectorSubtract(inflictor->s.origin, self->s.origin, dir); } else { self->client->killer_yaw = self->s.angles[YAW]; return; } // NEW FORMULA FOR THIS FROM 3.20 -FB if (dir[0]) self->client->killer_yaw = 180 / M_PI * atan2(dir[1], dir[0]); else { self->client->killer_yaw = 0; if (dir[1] > 0) self->client->killer_yaw = 90; else if (dir[1] < 0) self->client->killer_yaw = -90; } if (self->client->killer_yaw < 0) self->client->killer_yaw += 360; // ^^^ } /* ================== player_die ================== */ void player_die(edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { int n; VectorClear(self->avelocity); self->takedamage = DAMAGE_YES; self->movetype = MOVETYPE_TOSS; //FIREBLADE if (self->solid == SOLID_TRIGGER) { self->solid = SOLID_BBOX; gi.linkentity(self); RemoveFromTransparentList(self); } //FIREBLADE // zucc solves problem of people stopping doors while in their dead bodies // // ...only need it in DM though... // ...for teamplay, non-solid will get set soon after in CopyToBodyQue if (!teamplay->value || ctf->value || teamdm->value) { self->solid = SOLID_NOT; gi.linkentity(self); } self->s.modelindex2 = 0; // remove linked weapon model self->s.modelindex3 = 0; // remove linked ctf flag self->s.angles[0] = 0; self->s.angles[2] = 0; self->s.sound = 0; self->client->weapon_sound = 0; self->client->reload_attempts = 0; // stop them from trying to reload self->client->weapon_attempts = 0; //TempFile self->client->desired_zoom = 0; self->client->autoreloading = false; //TempFile self->maxs[2] = -8; self->svflags |= SVF_DEADMONSTER; if (!self->deadflag) { if (ctf->value) { self->client->respawn_time = level.time + CTFGetRespawnTime(self); } else if(teamdm->value) { self->client->respawn_time = level.time + teamdm_respawn->value; } else { self->client->respawn_time = level.time + 1.0; } LookAtKiller(self, inflictor, attacker); self->client->ps.pmove.pm_type = PM_DEAD; ClientObituary(self, inflictor, attacker); if (ctf->value) CTFFragBonuses(self, inflictor, attacker); //TossClientWeapon (self); TossItemsOnDeath(self); if (ctf->value) CTFDeadDropFlag(self); // let's be safe, if the player was killed and grapple disabled before it CTFPlayerResetGrapple(self); //FIREBLADE if (deathmatch->value && !teamplay->value) //FIREBLADE Cmd_Help_f(self); // show scores // always reset chase to killer, even if NULL if(limchasecam->value < 2 && attacker && attacker->client) self->client->resp.last_chase_target = attacker; } // remove powerups self->client->quad_framenum = 0; self->client->invincible_framenum = 0; self->client->breather_framenum = 0; self->client->enviro_framenum = 0; //zucc remove lasersight if (self->lasersight) SP_LaserSight(self, NULL); // TNG Turn Flashlight off if (self->flashlight) FL_make(self); //FIREBLADE // clean up sniper rifle stuff self->client->no_sniper_display = 0; self->client->resp.sniper_mode = SNIPER_1X; self->client->desired_fov = 90; self->client->ps.fov = 90; //FIREBLADE //SLIC2: Removed this from here //self->client->resp.streak = 0; //SLIC2 Bandage(self); // clear up the leg damage when dead sound? self->client->bandage_stopped = 0; // clear inventory memset(self->client->pers.inventory, 0, sizeof(self->client->pers.inventory)); // zucc - check if they have a primed grenade if (self->client->curr_weap == GRENADE_NUM && ((self->client->ps.gunframe >= GRENADE_IDLE_FIRST && self->client->ps.gunframe <= GRENADE_IDLE_LAST) || (self->client->ps.gunframe >= GRENADE_THROW_FIRST && self->client->ps.gunframe <= GRENADE_THROW_LAST))) { self->client->ps.gunframe = 0; // Reset Grenade Damage to 1.52 when requested: if (use_classic->value) fire_grenade2(self, self->s.origin, vec3_origin, 170, 0, 2, 170 * 2, false); else fire_grenade2(self, self->s.origin, vec3_origin, GRENADE_DAMRAD, 0, 2, GRENADE_DAMRAD * 2, false); } // Gibbing on really hard HC hit if ((((self->health < -35) && (meansOfDeath == MOD_HC)) || ((self->health < -20) && (meansOfDeath == MOD_M3))) && (sv_gib->value)) { gi.sound(self, CHAN_BODY, gi.soundindex("misc/udeath.wav"), 1, ATTN_NORM, 0); for (n = 0; n < 5; n++) ThrowGib(self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); ThrowClientHead(self, damage); self->client->anim_priority = ANIM_DEATH; self->client->anim_end = 0; self->takedamage = DAMAGE_NO; } else { // normal death if (!self->deadflag) { static int i; i = (i + 1) % 3; // start a death animation self->client->anim_priority = ANIM_DEATH; if (self->client->ps.pmove.pm_flags & PMF_DUCKED) { self->s.frame = FRAME_crdeath1 - 1; self->client->anim_end = FRAME_crdeath5; } else switch (i) { case 0: self->s.frame = FRAME_death101 - 1; self->client->anim_end = FRAME_death106; break; case 1: self->s.frame = FRAME_death201 - 1; self->client->anim_end = FRAME_death206; break; case 2: self->s.frame = FRAME_death301 - 1; self->client->anim_end = FRAME_death308; break; } if ((meansOfDeath == MOD_SNIPER) || (meansOfDeath == MOD_KNIFE) || (meansOfDeath == MOD_KNIFE_THROWN)) { gi.sound(self, CHAN_VOICE, gi.soundindex("misc/glurp.wav"), 1, ATTN_NORM, 0); // TempFile - BEGIN sniper gibbing if (meansOfDeath == MOD_SNIPER) { int n; switch (locOfDeath) { case LOC_HDAM: if (sv_gib->value) { for (n = 0; n < 8; n++) ThrowGib(self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); ThrowClientHead(self, damage); } } } } else gi.sound(self, CHAN_VOICE, gi.soundindex(va("*death%i.wav", (rand() % 4) + 1)), 1, ATTN_NORM, 0); } } // zucc this will fix a jump kick death generating a weapon self->client->curr_weap = MK23_NUM; //PG BUND - BEGIN self->client->resp.idletime = 0; // self->client->resp.last_killed_target = NULL; ResetKills(self); //PG BUND - END //AQ2:TNG Slicer Last Damage Location self->client->resp.last_damaged_part = 0; self->client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END //TempFile self->client->pers.num_kills = 0; //TempFile self->deadflag = DEAD_DEAD; gi.linkentity(self); // in ctf, when a player dies check if he should be moved to the other team if(ctf->value) CheckForUnevenTeams(self); } //======================================================================= /* ============== InitClientPersistant This is only called when the game first initializes in single player, but is called after each death and level change in deathmatch ============== */ // SLIC2 If pers structure gets memset to 0 lets cleannup unecessary initiations ( to 0 ) here void InitClientPersistant(gclient_t * client) { gitem_t *item; /* client_persistant_t oldpers; //FB 6/3/99 memcpy(oldpers, pers, sizeof(client->pers)); //FB 6/3/99 */ memset(&client->pers, 0, sizeof(client->pers)); // changed to mk23 item = GET_ITEM(MK23_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->pers.lastweapon = item; if ((int) wp_flags->value & WPF_KNIFE) { item = GET_ITEM(KNIFE_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; if (!(int) wp_flags->value & WPF_MK23) { client->pers.selected_item = ITEM_INDEX(item); client->pers.weapon = item; client->pers.lastweapon = item; } } client->pers.health = 100; client->pers.max_health = 100; //zucc changed maximum ammo amounts client->pers.max_bullets = 2; client->pers.max_shells = 14; client->pers.max_rockets = 2; client->pers.max_grenades = 50; client->pers.max_cells = 1; client->pers.max_slugs = 20; client->knife_max = 10; client->grenade_max = 2; client->pers.connected = true; //zucc client->fired = 0; client->burst = 0; client->fast_reload = 0; client->machinegun_shots = 0; client->unique_weapon_total = 0; client->unique_item_total = 0; if ((int) wp_flags->value & WPF_MK23) { client->curr_weap = MK23_NUM; } else if ((int) wp_flags->value & WPF_KNIFE) { client->curr_weap = KNIFE_NUM; } else { client->curr_weap = MK23_NUM; } //AQ2:TNG - Slicer Moved This To Here //client->pers.num_kills = 0; //AQ2:TNG END // AQ2:TNG - JBravo adding UVtime client->ctf_uvtime = 0; } // SLIC2 If resp structure gets memset to 0 lets cleannup unecessary initiations ( to 0 ) here void InitClientResp(gclient_t * client) { int team = client->resp.team; gitem_t *item = client->resp.item; gitem_t *weapon = client->resp.weapon; qboolean menu_shown = client->resp.menu_shown; qboolean dm_selected = client->resp.dm_selected; memset(&client->resp, 0, sizeof(client->resp)); client->resp.team = team; client->resp.enterframe = level.framenum; client->resp.coop_respawn = client->pers; if (!dm_choose->value) { if ((int) wp_flags->value & WPF_MP5) { client->resp.weapon = GET_ITEM(MP5_NUM); } else if ((int) wp_flags->value & WPF_MK23) { client->resp.weapon = GET_ITEM(MK23_NUM); } else if ((int) wp_flags->value & WPF_KNIFE) { client->resp.weapon = GET_ITEM(KNIFE_NUM); } else { client->resp.weapon = GET_ITEM(MK23_NUM); } client->resp.item = GET_ITEM(KEV_NUM); } else { if (wp_flags->value < 2) client->resp.weapon = GET_ITEM(MK23_NUM); } client->resp.ir = 1; if (!teamplay->value && auto_equip->value) { client->resp.menu_shown = menu_shown; } client->resp.dm_selected = dm_selected; // TNG:Freud, restore weapons and items from last map. if (auto_equip->value && ((teamplay->value && !teamdm->value) || dm_choose->value) && ctf->value != 2) { if (item) client->resp.item = item; if (weapon) client->resp.weapon = weapon; } client->resp.team = NOTEAM; // TNG:Freud, restore team from previous map if (auto_join->value && team) client->resp.saved_team = team; //TempFile - BEGIN client->resp.punch_desired = false; //client->resp.fire_time = 0; //client->resp.ignore_time = 0; //client->pers.num_kills = 0; AQ2:TNG Moved This to InitClientPersistant //TempFile - END //PG BUND - BEGIN // client->resp.last_killed_target = NULL; // ResetKills(ent); //client->resp.idletime = 0; //PG BUND - END //AQ2:TNG - Slicer : Reset Video Cheking vars //memset(client->resp.vidref, 0, sizeof(client->resp.vidref)); //memset(client->resp.gldriver, 0, sizeof(client->resp.gldriver)); //client->resp.gllockpvs = 0; //client->resp.glclear = 0; client->resp.gldynamic = 1; //client->resp.glmodulate = 0; client->resp.checked = false; //memset(&client->resp.checktime, 0, sizeof(client->resp.checktime)); //memset(&client->resp.rd_when, 0, sizeof(client->resp.rd_when)); //memset(client->resp.rd_rep, 0, sizeof(client->resp.rd_rep)); //client->resp.rd_mute = 0; //client->resp.rd_repcount = 0; //client->resp.rd_reptime = 0; //AQ2:TNG END //AQ2:TNG Slicer Last Damage Location //client->resp.last_damaged_part = 0; //client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END //AQ2:TNG Slicer Moved this to here //client->resp.killed_teammates = 0; //client->resp.idletime = 0; //AQ2:TNG END //AQ2:TNG Slicer - Matchmode //client->resp.subteam = 0; //client->resp.captain = 0; //client->resp.admin = 0; //client->resp.stat_mode_intermission = 0; //AQ2:TNG END // No automatic team join // if (ctf->value && client->resp.team < TEAM1) // CTFAssignTeam(client); } /* ================== SaveClientData Some information that should be persistant, like health, is still stored in the edict structure, so it needs to be mirrored out to the client structure before all the edicts are wiped. ================== */ void SaveClientData(void) { int i; edict_t *ent; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (!ent->inuse) continue; game.clients[i].pers.health = ent->health; game.clients[i].pers.max_health = ent->max_health; game.clients[i].pers.powerArmorActive = (ent->flags & FL_POWER_ARMOR); if (coop->value) game.clients[i].pers.score = ent->client->resp.score; } } void FetchClientEntData(edict_t * ent) { ent->health = ent->client->pers.health; ent->max_health = ent->client->pers.max_health; if (ent->client->pers.powerArmorActive) ent->flags |= FL_POWER_ARMOR; if (coop->value) ent->client->resp.score = ent->client->pers.score; } /* ======================================================================= SelectSpawnPoint ======================================================================= */ /* ================ PlayersRangeFromSpot Returns the distance to the nearest player from the given spot ================ */ float PlayersRangeFromSpot(edict_t * spot) { edict_t *player; float playerdistance, bestplayerdistance = 9999999; int n; for (n = 1; n <= maxclients->value; n++) { player = &g_edicts[n]; if (!player->inuse) continue; if (player->health <= 0) continue; playerdistance = Distance(spot->s.origin, player->s.origin); if (playerdistance < bestplayerdistance) bestplayerdistance = playerdistance; } return bestplayerdistance; } /* ================ SelectRandomDeathmatchSpawnPoint go to a random point, but NOT the two points closest to other players ================ */ edict_t *SelectRandomDeathmatchSpawnPoint(void) { edict_t *spot, *spot1, *spot2; int count = 0; int selection; float range, range1, range2; spot = NULL; range1 = range2 = 99999; spot1 = spot2 = NULL; while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { count++; range = PlayersRangeFromSpot(spot); if (range < range1) { if (range1 < range2) { range2 = range1; spot2 = spot1; } range1 = range; spot1 = spot; } else if (range < range2) { range2 = range; spot2 = spot; } } if (!count) return NULL; if (count <= 2) { spot1 = spot2 = NULL; } else count -= 2; selection = rand() % count; spot = NULL; do { spot = G_Find(spot, FOFS(classname), "info_player_deathmatch"); if (spot == spot1 || spot == spot2) selection++; } while (selection--); return spot; } /* ================ SelectFarthestDeathmatchSpawnPoint ================ */ edict_t *SelectFarthestDeathmatchSpawnPoint(void) { edict_t *bestspot; float bestdistance, bestplayerdistance; edict_t *spot; spot = NULL; bestspot = NULL; bestdistance = 0; while ((spot = G_Find(spot, FOFS(classname), "info_player_deathmatch")) != NULL) { bestplayerdistance = PlayersRangeFromSpot(spot); if (bestplayerdistance > bestdistance) { bestspot = spot; bestdistance = bestplayerdistance; } } if (bestspot) { return bestspot; } // if there is a player just spawned on each and every start spot // we have no choice to turn one into a telefrag meltdown spot = G_Find(NULL, FOFS(classname), "info_player_deathmatch"); return spot; } edict_t *SelectDeathmatchSpawnPoint(void) { if ((int) (dmflags->value) & DF_SPAWN_FARTHEST) return SelectFarthestDeathmatchSpawnPoint(); else return SelectRandomDeathmatchSpawnPoint(); } edict_t *SelectCoopSpawnPoint(edict_t * ent) { int index; edict_t *spot = NULL; char *target; index = ent->client - game.clients; // player 0 starts in normal player spawn point if (!index) return NULL; spot = NULL; // assume there are four coop spots at each spawnpoint while (1) { spot = G_Find(spot, FOFS(classname), "info_player_coop"); if (!spot) return NULL; // we didn't have enough... target = spot->targetname; if (!target) target = ""; if (Q_stricmp(game.spawnpoint, target) == 0) { // this is a coop spawn point for one of the clients here index--; if (!index) return spot; // this is it } } return spot; } /* =========== SelectSpawnPoint Chooses a player start, deathmatch start, coop start, etc ============ */ void SelectSpawnPoint(edict_t * ent, vec3_t origin, vec3_t angles) { edict_t *spot = NULL; //FIREBLADE if (ctf->value) spot = SelectCTFSpawnPoint(ent); else if (teamplay->value && !teamdm->value && ent->client->resp.team != NOTEAM) { spot = SelectTeamplaySpawnPoint(ent); } else { //FIREBLADE if (deathmatch->value) spot = SelectDeathmatchSpawnPoint(); else if (coop->value) spot = SelectCoopSpawnPoint(ent); } // find a single player start spot if (!spot) { //FIREBLADE if (deathmatch->value) { gi.dprintf("Warning: failed to find deathmatch spawn point\n"); } //FIREBLADE while ((spot = G_Find(spot, FOFS(classname), "info_player_start")) != NULL) { if (!game.spawnpoint[0] && !spot->targetname) break; if (!game.spawnpoint[0] || !spot->targetname) continue; if (Q_stricmp(game.spawnpoint, spot->targetname) == 0) break; } if (!spot) { if (!game.spawnpoint[0]) { // there wasn't a spawnpoint without a target, so use any spot = G_Find(spot, FOFS(classname), "info_player_start"); } if (!spot) gi.error("Couldn't find spawn point %s\n", game.spawnpoint); } } VectorCopy(spot->s.origin, origin); origin[2] += 9; VectorCopy(spot->s.angles, angles); } //====================================================================== void InitBodyQue(void) { int i; edict_t *ent; level.body_que = 0; for (i = 0; i < BODY_QUEUE_SIZE; i++) { ent = G_Spawn(); ent->classname = "bodyque"; } } void body_die(edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { /* int n;*/ if (self->health < -40) { // remove gibbing /* gi.sound (self, CHAN_BODY, gi.soundindex ("misc/udeath.wav"), 1, ATTN_NORM, 0); for (n= 0; n < 4; n++) ThrowGib (self, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); self->s.origin[2] -= 48; ThrowClientHead (self, damage);*/ self->takedamage = DAMAGE_NO; } } void CopyToBodyQue(edict_t * ent) { edict_t *body; // grab a body que and cycle to the next one body = &g_edicts[(int) maxclients->value + level.body_que + 1]; level.body_que = (level.body_que + 1) % BODY_QUEUE_SIZE; // FIXME: send an effect on the removed body gi.unlinkentity(ent); gi.unlinkentity(body); body->s = ent->s; body->s.number = body - g_edicts; body->svflags = ent->svflags; VectorCopy(ent->mins, body->mins); VectorCopy(ent->maxs, body->maxs); VectorCopy(ent->absmin, body->absmin); VectorCopy(ent->absmax, body->absmax); VectorCopy(ent->size, body->size); // All our bodies will be non-solid -FB body->solid = SOLID_NOT; //body->solid = ent->solid; body->clipmask = ent->clipmask; body->owner = ent->owner; //FB 5/31/99 body->movetype = MOVETYPE_TOSS; // just in case? // body->movetype = ent->movetype; VectorCopy(ent->velocity, body->velocity); body->mass = ent->mass; body->groundentity = NULL; //FB 5/31/99 //FB 6/1/99 body->s.renderfx = 0; //FB body->die = body_die; body->takedamage = DAMAGE_YES; //PG BUND - BEGIN //Disable to be seen by irvision body->s.renderfx &= ~RF_IR_VISIBLE; //PG BUND - END gi.linkentity(body); } void CleanBodies() { edict_t *ptr; int i; ptr = g_edicts + game.maxclients + 1; i = 0; while (i < BODY_QUEUE_SIZE) { gi.unlinkentity(ptr); ptr->solid = SOLID_NOT; ptr->movetype = MOVETYPE_NOCLIP; ptr->svflags |= SVF_NOCLIENT; ptr++; i++; } } void respawn(edict_t * self) { if (deathmatch->value || coop->value) { //FIREBLADE if (self->solid != SOLID_NOT || self->deadflag == DEAD_DEAD) //FIREBLADE CopyToBodyQue(self); PutClientInServer(self); if (ctf->value || teamdm->value) AddToTransparentList(self); //FIREBLADE self->svflags &= ~SVF_NOCLIENT; //FIREBLADE // Disable all this... -FB // // add a teleportation effect // self->s.event = EV_PLAYER_TELEPORT; // // // hold in place briefly // self->client->ps.pmove.pm_flags = PMF_TIME_TELEPORT; // self->client->ps.pmove.pm_time = 14; if(respawn_effect->value) { gi.WriteByte(svc_muzzleflash); gi.WriteShort(self - g_edicts); gi.WriteByte(MZ_RESPAWN); gi.multicast(self->s.origin, MULTICAST_PVS); } self->client->respawn_time = level.time + 2; return; } // restart the entire server gi.AddCommandString("menu_loadgame\n"); } //============================================================== void AllWeapons(edict_t * ent) { int i; gitem_t *it; for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_WEAPON)) continue; switch(it->typeNum) { case MK23_NUM: if ((int)wp_flags->value & WPF_MK23) { ent->client->pers.inventory[i] = 1; ent->client->mk23_rds = ent->client->mk23_max; } break; case MP5_NUM: if ((int)wp_flags->value & WPF_MP5) { ent->client->pers.inventory[i] = 1; ent->client->mp5_rds = ent->client->mp5_max; } break; case M4_NUM: if ((int)wp_flags->value & WPF_M4) { ent->client->pers.inventory[i] = 1; ent->client->m4_rds = ent->client->m4_max; } break; case M3_NUM: if ((int)wp_flags->value & WPF_M3) { ent->client->pers.inventory[i] = 1; ent->client->shot_rds = ent->client->shot_max; } break; case HC_NUM: if ((int)wp_flags->value & WPF_HC) { ent->client->pers.inventory[i] = 1; ent->client->cannon_rds = ent->client->cannon_max; ent->client->shot_rds = ent->client->shot_max; } break; case SNIPER_NUM: if ((int)wp_flags->value & WPF_SNIPER) { ent->client->pers.inventory[i] = 1; ent->client->sniper_rds = ent->client->sniper_max; } break; case DUAL_NUM: if ((int)wp_flags->value & WPF_DUAL) { ent->client->pers.inventory[i] = 1; ent->client->dual_rds = ent->client->dual_max; } break; case KNIFE_NUM: if ((int)wp_flags->value & WPF_KNIFE) { ent->client->pers.inventory[i] = 10; } break; case GRENADE_NUM: if ((int)wp_flags->value & WPF_GRENADE) { ent->client->pers.inventory[i] = tgren->value; } break; } } for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_AMMO)) continue; Add_Ammo(ent, it, 1000); } } void AllItems(edict_t * ent) { edict_t etemp; int i; gitem_t *it; for (i = 0; i < game.num_items; i++) { it = itemlist + i; if (!it->pickup) continue; if (!(it->flags & IT_ITEM)) continue; etemp.item = it; if (ent->client->unique_item_total >= unique_items->value) ent->client->unique_item_total = unique_items->value - 1; Pickup_Special(&etemp, ent); } } // equips a client with item/weapon in teamplay void EquipClient(edict_t * ent) { gclient_t *client; gitem_t *item; edict_t etemp; int band = 0; client = ent->client; if (!(client->resp.item) || !(client->resp.weapon)) return; if(use_grapple->value) client->pers.inventory[ITEM_INDEX(FindItem("Grapple"))] = 1; if (client->resp.item->typeNum == BAND_NUM) { band = 1; if (tgren->value > 0) // team grenades is turned on { item = GET_ITEM(GRENADE_NUM); client->pers.inventory[ITEM_INDEX(item)] = tgren->value; } } // set them up with initial pistol ammo if ((int)wp_flags->value & WPF_MK23) { item = GET_ITEM(MK23_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 2; else client->pers.inventory[ITEM_INDEX(item)] = 1; } if (client->resp.weapon->typeNum == MP5_NUM) { item = GET_ITEM(MP5_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->curr_weap = MP5_NUM; client->unique_weapon_total = 1; item = GET_ITEM(MP5_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 2; else client->pers.inventory[ITEM_INDEX(item)] = 1; client->mp5_rds = client->mp5_max; } else if (client->resp.weapon->typeNum == M4_NUM) { item = GET_ITEM(M4_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->curr_weap = M4_NUM; client->unique_weapon_total = 1; item = GET_ITEM(M4_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 2; else client->pers.inventory[ITEM_INDEX(item)] = 1; client->m4_rds = client->m4_max; } else if (client->resp.weapon->typeNum == M3_NUM) { item = GET_ITEM(M3_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->curr_weap = M3_NUM; client->unique_weapon_total = 1; item = GET_ITEM(SHELL_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 14; else client->pers.inventory[ITEM_INDEX(item)] = 7; client->shot_rds = client->shot_max; } else if (client->resp.weapon->typeNum == HC_NUM) { item = GET_ITEM(HC_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->curr_weap = HC_NUM; client->unique_weapon_total = 1; item = GET_ITEM(SHELL_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 24; else client->pers.inventory[ITEM_INDEX(item)] = 12; client->cannon_rds = client->cannon_max; } else if (client->resp.weapon->typeNum == SNIPER_NUM) { item = GET_ITEM(SNIPER_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[ITEM_INDEX(item)] = 1; client->pers.weapon = item; client->curr_weap = SNIPER_NUM; client->unique_weapon_total = 1; item = GET_ITEM(SNIPER_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 20; else client->pers.inventory[ITEM_INDEX(item)] = 10; client->sniper_rds = client->sniper_max; } else if (client->resp.weapon->typeNum == DUAL_NUM) { item = GET_ITEM(DUAL_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->curr_weap = DUAL_NUM; item = GET_ITEM(MK23_ANUM); if (band) client->pers.inventory[ITEM_INDEX(item)] = 4; else client->pers.inventory[ITEM_INDEX(item)] = 2; client->dual_rds = client->dual_max; } else if (client->resp.weapon->typeNum == KNIFE_NUM) { item = GET_ITEM(KNIFE_NUM); client->pers.selected_item = ITEM_INDEX(item); if (band) client->pers.inventory[client->pers.selected_item] = 20; else client->pers.inventory[client->pers.selected_item] = 10; client->pers.weapon = item; client->curr_weap = KNIFE_NUM; } etemp.item = client->resp.item; Pickup_Special(&etemp, ent); } // Igor[Rock] start void EquipClientDM(edict_t * ent) { gclient_t *client; gitem_t *item; client = ent->client; if(use_grapple->value) client->pers.inventory[ITEM_INDEX(FindItem("Grapple"))] = 1; if (!Q_stricmp(strtwpn->string, MK23_NAME)) return; // Give some ammo for the weapon if (Q_stricmp(strtwpn->string, MP5_NAME) == 0) { item = GET_ITEM(MP5_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->mp5_rds = client->mp5_max; client->curr_weap = MP5_NUM; if (!allweapon->value) { client->unique_weapon_total = 1; } item = GET_ITEM(MP5_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 1; } else if (Q_stricmp(strtwpn->string, M4_NAME) == 0) { item = GET_ITEM(M4_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->m4_rds = client->m4_max; client->curr_weap = M4_NUM; if (!allweapon->value) { client->unique_weapon_total = 1; } item = GET_ITEM(M4_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 1; } else if (Q_stricmp(strtwpn->string, M3_NAME) == 0) { item = GET_ITEM(M3_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->shot_rds = client->shot_max; client->curr_weap = M3_NUM; if (!allweapon->value) { client->unique_weapon_total = 1; } item = GET_ITEM(SHELL_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 7; } else if (Q_stricmp(strtwpn->string, HC_NAME) == 0) { item = GET_ITEM(HC_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->cannon_rds = client->cannon_max; client->shot_rds = client->shot_max; client->curr_weap = HC_NUM; if (!allweapon->value) { client->unique_weapon_total = 1; } item = GET_ITEM(SHELL_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 12; } else if (Q_stricmp(strtwpn->string, SNIPER_NAME) == 0) { item = GET_ITEM(SNIPER_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->sniper_rds = client->sniper_max; client->curr_weap = SNIPER_NUM; if (!allweapon->value) { client->unique_weapon_total = 1; } item = GET_ITEM(SNIPER_ANUM);; client->pers.inventory[ITEM_INDEX(item)] = 10; } else if (Q_stricmp(strtwpn->string, DUAL_NAME) == 0) { item = GET_ITEM(DUAL_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 1; client->pers.weapon = item; client->dual_rds = client->dual_max; client->mk23_rds = client->mk23_max; client->curr_weap = DUAL_NUM; item = GET_ITEM(MK23_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 2; } else if (Q_stricmp(strtwpn->string, GRENADE_NAME) == 0) { item = GET_ITEM(GRENADE_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = tgren->value; client->pers.weapon = item; client->curr_weap = GRENADE_NUM; } else if (Q_stricmp(strtwpn->string, KNIFE_NAME) == 0) { item = GET_ITEM(KNIFE_NUM); client->pers.selected_item = ITEM_INDEX(item); client->pers.inventory[client->pers.selected_item] = 10; client->pers.weapon = item; client->curr_weap = KNIFE_NUM; } } // Igor[Rock] ende /* =========== PutClientInServer Called when a player connects to a server or respawns in a deathmatch. ============ */ void PutClientInServer(edict_t * ent) { vec3_t mins = { -16, -16, -24 }; vec3_t maxs = { 16, 16, 32 }; int index; vec3_t spawn_origin, spawn_angles; gclient_t *client; int going_observer; int i; client_persistant_t saved; client_respawn_t resp; // zucc for ammo // gitem_t *item; //FF int save_team_wounds; int save_team_kills; char save_ipaddr[100]; //FF // find a spawn point // do it before setting health back up, so farthest // ranging doesn't count this client SelectSpawnPoint(ent, spawn_origin, spawn_angles); index = ent - g_edicts - 1; client = ent->client; // deathmatch wipes most client data every spawn if (deathmatch->value) { char userinfo[MAX_INFO_STRING]; resp = client->resp; memcpy(userinfo, client->pers.userinfo, sizeof(userinfo)); InitClientPersistant(client); ClientUserinfoChanged(ent, userinfo); } else if (coop->value) { int n; char userinfo[MAX_INFO_STRING]; resp = client->resp; memcpy(userinfo, client->pers.userinfo, sizeof(userinfo)); // this is kind of ugly, but it's how we want to handle keys in coop for (n = 0; n < MAX_ITEMS; n++) { if (itemlist[n].flags & IT_KEY) resp.coop_respawn.inventory[n] = client->pers.inventory[n]; } client->pers = resp.coop_respawn; ClientUserinfoChanged(ent, userinfo); if (resp.score > client->pers.score) client->pers.score = resp.score; } else { memset(&resp, 0, sizeof(resp)); } // clear everything but the persistant data saved = client->pers; //FF save_team_wounds = client->team_wounds; save_team_kills = client->team_kills; if (client->ipaddr) strcpy(save_ipaddr, client->ipaddr); //FF memset(client, 0, sizeof(*client)); client->pers = saved; //FF client->team_wounds = save_team_wounds; client->team_kills = save_team_kills; if (save_ipaddr && client->ipaddr) strcpy(client->ipaddr, save_ipaddr); //FF if (client->pers.health <= 0) InitClientPersistant(client); client->resp = resp; // copy some data from the client to the entity FetchClientEntData(ent); // clear entity values ent->groundentity = NULL; ent->client = &game.clients[index]; ent->takedamage = DAMAGE_AIM; ent->movetype = MOVETYPE_WALK; ent->viewheight = 22; ent->inuse = true; ent->classname = "player"; ent->mass = 200; ent->solid = SOLID_BBOX; ent->deadflag = DEAD_NO; ent->air_finished = level.time + 12; ent->clipmask = MASK_PLAYERSOLID; ent->model = "players/male/tris.md2"; ent->pain = player_pain; ent->die = player_die; ent->waterlevel = 0; ent->watertype = 0; ent->flags &= ~FL_NO_KNOCKBACK; ent->svflags &= ~SVF_DEADMONSTER; //FIREBLADE if (!teamplay->value || ent->client->resp.team != NOTEAM) { ent->flags &= ~FL_GODMODE; ent->svflags &= ~SVF_NOCLIENT; } //FIREBLADE VectorCopy(mins, ent->mins); VectorCopy(maxs, ent->maxs); VectorClear(ent->velocity); // clear playerstate values memset(&ent->client->ps, 0, sizeof(client->ps)); client->ps.pmove.origin[0] = spawn_origin[0] * 8; client->ps.pmove.origin[1] = spawn_origin[1] * 8; client->ps.pmove.origin[2] = spawn_origin[2] * 8; if (ctf->value) { //AQ2:TNG Igor not quite sure about this (FIXME) client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; //AQ2:TNG End } if (deathmatch->value && ((int) dmflags->value & DF_FIXED_FOV)) { client->ps.fov = 90; } else { client->ps.fov = atoi(Info_ValueForKey(client->pers.userinfo, "fov")); if (client->ps.fov < 1) client->ps.fov = 90; else if (client->ps.fov > 160) client->ps.fov = 160; } client->ps.gunindex = gi.modelindex(client->pers.weapon->view_model); // clear entity state values ent->s.effects = 0; ent->s.skinnum = ent - g_edicts - 1; ent->s.modelindex = 255; // will use the skin specified model // zucc vwep //ent->s.modelindex2 = 255; // custom gun model ShowGun(ent); ent->s.frame = 0; VectorCopy(spawn_origin, ent->s.origin); ent->s.origin[2] += 1; // make sure off ground VectorCopy(ent->s.origin, ent->s.old_origin); // set the delta angle for (i = 0; i < 3; i++) client->ps.pmove.delta_angles[i] = ANGLE2SHORT(spawn_angles[i] - client->resp.cmd_angles[i]); ent->s.angles[PITCH] = 0; ent->s.angles[YAW] = spawn_angles[YAW]; ent->s.angles[ROLL] = 0; VectorCopy(ent->s.angles, client->ps.viewangles); VectorCopy(ent->s.angles, client->v_angle); //FIREBLADE if (teamplay->value) { going_observer = StartClient(ent); } else { going_observer = ent->client->pers.spectator; if (dm_choose->value && !ent->client->resp.dm_selected) going_observer = 1; if (going_observer) { ent->movetype = MOVETYPE_NOCLIP; ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->client->resp.team = NOTEAM; ent->client->ps.gunindex = 0; } } // AQ2:TNG - JBravo adding UVtime if (ctf->value) { if (team_round_going && !lights_camera_action && uvtime->value && ent->client->resp.team != NOTEAM) { ent->client->ctf_uvtime = uvtime->value; } } //FIREBLADE if (!going_observer && !teamplay->value) { // this handles telefrags... if (dm_shield->value && (!teamplay->value || (teamdm->value && team_round_going && !lights_camera_action)) && uvtime->value) { ent->client->ctf_uvtime = uvtime->value; } KillBox(ent); } //FIREBLADE gi.linkentity(ent); //zucc give some ammo //item = FindItem("Pistol Clip"); // Add_Ammo(ent,item,1); client->mk23_max = 12; client->mp5_max = 30; client->m4_max = 24; client->shot_max = 7; client->sniper_max = 6; client->cannon_max = 2; client->dual_max = 24; if ((int) wp_flags->value & WPF_MK23) { client->mk23_rds = client->mk23_max; client->dual_rds = client->mk23_max; } else { client->mk23_rds = 0; client->dual_rds = 0; } client->knife_max = 10; client->grenade_max = 2; ent->lasersight = NULL; //other client->resp.sniper_mode = SNIPER_1X; client->bandaging = 0; client->leg_damage = 0; client->leg_noise = 0; client->leg_dam_count = 0; client->desired_fov = 90; client->ps.fov = 90; client->idle_weapon = 0; client->drop_knife = 0; client->no_sniper_display = 0; client->knife_sound = 0; client->doortoggle = 0; client->have_laser = 0; client->reload_attempts = 0; client->weapon_attempts = 0; //TempFile client->desired_zoom = 0; client->autoreloading = false; //TempFile //FIREBLADE if (!going_observer) { // items up here so that the bandolier will change equipclient below if (allitem->value) { AllItems(ent); } if ((teamplay->value && !teamdm->value && ctf->value != 2) || (!ctf->value && dm_choose->value)) EquipClient(ent); else if (deathmatch->value) EquipClientDM(ent); if (ent->client->menu) { PMenu_Close(ent); return; } //FIREBLADE if (allweapon->value) { AllWeapons(ent); } // force the current weapon up client->newweapon = client->pers.weapon; ChangeWeapon(ent); //FIREBLADE if (teamplay->value) { ent->solid = SOLID_TRIGGER; gi.linkentity(ent); } //FIREBLADE } } /* ===================== ClientBeginDeathmatch A client has just connected to the server in deathmatch mode, so clear everything out before starting them. ===================== */ void ClientBeginDeathmatch(edict_t * ent) { G_InitEdict(ent); InitClientResp(ent->client); //PG BUND - BEGIN ent->client->resp.team = NOTEAM; // if no auto equip, prompt for new weapon on level change if (!auto_equip->value) ent->client->resp.dm_selected = 0; /*client->resp.last_killed_target = NULL; client->resp.killed_teammates = 0; client->resp.idletime = 0; - AQ2:TNG Slicer Moved this to InitClientResp */ ResetKills(ent); TourneyNewPlayer(ent); vInitClient(ent); //PG BUND - END // locate ent at a spawn point PutClientInServer(ent); // FROM 3.20 -FB if (level.intermissiontime) { MoveClientToIntermission(ent); } else { // ^^^ if (!teamplay->value && !dm_choose->value) { //FB 5/31/99 // send effect gi.WriteByte(svc_muzzleflash); gi.WriteShort(ent - g_edicts); gi.WriteByte(MZ_LOGIN); gi.multicast(ent->s.origin, MULTICAST_PVS); } } gi.bprintf(PRINT_HIGH, "%s entered the game\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n entered the game", ent->client->pers.netname); // TNG:Freud Automaticly join saved teams. if (teamplay->value && ent->client->resp.saved_team) JoinTeam(ent, ent->client->resp.saved_team, 1); //FIREBLADE if (deathmatch->value && !teamplay->value && ent->solid == SOLID_NOT) { gi.bprintf(PRINT_HIGH, "%s became a spectator\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n became a spectator", ent->client->pers.netname); } //FIREBLADE //FIREBLADE if (!level.intermissiontime) PrintMOTD(ent); ent->client->resp.motd_refreshes = 1; //FIREBLADE //AQ2:TNG - Slicer: Set time to check clients ent->client->resp.checktime[0] = level.time + check_time->value; ent->client->resp.checktime[1] = level.time + (check_time->value + 2); ent->client->resp.checktime[1] = level.time + (check_time->value + 3); // make sure all view stuff is valid ClientEndServerFrame(ent); } /* =========== ClientBegin called when a client has finished connecting, and is ready to be placed into the game. This will happen every level load. ============ */ void ClientBegin(edict_t * ent) { int i; ent->client = game.clients + (ent - g_edicts - 1); if (deathmatch->value) { ClientBeginDeathmatch(ent); return; } //PG BUND - BEGIN ResetKills(ent); //AQ2:TNG - Slicer :Dunno Why these Vars Are Here, as it calls InitClientResp.. //Adding The Last_damaged_part anyway ent->client->resp.last_damaged_part = 0; ent->client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END ent->client->resp.killed_teammates = 0; ent->client->resp.idletime = 0; TourneyNewPlayer(ent); // client voting initialization vInitClient(ent); //PG BUND - END // if there is already a body waiting for us (a loadgame), just // take it, otherwise spawn one from scratch if (ent->inuse == true) { // the client has cleared the client side viewangles upon // connecting to the server, which is different than the // state when the game is saved, so we need to compensate // with deltaangles for (i = 0; i < 3; i++) ent->client->ps.pmove.delta_angles[i] = ANGLE2SHORT(ent->client->ps.viewangles[i]); } else { // a spawn point will completely reinitialize the entity // except for the persistant data that was initialized at // ClientConnect() time G_InitEdict(ent); ent->classname = "player"; ResetKills(ent); InitClientResp(ent->client); PutClientInServer(ent); } if (level.intermissiontime) { MoveClientToIntermission(ent); } else { // send effect if in a multiplayer game if (game.maxclients > 1) { //FIREBLADE if (!teamplay->value) { //FIREBLADE gi.WriteByte(svc_muzzleflash); gi.WriteShort(ent - g_edicts); gi.WriteByte(MZ_LOGIN); gi.multicast(ent->s.origin, MULTICAST_PVS); } gi.bprintf(PRINT_HIGH, "%s entered the game\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n entered the game", ent->client->pers.netname); } } // make sure all view stuff is valid ClientEndServerFrame(ent); } /* =========== ClientUserInfoChanged called whenever the player updates a userinfo variable. The game can override any of the settings in place (forcing skins or names, etc) before copying it off. ============ */ void ClientUserinfoChanged(edict_t * ent, char *userinfo) { char *s, *r, tnick[16]; qboolean nickChanged = false; // check for malformed or illegal info strings if (!Info_Validate(userinfo)) { strcpy(userinfo, "\\name\\badinfo\\skin\\male/grunt"); } // set name s = Info_ValueForKey(userinfo, "name"); Q_strncpyz(tnick, s, sizeof(tnick)); if(!tnick[0]) strcpy(tnick, "unnamed"); if(strcmp(ent->client->pers.netname, tnick)) { // on the initial update, we won't broadcast the message. if (ent->client->pers.netname[0]) { gi.bprintf(PRINT_MEDIUM, "%s is now known as %s.\n", ent->client->pers.netname, tnick); //TempFile IRC_printf(IRC_T_SERVER, "%n is now known as %n.", ent->client->pers.netname, tnick); nickChanged = true; } strcpy(ent->client->pers.netname, tnick); } //FIREBLADE s = Info_ValueForKey(userinfo, "spectator"); ent->client->pers.spectator = (strcmp(s, "0") != 0); r = Info_ValueForKey(userinfo, "rate"); ent->client->rate = atoi(r); //FIREBLADE // set skin s = Info_ValueForKey(userinfo, "skin"); // AQ:TNG - JBravo fixing $$ Skin server crash bug if (strstr(s, "$$")) { Info_SetValueForKey(userinfo, "skin", "male/grunt"); s = Info_ValueForKey(userinfo, "skin"); } // End $$ Skin server crash bug // combine name and skin into a configstring AssignSkin(ent, s, nickChanged); /* Not used in Action. // fov if (deathmatch->value && ((int)dmflags->value & DF_FIXED_FOV)) { ent->client->ps.fov = 90; } else { ent->client->ps.fov = atoi(Info_ValueForKey(userinfo, "fov")); if (ent->client->ps.fov < 1) ent->client->ps.fov = 90; else if (ent->client->ps.fov > 160) ent->client->ps.fov = 160; } */ ent->client->pers.firing_style = ACTION_FIRING_CENTER; // handedness s = Info_ValueForKey(userinfo, "hand"); if (strlen(s)) { ent->client->pers.hand = atoi(s); if (strstr(s, "classic high") != NULL) ent->client->pers.firing_style = ACTION_FIRING_CLASSIC_HIGH; else if (strstr(s, "classic") != NULL) ent->client->pers.firing_style = ACTION_FIRING_CLASSIC; } // save off the userinfo in case we want to check something later Q_strncpyz(ent->client->pers.userinfo, userinfo, sizeof(ent->client->pers.userinfo)); // zucc vwep ShowGun(ent); } /* =========== ClientConnect Called when a player begins connecting to the server. The game can refuse entrance to a client by returning false. If the client is allowed, the connection process will continue and eventually get to ClientBegin() Changing levels will NOT cause this to be called again, but loadgames will. ============ */ qboolean ClientConnect(edict_t * ent, char *userinfo) { char *value, *ipaddr; char ipaddr_buf[100]; int tempBan = 0; // check to see if they are on the banned IP list ipaddr = Info_ValueForKey(userinfo, "ip"); if (strlen(ipaddr) > sizeof(ipaddr_buf) - 1) gi.dprintf("ipaddr_buf length exceeded\n"); Q_strncpyz(ipaddr_buf, ipaddr, sizeof(ipaddr_buf)); if (SV_FilterPacket(ipaddr, &tempBan)) { userinfo[0] = '\0'; if(tempBan) Info_SetValueForKey(userinfo, "rejmsg", va("Temporary banned for %i games.", tempBan)); else Info_SetValueForKey(userinfo, "rejmsg", "Banned."); return false; } // check for a password value = Info_ValueForKey(userinfo, "password"); if (*password->string && strcmp(password->string, "none") && strcmp(password->string, value)) { userinfo[0] = '\0'; Info_SetValueForKey(userinfo, "rejmsg", "Password required or incorrect."); return false; } if (vClientConnect(ent, userinfo) == false) return false; // they can connect ent->client = game.clients + (ent - g_edicts - 1); ent->client->resp.stat_mode = 0; ent->client->team_kills = 0; ent->client->team_wounds = 0; ent->client->team_wounds_before = 0; ResetKills(ent); // We're not going to attempt to support reconnection... if (ent->inuse == true) { ClientDisconnect(ent); ent->inuse = false; } if (ent->inuse == false) { // clear the respawning variables InitClientResp(ent->client); if (!game.autosaved || !ent->client->pers.weapon) InitClientPersistant(ent->client); } ClientUserinfoChanged(ent, userinfo); if (game.maxclients > 1) { gi.dprintf("%s@%s connected\n", ent->client->pers.netname, ipaddr_buf); IRC_printf(IRC_T_SERVER, "%n@%s connected", ent->client->pers.netname, ipaddr_buf); } Q_strncpyz(ent->client->ipaddr, ipaddr_buf, sizeof(ent->client->ipaddr)); ent->svflags = 0; ent->client->pers.connected = true; return true; } /* =========== ClientDisconnect Called when a player drops from the server. Will not be called between levels. ============ */ void ClientDisconnect(edict_t * ent) { int playernum, i; edict_t *etemp; if (!ent->client) return; if (ent->client->resp.captain) { if(teamdm->value || ctf->value) { if(!team_round_going) teams[ent->client->resp.captain].ready = 0; teams[ent->client->resp.captain].locked = 0; } else { teams[ent->client->resp.captain].ready = 0; } } // reset item and weapon on disconnect ent->client->resp.item = NULL; ent->client->resp.weapon = NULL; ent->client->resp.dm_selected = 0; ent->client->resp.menu_shown = 0; // drop items if they are alive/not observer if (ent->solid != SOLID_NOT) TossItemsOnDeath(ent); // zucc free the lasersight if applicable if (ent->lasersight) SP_LaserSight(ent, NULL); // TNG Free Flashlight if (ent->flashlight) FL_make(ent); if (teamplay->value && ent->solid == SOLID_TRIGGER) RemoveFromTransparentList(ent); ent->lasersight = NULL; gi.bprintf(PRINT_HIGH, "%s disconnected\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n disconnected", ent->client->pers.netname); // go clear any clients that have this guy as their attacker for (i = 1; i <= maxclients->value; i++) { if ((etemp = &g_edicts[i]) && etemp->inuse) { if (etemp->client->attacker == ent) etemp->client->attacker = NULL; if (etemp->enemy == ent) // AQ:TNG - JBravo adding tkok etemp->enemy = NULL; } } TourneyRemovePlayer(ent); vClientDisconnect(ent); // client voting disconnect if (use_ghosts->value) CreateGhost(ent); if (ctf->value) CTFDeadDropFlag(ent); if (!teamplay->value) { // send effect gi.WriteByte(svc_muzzleflash); gi.WriteShort(ent - g_edicts); gi.WriteByte(MZ_LOGOUT); gi.multicast(ent->s.origin, MULTICAST_PVS); } gi.unlinkentity(ent); ent->s.modelindex = 0; ent->solid = SOLID_NOT; ent->inuse = false; ent->classname = "disconnected"; ent->client->pers.connected = false; playernum = ent - g_edicts - 1; gi.configstring(CS_PLAYERSKINS + playernum, ""); } void CreateGhost(edict_t * ent) { int x; qboolean duplicate = false; if (ent->client->resp.score == 0 && ent->client->resp.damage_dealt == 0) { return; } for (x = 0; x < num_ghost_players; x++) { if (duplicate == true) { ghost_players[x - 1] = ghost_players[x]; } else if (strcmp(ghost_players[x].ipaddr, ent->client->ipaddr) == 0 && strcmp(ghost_players[x].netname, ent->client->pers.netname) == 0) { duplicate = true; } } if (duplicate == true) num_ghost_players--; if (num_ghost_players < MAX_GHOSTS) { strcpy(ghost_players[num_ghost_players].ipaddr, ent->client->ipaddr); strcpy(ghost_players[num_ghost_players].netname, ent->client->pers.netname); ghost_players[num_ghost_players].enterframe = ent->client->resp.enterframe; ghost_players[num_ghost_players].disconnect_frame = level.framenum; // Score ghost_players[num_ghost_players].score = ent->client->resp.score; ghost_players[num_ghost_players].damage_dealt = ent->client->resp.damage_dealt; ghost_players[num_ghost_players].kills = ent->client->resp.kills; // Teamplay variables if (teamplay->value) { ghost_players[num_ghost_players].weapon = ent->client->resp.weapon; ghost_players[num_ghost_players].item = ent->client->resp.item; ghost_players[num_ghost_players].team = ent->client->resp.team; } // Statistics ghost_players[num_ghost_players].stats_shots_t = ent->client->resp.stats_shots_t; ghost_players[num_ghost_players].stats_shots_h = ent->client->resp.stats_shots_h; memcpy(ghost_players[num_ghost_players].stats_locations, ent->client->resp.stats_locations, sizeof(ent->client->resp.stats_locations)); memcpy(ghost_players[num_ghost_players].stats_shots, ent->client->resp.stats_shots, sizeof(ent->client->resp.stats_shots)); memcpy(ghost_players[num_ghost_players].stats_hits, ent->client->resp.stats_hits, sizeof(ent->client->resp.stats_hits)); memcpy(ghost_players[num_ghost_players].stats_headshot, ent->client->resp.stats_headshot, sizeof(ent->client->resp.stats_headshot)); num_ghost_players++; } else { gi.dprintf("Maximum number of ghosts reached.\n"); } } //============================================================== edict_t *pm_passent; // pmove doesn't need to know about passent and contentmask trace_t q_gameabi PM_trace(vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end) { if (pm_passent && pm_passent->health > 0) return gi.trace(start, mins, maxs, end, pm_passent, MASK_PLAYERSOLID); else return gi.trace(start, mins, maxs, end, pm_passent, MASK_DEADSOLID); } unsigned CheckBlock(void *b, int c) { int v, i; v = 0; for (i = 0; i < c; i++) v += ((byte *) b)[i]; return v; } void PrintPmove(pmove_t * pm) { unsigned c1, c2; c1 = CheckBlock(&pm->s, sizeof(pm->s)); c2 = CheckBlock(&pm->cmd, sizeof(pm->cmd)); Com_Printf("sv %3i:%i %i\n", pm->cmd.impulse, c1, c2); } /* ============== ClientThink This will be called once for each client frame, which will usually be a couple times for each server frame. ============== */ void ClientThink(edict_t * ent, usercmd_t * ucmd) { gclient_t *client; edict_t *other; int i, j; pmove_t pm; char ltm[64] = "\0"; level.current_entity = ent; client = ent->client; if (level.intermissiontime) { client->ps.pmove.pm_type = PM_FREEZE; // if (level.time > level.intermissiontime + 4.0) { if (ent->inuse && ent->client->resp.stat_mode > 0 && ent->client->resp.stat_mode_intermission == 0) { ent->client->resp.stat_mode_intermission = 1; Cmd_Stats_f(ent, ltm); } } // can exit intermission after five seconds if (level.time > level.intermissiontime + 5.0 && (ucmd->buttons & BUTTON_ANY)) level.exitintermission = true; return; } //FIREBLADE //PG BUND if ((int) motd_time->value > (client->resp.motd_refreshes * 2) && !(client->menu)) { if (client->resp.last_motd_refresh < (level.framenum - 20)) { client->resp.last_motd_refresh = level.framenum; client->resp.motd_refreshes++; PrintMOTD(ent); } } //FIREBLADE // show team or weapon menu immediately when connected if (auto_menu->value && !client->menu && !client->resp.menu_shown && (teamplay->value || dm_choose->value)) { Cmd_Inven_f(ent); } if(pause_time > 0) { client->ps.pmove.pm_type = PM_FREEZE; return; } pm_passent = ent; // FROM 3.20 -FB if (ent->client->chase_mode) { client->resp.cmd_angles[0] = SHORT2ANGLE(ucmd->angles[0]); client->resp.cmd_angles[1] = SHORT2ANGLE(ucmd->angles[1]); client->resp.cmd_angles[2] = SHORT2ANGLE(ucmd->angles[2]); } else { // ^^^ // set up for pmove memset(&pm, 0, sizeof(pm)); if (ent->movetype == MOVETYPE_NOCLIP) client->ps.pmove.pm_type = PM_SPECTATOR; else if (ent->s.modelindex != 255) client->ps.pmove.pm_type = PM_GIB; else if (ent->deadflag) client->ps.pmove.pm_type = PM_DEAD; else client->ps.pmove.pm_type = PM_NORMAL; client->ps.pmove.gravity = sv_gravity->value; pm.s = client->ps.pmove; for (i = 0; i < 3; i++) { pm.s.origin[i] = ent->s.origin[i] * 8; pm.s.velocity[i] = ent->velocity[i] * 8; } if (memcmp(&client->old_pmove, &pm.s, sizeof(pm.s))) { pm.snapinitial = true; // gi.dprintf ("pmove changed!\n"); } pm.cmd = *ucmd; pm.trace = PM_trace; // adds default parms pm.pointcontents = gi.pointcontents; // perform a pmove gi.Pmove(&pm); //FB 6/3/99 - info from Mikael Lindh from AQ:G if (pm.maxs[2] == 4) { ent->maxs[2] = CROUCHING_MAXS2; pm.maxs[2] = CROUCHING_MAXS2; ent->viewheight = CROUCHING_VIEWHEIGHT; pm.viewheight = (float) ent->viewheight; } //FB 6/3/99 // save results of pmove client->ps.pmove = pm.s; client->old_pmove = pm.s; // really stopping jumping with leg damage if (ent->client->leg_damage && ent->groundentity && pm.s.velocity[2] > 10) { pm.s.velocity[2] = 0.0; } for (i = 0; i < 3; i++) { ent->s.origin[i] = pm.s.origin[i] * 0.125; ent->velocity[i] = pm.s.velocity[i] * 0.125; } // zucc stumbling associated with leg damage if (level.framenum % 6 <= 2 && ent->client->leg_damage) { //Slow down code FOO/zucc for (i = 0; i < 3; i++) { if ((i < 2 || ent->velocity[2] > 0) && (ent->groundentity && pm.groundentity)) ent->velocity[i] /= 4 * ent->client->leghits; //FOO } if (level.framenum % (6 * 12) == 0 && ent->client->leg_damage > 1) gi.sound(ent, CHAN_BODY, gi.soundindex(va("*pain100_1.wav")), 1, ATTN_NORM, 0); ent->velocity[0] = (float) ((int) (ent->velocity[0] * 8)) / 8; ent->velocity[1] = (float) ((int) (ent->velocity[1] * 8)) / 8; ent->velocity[2] = (float) ((int) (ent->velocity[2] * 8)) / 8; } VectorCopy(pm.mins, ent->mins); VectorCopy(pm.maxs, ent->maxs); client->resp.cmd_angles[0] = SHORT2ANGLE(ucmd->angles[0]); client->resp.cmd_angles[1] = SHORT2ANGLE(ucmd->angles[1]); client->resp.cmd_angles[2] = SHORT2ANGLE(ucmd->angles[2]); // don't play sounds if they have leg damage, they can't jump anyway if (ent->groundentity && !pm.groundentity && (pm.cmd.upmove >= 10) && (pm.waterlevel == 0) && !ent->client->leg_damage) { /* don't play jumps period. gi.sound(ent, CHAN_VOICE, gi.soundindex("*jump1.wav"), 1, ATTN_NORM, 0); PlayerNoise(ent, ent->s.origin, PNOISE_SELF); */ ent->client->jumping = 1; } ent->viewheight = pm.viewheight; ent->waterlevel = pm.waterlevel; ent->watertype = pm.watertype; ent->groundentity = pm.groundentity; if (pm.groundentity) ent->groundentity_linkcount = pm.groundentity->linkcount; if (ent->deadflag) { client->ps.viewangles[ROLL] = 40; client->ps.viewangles[PITCH] = -15; client->ps.viewangles[YAW] = client->killer_yaw; } else { VectorCopy(pm.viewangles, client->v_angle); VectorCopy(pm.viewangles, client->ps.viewangles); } if(client->ctf_grapple) CTFGrapplePull(client->ctf_grapple); gi.linkentity(ent); if (ent->movetype != MOVETYPE_NOCLIP) G_TouchTriggers(ent); // stop manipulating doors client->doortoggle = 0; //Should move this to ClientBeginServerFrame? -M if (ent->client->jumping && ent->solid != SOLID_NOT && !lights_camera_action && !ent->client->ctf_uvtime) kick_attack(ent); // touch other objects for (i = 0; i < pm.numtouch; i++) { other = pm.touchents[i]; for (j = 0; j < i; j++) if (pm.touchents[j] == other) break; if (j != i) continue; // duplicated if (!other->touch) continue; other->touch(other, ent, NULL, NULL); } } client->oldbuttons = client->buttons; client->buttons = ucmd->buttons; client->latched_buttons |= client->buttons & ~client->oldbuttons; // save light level the player is standing on for // monster sighting AI ent->light_level = ucmd->lightlevel; // fire weapon from final position if needed if (client->latched_buttons & BUTTON_ATTACK) { //TempFile //We're gonna fire in this frame? Then abort any punching. client->resp.fire_time = level.framenum; client->resp.punch_desired = false; //TempFile if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) { client->latched_buttons = 0; if (client->chase_mode) { // AQ:TNG - JBravo fixing Limchasecam if ((limchasecam->value != 2) || (client->resp.team == NOTEAM)) { if (client->chase_mode == 1) { client->desired_fov = 90; client->ps.fov = 90; client->chase_mode++; } else if ((limchasecam->value != 1) || (client->resp.team == NOTEAM)) { client->chase_mode = 0; client->chase_target = NULL; client->desired_fov = 90; client->ps.fov = 90; client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; } else { client->chase_mode = 1; UpdateChaseCam(ent); } } } else { client->chase_target = NULL; GetChaseTarget(ent); if (client->chase_target != NULL) { if (limchasecam->value == 2) { client->chase_mode = 1; UpdateChaseCam(ent); client->chase_mode = 2; } else { client->chase_mode = 1; } UpdateChaseCam(ent); } } } else if (!client->weapon_thunk) { client->weapon_thunk = true; Think_Weapon(ent); } } if (client->chase_mode) { if (ucmd->upmove >= 10) { if (!(client->ps.pmove.pm_flags & PMF_JUMP_HELD)) { client->ps.pmove.pm_flags |= PMF_JUMP_HELD; if (client->chase_target) { ChaseNext(ent); } else { GetChaseTarget(ent); UpdateChaseCam(ent); } } } else client->ps.pmove.pm_flags &= ~PMF_JUMP_HELD; //FIREBLADE ChaseTargetGone(ent); // run a check...result not important. //FIREBLADE } // FROM 3.20 -FB // update chase cam if being followed for (i = 1; i <= maxclients->value; i++) { other = g_edicts + i; if (other->inuse && other->client->chase_mode && other->client->chase_target == ent) UpdateChaseCam(other); } // ^^^ //PG BUND - BEGIN if (ppl_idletime->value) { if (ent->solid != SOLID_NOT && ent->deadflag != DEAD_DEAD) { if (ucmd->forwardmove == 0 && ucmd->sidemove == 0) { if (client->resp.idletime) { if (level.time >= client->resp.idletime + ppl_idletime->value) { PlayRandomInsaneSound(ent); client->resp.idletime = 0; } } else { client->resp.idletime = level.time; } } else client->resp.idletime = 0; } } //PG BUND - END if (ent->client->autoreloading && (ent->client->weaponstate == WEAPON_END_MAG) && (ent->client->curr_weap == MK23_NUM)) { ent->client->autoreloading = false; Cmd_New_Reload_f(ent); } //TempFile - END } /* ============== ClientBeginServerFrame This will be called once for each server frame, before running any other entities in the world. ============== */ void ClientBeginServerFrame(edict_t * ent) { gclient_t *client; int buttonMask; if (level.intermissiontime) return; client = ent->client; // force spawn when weapon and item selected in dm if (deathmatch->value && dm_choose->value && !teamplay->value && !client->resp.dm_selected) { if (client->resp.weapon && (client->resp.item || itm_flags->value == 0)) { client->resp.dm_selected = 1; client->chase_mode = 0; client->chase_target = NULL; client->desired_fov = 90; client->ps.fov = 90; client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; ent->solid = SOLID_BBOX; gi.linkentity(ent); gi.bprintf(PRINT_HIGH, "%s joined the game\n", client->pers.netname); IRC_printf(IRC_T_SERVER, "%n joined the game", client->pers.netname); // send effect gi.WriteByte(svc_muzzleflash); gi.WriteShort(ent - g_edicts); gi.WriteByte(MZ_LOGIN); gi.multicast(ent->s.origin, MULTICAST_PVS); respawn(ent); } return; } //FIREBLADE if (deathmatch->value && !teamplay->value && ((ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) != ent->client->pers.spectator)) { if (ent->solid != SOLID_NOT || ent->deadflag == DEAD_DEAD) { if (ent->deadflag != DEAD_DEAD) { ent->flags &= ~FL_GODMODE; ent->health = 0; meansOfDeath = MOD_SUICIDE; player_die(ent, ent, ent, 100000, vec3_origin); // don't even bother waiting for death frames ent->deadflag = DEAD_DEAD; // This will make ClientBeginServerFrame crank us into observer mode // as soon as our death frames are done... -FB ent->solid = SOLID_NOT; // Also set this so we can have a way to know we've already done this... ent->movetype = MOVETYPE_NOCLIP; gi.linkentity(ent); gi.bprintf(PRINT_HIGH, "%s became a spectator\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n became a spectator", ent->client->pers.netname); } else // immediately become observer... { if (ent->movetype != MOVETYPE_NOCLIP) // have we already done this? see above... { CopyToBodyQue(ent); ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->movetype = MOVETYPE_NOCLIP; ent->client->pers.health = 100; ent->health = 100; ent->deadflag = DEAD_NO; gi.linkentity(ent); gi.bprintf(PRINT_HIGH, "%s became a spectator\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n became a spectator", ent->client->pers.netname); } } } else { ent->client->chase_mode = 0; ent->client->chase_target = NULL; ent->client->desired_fov = 90; ent->client->ps.fov = 90; //FB 5/31/99 added ent->client->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; ent->solid = SOLID_BBOX; gi.linkentity(ent); gi.bprintf(PRINT_HIGH, "%s rejoined the game\n", ent->client->pers.netname); IRC_printf(IRC_T_SERVER, "%n rejoined the game", ent->client->pers.netname); respawn(ent); } } //FIREBLADE // run weapon animations if it hasn't been done by a ucmd_t if (!client->weapon_thunk) Think_Weapon(ent); else client->weapon_thunk = false; if (ent->deadflag) { // wait for any button just going down if (level.time > client->respawn_time) { //FIREBLADE if (((!ctf->value && !teamdm->value) || (ent->client->resp.team == NOTEAM || ent->client->resp.subteam)) && (teamplay->value || (ent->client->pers.spectator && ent->solid == SOLID_NOT && ent->deadflag == DEAD_DEAD))) { CopyToBodyQue(ent); ent->solid = SOLID_NOT; ent->svflags |= SVF_NOCLIENT; ent->movetype = MOVETYPE_NOCLIP; ent->client->pers.health = 100; ent->health = 100; ent->deadflag = DEAD_NO; client->ps.pmove.delta_angles[PITCH] = ANGLE2SHORT(0 - client->resp.cmd_angles[PITCH]); client->ps.pmove.delta_angles[YAW] = ANGLE2SHORT(client->killer_yaw - client->resp.cmd_angles[YAW]); client->ps.pmove.delta_angles[ROLL] = ANGLE2SHORT(0 - client->resp.cmd_angles[ROLL]); ent->s.angles[PITCH] = 0; ent->s.angles[YAW] = client->killer_yaw; ent->s.angles[ROLL] = 0; VectorCopy(ent->s.angles, client->ps.viewangles); VectorCopy(ent->s.angles, client->v_angle); gi.linkentity(ent); if (teamplay->value) { if(ent->client->resp.last_chase_target && ent->client->resp.last_chase_target->solid != SOLID_NOT && ent->client->resp.last_chase_target->deadflag != DEAD_DEAD) ent->client->chase_target = ent->client->resp.last_chase_target; if(ent->client->chase_target == NULL) GetChaseTarget(ent); if (ent->client->chase_target != NULL) { ent->client->chase_mode = 1; UpdateChaseCam(ent); ent->client->chase_mode = 2; } } } //FIREBLADE else { // in deathmatch, only wait for attack button if (deathmatch->value) buttonMask = BUTTON_ATTACK; else buttonMask = -1; if ((client->latched_buttons & buttonMask) || (deathmatch->value && ((int) dmflags->value & DF_FORCE_RESPAWN))) { respawn(ent); client->latched_buttons = 0; } } } return; } // add player trail so monsters can follow if (!deathmatch->value && !visible(ent, PlayerTrail_LastSpot())) PlayerTrail_Add(ent->s.old_origin); if (client->resp.punch_desired && ent->solid != SOLID_NOT) { if(!lights_camera_action && !ent->client->ctf_uvtime) punch_attack(ent); client->resp.punch_desired = false; } client->latched_buttons = 0; }
550
./aq2-tng/source/g_combat.c
//----------------------------------------------------------------------------- // g_combat.c // // $Id: g_combat.c,v 1.27 2002/09/04 11:23:09 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_combat.c,v $ // Revision 1.27 2002/09/04 11:23:09 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.26 2002/04/01 15:47:51 freud // Typo fixed for statistics // // Revision 1.25 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.24 2002/02/19 10:28:43 freud // Added to %D hit in the kevlar vest and kevlar helmet, also body for handcannon // and shotgun. // // Revision 1.23 2002/02/18 17:17:20 freud // Fixed the CTF leaving team bug. Also made the shield more efficient, // No falling damage. // // Revision 1.22 2002/02/18 13:55:35 freud // Added last damaged players %P // // Revision 1.21 2002/02/01 17:49:56 freud // Heavy changes in stats code. Removed lots of variables and replaced them // with int arrays of MODs. This cleaned tng_stats.c up a whole lots and // everything looks well, might need more testing. // // Revision 1.20 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.19 2002/01/23 14:51:35 ra // Damn if statements from HELL (ff_afterrounds fix) // // Revision 1.18 2002/01/23 14:18:02 ra // Fixed another ff_afterrounds bobo // // Revision 1.17 2001/12/23 21:19:41 deathwatch // Updated stats with location and average // cleaned it up a bit as well // // Revision 1.16 2001/12/23 16:30:50 ra // 2.5 ready. New stats from Freud. HC and shotgun gibbing seperated. // // Revision 1.15 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.14 2001/08/18 01:28:06 deathwatch // Fixed some stats stuff, added darkmatch + day_cycle, cleaned up several files, restructured ClientCommand // // Revision 1.13 2001/08/17 21:31:37 deathwatch // Added support for stats // // Revision 1.12 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.11 2001/08/06 03:00:48 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.10 2001/07/16 19:02:06 ra // Fixed compilerwarnings (-g -Wall). Only one remains. // // Revision 1.9 2001/06/22 18:54:38 igor_rock // fixed the "accuracy" for killing teammates with headshots // // Revision 1.8 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.7 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.6.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.6.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.6.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.6 2001/05/20 12:54:18 igor_rock // Removed newlines from Centered Messages like "Impressive" // // Revision 1.5 2001/05/12 14:05:29 mort // Hurting someone whilst they are "god" is fixed now // // Revision 1.4 2001/05/11 12:21:19 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.2 2001/05/07 20:06:45 igor_rock // changed sound dir from sound/rock to sound/tng // // Revision 1.1.1.1 2001/05/06 17:30:50 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" void Add_TeamWound (edict_t * attacker, edict_t * victim, int mod); /* ============ CanDamage Returns true if the inflictor can directly damage the target. Used for explosions and melee attacks. ============ */ qboolean CanDamage (edict_t * targ, edict_t * inflictor) { vec3_t dest; trace_t trace; // bmodels need special checking because their origin is 0,0,0 //GLASS FX if ((targ->movetype == MOVETYPE_PUSH) || ((targ->movetype == MOVETYPE_FLYMISSILE) && (0 == Q_stricmp ("func_explosive", targ->classname)))) //GLASS FX { VectorAdd (targ->absmin, targ->absmax, dest); VectorScale (dest, 0.5, dest); PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, dest, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; if (trace.ent == targ) return true; return false; } PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, targ->s.origin, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; VectorCopy (targ->s.origin, dest); dest[0] += 15.0; dest[1] += 15.0; PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, dest, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; VectorCopy (targ->s.origin, dest); dest[0] += 15.0; dest[1] -= 15.0; PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, dest, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; VectorCopy (targ->s.origin, dest); dest[0] -= 15.0; dest[1] += 15.0; PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, dest, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; VectorCopy (targ->s.origin, dest); dest[0] -= 15.0; dest[1] -= 15.0; PRETRACE (); trace = gi.trace (inflictor->s.origin, vec3_origin, vec3_origin, dest, inflictor, MASK_SOLID); POSTTRACE (); if (trace.fraction == 1.0) return true; return false; } /* ============ Killed ============ */ void Killed (edict_t * targ, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { if (targ->health < -999) targ->health = -999; if (targ->client) { targ->client->bleeding = 0; //targ->client->bleedcount = 0; targ->client->bleed_remain = 0; } targ->enemy = attacker; if ((targ->svflags & SVF_MONSTER) && (targ->deadflag != DEAD_DEAD)) { // targ->svflags |= SVF_DEADMONSTER; // now treat as a different content type if (!(targ->monsterinfo.aiflags & AI_GOOD_GUY)) { level.killed_monsters++; if (coop->value && attacker->client) attacker->client->resp.score++; // medics won't heal monsters that they kill themselves if (strcmp (attacker->classname, "monster_medic") == 0) targ->owner = attacker; } } if (targ->movetype == MOVETYPE_PUSH || targ->movetype == MOVETYPE_STOP || targ->movetype == MOVETYPE_NONE) { // doors, triggers, etc targ->die (targ, inflictor, attacker, damage, point); return; } if ((targ->svflags & SVF_MONSTER) && (targ->deadflag != DEAD_DEAD)) { targ->touch = NULL; monster_death_use (targ); } targ->die (targ, inflictor, attacker, damage, point); } /* ================ SpawnDamage ================ */ void SpawnDamage (int type, vec3_t origin, vec3_t normal, int damage) { if (damage > 255) damage = 255; gi.WriteByte (svc_temp_entity); gi.WriteByte (type); // gi.WriteByte (damage); gi.WritePosition (origin); gi.WriteDir (normal); gi.multicast (origin, MULTICAST_PVS); } /* ============ T_Damage targ entity that is being damaged inflictor entity that is causing the damage attacker entity that caused the inflictor to damage targ example: targ=monster, inflictor=rocket, attacker=player dir direction of the attack point point at which the damage is being inflicted normal normal vector from that point damage amount of damage being inflicted knockback force to be applied against targ as a result of the damage dflags these flags are used to control how T_Damage works DAMAGE_RADIUS damage was indirect (from a nearby explosion) DAMAGE_NO_ARMOR armor does not protect from this damage DAMAGE_ENERGY damage is from an energy based weapon DAMAGE_NO_KNOCKBACK do not affect velocity, just view angles DAMAGE_BULLET damage is from a bullet (used for ricochets) DAMAGE_NO_PROTECTION kills godmode, armor, everything ============ */ static int CheckPowerArmor (edict_t * ent, vec3_t point, vec3_t normal, int damage, int dflags) { gclient_t *client; int save; int power_armor_type; // AQ:TNG - JBravo fixing compilerwarnings. // Bah. JB will crash da servah if dis is wrong. int index = 0; // JBravo. int damagePerCell; int pa_te_type; int power = 0; int power_used; if (!damage) return 0; client = ent->client; if (dflags & DAMAGE_NO_ARMOR) return 0; if (client) { power_armor_type = PowerArmorType (ent); if (power_armor_type != POWER_ARMOR_NONE) { index = ITEM_INDEX (FindItem ("Cells")); power = client->pers.inventory[index]; } } else if (ent->svflags & SVF_MONSTER) { power_armor_type = ent->monsterinfo.power_armor_type; power = ent->monsterinfo.power_armor_power; } else return 0; if (power_armor_type == POWER_ARMOR_NONE) return 0; if (!power) return 0; if (power_armor_type == POWER_ARMOR_SCREEN) { vec3_t vec; float dot; vec3_t forward; // only works if damage point is in front AngleVectors (ent->s.angles, forward, NULL, NULL); VectorSubtract (point, ent->s.origin, vec); VectorNormalize (vec); dot = DotProduct (vec, forward); if (dot <= 0.3) return 0; damagePerCell = 1; pa_te_type = TE_SCREEN_SPARKS; damage = damage / 3; } else { damagePerCell = 2; pa_te_type = TE_SHIELD_SPARKS; damage = (2 * damage) / 3; } save = power * damagePerCell; if (!save) return 0; if (save > damage) save = damage; SpawnDamage (pa_te_type, point, normal, save); ent->powerarmor_time = level.time + 0.2; power_used = save / damagePerCell; if (client) client->pers.inventory[index] -= power_used; else ent->monsterinfo.power_armor_power -= power_used; return save; } static int CheckArmor (edict_t * ent, vec3_t point, vec3_t normal, int damage, int te_sparks, int dflags) { gclient_t *client; int save; int index; gitem_t *armor; if (!damage) return 0; client = ent->client; if (!client) return 0; if (dflags & DAMAGE_NO_ARMOR) return 0; index = ArmorIndex (ent); if (!index) return 0; armor = GetItemByIndex (index); if (dflags & DAMAGE_ENERGY) save = ceil (((gitem_armor_t *) armor->info)->energy_protection * damage); else save = ceil (((gitem_armor_t *) armor->info)->normal_protection * damage); if (save >= client->pers.inventory[index]) save = client->pers.inventory[index]; if (!save) return 0; client->pers.inventory[index] -= save; SpawnDamage (te_sparks, point, normal, save); return save; } void M_ReactToDamage (edict_t * targ, edict_t * attacker) { if (!(attacker->client) && !(attacker->svflags & SVF_MONSTER)) return; if (attacker == targ || attacker == targ->enemy) return; // if we are a good guy monster and our attacker is a player // or another good guy, do not get mad at them if (targ->monsterinfo.aiflags & AI_GOOD_GUY) { if (attacker->client || (attacker->monsterinfo.aiflags & AI_GOOD_GUY)) return; } // we now know that we are not both good guys // if attacker is a client, get mad at them because he's good and we're not if (attacker->client) { // this can only happen in coop (both new and old enemies are clients) // only switch if can't see the current enemy if (targ->enemy && targ->enemy->client) { if (visible (targ, targ->enemy)) { targ->oldenemy = attacker; return; } targ->oldenemy = targ->enemy; } targ->enemy = attacker; if (!(targ->monsterinfo.aiflags & AI_DUCKED)) FoundTarget (targ); return; } // it's the same base (walk/swim/fly) type and a different classname and it's not a tank // (they spray too much), get mad at them if (((targ->flags & (FL_FLY | FL_SWIM)) == (attacker->flags & (FL_FLY | FL_SWIM))) && (strcmp (targ->classname, attacker->classname) != 0) && (strcmp (attacker->classname, "monster_tank") != 0) && (strcmp (attacker->classname, "monster_supertank") != 0) && (strcmp (attacker->classname, "monster_makron") != 0) && (strcmp (attacker->classname, "monster_jorg") != 0)) { if (targ->enemy && targ->enemy->client) targ->oldenemy = targ->enemy; targ->enemy = attacker; if (!(targ->monsterinfo.aiflags & AI_DUCKED)) FoundTarget (targ); } else // otherwise get mad at whoever they are mad at (help our buddy) { if (targ->enemy && targ->enemy->client) targ->oldenemy = targ->enemy; targ->enemy = attacker->enemy; if (!(targ->monsterinfo.aiflags & AI_DUCKED)) FoundTarget (targ); } } qboolean CheckTeamDamage (edict_t * targ, edict_t * attacker) { //AQ2:TNG Igor isn't quite sure if the next statement really belongs here... (FIXME) commented it out (friendly fire already does it, hm?) // if (ctf->value && targ->client && attacker->client) // if (targ->client->resp.team == attacker->client->resp.team && // targ != attacker) // return true; //AQ2:TNG End //FIXME make the next line real and uncomment this block // if ((ability to damage a teammate == OFF) && (targ's team == attacker's team)) return false; } void BloodSprayThink (edict_t * self) { /* if ( self->dmg > 0 ) { self->dmg -= 10; // SpawnDamage (TE_BLOOD, self->s.origin, self->movedir, self->dmg); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPLASH); gi.WriteByte (6); gi.WritePosition (self->s.origin); gi.WriteDir (self->movedir); gi.WriteByte (6); //blood gi.multicast (self->s.origin, MULTICAST_PVS); } else { self->think = G_FreeEdict; } self->nextthink = level.time + 0.1; gi.linkentity (self); */ G_FreeEdict (self); } void blood_spray_touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other == ent->owner) return; ent->think = G_FreeEdict; ent->nextthink = level.time + 0.1; } void spray_blood (edict_t * self, vec3_t start, vec3_t dir, int damage, int mod) { edict_t *blood; int speed; switch (mod) { case MOD_MK23: speed = 1800; break; case MOD_MP5: speed = 1500; break; case MOD_M4: speed = 2400; break; case MOD_KNIFE: speed = 0; break; case MOD_KNIFE_THROWN: speed = 0; break; case MOD_DUAL: speed = 1800; break; case MOD_SNIPER: speed = 4000; break; default: speed = 1800; } blood = G_Spawn (); VectorNormalize (dir); VectorCopy (start, blood->s.origin); VectorCopy (dir, blood->movedir); vectoangles (dir, blood->s.angles); VectorScale (dir, speed, blood->velocity); blood->movetype = MOVETYPE_BLOOD; blood->clipmask = MASK_SHOT; blood->solid = SOLID_BBOX; blood->s.effects |= EF_GIB; VectorClear (blood->mins); VectorClear (blood->maxs); blood->s.modelindex = gi.modelindex ("sprites/null.sp2"); blood->owner = self; blood->nextthink = level.time + speed / 1000; //3.2; blood->touch = blood_spray_touch; blood->think = BloodSprayThink; blood->dmg = damage; blood->classname = "blood_spray"; gi.linkentity (blood); } // zucc based on some code in Action Quake void spray_sniper_blood (edict_t * self, vec3_t start, vec3_t dir) { vec3_t forward; int mod = MOD_SNIPER; VectorCopy (dir, forward); forward[2] += .03f; spray_blood (self, start, forward, 0, mod); VectorCopy (dir, forward); forward[2] -= .03f; spray_blood (self, start, forward, 0, mod); VectorCopy (dir, forward); if ((forward[0] > 0) && (forward[1] > 0)) { forward[0] -= .03f; forward[1] += .03f; } if ((forward[0] > 0) && (forward[1] < 0)) { forward[0] += .03f; forward[1] += .03f; } if ((forward[0] < 0) && (forward[1] > 0)) { forward[0] -= .03f; forward[1] -= .03f; } if ((forward[0] < 0) && (forward[1] < 0)) { forward[0] += .03f; forward[1] -= .03f; } spray_blood (self, start, forward, 0, mod); VectorCopy (dir, forward); if ((forward[0] > 0) && (forward[1] > 0)) { forward[0] += .03f; forward[1] -= .03f; } if ((forward[0] > 0) && (forward[1] < 0)) { forward[0] -= .03f; forward[1] -= .03f; } if ((forward[0] < 0) && (forward[1] > 0)) { forward[0] += .03f; forward[1] += .03f; } if ((forward[0] < 0) && (forward[1] < 0)) { forward[0] -= .03f; forward[1] += .03f; } spray_blood (self, start, forward, 0, mod); VectorCopy (dir, forward); spray_blood (self, start, forward, 0, mod); } void VerifyHeadShot (vec3_t point, vec3_t dir, float height, vec3_t newpoint) { vec3_t normdir; vec3_t normdir2; VectorNormalize2 (dir, normdir); VectorScale (normdir, height, normdir2); VectorAdd (point, normdir2, newpoint); } // zucc adding location hit code // location hit code based off ideas by pyromage and shockman #define LEG_DAMAGE (height/2.2) - abs(targ->mins[2]) - 3 #define STOMACH_DAMAGE (height/1.8) - abs(targ->mins[2]) #define CHEST_DAMAGE (height/1.4) - abs(targ->mins[2]) #define HEAD_HEIGHT 12.0 qboolean IsFemale (edict_t * ent); void T_Damage (edict_t * targ, edict_t * inflictor, edict_t * attacker, vec3_t dir, vec3_t point, vec3_t normal, int damage, int knockback, int dflags, int mod) { gclient_t *client; char buf[256]; int take, save; int asave, psave; int te_sparks, do_sparks = 0; int damage_type = 0; // used for MOD later int bleeding = 0; // damage causes bleeding int head_success = 0; int instant_dam = 1; float z_rel; int height; float from_top; vec_t dist; float targ_maxs2; //FB 6/1/99 // do this before teamplay check if (!targ->takedamage) return; //FIREBLADE if (teamplay->value && mod != MOD_TELEFRAG) { if (lights_camera_action) return; // AQ2:TNG - JBravo adding UVtime if (ctf->value && targ->client) { if(targ->client->ctf_uvtime > 0) return; if (attacker->client && attacker->client->ctf_uvtime > 0) return; } // AQ2:TNG - JBravo adding FF after rounds if (targ != attacker && targ->client && attacker->client && targ->client->resp.team == attacker->client->resp.team && ((int)(dmflags->value) & (DF_NO_FRIENDLY_FIRE))) { if (team_round_going) return; else if (!ff_afterround->value) return; } // AQ:TNG } //FIREBLADE if (dm_shield->value && targ->client) { if (targ->client->ctf_uvtime > 0) return; if (attacker->client && attacker->client->ctf_uvtime > 0) return; } // damage reduction for shotgun // if far away, reduce it to original action levels if (mod == MOD_M3) { dist = Distance(targ->s.origin, inflictor->s.origin); if (dist > 450.0) damage = damage - 2; } targ_maxs2 = targ->maxs[2]; if (targ_maxs2 == 4) targ_maxs2 = CROUCHING_MAXS2; //FB 6/1/99 height = abs (targ->mins[2]) + targ_maxs2; // locational damage code // base damage is head shot damage, so all the scaling is downwards if (targ->client) { if (!((targ != attacker) && ((deathmatch->value && ((int)dmflags->value & (DF_MODELTEAMS | DF_SKINTEAMS))) || coop->value) && (attacker && attacker->client && OnSameTeam (targ, attacker) && ((int)dmflags->value & DF_NO_FRIENDLY_FIRE) && (team_round_going && ff_afterround->value)))) { // TNG Stats - Add +1 to hit, make sure that hc and m3 are handles differently if ((attacker->client) && (mod != MOD_M3) && (mod != MOD_HC)) { strcpy(attacker->client->resp.last_damaged_players, targ->client->pers.netname); if (!teamplay->value || team_round_going || stats_afterround->value) { attacker->client->resp.stats_hits[mod]++; attacker->client->resp.stats_shots_h++; } } // TNG Stats END if (mod == MOD_MK23 || mod == MOD_MP5 || mod == MOD_M4 || mod == MOD_SNIPER || mod == MOD_DUAL || mod == MOD_KNIFE || mod == MOD_KNIFE_THROWN) { z_rel = point[2] - targ->s.origin[2]; from_top = targ_maxs2 - z_rel; if (from_top < 0.0) //FB 6/1/99 from_top = 0.0; //Slightly negative values were being handled wrong bleeding = 1; instant_dam = 0; // damage reduction for longer range pistol shots if (mod == MOD_MK23 || mod == MOD_DUAL) { dist = Distance(targ->s.origin, inflictor->s.origin); if (dist > 600.0 && dist < 1400.0) damage = (int) (damage * 2 / 3); else if (dist > 1400.0) damage = (int) (damage * 1 / 2); } //gi.cprintf(targ, PRINT_HIGH, "z_rel is %f\n leg: %f stomach: %f chest: %f\n", z_rel, LEG_DAMAGE, STOMACH_DAMAGE, CHEST_DAMAGE ); //gi.cprintf(targ, PRINT_HIGH, "point[2]: %f targ->s.origin[2]: %f height: %d\n", point[2], targ->s.origin[2], height ); //gi.cprintf(targ, PRINT_HIGH, "abs(trag->min[2]): %d targ_max[2] %d\n", (int)abs(targ->mins[2]), (int)targ_maxs2); //gi.cprintf(attacker, PRINT_HIGH, "abs(trag->min[2]): %d targ_max[2] %d\n", (int)abs(targ->mins[2]), (int)targ_maxs2); //gi.cprintf(attacker, PRINT_HIGH, "abs(trag->min[0]): %d targ_max[0] %d\n", (int)abs(targ->mins[0]), (int)targ->maxs[0]); //gi.cprintf(attacker, PRINT_HIGH, "abs(trag->min[1]): %d targ_max[1] %d\n", (int)abs(targ->mins[1]), (int)targ->maxs[1]); if (from_top < 2 * HEAD_HEIGHT) { vec3_t new_point; VerifyHeadShot (point, dir, HEAD_HEIGHT, new_point); VectorSubtract (new_point, targ->s.origin, new_point); //gi.cprintf(attacker, PRINT_HIGH, "z: %d y: %d x: %d\n", (int)(targ_maxs2 - new_point[2]),(int)(new_point[1]) , (int)(new_point[0]) ); if ((targ_maxs2 - new_point[2]) < HEAD_HEIGHT && (abs (new_point[1])) < HEAD_HEIGHT * .8 && (abs (new_point[0])) < HEAD_HEIGHT * .8) { head_success = 1; } } if (head_success) { if (attacker->client) { if (!teamplay->value || team_round_going || stats_afterround->value) { attacker->client->resp.stats_headshot[mod]++; } //AQ2:TNG Slicer Last Damage Location if (INV_AMMO(targ, HELM_NUM)) { attacker->client->resp.last_damaged_part = LOC_KVLR_HELMET; if ((!teamplay->value || team_round_going || stats_afterround->value)) attacker->client->resp.stats_locations[LOC_KVLR_HELMET]++; } else { attacker->client->resp.last_damaged_part = LOC_HDAM; if ((!teamplay->value || team_round_going || stats_afterround->value)) attacker->client->resp.stats_locations[LOC_HDAM]++; } //AQ2:TNG END if (!OnSameTeam (targ, attacker)) attacker->client->resp.hs_streak++; // AQ:TNG Igor[Rock] changing sound dir if (attacker->client->resp.hs_streak == 3) { if (use_rewards->value) { sprintf (buf, "ACCURACY %s!", attacker->client->pers.netname); CenterPrintAll (buf); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("tng/accuracy.wav"), 1.0, ATTN_NONE, 0.0); } attacker->client->resp.hs_streak = 0; } // end of changing sound dir } if (INV_AMMO(targ, HELM_NUM) && mod != MOD_KNIFE && mod != MOD_KNIFE_THROWN && mod != MOD_SNIPER) { if (attacker->client) { gi.cprintf (attacker, PRINT_HIGH, "%s has a Kevlar Helmet - AIM FOR THE BODY!\n", targ->client->pers.netname); gi.cprintf (targ, PRINT_HIGH, "Kevlar Helmet absorbed a part of %s's shot\n", attacker->client->pers.netname); } gi.sound (targ, CHAN_ITEM, gi.soundindex("misc/vest.wav"), 1, ATTN_NORM, 0); damage = (int) (damage / 2); damage_type = LOC_HDAM; bleeding = 0; instant_dam = 1; stopAP = 1; do_sparks = 1; } else if (INV_AMMO(targ, HELM_NUM) && mod == MOD_SNIPER) { if (attacker->client) { gi.cprintf (attacker, PRINT_HIGH, "%s has a Kevlar Helmet, too bad you have AP rounds...\n", targ->client->pers.netname); gi.cprintf (targ, PRINT_HIGH, "Kevlar Helmet absorbed some of %s's AP sniper round\n", attacker->client->pers.netname); } damage = (int) (damage * 0.325); gi.sound (targ, CHAN_VOICE, gi.soundindex("misc/headshot.wav"), 1, ATTN_NORM, 0); damage_type = LOC_HDAM; } else { damage = damage * 1.8 + 1; gi.cprintf (targ, PRINT_HIGH, "Head damage\n"); if (attacker->client) gi.cprintf (attacker, PRINT_HIGH, "You hit %s in the head\n", targ->client->pers.netname); damage_type = LOC_HDAM; if (mod != MOD_KNIFE && mod != MOD_KNIFE_THROWN) gi.sound (targ, CHAN_VOICE, gi.soundindex ("misc/headshot.wav"), 1, ATTN_NORM, 0); //else // gi.sound(targ, CHAN_VOICE, gi.soundindex("misc/glurp.wav"), 1, ATTN_NORM, 0); } } else if (z_rel < LEG_DAMAGE) { damage = damage * .25; gi.cprintf (targ, PRINT_HIGH, "Leg damage\n"); if (attacker->client) { attacker->client->resp.hs_streak = 0; gi.cprintf (attacker, PRINT_HIGH, "You hit %s in the legs\n", targ->client->pers.netname); } damage_type = LOC_LDAM; targ->client->leg_damage = 1; targ->client->leghits++; //AQ2:TNG Slicer Last Damage Location attacker->client->resp.last_damaged_part = LOC_LDAM; //AQ2:TNG END if (!teamplay->value || team_round_going || stats_afterround->value) attacker->client->resp.stats_locations[LOC_LDAM]++; // TNG Stats } else if (z_rel < STOMACH_DAMAGE) { damage = damage * .4; gi.cprintf (targ, PRINT_HIGH, "Stomach damage\n"); if (attacker->client) { attacker->client->resp.hs_streak = 0; gi.cprintf (attacker, PRINT_HIGH, "You hit %s in the stomach\n", targ->client->pers.netname); } damage_type = LOC_SDAM; //TempFile bloody gibbing if (mod == MOD_SNIPER && sv_gib->value) ThrowGib (targ, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); //AQ2:TNG Slicer Last Damage Location attacker->client->resp.last_damaged_part = LOC_SDAM; //AQ2:TNG END if (!teamplay->value || team_round_going || stats_afterround->value) attacker->client->resp.stats_locations[LOC_SDAM]++; // TNG Stats } else //(z_rel < CHEST_DAMAGE) { if (attacker->client) { attacker->client->resp.hs_streak = 0; } if (INV_AMMO(targ, KEV_NUM) && mod != MOD_KNIFE && mod != MOD_KNIFE_THROWN && mod != MOD_SNIPER) { if (attacker->client) { gi.cprintf (attacker, PRINT_HIGH, "%s has a Kevlar Vest - AIM FOR THE HEAD!\n", targ->client->pers.netname); gi.cprintf (targ, PRINT_HIGH, "Kevlar Vest absorbed most of %s's shot\n", attacker->client->pers.netname); /* if (IsFemale(targ)) gi.cprintf(attacker, PRINT_HIGH, "You bruised %s through her Kevlar Vest\n", targ->client->pers.netname); else gi.cprintf(attacker, PRINT_HIGH, "You bruised %s through his Kevlar Vest\n", targ->client->pers.netname); */ } gi.sound (targ, CHAN_ITEM, gi.soundindex ("misc/vest.wav"), 1, ATTN_NORM, 0); damage = (int) (damage / 10); damage_type = LOC_CDAM; bleeding = 0; instant_dam = 1; stopAP = 1; do_sparks = 1; } else if (INV_AMMO(targ, KEV_NUM) && mod == MOD_SNIPER) { if (attacker->client) { gi.cprintf (attacker, PRINT_HIGH, "%s has a Kevlar Vest, too bad you have AP rounds...\n", targ->client->pers.netname); gi.cprintf (targ, PRINT_HIGH, "Kevlar Vest absorbed some of %s's AP sniper round\n", attacker->client->pers.netname); } damage = damage * .325; damage_type = LOC_CDAM; } else { damage = damage * .65; gi.cprintf (targ, PRINT_HIGH, "Chest damage\n"); if (attacker->client) gi.cprintf (attacker, PRINT_HIGH, "You hit %s in the chest\n", targ->client->pers.netname); damage_type = LOC_CDAM; //TempFile bloody gibbing if (mod == MOD_SNIPER && sv_gib->value) ThrowGib (targ, "models/objects/gibs/sm_meat/tris.md2", damage, GIB_ORGANIC); } //AQ2:TNG Slicer Last Damage Location if (INV_AMMO(targ, KEV_NUM) && mod != MOD_KNIFE && mod != MOD_KNIFE_THROWN) { attacker->client->resp.last_damaged_part = LOC_KVLR_VEST; if (!teamplay->value || team_round_going || stats_afterround->value) attacker->client->resp.stats_locations[LOC_KVLR_VEST]++; // TNG Stats } else { attacker->client->resp.last_damaged_part = LOC_CDAM; if (!teamplay->value || team_round_going || stats_afterround->value) attacker->client->resp.stats_locations[LOC_CDAM]++; // TNG Stats } //AQ2:TNG END } /*else { // no mod to damage gi.cprintf(targ, PRINT_HIGH, "Head damage\n"); if (attacker->client) gi.cprintf(attacker, PRINT_HIGH, "You hit %s in the head\n", targ->client->pers.netname); damage_type = LOC_HDAM; gi.sound(targ, CHAN_VOICE, gi.soundindex("misc/headshot.wav"), 1, ATTN_NORM, 0); } */ } if (team_round_going && attacker->client && targ != attacker && OnSameTeam (targ, attacker)) { Add_TeamWound (attacker, targ, mod); } } } if (damage_type && !instant_dam) // bullets but not vest hits { vec3_t temp; vec3_t temporig; //vec3_t forward; VectorMA (targ->s.origin, 50, dir, temp); //AngleVectors (attacker->client->v_angle, forward, NULL, NULL); VectorScale (dir, 20, temp); VectorAdd (point, temp, temporig); if (mod != MOD_SNIPER) spray_blood (targ, temporig, dir, damage, mod); else spray_sniper_blood (targ, temporig, dir); } if (mod == MOD_FALLING && !(targ->flags & FL_GODMODE) ) { if (targ->client && targ->health > 0) { gi.cprintf (targ, PRINT_HIGH, "Leg damage\n"); targ->client->leg_damage = 1; targ->client->leghits++; // bleeding = 1; for testing } } // friendly fire avoidance // if enabled you can't hurt teammates (but you can hurt yourself) // knockback still occurs if (targ != attacker && ((deathmatch->value && ((int)dmflags->value & (DF_MODELTEAMS | DF_SKINTEAMS))) || coop->value)) { if (OnSameTeam (targ, attacker)) { if ((int)dmflags->value & DF_NO_FRIENDLY_FIRE && (team_round_going || !ff_afterround->value)) damage = 0; else mod |= MOD_FRIENDLY_FIRE; } } meansOfDeath = mod; locOfDeath = damage_type; // location client = targ->client; if (dflags & DAMAGE_BULLET) te_sparks = TE_BULLET_SPARKS; else te_sparks = TE_SPARKS; VectorNormalize (dir); // bonus damage for suprising a monster // if (!(dflags & DAMAGE_RADIUS) && (targ->svflags & SVF_MONSTER) && (attacker->client) && (!targ->enemy) && (targ->health > 0)) // damage *= 2; if (targ->flags & FL_NO_KNOCKBACK) knockback = 0; // figure momentum add if (!(dflags & DAMAGE_NO_KNOCKBACK)) { if ((knockback) && (targ->movetype != MOVETYPE_NONE) && (targ->movetype != MOVETYPE_BOUNCE) && (targ->movetype != MOVETYPE_PUSH) && (targ->movetype != MOVETYPE_STOP)) { vec3_t kvel, flydir; float mass; if (mod != MOD_FALLING) { VectorCopy (dir, flydir); flydir[2] += 0.4f; } if (targ->mass < 50) mass = 50; else mass = targ->mass; if (targ->client && attacker == targ) VectorScale (flydir, 1600.0 * (float) knockback / mass, kvel); // the rocket jump hack... else VectorScale (flydir, 500.0 * (float) knockback / mass, kvel); // FB //if (mod == MOD_KICK ) //{ // kvel[2] = 0; //} VectorAdd (targ->velocity, kvel, targ->velocity); } } take = damage; save = 0; // check for godmode if ((targ->flags & FL_GODMODE) && !(dflags & DAMAGE_NO_PROTECTION)) { take = 0; save = damage; SpawnDamage (te_sparks, point, normal, save); } // zucc don't need this stuff, but to remove it need to change how damagefeedback works with colors // check for invincibility if ((client && client->invincible_framenum > level.framenum) && !(dflags & DAMAGE_NO_PROTECTION)) { if (targ->pain_debounce_time < level.time) { gi.sound (targ, CHAN_ITEM, gi.soundindex ("items/protect4.wav"), 1, ATTN_NORM, 0); targ->pain_debounce_time = level.time + 2; } take = 0; save = damage; } psave = CheckPowerArmor (targ, point, normal, take, dflags); take -= psave; asave = CheckArmor (targ, point, normal, take, te_sparks, dflags); take -= asave; //treat cheat/powerup savings the same as armor asave += save; // team damage avoidance if (!(dflags & DAMAGE_NO_PROTECTION) && CheckTeamDamage (targ, attacker)) return; if ((mod == MOD_M3) || (mod == MOD_HC) || (mod == MOD_HELD_GRENADE) || (mod == MOD_HG_SPLASH) || (mod == MOD_G_SPLASH) || (mod == MOD_BREAKINGGLASS)) { //FB 6/3/99 - shotgun damage report stuff int playernum = targ - g_edicts; playernum--; if (playernum >= 0 && playernum <= game.maxclients - 1) *(took_damage + playernum) = 1; //FB 6/3/99 bleeding = 1; instant_dam = 0; } /* if ( (mod == MOD_M3) || (mod == MOD_HC) ) { instant_dam = 1; remain = take % 2; take = (int)(take/2); // balances out difference in how action and axshun handle damage/bleeding } */ if (ctf->value) CTFCheckHurtCarrier (targ, attacker); // do the damage if (take) { // zucc added check for stopAP, if it hit a vest we want sparks if (((targ->svflags & SVF_MONSTER) || (client)) && !do_sparks) SpawnDamage (TE_BLOOD, point, normal, take); else SpawnDamage (te_sparks, point, normal, take); // all things that have at least some instantaneous damage, i.e. bruising/falling if (instant_dam) targ->health = targ->health - take; if (targ->health <= 0) { if (client && attacker->client) { //Added these here also, if this is the last shot and before shots is from //different attacker, msg's would go to wrong client -M if (!OnSameTeam (attacker, targ)) attacker->client->resp.damage_dealt += damage; client->attacker = attacker; client->attacker_mod = mod; client->attacker_loc = damage_type; } if ((targ->svflags & SVF_MONSTER) || (client)) targ->flags |= FL_NO_KNOCKBACK; Killed (targ, inflictor, attacker, take, point); return; } } if (targ->svflags & SVF_MONSTER) { M_ReactToDamage (targ, attacker); if (!(targ->monsterinfo.aiflags & AI_DUCKED) && (take)) { targ->pain (targ, attacker, knockback, take); // nightmare mode monsters don't go into pain frames often if (skill->value == 3) targ->pain_debounce_time = level.time + 5; } } else if (client) { if (!(targ->flags & FL_GODMODE) && (take)) targ->pain (targ, attacker, knockback, take); } else if (take) { if (targ->pain) targ->pain (targ, attacker, knockback, take); } // add to the damage inflicted on a player this frame // the total will be turned into screen blends and view angle kicks // at the end of the frame if (client) { client->damage_parmor += psave; client->damage_armor += asave; client->damage_blood += take; client->damage_knockback += knockback; //zucc handle adding bleeding here if (damage_type && bleeding) // one of the hit location weapons { /* zucc add in partial bleeding, changed if ( client->bleeding < 4*damage*BLEED_TIME ) { client->bleeding = 4*damage*BLEED_TIME + client->bleeding/2; } else { client->bleeding += damage*BLEED_TIME*2; } */ client->bleeding += damage * BLEED_TIME; VectorSubtract (point, targ->absmax, targ->client->bleedloc_offset); //VectorSubtract(point, targ->s.origin, client->bleedloc_offset); } else if (bleeding) { /* if ( client->bleeding < damage*BLEED_TIME ) { client->bleeding = damage*BLEED_TIME; //client->bleedcount = 0; } */ client->bleeding += damage * BLEED_TIME; VectorSubtract (point, targ->absmax, targ->client->bleedloc_offset); //VectorSubtract(point, targ->s.origin, client->bleedloc_offset); } if (attacker->client) { if (!OnSameTeam (attacker, targ)) attacker->client->resp.damage_dealt += damage; client->attacker = attacker; client->attacker_mod = mod; client->attacker_loc = damage_type; client->push_timeout = 50; //VectorCopy(dir, client->bleeddir ); //VectorCopy(point, client->bleedpoint ); //VectorCopy(normal, client->bleednormal); } VectorCopy (point, client->damage_from); } } /* ============ T_RadiusDamage ============ */ void T_RadiusDamage (edict_t * inflictor, edict_t * attacker, float damage, edict_t * ignore, float radius, int mod) { float points; edict_t *ent = NULL; vec3_t v; vec3_t dir; while ((ent = findradius (ent, inflictor->s.origin, radius)) != NULL) { if (ent == ignore) continue; if (!ent->takedamage) continue; VectorAdd (ent->mins, ent->maxs, v); VectorMA (ent->s.origin, 0.5, v, v); VectorSubtract (inflictor->s.origin, v, v); points = damage - 0.5 * VectorLength (v); //zucc reduce damage for crouching, max is 32 when standing if (ent->maxs[2] < 20) { points = points * 0.5; // hefty reduction in damage } //if (ent == attacker) //points = points * 0.5; if (points > 0) { #ifdef _DEBUG if (0 == Q_stricmp (ent->classname, "func_explosive")) { CGF_SFX_ShootBreakableGlass (ent, inflictor, 0, mod); } else #endif if (CanDamage (ent, inflictor)) { VectorSubtract (ent->s.origin, inflictor->s.origin, dir); // zucc scaled up knockback(kick) of grenades T_Damage (ent, inflictor, attacker, dir, ent->s.origin, vec3_origin, (int) (points * .75), (int) (points * .75), DAMAGE_RADIUS, mod); } } } }
551
./aq2-tng/source/a_ctf.c
//----------------------------------------------------------------------------- // CTF related code // // $Id: a_ctf.c,v 1.20 2003/06/15 21:43:53 igor Exp $ // //----------------------------------------------------------------------------- // $Log: a_ctf.c,v $ // Revision 1.20 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.19 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.18 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.17 2002/02/18 17:17:20 freud // Fixed the CTF leaving team bug. Also made the shield more efficient, // No falling damage. // // Revision 1.16 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.15 2001/08/08 12:42:22 slicerdw // Ctf Should finnaly be fixed now, lets hope so // // Revision 1.14 2001/08/06 14:38:44 ra // Adding UVtime for ctf // // Revision 1.13 2001/06/26 18:47:30 igor_rock // added ctf_respawn cvar // // Revision 1.12 2001/06/20 10:04:13 igor_rock // corrected the path for the flagsounds (from ctf/ to tng/) // // Revision 1.11 2001/06/15 14:18:07 igor_rock // corrected bug with destroyed flags (won't be destroyed anymore, instead they // return to the base). // // Revision 1.10 2001/06/13 13:05:41 igor_rock // corrected a minor error in CTFEffects // // Revision 1.9 2001/06/13 07:55:17 igor_rock // Re-Added a_match.h and a_match.c // Added CTF Header for a_ctf.h and a_ctf.c // //----------------------------------------------------------------------------- #include "g_local.h" ctfgame_t ctfgame; cvar_t *ctf; cvar_t *ctf_forcejoin; cvar_t *ctf_mode; cvar_t *ctf_dropflag; cvar_t *ctf_respawn; cvar_t *ctf_model; /*--------------------------------------------------------------------------*/ gitem_t *flag1_item; gitem_t *flag2_item; void CTFInit(void) { if (!flag1_item) flag1_item = FindItemByClassname("item_flag_team1"); if (!flag2_item) flag2_item = FindItemByClassname("item_flag_team2"); if(ctfgame.author) gi.TagFree(ctfgame.author); if(ctfgame.comment) gi.TagFree(ctfgame.comment); memset(&ctfgame, 0, sizeof(ctfgame)); } /*--------------------------------------------------------------------------*/ qboolean CTFLoadConfig(char *mapname) { char buf[1024]; char *ptr; FILE *fh; gi.dprintf("Trying to load CTF configuration file\n", mapname); /* zero is perfectly acceptable respawn time, but we want to know if it came from the config or not */ ctfgame.spawn_red = -1; ctfgame.spawn_blue = -1; sprintf (buf, "%s/tng/%s.ctf", GAMEVERSION, mapname); fh = fopen (buf, "r"); if (!fh) { gi.dprintf ("Warning: CTF configuration file %s was not found.\n", buf); return false; } gi.dprintf("-------------------------------------\n"); gi.dprintf("CTF configuration loaded from %s\n", buf); ptr = INI_Find(fh, "ctf", "author"); if(ptr) { gi.dprintf(" Author : %s\n", ptr); ctfgame.author = gi.TagMalloc(strlen(ptr)+1, TAG_LEVEL); strcpy(ctfgame.author, ptr); } ptr = INI_Find(fh, "ctf", "comment"); if(ptr) { gi.dprintf(" Comment : %s\n", ptr); ctfgame.comment = gi.TagMalloc(strlen(ptr)+1, TAG_LEVEL); strcpy(ctfgame.comment, ptr); } ptr = INI_Find(fh, "ctf", "type"); if(ptr) { gi.dprintf(" Game type : %s\n", ptr); if(strcmp(ptr, "balanced") == 0) ctfgame.type = 1; if(strcmp(ptr, "offdef") == 0) ctfgame.type = 2; } ptr = INI_Find(fh, "ctf", "offence"); if(ptr) { gi.dprintf(" Offence : %s\n", ptr); ctfgame.offence = TEAM1; if(strcmp(ptr, "blue") == 0) ctfgame.offence = TEAM2; } ptr = INI_Find(fh, "ctf", "grapple"); gi.cvar_forceset("use_grapple", "0"); if(ptr) { gi.dprintf(" Grapple : %s\n", ptr); if(strcmp(ptr, "1") == 0) gi.cvar_forceset("use_grapple", "1"); else if(strcmp(ptr, "2") == 0) gi.cvar_forceset("use_grapple", "2"); } gi.dprintf(" Spawn times\n"); ptr = INI_Find(fh, "respawn", "red"); if(ptr) { gi.dprintf(" Red : %s\n", ptr); ctfgame.spawn_red = atoi(ptr); } ptr = INI_Find(fh, "respawn", "blue"); if(ptr) { gi.dprintf(" Blue : %s\n", ptr); ctfgame.spawn_blue = atoi(ptr); } gi.dprintf(" Flags\n"); ptr = INI_Find(fh, "flags", "red"); if(ptr) { gi.dprintf(" Red : %s\n", ptr); CTFSetFlag(TEAM1, ptr); } ptr = INI_Find(fh, "flags", "blue"); if(ptr) { gi.dprintf(" Blue : %s\n", ptr); CTFSetFlag(TEAM2, ptr); } gi.dprintf(" Spawns\n"); ptr = INI_Find(fh, "spawns", "red"); if(ptr) { gi.dprintf(" Red : %s\n", ptr); CTFSetTeamSpawns(TEAM1, ptr); ctfgame.custom_spawns = true; } ptr = INI_Find(fh, "spawns", "blue"); if(ptr) { gi.dprintf(" Blue : %s\n", ptr); CTFSetTeamSpawns(TEAM2, ptr); ctfgame.custom_spawns = true; } // automagically change spawns *only* when we do not have team spawns if(!ctfgame.custom_spawns) ChangePlayerSpawns(); gi.dprintf("-------------------------------------\n"); fclose(fh); return true; } /* taken from g_spawn */ char *ED_NewString (char *string); void CTFSetFlag(int team, char *str) { char *flag_name; edict_t *ent = NULL; vec3_t position; if(team == TEAM1) flag_name = "item_flag_team1"; else if(team == TEAM2) flag_name = "item_flag_team2"; else return; if (sscanf(str, "<%f %f %f>", &position[0], &position[1], &position[2]) != 3) return; /* find and remove existing flag(s) if any */ while ((ent = G_Find(ent, FOFS(classname), flag_name)) != NULL) { G_FreeEdict (ent); } ent = G_Spawn (); ent->classname = ED_NewString (flag_name); ent->spawnflags &= ~(SPAWNFLAG_NOT_EASY | SPAWNFLAG_NOT_MEDIUM | SPAWNFLAG_NOT_HARD | SPAWNFLAG_NOT_COOP | SPAWNFLAG_NOT_DEATHMATCH); VectorCopy(position, ent->s.origin); ED_CallSpawn (ent); } void CTFSetTeamSpawns(int team, char *str) { edict_t *spawn = NULL; char *next; vec3_t pos; float angle; char *team_spawn_name = "info_player_team1"; if(team == TEAM2) team_spawn_name = "info_player_team2"; /* find and remove all team spawns for this team */ while ((spawn = G_Find(spawn, FOFS(classname), team_spawn_name)) != NULL) { G_FreeEdict (spawn); } next = strtok(str, ","); do { if (sscanf(next, "<%f %f %f %f>", &pos[0], &pos[1], &pos[2], &angle) != 4) { gi.dprintf("CTFSetTeamSpawns: invalid spawn point: %s, expected <x y z a>\n", next); continue; } spawn = G_Spawn (); VectorCopy(pos, spawn->s.origin); spawn->s.angles[YAW] = angle; spawn->classname = ED_NewString (team_spawn_name); ED_CallSpawn (spawn); next = strtok(NULL, ","); } while(next != NULL); } /* returns the respawn time for this particular client */ int CTFGetRespawnTime(edict_t *ent) { int spawntime = ctf_respawn->value; if(ent->client->resp.team == TEAM1 && ctfgame.spawn_red > -1) spawntime = ctfgame.spawn_red; if(ent->client->resp.team == TEAM2 && ctfgame.spawn_blue > -1) spawntime = ctfgame.spawn_blue; gi.cprintf(ent, PRINT_HIGH, "You will respawn in %d seconds\n", spawntime); return spawntime; } /* Has flag: * JBravo: Does the player have a flag ? */ qboolean HasFlag(edict_t * ent) { if (!ctf->value) return false; if (ent->client->pers.inventory[ITEM_INDEX(flag1_item)] || ent->client->pers.inventory[ITEM_INDEX(flag2_item)]) return true; return false; } char *CTFTeamName(int team) { switch (team) { case TEAM1: return "RED"; case TEAM2: return "BLUE"; } return "UKNOWN"; } char *CTFOtherTeamName(int team) { switch (team) { case TEAM1: return "BLUE"; case TEAM2: return "RED"; } return "UKNOWN"; } int CTFOtherTeam(int team) { switch (team) { case TEAM1: return TEAM2; case TEAM2: return TEAM1; case NOTEAM: return NOTEAM; /* there is no other team for NOTEAM, but I want it back! */ } return -1; // invalid value } /*--------------------------------------------------------------------------*/ edict_t *SelectRandomDeathmatchSpawnPoint(void); edict_t *SelectFarthestDeathmatchSpawnPoint(void); float PlayersRangeFromSpot(edict_t * spot); void ResetPlayers() { edict_t *ent; int i; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (ent->inuse) { // ent->client->resp.team = NOTEAM; PutClientInServer(ent); } } } void CTFSwapTeams() { vec3_t point; edict_t *ent; int i; for (i = 0; i < game.maxclients; i++) { ent = &g_edicts[1 + i]; if (ent->inuse) { ent->client->resp.team = CTFOtherTeam(ent->client->resp.team); } } /* swap scores too! */ i = ctfgame.team1; ctfgame.team1 = ctfgame.team2; ctfgame.team2 = i; } void CTFAssignTeam(gclient_t * who) { edict_t *player; int i, team1count = 0, team2count = 0; who->resp.ctf_state = CTF_STATE_START; if (!((int) dmflags->value & DF_CTF_FORCEJOIN)) { who->resp.team = NOTEAM; return; } for (i = 1; i <= (int)maxclients->value; i++) { player = &g_edicts[i]; if (!player->inuse || player->client == who) continue; switch (player->client->resp.team) { case TEAM1: team1count++; break; case TEAM2: team2count++; } } if (team1count < team2count) who->resp.team = TEAM1; else if (team2count < team1count) who->resp.team = TEAM2; else if (rand() & 1) who->resp.team = TEAM1; else who->resp.team = TEAM2; } /* ================ SelectCTFSpawnPoint go to a ctf point, but NOT the two points closest to other players ================ */ edict_t *SelectCTFSpawnPoint(edict_t * ent) { edict_t *spot, *spot1, *spot2; int count = 0; int selection; float range, range1, range2; char *cname; /*if (ent->client->resp.ctf_state != CTF_STATE_START) { if (rand() & 1) { if ((int) (dmflags->value) & DF_SPAWN_FARTHEST) return SelectFarthestDeathmatchSpawnPoint(); else return SelectRandomDeathmatchSpawnPoint(); } }*/ //Why the fuck this was here? -Mani ent->client->resp.ctf_state = CTF_STATE_PLAYING; switch (ent->client->resp.team) { case TEAM1: cname = "info_player_team1"; break; case TEAM2: cname = "info_player_team2"; break; default: /* FIXME: might return NULL when dm spawns are converted to team ones */ return SelectRandomDeathmatchSpawnPoint(); } spot = NULL; range1 = range2 = 99999; spot1 = spot2 = NULL; while ((spot = G_Find(spot, FOFS(classname), cname)) != NULL) { count++; range = PlayersRangeFromSpot(spot); if (range < range1) { if (range1 < range2) { range2 = range1; spot2 = spot1; } range1 = range; spot1 = spot; } else if (range < range2) { range2 = range; spot2 = spot; } } if (!count) return SelectRandomDeathmatchSpawnPoint(); if (count <= 2) { spot1 = spot2 = NULL; } else count -= 2; selection = rand() % count; spot = NULL; do { spot = G_Find(spot, FOFS(classname), cname); if (spot == spot1 || spot == spot2) selection++; } while (selection--); return spot; } /*------------------------------------------------------------------------*/ /* CTFFragBonuses Calculate the bonuses for flag defense, flag carrier defense, etc. Note that bonuses are not cumaltive. You get one, they are in importance order. */ void CTFFragBonuses(edict_t * targ, edict_t * inflictor, edict_t * attacker) { int i, otherteam; gitem_t *flag_item, *enemy_flag_item; edict_t *ent, *flag, *carrier; char *c; vec3_t v1, v2; carrier = NULL; // no bonus for fragging yourself if (!targ->client || !attacker->client || targ == attacker) return; otherteam = CTFOtherTeam(targ->client->resp.team); if (otherteam < 0) return; // whoever died isn't on a team // same team, if the flag at base, check to he has the enemy flag if (targ->client->resp.team == TEAM1) { flag_item = flag1_item; enemy_flag_item = flag2_item; } else { flag_item = flag2_item; enemy_flag_item = flag1_item; } // did the attacker frag the flag carrier? if (targ->client->pers.inventory[ITEM_INDEX(enemy_flag_item)]) { attacker->client->resp.ctf_lastfraggedcarrier = level.time; attacker->client->resp.score += CTF_FRAG_CARRIER_BONUS; gi.cprintf(attacker, PRINT_MEDIUM, "BONUS: %d points for fragging enemy flag carrier.\n", CTF_FRAG_CARRIER_BONUS); // the the target had the flag, clear the hurt carrier // field on the other team for (i = 1; i <= maxclients->value; i++) { ent = g_edicts + i; if (ent->inuse && ent->client->resp.team == otherteam) ent->client->resp.ctf_lasthurtcarrier = 0; } return; } if (targ->client->resp.ctf_lasthurtcarrier && level.time - targ->client->resp.ctf_lasthurtcarrier < CTF_CARRIER_DANGER_PROTECT_TIMEOUT && !attacker->client->pers.inventory[ITEM_INDEX(flag_item)]) { // attacker is on the same team as the flag carrier and // fragged a guy who hurt our flag carrier attacker->client->resp.score += CTF_CARRIER_DANGER_PROTECT_BONUS; gi.bprintf(PRINT_MEDIUM, "%s defends %s's flag carrier against an agressive enemy\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); IRC_printf(IRC_T_GAME, "%n defends %n's flag carrier against an agressive enemy\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); return; } // flag and flag carrier area defense bonuses // we have to find the flag and carrier entities // find the flag switch (attacker->client->resp.team) { case TEAM1: c = "item_flag_team1"; break; case TEAM2: c = "item_flag_team2"; break; default: return; } flag = NULL; while ((flag = G_Find(flag, FOFS(classname), c)) != NULL) { if (!(flag->spawnflags & DROPPED_ITEM)) break; } if (!flag) return; // can't find attacker's flag // find attacker's team's flag carrier for (i = 1; i <= maxclients->value; i++) { carrier = g_edicts + i; if (carrier->inuse && carrier->client->pers.inventory[ITEM_INDEX(flag_item)]) break; carrier = NULL; } // ok we have the attackers flag and a pointer to the carrier // check to see if we are defending the base's flag VectorSubtract(targ->s.origin, flag->s.origin, v1); VectorSubtract(attacker->s.origin, flag->s.origin, v2); if (VectorLength(v1) < CTF_TARGET_PROTECT_RADIUS || VectorLength(v2) < CTF_TARGET_PROTECT_RADIUS || loc_CanSee(flag, targ) || loc_CanSee(flag, attacker)) { // we defended the base flag attacker->client->resp.score += CTF_FLAG_DEFENSE_BONUS; if (flag->solid == SOLID_NOT) { gi.bprintf(PRINT_MEDIUM, "%s defends the %s base.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); IRC_printf(IRC_T_GAME, "%n defends the %n base.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); } else { gi.bprintf(PRINT_MEDIUM, "%s defends the %s flag.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); IRC_printf(IRC_T_GAME, "%n defends the %n flag.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); } return; } if (carrier && carrier != attacker) { VectorSubtract(targ->s.origin, carrier->s.origin, v1); VectorSubtract(attacker->s.origin, carrier->s.origin, v1); if (VectorLength(v1) < CTF_ATTACKER_PROTECT_RADIUS || VectorLength(v2) < CTF_ATTACKER_PROTECT_RADIUS || loc_CanSee(carrier, targ) || loc_CanSee(carrier, attacker)) { attacker->client->resp.score += CTF_CARRIER_PROTECT_BONUS; gi.bprintf(PRINT_MEDIUM, "%s defends the %s's flag carrier.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); IRC_printf(IRC_T_GAME, "%n defends the %n's flag carrier.\n", attacker->client->pers.netname, CTFTeamName(attacker->client->resp.team)); return; } } } void CTFCheckHurtCarrier(edict_t * targ, edict_t * attacker) { gitem_t *flag_item; if (!targ->client || !attacker->client) return; if (targ->client->resp.team == TEAM1) flag_item = flag2_item; else flag_item = flag1_item; if (targ->client->pers.inventory[ITEM_INDEX(flag_item)] && targ->client->resp.team != attacker->client->resp.team) attacker->client->resp.ctf_lasthurtcarrier = level.time; } /*------------------------------------------------------------------------*/ void CTFResetFlag(int team) { char *c; int i; edict_t *ent = NULL; switch (team) { case TEAM1: c = "item_flag_team1"; break; case TEAM2: c = "item_flag_team2"; break; default: return; } /* hifi: drop this team flag if a player is carrying one (so the next loop returns it correctly) */ for (i = 1; i <= (int)maxclients->value; i++) { ent= &g_edicts[i]; if(team == TEAM1) { if (ent->client->pers.inventory[ITEM_INDEX(flag1_item)]) { Drop_Item(ent, flag1_item); ent->client->pers.inventory[ITEM_INDEX(flag1_item)] = 0; } } else if(team == TEAM2) { if (ent->client->pers.inventory[ITEM_INDEX(flag2_item)]) { Drop_Item(ent, flag2_item); ent->client->pers.inventory[ITEM_INDEX(flag2_item)] = 0; } } } while ((ent = G_Find(ent, FOFS(classname), c)) != NULL) { if (ent->spawnflags & DROPPED_ITEM) G_FreeEdict(ent); else { ent->svflags &= ~SVF_NOCLIENT; ent->solid = SOLID_TRIGGER; gi.linkentity(ent); ent->s.event = EV_ITEM_RESPAWN; } } } void CTFResetFlags(void) { CTFResetFlag(TEAM1); CTFResetFlag(TEAM2); } qboolean CTFPickup_Flag(edict_t * ent, edict_t * other) { int team, i; edict_t *player; gitem_t *flag_item, *enemy_flag_item; /* FIXME: players shouldn't be able to touch flags before LCA! */ if(!team_round_going) return false; // figure out what team this flag is if (strcmp(ent->classname, "item_flag_team1") == 0) team = TEAM1; else if (strcmp(ent->classname, "item_flag_team2") == 0) team = TEAM2; else { gi.cprintf(ent, PRINT_HIGH, "Don't know what team the flag is on.\n"); return false; } // same team, if the flag at base, check to he has the enemy flag if (team == TEAM1) { flag_item = flag1_item; enemy_flag_item = flag2_item; } else { flag_item = flag2_item; enemy_flag_item = flag1_item; } if (team == other->client->resp.team) { if (!(ent->spawnflags & DROPPED_ITEM)) { // the flag is at home base. if the player has the enemy // flag, he's just won! if (other->client->pers.inventory[ITEM_INDEX(enemy_flag_item)]) { gi.bprintf(PRINT_HIGH, "%s captured the %s flag!\n", other->client->pers.netname, CTFOtherTeamName(team)); IRC_printf(IRC_T_GAME, "%n captured the %n flag!\n", other->client->pers.netname, CTFOtherTeamName(team)); other->client->pers.inventory[ITEM_INDEX(enemy_flag_item)] = 0; ctfgame.last_flag_capture = level.time; ctfgame.last_capture_team = team; if (team == TEAM1) ctfgame.team1++; else ctfgame.team2++; gi.sound(ent, CHAN_RELIABLE + CHAN_NO_PHS_ADD + CHAN_VOICE, gi.soundindex("tng/flagcap.wav"), 1, ATTN_NONE, 0); // other gets another 10 frag bonus other->client->resp.score += CTF_CAPTURE_BONUS; CTFCapReward(other); // Ok, let's do the player loop, hand out the bonuses for (i = 1; i <= maxclients->value; i++) { player = &g_edicts[i]; if (!player->inuse) continue; if (player->client->resp.team != other->client->resp.team) player->client->resp.ctf_lasthurtcarrier = -5; else if (player->client->resp.team == other->client->resp.team) { if (player != other) player->client->resp.score += CTF_TEAM_BONUS; // award extra points for capture assists if (player->client->resp.ctf_lastreturnedflag + CTF_RETURN_FLAG_ASSIST_TIMEOUT > level.time) { gi.bprintf(PRINT_HIGH, "%s gets an assist for returning the flag!\n", player->client->pers.netname); IRC_printf(IRC_T_GAME, "%n gets an assist for returning the flag!\n", player->client->pers.netname); player->client->resp.score += CTF_RETURN_FLAG_ASSIST_BONUS; } if (player->client->resp.ctf_lastfraggedcarrier + CTF_FRAG_CARRIER_ASSIST_TIMEOUT > level.time) { gi.bprintf(PRINT_HIGH, "%s gets an assist for fragging the flag carrier!\n", player->client->pers.netname); IRC_printf(IRC_T_GAME, "%n gets an assist for fragging the flag carrier!\n", player->client->pers.netname); player->client->resp.score += CTF_FRAG_CARRIER_ASSIST_BONUS; } } } CTFResetFlags(); return false; } return false; // its at home base already } // hey, its not home. return it by teleporting it back gi.bprintf(PRINT_HIGH, "%s returned the %s flag!\n", other->client->pers.netname, CTFTeamName(team)); IRC_printf(IRC_T_GAME, "%n returned the %s flag!\n", other->client->pers.netname, CTFTeamName(team)); other->client->resp.score += CTF_RECOVERY_BONUS; other->client->resp.ctf_lastreturnedflag = level.time; gi.sound(ent, CHAN_RELIABLE + CHAN_NO_PHS_ADD + CHAN_VOICE, gi.soundindex("tng/flagret.wav"), 1, ATTN_NONE, 0); //CTFResetFlag will remove this entity! We must return false CTFResetFlag(team); return false; } // AQ2:TNG - JBravo adding UVtime if (other->client->ctf_uvtime) { other->client->ctf_uvtime = 0; gi.centerprintf(other, "Flag taken! Shields are DOWN! Run for it!"); } else { gi.centerprintf(other, "You've got the ENEMY FLAG! Run for it!"); } // hey, its not our flag, pick it up gi.bprintf(PRINT_HIGH, "%s got the %s flag!\n", other->client->pers.netname, CTFTeamName(team)); IRC_printf(IRC_T_GAME, "%n got the %n flag!\n", other->client->pers.netname, CTFTeamName(team)); other->client->resp.score += CTF_FLAG_BONUS; other->client->pers.inventory[ITEM_INDEX(flag_item)] = 1; other->client->resp.ctf_flagsince = level.time; // pick up the flag // if it's not a dropped flag, we just make is disappear // if it's dropped, it will be removed by the pickup caller if (!(ent->spawnflags & DROPPED_ITEM)) { ent->flags |= FL_RESPAWN; ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; } return true; } static void CTFDropFlagTouch(edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { //owner (who dropped us) can't touch for two secs if (other == ent->owner && ent->nextthink - level.time > CTF_AUTO_FLAG_RETURN_TIMEOUT - 2) return; Touch_Item(ent, other, plane, surf); } static void CTFDropFlagThink(edict_t * ent) { // auto return the flag // reset flag will remove ourselves if (strcmp(ent->classname, "item_flag_team1") == 0) { CTFResetFlag(TEAM1); gi.bprintf(PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName(TEAM1)); IRC_printf(IRC_T_GAME, "The %n flag has returned!\n", CTFTeamName(TEAM1)); } else if (strcmp(ent->classname, "item_flag_team2") == 0) { CTFResetFlag(TEAM2); gi.bprintf(PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName(TEAM2)); IRC_printf(IRC_T_GAME, "The %n flag has returned!\n", CTFTeamName(TEAM2)); } } // Called from PlayerDie, to drop the flag from a dying player void CTFDeadDropFlag(edict_t * self) { edict_t *dropped = NULL; if (!flag1_item || !flag2_item) CTFInit(); if (self->client->pers.inventory[ITEM_INDEX(flag1_item)]) { dropped = Drop_Item(self, flag1_item); self->client->pers.inventory[ITEM_INDEX(flag1_item)] = 0; gi.bprintf(PRINT_HIGH, "%s lost the %s flag!\n", self->client->pers.netname, CTFTeamName(TEAM1)); IRC_printf(IRC_T_GAME, "%n lost the %n flag!\n", self->client->pers.netname, CTFTeamName(TEAM1)); } else if (self->client->pers.inventory[ITEM_INDEX(flag2_item)]) { dropped = Drop_Item(self, flag2_item); self->client->pers.inventory[ITEM_INDEX(flag2_item)] = 0; gi.bprintf(PRINT_HIGH, "%s lost the %s flag!\n", self->client->pers.netname, CTFTeamName(TEAM2)); IRC_printf(IRC_T_GAME, "%n lost the %n flag!\n", self->client->pers.netname, CTFTeamName(TEAM2)); } if (dropped) { dropped->think = CTFDropFlagThink; dropped->nextthink = level.time + CTF_AUTO_FLAG_RETURN_TIMEOUT; dropped->touch = CTFDropFlagTouch; } } void CTFDrop_Flag(edict_t * ent, gitem_t * item) { edict_t *dropped = NULL; if (ctf_dropflag->value) { if (!flag1_item || !flag2_item) CTFInit(); if (ent->client->pers.inventory[ITEM_INDEX(flag1_item)]) { dropped = Drop_Item(ent, flag1_item); ent->client->pers.inventory[ITEM_INDEX(flag1_item)] = 0; } else if (ent->client->pers.inventory[ITEM_INDEX(flag2_item)]) { dropped = Drop_Item(ent, flag2_item); ent->client->pers.inventory[ITEM_INDEX(flag2_item)] = 0; } if (dropped) { dropped->think = CTFDropFlagThink; dropped->nextthink = level.time + CTF_AUTO_FLAG_RETURN_TIMEOUT; dropped->touch = CTFDropFlagTouch; } } else { if (rand() & 1) gi.cprintf(ent, PRINT_HIGH, "Only lusers drop flags.\n"); else gi.cprintf(ent, PRINT_HIGH, "Winners don't drop flags.\n"); } return; } static void CTFFlagThink(edict_t * ent) { if (ent->solid != SOLID_NOT) ent->s.frame = 173 + (((ent->s.frame - 173) + 1) % 16); ent->nextthink = level.time + FRAMETIME; } void CTFFlagSetup(edict_t * ent) { trace_t tr; vec3_t dest; VectorSet(ent->mins, -15, -15, -15); VectorSet(ent->maxs, 15, 15, 15); if (ent->model) gi.setmodel(ent, ent->model); else gi.setmodel(ent, ent->item->world_model); ent->solid = SOLID_TRIGGER; ent->movetype = MOVETYPE_TOSS; ent->touch = Touch_Item; VectorCopy(ent->s.origin, dest); dest[2] -= 128; tr = gi.trace(ent->s.origin, ent->mins, ent->maxs, dest, ent, MASK_SOLID); if (tr.startsolid) { gi.dprintf("CTFFlagSetup: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin)); G_FreeEdict(ent); return; } VectorCopy(tr.endpos, ent->s.origin); gi.linkentity(ent); ent->nextthink = level.time + FRAMETIME; ent->think = CTFFlagThink; } void CTFEffects(edict_t * player) { player->s.effects &= ~(EF_FLAG1 | EF_FLAG2); if (player->health > 0) { if (player->client->pers.inventory[ITEM_INDEX(flag1_item)]) { player->s.effects |= EF_FLAG1; } if (player->client->pers.inventory[ITEM_INDEX(flag2_item)]) { player->s.effects |= EF_FLAG2; } } // megahealth players glow anyway if(player->health > 100) player->s.effects |= EF_TAGTRAIL; if (player->client->pers.inventory[ITEM_INDEX(flag1_item)]) player->s.modelindex3 = gi.modelindex("models/flags/flag1.md2"); else if (player->client->pers.inventory[ITEM_INDEX(flag2_item)]) player->s.modelindex3 = gi.modelindex("models/flags/flag2.md2"); else player->s.modelindex3 = 0; } // called when we enter the intermission void CTFCalcScores(void) { int i; ctfgame.total1 = ctfgame.total2 = 0; for (i = 0; i < maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].resp.team == TEAM1) ctfgame.total1 += game.clients[i].resp.score; else if (game.clients[i].resp.team == TEAM2) ctfgame.total2 += game.clients[i].resp.score; } } void GetCTFScores(int *t1score, int *t2score) { *t1score = ctfgame.team1; *t2score = ctfgame.team2; } void SetCTFStats(edict_t * ent) { int p1, p2; edict_t *e; // logo headers for the frag display ent->client->ps.stats[STAT_TEAM1_HEADER] = gi.imageindex("ctfsb1"); ent->client->ps.stats[STAT_TEAM2_HEADER] = gi.imageindex("ctfsb2"); // if during intermission, we must blink the team header of the winning team if (level.intermissiontime && (level.framenum & 8)) { // blink 1/8th second // note that ctfgame.total[12] is set when we go to intermission if (ctfgame.team1 > ctfgame.team2) ent->client->ps.stats[STAT_TEAM1_HEADER] = 0; else if (ctfgame.team2 > ctfgame.team1) ent->client->ps.stats[STAT_TEAM2_HEADER] = 0; else if (ctfgame.total1 > ctfgame.total2) // frag tie breaker ent->client->ps.stats[STAT_TEAM1_HEADER] = 0; else if (ctfgame.total2 > ctfgame.total1) ent->client->ps.stats[STAT_TEAM2_HEADER] = 0; else { // tie game! ent->client->ps.stats[STAT_TEAM1_HEADER] = 0; ent->client->ps.stats[STAT_TEAM2_HEADER] = 0; } } // figure out what icon to display for team logos // three states: // flag at base // flag taken // flag dropped p1 = gi.imageindex("i_ctf1"); e = G_Find(NULL, FOFS(classname), "item_flag_team1"); if (e != NULL) { if (e->solid == SOLID_NOT) { int i; // not at base // check if on player p1 = gi.imageindex("i_ctf1d"); // default to dropped for (i = 1; i <= maxclients->value; i++) if (g_edicts[i].inuse && g_edicts[i].client->pers.inventory[ITEM_INDEX(flag1_item)]) { // enemy has it p1 = gi.imageindex("i_ctf1t"); break; } } else if (e->spawnflags & DROPPED_ITEM) p1 = gi.imageindex("i_ctf1d"); // must be dropped } p2 = gi.imageindex("i_ctf2"); e = G_Find(NULL, FOFS(classname), "item_flag_team2"); if (e != NULL) { if (e->solid == SOLID_NOT) { int i; // not at base // check if on player p2 = gi.imageindex("i_ctf2d"); // default to dropped for (i = 1; i <= maxclients->value; i++) if (g_edicts[i].inuse && g_edicts[i].client->pers.inventory[ITEM_INDEX(flag2_item)]) { // enemy has it p2 = gi.imageindex("i_ctf2t"); break; } } else if (e->spawnflags & DROPPED_ITEM) p2 = gi.imageindex("i_ctf2d"); // must be dropped } ent->client->ps.stats[STAT_TEAM1_PIC] = p1; ent->client->ps.stats[STAT_TEAM2_PIC] = p2; if (ctfgame.last_flag_capture && level.time - ctfgame.last_flag_capture < 5) { if (ctfgame.last_capture_team == TEAM1) if (level.framenum & 8) ent->client->ps.stats[STAT_TEAM1_PIC] = p1; else ent->client->ps.stats[STAT_TEAM1_PIC] = 0; else if (level.framenum & 8) ent->client->ps.stats[STAT_TEAM2_PIC] = p2; else ent->client->ps.stats[STAT_TEAM2_PIC] = 0; } ent->client->ps.stats[STAT_TEAM1_SCORE] = ctfgame.team1; ent->client->ps.stats[STAT_TEAM2_SCORE] = ctfgame.team2; ent->client->ps.stats[STAT_FLAG_PIC] = 0; if (ent->client->resp.team == TEAM1 && ent->client->pers.inventory[ITEM_INDEX(flag2_item)] && (level.framenum & 8)) ent->client->ps.stats[STAT_FLAG_PIC] = gi.imageindex("i_ctf2"); else if (ent->client->resp.team == TEAM2 && ent->client->pers.inventory[ITEM_INDEX(flag1_item)] && (level.framenum & 8)) ent->client->ps.stats[STAT_FLAG_PIC] = gi.imageindex("i_ctf1"); ent->client->ps.stats[STAT_ID_VIEW] = 0; if (!ent->client->resp.id) SetIDView(ent); } /*------------------------------------------------------------------------*/ /*QUAKED info_player_team1 (1 0 0) (-16 -16 -24) (16 16 32) potential team1 spawning position for ctf games */ void SP_info_player_team1(edict_t * self) { } /*QUAKED info_player_team2 (0 0 1) (-16 -16 -24) (16 16 32) potential team2 spawning position for ctf games */ void SP_info_player_team2(edict_t * self) { } /* ================== CTFScoreboardMessage ================== */ void CTFScoreboardMessage(edict_t * ent, edict_t * killer) { char entry[1024], string[1400], damage[50]; int len, i, j, k, n; int sorted[2][MAX_CLIENTS]; int sortedscores[2][MAX_CLIENTS]; int score, total[2], totalscore[2]; int last[2]; gclient_t *cl; edict_t *cl_ent; int team, maxsize = 1000; if (ent->client->scoreboardnum == 1) { // sort the clients by team and score total[0] = total[1] = 0; last[0] = last[1] = 0; totalscore[0] = totalscore[1] = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; if (game.clients[i].resp.team == TEAM1) team = 0; else if (game.clients[i].resp.team == TEAM2) team = 1; else continue; // unknown team? score = game.clients[i].resp.score; for (j = 0; j < total[team]; j++) { if (score > sortedscores[team][j]) break; } for (k = total[team]; k > j; k--) { sorted[team][k] = sorted[team][k - 1]; sortedscores[team][k] = sortedscores[team][k - 1]; } sorted[team][j] = i; sortedscores[team][j] = score; totalscore[team] += score; total[team]++; } // print level name and exit rules // add the clients in sorted order *string = 0; len = 0; // team one sprintf(string, "if 30 xv 8 yv 8 pic 30 endif " "xv 40 yv 28 string \"%4d/%-3d\" " "xv 98 yv 12 num 2 26 " "if 31 xv 168 yv 8 pic 31 endif " "xv 200 yv 28 string \"%4d/%-3d\" " "xv 256 yv 12 num 2 27 ", totalscore[0], total[0], totalscore[1], total[1]); len = strlen(string); for (i = 0; i < 16; i++) { if (i >= total[0] && i >= total[1]) break; // we're done *entry = 0; // left side if (i < total[0]) { cl = &game.clients[sorted[0][i]]; cl_ent = g_edicts + 1 + sorted[0][i]; sprintf(entry + strlen(entry), "ctf 0 %d %d %d %d ", 42 + i * 8, sorted[0][i], cl->resp.score, cl->ping > 999 ? 999 : cl->ping); if (cl_ent->client->pers.inventory[ITEM_INDEX(flag2_item)]) sprintf(entry + strlen(entry), "xv 56 yv %d picn sbfctf2 ", 42 + i * 8); if (maxsize - len > strlen(entry)) { strcat(string, entry); len = strlen(string); last[0] = i; } } // right side if (i < total[1]) { cl = &game.clients[sorted[1][i]]; cl_ent = g_edicts + 1 + sorted[1][i]; sprintf(entry + strlen(entry), "ctf 160 %d %d %d %d ", 42 + i * 8, sorted[1][i], cl->resp.score, cl->ping > 999 ? 999 : cl->ping); if (cl_ent->client->pers.inventory[ITEM_INDEX(flag1_item)]) sprintf(entry + strlen(entry), "xv 216 yv %d picn sbfctf1 ", 42 + i * 8); if (maxsize - len > strlen(entry)) { strcat(string, entry); len = strlen(string); last[1] = i; } } } // put in spectators if we have enough room if (last[0] > last[1]) j = last[0]; else j = last[1]; j = (j + 2) * 8 + 42; k = n = 0; if (maxsize - len > 50) { for (i = 0; i < maxclients->value; i++) { cl_ent = g_edicts + 1 + i; cl = &game.clients[i]; if (!cl_ent->inuse || cl_ent->solid != SOLID_NOT || cl_ent->client->resp.team != NOTEAM) continue; if (!k) { k = 1; sprintf(entry, "xv 0 yv %d string2 \"Spectators\" ", j); strcat(string, entry); len = strlen(string); j += 8; } sprintf(entry + strlen(entry), "ctf %d %d %d %d %d ", (n & 1) ? 160 : 0, // x j, // y i, // playernum cl->resp.score, cl->ping > 999 ? 999 : cl->ping); if (maxsize - len > strlen(entry)) { strcat(string, entry); len = strlen(string); } if (n & 1) j += 8; n++; } } if (total[0] - last[0] > 1) // couldn't fit everyone sprintf(string + strlen(string), "xv 8 yv %d string \"..and %d more\" ", 42 + (last[0] + 1) * 8, total[0] - last[0] - 1); if (total[1] - last[1] > 1) // couldn't fit everyone sprintf(string + strlen(string), "xv 168 yv %d string \"..and %d more\" ", 42 + (last[1] + 1) * 8, total[1] - last[1] - 1); } else if (ent->client->scoreboardnum == 2) { int total, score, ping; int sortedscores[MAX_CLIENTS], sorted[MAX_CLIENTS]; total = score = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; score = game.clients[i].resp.score; if (noscore->value) { j = total; } else { for (j = 0; j < total; j++) { if (score > sortedscores[j]) break; } for (k = total; k > j; k--) { sorted[k] = sorted[k - 1]; sortedscores[k] = sortedscores[k - 1]; } } sorted[j] = i; sortedscores[j] = score; total++; } if (noscore->value) // AQ2:TNG Deathwatch - Nice little bar { strcpy(string, "xv 0 yv 32 string2 \"Player Time Ping\" " "xv 0 yv 40 string2 \"¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ\" "); } else { strcpy(string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Kills\" " "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧₧ƒ\" "); } // AQ2:TNG END for (i = 0; i < total; i++) { ping = game.clients[sorted[i]].ping; if (ping > 999) ping = 999; if (noscore->value) { sprintf(string + strlen(string), "xv 0 yv %d string \"%-15s %4d %4d\" ", 48 + i * 8, game.clients[sorted[i]].pers.netname, (level.framenum - game.clients[sorted[i]].resp.enterframe) / 600, ping); } else { if (game.clients[sorted[i]].resp.damage_dealt < 1000000) sprintf(damage, "%d", game.clients[sorted[i]].resp.damage_dealt); else strcpy(damage, "******"); sprintf(string + strlen(string), "xv 0 yv %d string \"%5d %-15s %4d %4d %6s %5d\" ", 48 + i * 8, sortedscores[i], game.clients[sorted[i]].pers.netname, (level.framenum - game.clients[sorted[i]].resp.enterframe) / 600, ping, damage, game.clients[sorted[i]].resp.kills); } if (strlen(string) > (maxsize - 100) && i < (total - 2)) { sprintf(string + strlen(string), "xv 0 yv %d string \"..and %d more\" ", 48 + (i + 1) * 8, (total - i - 1)); break; } } } if (strlen(string) > 1023) // for debugging... gi.dprintf("Warning: scoreboard string neared or exceeded max length\nDump:\n%s\n---\n", string); gi.WriteByte(svc_layout); gi.WriteString(string); } /*-----------------------------------------------------------------------*/ /*QUAKED misc_ctf_banner (1 .5 0) (-4 -64 0) (4 64 248) TEAM2 The origin is the bottom of the banner. The banner is 248 tall. */ static void misc_ctf_banner_think(edict_t * ent) { ent->s.frame = (ent->s.frame + 1) % 16; ent->nextthink = level.time + FRAMETIME; } void SP_misc_ctf_banner(edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_NOT; ent->s.modelindex = gi.modelindex("models/ctf/banner/tris.md2"); if (ent->spawnflags & 1) // team2 ent->s.skinnum = 1; ent->s.frame = rand() % 16; gi.linkentity(ent); ent->think = misc_ctf_banner_think; ent->nextthink = level.time + FRAMETIME; } /*QUAKED misc_ctf_small_banner (1 .5 0) (-4 -32 0) (4 32 124) TEAM2 The origin is the bottom of the banner. The banner is 124 tall. */ void SP_misc_ctf_small_banner(edict_t * ent) { ent->movetype = MOVETYPE_NONE; ent->solid = SOLID_NOT; ent->s.modelindex = gi.modelindex("models/ctf/banner/small.md2"); if (ent->spawnflags & 1) // team2 ent->s.skinnum = 1; ent->s.frame = rand() % 16; gi.linkentity(ent); ent->think = misc_ctf_banner_think; ent->nextthink = level.time + FRAMETIME; } /*-----------------------------------------------------------------------*/ void CTFCredits(edict_t * ent, pmenu_t * p); void DeathmatchScoreboard(edict_t * ent); void CTFShowScores(edict_t * ent, pmenu_t * p) { PMenu_Close(ent); ent->client->showscores = true; ent->client->showinventory = false; DeathmatchScoreboard(ent); } qboolean CTFCheckRules(void) { if (capturelimit->value && (ctfgame.team1 >= capturelimit->value || ctfgame.team2 >= capturelimit->value)) { gi.bprintf(PRINT_HIGH, "Capturelimit hit.\n"); IRC_printf(IRC_T_GAME, "Capturelimit hit.\n"); return true; } if(timelimit->value > 0 && ctfgame.type > 0) { if(ctfgame.halftime == 0 && level.time == (timelimit->value * 60) / 2 - 60) { CenterPrintAll ("1 MINUTE LEFT..."); gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("tng/1_minute.wav"), 1.0, ATTN_NONE, 0.0); ctfgame.halftime = 1; } if(ctfgame.halftime == 1 && level.time == (timelimit->value * 60) / 2 - 10) { gi.sound (&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex ("world/10_0.wav"), 1.0, ATTN_NONE, 0.0); ctfgame.halftime = 2; } if(ctfgame.halftime < 3 && level.time == (timelimit->value * 60) / 2 + 1) { team_round_going = team_round_countdown = team_game_going = 0; MakeAllLivePlayersObservers (); CTFSwapTeams(); CenterPrintAll("The teams have been switched!"); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("misc/secret.wav"), 1.0, ATTN_NONE, 0.0); ctfgame.halftime = 3; } } return false; } /*-------------------------------------------------------------------------- * just here to help old map conversions *--------------------------------------------------------------------------*/ static void old_teleporter_touch(edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { edict_t *dest; int i; vec3_t forward; if (!other->client) return; dest = G_Find(NULL, FOFS(targetname), self->target); if (!dest) { gi.dprintf("Couldn't find destination\n"); return; } // unlink to make sure it can't possibly interfere with KillBox gi.unlinkentity(other); VectorCopy(dest->s.origin, other->s.origin); VectorCopy(dest->s.origin, other->s.old_origin); // clear the velocity and hold them in place briefly VectorClear(other->velocity); other->client->ps.pmove.pm_time = 160 >> 3; // hold time other->client->ps.pmove.pm_flags |= PMF_TIME_TELEPORT; // draw the teleport splash at source and on the player self->enemy->s.event = EV_PLAYER_TELEPORT; other->s.event = EV_PLAYER_TELEPORT; // set angles for (i = 0; i < 3; i++) other->client->ps.pmove.delta_angles[i] = ANGLE2SHORT(dest->s.angles[i] - other->client->resp.cmd_angles[i]); other->s.angles[PITCH] = 0; other->s.angles[YAW] = dest->s.angles[YAW]; other->s.angles[ROLL] = 0; VectorCopy(dest->s.angles, other->client->ps.viewangles); VectorCopy(dest->s.angles, other->client->v_angle); // give a little forward velocity AngleVectors(other->client->v_angle, forward, NULL, NULL); VectorScale(forward, 200, other->velocity); // kill anything at the destination if (!KillBox(other)) { } gi.linkentity(other); } /*QUAKED trigger_teleport (0.5 0.5 0.5) ? Players touching this will be teleported */ void SP_trigger_teleport(edict_t * ent) { edict_t *s; int i; if (!ent->target) { gi.dprintf("teleporter without a target.\n"); G_FreeEdict(ent); return; } ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_TRIGGER; ent->touch = old_teleporter_touch; gi.setmodel(ent, ent->model); gi.linkentity(ent); // noise maker and splash effect dude s = G_Spawn(); ent->enemy = s; for (i = 0; i < 3; i++) s->s.origin[i] = ent->mins[i] + (ent->maxs[i] - ent->mins[i]) / 2; s->s.sound = gi.soundindex("world/hum1.wav"); gi.linkentity(s); } /*QUAKED info_teleport_destination (0.5 0.5 0.5) (-16 -16 -24) (16 16 32) Point trigger_teleports at these. */ void SP_info_teleport_destination(edict_t * ent) { ent->s.origin[2] += 16; } void CTFDestroyFlag(edict_t * self) { //flags are important if (ctf->value) { if (strcmp(self->classname, "item_flag_team1") == 0) { CTFResetFlag(TEAM1); // this will free self! gi.bprintf(PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName(TEAM1)); IRC_printf(IRC_T_GAME, "The %n flag has returned!\n", CTFTeamName(TEAM1)); return; } if (strcmp(self->classname, "item_flag_team2") == 0) { CTFResetFlag(TEAM2); // this will free self! gi.bprintf(PRINT_HIGH, "The %s flag has returned!\n", CTFTeamName(TEAM2)); IRC_printf(IRC_T_GAME, "The %n flag has returned!\n", CTFTeamName(TEAM2)); return; } } // just release it. G_FreeEdict(self); } /* give client full health and some ammo for reward */ void CTFCapReward(edict_t * ent) { gclient_t *client; gitem_t *item; edict_t etemp; int was_bandaging = 0; int band; int player_weapon; if(!ctf_mode->value) return; if(ctf_mode->value > 1) ent->client->resp.ctf_capstreak++; else /* capstreak is used as a multiplier so default it to one */ ent->client->resp.ctf_capstreak = 1; band = ent->client->resp.ctf_capstreak; client = ent->client; // give initial knife if none if ((int)wp_flags->value & WPF_KNIFE && ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(KNIFE_NUM))] == 0) ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(KNIFE_NUM))] += 1; if (client->resp.item->typeNum == BAND_NUM) { band =+ 1; if (tgren->value > 0) // team grenades is turned on { item = GET_ITEM(GRENADE_NUM); client->pers.inventory[ITEM_INDEX(item)] = tgren->value; } } // give pistol clips if ((int)wp_flags->value & WPF_MK23) { item = GET_ITEM(MK23_ANUM); client->mk23_rds = client->mk23_max; client->pers.inventory[ITEM_INDEX(item)] = 1*band; } player_weapon = client->resp.weapon->typeNum; // find out which weapon the player is holding in it's inventory if(client->unique_weapon_total > 0) { if(ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(MP5_NUM))]) player_weapon = MP5_NUM; if(ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(M4_NUM))]) player_weapon = M4_NUM; if(ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(M3_NUM))]) player_weapon = M3_NUM; if(ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(HC_NUM))]) player_weapon = HC_NUM; if(ent->client->pers.inventory[ITEM_INDEX(GET_ITEM(SNIPER_NUM))]) player_weapon = SNIPER_NUM; } // if player has no special weapon, give the initial one if (player_weapon == MP5_NUM) { if(client->unique_weapon_total < 1) { item = GET_ITEM(MP5_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; client->unique_weapon_total = 1; } item = GET_ITEM(MP5_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 1*band; client->mp5_rds = client->mp5_max; } else if (player_weapon == M4_NUM) { if(client->unique_weapon_total < 1) { item = GET_ITEM(M4_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; client->unique_weapon_total = 1; } item = GET_ITEM(M4_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 1*band; client->m4_rds = client->m4_max; } else if (player_weapon == M3_NUM) { if(client->unique_weapon_total < 1) { item = GET_ITEM(M3_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; client->unique_weapon_total = 1; } item = GET_ITEM(SHELL_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 7*band; client->shot_rds = client->shot_max; } else if (player_weapon == HC_NUM) { if(client->unique_weapon_total < 1) { item = GET_ITEM(HC_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; client->unique_weapon_total = 1; } item = GET_ITEM(SHELL_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 12*band; client->cannon_rds = client->cannon_max; } else if (player_weapon == SNIPER_NUM) { if(client->unique_weapon_total < 1) { item = GET_ITEM(SNIPER_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; client->unique_weapon_total = 1; } item = GET_ITEM(SNIPER_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 10*band; client->sniper_rds = client->sniper_max; } else if (player_weapon == DUAL_NUM) { item = GET_ITEM(DUAL_NUM); client->pers.inventory[ITEM_INDEX(item)] = 1; item = GET_ITEM(MK23_ANUM); client->pers.inventory[ITEM_INDEX(item)] = 2*band; client->dual_rds = client->dual_max; } else if (player_weapon == KNIFE_NUM) { item = GET_ITEM(KNIFE_NUM); client->pers.inventory[ITEM_INDEX(item)] = 10*band; } if(ent->client->bandaging || ent->client->bandage_stopped) was_bandaging = 1; ent->client->leg_noise = 0; ent->client->leg_damage = 0; ent->client->leghits = 0; ent->client->bleeding = 0; ent->client->bleed_remain = 0; ent->client->bandaging = 0; ent->client->leg_dam_count = 0; ent->client->attacker = NULL; ent->client->bandage_stopped = 0; ent->client->idle_weapon = 0; // automagically change to special in any case, it's fully reloaded if((client->curr_weap != player_weapon && ent->client->weaponstate == WEAPON_READY) || was_bandaging) { client->newweapon = client->pers.weapon; ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = 0; ReadySpecialWeapon(ent); } // give health times cap streak ent->health = ent->max_health * (ent->client->resp.ctf_capstreak > 4 ? 4 : ent->client->resp.ctf_capstreak); ent->client->pers.health = ent->health; if(ent->client->resp.ctf_capstreak == 2) gi.centerprintf(ent, "CAPTURED TWO TIMES IN A ROW!\n\nYou have been rewarded with DOUBLE health and ammo!\n\nNow go get some more!"); else if(ent->client->resp.ctf_capstreak == 3) gi.centerprintf(ent, "CAPTURED THREE TIMES IN A ROW!\n\nYou have been rewarded with TRIPLE health and ammo!\n\nNow go get some more!"); else if(ent->client->resp.ctf_capstreak == 4) gi.centerprintf(ent, "CAPTURED FOUR TIMES IN A ROW!\n\nYou have been rewarded with QUAD health and ammo!\n\nNow go get some more!"); else if(ent->client->resp.ctf_capstreak > 4) gi.centerprintf(ent, "CAPTURED YET AGAIN!\n\nYou have been rewarded QUAD health and %d times your ammo!\n\nNow go get some more!", ent->client->resp.ctf_capstreak); else gi.centerprintf(ent, "CAPTURED!\n\nYou have been rewarded.\n\nNow go get some more!"); }
552
./aq2-tng/source/a_xmenu.c
//----------------------------------------------------------------------------- // a_xmenu.c // // $Id: a_xmenu.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: a_xmenu.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:25:35 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #define X_MENU ent->x_menu static XMENU_TITLE xRaw[] = { "Çüüüüüüüüüüüüüüüüé", // double line "previous page", "next page", "Use [ and ] to move cursor", "ENTER to select, TAB to exit", "", // single line "Çüüüüüüüüüüüüüüüüüüüüüüüüüüüé" // double line }; qboolean xMenu_Add (edict_t * ent, char *name, void (*SelectFunc) (edict_t * ent, pmenu_t * p)) { if (X_MENU->xmenucount < XMENU_TOTAL_ENTRIES) { if (name) Q_strncpyz(X_MENU->xmenuentries[X_MENU->xmenucount].name, name, XMENU_TITLE_MAX); else X_MENU->xmenuentries[X_MENU->xmenucount].name[0] = '\0'; X_MENU->xmenuentries[X_MENU->xmenucount].SelectFunc = SelectFunc; X_MENU->xmenucount++; } return (X_MENU->xmenucount < XMENU_TOTAL_ENTRIES); } void xMenu_Set (edict_t * ent); void xMenu_Next (edict_t * ent, pmenu_t * p) { X_MENU->xmenucount = 2; X_MENU->DoAddMenu (ent, X_MENU->xmenutop + XMENU_MAX_ENTRIES); if (X_MENU->xmenucount > 2) { X_MENU->xmenutop += XMENU_MAX_ENTRIES; xMenu_Set (ent); PMenu_Close (ent); PMenu_Open (ent, X_MENU->themenu, 5, XMENU_END_ENTRY); //PMenu_Update(ent); } } void xMenu_Prev (edict_t * ent, pmenu_t * p) { int temptop; X_MENU->xmenucount = 2; if (X_MENU->xmenutop < XMENU_MAX_ENTRIES) temptop = 0; else temptop = X_MENU->xmenutop - XMENU_MAX_ENTRIES; X_MENU->DoAddMenu (ent, temptop); if (X_MENU->xmenucount > 2) { X_MENU->xmenutop = temptop; xMenu_Set (ent); PMenu_Close (ent); PMenu_Open (ent, X_MENU->themenu, 5, XMENU_END_ENTRY); //PMenu_Update(ent); } } void xMenu_Set (edict_t * ent) { int i; //setting title X_MENU->themenu[0].text = X_MENU->xmenuentries[0].name; X_MENU->themenu[0].align = PMENU_ALIGN_CENTER; X_MENU->themenu[1].text = NULL; X_MENU->themenu[1].align = PMENU_ALIGN_CENTER; X_MENU->themenu[2].text = X_MENU->xmenuentries[1].name; X_MENU->themenu[2].align = PMENU_ALIGN_CENTER; X_MENU->themenu[3].text = xRaw[5]; X_MENU->themenu[3].align = PMENU_ALIGN_CENTER; //setting bottom X_MENU->themenu[XMENU_END_ENTRY - 3].text = xRaw[5]; X_MENU->themenu[XMENU_END_ENTRY - 3].align = PMENU_ALIGN_CENTER; X_MENU->themenu[XMENU_END_ENTRY - 2].text = xRaw[3]; X_MENU->themenu[XMENU_END_ENTRY - 2].align = PMENU_ALIGN_CENTER; X_MENU->themenu[XMENU_END_ENTRY - 1].text = xRaw[4]; X_MENU->themenu[XMENU_END_ENTRY - 1].align = PMENU_ALIGN_CENTER; for (i = 2; i < X_MENU->xmenucount; i++) { X_MENU->themenu[i + 3].text = X_MENU->xmenuentries[i].name; X_MENU->themenu[i + 3].SelectFunc = X_MENU->xmenuentries[i].SelectFunc; } while (i < XMENU_TOTAL_ENTRIES) { X_MENU->themenu[i + 3].text = NULL; X_MENU->themenu[i + 3].SelectFunc = NULL; i++; } if (X_MENU->xmenucount == XMENU_TOTAL_ENTRIES) { //next must be enabled X_MENU->themenu[XMENU_END_ENTRY - 5].text = xRaw[2]; X_MENU->themenu[XMENU_END_ENTRY - 5].SelectFunc = xMenu_Next; } else { X_MENU->themenu[XMENU_END_ENTRY - 5].text = NULL; X_MENU->themenu[XMENU_END_ENTRY - 5].SelectFunc = NULL; } if (X_MENU->xmenutop) { //prev must be enabled X_MENU->themenu[XMENU_END_ENTRY - 6].text = xRaw[1]; X_MENU->themenu[XMENU_END_ENTRY - 6].SelectFunc = xMenu_Prev; } else { X_MENU->themenu[XMENU_END_ENTRY - 6].text = NULL; X_MENU->themenu[XMENU_END_ENTRY - 6].SelectFunc = NULL; } } qboolean xMenu_New (edict_t * ent, char *title, char *subtitle, void (*DoAddMenu) (edict_t * ent, int fromix)) { if (!DoAddMenu) return false; if (!X_MENU) { //no menu yet, allocate memory for it... X_MENU = gi.TagMalloc (sizeof (xmenu_t), TAG_GAME); if (!X_MENU) { gi.dprintf ("Error allocating xmenu space\n"); return false; } } X_MENU->DoAddMenu = DoAddMenu; X_MENU->xmenucount = 2; X_MENU->xmenutop = 0; //memset(xmenuentries, 0, sizeof(xmenuentries)); strcpy (X_MENU->xmenuentries[0].name, "*"); if (title) Q_strncatz(X_MENU->xmenuentries[0].name, title, XMENU_TITLE_MAX); else Q_strncatz(X_MENU->xmenuentries[0].name, "Menu", XMENU_TITLE_MAX); if (subtitle) Q_strncpyz(X_MENU->xmenuentries[1].name, subtitle, XMENU_TITLE_MAX); else Q_strncpyz(X_MENU->xmenuentries[1].name, "make your choice", XMENU_TITLE_MAX); X_MENU->xmenuentries[0].SelectFunc = NULL; X_MENU->xmenuentries[1].SelectFunc = NULL; DoAddMenu (ent, 0); if (X_MENU->xmenucount > 2) { xMenu_Set (ent); if (ent->client->menu) PMenu_Close (ent); PMenu_Open (ent, X_MENU->themenu, 5, XMENU_END_ENTRY); return true; } return false; }
553
./aq2-tng/source/g_phys.c
//----------------------------------------------------------------------------- // g_phys.c // // $Id: g_phys.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_phys.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:30:45 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "cgf_sfx_glass.h" /* pushmove objects do not obey gravity, and do not interact with each other or trigger fields, but block normal movement and push normal objects when they move. onground is set for toss objects when they come to a complete rest. it is set for steping or walking objects doors, plats, etc are SOLID_BSP, and MOVETYPE_PUSH bonus items are SOLID_TRIGGER touch, and MOVETYPE_TOSS corpses are SOLID_NOT and MOVETYPE_TOSS crates are SOLID_BBOX and MOVETYPE_TOSS walking monsters are SOLID_SLIDEBOX and MOVETYPE_STEP flying/floating monsters are SOLID_SLIDEBOX and MOVETYPE_FLY solid_edge items only clip against bsp models. */ /* ============ SV_TestEntityPosition ============ */ edict_t * SV_TestEntityPosition (edict_t * ent) { trace_t trace; int mask; if (ent->clipmask) mask = ent->clipmask; else mask = MASK_SOLID; PRETRACE (); trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, ent->s.origin, ent, mask); POSTTRACE (); if (trace.startsolid) return g_edicts; return NULL; } /* ================ SV_CheckVelocity ================ */ void SV_CheckVelocity (edict_t * ent) { int i; // // bound velocity // for (i = 0; i < 3; i++) { if (ent->velocity[i] > sv_maxvelocity->value) ent->velocity[i] = sv_maxvelocity->value; else if (ent->velocity[i] < -sv_maxvelocity->value) ent->velocity[i] = -sv_maxvelocity->value; } } /* ============= SV_RunThink Runs thinking code for this frame if necessary ============= */ qboolean SV_RunThink (edict_t * ent) { float thinktime; thinktime = ent->nextthink; if (thinktime <= 0) return true; if (thinktime > level.time + 0.001) return true; ent->nextthink = 0; if (!ent->think) gi.error ("NULL ent->think"); ent->think (ent); return false; } /* ================== SV_Impact Two entities have touched, so run their touch functions ================== */ void SV_Impact (edict_t * e1, trace_t * trace) { edict_t *e2; // cplane_t backplane; e2 = trace->ent; if (e1->touch && e1->solid != SOLID_NOT) e1->touch (e1, e2, &trace->plane, trace->surface); if (e2->touch && e2->solid != SOLID_NOT) e2->touch (e2, e1, NULL, NULL); } /* ================== ClipVelocity Slide off of the impacting object returns the blocked flags (1 = floor, 2 = step / wall) ================== */ #define STOP_EPSILON 0.1 int ClipVelocity (vec3_t in, vec3_t normal, vec3_t out, float overbounce) { float backoff; float change; int i, blocked; blocked = 0; if (normal[2] > 0) blocked |= 1; // floor if (!normal[2]) blocked |= 2; // step backoff = DotProduct (in, normal) * overbounce; for (i = 0; i < 3; i++) { change = normal[i] * backoff; out[i] = in[i] - change; if (out[i] > -STOP_EPSILON && out[i] < STOP_EPSILON) out[i] = 0; } return blocked; } /* ============ SV_FlyMove The basic solid body movement clip that slides along multiple planes Returns the clipflags if the velocity was modified (hit something solid) 1 = floor 2 = wall / step 4 = dead stop ============ */ #define MAX_CLIP_PLANES 5 int SV_FlyMove (edict_t * ent, float time, int mask) { edict_t *hit; int bumpcount, numbumps; vec3_t dir; float d; int numplanes; vec3_t planes[MAX_CLIP_PLANES]; vec3_t primal_velocity, original_velocity, new_velocity; int i, j; trace_t trace; vec3_t end; float time_left; int blocked; numbumps = 4; blocked = 0; VectorCopy (ent->velocity, original_velocity); VectorCopy (ent->velocity, primal_velocity); numplanes = 0; time_left = time; ent->groundentity = NULL; for (bumpcount = 0; bumpcount < numbumps; bumpcount++) { for (i = 0; i < 3; i++) end[i] = ent->s.origin[i] + time_left * ent->velocity[i]; PRETRACE (); trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, end, ent, mask); POSTTRACE (); if (trace.allsolid) { // entity is trapped in another solid VectorCopy (vec3_origin, ent->velocity); return 3; } if (trace.fraction > 0) { // actually covered some distance VectorCopy (trace.endpos, ent->s.origin); VectorCopy (ent->velocity, original_velocity); numplanes = 0; } if (trace.fraction == 1) break; // moved the entire distance hit = trace.ent; if (trace.plane.normal[2] > 0.7) { blocked |= 1; // floor if (hit->solid == SOLID_BSP) { ent->groundentity = hit; ent->groundentity_linkcount = hit->linkcount; } } if (!trace.plane.normal[2]) { blocked |= 2; // step } // // run the impact function // SV_Impact (ent, &trace); if (!ent->inuse) break; // removed by the impact function time_left -= time_left * trace.fraction; // cliped to another plane if (numplanes >= MAX_CLIP_PLANES) { // this shouldn't really happen VectorCopy (vec3_origin, ent->velocity); return 3; } VectorCopy (trace.plane.normal, planes[numplanes]); numplanes++; // // modify original_velocity so it parallels all of the clip planes // for (i = 0; i < numplanes; i++) { ClipVelocity (original_velocity, planes[i], new_velocity, 1); for (j = 0; j < numplanes; j++) // The following VectorCompare was added in 3.20, adding it. -FB if ((j != i) && !VectorCompare (planes[i], planes[j])) { if (DotProduct (new_velocity, planes[j]) < 0) break; // not ok } if (j == numplanes) break; } if (i != numplanes) { // go along this plane VectorCopy (new_velocity, ent->velocity); } else { // go along the crease if (numplanes != 2) { // gi.dprintf ("clip velocity, numplanes == %i\n",numplanes); VectorCopy (vec3_origin, ent->velocity); return 7; } CrossProduct (planes[0], planes[1], dir); d = DotProduct (dir, ent->velocity); VectorScale (dir, d, ent->velocity); } // // if original velocity is against the original velocity, stop dead // to avoid tiny occilations in sloping corners // if (DotProduct (ent->velocity, primal_velocity) <= 0) { VectorCopy (vec3_origin, ent->velocity); return blocked; } } return blocked; } /* ============ SV_AddGravity ============ */ void SV_AddGravity (edict_t * ent) { ent->velocity[2] -= ent->gravity * sv_gravity->value * FRAMETIME; } /* =============================================================================== PUSHMOVE =============================================================================== */ /* ============ SV_PushEntity Does not change the entities velocity at all ============ */ trace_t SV_PushEntity (edict_t * ent, vec3_t push) { trace_t trace; vec3_t start; vec3_t end; int mask; VectorCopy (ent->s.origin, start); VectorAdd (start, push, end); retry: if (ent->clipmask) mask = ent->clipmask; else mask = MASK_SOLID; PRETRACE (); trace = gi.trace (start, ent->mins, ent->maxs, end, ent, mask); POSTTRACE (); VectorCopy (trace.endpos, ent->s.origin); if(ent->inuse) gi.linkentity (ent); if (trace.fraction != 1.0) { SV_Impact (ent, &trace); // if the pushed entity went away and the pusher is still there if (!trace.ent->inuse && ent->inuse) { // move the pusher back and try again VectorCopy (start, ent->s.origin); gi.linkentity (ent); goto retry; } } if (ent->inuse) G_TouchTriggers (ent); return trace; } typedef struct { edict_t *ent; vec3_t origin; vec3_t angles; float deltayaw; } pushed_t; pushed_t pushed[MAX_EDICTS], *pushed_p; edict_t *obstacle; /* ============ SV_Push Objects need to be moved back on a failed push, otherwise riders would continue to slide. ============ */ qboolean SV_Push (edict_t * pusher, vec3_t move, vec3_t amove) { int i, e; edict_t *check, *block; vec3_t mins, maxs; pushed_t *p; vec3_t org, org2, move2, forward, right, up; // clamp the move to 1/8 units, so the position will // be accurate for client side prediction for (i = 0; i < 3; i++) { float temp; temp = move[i] * 8.0; if (temp > 0.0) temp += 0.5; else temp -= 0.5; move[i] = 0.125 * (int) temp; } // find the bounding box for (i = 0; i < 3; i++) { mins[i] = pusher->absmin[i] + move[i]; maxs[i] = pusher->absmax[i] + move[i]; } // we need this for pushing things later VectorSubtract (vec3_origin, amove, org); AngleVectors (org, forward, right, up); // save the pusher's original position pushed_p->ent = pusher; VectorCopy (pusher->s.origin, pushed_p->origin); VectorCopy (pusher->s.angles, pushed_p->angles); if (pusher->client) pushed_p->deltayaw = pusher->client->ps.pmove.delta_angles[YAW]; pushed_p++; // move the pusher to it's final position VectorAdd (pusher->s.origin, move, pusher->s.origin); VectorAdd (pusher->s.angles, amove, pusher->s.angles); gi.linkentity (pusher); // see if any solid entities are inside the final position check = g_edicts + 1; for (e = 1; e < globals.num_edicts; e++, check++) { if (!check->inuse) continue; if (check->movetype == MOVETYPE_PUSH || check->movetype == MOVETYPE_STOP || check->movetype == MOVETYPE_NONE || check->movetype == MOVETYPE_NOCLIP) continue; if (!check->area.prev) continue; // not linked in anywhere // if the entity is standing on the pusher, it will definitely be moved if (check->groundentity != pusher) { // see if the ent needs to be tested if (check->absmin[0] >= maxs[0] || check->absmin[1] >= maxs[1] || check->absmin[2] >= maxs[2] || check->absmax[0] <= mins[0] || check->absmax[1] <= mins[1] || check->absmax[2] <= mins[2]) continue; // see if the ent's bbox is inside the pusher's final position if (!SV_TestEntityPosition (check)) continue; } if ((pusher->movetype == MOVETYPE_PUSH) || (check->groundentity == pusher)) { // move this entity pushed_p->ent = check; VectorCopy (check->s.origin, pushed_p->origin); VectorCopy (check->s.angles, pushed_p->angles); pushed_p++; // try moving the contacted entity VectorAdd (check->s.origin, move, check->s.origin); if (check->client) { // FIXME: doesn't rotate monsters? check->client->ps.pmove.delta_angles[YAW] += amove[YAW]; } // figure movement due to the pusher's amove VectorSubtract (check->s.origin, pusher->s.origin, org); org2[0] = DotProduct (org, forward); org2[1] = -DotProduct (org, right); org2[2] = DotProduct (org, up); VectorSubtract (org2, org, move2); VectorAdd (check->s.origin, move2, check->s.origin); // may have pushed them off an edge if (check->groundentity != pusher) check->groundentity = NULL; block = SV_TestEntityPosition (check); if (!block) { // pushed ok gi.linkentity (check); // impact? continue; } // if it is ok to leave in the old position, do it // this is only relevent for riding entities, not pushed // FIXME: this doesn't acount for rotation VectorSubtract (check->s.origin, move, check->s.origin); block = SV_TestEntityPosition (check); if (!block) { pushed_p--; continue; } } // save off the obstacle so we can call the block function obstacle = check; // move back any entities we already moved // go backwards, so if the same entity was pushed // twice, it goes back to the original position for (p = pushed_p - 1; p >= pushed; p--) { VectorCopy (p->origin, p->ent->s.origin); VectorCopy (p->angles, p->ent->s.angles); if (p->ent->client) { p->ent->client->ps.pmove.delta_angles[YAW] = p->deltayaw; } gi.linkentity (p->ent); } return false; } //FIXME: is there a better way to handle this? // see if anything we moved has touched a trigger for (p = pushed_p - 1; p >= pushed; p--) G_TouchTriggers (p->ent); return true; } /* ================ SV_Physics_Pusher Bmodel objects don't interact with each other, but push all box objects ================ */ void SV_Physics_Pusher (edict_t * ent) { vec3_t move, amove; edict_t *part, *mv; // if not a team captain, so movement will be handled elsewhere if (ent->flags & FL_TEAMSLAVE) return; // make sure all team slaves can move before commiting // any moves or calling any think functions // if the move is blocked, all moved objects will be backed out //retry: pushed_p = pushed; for (part = ent; part; part = part->teamchain) { if (part->velocity[0] || part->velocity[1] || part->velocity[2] || part->avelocity[0] || part->avelocity[1] || part->avelocity[2]) { // object is moving VectorScale (part->velocity, FRAMETIME, move); VectorScale (part->avelocity, FRAMETIME, amove); if (!SV_Push (part, move, amove)) break; // move was blocked } } if (pushed_p > &pushed[MAX_EDICTS]) gi.error (ERR_FATAL, "pushed_p > &pushed[MAX_EDICTS], memory corrupted"); if (part) { // the move failed, bump all nextthink times and back out moves for (mv = ent; mv; mv = mv->teamchain) { if (mv->nextthink > 0) mv->nextthink += FRAMETIME; } // if the pusher has a "blocked" function, call it // otherwise, just stay in place until the obstacle is gone if (part->blocked) part->blocked (part, obstacle); #if 0 // if the pushed entity went away and the pusher is still there if (!obstacle->inuse && part->inuse) goto retry; #endif } else { // the move succeeded, so call all think functions for (part = ent; part; part = part->teamchain) { SV_RunThink (part); } } } //================================================================== /* ============= SV_Physics_None Non moving objects can only think ============= */ void SV_Physics_None (edict_t * ent) { // regular thinking SV_RunThink (ent); } /* ============= SV_Physics_Noclip A moving object that doesn't obey physics ============= */ void SV_Physics_Noclip (edict_t * ent) { // regular thinking if (!SV_RunThink (ent)) return; VectorMA (ent->s.angles, FRAMETIME, ent->avelocity, ent->s.angles); VectorMA (ent->s.origin, FRAMETIME, ent->velocity, ent->s.origin); gi.linkentity (ent); } /* ============================================================================== TOSS / BOUNCE ============================================================================== */ /* ============= SV_Physics_Bounce bounce movement. When onground, do nothing. This is a copy of SV_Physics_Toss() modified to provide more realistic bounce physics ============= */ void SV_Physics_Bounce (edict_t * ent); void SV_Physics_Bounce (edict_t * ent) { trace_t trace; vec3_t move, planeVel, normalVel, temp; edict_t *slave; qboolean wasinwater; qboolean isinwater; vec3_t old_origin; float movetime; // regular thinking SV_RunThink (ent); if (!ent->inuse) return; // if not a team captain, so movement will be handled elsewhere if (ent->flags & FL_TEAMSLAVE) return; if (ent->velocity[2] > 0) ent->groundentity = NULL; // check for the groundentity going away if (ent->groundentity) if (!ent->groundentity->inuse) ent->groundentity = NULL; // if onground, return without moving if (ent->groundentity) return; VectorCopy (ent->s.origin, old_origin); SV_CheckVelocity (ent); // move angles VectorMA (ent->s.angles, FRAMETIME, ent->avelocity, ent->s.angles); // add gravity ent->velocity[2] -= ent->gravity * sv_gravity->value * FRAMETIME; movetime = FRAMETIME; while (movetime > 0) { // move origin VectorScale (ent->velocity, movetime, move); // do the move (checking to see if we hit anything) trace = SV_PushEntity (ent, move); // SV_PushEntity might have called touch() functions so its possible we disappeared if (!ent->inuse) return; // we hit something so calculate rebound velocity etc. if (trace.fraction < 1) { // find component of velocity in direction of normal VectorScale (trace.plane.normal, DotProduct (trace.plane.normal, ent->velocity), normalVel); // find component of velocity parallel to plane of impact VectorSubtract (ent->velocity, normalVel, planeVel); // apply friction (lose 25% of velocity parallel to impact plane) VectorScale (planeVel, 0.75, planeVel); // calculate final velocity (rebound with 60% of impact velocity) // negative since rebound causes direction reversal VectorMA (planeVel, -0.6, normalVel, ent->velocity); // stop if on ground // only consider stopping if impact plane is less than 45 degrees with respect to horizontal // arccos(0.7) ~ 45 degrees if (trace.plane.normal[2] > 0.7) { VectorCopy (ent->velocity, temp); // zero out z component (vertical) since we want to consider horizontal and vertical motion // separately temp[2] = 0; if ((VectorLength (temp) < 20) && (ent->velocity[2] < ent->gravity * sv_gravity->value * FRAMETIME * 1.5)) { ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; VectorCopy (vec3_origin, ent->velocity); VectorCopy (vec3_origin, ent->avelocity); break; // stopped, so no further simulation is necessary } } } // remaining amount of FRAMETIME left to simulate movetime *= (1.0 - trace.fraction); } // check for water transition wasinwater = (ent->watertype & MASK_WATER); ent->watertype = gi.pointcontents (ent->s.origin); isinwater = ent->watertype & MASK_WATER; if (isinwater) ent->waterlevel = 1; else ent->waterlevel = 0; if (!wasinwater && isinwater) gi.positioned_sound (old_origin, g_edicts, CHAN_AUTO, gi.soundindex ("misc/h2ohit1.wav"), 1, 1, 0); else if (wasinwater && !isinwater) gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex ("misc/h2ohit1.wav"), 1, 1, 0); // move teamslaves for (slave = ent->teamchain; slave; slave = slave->teamchain) { VectorCopy (ent->s.origin, slave->s.origin); gi.linkentity (slave); } } /* ============= SV_Physics_Toss Toss, bounce, and fly movement. When onground, do nothing. ============= */ void SV_Physics_Toss (edict_t * ent) { trace_t trace; vec3_t move; float backoff; edict_t *slave; qboolean wasinwater; qboolean isinwater; vec3_t old_origin; // regular thinking SV_RunThink (ent); // if not a team captain, so movement will be handled elsewhere if (ent->flags & FL_TEAMSLAVE) return; if (ent->velocity[2] > 0) ent->groundentity = NULL; // check for the groundentity going away if (ent->groundentity) if (!ent->groundentity->inuse) ent->groundentity = NULL; // if onground, return without moving if (ent->groundentity) return; VectorCopy (ent->s.origin, old_origin); SV_CheckVelocity (ent); // add gravity if (ent->movetype != MOVETYPE_FLY && ent->movetype != MOVETYPE_FLYMISSILE) SV_AddGravity (ent); // move angles VectorMA (ent->s.angles, FRAMETIME, ent->avelocity, ent->s.angles); // move origin VectorScale (ent->velocity, FRAMETIME, move); trace = SV_PushEntity (ent, move); if (!ent->inuse) return; // zucc added from action to cause blood splatters if (trace.fraction < 1 && ent->movetype == MOVETYPE_BLOOD) { if (!ent->splatted) { AddSplat (ent->owner, ent->s.origin, &trace); ent->splatted = true; } return; } if (trace.fraction < 1) { if (ent->movetype == MOVETYPE_BOUNCE) backoff = 1.4f; // 1.5 is normal -Zucc/FB else backoff = 1; ClipVelocity (ent->velocity, trace.plane.normal, ent->velocity, backoff); // stop if on ground if (trace.plane.normal[2] > 0.7) { // zucc moved velocity check down from 60 if (ent->velocity[2] < 10 || ent->movetype != MOVETYPE_BOUNCE) { ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; VectorCopy (vec3_origin, ent->velocity); VectorCopy (vec3_origin, ent->avelocity); } } // if (ent->touch) // ent->touch (ent, trace.ent, &trace.plane, trace.surface); } // check for water transition wasinwater = (ent->watertype & MASK_WATER); ent->watertype = gi.pointcontents (ent->s.origin); isinwater = ent->watertype & MASK_WATER; if (isinwater) ent->waterlevel = 1; else ent->waterlevel = 0; if (!wasinwater && isinwater) gi.positioned_sound (old_origin, g_edicts, CHAN_AUTO, gi.soundindex ("misc/h2ohit1.wav"), 1, 1, 0); else if (wasinwater && !isinwater) gi.positioned_sound (ent->s.origin, g_edicts, CHAN_AUTO, gi.soundindex ("misc/h2ohit1.wav"), 1, 1, 0); // move teamslaves for (slave = ent->teamchain; slave; slave = slave->teamchain) { VectorCopy (ent->s.origin, slave->s.origin); gi.linkentity (slave); } } /* =============================================================================== STEPPING MOVEMENT =============================================================================== */ /* ============= SV_Physics_Step Monsters freefall when they don't have a ground entity, otherwise all movement is done with discrete steps. This is also used for objects that have become still on the ground, but will fall if the floor is pulled out from under them. FIXME: is this true? ============= */ //FIXME: hacked in for E3 demo #define sv_stopspeed 100 #define sv_friction 6 #define sv_waterfriction 1 void SV_AddRotationalFriction (edict_t * ent) { int n; float adjustment; VectorMA (ent->s.angles, FRAMETIME, ent->avelocity, ent->s.angles); adjustment = FRAMETIME * sv_stopspeed * sv_friction; for (n = 0; n < 3; n++) { if (ent->avelocity[n] > 0) { ent->avelocity[n] -= adjustment; if (ent->avelocity[n] < 0) ent->avelocity[n] = 0; } else { ent->avelocity[n] += adjustment; if (ent->avelocity[n] > 0) ent->avelocity[n] = 0; } } } void SV_Physics_Step (edict_t * ent) { qboolean wasonground; qboolean hitsound = false; float *vel; float speed, newspeed, control; float friction; edict_t *groundentity; int mask; // airborn monsters should always check for ground if (!ent->groundentity) M_CheckGround (ent); groundentity = ent->groundentity; SV_CheckVelocity (ent); if (groundentity) wasonground = true; else wasonground = false; if (ent->avelocity[0] || ent->avelocity[1] || ent->avelocity[2]) SV_AddRotationalFriction (ent); // add gravity except: // flying monsters // swimming monsters who are in the water if (!wasonground) if (!(ent->flags & FL_FLY)) if (!((ent->flags & FL_SWIM) && (ent->waterlevel > 2))) { if (ent->velocity[2] < sv_gravity->value * -0.1) hitsound = true; if (ent->waterlevel == 0) SV_AddGravity (ent); } // friction for flying monsters that have been given vertical velocity if ((ent->flags & FL_FLY) && (ent->velocity[2] != 0)) { speed = fabs (ent->velocity[2]); control = speed < sv_stopspeed ? sv_stopspeed : speed; friction = sv_friction / 3; newspeed = speed - (FRAMETIME * control * friction); if (newspeed < 0) newspeed = 0; newspeed /= speed; ent->velocity[2] *= newspeed; } // friction for flying monsters that have been given vertical velocity if ((ent->flags & FL_SWIM) && (ent->velocity[2] != 0)) { speed = fabs (ent->velocity[2]); control = speed < sv_stopspeed ? sv_stopspeed : speed; newspeed = speed - (FRAMETIME * control * sv_waterfriction * ent->waterlevel); if (newspeed < 0) newspeed = 0; newspeed /= speed; ent->velocity[2] *= newspeed; } if (ent->velocity[2] || ent->velocity[1] || ent->velocity[0]) { // apply friction // let dead monsters who aren't completely onground slide if ((wasonground) || (ent->flags & (FL_SWIM | FL_FLY))) if (!(ent->health <= 0.0 && !M_CheckBottom (ent))) { vel = ent->velocity; speed = sqrt (vel[0] * vel[0] + vel[1] * vel[1]); if (speed) { friction = sv_friction; control = speed < sv_stopspeed ? sv_stopspeed : speed; newspeed = speed - FRAMETIME * control * friction; if (newspeed < 0) newspeed = 0; newspeed /= speed; vel[0] *= newspeed; vel[1] *= newspeed; } } if (ent->svflags & SVF_MONSTER) mask = MASK_MONSTERSOLID; else mask = MASK_SOLID; SV_FlyMove (ent, FRAMETIME, mask); gi.linkentity (ent); G_TouchTriggers (ent); // Following check was added in 3.20. Adding here. -FB if (!ent->inuse) return; if (ent->groundentity) if (!wasonground) if (hitsound) gi.sound (ent, 0, gi.soundindex ("world/land.wav"), 1, 1, 0); } // regular thinking SV_RunThink (ent); } //============================================================================ /* ================ G_RunEntity ================ */ void G_RunEntity (edict_t * ent) { if (ent->prethink) ent->prethink (ent); switch ((int) ent->movetype) { case MOVETYPE_PUSH: case MOVETYPE_STOP: SV_Physics_Pusher (ent); break; case MOVETYPE_NONE: SV_Physics_None (ent); break; case MOVETYPE_NOCLIP: SV_Physics_Noclip (ent); break; case MOVETYPE_STEP: SV_Physics_Step (ent); break; case MOVETYPE_BOUNCE: SV_Physics_Bounce (ent); // provided by siris break; case MOVETYPE_TOSS: case MOVETYPE_FLY: // zucc added for blood splatting case MOVETYPE_BLOOD: // zucc case MOVETYPE_FLYMISSILE: SV_Physics_Toss (ent); break; default: gi.error ("SV_Physics: bad movetype %i", (int) ent->movetype); } }
554
./aq2-tng/source/a_radio.c
//----------------------------------------------------------------------------- // Radio-related code for Action (formerly Axshun) // // -Fireblade // // $Id: a_radio.c,v 1.6 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: a_radio.c,v $ // Revision 1.6 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.5 2002/03/26 21:49:01 ra // Bufferoverflow fixes // // Revision 1.4 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.3 2001/09/05 14:33:57 slicerdw // Added Fix's from the 2.1 release // // Revision 1.2 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.1.1.1 2001/05/06 17:24:29 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" void Cmd_Say_f (edict_t * ent, qboolean team, qboolean arg0, qboolean partner_msg); // Each of the possible radio messages and their length radio_msg_t male_radio_msgs[] = { {"1", 6, 0}, {"2", 6, 0}, {"3", 8, 0}, {"4", 7, 0}, {"5", 8, 0}, {"6", 9, 0}, {"7", 8, 0}, {"8", 7, 0}, {"9", 7, 0}, {"10", 6, 0}, {"back", 6, 0}, {"cover", 7, 0}, {"down", 13, 0}, {"enemyd", 10, 0}, {"enemys", 9, 0}, {"forward", 6, 0}, {"go", 6, 0}, {"im_hit", 7, 0}, {"left", 7, 0}, {"reportin", 9, 0}, {"right", 6, 0}, {"taking_f", 22, 0}, {"teamdown", 13, 0}, {"treport", 12, 0}, {"up", 4, 0} //{"END", 0, 0} // end of list delimiter }; radio_msg_t female_radio_msgs[] = { {"1", 5, 0}, {"2", 5, 0}, {"3", 5, 0}, {"4", 5, 0}, {"5", 5, 0}, {"6", 8, 0}, {"7", 7, 0}, {"8", 5, 0}, {"9", 5, 0}, {"10", 5, 0}, {"back", 6, 0}, {"cover", 5, 0}, {"down", 6, 0}, {"enemyd", 9, 0}, {"enemys", 9, 0}, {"forward", 8, 0}, {"go", 6, 0}, {"im_hit", 7, 0}, {"left", 8, 0}, {"reportin", 9, 0}, {"right", 5, 0}, {"taking_f", 22, 0}, {"teamdown", 10, 0}, {"treport", 12, 0}, {"up", 6, 0} //{"END", 0, 0}, // end of list delimiter }; static const int numMaleSnds = ( sizeof( male_radio_msgs ) / sizeof( male_radio_msgs[0] ) ); static const int numFemaleSnds = ( sizeof( female_radio_msgs ) / sizeof( female_radio_msgs[0] ) ); #define RADIO_MALE_DIR "radio/male/" #define RADIO_FEMALE_DIR "radio/female/" #define RADIO_CLICK 0 #define RADIO_DEATH_MALE 1 #define RADIO_DEATH_FEMALE 2 radio_msg_t globalRadio[] = { {"radio/click.wav", 2, 0}, {"radio/male/rdeath.wav", 27, 0}, {"radio/female/rdeath.wav", 30, 0} }; void PrecacheRadioSounds () { int i; char path[MAX_QPATH]; globalRadio[RADIO_CLICK].sndIndex = gi.soundindex(globalRadio[RADIO_CLICK].msg); globalRadio[RADIO_DEATH_MALE].sndIndex = gi.soundindex(globalRadio[RADIO_DEATH_MALE].msg); globalRadio[RADIO_DEATH_FEMALE].sndIndex = gi.soundindex(globalRadio[RADIO_DEATH_FEMALE].msg); //male for(i = 0; i < numMaleSnds; i++) { Com_sprintf (path, sizeof(path), "%s%s.wav", RADIO_MALE_DIR, male_radio_msgs[i].msg); male_radio_msgs[i].sndIndex = gi.soundindex(path); } //female for(i = 0; i < numFemaleSnds; i++) { Com_sprintf (path, sizeof(path), "%s%s.wav", RADIO_FEMALE_DIR, female_radio_msgs[i].msg); female_radio_msgs[i].sndIndex = gi.soundindex(path); } } void DeleteRadioQueueEntry (edict_t *ent, int entry_num) { int i; if (ent->client->resp.radio_queue_size <= entry_num) { gi.dprintf("DeleteRadioQueueEntry: attempt to delete out of range queue entry: %i\n", entry_num); return; } for (i = entry_num + 1; i < ent->client->resp.radio_queue_size; i++) { memcpy (&(ent->client->resp.radio_queue[i - 1]), &(ent->client->resp.radio_queue[i]), sizeof(radio_queue_entry_t)); } ent->client->resp.radio_queue_size--; } // RadioThink should be called once on each player per server frame. void RadioThink (edict_t * ent) { // Try to clean things up, a bit.... if (ent->client->resp.radio_partner) { if (!ent->client->resp.radio_partner->inuse || ent->client->resp.radio_partner->client->resp.radio_partner != ent) { ent->client->resp.radio_partner = NULL; } } if (ent->client->resp.partner_last_offered_to) { if (!ent->client->resp.partner_last_offered_to->inuse || ent->client->resp.partner_last_offered_to->solid == SOLID_NOT) { ent->client->resp.partner_last_offered_to = NULL; } } if (ent->client->resp.partner_last_denied_from) { if (!ent->client->resp.partner_last_denied_from->inuse || ent->client->resp.partner_last_denied_from->solid == SOLID_NOT) { ent->client->resp.partner_last_denied_from = NULL; } } // ................................ if (ent->client->resp.radio_power_off) { ent->client->resp.radio_queue_size = 0; return; } if (ent->client->resp.radio_delay > 0) { ent->client->resp.radio_delay--; if(ent->client->resp.radio_delay) return; } if (ent->client->resp.radio_queue_size) { edict_t *from; int check; from = ent->client->resp.radio_queue[0].from_player; if (!ent->client->resp.radio_queue[0].click && (!from->inuse || from->solid == SOLID_NOT || from->deadflag == DEAD_DEAD)) { if (ent->client->resp.radio_queue[0].from_gender) { ent->client->resp.radio_queue[0].sndIndex = globalRadio[RADIO_DEATH_FEMALE].sndIndex; ent->client->resp.radio_queue[0].length = globalRadio[RADIO_DEATH_FEMALE].length; } else { ent->client->resp.radio_queue[0].sndIndex = globalRadio[RADIO_DEATH_MALE].sndIndex; ent->client->resp.radio_queue[0].length = globalRadio[RADIO_DEATH_MALE].length; } for (check = 1; check < ent->client->resp.radio_queue_size; check++) { if (!ent->client->resp.radio_queue[check].click && ent->client->resp.radio_queue[check].from_player == from) { DeleteRadioQueueEntry (ent, check); check--; } } } unicastSound(ent, ent->client->resp.radio_queue[0].sndIndex, 1.0); ent->client->resp.radio_delay = ent->client->resp.radio_queue[0].length; DeleteRadioQueueEntry (ent, 0); //We can remove it here? } } void AppendRadioMsgToQueue (edict_t *ent, int sndIndex, int len, int click, edict_t *from_player) { radio_queue_entry_t *newentry; if (ent->client->resp.radio_queue_size >= MAX_RADIO_QUEUE_SIZE) { gi.dprintf("AppendRadioMsgToQueue: Maximum radio queue size exceeded\n"); return; } newentry = &(ent->client->resp.radio_queue[ent->client->resp.radio_queue_size]); newentry->sndIndex = sndIndex; newentry->from_player = from_player; newentry->from_gender = from_player->client->resp.radio_gender; newentry->length = len; newentry->click = click; ent->client->resp.radio_queue_size++; } void InsertRadioMsgInQueueBeforeClick (edict_t *ent, int sndIndex, int len, edict_t *from_player) { radio_queue_entry_t *newentry; if (ent->client->resp.radio_queue_size >= MAX_RADIO_QUEUE_SIZE) { gi.dprintf("InsertRadioMsgInQueueBeforeClick: Maximum radio queue size exceeded\n"); return; } memcpy (&(ent->client->resp.radio_queue[ent->client->resp.radio_queue_size]), &(ent->client->resp.radio_queue[ent->client->resp.radio_queue_size - 1]), sizeof (radio_queue_entry_t)); newentry = &(ent->client->resp.radio_queue[ent->client->resp.radio_queue_size - 1]); newentry->sndIndex = sndIndex; newentry->from_player = from_player; newentry->from_gender = from_player->client->resp.radio_gender; newentry->length = len; newentry->click = 0; ent->client->resp.radio_queue_size++; } void AddRadioMsg (edict_t *ent, int sndIndex, int len, edict_t *from_player) { if (ent->client->resp.radio_queue_size == 0) { AppendRadioMsgToQueue (ent, globalRadio[RADIO_CLICK].sndIndex, globalRadio[RADIO_CLICK].length, 1, from_player); AppendRadioMsgToQueue (ent, sndIndex, len, 0, from_player); AppendRadioMsgToQueue (ent, globalRadio[RADIO_CLICK].sndIndex, globalRadio[RADIO_CLICK].length, 1, from_player); } else // we have some msgs in it already... { if (ent->client->resp.radio_queue_size < MAX_RADIO_QUEUE_SIZE) InsertRadioMsgInQueueBeforeClick (ent, sndIndex, len, from_player); // else ignore the message... } } void RadioBroadcast (edict_t * ent, int partner, char *msg) { int j, i, msg_len, numSnds; edict_t *other; radio_msg_t *radio_msgs; int msg_soundIndex = 0; char msgname_num[8], filteredmsg[48]; qboolean found = false; if (ent->deadflag == DEAD_DEAD || ent->solid == SOLID_NOT) return; if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } if (ent->client->resp.radio_power_off) { gi.centerprintf (ent, "Your radio is off!"); return; } if (partner && ent->client->resp.radio_partner == NULL) { gi.cprintf (ent, PRINT_HIGH, "You don't have a partner.\n"); return; } if (ent->client->resp.radio_gender) { radio_msgs = female_radio_msgs; numSnds = numFemaleSnds; } else { radio_msgs = male_radio_msgs; numSnds = numMaleSnds; } i = found = 0; msg_len = 0; Q_strncpyz(filteredmsg, msg, sizeof(filteredmsg)); for(i = 0; i < numSnds; i++) { if (!Q_stricmp(radio_msgs[i].msg, filteredmsg)) { found = true; msg_soundIndex = radio_msgs[i].sndIndex; msg_len = radio_msgs[i].length; break; } } if (!found) { gi.centerprintf (ent, "'%s' is not a valid radio message", filteredmsg); return; } if (radiolog->value) { gi.cprintf (NULL, PRINT_CHAT, "[%s RADIO] %s: %s\n", partner ? "PARTNER" : "TEAM", ent->client->pers.netname, filteredmsg); } //TempFile BEGIN if (Q_stricmp (filteredmsg, "enemyd") == 0) { if ((ent->client->pers.num_kills > 1) && (ent->client->pers.num_kills <= 10)) { // If we are reporting enemy down, add the number of kills. sprintf (msgname_num, "%i", ent->client->pers.num_kills); ent->client->pers.num_kills = 0; // prevent from getting into an endless loop RadioBroadcast (ent, partner, msgname_num); // Now THAT'S recursion! =) } ent->client->pers.num_kills = 0; } //TempFile END //AQ2:TNG Slicer if (radio_repeat->value) { //SLIC2 Optimization if (CheckForRepeat (ent, i) == false) return; } if (radio_max->value) { if (CheckForFlood (ent) == false) return; } //AQ2:TNG END for (j = 1; j <= game.maxclients; j++) { other = &g_edicts[j]; if (!other->inuse) continue; if (!other->client) continue; if (!OnSameTeam(ent, other)) continue; if (partner && other != ent->client->resp.radio_partner) continue; AddRadioMsg (other, msg_soundIndex, msg_len, ent); } } void Cmd_Radio_f (edict_t * ent) { RadioBroadcast(ent, ent->client->resp.radio_partner_mode, gi.args()); } void Cmd_Radiopartner_f (edict_t * ent) { RadioBroadcast(ent, 1, gi.args()); } void Cmd_Radioteam_f (edict_t * ent) { RadioBroadcast(ent, 0, gi.args()); } void Cmd_Radiogender_f (edict_t * ent) { char *arg; if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } arg = gi.args(); if (arg == NULL || !strlen(arg)) { if (ent->client->resp.radio_gender) gi.cprintf (ent, PRINT_HIGH, "Radio gender currently set to female\n"); else gi.cprintf (ent, PRINT_HIGH, "Radio gender currently set to male\n"); return; } if (!Q_stricmp(arg, "male")) { gi.cprintf (ent, PRINT_HIGH, "Radio gender set to male\n"); ent->client->resp.radio_gender = 0; } else if (!Q_stricmp(arg, "female")) { gi.cprintf (ent, PRINT_HIGH, "Radio gender set to female\n"); ent->client->resp.radio_gender = 1; } else { gi.cprintf (ent, PRINT_HIGH, "Invalid gender selection, try 'male' or 'female'\n"); } } void Cmd_Radio_power_f (edict_t * ent) { if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } ent->client->resp.radio_power_off = !ent->client->resp.radio_power_off; if (ent->client->resp.radio_power_off) { gi.centerprintf (ent, "Radio switched off"); unicastSound(ent, globalRadio[RADIO_CLICK].sndIndex, 1.0); } else { gi.centerprintf (ent, "Radio switched on"); unicastSound(ent, globalRadio[RADIO_CLICK].sndIndex, 1.0); } } void Cmd_Channel_f (edict_t * ent) { if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } ent->client->resp.radio_partner_mode = !ent->client->resp.radio_partner_mode; if (ent->client->resp.radio_partner_mode) { gi.centerprintf (ent, "Channel set to 1, partner channel"); } else { gi.centerprintf (ent, "Channel set to 0, team channel"); } } // DetermineViewedTeammate: determine the current player you're viewing (only looks for live teammates) // Modified from SetIDView (which was used from Zoid's CTF) edict_t *DetermineViewedTeammate (edict_t * ent) { vec3_t forward, dir; trace_t tr; edict_t *who, *best; //FIREBLADE, suggested by hal[9k] 3/11/1999 float bd = 0.9f; //FIREBLADE float d; int i; AngleVectors (ent->client->v_angle, forward, NULL, NULL); VectorScale (forward, 8192, forward); VectorAdd (ent->s.origin, forward, forward); PRETRACE (); tr = gi.trace (ent->s.origin, NULL, NULL, forward, ent, MASK_SOLID); POSTTRACE (); if (tr.fraction < 1 && tr.ent && tr.ent->client) { return NULL; } AngleVectors (ent->client->v_angle, forward, NULL, NULL); best = NULL; for (i = 1; i <= maxclients->value; i++) { who = g_edicts + i; if (!who->inuse) continue; VectorSubtract (who->s.origin, ent->s.origin, dir); VectorNormalize (dir); d = DotProduct (forward, dir); if (d > bd && loc_CanSee (ent, who) && who->solid != SOLID_NOT && who->deadflag != DEAD_DEAD && OnSameTeam (who, ent)) { bd = d; best = who; } } if (bd > 0.90) { return best; } return NULL; } void Cmd_Partner_f (edict_t * ent) { edict_t *target; char *genderstr; if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } if (ent->deadflag == DEAD_DEAD || ent->solid == SOLID_NOT) return; if (ent->client->resp.radio_partner && !ent->client->resp.radio_partner->inuse) { // just in case RadioThink hasn't caught it yet... avoid any problems ent->client->resp.radio_partner = NULL; } if (ent->client->resp.radio_partner) { gi.centerprintf (ent, "You already have a partner, %s", ent->client->resp.radio_partner->client->pers.netname); return; } target = DetermineViewedTeammate (ent); if (target == NULL) { gi.centerprintf (ent, "No potential partner selected"); return; } if (target->client->resp.radio_partner) { gi.centerprintf (ent, "%s already has a partner", target->client->pers.netname); return; } if (target->client->resp.partner_last_offered_to == ent && ent->client->resp.partner_last_offered_from == target) { gi.centerprintf (ent, "%s is now your partner", target->client->pers.netname); gi.centerprintf (target, "%s is now your partner", ent->client->pers.netname); ent->client->resp.radio_partner = target; target->client->resp.radio_partner = ent; ent->client->resp.partner_last_offered_from = NULL; target->client->resp.partner_last_offered_to = NULL; return; } if (target->client->resp.partner_last_denied_from == ent) { gi.centerprintf (ent, "%s has already denied you", target->client->pers.netname); return; } if (target == ent->client->resp.partner_last_offered_to) { if (IsFemale (target)) genderstr = "her"; else if (IsNeutral (target)) genderstr = "it"; else genderstr = "him"; gi.centerprintf (ent, "Already awaiting confirmation from %s", genderstr); return; } if (IsFemale (ent)) genderstr = "her"; else if (IsNeutral (ent)) genderstr = "it"; else genderstr = "him"; gi.centerprintf (ent, "Awaiting confirmation from %s", target->client->pers.netname); gi.centerprintf (target, "%s offers to be your partner\n" "To accept:\nView %s and use the 'partner' command\n" "To deny:\nUse the 'deny' command", ent->client->pers.netname, genderstr); ent->client->resp.partner_last_offered_to = target; target->client->resp.partner_last_offered_from = ent; } void Cmd_Unpartner_f (edict_t * ent) { edict_t *target; if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } if (ent->client->resp.radio_partner && !ent->client->resp.radio_partner->inuse) { // just in case RadioThink hasn't caught it yet... avoid any problems ent->client->resp.radio_partner = NULL; } target = ent->client->resp.radio_partner; if (target == NULL) { gi.centerprintf (ent, "You don't have a partner"); return; } if (target->client->resp.radio_partner == ent) { gi.centerprintf (target, "%s broke your partnership", ent->client->pers.netname); target->client->resp.radio_partner = NULL; } gi.centerprintf (ent, "You broke your partnership with %s", target->client->pers.netname); ent->client->resp.radio_partner = NULL; } void Cmd_Deny_f (edict_t * ent) { edict_t *target; if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } if (ent->deadflag == DEAD_DEAD || ent->solid == SOLID_NOT) return; target = ent->client->resp.partner_last_offered_from; if (target && target->inuse) { gi.centerprintf (ent, "You denied %s", target->client->pers.netname); gi.centerprintf (target, "%s has denied you", ent->client->pers.netname); ent->client->resp.partner_last_denied_from = target; ent->client->resp.partner_last_offered_from = NULL; if (target->client->resp.partner_last_offered_to == ent) target->client->resp.partner_last_offered_to = NULL; } else { gi.centerprintf (ent, "No one has offered to be your partner"); return; } } void Cmd_Say_partner_f (edict_t * ent) { if (!teamplay->value) { if (!((int) (dmflags->value) & (DF_MODELTEAMS | DF_SKINTEAMS))) return; // don't allow in a non-team setup... } if (ent->client->resp.radio_partner == NULL) { gi.cprintf (ent, PRINT_HIGH, "You don't have a partner.\n"); return; } Cmd_Say_f (ent, false, false, true); } //SLIC2 Redesigned and optimized these two functions qboolean CheckForFlood(edict_t * ent) { //If he's muted.. if (ent->client->resp.rd_mute) { if (ent->client->resp.rd_mute > level.time) // Still muted.. return false; else ent->client->resp.rd_mute = 0; // No longer muted.. } if (!ent->client->resp.rd_Count) { ent->client->resp.rd_time = level.time; ++ent->client->resp.rd_Count; } else { ++ent->client->resp.rd_Count; if (level.time - ent->client->resp.rd_time < radio_time->value) { if (ent->client->resp.rd_Count >= radio_max->value) { gi.cprintf (ent, PRINT_HIGH, "[RADIO FLOOD PROTECTION]: Flood Detected, you are silenced for %d secs\n",(int) radio_ban->value); ent->client->resp.rd_mute = level.time + radio_ban->value; return false; } } else { ent->client->resp.rd_Count = 0; } } return true; } qboolean CheckForRepeat(edict_t * ent, int radioCode) { //If he's muted.. if (ent->client->resp.rd_mute) { if (ent->client->resp.rd_mute > level.time) // Still muted.. return false; else ent->client->resp.rd_mute = 0; // No longer muted.. } if (ent->client->resp.rd_lastRadio == radioCode) { //He's trying to repeat it.. if ((level.time - ent->client->resp.rd_repTime) < radio_repeat_time->value) { if (++ent->client->resp.rd_repCount == radio_repeat->value) { //Busted gi.cprintf (ent, PRINT_HIGH,"[RADIO FLOOD PROTECTION]: Repeat Flood Detected, you are silenced for %d secs\n",(int) radio_ban->value); ent->client->resp.rd_mute = level.time + radio_ban->value; return false; } } else ent->client->resp.rd_repCount = 0; ent->client->resp.rd_repTime = level.time; } ent->client->resp.rd_lastRadio = radioCode; ent->client->resp.rd_repTime = level.time; return true; }
555
./aq2-tng/source/lcchack.c
//----------------------------------------------------------------------------- // lcchack.c // // $Id: lcchack.c,v 1.3 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: lcchack.c,v $ // Revision 1.3 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.2 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.1.1.1 2001/05/06 17:24:39 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include <stdio.h> int _stdcall DLLMain (void *hinstDll, unsigned long dwReason, void *reserved) { return (1); }
556
./aq2-tng/source/g_main.c
//----------------------------------------------------------------------------- // // // $Id: g_main.c,v 1.73 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: g_main.c,v $ // Revision 1.73 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.72 2004/01/18 11:25:31 igor_rock // added flashgrenades // // Revision 1.71 2003/06/16 18:16:06 igor // added IRC_poll to enable IRC mode (i had overseen it the first time) // // Revision 1.70 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.69 2003/06/15 15:34:32 igor // - removed the zcam code from this branch (see other branch) // - added fixes from 2.72 (source only) version // - resetted version number to 2.72 // - This version should be exactly like the release 2.72 - just with a few // more fixes (which whoever did the source only variant didn't get because // he didn't use the CVS as he should. Shame on him. // // Revision 1.68 2002/09/04 11:23:10 ra // Added zcam to TNG and bumped version to 3.0 // // Revision 1.67 2002/08/12 09:36:34 freud // Fixed the maxclients = 20 bug. G_RunEntity was not run if maxclients // 20, very weird code.. :) // // Revision 1.66 2002/03/30 17:20:59 ra // New cvar use_buggy_bandolier to control behavior of dropping bando and grenades // // Revision 1.65 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.64 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.63 2002/03/27 15:16:56 freud // Original 1.52 spawn code implemented for use_newspawns 0. // Teamplay, when dropping bandolier, your drop the grenades. // Teamplay, cannot pick up grenades unless wearing bandolier. // // Revision 1.62 2002/03/25 23:35:19 freud // Ghost code, use_ghosts and more stuff.. // // Revision 1.61 2002/03/25 18:32:11 freud // I'm being too productive.. New ghost command needs testing. // // Revision 1.60 2002/03/25 15:16:24 freud // use_newspawns had a typo in g_main.c fixed. // // Revision 1.58 2002/02/19 09:32:47 freud // Removed PING PONGs from CVS, not fit for release. // // Revision 1.57 2002/02/18 23:17:55 freud // Polling tweaks for PINGs // // Revision 1.56 2002/02/18 20:33:48 freud // PING PONG Change polling times // // Revision 1.55 2002/02/18 20:21:36 freud // Added PING PONG mechanism for timely disconnection of clients. This is // based on a similar scheme as the scheme used by IRC. The client has // cvar ping_timeout seconds to reply or will be disconnected. // // Revision 1.54 2002/02/18 19:44:45 freud // Fixed the teamskin/teamname bug after softmap/map_restart // // Revision 1.53 2002/02/17 20:10:09 freud // Better naming of auto_items is auto_equip, requested by Deathwatch. // // Revision 1.52 2002/02/17 20:01:32 freud // Fixed stat_mode overflows, finally. // Added 2 new cvars: // auto_join (0|1), enables auto joining teams from previous map. // auto_items (0|1), enables weapon and items caching between maps. // // Revision 1.51 2002/02/17 19:04:14 freud // Possible bugfix for overflowing clients with stat_mode set. // // Revision 1.50 2002/02/03 01:07:28 freud // more fixes with stats // // Revision 1.49 2002/02/01 15:02:43 freud // More stat_mode fixes, stat_mode 1 would overflow clients at EndDMLevel. // // Revision 1.48 2002/02/01 12:54:08 ra // messin with stat_mode // // Revision 1.47 2002/01/24 11:29:34 ra // Cleanup's in stats code // // Revision 1.46 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.45 2002/01/23 01:29:07 deathwatch // rrot should be a lot more random now (hope it works under linux as well) // // Revision 1.44 2002/01/22 16:55:49 deathwatch // fixed a bug with rrot which would make it override sv softmap (moved the dosoft check up in g_main.c // fixed a bug with rrot which would let it go to the same map (added an if near the end of the rrot statement in the EndDMLevel function) // // Revision 1.43 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.41 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.40 2001/11/29 17:58:31 igor_rock // TNG IRC Bot - First Version // // Revision 1.39 2001/11/25 19:09:25 slicerdw // Fixed Matchtime // // Revision 1.38 2001/11/10 14:00:14 deathwatch // Fixed resetting of teamXscores // // Revision 1.37 2001/11/09 23:58:12 deathwatch // Fiixed the %me command to display '[DEAD]' properly // Added the resetting of the teamXscore cvars at the exitlevel function where the team scores are reset as well. (not sure if that is correct) // // Revision 1.36 2001/11/08 10:05:09 igor_rock // day/night changing smoothened // changed default for day_cycle to 10 (because of more steps) // // Revision 1.35 2001/11/04 15:15:19 ra // New server commands: "sv softmap" and "sv map_restart". sv softmap // takes one map as argument and starts is softly without restarting // the server. map_restart softly restarts the current map. // // Revision 1.34 2001/11/02 16:07:47 ra // Changed teamplay spawn code so that teams dont spawn in the same place // often in a row // // Revision 1.33 2001/09/30 03:09:34 ra // Removed new stats at end of rounds and created a new command to // do the same functionality. Command is called "time" // // Revision 1.32 2001/09/29 19:54:04 ra // Made a CVAR to turn off extratimingstats // // Revision 1.31 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.30 2001/09/28 13:44:23 slicerdw // Several Changes / improvements // // Revision 1.29 2001/09/02 20:33:34 deathwatch // Added use_classic and fixed an issue with ff_afterround, also updated version // nr and cleaned up some commands. // // Updated the VC Project to output the release build correctly. // // Revision 1.28 2001/08/18 15:22:28 deathwatch // fixed the if in CycleLights to prevent the lights from cycling in other modes // // Revision 1.27 2001/08/18 01:28:06 deathwatch // Fixed some stats stuff, added darkmatch + day_cycle, cleaned up several files, restructured ClientCommand // // Revision 1.26 2001/08/15 14:50:48 slicerdw // Added Flood protections to Radio & Voice, Fixed the sniper bug AGAIN // // Revision 1.25 2001/08/08 12:42:22 slicerdw // Ctf Should finnaly be fixed now, lets hope so // // Revision 1.24 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.23 2001/08/06 03:00:49 ra // Added FF after rounds. Please someone look at the EVIL if statments for me :) // // Revision 1.22 2001/07/25 23:02:02 slicerdw // Fixed the source, added the weapons and items capping to choose command // // Revision 1.21 2001/07/20 11:56:04 slicerdw // Added a check for the players spawning during countdown on ctf ( lets hope it works ) // // Revision 1.19 2001/06/26 21:19:31 ra // Adding timestamps to gameendings. // // Revision 1.18 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.17 2001/06/23 14:09:17 slicerdw // Small fix on the Time Reporting on matchmode // // Revision 1.16 2001/06/22 16:34:05 slicerdw // Finished Matchmode Basics, now with admins, Say command tweaked... // // Revision 1.15 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.12 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.11 2001/06/18 12:36:40 igor_rock // added new irvision mode (with reddish screen and alpha blend) and corresponding // new cvar "new_irvision" to enable the new mode // // Revision 1.10 2001/06/13 08:39:13 igor_rock // changed "cvote" to "use_cvote" (like the other votecvars) // // Revision 1.9 2001/06/01 19:18:42 slicerdw // Added Matchmode Code // // Revision 1.8 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.7.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.7.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.7.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.7 2001/05/14 21:10:16 igor_rock // added wp_flags support (and itm_flags skeleton - doesn't disturb in the moment) // // Revision 1.6 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.5 2001/05/12 21:19:51 ra // // // Added punishkills. // // Revision 1.4 2001/05/12 20:58:22 ra // // // Adding public mapvoting and kickvoting. Its controlable via cvar's mv_public // and vk_public (both default off) // // Revision 1.3 2001/05/07 21:18:35 slicerdw // Added Video Checking System // // Revision 1.2 2001/05/07 08:32:17 mort // Basic CTF code // No spawns etc // Just the cvars and flag entity // // Revision 1.1.1.1 2001/05/06 17:31:37 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include <time.h> #include "g_local.h" game_locals_t game; level_locals_t level; game_import_t gi; game_export_t globals; spawn_temp_t st; int sm_meat_index; int snd_fry; int meansOfDeath; int locOfDeath; int stopAP; edict_t *g_edicts; //FIREBLADE cvar_t *hostname; cvar_t *teamplay; cvar_t *radiolog; cvar_t *motd_time; cvar_t *actionmaps; cvar_t *roundtimelimit; cvar_t *maxteamkills; cvar_t *twbanrounds; cvar_t *tkbanrounds; cvar_t *limchasecam; cvar_t *roundlimit; cvar_t *skipmotd; cvar_t *nohud; cvar_t *noscore; cvar_t *use_newscore; cvar_t *actionversion; cvar_t *needpass; cvar_t *use_voice; cvar_t *ppl_idletime; cvar_t *use_buggy_bandolier; cvar_t *use_tourney; cvar_t *use_3teams; cvar_t *use_kickvote; cvar_t *mv_public; // AQ:TNG - JBravo adding public voting cvar_t *vk_public; // AQ:TNG - JBravo adding public voting cvar_t *punishkills; // AQ:TNG - JBravo adding punishkills cvar_t *mapvote_waittime; cvar_t *ff_afterround; cvar_t *uvtime; // CTF Invunerability Time cvar_t *sv_gib; cvar_t *sv_crlf; // Allow Control Char cvar_t *vrot; // Vote Rotation cvar_t *rrot; // Random Rotation cvar_t *strtwpn; // Start DM Weapon cvar_t *llsound; cvar_t *use_cvote; cvar_t *new_irvision; cvar_t *use_rewards; cvar_t *use_warnings; cvar_t *use_mapvote; cvar_t *use_scramblevote; cvar_t *deathmatch; cvar_t *coop; cvar_t *dmflags; cvar_t *skill; cvar_t *fraglimit; cvar_t *timelimit; cvar_t *capturelimit; cvar_t *password; cvar_t *maxclients; cvar_t *maxentities; cvar_t *g_select_empty; cvar_t *dedicated; cvar_t *filterban; cvar_t *sv_maxvelocity; cvar_t *sv_gravity; cvar_t *sv_rollspeed; cvar_t *sv_rollangle; cvar_t *gun_x; cvar_t *gun_y; cvar_t *gun_z; cvar_t *run_pitch; cvar_t *run_roll; cvar_t *bob_up; cvar_t *bob_pitch; cvar_t *bob_roll; cvar_t *sv_cheats; cvar_t *flood_msgs; cvar_t *flood_persecond; cvar_t *flood_waitdelay; cvar_t *unique_weapons; cvar_t *unique_items; cvar_t *ir; cvar_t *knifelimit; cvar_t *tgren; //SLIC2 /*cvar_t *flashgren; cvar_t *flashradius; cvar_t *flashtime;*/ //SLIC2 cvar_t *allweapon; cvar_t *allitem; cvar_t *sv_shelloff; cvar_t *bholelimit; cvar_t *splatlimit; cvar_t *check_time; // Time to wait before checks start ? cvar_t *video_check; cvar_t *video_checktime; cvar_t *video_max_3dfx; cvar_t *video_max_3dfxam; cvar_t *video_max_opengl; cvar_t *video_force_restart; cvar_t *video_check_lockpvs; cvar_t *video_check_glclear; cvar_t *hc_single; cvar_t *wp_flags; // Weapon Banning cvar_t *itm_flags; // Item Banning cvar_t *matchmode; cvar_t *darkmatch; // Darkmatch cvar_t *day_cycle; // If darkmatch is on, this value is the nr of seconds between each interval (day, dusk, night, dawn) cvar_t *hearall; // used for matchmode cvar_t *mm_forceteamtalk; cvar_t *mm_adminpwd; cvar_t *mm_allowlock; cvar_t *mm_pausecount; cvar_t *mm_pausetime; cvar_t *teamdm; cvar_t *teamdm_respawn; cvar_t *respawn_effect; cvar_t *dm_shield; cvar_t *item_respawnmode; cvar_t *item_respawn; cvar_t *weapon_respawn; cvar_t *ammo_respawn; cvar_t *wave_time; /*cvar_t *team1score; cvar_t *team2score; cvar_t *team3score;*/ cvar_t *stats_endmap; // If on (1) show the fpm/etc stats when the map ends cvar_t *stats_afterround; // Collect TNG stats between rounds cvar_t *auto_join; cvar_t *auto_equip; cvar_t *auto_menu; cvar_t *dm_choose; //TNG:Freud - new spawning system cvar_t *use_oldspawns; //TNG:Freud - ghosts cvar_t *use_ghosts; cvar_t *use_punch; cvar_t *radio_max; // max nr Radio and Voice requests cvar_t *radio_time; // max nr of time for the radio_max cvar_t *radio_ban; // silence for xx nr of secs cvar_t *radio_repeat; // same as radio_max, only for repeats //SLIC2 cvar_t *radio_repeat_time; cvar_t *use_classic; // Used to reset spread/gren strength to 1.52 int pause_time = 0; void SpawnEntities (char *mapname, char *entities, char *spawnpoint); void ClientThink (edict_t * ent, usercmd_t * cmd); qboolean ClientConnect (edict_t * ent, char *userinfo); void ClientUserinfoChanged (edict_t * ent, char *userinfo); void ClientDisconnect (edict_t * ent); void ClientBegin (edict_t * ent); void ClientCommand (edict_t * ent); void CheckNeedPass (void); void RunEntity (edict_t * ent); void WriteGame (char *filename, qboolean autosave); void ReadGame (char *filename); void WriteLevel (char *filename); void ReadLevel (char *filename); void InitGame (void); void G_RunFrame (void); int dosoft; int softquit = 0; gghost_t ghost_players[MAX_GHOSTS]; int num_ghost_players; //=================================================================== void ShutdownGame (void) { gi.dprintf ("==== ShutdownGame ====\n"); IRC_printf (IRC_T_SERVER, "==== ShutdownGame ===="); IRC_exit (); //PG BUND vExitGame (); gi.FreeTags (TAG_LEVEL); gi.FreeTags (TAG_GAME); } /* ================= GetGameAPI Returns a pointer to the structure with all entry points and global variables ================= */ game_export_t *GetGameAPI (game_import_t * import) { gi = *import; globals.apiversion = GAME_API_VERSION; globals.Init = InitGame; globals.Shutdown = ShutdownGame; globals.SpawnEntities = SpawnEntities; globals.WriteGame = WriteGame; globals.ReadGame = ReadGame; globals.WriteLevel = WriteLevel; globals.ReadLevel = ReadLevel; globals.ClientThink = ClientThink; globals.ClientConnect = ClientConnect; globals.ClientUserinfoChanged = ClientUserinfoChanged; globals.ClientDisconnect = ClientDisconnect; globals.ClientBegin = ClientBegin; globals.ClientCommand = ClientCommand; globals.RunFrame = G_RunFrame; globals.ServerCommand = ServerCommand; globals.edict_size = sizeof (edict_t); return &globals; } #ifndef GAME_HARD_LINKED // this is only here so the functions in q_shared.c and q_shwin.c can link void Sys_Error (const char *error, ...) { va_list argptr; char text[1024]; va_start (argptr, error); vsnprintf (text, sizeof(text),error, argptr); va_end (argptr); gi.error (ERR_FATAL, "%s", text); } void Com_Printf (const char *msg, ...) { va_list argptr; char text[1024]; va_start (argptr, msg); vsnprintf (text, sizeof(text), msg, argptr); va_end (argptr); gi.dprintf ("%s", text); } #endif //====================================================================== /* ================= ClientEndServerFrames ================= */ void ClientEndServerFrames (void) { int i; edict_t *ent; // calc the player views now that all pushing // and damage has been added for (i = 0; i < maxclients->value; i++) { ent = g_edicts + 1 + i; if (!ent->inuse || !ent->client) continue; ClientEndServerFrame (ent); } } /* ================= EndDMLevel The timelimit or fraglimit has been exceeded ----------------- ================= */ //AZEROV extern void UnBan_TeamKillers (void); //AZEROV void EndDMLevel (void) { edict_t *ent = NULL; // TNG Stats was: edict_t *ent = NULL; char *nextmapname = NULL; qboolean byvote = false; votelist_t *maptosort = NULL; votelist_t *tmp = NULL; int newmappos; // TNG Stats, was: int newmappos; char ltm[64] = "\0"; struct tm *now; time_t tnow; tnow = time ((time_t *) 0); now = localtime (&tnow); (void) strftime (ltm, 64, "%A %d %B %H:%M:%S", now); gi.bprintf (PRINT_HIGH, "Game ending at: %s\n", ltm); IRC_printf (IRC_T_GAME, "Game ending at: %s", ltm); // stay on same level flag if ((int) dmflags->value & DF_SAME_LEVEL) { ent = G_Spawn (); ent->classname = "target_changelevel"; nextmapname = ent->map = level.mapname; } //FIREBLADE // else if (!actionmaps->value || num_maps < 1) //FIREBLADE //Igor[Rock] Begin else if (!actionmaps->value || (num_maps < 1 && (map_num_maps < 1 || !vrot->value || !rrot->value))) //Igor[Rock] End { if (level.nextmap[0]) { // go to a specific map ent = G_Spawn (); ent->classname = "target_changelevel"; nextmapname = ent->map = level.nextmap; } else { // search for a changelevel ent = G_Find (NULL, FOFS (classname), "target_changelevel"); if (!ent) { // the map designer didn't include a changelevel, // so create a fake ent that goes back to the same level ent = G_Spawn (); ent->classname = "target_changelevel"; nextmapname = ent->map = level.mapname; } } } //FIREBLADE else { //Igor[Rock] BEGIN if (dosoft==1) { team_round_going = 0; team_game_going = 0; dosoft=0; ent = G_Spawn (); nextmapname = ent->map = level.nextmap; } else if (vrot->value) { ent = G_Spawn (); ent->classname = "target_changelevel"; Q_strncpyz(level.nextmap, map_votes->mapname, sizeof(level.nextmap)); nextmapname = ent->map = level.nextmap; maptosort = map_votes; map_votes = maptosort->next; for (tmp = map_votes; tmp->next != NULL; tmp = tmp->next) ; tmp->next = maptosort; maptosort->next = NULL; } else if (rrot->value) { // TNG: Making sure the rotation works fine // If there is just one map in the rotation: if(num_maps == 1) { cur_map = 0; ent = G_Spawn (); ent->classname = "target_changelevel"; //Yoohoo Q_strncpyz(level.nextmap, map_rotation[cur_map], sizeof(level.nextmap)); nextmapname = ent->map = level.nextmap; } // if there are 2 or more else { nextmapname = level.mapname; while(!Q_stricmp(level.mapname, nextmapname)) { srand(rand()); // Reinitializing the random generator cur_map = rand () % num_maps; if (cur_map >= num_maps) cur_map = 0; ent = G_Spawn (); ent->classname = "target_changelevel"; //Yoohoo Q_strncpyz(level.nextmap, map_rotation[cur_map], sizeof(level.nextmap)); nextmapname = ent->map = level.nextmap; } } } else { //Igor[Rock] End cur_map++; if (cur_map >= num_maps) cur_map = 0; ent = G_Spawn (); ent->classname = "target_changelevel"; Q_strncpyz(level.nextmap, map_rotation[cur_map], sizeof(level.nextmap)); nextmapname = ent->map = level.nextmap; //Igor[Rock] BEGIN } //Igor[Rock] End } //PG BUND - BEGIN level.tempmap[0] = '\0'; vExitLevel (level.tempmap); if (level.tempmap[0]) { // change to new map... byvote = true; nextmapname = ent->map = level.tempmap; // TempFile added ent->map to fit 1.52 EndDMLevel() conventions if (level.nextmap != NULL) level.nextmap[0] = '\0'; } //PG BUND - END //Igor[Rock] Begin (we have to change the position in the maplist here, because now the votes are up-to-date if ((maptosort != NULL) && (num_allvotes > map_num_maps)) { // I inserted the map_num_maps here to block an one user vote rotation... newmappos = (int) (((100.0 - (((float) maptosort->num_allvotes * 100.0) / (float) num_allvotes)) * ((float) map_num_maps - 1.0)) / 100.0); if (!(newmappos == (map_num_maps - 1))) { // Delete the map from the end of the list for (tmp = map_votes; tmp->next != maptosort; tmp = tmp->next) ; tmp->next = NULL; //insert it at the right position if (newmappos == 0) { maptosort->next = map_votes; map_votes = maptosort; } else { newmappos--; for (tmp = map_votes; newmappos > 0; tmp = tmp->next) { newmappos--; } maptosort->next = tmp->next; tmp->next = maptosort; } } } //Igor[Rock] End if (level.nextmap != NULL && !byvote) { gi.bprintf (PRINT_HIGH, "Next map in rotation is %s.\n", level.nextmap); IRC_printf (IRC_T_SERVER, "Next map in rotation is %s.", level.nextmap); } //FIREBLADE ReadMOTDFile (); BeginIntermission (ent); //AZEROV UnBan_TeamKillers (); //AZEROV } /* ================= CheckDMRules ================= */ void CheckDMRules (void) { int i; gclient_t *cl; if (level.intermissiontime) return; if (!deathmatch->value) return; //FIREBLADE if (teamplay->value) { CheckTeamRules (); if (ctf->value) { if (CTFCheckRules ()) { ResetPlayers (); EndDMLevel (); } } } else /* not teamplay */ { if (timelimit->value) { if (level.time >= timelimit->value * 60) { gi.bprintf (PRINT_HIGH, "Timelimit hit.\n"); IRC_printf (IRC_T_GAME, "Timelimit hit."); EndDMLevel (); return; } } if (dm_shield->value) { for (i = 0; i < maxclients->value; i++) { if (!g_edicts[i + 1].inuse) continue; if (game.clients[i].ctf_uvtime > 0) { game.clients[i].ctf_uvtime--; if (!game.clients[i].ctf_uvtime) { gi.centerprintf (&g_edicts[i + 1], "ACTION!"); } else if (game.clients[i].ctf_uvtime % 10 == 0) { gi.centerprintf (&g_edicts[i + 1], "Shield %d", game.clients[i].ctf_uvtime / 10); } } } } //FIREBLADE //PG BUND - BEGIN if (vCheckVote () == true) { EndDMLevel (); return; } //PG BUND - END } if (fraglimit->value) { for (i = 0; i < maxclients->value; i++) { cl = game.clients + i; if (!g_edicts[i + 1].inuse) continue; if (cl->resp.score >= fraglimit->value) { gi.bprintf (PRINT_HIGH, "Fraglimit hit.\n"); IRC_printf (IRC_T_GAME, "Fraglimit hit."); if (ctf->value) ResetPlayers (); EndDMLevel (); return; } } } } /* ============= ExitLevel ============= */ void ExitLevel (void) { int i; edict_t *ent; char command[256]; if(softquit) { gi.bprintf(PRINT_HIGH, "Soft quit was requested by admin. The server will now exit.\n"); /* leave clients reconnecting just in case if the server will come back */ for (i = 1; i <= (int) (maxclients->value); i++) { ent = getEnt (i); if(!ent->inuse) continue; stuffcmd (ent, "reconnect\n"); } Com_sprintf (command, sizeof (command), "quit\n"); gi.AddCommandString (command); level.changemap = NULL; level.exitintermission = 0; level.intermissiontime = 0; ClientEndServerFrames (); return; } Com_sprintf (command, sizeof (command), "gamemap \"%s\"\n", level.changemap); gi.AddCommandString (command); level.changemap = NULL; level.exitintermission = 0; level.intermissiontime = 0; ClientEndServerFrames (); // clear some things before going to next level for (i = 0; i < maxclients->value; i++) { ent = g_edicts + 1 + i; if (!ent->inuse) continue; if (ent->health > ent->client->pers.max_health) ent->health = ent->client->pers.max_health; } //FIREBLADE if (teamplay->value) { for(i=TEAM1; i<TEAM_TOP; i++) { teams[i].score = 0; // AQ2 TNG - Reset serverinfo score cvars too gi.cvar_forceset(teams[i].teamscore->name, "0"); } } //FIREBLADE if (ctf->value) { CTFInit (); } } // TNG Darkmatch int day_cycle_at = 0; // variable that keeps track where we are in the cycle (0 = normal, 1 = darker, 2 = dark, 3 = pitch black, 4 = dark, 5 = darker) float day_next_cycle = 10.0; void CycleLights () { static const char brightness[] = "mmmlkjihgfedcbaaabcdefghijkl"; char temp[2]; if (darkmatch->value != 3 || !day_cycle->value) return; if (level.time == 10.0) day_next_cycle = level.time + day_cycle->value; if (day_next_cycle == level.time) { day_cycle_at++; if (day_cycle_at >= strlen(brightness)) { day_cycle_at = 0; } temp[0] = brightness[day_cycle_at]; temp[1] = 0; gi.configstring (CS_LIGHTS + 0, temp); day_next_cycle = level.time + day_cycle->value; } } /* ================ G_RunFrame Advances the world by 0.1 seconds ================ */ void G_RunFrame (void) { int i; edict_t *ent; realLtime += 0.1f; if(pause_time) { if(pause_time <= 50) { if(pause_time % 10 == 0) CenterPrintAll (va("Game will unpause in %i seconds!", pause_time/10)); } else if(pause_time == 100) CenterPrintAll ("Game will unpause in 10 seconds!"); else if ((pause_time % 100) == 0) gi.bprintf (PRINT_HIGH, "Game is paused for %i:%02i.\n", (pause_time/10)/60, (pause_time/10)%60); pause_time--; } if(!pause_time) { level.framenum++; level.time = level.framenum * FRAMETIME; // choose a client for monsters to target this frame AI_SetSightClient (); } // IRC poll IRC_poll (); // exit intermissions if (level.exitintermission) { ExitLevel (); return; } // TNG Darkmatch Cycle if(!pause_time) { CycleLights (); // // treat each object in turn // even the world gets a chance to think // ent = &g_edicts[0]; for (i = 0; i < globals.num_edicts; i++, ent++) { if (!ent->inuse) continue; level.current_entity = ent; VectorCopy (ent->s.origin, ent->s.old_origin); // if the ground entity moved, make sure we are still on it if (ent->groundentity && ent->groundentity->linkcount != ent->groundentity_linkcount) { ent->groundentity = NULL; if (!(ent->flags & (FL_SWIM | FL_FLY)) && ent->svflags & SVF_MONSTER) { M_CheckGround (ent); } } if (i > 0 && i <= maxclients->value) { if (!(level.framenum % 80)) stuffcmd(ent, "cmd_stat_mode $stat_mode\n"); // TNG Stats End ClientBeginServerFrame (ent); continue; } G_RunEntity (ent); } // see if it is time to end a deathmatch CheckDMRules (); } CheckNeedPass (); // build the playerstate_t structures for all players ClientEndServerFrames (); } //ADDED FROM 3.20 SOURCE -FB //Commented out spectator_password stuff since we don't have that now. /* ================= CheckNeedPass ================= */ void CheckNeedPass (void) { int need; // if password or spectator_password has changed, update needpass // as needed if (password->modified /*|| spectator_password->modified */ ) { password->modified = /*spectator_password->modified = */ false; need = 0; if (*password->string && Q_stricmp (password->string, "none")) need |= 1; /* if (*spectator_password->string && Q_stricmp(spectator_password->string, "none")) need |= 2; */ gi.cvar_set ("needpass", va ("%d", need)); } } //FROM 3.20 END
557
./aq2-tng/source/tng_balancer.c
#include "g_local.h" cvar_t *eventeams; cvar_t *use_balancer; edict_t *FindNewestPlayer(int team) { edict_t *etmp,*ent = NULL; int i; int most_time = 0; for (i = 1; i <= maxclients->value; i++) { etmp = g_edicts + i; if (etmp->inuse) { if(etmp->client->resp.team == team) { if(etmp->client->resp.joined_team > most_time) { most_time = etmp->client->resp.joined_team; ent = etmp; } } } } return ent; } void CalculatePlayers(int *team1, int *team2, int *team3, int *spectator) { edict_t *e; int i; for (i = 1; i <= maxclients->value; i++) { e = g_edicts + i; if (e->inuse) { if(e->client->resp.team == TEAM1 && team1 != NULL) (*team1)++; else if(e->client->resp.team == TEAM2 && team2 != NULL) (*team2)++; else if(e->client->resp.team == TEAM3 && team3 != NULL) (*team3)++; else if(e->client->resp.team == NOTEAM && spectator != NULL) (*spectator)++; // if it's none of the above, what the heck is it?! } } } /* parameter can be current (dead) player or null */ qboolean CheckForUnevenTeams (edict_t *ent) { edict_t *swap_ent = NULL; int team1 = 0, team2 = 0, other_team = 0; if(!use_balancer->value || use_3teams->value) return false; CalculatePlayers(&team1, &team2, NULL, NULL); if(team1 > team2+1) { other_team = TEAM2; swap_ent = FindNewestPlayer(TEAM1); } else if(team2 > team1+1) { other_team = TEAM1; swap_ent = FindNewestPlayer(TEAM2); } if(swap_ent && (!ent || ent == swap_ent)) { gi.centerprintf (swap_ent, "You have been swapped to the other team to even the game."); unicastSound(swap_ent, gi.soundindex("misc/talk1.wav"), 1.0); swap_ent->client->team_force = true; JoinTeam(swap_ent, other_team, 1); return true; } return false; } qboolean IsAllowedToJoin(edict_t *ent, int desired_team) { int onteam1 = 0, onteam2 = 0; /* FIXME: make this work with threeteam */ if (use_3teams->value) return true; if(ent->client->team_force) { ent->client->team_force = false; return true; } CalculatePlayers(&onteam1, &onteam2, NULL, NULL); /* can join both teams if they are even and can join if the other team has less players than current */ if((desired_team == TEAM1 && onteam1 < onteam2) || (desired_team == TEAM2 && onteam2 < onteam1) || (ent->client->resp.team == NOTEAM && onteam1 == onteam2)) return true; return false; }
558
./aq2-tng/source/a_vote.c
//----------------------------------------------------------------------------- // a_vote.c // // $Id: a_vote.c,v 1.14 2003/12/09 22:06:11 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: a_vote.c,v $ // Revision 1.14 2003/12/09 22:06:11 igor_rock // added "ignorepart" commadn to ignore all players with the specified part in // their name (one shot function: if player changes his name/new palyers join, // the list will _not_ changed!) // // Revision 1.13 2003/10/01 19:39:08 igor_rock // corrected underflow bugs (thanks to nopcode for bug report) // // Revision 1.12 2001/11/27 20:36:32 igor_rock // corrected the mapvoting spamm protection // // Revision 1.11 2001/11/08 11:01:10 igor_rock // finally got this damn configvote bug - configvote is OK now! :-) // // Revision 1.10 2001/11/03 17:21:57 deathwatch // Fixed something in the time command, removed the .. message from the voice command, fixed the vote spamming with mapvote, removed addpoint command (old pb command that wasnt being used). Some cleaning up of the source at a few points. // // Revision 1.9 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.8 2001/07/25 23:02:02 slicerdw // Fixed the source, added the weapons and items capping to choose command // // Revision 1.7 2001/07/16 18:28:46 ra // Changed a 40 second hard limit on mapvoting into a cvar. // // Revision 1.6 2001/06/20 07:21:21 igor_rock // added use_warnings to enable/disable time/frags left msgs // added use_rewards to enable/disable eimpressive, excellent and accuracy msgs // change the configfile prefix for modes to "mode_" instead "../mode-" because // they don't have to be in the q2 dir for doewnload protection (action dir is sufficient) // and the "-" is bad in filenames because of linux command line parameters start with "-" // // Revision 1.5 2001/06/18 11:01:42 igor_rock // added "mode-" prefix to votet configfiles, so all mode configs are close together // when someone makes a "dir" or "ls -al" command on the server (cosmetic change) // // Revision 1.4 2001/06/13 09:14:23 igor_rock // change the path for configs from "config/" to "../" because of possibility // of exploit with the "download" command if "allow_download" is set // // Revision 1.3 2001/06/13 08:39:13 igor_rock // changed "cvote" to "use_cvote" (like the other votecvars) // // Revision 1.2 2001/05/12 20:58:22 ra // // // Adding public mapvoting and kickvoting. Its controlable via cvar's mv_public // and vk_public (both default off) // // Revision 1.1.1.1 2001/05/06 17:25:12 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #ifndef MAX_STR_LEN #define MAX_STR_LEN 1000 #endif // MAX_STR_LEN //=== misc functions ======================================================= // //========================================================================== void _printplayerlist (edict_t * self, char *buf, qboolean (*markthis) (edict_t * self, edict_t * other)) { int count = 0, i; edict_t *other; char dummy, tmpbuf[32]; Q_strncatz (buf, " # Name\n", MAX_STRING_CHARS); Q_strncatz (buf, "------------------------------------\n", MAX_STRING_CHARS); for (i = 1; i <= game.maxclients; i++) { other = &g_edicts[i]; if (other->client && other != self && other->inuse) { if (markthis (self, other) == true) dummy = '*'; else dummy = ' '; sprintf (tmpbuf, "%2i %c%s\n", i, dummy, other->client->pers.netname); count++; Q_strncatz (buf, tmpbuf, MAX_STRING_CHARS); } } if (!count) Q_strncatz (buf, "None\n", MAX_STRING_CHARS); Q_strncatz (buf, "\n", MAX_STRING_CHARS); } int _numclients (void) { int count, i; edict_t *other; count = 0; for (i = 1; i <= maxclients->value; i++) { other = &g_edicts[i]; if (other->inuse && Info_ValueForKey(other->client->pers.userinfo, "mvdspec")[0] == '\0') count++; } return count; } //=== map voting =========================================================== // // Original programed by Black Cross[NL], adapted, major changes. // //========================================================================== votelist_t *map_votes; int map_num_maps; int map_num_votes; int map_num_clients; qboolean map_need_to_check_votes; cvar_t *mapvote_min; cvar_t *mapvote_need; cvar_t *mapvote_pass; //Igor[Rock] BEGIN // moved here from the func ReadMapListFile because I need it global char maplistpath[MAX_STR_LEN]; //Igor[Rock] END #define MAPVOTESECTION "mapvote" // forward declarations votelist_t *MapWithMostVotes (float *p); int AddVoteToMap (char *mapname, edict_t * ent); void ReadMaplistFile (void); qboolean _iCheckMapVotes (void); // void Cmd_Votemap_f (edict_t * ent, char *t) { char *oldvote; if (!*t) { gi.cprintf (ent, PRINT_HIGH, "You need an argument to the vote command (name of map).\n"); return; } if (level.intermissiontime) { gi.cprintf (ent, PRINT_HIGH, "Mapvote disabled during intermission\n"); return; } // BEGIN Igor[Rock] if (level.time < mapvote_waittime->value) { gi.cprintf (ent, PRINT_HIGH, "Mapvote currently blocked - Please vote again in %d seconds\n", (int) ((float) mapvote_waittime->value + 1.0 - level.time)); } else { // END Igor[Rock] oldvote = ent->client->resp.mapvote; switch (AddVoteToMap (t, ent)) { case 0: gi.cprintf (ent, PRINT_HIGH, "You have voted on map \"%s\"\n", t); if (mv_public->value) gi.bprintf (PRINT_HIGH, "%s voted for \"%s\"\n", ent->client->pers.netname, t); break; case 1: gi.cprintf (ent, PRINT_HIGH, "You have changed your vote to map \"%s\"\n", t); if (mv_public->value) { if(Q_stricmp (t, oldvote)) gi.bprintf (PRINT_HIGH,"%s changed his mind and voted for \"%s\"\n", ent->client->pers.netname, t); else gi.cprintf (ent, PRINT_HIGH, "We heard you the first time!\n"); } break; default: //error gi.cprintf (ent, PRINT_HIGH, "Map \"%s\" is not in the votelist!\n", t); break; } } return; } void Cmd_Maplist_f (edict_t * ent, char *dummy) { //go through the votelist and list out all the maps and % votes int lines, chars_on_line, len_mr; float p_test = 0.0f, p_most = 0.0f; votelist_t *search, *most; char msg_buf[MAX_STRING_CHARS], tmp_buf[128]; //only 40 are used most = MapWithMostVotes (&p_most); sprintf (msg_buf, "List of maps that can be voted on:\nRequire more than %d%% votes (%.2f)\n\n", (int)mapvote_pass->value, mapvote_pass->value / 100.0f); lines = chars_on_line = 0; for (search = map_votes; search != NULL; search = search->next) { if (map_num_clients > 0) p_test = (float) ((float) search->num_votes / (float) map_num_clients); if (p_test >= 10.0) len_mr = 11; else len_mr = 10; len_mr += strlen (search->mapname); //Igor[Rock] begin // if (num_allvotes && vrot->value) // len_mr += 4; //Igor[Rock] end if ((chars_on_line + len_mr + 2) > 39) { Q_strncatz (msg_buf, "\n", sizeof(msg_buf)); lines++; chars_on_line = 0; if (lines > 25) break; } //Igor[Rock] begin // if (num_allvotes && vrot->value) { // sprintf(tmp_buf, "%s (%.2f,%2d%%%%) ", // search->mapname, p_test, // (search->num_allvotes * 100) / num_allvotes); // } // else { Com_sprintf (tmp_buf, sizeof(tmp_buf), "%s (%.2f) ", search->mapname, p_test); // } //Igor[Rock] End Q_strncatz(msg_buf, tmp_buf, sizeof(msg_buf)); chars_on_line += len_mr; } if (map_votes == NULL) Q_strncatz(msg_buf, "None!", sizeof(msg_buf)); else if (most != NULL) { Com_sprintf (tmp_buf, sizeof(tmp_buf), "\n\nMost votes: %s (%.2f)", most->mapname, p_most); Q_strncatz(msg_buf, tmp_buf, sizeof(msg_buf)); } Q_strncatz(msg_buf, "\n\n", sizeof(msg_buf)); Com_sprintf (tmp_buf, sizeof(tmp_buf), "%d/%d (%.2f%%) clients voted\n%d client%s minimum (%d%% required)", map_num_votes, map_num_clients, (float)( (float)map_num_votes / (float)(map_num_clients > 0 ? map_num_clients : 1) * 100.0f), // TempFile changed to percentual display (int)mapvote_min->value, (mapvote_min->value > 1 ? "s" : ""), (int)mapvote_need->value); Q_strncatz(msg_buf, tmp_buf, sizeof(msg_buf)); gi.centerprintf (ent, "%s", msg_buf); return; } // void _MapInitClient (edict_t * ent) { ent->client->resp.mapvote = NULL; } // void _RemoveVoteFromMap (edict_t * ent) { votelist_t *search; map_need_to_check_votes = true; if (ent->client->resp.mapvote == NULL) return; for (search = map_votes; search != NULL; search = search->next) { if (Q_stricmp (search->mapname, ent->client->resp.mapvote) == 0) { map_num_votes--; search->num_votes--; ent->client->resp.mapvote = NULL; break; } } return; } // void _MapExitLevel (char *NextMap) { votelist_t *votemap = NULL; //Igor[Rock] BEGIN FILE *votefile; char buf[MAX_STR_LEN]; //Igor[Rock] END if (_iCheckMapVotes ()) { votemap = MapWithMostVotes (NULL); Q_strncpyz (NextMap, votemap->mapname, MAX_QPATH); gi.bprintf (PRINT_HIGH, "Next map was voted on and is %s.\n", NextMap); } //clear stats for (votemap = map_votes; votemap != NULL; votemap = votemap->next) { //Igor[Rock] BEGIN if (votemap->num_votes) { votemap->num_allvotes += votemap->num_votes; num_allvotes += votemap->num_votes; } if (Q_stricmp (level.mapname, votemap->mapname) == 0) { if (map_num_clients > 1) { if (votemap->num_allvotes < (map_num_clients / 2)) { num_allvotes -= votemap->num_allvotes; votemap->num_allvotes = 0; } else { num_allvotes -= (map_num_clients / 2); votemap->num_allvotes -= (map_num_clients / 2); } } else { if (votemap->num_allvotes) { num_allvotes--; votemap->num_allvotes--; } } } //Igor[Rock] END votemap->num_votes = 0; } //Igor[Rock] BEGIN // Save the actual votes to a file votefile = fopen (maplistpath, "w"); if (votefile != NULL) { sprintf (buf, "%d\n", num_allvotes); fputs (buf, votefile); for (votemap = map_votes; votemap != NULL; votemap = votemap->next) { sprintf (buf, "%s,%d\n", votemap->mapname, votemap->num_allvotes); fputs (buf, votefile); } fclose (votefile); } //Igor[Rock] END map_num_votes = 0; map_num_clients = 0; map_need_to_check_votes = true; } // qboolean _CheckMapVotes (void) { if (use_mapvote->value == 2 && !matchmode->value) //Change to voted map only at mapchange return false; if (_iCheckMapVotes() == true) { gi.bprintf (PRINT_HIGH, "More than %i%% map votes reached.\n", (int)mapvote_pass->value); return true; } return false; } // qboolean _MostVotesStr (char *buf) { float p_most = 0.0f; votelist_t *most; most = MapWithMostVotes(&p_most); if (most != NULL) { sprintf (buf, "%s (%.2f%%)", most->mapname, p_most * 100.0f); return true; } else strcpy (buf, "(no map)"); return false; } // void _MapWithMostVotes (void) { char buf[1024], sbuf[512]; if (_MostVotesStr (sbuf)) { sprintf (buf, "Most wanted map: %s\n", sbuf); gi.bprintf (PRINT_HIGH, strtostr2 (buf)); } } // cvar_t *_InitMapVotelist (ini_t * ini) { char buf[1024]; // note that this is done whether we have set "use_mapvote" or not! map_votes = NULL; map_num_maps = 0; map_num_votes = 0; map_num_clients = 0; map_need_to_check_votes = true; ReadMaplistFile (); use_mapvote = gi.cvar ("use_mapvote", "0", 0); //Igor[Rock] Begin vrot = gi.cvar ("vrot", "0", CVAR_LATCH); rrot = gi.cvar ("rrot", "0", CVAR_LATCH); //Igor[Rock] End mapvote_min = gi.cvar ("mapvote_min", ReadIniStr (ini, MAPVOTESECTION, "mapvote_min", buf, "1"), CVAR_LATCH); mapvote_need = gi.cvar ("mapvote_need", ReadIniStr (ini, MAPVOTESECTION, "mapvote_need", buf, "0"), CVAR_LATCH); mapvote_pass = gi.cvar ("mapvote_pass", ReadIniStr (ini, MAPVOTESECTION, "mapvote_pass", buf, "50"), CVAR_LATCH); return (use_mapvote); } //--------------- qboolean _iCheckMapVotes (void) { static qboolean enough = false; float p; votelist_t *tmp; if (!map_need_to_check_votes) return (enough); tmp = MapWithMostVotes (&p); enough = (tmp != NULL && p >= mapvote_pass->value / 100.0f); if (map_num_clients < mapvote_min->value) enough = false; if (mapvote_need->value) { if ((float)((float) map_num_votes / (float) map_num_clients) < (float)(mapvote_need->value / 100.0f)) enough = false; } map_need_to_check_votes = false; return (enough); } votelist_t *MapWithMostVotes (float *p) { int i; float p_most = 0.0f, votes; votelist_t *search, *most; edict_t *e; if (map_votes == NULL) return (NULL); //find map_num_clients map_num_clients = _numclients(); if (map_num_clients == 0) return (NULL); most = NULL; for (search = map_votes; search != NULL; search = search->next) { votes = (float)((float)search->num_votes / (float)map_num_clients); if (votes > p_most) { p_most = votes; most = search; } } if (p != NULL) *p = p_most; return (most); } int AddVoteToMap (char *mapname, edict_t * ent) { int changed = 0; votelist_t *search; map_need_to_check_votes = true; if (ent->client->resp.mapvote != NULL) { _RemoveVoteFromMap (ent); changed = 1; } for (search = map_votes; search != NULL; search = search->next) { if (!Q_stricmp(search->mapname, mapname)) { map_num_votes++; search->num_votes++; ent->client->resp.mapvote = search->mapname; return changed; } } // if we get here we didn't find the map! return -1; } void MapSelected (edict_t * ent, pmenu_t * p) { char *ch; ch = p->text; if (ch) { while (*ch != ' ' && *ch != '\0') ch++; *ch = '\0'; } ch = p->text; if (ch && *ch == '*') ch++; PMenu_Close (ent); Cmd_Votemap_f (ent, ch); } void AddMapToMenu (edict_t * ent, int fromix) { int i; char buffer[512], spc[64]; votelist_t *search; float prozent; i = 0; search = map_votes; while (search && i < fromix) { search = search->next; i++; } while (search) { prozent = (float) (((float) search->num_votes / (float) map_num_clients) * 100.0f); i = 27 - strlen (search->mapname); if (prozent < 10.00) i -= 6; else if (prozent < 100.00) i -= 7; else i -= 8; if (i < 0) i = 0; spc[i--] = '\0'; while (i >= 0) spc[i--] = ' '; //+ Marker: Hier einbauen, da▀ die gewΣhlte Karte markiert ist // problem: '*' am anfang wird nicht berⁿcksichtigt. - erledigt - //alt: sprintf(buffer, "%s%s%.1f%%", search->mapname, spc, prozent); sprintf (buffer, "%s%s%s%.1f%%", ent->client->resp.mapvote == search->mapname ? "*" : "", search->mapname, spc, prozent); if (xMenu_Add (ent, buffer, MapSelected) == true) search = search->next; else search = NULL; } } void MapVoteMenu (edict_t * ent, pmenu_t * p) { char buf[1024], sbuf[512]; PMenu_Close (ent); if (_MostVotesStr (sbuf)); sprintf (buf, "most: %s", sbuf); if (xMenu_New (ent, MAPMENUTITLE, buf, AddMapToMenu) == false) gi.cprintf (ent, PRINT_MEDIUM, "No map to vote for.\n"); } void ReadMaplistFile (void) { int i, bs; votelist_t *list = NULL, *tmp; FILE *maplist_file; char buf[MAX_STR_LEN]; //Igor[Rock] BEGIN // added variable maplist.ini Files with Variable "maplistname" // changed maplistpath to a global variable! cvar_t *maplistname; maplistname = gi.cvar ("maplistname", "maplist.ini", 0); if (maplistname->string && *(maplistname->string)) sprintf (maplistpath, "%s/%s", GAMEVERSION, maplistname->string); else sprintf (maplistpath, "%s/%s", GAMEVERSION, "maplist.ini"); maplist_file = fopen (maplistpath, "r"); //Igor[Rock] End if (maplist_file == NULL) { // no "maplist.ini" file so use the maps from "action.ini" if (num_maps <= 0) return; map_votes = (struct votelist_s *) gi.TagMalloc (sizeof (struct votelist_s), TAG_GAME); map_votes->mapname = map_rotation[0]; map_votes->num_votes = 0; //Igor[Rock] BEGIN map_votes->num_allvotes = 0; //Igor[Rock] END map_votes->next = NULL; list = map_votes; for (i = 1; i < num_maps; i++) { tmp = (struct votelist_s *) gi.TagMalloc (sizeof (struct votelist_s), TAG_GAME); tmp->mapname = map_rotation[i]; tmp->num_votes = 0; //Igor[Rock] BEGIN tmp->num_allvotes = 0; //Igor[Rock] END tmp->next = NULL; list->next = tmp; list = tmp; } } else { // read the maplist.ini file for (i = 0; fgets (buf, MAX_STR_LEN - 10, maplist_file) != NULL;) { //first remove trailing spaces for (bs = strlen (buf); bs > 0 && (buf[bs - 1] == '\r' || buf[bs - 1] == '\n' || buf[bs - 1] == ' '); bs--) buf[bs - 1] = '\0'; if (bs > 0 && strncmp (buf, "#", 1) != 0 && strncmp (buf, "//", 2) != 0) { if (i == 0) { map_votes = (struct votelist_s *) gi. TagMalloc (sizeof (struct votelist_s), TAG_GAME); map_votes->mapname = gi.TagMalloc (bs + 1, TAG_GAME); strcpy (map_votes->mapname, buf); map_votes->num_votes = 0; //Igor[Rock] BEGIN map_votes->num_allvotes = 0; //Igor[Rock] END map_votes->next = NULL; list = map_votes; i++; } else { tmp = (struct votelist_s *) gi. TagMalloc (sizeof (struct votelist_s), TAG_GAME); tmp->mapname = gi.TagMalloc (bs + 1, TAG_GAME); strcpy (tmp->mapname, buf); tmp->num_votes = 0; //Igor[Rock] BEGIN tmp->num_allvotes = 0; //Igor[Rock] END tmp->next = NULL; list->next = tmp; list = tmp; i++; } } } fclose (maplist_file); map_num_maps = i; } //Igor[Rock] BEGIN //load the saved values from the last run of the server sprintf (maplistpath, "%s-votes", maplistpath); maplist_file = fopen (maplistpath, "r"); if (maplist_file != NULL) { for (i = 0; fgets (buf, MAX_STR_LEN - 10, maplist_file) != NULL;) { //first remove trailing spaces for (bs = strlen (buf); bs > 0 && (buf[bs - 1] == '\r' || buf[bs - 1] == '\n' || buf[bs - 1] == ' '); bs--) buf[bs - 1] = '\0'; if (i == 0) { num_allvotes = atoi (buf); } else { for (tmp = map_votes; tmp->next != NULL; tmp = tmp->next) { if (!strncmp (tmp->mapname, buf, strlen (tmp->mapname))) { tmp->num_allvotes = atoi (&buf[strlen (tmp->mapname) + 1]); } } } i++; } fclose (maplist_file); } //Igor[Rock] End return; } //=== kick voting ========================================================== // //========================================================================== #define KICKVOTESECTION "kickvote" cvar_t *kickvote_min; cvar_t *kickvote_need; cvar_t *kickvote_pass; cvar_t *kickvote_tempban; qboolean kickvotechanged = false; edict_t *Mostkickvotes = NULL; float Allkickvotes = 0.0; float Mostkickpercent = 0.0; void _SetKickVote (edict_t * ent, edict_t * target) { if (ent->client->resp.kickvote == target) { ent->client->resp.kickvote = NULL; gi.cprintf (ent, PRINT_MEDIUM, "Your kickvote on %s is removed\n", target->client->pers.netname); if (vk_public->value) gi.bprintf (PRINT_HIGH, "%s doesnt want to kick %s after all\n", ent->client->pers.netname, target->client->pers.netname); } else { if (ent->client->resp.kickvote) { gi.cprintf (ent, PRINT_MEDIUM, "Kickvote was changed to %s\n", target->client->pers.netname); } else { gi.cprintf (ent, PRINT_MEDIUM, "You voted on %s to be kicked\n", target->client->pers.netname); if (vk_public->value) { gi.bprintf (PRINT_HIGH, "%s voted to kick %s\n", ent->client->pers.netname, target->client->pers.netname); } } ent->client->resp.kickvote = target; kickvotechanged = true; } kickvotechanged = true; _CheckKickVote (); } void _ClrKickVotesOn (edict_t * target) { edict_t *other; int i, j; j = 0; for (i = 1; i <= game.maxclients; i++) { other = &g_edicts[i]; if (other->client && other->inuse) { if (other->client->resp.kickvote == target) { other->client->resp.kickvote = NULL; j++; } } } if (j > 0 || target->client->resp.kickvote) { kickvotechanged = true; _CheckKickVote (); } } void _DoKick (edict_t * target) { char buf[128]; sprintf (buf, "more than %i%% voted for.", (int) kickvote_pass->value); _ClrKickVotesOn (target); if (kickvote_tempban->value) Ban_TeamKiller(target, 1); //Ban for 1 game KickClient (target, buf); } cvar_t *_InitKickVote (ini_t * ini) { char buf[1024]; kickvote_min = gi.cvar ("kickvote_min", ReadIniStr (ini, KICKVOTESECTION, "kickvote_min", buf, "4"), CVAR_LATCH); kickvote_need = gi.cvar ("kickvote_need", ReadIniStr (ini, KICKVOTESECTION, "kickvote_need", buf, "0"), CVAR_LATCH); kickvote_pass = gi.cvar ("kickvote_pass", ReadIniStr (ini, KICKVOTESECTION, "kickvote_pass", buf, "75"), CVAR_LATCH); kickvote_tempban = gi.cvar ("kickvote_tempban", ReadIniStr (ini, KICKVOTESECTION, "kickvote_tempban", buf, "1"), CVAR_LATCH); kickvotechanged = false; return (use_kickvote); } void _InitKickClient (edict_t * ent) { ent->client->resp.kickvote = NULL; } void _ClientKickDisconnect (edict_t * ent) { _ClrKickVotesOn (ent); } void _CheckKickVote (void) { int i, j, votes, maxvotes, playernum, playervoted; edict_t *other, *target, *mtarget; if (kickvotechanged == false) return; kickvotechanged = false; playernum = _numclients (); if (playernum < kickvote_need->value) return; maxvotes = 0; mtarget = NULL; playervoted = 0; for (i = 1; i <= game.maxclients; i++) { other = &g_edicts[i]; if (other->client && other->inuse && other->client->resp.kickvote) { votes = 0; target = other->client->resp.kickvote; playervoted++; for (j = 1; j <= game.maxclients; j++) { other = &g_edicts[j]; if (other->client && other->inuse && other->client->resp.kickvote == target) votes++; } if (votes > maxvotes) { maxvotes = votes; mtarget = target; } } } Mostkickvotes = NULL; if (!mtarget) return; Mostkickvotes = mtarget; Mostkickpercent = (float) (((float) maxvotes / (float) playernum) * 100.0); Allkickvotes = (float) (((float) playervoted / (float) playernum) * 100.0); if (Allkickvotes < kickvote_need->value) return; if (Mostkickpercent < kickvote_pass->value) return; // finally _DoKick (mtarget); } void _KickSelected (edict_t * ent, pmenu_t * p) { char *ch; ch = p->text; if (ch) { while (*ch != ':' && *ch != '\0') ch++; *ch = '\0'; } ch = p->text; if (ch && *ch == '*') ch++; PMenu_Close (ent); Cmd_Votekicknum_f (ent, ch); } #define MostKickMarker " " void _AddKickuserToMenu (edict_t * ent, int fromix) { int i, j; edict_t *other; qboolean erg; char buf[256]; j = 0; for(i = 1; i <= game.maxclients && j < fromix; i++) { other = &g_edicts[i]; if (other->inuse && other != ent) j++; } erg = true; while (i <= game.maxclients && erg) { other = &g_edicts[i]; if (other->inuse && other != ent) { //+ Marker: Hier gewΣhlten markieren - erledigt - sprintf (buf, "%s%2i: %s%s", other == ent->client->resp.kickvote ? "*" : "", i, other->client->pers.netname, other == Mostkickvotes ? MostKickMarker : ""); erg = xMenu_Add (ent, buf, _KickSelected); } i++; } } void _KickVoteSelected (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); if (xMenu_New (ent, KICKMENUTITLE, "vote for a player to kick", _AddKickuserToMenu) == false) gi.cprintf (ent, PRINT_MEDIUM, "No player to kick.\n"); } void Cmd_Votekick_f (edict_t * ent, char *argument) { edict_t *target; if (!*argument) { gi.cprintf (ent, PRINT_HIGH, "\nUse votekick <playername>.\n"); return; } target = FindClientByPersName (argument); if (target && target != ent) _SetKickVote (ent, target); else gi.cprintf (ent, PRINT_HIGH, "\nUse kicklist to see who can be kicked.\n"); } void Cmd_Votekicknum_f (edict_t * ent, char *argument) { int i; edict_t *target; if (!*argument) { gi.cprintf (ent, PRINT_HIGH, "\nUse votekicknum <playernumber>.\n"); return; } i = atoi (argument); if(i < 1 || i > game.maxclients) { gi.cprintf (ent, PRINT_MEDIUM, "\nUsed votekicknum with illegal number.\n"); return; } target = &g_edicts[i]; if (target && target->client && target != ent && target->inuse) _SetKickVote (ent, target); else gi.cprintf (ent, PRINT_HIGH, "\nUse kicklist to see who can be kicked.\n"); } qboolean _vkMarkThis (edict_t * self, edict_t * other) { if (self->client->resp.kickvote == other) return true; return false; } void Cmd_Kicklist_f (edict_t * ent, char *argument) { char buf[MAX_STRING_CHARS], tbuf[256]; strcpy (buf, "\nAvailable players to kick:\n\n"); _printplayerlist (ent, buf, _vkMarkThis); // adding vote settings Com_sprintf (tbuf, sizeof(tbuf), "Vote rules: %i client%s min. (currently %i),\n" \ "%.1f%% must have voted overall (currently %.1f%%)\n" \ "and %.1f%%%% on the same (currently %.1f%% on %s),\n" \ "kicked players %s be temporarily banned.\n\n", (int) (kickvote_min->value), (kickvote_min->value == 1) ? " " : "s ", _numclients (), kickvote_need->value, Allkickvotes, kickvote_pass->value, Mostkickpercent, Mostkickvotes == NULL ? "nobody" : Mostkickvotes->client->pers.netname, kickvote_tempban ? "will" : "won't"); // double percent sign! cprintf will process them as format strings. Q_strncatz (buf, tbuf, sizeof(buf)); gi.cprintf (ent, PRINT_MEDIUM, "%s", buf); } //=== config voting ======================================================== // // Original programed by Black Cross[NL], adapted, major changes. // //========================================================================== configlist_t *config_votes; int config_num_configs; int config_num_votes; int config_num_clients; qboolean config_need_to_check_votes; cvar_t *cvote_min; cvar_t *cvote_need; cvar_t *cvote_pass; char configlistpath[MAX_STR_LEN]; #define CONFIGVOTESECTION "configvote" // forward declarations configlist_t *ConfigWithMostVotes (float *p); int AddVoteToConfig (char *configname, edict_t * ent); void ReadConfiglistFile (void); qboolean _iCheckConfigVotes (void); // void Cmd_Voteconfig_f (edict_t * ent, char *t) { if (!*t) { gi.cprintf (ent, PRINT_HIGH, "You need an argument to the vote command (name of config).\n"); return; } if (level.intermissiontime) { gi.cprintf (ent, PRINT_HIGH, "Configvote disabled during intermission\n"); return; } // BEGIN Igor[Rock] if (level.time < 40.0) { gi.cprintf (ent, PRINT_HIGH, "Configvote currently blocked - Please vote again in %d seconds\n", (int) (41.0 - level.time)); } else { // END Igor[Rock] switch (AddVoteToConfig (t, ent)) { case 0: gi.cprintf (ent, PRINT_HIGH, "You have voted on config \"%s\"\n", t); break; case 1: gi.cprintf (ent, PRINT_HIGH, "You have changed your vote to config \"%s\"\n", t); break; default: //error gi.cprintf (ent, PRINT_HIGH, "Config \"%s\" is not in the votelist!\n", t); break; } // BEGIN Igor[Rock] } //END Igor[Rock] return; } // void Cmd_Configlist_f (edict_t * ent, char *dummy) { //go through the votelist and list out all the configs and % votes int lines, chars_on_line, len_mr; float p_test, p_most; configlist_t *search, *most; char msg_buf[MAX_STRING_CHARS], tmp_buf[128]; //only 40 are used p_test = p_most = 0.0; most = ConfigWithMostVotes (&p_most); sprintf (msg_buf, "List of configs that can be voted on:\nRequire more than %d%% votes (%.2f)\n\n", (int) cvote_pass->value, (float) ((float) cvote_pass->value / 100.0)); lines = chars_on_line = 0; for (search = config_votes; search != NULL; search = search->next) { if (config_num_clients > 0) p_test = (float)((float) search->num_votes / (float) config_num_clients); if (p_test >= 10.0) len_mr = 11; else len_mr = 10; len_mr += strlen (search->configname); if ((chars_on_line + len_mr + 2) > 39) { Q_strncatz (msg_buf, "\n", sizeof(msg_buf)); lines++; chars_on_line = 0; if (lines > 25) break; } sprintf (tmp_buf, "%s (%.2f) ", search->configname, p_test); Q_strncatz (msg_buf, tmp_buf, sizeof(msg_buf)); chars_on_line += len_mr; } if (config_votes == NULL) Q_strncatz (msg_buf, "None!", sizeof(msg_buf)); else if (most != NULL) { sprintf (tmp_buf, "\n\nMost votes: %s (%.2f)", most->configname, p_most); Q_strncatz (msg_buf, tmp_buf, sizeof(msg_buf)); } Q_strncatz (msg_buf, "\n\n", sizeof(msg_buf)); Com_sprintf (tmp_buf, sizeof(tmp_buf), "%d/%d (%.2f%%) clients voted\n%d client%s minimum (%d%% required)", config_num_votes, config_num_clients, (float) ((float) config_num_votes / (float) (config_num_clients > 0 ? config_num_clients : 1) * 100), (int) cvote_min->value, (cvote_min->value > 1 ? "s" : ""), (int) cvote_need->value); Q_strncatz (msg_buf, tmp_buf, sizeof(msg_buf)); gi.centerprintf (ent, "%s", msg_buf); return; } // void _ConfigInitClient (edict_t * ent) { ent->client->resp.cvote = NULL; } // void _RemoveVoteFromConfig (edict_t * ent) { configlist_t *search; config_need_to_check_votes = true; if (ent->client->resp.cvote == NULL) return; for (search = config_votes; search != NULL; search = search->next) { if (!Q_stricmp(search->configname, ent->client->resp.cvote)) { config_num_votes--; search->num_votes--; ent->client->resp.cvote = NULL; break; } } return; } // void _ConfigExitLevel (char *NextMap) { configlist_t *voteconfig = NULL; char buf[MAX_STR_LEN]; if (_iCheckConfigVotes ()) { voteconfig = ConfigWithMostVotes (NULL); gi.bprintf (PRINT_HIGH, "A new config was voted on and is %s.\n", voteconfig->configname); Com_sprintf (buf, sizeof (buf), "exec \"mode_%s.cfg\"\n", voteconfig->configname); //clear stats for (voteconfig = config_votes; voteconfig != NULL; voteconfig = voteconfig->next) { voteconfig->num_votes = 0; } //clear stats config_num_votes = 0; config_num_clients = 0; config_need_to_check_votes = true; gi.AddCommandString (buf); } else { //clear stats for (voteconfig = config_votes; voteconfig != NULL; voteconfig = voteconfig->next) { voteconfig->num_votes = 0; } //clear stats config_num_votes = 0; config_num_clients = 0; config_need_to_check_votes = true; } } // qboolean _CheckConfigVotes (void) { if (_iCheckConfigVotes () == true) { gi.bprintf (PRINT_HIGH, "More than %i%% config votes reached.\n", (int) cvote_pass->value); return true; } return false; } // qboolean _ConfigMostVotesStr (char *buf) { float p_most = 0.0f; configlist_t *most; most = ConfigWithMostVotes (&p_most); if (most != NULL) { sprintf (buf, "%s (%.2f%%)", most->configname, p_most * 100.0); return true; } else strcpy (buf, "(no config)"); return false; } // void _ConfigWithMostVotes (void) { char buf[1024], sbuf[512]; if (_ConfigMostVotesStr (sbuf)) { sprintf (buf, "Most wanted config: %s\n", sbuf); gi.bprintf (PRINT_HIGH, strtostr2 (buf)); } } // cvar_t *_InitConfiglist (ini_t * ini) { char buf[1024]; // note that this is done whether we have set "use_cvote" or not! config_votes = NULL; config_num_configs = 0; config_num_votes = 0; config_num_clients = 0; config_need_to_check_votes = true; ReadConfiglistFile (); use_cvote = gi.cvar ("use_cvote", "0", 0); cvote_min = gi.cvar ("cvote_min", ReadIniStr (ini, CONFIGVOTESECTION, "cvote_min", buf, "1"), CVAR_LATCH); cvote_need = gi.cvar ("cvote_need", ReadIniStr (ini, CONFIGVOTESECTION, "cvote_need", buf, "0"), CVAR_LATCH); cvote_pass = gi.cvar ("cvote_pass", ReadIniStr (ini, CONFIGVOTESECTION, "cvote_pass", buf, "50"), CVAR_LATCH); return (use_cvote); } //--------------- qboolean _iCheckConfigVotes (void) { static qboolean enough = false; float p; configlist_t *tmp; if (!config_need_to_check_votes) return (enough); tmp = ConfigWithMostVotes (&p); enough = (tmp != NULL && p >= (float) (cvote_pass->value / 100.0f)); if (config_num_clients < cvote_min->value) enough = false; if (cvote_need->value) { if ((float) ((float)config_num_votes / (float)config_num_clients) < (float)(cvote_need->value / 100.0f)) enough = false; } config_need_to_check_votes = false; return (enough); } configlist_t *ConfigWithMostVotes (float *p) { int i; float p_most; configlist_t *search, *most; edict_t *e; p_most = 0.0; if (config_votes == NULL) return (NULL); //find config_num_clients config_num_clients = 0; for (i = 1; i <= maxclients->value; i++) { e = g_edicts + i; if (e->inuse) config_num_clients++; } if (config_num_clients == 0) return (NULL); most = NULL; for (search = config_votes; search != NULL; search = search->next) { if ((float) ((float) search->num_votes / (float) config_num_clients) > p_most) { p_most = (float) ((float) search->num_votes / (float) config_num_clients); most = search; } } if (p != NULL) *p = p_most; return (most); } int AddVoteToConfig (char *configname, edict_t * ent) { int changed = 0; configlist_t *search; config_need_to_check_votes = true; if (ent->client->resp.cvote != NULL) { _RemoveVoteFromConfig (ent); changed = 1; } for (search = config_votes; search != NULL; search = search->next) if (Q_stricmp (search->configname, configname) == 0) { config_num_votes++; search->num_votes++; ent->client->resp.cvote = search->configname; return changed; } // if we get here we didn't find the config! return -1; } void ConfigSelected (edict_t * ent, pmenu_t * p) { char *ch; ch = p->text; if (ch) { while (*ch != ' ' && *ch != '\0') ch++; *ch = '\0'; } ch = p->text; if (ch && *ch == '*') ch++; PMenu_Close (ent); Cmd_Voteconfig_f (ent, ch); } void AddConfigToMenu (edict_t * ent, int fromix) { int i; char buffer[512], spc[64]; configlist_t *search; float prozent; i = 0; search = config_votes; while (search && i < fromix) { search = search->next; i++; } while (search) { prozent = (float) (((float) search->num_votes / (float) config_num_clients) * 100); i = 27 - strlen (search->configname); if (prozent < 10.00) i -= 6; else if (prozent < 100.00) i -= 7; else i -= 8; if (i < 0) i = 0; spc[i--] = '\0'; while (i >= 0) spc[i--] = ' '; sprintf (buffer, "%s%s%s%.1f%%", ent->client->resp.cvote == search->configname ? "*" : "", search->configname, spc, prozent); if (xMenu_Add (ent, buffer, ConfigSelected) == true) search = search->next; else search = NULL; } } void ConfigVoteMenu (edict_t * ent, pmenu_t * p) { char buf[1024], sbuf[512]; PMenu_Close (ent); if (_ConfigMostVotesStr (sbuf)); sprintf (buf, "most: %s", sbuf); if (xMenu_New (ent, CONFIGMENUTITLE, buf, AddConfigToMenu) == false) gi.cprintf (ent, PRINT_MEDIUM, "No config to vote for.\n"); } void ReadConfiglistFile (void) { int i, bs; configlist_t *list = NULL, *tmp; FILE *configlist_file; char buf[MAX_STR_LEN]; cvar_t *configlistname; configlistname = gi.cvar ("configlistname", "configlist.ini", 0); if (configlistname->string && *(configlistname->string)) sprintf (configlistpath, "%s/%s", GAMEVERSION, configlistname->string); else sprintf (configlistpath, "%s/%s", GAMEVERSION, "configlist.ini"); configlist_file = fopen (configlistpath, "r"); //Igor[Rock] End if (configlist_file == NULL) { } else { // read the configlist.ini file for (i = 0; fgets (buf, MAX_STR_LEN - 10, configlist_file) != NULL;) { //first remove trailing spaces for (bs = strlen (buf); bs > 0 && (buf[bs - 1] == '\r' || buf[bs - 1] == '\n' || buf[bs - 1] == ' '); bs--) buf[bs - 1] = '\0'; if (bs > 0 && strncmp (buf, "#", 1) != 0 && strncmp (buf, "//", 2) != 0) { if (i == 0) { config_votes = (struct configlist_s *) gi. TagMalloc (sizeof (struct configlist_s), TAG_GAME); config_votes->configname = gi.TagMalloc (bs + 1, TAG_GAME); strcpy (config_votes->configname, buf); config_votes->num_votes = 0; config_votes->next = NULL; list = config_votes; i++; } else { tmp = (struct configlist_s *) gi. TagMalloc (sizeof (struct configlist_s), TAG_GAME); tmp->configname = gi.TagMalloc (bs + 1, TAG_GAME); strcpy (tmp->configname, buf); tmp->num_votes = 0; tmp->next = NULL; list->next = tmp; list = tmp; i++; } } } fclose (configlist_file); config_num_configs = i; } return; } //=== player ignoring ====================================================== // // player ingoring is no voting, but since it uses the same // functions like kickvoting and offers a menu, I put it here. // At least you can say, that when it's no vote, it's a choice! :) // //========================================================================== #define IGNORELIST client->resp.ignorelist //Returns the next free slot in ignore list int _FindFreeIgnoreListEntry (edict_t * source) { return (IsInIgnoreList (source, NULL)); } //Clears a clients ignore list void _ClearIgnoreList (edict_t * ent) { int i; if (!ent->client) return; for (i = 0; i < PG_MAXPLAYERS; i++) ent->IGNORELIST[i] = NULL; } //Checks if an edict is to be ignored, returns position int IsInIgnoreList (edict_t * source, edict_t * subject) { int i; if (!source || !source->client) return 0; //ignorelist[0] is not used... for (i = 1; i < PG_MAXPLAYERS; i++) { if (source->IGNORELIST[i] == subject) return i; } return 0; } //Adds an edict to ignore list. If allready in, it will be removed void _AddOrDelIgnoreSubject (edict_t * source, edict_t * subject, qboolean silent) { int i; if (!source->client) return; if (!subject->client || !subject->inuse) { gi.cprintf (source, PRINT_MEDIUM, "\nOnly valid clients may be added to ignore list!\n"); return; } i = IsInIgnoreList (source, subject); if (i) { //subject is in ignore list, so delete it source->IGNORELIST[i] = NULL; if (!silent) gi.cprintf (source, PRINT_MEDIUM, "\n%s was removed from ignore list.\n", subject->client->pers.netname); //Maybe this has to be taken out :) if (!silent) gi.cprintf (subject, PRINT_MEDIUM, "\n%s listen to your words.\n", source->client->pers.netname); source->client->resp.ignore_time = level.framenum; } else { //subject has to be added i = _FindFreeIgnoreListEntry (source); if (!i) { if (!silent) gi.cprintf (source, PRINT_MEDIUM, "\nSorry, ignore list is full!\n"); } else { //we've found a place source->IGNORELIST[i] = subject; if (!silent) gi.cprintf (source, PRINT_MEDIUM, "\n%s was added to ignore list.\n", subject->client->pers.netname); //Maybe this has to be taken out :) if (!silent) gi.cprintf (subject, PRINT_MEDIUM, "\n%s ignores you.\n", source->client->pers.netname); } } } // void _ClrIgnoresOn (edict_t * target) { edict_t *other; int i; for (i = 1; i <= game.maxclients; i++) { other = &g_edicts[i]; if (other->client && other->inuse) { if (IsInIgnoreList (other, target)) _AddOrDelIgnoreSubject (other, target, true); } } } //Ignores players by part of the name void Cmd_IgnorePart_f (edict_t * self, char *s) { int i; int j; edict_t *target; if (!*s) { gi.cprintf (self, PRINT_MEDIUM, "\nUse ignorepart <part-of-playername>.\n"); return; } if (level.framenum < (self->client->resp.ignore_time + 100)) { gi.cprintf (self, PRINT_MEDIUM, "Wait 10 seconds before ignoring again.\n"); return; } j = 0; for (i = 1; i <= game.maxclients; i++) { target = &g_edicts[i]; if (target && target->client && target != self && (strstr(target->client->pers.netname, s) != 0)) { _AddOrDelIgnoreSubject (self, target, false); j++; } } if (j == 0) { gi.cprintf (self, PRINT_MEDIUM, "\nUse ignorelist to see who can be ignored.\n"); } } //Ignores a player by name void Cmd_Ignore_f (edict_t * self, char *s) { edict_t *target; if (!*s) { gi.cprintf (self, PRINT_MEDIUM, "\nUse ignore <playername>.\n"); return; } if (level.framenum < (self->client->resp.ignore_time + 50)) { gi.cprintf (self, PRINT_MEDIUM, "Wait 5 seconds before ignoring again.\n"); return; } target = FindClientByPersName (s); if (target && target != self) _AddOrDelIgnoreSubject (self, target, false); else gi.cprintf (self, PRINT_MEDIUM, "\nUse ignorelist to see who can be ignored.\n"); } //Ignores a player by number void Cmd_Ignorenum_f (edict_t * self, char *s) { int i; edict_t *target; if (!*s) { gi.cprintf (self, PRINT_MEDIUM, "\nUse ignorenum <playernumber>.\n"); return; } if (level.framenum < (self->client->resp.ignore_time + 50)) { gi.cprintf (self, PRINT_MEDIUM, "Wait 5 seconds before ignoring again.\n"); return; } i = atoi (s); if(i < 1 || i > game.maxclients) { gi.cprintf (self, PRINT_MEDIUM, "\nUsed ignorenum with illegal number.\n"); return; } target = &g_edicts[i]; if (target && target->client && target != self && target->inuse) _AddOrDelIgnoreSubject (self, target, false); else gi.cprintf (self, PRINT_MEDIUM, "\nUse ignorelist to see who can be ignored.\n"); } qboolean _ilMarkThis (edict_t * self, edict_t * other) { if (IsInIgnoreList (self, other)) return true; return false; } void Cmd_Ignorelist_f (edict_t * self, char *s) { char buf[MAX_STRING_CHARS]; strcpy (buf, "\nAvailable players to ignore:\n\n"); _printplayerlist (self, buf, _ilMarkThis); gi.cprintf (self, PRINT_MEDIUM, "%s", buf); } //Clears ignore list - user interface :) void Cmd_Ignoreclear_f (edict_t * self, char *s) { _ClearIgnoreList (self); gi.cprintf (self, PRINT_MEDIUM, "\nYour ignorelist is now clear.\n"); } void _IgnoreSelected (edict_t * ent, pmenu_t * p) { char *ch; ch = p->text; if (ch) { while (*ch != ':' && *ch != '\0') ch++; *ch = '\0'; } ch = p->text; if (ch && *ch == '*') ch++; PMenu_Close (ent); Cmd_Ignorenum_f (ent, ch); } void _AddIgnoreuserToMenu (edict_t * ent, int fromix) { int i, j; edict_t *other; qboolean erg; char buf[256]; j = 0; for (i = 1; i <= game.maxclients && j < fromix; i++) { other = &g_edicts[i]; if (other->inuse && other != ent) j++; } erg = true; while (i <= game.maxclients && erg) { other = &g_edicts[i]; if (other->inuse && other != ent) { //+ Marker: Hier gewΣhlten markieren - erledigt - sprintf (buf, "%s%2i: %s", IsInIgnoreList (ent, other) ? "*" : "", i, other->client->pers.netname); erg = xMenu_Add (ent, buf, _IgnoreSelected); } i++; } } void _IgnoreVoteSelected (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); if (xMenu_New (ent, IGNOREMENUTITLE, "de-/select a player to ignore", _AddIgnoreuserToMenu) == false) gi.cprintf (ent, PRINT_MEDIUM, "No player to ignore.\n"); } //=== flag voting ========================================================== // //========================================================================== // hifi cvar_t *scramblevote_min; cvar_t *scramblevote_need; cvar_t *scramblevote_pass; cvar_t *_InitScrambleVote (ini_t * ini) { use_scramblevote = gi.cvar ("use_scramblevote", "0", 0); scramblevote_min = gi.cvar ("scramblevote_min", "4", 0); scramblevote_need = gi.cvar ("scramblevote_need", "0", 0); scramblevote_pass = gi.cvar ("scramblevote_pass", "75", 0); if(!teamplay->value) return (teamplay); return (use_scramblevote); } edict_t *_RandomTeamPlayer() { int i; edict_t *ent; for (i = 1; i <= game.maxclients; i++) { ent = &g_edicts[rand() % game.maxclients + 1]; if (ent->client && ent->inuse && ent->client->resp.team != NOTEAM) { return ent; } } return NULL; } void _CalcScrambleVotes (int *numclients, int *numvotes, float *percent) { int i; edict_t *ent; *numclients = _numclients (); *numvotes = 0; *percent = 0.00f; for (i = 1; i <= game.maxclients; i++) { ent = &g_edicts[i]; if (ent->client && ent->inuse && ent->client->resp.scramblevote) { (*numvotes)++; } } if(*numvotes > 0) (*percent) = (float) (((float) *numvotes / (float) *numclients) * 100.0); } void MakeAllLivePlayersObservers(void); void _CheckScrambleVote (void) { int i, numvotes, playernum, team; float votes; edict_t *ent, *other; char buf[128]; _CalcScrambleVotes(&playernum, &numvotes, &votes); if (numvotes > 0) { sprintf (buf, "Scramble: %d votes (%.1f%%), need %.1f%%\n", numvotes, votes, scramblevote_pass->value); gi.bprintf (PRINT_HIGH, strtostr2 (buf)); } if (playernum < scramblevote_min->value) return; if (numvotes < scramblevote_need->value) return; if (votes < scramblevote_pass->value) return; MakeAllLivePlayersObservers (); for (i = 1; i <= game.maxclients; i++) { ent = &g_edicts[i]; if (ent->client && ent->inuse && ent->client->resp.team != NOTEAM) { other = _RandomTeamPlayer(); if(other != NULL && rand() % 2) { team = other->client->resp.team; other->client->resp.team = ent->client->resp.team; ent->client->resp.team = team; ent->client->resp.scramblevote = false; } } } CenterPrintAll("The teams have been scrambled!"); } void _VoteScrambleSelected (edict_t * ent, pmenu_t * p) { PMenu_Close (ent); Cmd_Votescramble_f (ent, NULL); } void Cmd_Votescramble_f (edict_t * ent, char *argument) { if(!teamplay->value) return; if(use_3teams->value) { gi.cprintf (ent, PRINT_HIGH, "\nNot in threeteam (yet).\n"); return; } ent->client->resp.scramblevote = !ent->client->resp.scramblevote; if(ent->client->resp.scramblevote) { gi.cprintf (ent, PRINT_HIGH, "\nYou voted for team scramble.\n"); gi.bprintf (PRINT_HIGH, "%s voted for team scramble\n", ent->client->pers.netname); } else { gi.cprintf (ent, PRINT_HIGH, "\nYou took your scramble vote back.\n"); gi.bprintf (PRINT_HIGH, "%s changed his mind about team scramble\n", ent->client->pers.netname); } }
559
./aq2-tng/source/g_ai.c
//----------------------------------------------------------------------------- // g_ai.c // // $Id: g_ai.c,v 1.3 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_ai.c,v $ // Revision 1.3 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.2 2001/05/12 00:37:03 ra // // // Fixing various compilerwarnings. // // Revision 1.1.1.1 2001/05/06 17:29:54 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" qboolean FindTarget (edict_t * self); extern cvar_t *maxclients; qboolean ai_checkattack (edict_t * self, float dist); qboolean enemy_vis; qboolean enemy_infront; int enemy_range; float enemy_yaw; //============================================================================ /* ================= AI_SetSightClient Called once each frame to set level.sight_client to the player to be checked for in findtarget. If all clients are either dead or in notarget, sight_client will be null. In coop games, sight_client will cycle between the clients. ================= */ void AI_SetSightClient (void) { edict_t *ent; int start, check; if (level.sight_client == NULL) start = 1; else start = level.sight_client - g_edicts; check = start; while (1) { check++; if (check > game.maxclients) check = 1; ent = &g_edicts[check]; if (ent->inuse && ent->health > 0 && !(ent->flags & FL_NOTARGET)) { level.sight_client = ent; return; // got one } if (check == start) { level.sight_client = NULL; return; // nobody to see } } } //============================================================================ /* ============= ai_move Move the specified distance at current facing. This replaces the QC functions: ai_forward, ai_back, ai_pain, and ai_painforward ============== */ void ai_move (edict_t * self, float dist) { M_walkmove (self, self->s.angles[YAW], dist); } /* ============= ai_stand Used for standing around and looking for players Distance is for slight position adjustments needed by the animations ============== */ void ai_stand (edict_t * self, float dist) { vec3_t v; if (dist) M_walkmove (self, self->s.angles[YAW], dist); if (self->monsterinfo.aiflags & AI_STAND_GROUND) { if (self->enemy) { VectorSubtract (self->enemy->s.origin, self->s.origin, v); self->ideal_yaw = vectoyaw (v); if (self->s.angles[YAW] != self->ideal_yaw && self->monsterinfo.aiflags & AI_TEMP_STAND_GROUND) { self->monsterinfo.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); self->monsterinfo.run (self); } M_ChangeYaw (self); ai_checkattack (self, 0); } else FindTarget (self); return; } if (FindTarget (self)) return; if (level.time > self->monsterinfo.pausetime) { self->monsterinfo.walk (self); return; } if (!(self->spawnflags & 1) && (self->monsterinfo.idle) && (level.time > self->monsterinfo.idle_time)) { if (self->monsterinfo.idle_time) { self->monsterinfo.idle (self); self->monsterinfo.idle_time = level.time + 15 + random () * 15; } else { self->monsterinfo.idle_time = level.time + random () * 15; } } } /* ============= ai_walk The monster is walking it's beat ============= */ void ai_walk (edict_t * self, float dist) { M_MoveToGoal (self, dist); // check for noticing a player if (FindTarget (self)) return; if ((self->monsterinfo.search) && (level.time > self->monsterinfo.idle_time)) { if (self->monsterinfo.idle_time) { self->monsterinfo.search (self); self->monsterinfo.idle_time = level.time + 15 + random () * 15; } else { self->monsterinfo.idle_time = level.time + random () * 15; } } } /* ============= ai_charge Turns towards target and advances Use this call with a distnace of 0 to replace ai_face ============== */ void ai_charge (edict_t * self, float dist) { vec3_t v; VectorSubtract (self->enemy->s.origin, self->s.origin, v); self->ideal_yaw = vectoyaw (v); M_ChangeYaw (self); if (dist) M_walkmove (self, self->s.angles[YAW], dist); } /* ============= ai_turn don't move, but turn towards ideal_yaw Distance is for slight position adjustments needed by the animations ============= */ void ai_turn (edict_t * self, float dist) { if (dist) M_walkmove (self, self->s.angles[YAW], dist); if (FindTarget (self)) return; M_ChangeYaw (self); } /* .enemy Will be world if not currently angry at anyone. .movetarget The next path spot to walk toward. If .enemy, ignore .movetarget. When an enemy is killed, the monster will try to return to it's path. .hunt_time Set to time + something when the player is in sight, but movement straight for him is blocked. This causes the monster to use wall following code for movement direction instead of sighting on the player. .ideal_yaw A yaw angle of the intended direction, which will be turned towards at up to 45 deg / state. If the enemy is in view and hunt_time is not active, this will be the exact line towards the enemy. .pausetime A monster will leave it's stand state and head towards it's .movetarget when time > .pausetime. walkmove(angle, speed) primitive is all or nothing */ /* ============= range returns the range catagorization of an entity reletive to self 0 melee range, will become hostile even if back is turned 1 visibility and infront, or visibility and show hostile 2 infront and show hostile 3 only triggered by damage ============= */ int range (edict_t * self, edict_t * other) { vec3_t v; float len; VectorSubtract (self->s.origin, other->s.origin, v); len = VectorLength (v); if (len < MELEE_DISTANCE) return RANGE_MELEE; if (len < 500) return RANGE_NEAR; if (len < 1000) return RANGE_MID; return RANGE_FAR; } /* ============= visible returns 1 if the entity is visible to self, even if not infront () ============= */ qboolean visible (edict_t * self, edict_t * other) { vec3_t spot1; vec3_t spot2; trace_t trace; VectorCopy (self->s.origin, spot1); spot1[2] += self->viewheight; VectorCopy (other->s.origin, spot2); spot2[2] += other->viewheight; trace = gi.trace (spot1, vec3_origin, vec3_origin, spot2, self, MASK_OPAQUE); if (trace.fraction == 1.0) return true; return false; } /* ============= infront returns 1 if the entity is in front (in sight) of self ============= */ qboolean infront (edict_t * self, edict_t * other) { vec3_t vec; float dot; vec3_t forward; AngleVectors (self->s.angles, forward, NULL, NULL); VectorSubtract (other->s.origin, self->s.origin, vec); VectorNormalize (vec); dot = DotProduct (vec, forward); if (dot > 0.3) return true; return false; } //============================================================================ void HuntTarget (edict_t * self) { vec3_t vec; self->goalentity = self->enemy; if (self->monsterinfo.aiflags & AI_STAND_GROUND) self->monsterinfo.stand (self); else self->monsterinfo.run (self); VectorSubtract (self->enemy->s.origin, self->s.origin, vec); self->ideal_yaw = vectoyaw (vec); // wait a while before first attack if (!(self->monsterinfo.aiflags & AI_STAND_GROUND)) AttackFinished (self, 1); } void FoundTarget (edict_t * self) { // let other monsters see this monster for a while if (self->enemy->client) { level.sight_entity = self; level.sight_entity_framenum = level.framenum; level.sight_entity->light_level = 128; } self->show_hostile = level.time + 1; // wake up other monsters VectorCopy (self->enemy->s.origin, self->monsterinfo.last_sighting); self->monsterinfo.trail_time = level.time; if (!self->combattarget) { HuntTarget (self); return; } self->goalentity = self->movetarget = G_PickTarget (self->combattarget); if (!self->movetarget) { self->goalentity = self->movetarget = self->enemy; HuntTarget (self); gi.dprintf ("%s at %s, combattarget %s not found\n", self->classname, vtos (self->s.origin), self->combattarget); return; } // clear out our combattarget, these are a one shot deal self->combattarget = NULL; self->monsterinfo.aiflags |= AI_COMBAT_POINT; // clear the targetname, that point is ours! self->movetarget->targetname = NULL; self->monsterinfo.pausetime = 0; // run for it self->monsterinfo.run (self); } /* =========== FindTarget Self is currently not attacking anything, so try to find a target Returns TRUE if an enemy was sighted When a player fires a missile, the point of impact becomes a fakeplayer so that monsters that see the impact will respond as if they had seen the player. To avoid spending too much time, only a single client (or fakeclient) is checked each frame. This means multi player games will have slightly slower noticing monsters. ============ */ qboolean FindTarget (edict_t * self) { edict_t *client; qboolean heardit; int r; if (self->monsterinfo.aiflags & AI_GOOD_GUY) { if (self->goalentity && self->goalentity->inuse && self->goalentity->classname) { if (strcmp (self->goalentity->classname, "target_actor") == 0) return false; } //FIXME look for monsters? return false; } // if we're going to a combat point, just proceed if (self->monsterinfo.aiflags & AI_COMBAT_POINT) return false; // if the first spawnflag bit is set, the monster will only wake up on // really seeing the player, not another monster getting angry or hearing // something // revised behavior so they will wake up if they "see" a player make a noise // but not weapon impact/explosion noises heardit = false; if ((level.sight_entity_framenum >= (level.framenum - 1)) && !(self->spawnflags & 1)) { client = level.sight_entity; if (client->enemy == self->enemy) { return false; } } else if (level.sound_entity_framenum >= (level.framenum - 1)) { client = level.sound_entity; heardit = true; } else if (!(self->enemy) && (level.sound2_entity_framenum >= (level.framenum - 1)) && !(self->spawnflags & 1)) { client = level.sound2_entity; heardit = true; } else { client = level.sight_client; if (!client) return false; // no clients to get mad at } // if the entity went away, forget it if (!client->inuse) return false; if (client == self->enemy) return true; // JDC false; if (client->client) { if (client->flags & FL_NOTARGET) return false; } else if (client->svflags & SVF_MONSTER) { if (!client->enemy) return false; if (client->enemy->flags & FL_NOTARGET) return false; } else if (heardit) { if (client->owner->flags & FL_NOTARGET) return false; } else return false; if (!heardit) { r = range (self, client); if (r == RANGE_FAR) return false; // this is where we would check invisibility // is client in an spot too dark to be seen? if (client->light_level <= 5) return false; if (!visible (self, client)) { return false; } if (r == RANGE_NEAR) { if (client->show_hostile < level.time && !infront (self, client)) { return false; } } else if (r == RANGE_MID) { if (!infront (self, client)) { return false; } } self->enemy = client; if (strcmp (self->enemy->classname, "player_noise") != 0) { self->monsterinfo.aiflags &= ~AI_SOUND_TARGET; if (!self->enemy->client) { self->enemy = self->enemy->enemy; if (!self->enemy->client) { self->enemy = NULL; return false; } } } } else // heardit { vec3_t temp; if (self->spawnflags & 1) { if (!visible (self, client)) return false; } else { if (!gi.inPHS (self->s.origin, client->s.origin)) return false; } VectorSubtract (client->s.origin, self->s.origin, temp); if (VectorLength (temp) > 1000) // too far to hear { return false; } // check area portals - if they are different and not connected then we can't hear it if (client->areanum != self->areanum) if (!gi.AreasConnected (self->areanum, client->areanum)) return false; self->ideal_yaw = vectoyaw (temp); M_ChangeYaw (self); // hunt the sound for a bit; hopefully find the real player self->monsterinfo.aiflags |= AI_SOUND_TARGET; self->enemy = client; } // // got one // FoundTarget (self); if (!(self->monsterinfo.aiflags & AI_SOUND_TARGET) && (self->monsterinfo.sight)) self->monsterinfo.sight (self, self->enemy); return true; } //============================================================================= /* ============ FacingIdeal ============ */ qboolean FacingIdeal (edict_t * self) { float delta; delta = anglemod (self->s.angles[YAW] - self->ideal_yaw); if (delta > 45 && delta < 315) return false; return true; } //============================================================================= qboolean M_CheckAttack (edict_t * self) { vec3_t spot1, spot2; float chance; trace_t tr; if (self->enemy->health > 0) { // see if any entities are in the way of the shot VectorCopy (self->s.origin, spot1); spot1[2] += self->viewheight; VectorCopy (self->enemy->s.origin, spot2); spot2[2] += self->enemy->viewheight; tr = gi.trace (spot1, NULL, NULL, spot2, self, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_SLIME | CONTENTS_LAVA | CONTENTS_WINDOW); // do we have a clear shot? if (tr.ent != self->enemy) return false; } // melee attack if (enemy_range == RANGE_MELEE) { // don't always melee in easy mode if (skill->value == 0 && (rand () & 3)) return false; if (self->monsterinfo.melee) self->monsterinfo.attack_state = AS_MELEE; else self->monsterinfo.attack_state = AS_MISSILE; return true; } // missile attack if (!self->monsterinfo.attack) return false; if (level.time < self->monsterinfo.attack_finished) return false; if (enemy_range == RANGE_FAR) return false; if (self->monsterinfo.aiflags & AI_STAND_GROUND) { chance = 0.4f; } else if (enemy_range == RANGE_MELEE) { chance = 0.2f; } else if (enemy_range == RANGE_NEAR) { chance = 0.1f; } else if (enemy_range == RANGE_MID) { chance = 0.02f; } else { return false; } if (skill->value == 0) chance *= 0.5f; else if (skill->value >= 2) chance *= 2; if (random () < chance) { self->monsterinfo.attack_state = AS_MISSILE; self->monsterinfo.attack_finished = level.time + 2 * random (); return true; } if (self->flags & FL_FLY) { if (random () < 0.3) self->monsterinfo.attack_state = AS_SLIDING; else self->monsterinfo.attack_state = AS_STRAIGHT; } return false; } /* ============= ai_run_melee Turn and close until within an angle to launch a melee attack ============= */ void ai_run_melee (edict_t * self) { self->ideal_yaw = enemy_yaw; M_ChangeYaw (self); if (FacingIdeal (self)) { self->monsterinfo.melee (self); self->monsterinfo.attack_state = AS_STRAIGHT; } } /* ============= ai_run_missile Turn in place until within an angle to launch a missile attack ============= */ void ai_run_missile (edict_t * self) { self->ideal_yaw = enemy_yaw; M_ChangeYaw (self); if (FacingIdeal (self)) { self->monsterinfo.attack (self); self->monsterinfo.attack_state = AS_STRAIGHT; } }; /* ============= ai_run_slide Strafe sideways, but stay at aproximately the same range ============= */ void ai_run_slide (edict_t * self, float distance) { float ofs; self->ideal_yaw = enemy_yaw; M_ChangeYaw (self); if (self->monsterinfo.lefty) ofs = 90; else ofs = -90; if (M_walkmove (self, self->ideal_yaw + ofs, distance)) return; self->monsterinfo.lefty = 1 - self->monsterinfo.lefty; M_walkmove (self, self->ideal_yaw - ofs, distance); } /* ============= ai_checkattack Decides if we're going to attack or do something else used by ai_run and ai_stand ============= */ qboolean ai_checkattack (edict_t * self, float dist) { vec3_t temp; qboolean hesDeadJim; // this causes monsters to run blindly to the combat point w/o firing if (self->goalentity) { if (self->monsterinfo.aiflags & AI_COMBAT_POINT) return false; if (self->monsterinfo.aiflags & AI_SOUND_TARGET) { if ((level.time - self->enemy->teleport_time) > 5.0) { // AQ:TNG JBravo fixing compiler warning with braces. if (self->goalentity == self->enemy) { if (self->movetarget) self->goalentity = self->movetarget; else self->goalentity = NULL; } // End warningfix. self->monsterinfo.aiflags &= ~AI_SOUND_TARGET; if (self->monsterinfo.aiflags & AI_TEMP_STAND_GROUND) self->monsterinfo.aiflags &= ~(AI_STAND_GROUND | AI_TEMP_STAND_GROUND); } else { self->show_hostile = level.time + 1; return false; } } } enemy_vis = false; // see if the enemy is dead hesDeadJim = false; if ((!self->enemy) || (!self->enemy->inuse)) { hesDeadJim = true; } else if (self->monsterinfo.aiflags & AI_MEDIC) { if (self->enemy->health > 0) { hesDeadJim = true; self->monsterinfo.aiflags &= ~AI_MEDIC; } } else { if (self->monsterinfo.aiflags & AI_BRUTAL) { if (self->enemy->health <= -80) hesDeadJim = true; } else { if (self->enemy->health <= 0) hesDeadJim = true; } } if (hesDeadJim) { self->enemy = NULL; // FIXME: look all around for other targets if (self->oldenemy && self->oldenemy->health > 0) { self->enemy = self->oldenemy; self->oldenemy = NULL; HuntTarget (self); } else { if (self->movetarget) { self->goalentity = self->movetarget; self->monsterinfo.walk (self); } else { // we need the pausetime otherwise the stand code // will just revert to walking with no target and // the monsters will wonder around aimlessly trying // to hunt the world entity self->monsterinfo.pausetime = level.time + 100000000; self->monsterinfo.stand (self); } return true; } } self->show_hostile = level.time + 1; // wake up other monsters // check knowledge of enemy enemy_vis = visible (self, self->enemy); if (enemy_vis) { self->monsterinfo.search_time = level.time + 5; VectorCopy (self->enemy->s.origin, self->monsterinfo.last_sighting); } // look for other coop players here // if (coop && self->monsterinfo.search_time < level.time) // { // if (FindTarget (self)) // return true; // } enemy_infront = infront (self, self->enemy); enemy_range = range (self, self->enemy); VectorSubtract (self->enemy->s.origin, self->s.origin, temp); enemy_yaw = vectoyaw (temp); // JDC self->ideal_yaw = enemy_yaw; if (self->monsterinfo.attack_state == AS_MISSILE) { ai_run_missile (self); return true; } if (self->monsterinfo.attack_state == AS_MELEE) { ai_run_melee (self); return true; } // if enemy is not currently visible, we will never attack if (!enemy_vis) return false; return self->monsterinfo.checkattack (self); } /* ============= ai_run The monster has an enemy it is trying to kill ============= */ void ai_run (edict_t * self, float dist) { vec3_t v; edict_t *tempgoal; edict_t *save; qboolean new; edict_t *marker; float d1, d2; trace_t tr; vec3_t v_forward, v_right; float left, center, right; vec3_t left_target, right_target; // if we're going to a combat point, just proceed if (self->monsterinfo.aiflags & AI_COMBAT_POINT) { M_MoveToGoal (self, dist); return; } if (self->monsterinfo.aiflags & AI_SOUND_TARGET) { VectorSubtract (self->s.origin, self->enemy->s.origin, v); if (VectorLength (v) < 64) { self->monsterinfo.aiflags |= (AI_STAND_GROUND | AI_TEMP_STAND_GROUND); self->monsterinfo.stand (self); return; } M_MoveToGoal (self, dist); if (!FindTarget (self)) return; } if (ai_checkattack (self, dist)) return; if (self->monsterinfo.attack_state == AS_SLIDING) { ai_run_slide (self, dist); return; } if (enemy_vis) { // if (self.aiflags & AI_LOST_SIGHT) // dprint("regained sight\n"); M_MoveToGoal (self, dist); self->monsterinfo.aiflags &= ~AI_LOST_SIGHT; VectorCopy (self->enemy->s.origin, self->monsterinfo.last_sighting); self->monsterinfo.trail_time = level.time; return; } // coop will change to another enemy if visible if (coop->value) { // FIXME: insane guys get mad with this, which causes crashes! if (FindTarget (self)) return; } if ((self->monsterinfo.search_time) && (level.time > (self->monsterinfo.search_time + 20))) { M_MoveToGoal (self, dist); self->monsterinfo.search_time = 0; // dprint("search timeout\n"); return; } save = self->goalentity; tempgoal = G_Spawn (); self->goalentity = tempgoal; new = false; if (!(self->monsterinfo.aiflags & AI_LOST_SIGHT)) { // just lost sight of the player, decide where to go first // dprint("lost sight of player, last seen at "); dprint(vtos(self.last_sighting)); dprint("\n"); self->monsterinfo.aiflags |= (AI_LOST_SIGHT | AI_PURSUIT_LAST_SEEN); self->monsterinfo.aiflags &= ~(AI_PURSUE_NEXT | AI_PURSUE_TEMP); new = true; } if (self->monsterinfo.aiflags & AI_PURSUE_NEXT) { self->monsterinfo.aiflags &= ~AI_PURSUE_NEXT; // dprint("reached current goal: "); dprint(vtos(self.origin)); dprint(" "); dprint(vtos(self.last_sighting)); dprint(" "); dprint(ftos(vlen(self.origin - self.last_sighting))); dprint("\n"); // give ourself more time since we got this far self->monsterinfo.search_time = level.time + 5; if (self->monsterinfo.aiflags & AI_PURSUE_TEMP) { // dprint("was temp goal; retrying original\n"); self->monsterinfo.aiflags &= ~AI_PURSUE_TEMP; marker = NULL; VectorCopy (self->monsterinfo.saved_goal, self->monsterinfo.last_sighting); new = true; } else if (self->monsterinfo.aiflags & AI_PURSUIT_LAST_SEEN) { self->monsterinfo.aiflags &= ~AI_PURSUIT_LAST_SEEN; marker = PlayerTrail_PickFirst (self); } else { marker = PlayerTrail_PickNext (self); } if (marker) { VectorCopy (marker->s.origin, self->monsterinfo.last_sighting); self->monsterinfo.trail_time = marker->timestamp; self->s.angles[YAW] = self->ideal_yaw = marker->s.angles[YAW]; // dprint("heading is "); dprint(ftos(self.ideal_yaw)); dprint("\n"); // debug_drawline(self.origin, self.last_sighting, 52); new = true; } } VectorSubtract (self->s.origin, self->monsterinfo.last_sighting, v); d1 = VectorLength (v); if (d1 <= dist) { self->monsterinfo.aiflags |= AI_PURSUE_NEXT; dist = d1; } VectorCopy (self->monsterinfo.last_sighting, self->goalentity->s.origin); if (new) { // gi.dprintf("checking for course correction\n"); tr = gi.trace (self->s.origin, self->mins, self->maxs, self->monsterinfo.last_sighting, self, MASK_PLAYERSOLID); if (tr.fraction < 1) { VectorSubtract (self->goalentity->s.origin, self->s.origin, v); d1 = VectorLength (v); center = tr.fraction; d2 = d1 * ((center + 1) / 2); self->s.angles[YAW] = self->ideal_yaw = vectoyaw (v); AngleVectors (self->s.angles, v_forward, v_right, NULL); VectorSet (v, d2, -16, 0); G_ProjectSource (self->s.origin, v, v_forward, v_right, left_target); tr = gi.trace (self->s.origin, self->mins, self->maxs, left_target, self, MASK_PLAYERSOLID); left = tr.fraction; VectorSet (v, d2, 16, 0); G_ProjectSource (self->s.origin, v, v_forward, v_right, right_target); tr = gi.trace (self->s.origin, self->mins, self->maxs, right_target, self, MASK_PLAYERSOLID); right = tr.fraction; center = (d1 * center) / d2; if (left >= center && left > right) { if (left < 1) { VectorSet (v, d2 * left * 0.5, -16, 0); G_ProjectSource (self->s.origin, v, v_forward, v_right, left_target); // gi.dprintf("incomplete path, go part way and adjust again\n"); } VectorCopy (self->monsterinfo.last_sighting, self->monsterinfo.saved_goal); self->monsterinfo.aiflags |= AI_PURSUE_TEMP; VectorCopy (left_target, self->goalentity->s.origin); VectorCopy (left_target, self->monsterinfo.last_sighting); VectorSubtract (self->goalentity->s.origin, self->s.origin, v); self->s.angles[YAW] = self->ideal_yaw = vectoyaw (v); // gi.dprintf("adjusted left\n"); // debug_drawline(self.origin, self.last_sighting, 152); } else if (right >= center && right > left) { if (right < 1) { VectorSet (v, d2 * right * 0.5, 16, 0); G_ProjectSource (self->s.origin, v, v_forward, v_right, right_target); // gi.dprintf("incomplete path, go part way and adjust again\n"); } VectorCopy (self->monsterinfo.last_sighting, self->monsterinfo.saved_goal); self->monsterinfo.aiflags |= AI_PURSUE_TEMP; VectorCopy (right_target, self->goalentity->s.origin); VectorCopy (right_target, self->monsterinfo.last_sighting); VectorSubtract (self->goalentity->s.origin, self->s.origin, v); self->s.angles[YAW] = self->ideal_yaw = vectoyaw (v); // gi.dprintf("adjusted right\n"); // debug_drawline(self.origin, self.last_sighting, 152); } } // else gi.dprintf("course was fine\n"); } M_MoveToGoal (self, dist); G_FreeEdict (tempgoal); if (self) self->goalentity = save; }
560
./aq2-tng/source/g_target.c
//----------------------------------------------------------------------------- // g_target.c // // $Id: g_target.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_target.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:31:44 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" /*QUAKED target_temp_entity (1 0 0) (-8 -8 -8) (8 8 8) Fire an origin based temp entity event to the clients. "style" type byte */ void Use_Target_Tent (edict_t * ent, edict_t * other, edict_t * activator) { gi.WriteByte (svc_temp_entity); gi.WriteByte (ent->style); gi.WritePosition (ent->s.origin); gi.multicast (ent->s.origin, MULTICAST_PVS); } void SP_target_temp_entity (edict_t * ent) { ent->use = Use_Target_Tent; } //========================================================== //========================================================== /*QUAKED target_speaker (1 0 0) (-8 -8 -8) (8 8 8) looped-on looped-off reliable "noise" wav file to play "attenuation" -1 = none, send to whole level 1 = normal fighting sounds 2 = idle sound level 3 = ambient sound level "volume" 0.0 to 1.0 Normal sounds play each time the target is used. The reliable flag can be set for crucial voiceovers. Looped sounds are always atten 3 / vol 1, and the use function toggles it on/off. Multiple identical looping sounds will just increase volume without any speed cost. */ void Use_Target_Speaker (edict_t * ent, edict_t * other, edict_t * activator) { int chan; if (ent->spawnflags & 3) { // looping sound toggles if (ent->s.sound) ent->s.sound = 0; // turn it off else ent->s.sound = ent->noise_index; // start it } else { // normal sound if (ent->spawnflags & 4) chan = CHAN_VOICE | CHAN_RELIABLE; else chan = CHAN_VOICE; // use a positioned_sound, because this entity won't normally be // sent to any clients because it is invisible gi.positioned_sound (ent->s.origin, ent, chan, ent->noise_index, ent->volume, ent->attenuation, 0); } } void SP_target_speaker (edict_t * ent) { char buffer[MAX_QPATH]; if (!st.noise) { gi.dprintf ("target_speaker with no noise set at %s\n", vtos (ent->s.origin)); return; } if (!strstr (st.noise, ".wav")) Com_sprintf (buffer, sizeof (buffer), "%s.wav", st.noise); else Q_strncpyz(buffer, st.noise, sizeof (buffer)); ent->noise_index = gi.soundindex (buffer); if (!ent->volume) ent->volume = 1.0; if (!ent->attenuation) ent->attenuation = 1.0; else if (ent->attenuation == -1) // use -1 so 0 defaults to 1 ent->attenuation = 0; // check for prestarted looping sound if (ent->spawnflags & 1) ent->s.sound = ent->noise_index; ent->use = Use_Target_Speaker; // must link the entity so we get areas and clusters so // the server can determine who to send updates to gi.linkentity (ent); } //========================================================== void Use_Target_Help (edict_t * ent, edict_t * other, edict_t * activator) { if (ent->spawnflags & 1) Q_strncpyz(game.helpmessage1, ent->message, sizeof (game.helpmessage2)); else Q_strncpyz(game.helpmessage2, ent->message, sizeof (game.helpmessage1)); game.helpchanged++; } /*QUAKED target_help (1 0 1) (-16 -16 -24) (16 16 24) help1 When fired, the "message" key becomes the current personal computer string, and the message light will be set on all clients status bars. */ void SP_target_help (edict_t * ent) { if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (ent); return; } if (!ent->message) { gi.dprintf ("%s with no message at %s\n", ent->classname, vtos (ent->s.origin)); G_FreeEdict (ent); return; } ent->use = Use_Target_Help; } //========================================================== /*QUAKED target_secret (1 0 1) (-8 -8 -8) (8 8 8) Counts a secret found. These are single use targets. */ void use_target_secret (edict_t * ent, edict_t * other, edict_t * activator) { gi.sound (ent, CHAN_VOICE, ent->noise_index, 1, ATTN_NORM, 0); level.found_secrets++; G_UseTargets (ent, activator); G_FreeEdict (ent); } void SP_target_secret (edict_t * ent) { if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (ent); return; } ent->use = use_target_secret; if (!st.noise) st.noise = "misc/secret.wav"; ent->noise_index = gi.soundindex (st.noise); ent->svflags = SVF_NOCLIENT; level.total_secrets++; // map bug hack if (!Q_stricmp (level.mapname, "mine3") && ent->s.origin[0] == 280 && ent->s.origin[1] == -2048 && ent->s.origin[2] == -624) ent->message = "You have found a secret area."; } //========================================================== /*QUAKED target_goal (1 0 1) (-8 -8 -8) (8 8 8) Counts a goal completed. These are single use targets. */ void use_target_goal (edict_t * ent, edict_t * other, edict_t * activator) { gi.sound (ent, CHAN_VOICE, ent->noise_index, 1, ATTN_NORM, 0); level.found_goals++; if (level.found_goals == level.total_goals) gi.configstring (CS_CDTRACK, "0"); G_UseTargets (ent, activator); G_FreeEdict (ent); } void SP_target_goal (edict_t * ent) { if (deathmatch->value) { // auto-remove for deathmatch G_FreeEdict (ent); return; } ent->use = use_target_goal; if (!st.noise) st.noise = "misc/secret.wav"; ent->noise_index = gi.soundindex (st.noise); ent->svflags = SVF_NOCLIENT; level.total_goals++; } //========================================================== /*QUAKED target_explosion (1 0 0) (-8 -8 -8) (8 8 8) Spawns an explosion temporary entity when used. "delay" wait this long before going off "dmg" how much radius damage should be done, defaults to 0 */ void target_explosion_explode (edict_t * self) { float save; gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_EXPLOSION1); gi.WritePosition (self->s.origin); gi.multicast (self->s.origin, MULTICAST_PHS); T_RadiusDamage (self, self->activator, self->dmg, NULL, self->dmg + 40, MOD_EXPLOSIVE); save = self->delay; self->delay = 0; G_UseTargets (self, self->activator); self->delay = save; } void use_target_explosion (edict_t * self, edict_t * other, edict_t * activator) { self->activator = activator; if (!self->delay) { target_explosion_explode (self); return; } self->think = target_explosion_explode; self->nextthink = level.time + self->delay; } void SP_target_explosion (edict_t * ent) { ent->use = use_target_explosion; ent->svflags = SVF_NOCLIENT; } //========================================================== /*QUAKED target_changelevel (1 0 0) (-8 -8 -8) (8 8 8) Changes level to "map" when fired */ void use_target_changelevel (edict_t * self, edict_t * other, edict_t * activator) { if (level.intermissiontime) return; // already activated if (!deathmatch->value && !coop->value) { if (g_edicts[1].health <= 0) return; } // if noexit, do a ton of damage to other if (deathmatch->value && !((int) dmflags->value & DF_ALLOW_EXIT) && other != world) { T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, 10 * other->max_health, 1000, 0, MOD_EXIT); return; } // if multiplayer, let everyone know who hit the exit if (deathmatch->value) { if (activator && activator->client) gi.bprintf (PRINT_HIGH, "%s exited the level.\n", activator->client->pers.netname); } // if going to a new unit, clear cross triggers if (strstr (self->map, "*")) game.serverflags &= ~(SFL_CROSS_TRIGGER_MASK); BeginIntermission (self); } void SP_target_changelevel (edict_t * ent) { if (!ent->map) { gi.dprintf ("target_changelevel with no map at %s\n", vtos (ent->s.origin)); G_FreeEdict (ent); return; } // ugly hack because *SOMEBODY* screwed up their map if ((Q_stricmp (level.mapname, "fact1") == 0) && (Q_stricmp (ent->map, "fact3") == 0)) ent->map = "fact3$secret1"; ent->use = use_target_changelevel; ent->svflags = SVF_NOCLIENT; } //========================================================== /*QUAKED target_splash (1 0 0) (-8 -8 -8) (8 8 8) Creates a particle splash effect when used. Set "sounds" to one of the following: 1) sparks 2) blue water 3) brown water 4) slime 5) lava 6) blood "count" how many pixels in the splash "dmg" if set, does a radius damage at this location when it splashes useful for lava/sparks */ void use_target_splash (edict_t * self, edict_t * other, edict_t * activator) { gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPLASH); gi.WriteByte (self->count); gi.WritePosition (self->s.origin); gi.WriteDir (self->movedir); gi.WriteByte (self->sounds); gi.multicast (self->s.origin, MULTICAST_PVS); if (self->dmg) T_RadiusDamage (self, activator, self->dmg, NULL, self->dmg + 40, MOD_SPLASH); } void SP_target_splash (edict_t * self) { self->use = use_target_splash; G_SetMovedir (self->s.angles, self->movedir); if (!self->count) self->count = 32; self->svflags = SVF_NOCLIENT; } //========================================================== /*QUAKED target_spawner (1 0 0) (-8 -8 -8) (8 8 8) Set target to the type of entity you want spawned. Useful for spawning monsters and gibs in the factory levels. For monsters: Set direction to the facing you want it to have. For gibs: Set direction if you want it moving and speed how fast it should be moving otherwise it will just be dropped */ void ED_CallSpawn (edict_t * ent); void use_target_spawner (edict_t * self, edict_t * other, edict_t * activator) { edict_t *ent; ent = G_Spawn (); ent->classname = self->target; VectorCopy (self->s.origin, ent->s.origin); VectorCopy (self->s.angles, ent->s.angles); ED_CallSpawn (ent); gi.unlinkentity (ent); KillBox (ent); gi.linkentity (ent); if (self->speed) VectorCopy (self->movedir, ent->velocity); } void SP_target_spawner (edict_t * self) { self->use = use_target_spawner; self->svflags = SVF_NOCLIENT; if (self->speed) { G_SetMovedir (self->s.angles, self->movedir); VectorScale (self->movedir, self->speed, self->movedir); } } //========================================================== /*QUAKED target_blaster (1 0 0) (-8 -8 -8) (8 8 8) NOTRAIL NOEFFECTS Fires a blaster bolt in the set direction when triggered. dmg default is 15 speed default is 1000 */ void use_target_blaster (edict_t * self, edict_t * other, edict_t * activator) { int effect; if (self->spawnflags & 2) effect = 0; else if (self->spawnflags & 1) effect = EF_HYPERBLASTER; else effect = EF_BLASTER; fire_blaster (self, self->s.origin, self->movedir, self->dmg, self->speed, EF_BLASTER, MOD_TARGET_BLASTER); gi.sound (self, CHAN_VOICE, self->noise_index, 1, ATTN_NORM, 0); } void SP_target_blaster (edict_t * self) { self->use = use_target_blaster; G_SetMovedir (self->s.angles, self->movedir); self->noise_index = gi.soundindex ("weapons/laser2.wav"); if (!self->dmg) self->dmg = 15; if (!self->speed) self->speed = 1000; self->svflags = SVF_NOCLIENT; } //========================================================== /*QUAKED target_crosslevel_trigger (.5 .5 .5) (-8 -8 -8) (8 8 8) trigger1 trigger2 trigger3 trigger4 trigger5 trigger6 trigger7 trigger8 Once this trigger is touched/used, any trigger_crosslevel_target with the same trigger number is automatically used when a level is started within the same unit. It is OK to check multiple triggers. Message, delay, target, and killtarget also work. */ void trigger_crosslevel_trigger_use (edict_t * self, edict_t * other, edict_t * activator) { game.serverflags |= self->spawnflags; G_FreeEdict (self); } void SP_target_crosslevel_trigger (edict_t * self) { self->svflags = SVF_NOCLIENT; self->use = trigger_crosslevel_trigger_use; } /*QUAKED target_crosslevel_target (.5 .5 .5) (-8 -8 -8) (8 8 8) trigger1 trigger2 trigger3 trigger4 trigger5 trigger6 trigger7 trigger8 Triggered by a trigger_crosslevel elsewhere within a unit. If multiple triggers are checked, all must be true. Delay, target and killtarget also work. "delay" delay before using targets if the trigger has been activated (default 1) */ void target_crosslevel_target_think (edict_t * self) { if (self->spawnflags == (game.serverflags & SFL_CROSS_TRIGGER_MASK & self->spawnflags)) { G_UseTargets (self, self); G_FreeEdict (self); } } void SP_target_crosslevel_target (edict_t * self) { if (!self->delay) self->delay = 1; self->svflags = SVF_NOCLIENT; self->think = target_crosslevel_target_think; self->nextthink = level.time + self->delay; } //========================================================== /*QUAKED target_laser (0 .5 .8) (-8 -8 -8) (8 8 8) START_ON RED GREEN BLUE YELLOW ORANGE FAT When triggered, fires a laser. You can either set a target or a direction. */ void target_laser_think (edict_t * self) { edict_t *ignore; vec3_t start; vec3_t end; trace_t tr; vec3_t point; vec3_t last_movedir; int count; if (self->spawnflags & 0x80000000) count = 8; else count = 4; if (self->enemy) { VectorCopy (self->movedir, last_movedir); VectorMA (self->enemy->absmin, 0.5, self->enemy->size, point); VectorSubtract (point, self->s.origin, self->movedir); VectorNormalize (self->movedir); if (!VectorCompare (self->movedir, last_movedir)) self->spawnflags |= 0x80000000; } ignore = self; VectorCopy (self->s.origin, start); VectorMA (start, 2048, self->movedir, end); while (1) { PRETRACE (); tr = gi.trace (start, NULL, NULL, end, ignore, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER); POSTTRACE (); if (!tr.ent) break; // hurt it if we can if ((tr.ent->takedamage) && !(tr.ent->flags & FL_IMMUNE_LASER)) T_Damage (tr.ent, self, self->activator, self->movedir, tr.endpos, vec3_origin, self->dmg, 1, DAMAGE_ENERGY, MOD_TARGET_LASER); // if we hit something that's not a monster or player or is immune to lasers, we're done if (!(tr.ent->svflags & SVF_MONSTER) && (!tr.ent->client)) { if (self->spawnflags & 0x80000000) { self->spawnflags &= ~0x80000000; gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_LASER_SPARKS); gi.WriteByte (count); gi.WritePosition (tr.endpos); gi.WriteDir (tr.plane.normal); gi.WriteByte (self->s.skinnum); gi.multicast (tr.endpos, MULTICAST_PVS); } break; } ignore = tr.ent; VectorCopy (tr.endpos, start); } VectorCopy (tr.endpos, self->s.old_origin); self->nextthink = level.time + FRAMETIME; } void target_laser_on (edict_t * self) { if (!self->activator) self->activator = self; self->spawnflags |= 0x80000001; self->svflags &= ~SVF_NOCLIENT; target_laser_think (self); } void target_laser_off (edict_t * self) { self->spawnflags &= ~1; self->svflags |= SVF_NOCLIENT; self->nextthink = 0; } void target_laser_use (edict_t * self, edict_t * other, edict_t * activator) { self->activator = activator; if (self->spawnflags & 1) target_laser_off (self); else target_laser_on (self); } void target_laser_start (edict_t * self) { edict_t *ent; self->movetype = MOVETYPE_NONE; self->solid = SOLID_NOT; self->s.renderfx |= RF_BEAM | RF_TRANSLUCENT; self->s.modelindex = 1; // must be non-zero // set the beam diameter if (self->spawnflags & 64) self->s.frame = 16; else self->s.frame = 4; // set the color if (self->spawnflags & 2) self->s.skinnum = 0xf2f2f0f0; else if (self->spawnflags & 4) self->s.skinnum = 0xd0d1d2d3; else if (self->spawnflags & 8) self->s.skinnum = 0xf3f3f1f1; else if (self->spawnflags & 16) self->s.skinnum = 0xdcdddedf; else if (self->spawnflags & 32) self->s.skinnum = 0xe0e1e2e3; if (!self->enemy) { if (self->target) { ent = G_Find (NULL, FOFS (targetname), self->target); if (!ent) gi.dprintf ("%s at %s: %s is a bad target\n", self->classname, vtos (self->s.origin), self->target); self->enemy = ent; } else { G_SetMovedir (self->s.angles, self->movedir); } } self->use = target_laser_use; self->think = target_laser_think; if (!self->dmg) self->dmg = 1; VectorSet (self->mins, -8, -8, -8); VectorSet (self->maxs, 8, 8, 8); gi.linkentity (self); if (self->spawnflags & 1) target_laser_on (self); else target_laser_off (self); } void SP_target_laser (edict_t * self) { // let everything else get spawned before we start firing self->think = target_laser_start; self->nextthink = level.time + 1; } //========================================================== /*QUAKED target_lightramp (0 .5 .8) (-8 -8 -8) (8 8 8) TOGGLE speed How many seconds the ramping will take message two letters; starting lightlevel and ending lightlevel */ void target_lightramp_think (edict_t * self) { char style[2]; style[0] = 'a' + self->movedir[0] + (level.time - self->timestamp) / FRAMETIME * self->movedir[2]; style[1] = 0; gi.configstring (CS_LIGHTS + self->enemy->style, style); if ((level.time - self->timestamp) < self->speed) { self->nextthink = level.time + FRAMETIME; } else if (self->spawnflags & 1) { char temp; temp = self->movedir[0]; self->movedir[0] = self->movedir[1]; self->movedir[1] = temp; self->movedir[2] *= -1; } } void target_lightramp_use (edict_t * self, edict_t * other, edict_t * activator) { if (!self->enemy) { edict_t *e; // check all the targets e = NULL; while (1) { e = G_Find (e, FOFS (targetname), self->target); if (!e) break; if (strcmp (e->classname, "light") != 0) { gi.dprintf ("%s at %s ", self->classname, vtos (self->s.origin)); gi.dprintf ("target %s (%s at %s) is not a light\n", self->target, e->classname, vtos (e->s.origin)); } else { self->enemy = e; } } if (!self->enemy) { gi.dprintf ("%s target %s not found at %s\n", self->classname, self->target, vtos (self->s.origin)); G_FreeEdict (self); return; } } self->timestamp = level.time; target_lightramp_think (self); } void SP_target_lightramp (edict_t * self) { if (!self->message || strlen (self->message) != 2 || self->message[0] < 'a' || self->message[0] > 'z' || self->message[1] < 'a' || self->message[1] > 'z' || self->message[0] == self->message[1]) { gi.dprintf ("target_lightramp has bad ramp (%s) at %s\n", self->message, vtos (self->s.origin)); G_FreeEdict (self); return; } if (deathmatch->value) { G_FreeEdict (self); return; } if (!self->target) { gi.dprintf ("%s with no target at %s\n", self->classname, vtos (self->s.origin)); G_FreeEdict (self); return; } self->svflags |= SVF_NOCLIENT; self->use = target_lightramp_use; self->think = target_lightramp_think; self->movedir[0] = self->message[0] - 'a'; self->movedir[1] = self->message[1] - 'a'; self->movedir[2] = (self->movedir[1] - self->movedir[0]) / (self->speed / FRAMETIME); } //========================================================== /*QUAKED target_earthquake (1 0 0) (-8 -8 -8) (8 8 8) When triggered, this initiates a level-wide earthquake. All players and monsters are affected. "speed" severity of the quake (default:200) "count" duration of the quake (default:5) */ void target_earthquake_think (edict_t * self) { int i; edict_t *e; if (self->last_move_time < level.time) { gi.positioned_sound (self->s.origin, self, CHAN_AUTO, self->noise_index, 1.0, ATTN_NONE, 0); self->last_move_time = level.time + 0.5; } for (i = 1, e = g_edicts + i; i < globals.num_edicts; i++, e++) { if (!e->inuse) continue; if (!e->client) continue; if (!e->groundentity) continue; e->groundentity = NULL; e->velocity[0] += crandom () * 150; e->velocity[1] += crandom () * 150; e->velocity[2] = self->speed * (100.0 / e->mass); } if (level.time < self->timestamp) self->nextthink = level.time + FRAMETIME; } void target_earthquake_use (edict_t * self, edict_t * other, edict_t * activator) { self->timestamp = level.time + self->count; self->nextthink = level.time + FRAMETIME; self->activator = activator; self->last_move_time = 0; } void SP_target_earthquake (edict_t * self) { if (!self->targetname) gi.dprintf ("untargeted %s at %s\n", self->classname, vtos (self->s.origin)); if (!self->count) self->count = 5; if (!self->speed) self->speed = 200; self->svflags |= SVF_NOCLIENT; self->think = target_earthquake_think; self->use = target_earthquake_use; self->noise_index = gi.soundindex ("world/quake.wav"); }
561
./aq2-tng/source/a_menu.c
//----------------------------------------------------------------------------- // Action (formerly Axshun) menu code // This is directly from Zoid's CTF code. Thanks to Zoid again. // -Fireblade // // $Id: a_menu.c,v 1.1.1.1 2001/05/06 17:24:26 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: a_menu.c,v $ // Revision 1.1.1.1 2001/05/06 17:24:26 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" void PMenu_Open (edict_t * ent, pmenu_t * entries, int cur, int num) { pmenuhnd_t *hnd; pmenu_t *p; int i; if (!ent->client) return; if (ent->client->menu) { gi.dprintf ("warning, ent already has a menu\n"); PMenu_Close (ent); } hnd = gi.TagMalloc (sizeof (*hnd), TAG_GAME); hnd->entries = entries; hnd->num = num; if (cur < 0 || !entries[cur].SelectFunc) { for (i = 0, p = entries; i < num; i++, p++) if (p->SelectFunc) break; } else i = cur; if (i >= num) hnd->cur = -1; else hnd->cur = i; ent->client->showscores = true; ent->client->inmenu = true; ent->client->menu = hnd; PMenu_Update (ent); gi.unicast (ent, true); } void PMenu_Close (edict_t * ent) { if (!ent->client->menu) return; gi.TagFree (ent->client->menu); ent->client->menu = NULL; ent->client->showscores = false; } void PMenu_Update (edict_t * ent) { char string[1024]; int i, len; pmenu_t *p; int x; pmenuhnd_t *hnd; char *t; qboolean alt = false; if (!ent->client->menu) { gi.dprintf ("warning: ent has no menu\n"); return; } hnd = ent->client->menu; strcpy (string, "xv 32 yv 8 "); len = strlen(string); for (i = 0, p = hnd->entries; i < hnd->num; i++, p++) { if (!p->text || !*(p->text)) continue; // blank line alt = false; t = p->text; if (*t == '*') { alt = true; t++; } if (p->align == PMENU_ALIGN_CENTER) x = 196 / 2 - strlen (t) * 4 + 64; else if (p->align == PMENU_ALIGN_RIGHT) x = 64 + (196 - strlen (t) * 8); else x = 64; Com_sprintf (string + len, sizeof(string)-len, "yv %d xv %d ", 32 + i * 8, x - ((hnd->cur == i) ? 8 : 0)); len = strlen(string); if (hnd->cur == i) Com_sprintf (string + len, sizeof(string)-len, "string2 \"\x0d%s\" ", t); else if (alt) Com_sprintf (string + len, sizeof(string)-len, "string2 \"%s\" ", t); else Com_sprintf (string + len, sizeof(string)-len, "string \"%s\" ", t); len = strlen(string); if(len >= sizeof(string)-1) break; } gi.WriteByte (svc_layout); gi.WriteString (string); } void PMenu_Next (edict_t * ent) { pmenuhnd_t *hnd; int i; pmenu_t *p; if (!ent->client->menu) { gi.dprintf ("warning: ent has no menu\n"); return; } hnd = ent->client->menu; if (hnd->cur < 0) return; // no selectable entries i = hnd->cur; p = hnd->entries + hnd->cur; do { i++, p++; if (i == hnd->num) i = 0, p = hnd->entries; if (p->SelectFunc) break; } while (i != hnd->cur); hnd->cur = i; PMenu_Update (ent); gi.unicast (ent, true); } void PMenu_Prev (edict_t * ent) { pmenuhnd_t *hnd; int i; pmenu_t *p; if (!ent->client->menu) { gi.dprintf ("warning: ent has no menu\n"); return; } hnd = ent->client->menu; if (hnd->cur < 0) return; // no selectable entries i = hnd->cur; p = hnd->entries + hnd->cur; do { if (i == 0) { i = hnd->num - 1; p = hnd->entries + i; } else i--, p--; if (p->SelectFunc) break; } while (i != hnd->cur); hnd->cur = i; PMenu_Update (ent); gi.unicast (ent, true); } void PMenu_Select (edict_t * ent) { pmenuhnd_t *hnd; pmenu_t *p; if (!ent->client->menu) { gi.dprintf ("warning: ent has no menu\n"); return; } hnd = ent->client->menu; if (hnd->cur < 0) return; // no selectable entries p = hnd->entries + hnd->cur; if (p->SelectFunc) p->SelectFunc (ent, p); }
562
./aq2-tng/source/tng_ini.c
#include "g_local.h" #define MAX_INI_STR_LEN 128 #define MAX_INI_SIZE 1024L char *INI_Find(FILE *fh, const char *section, const char *key) { long fsize; char _ini_file[MAX_INI_SIZE]; static char _ini_ret[MAX_INI_STR_LEN]; char *line, *value; char cur_section[MAX_INI_STR_LEN]; memset(&_ini_ret, 0, MAX_INI_STR_LEN); memset(&cur_section, 0, MAX_INI_STR_LEN); memset(&_ini_file, 0, MAX_INI_SIZE); if(!fh) { gi.bprintf(PRINT_HIGH, "INI_Find: file handle for INI_Find was NULL\n"); return NULL; } fseek(fh, 0, SEEK_END); fsize = ftell(fh); rewind(fh); if(fsize > MAX_INI_SIZE) { gi.bprintf(PRINT_HIGH, "INI_Find: max file size is %ld, file to be read is %ld!\n", MAX_INI_SIZE, fsize); return NULL; } if(fread(&_ini_file, fsize, 1, fh) < 1) { gi.bprintf(PRINT_HIGH, "INI_Find: read failed: %d\n", ferror(fh)); return NULL; } line = strtok(_ini_file, "\n"); do { if(strlen(line) > 2 && line[0] != ';') { // remove DOS line endings if(line[strlen(line)-1] == 0x0D) line[strlen(line)-1] = 0x00; if(line[0] == '[' && line[strlen(line)-1] == ']') { memset(&cur_section, 0, MAX_INI_STR_LEN); strncpy(cur_section, line+1, strlen(line)-2); } else { value = strstr(line, "="); if(!value || value == line) { gi.bprintf(PRINT_HIGH, "INI_Find: invalid key/value pair: \"%s\"\n", line); } else { *value = 0; // null the delimeter, now line points to key and value+1 to value value++; /* this handles NULL (empty) section properly */ if(section == NULL || section[0] == 0) { if(cur_section[0] == 0 && strcmp(line, key) == 0) { strncpy(_ini_ret, value, MAX_INI_STR_LEN); return _ini_ret; } } else if(strcmp(section, cur_section) == 0 && strcmp(line, key) == 0) { strncpy(_ini_ret, value, MAX_INI_STR_LEN); return _ini_ret; } } } } line = strtok(NULL, "\n"); } while(line != NULL); return NULL; }
563
./aq2-tng/source/p_trail.c
//----------------------------------------------------------------------------- // p_trail.c // // $Id: p_trail.c,v 1.2 2001/09/28 13:48:35 ra Exp $ // //----------------------------------------------------------------------------- // $Log: p_trail.c,v $ // Revision 1.2 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:25:35 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" /* ============================================================================== PLAYER TRAIL ============================================================================== This is a circular list containing the a list of points of where the player has been recently. It is used by monsters for pursuit. .origin the spot .owner forward link .aiment backward link */ #define TRAIL_LENGTH 8 edict_t *trail[TRAIL_LENGTH]; int trail_head; qboolean trail_active = false; #define NEXT(n) (((n) + 1) & (TRAIL_LENGTH - 1)) #define PREV(n) (((n) - 1) & (TRAIL_LENGTH - 1)) void PlayerTrail_Init (void) { int n; if (deathmatch->value /* FIXME || coop */ ) return; for (n = 0; n < TRAIL_LENGTH; n++) { trail[n] = G_Spawn (); trail[n]->classname = "player_trail"; } trail_head = 0; trail_active = true; } void PlayerTrail_Add (vec3_t spot) { vec3_t temp; if (!trail_active) return; VectorCopy (spot, trail[trail_head]->s.origin); trail[trail_head]->timestamp = level.time; VectorSubtract (spot, trail[PREV (trail_head)]->s.origin, temp); trail[trail_head]->s.angles[1] = vectoyaw (temp); trail_head = NEXT (trail_head); } void PlayerTrail_New (vec3_t spot) { if (!trail_active) return; PlayerTrail_Init (); PlayerTrail_Add (spot); } edict_t * PlayerTrail_PickFirst (edict_t * self) { int marker; int n; if (!trail_active) return NULL; for (marker = trail_head, n = TRAIL_LENGTH; n; n--) { if (trail[marker]->timestamp <= self->monsterinfo.trail_time) marker = NEXT (marker); else break; } if (visible (self, trail[marker])) { return trail[marker]; } if (visible (self, trail[PREV (marker)])) { return trail[PREV (marker)]; } return trail[marker]; } edict_t * PlayerTrail_PickNext (edict_t * self) { int marker; int n; if (!trail_active) return NULL; for (marker = trail_head, n = TRAIL_LENGTH; n; n--) { if (trail[marker]->timestamp <= self->monsterinfo.trail_time) marker = NEXT (marker); else break; } return trail[marker]; } edict_t * PlayerTrail_LastSpot (void) { return trail[PREV (trail_head)]; }
564
./aq2-tng/source/p_hud.c
//----------------------------------------------------------------------------- // p_hud.c // // $Id: p_hud.c,v 1.8 2002/01/24 02:24:56 deathwatch Exp $ // //----------------------------------------------------------------------------- // $Log: p_hud.c,v $ // Revision 1.8 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.7 2002/01/02 01:18:24 deathwatch // Showing health icon when bandaging (thanks to Dome for submitting this code) // // Revision 1.6 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.5 2001/08/20 00:41:15 slicerdw // Added a new scoreboard for Teamplay with stats ( when map ends ) // // Revision 1.4 2001/07/16 19:02:06 ra // Fixed compilerwarnings (-g -Wall). Only one remains. // // Revision 1.3 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.2.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.2.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.2.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.2 2001/05/11 16:07:26 mort // Various CTF bits and pieces... // // Revision 1.1.1.1 2001/05/06 17:25:15 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" /* ====================================================================== INTERMISSION ====================================================================== */ void MoveClientToIntermission (edict_t * ent) { if (deathmatch->value || coop->value) { ent->client->showscores = true; ent->client->scoreboardnum = 1; } VectorCopy (level.intermission_origin, ent->s.origin); ent->client->ps.pmove.origin[0] = level.intermission_origin[0] * 8; ent->client->ps.pmove.origin[1] = level.intermission_origin[1] * 8; ent->client->ps.pmove.origin[2] = level.intermission_origin[2] * 8; VectorCopy (level.intermission_angle, ent->client->ps.viewangles); ent->client->ps.pmove.pm_type = PM_FREEZE; ent->client->ps.gunindex = 0; ent->client->ps.blend[3] = 0; ent->client->ps.rdflags &= ~RDF_UNDERWATER; // clean up powerup info ent->client->quad_framenum = 0; ent->client->invincible_framenum = 0; ent->client->breather_framenum = 0; ent->client->enviro_framenum = 0; ent->client->grenade_blew_up = false; ent->client->grenade_time = 0; ent->viewheight = 0; ent->s.modelindex = 0; ent->s.modelindex2 = 0; ent->s.modelindex3 = 0; ent->s.modelindex = 0; ent->s.effects = 0; ent->s.sound = 0; ent->solid = SOLID_NOT; //FIREBLADE ent->client->resp.sniper_mode = SNIPER_1X; ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->ps.stats[STAT_SNIPER_ICON] = 0; //FIREBLADE // add the layout if (deathmatch->value || coop->value) { DeathmatchScoreboardMessage (ent, NULL); gi.unicast (ent, true); } } void BeginIntermission (edict_t * targ) { int i, n; edict_t *ent, *client; if (level.intermissiontime) return; // already activated //FIREBLADE if (ctf->value) CTFCalcScores (); else if (teamplay->value) TallyEndOfLevelTeamScores (); //FIREBLADE game.autosaved = false; // respawn any dead clients for (i = 0; i < maxclients->value; i++) { client = g_edicts + 1 + i; if (!client->inuse) continue; if (client->health <= 0) respawn (client); } level.intermissiontime = level.time; level.changemap = targ->map; if (strchr(level.changemap, '*')) { if (coop->value) { for (i = 0; i < maxclients->value; i++) { client = g_edicts + 1 + i; if (!client->inuse) continue; // strip players of all keys between units for (n = 0; n < MAX_ITEMS; n++) { if (itemlist[n].flags & IT_KEY) client->client->pers.inventory[n] = 0; } } } } else { if (!deathmatch->value) { level.exitintermission = 1; // go immediately to the next level return; } } level.exitintermission = 0; // find an intermission spot ent = G_Find (NULL, FOFS (classname), "info_player_intermission"); if (!ent) { // the map creator forgot to put in an intermission point... ent = G_Find (NULL, FOFS (classname), "info_player_start"); if (!ent) ent = G_Find (NULL, FOFS (classname), "info_player_deathmatch"); } else { // chose one of four spots i = rand () & 3; while (i--) { ent = G_Find (ent, FOFS (classname), "info_player_intermission"); if (!ent) // wrap around the list ent = G_Find (ent, FOFS (classname), "info_player_intermission"); } } VectorCopy (ent->s.origin, level.intermission_origin); VectorCopy (ent->s.angles, level.intermission_angle); // move all clients to the intermission point for (i = 0; i < maxclients->value; i++) { client = g_edicts + 1 + i; if (!client->inuse) continue; MoveClientToIntermission (client); } // AZEROV: Clear the team kills for everyone //gi.cprintf(NULL,PRINT_MEDIUM,"Resetting all team kills\n"); for (i = 1; i <= maxclients->value; i++) { edict_t *temp_ent; temp_ent = g_edicts + i; if (!temp_ent->inuse || !temp_ent->client) { continue; } temp_ent->client->team_wounds = 0; temp_ent->client->team_kills = 0; } // AZEROV } void A_ScoreboardMessage (edict_t * ent, edict_t * killer); /* ================== DeathmatchScoreboardMessage ================== */ void DeathmatchScoreboardMessage (edict_t * ent, edict_t * killer) { char entry[128]; char string[1024]; int stringlength; int i, j, k; int sorted[MAX_CLIENTS]; int sortedscores[MAX_CLIENTS]; int score, total; int picnum; int x, y; gclient_t *cl; edict_t *cl_ent; char *tag; //FIREBLADE if (teamplay->value && !use_tourney->value) { // DW: If the map ends if (level.intermissiontime) { if(stats_endmap->value && !teamdm->value && !ctf->value) // And we are to show the stats screen A_ScoreboardEndLevel (ent, killer); // do it else // otherwise A_ScoreboardMessage (ent, killer); // show the original } else A_ScoreboardMessage (ent, killer); return; } //FIREBLADE // sort the clients by score total = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; score = game.clients[i].resp.score; for (j = 0; j < total; j++) { if (score > sortedscores[j]) break; } for (k = total; k > j; k--) { sorted[k] = sorted[k - 1]; sortedscores[k] = sortedscores[k - 1]; } sorted[j] = i; sortedscores[j] = score; total++; } // print level name and exit rules string[0] = 0; stringlength = 0; // add the clients in sorted order if (total > 12) total = 12; for (i = 0; i < total; i++) { cl = &game.clients[sorted[i]]; cl_ent = g_edicts + 1 + sorted[i]; picnum = gi.imageindex ("i_fixme"); x = (i >= 6) ? 160 : 0; y = 32 + 32 * (i % 6); // add a dogtag if (cl_ent == ent) tag = "tag1"; else if (cl_ent == killer) tag = "tag2"; else tag = NULL; if (tag) { Com_sprintf (entry, sizeof (entry), "xv %i yv %i picn %s ", x + 32, y, tag); j = strlen (entry); if (stringlength + j > 1023) break; strcpy (string + stringlength, entry); stringlength += j; } // send the layout Com_sprintf (entry, sizeof (entry), "client %i %i %i %i %i %i ", x, y, sorted[i], cl->resp.score, cl->ping, (level.framenum - cl->resp.enterframe) / 600); j = strlen (entry); if (stringlength + j > 1023) break; strcpy (string + stringlength, entry); stringlength += j; } gi.WriteByte (svc_layout); gi.WriteString (string); } /* ================== DeathmatchScoreboard Draw instead of help message. Note that it isn't that hard to overflow the 1400 byte message limit! ================== */ void DeathmatchScoreboard (edict_t * ent) { DeathmatchScoreboardMessage (ent, ent->enemy); gi.unicast (ent, true); } /* ================== Cmd_Score_f Display the scoreboard ================== */ void Cmd_Score_f (edict_t * ent) { ent->client->showinventory = false; ent->client->showhelp = false; //FIREBLADE if (ent->client->menu) PMenu_Close (ent); //FIREBLADE if (!deathmatch->value && !coop->value) return; if (ent->client->showscores) { //FIREBLADE if (teamplay->value && ent->client->scoreboardnum < 2) // toggle scoreboards... { ent->client->scoreboardnum++; DeathmatchScoreboard (ent); return; } //FIREBLADE ent->client->showscores = false; return; } ent->client->showscores = true; //FIREBLADE ent->client->scoreboardnum = 1; //FIREBLADE DeathmatchScoreboard (ent); } /* ================== HelpComputer Draw help computer. ================== */ void HelpComputer (edict_t * ent) { char string[1024]; char *sk; if (skill->value == 0) sk = "easy"; else if (skill->value == 1) sk = "medium"; else if (skill->value == 2) sk = "hard"; else sk = "hard+"; // send the layout Com_sprintf (string, sizeof (string), "xv 32 yv 8 picn help " // background "xv 202 yv 12 string2 \"%s\" " // skill "xv 0 yv 24 cstring2 \"%s\" " // level name "xv 0 yv 54 cstring2 \"%s\" " // help 1 "xv 0 yv 110 cstring2 \"%s\" " // help 2 "xv 50 yv 164 string2 \" kills goals secrets\" " "xv 50 yv 172 string2 \"%3i/%3i %i/%i %i/%i\" ", sk, level.level_name, game.helpmessage1, game.helpmessage2, level.killed_monsters, level.total_monsters, level.found_goals, level.total_goals, level.found_secrets, level.total_secrets); gi.WriteByte (svc_layout); gi.WriteString (string); gi.unicast (ent, true); } /* ================== Cmd_Help_f Display the current help message ================== */ void Cmd_Help_f (edict_t * ent) { // this is for backwards compatability if (deathmatch->value) { Cmd_Score_f (ent); return; } ent->client->showinventory = false; ent->client->showscores = false; if (ent->client->showhelp && (ent->client->resp.game_helpchanged == game.helpchanged)) { ent->client->showhelp = false; return; } ent->client->showhelp = true; ent->client->resp.helpchanged = 0; HelpComputer (ent); } //======================================================================= /* =============== G_SetStats Rearranged for chase cam support -FB =============== */ void G_SetStats (edict_t * ent) { gitem_t *item; // AQ:TNG - JBravo fixing compilerwarnings. // Another one Im not 100% sure about... int cells = 0; int index; // JBravo. int power_armor_type; if (!ent->client->chase_mode) { // // health // ent->client->ps.stats[STAT_HEALTH_ICON] = level.pic_health; ent->client->ps.stats[STAT_HEALTH] = ent->health; // // ammo (now clips really) // // zucc modified this to do clips instead if (!ent->client-> ammo_index /* || !ent->client->pers.inventory[ent->client->ammo_index] */ ) { ent->client->ps.stats[STAT_CLIP_ICON] = 0; ent->client->ps.stats[STAT_CLIP] = 0; } else { item = &itemlist[ent->client->ammo_index]; ent->client->ps.stats[STAT_CLIP_ICON] = gi.imageindex (item->icon); ent->client->ps.stats[STAT_CLIP] = ent->client->pers.inventory[ent->client->ammo_index]; } // zucc display special item and special weapon if (INV_AMMO(ent, SNIPER_NUM)) ent->client->ps.stats[STAT_WEAPONS_ICON] = gi.imageindex(GET_ITEM(SNIPER_NUM)->icon); else if (INV_AMMO(ent, M4_NUM)) ent->client->ps.stats[STAT_WEAPONS_ICON] = gi.imageindex(GET_ITEM(M4_NUM)->icon); else if (INV_AMMO(ent, MP5_NUM)) ent->client->ps.stats[STAT_WEAPONS_ICON] = gi.imageindex(GET_ITEM(MP5_NUM)->icon); else if (INV_AMMO(ent, M3_NUM)) ent->client->ps.stats[STAT_WEAPONS_ICON] = gi.imageindex(GET_ITEM(M3_NUM)->icon); else if (INV_AMMO(ent, HC_NUM)) ent->client->ps.stats[STAT_WEAPONS_ICON] = gi.imageindex(GET_ITEM(HC_NUM)->icon); else ent->client->ps.stats[STAT_WEAPONS_ICON] = 0; if (INV_AMMO(ent, KEV_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(KEV_NUM)->icon); else if (INV_AMMO(ent, LASER_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(LASER_NUM)->icon); else if (INV_AMMO(ent, SLIP_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(SLIP_NUM)->icon); else if (INV_AMMO(ent, SIL_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(SIL_NUM)->icon); else if (INV_AMMO(ent, HELM_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(HELM_NUM)->icon); else if (INV_AMMO(ent, BAND_NUM)) ent->client->ps.stats[STAT_ITEMS_ICON] = gi.imageindex (GET_ITEM(BAND_NUM)->icon); else ent->client->ps.stats[STAT_ITEMS_ICON] = 0; // grenades remaining if (INV_AMMO(ent, GRENADE_NUM)) { ent->client->ps.stats[STAT_GRENADE_ICON] = gi.imageindex ("a_m61frag"); ent->client->ps.stats[STAT_GRENADES] = INV_AMMO(ent, GRENADE_NUM); } else { ent->client->ps.stats[STAT_GRENADE_ICON] = 0; } // // ammo by weapon // // if (ent->client->pers.weapon) { switch (ent->client->curr_weap) { case MK23_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_bullets"); ent->client->ps.stats[STAT_AMMO] = ent->client->mk23_rds; break; case MP5_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_bullets"); ent->client->ps.stats[STAT_AMMO] = ent->client->mp5_rds; break; case M4_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_bullets"); ent->client->ps.stats[STAT_AMMO] = ent->client->m4_rds; break; case M3_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_shells"); ent->client->ps.stats[STAT_AMMO] = ent->client->shot_rds; break; case HC_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_shells"); ent->client->ps.stats[STAT_AMMO] = ent->client->cannon_rds; break; case SNIPER_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_bullets"); ent->client->ps.stats[STAT_AMMO] = ent->client->sniper_rds; break; case DUAL_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_bullets"); ent->client->ps.stats[STAT_AMMO] = ent->client->dual_rds; break; case KNIFE_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("w_knife"); ent->client->ps.stats[STAT_AMMO] = INV_AMMO(ent, KNIFE_NUM); break; case GRENADE_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = gi.imageindex("a_m61frag"); ent->client->ps.stats[STAT_AMMO] = INV_AMMO(ent, GRENADE_NUM); break; case GRAPPLE_NUM: ent->client->ps.stats[STAT_AMMO_ICON] = 0; ent->client->ps.stats[STAT_AMMO] = 0; break; default: gi.dprintf ("Failed to find weapon/icon for hud.\n"); break; } } // // sniper mode icons // //if ( ent->client->sniper_mode ) // gi.cprintf (ent, PRINT_HIGH, "Sniper Zoom set at %d.\n", ent->client->sniper_mode); if (ent->client->resp.sniper_mode == SNIPER_1X || ent->client->weaponstate == WEAPON_RELOADING || ent->client->weaponstate == WEAPON_BUSY || ent->client->no_sniper_display) ent->client->ps.stats[STAT_SNIPER_ICON] = 0; else if (ent->client->resp.sniper_mode == SNIPER_2X) ent->client->ps.stats[STAT_SNIPER_ICON] = gi.imageindex ("scope2x"); else if (ent->client->resp.sniper_mode == SNIPER_4X) ent->client->ps.stats[STAT_SNIPER_ICON] = gi.imageindex ("scope4x"); else if (ent->client->resp.sniper_mode == SNIPER_6X) ent->client->ps.stats[STAT_SNIPER_ICON] = gi.imageindex ("scope6x"); // // armor // power_armor_type = PowerArmorType (ent); if (power_armor_type) { cells = ent->client->pers.inventory[ITEM_INDEX (FindItem ("cells"))]; if (cells == 0) { // ran out of cells for power armor ent->flags &= ~FL_POWER_ARMOR; gi.sound (ent, CHAN_ITEM, gi.soundindex ("misc/power2.wav"), 1, ATTN_NORM, 0); power_armor_type = 0;; } } index = ArmorIndex (ent); if (power_armor_type && (!index || (level.framenum & 8))) { // flash between power armor and other armor icon ent->client->ps.stats[STAT_ARMOR_ICON] = gi.imageindex ("i_powershield"); ent->client->ps.stats[STAT_ARMOR] = cells; } else if (index) { item = GetItemByIndex (index); ent->client->ps.stats[STAT_ARMOR_ICON] = gi.imageindex (item->icon); ent->client->ps.stats[STAT_ARMOR] = ent->client->pers.inventory[index]; } else { ent->client->ps.stats[STAT_ARMOR_ICON] = 0; ent->client->ps.stats[STAT_ARMOR] = 0; } // // pickup message // if (level.time > ent->client->pickup_msg_time) { ent->client->ps.stats[STAT_PICKUP_ICON] = 0; ent->client->ps.stats[STAT_PICKUP_STRING] = 0; } // // timers // if (ent->client->quad_framenum > level.framenum) { ent->client->ps.stats[STAT_TIMER_ICON] = gi.imageindex ("p_quad"); ent->client->ps.stats[STAT_TIMER] = (ent->client->quad_framenum - level.framenum) / 10; } else if (ent->client->invincible_framenum > level.framenum) { ent->client->ps.stats[STAT_TIMER_ICON] = gi.imageindex ("p_invulnerability"); ent->client->ps.stats[STAT_TIMER] = (ent->client->invincible_framenum - level.framenum) / 10; } else if (ent->client->enviro_framenum > level.framenum) { ent->client->ps.stats[STAT_TIMER_ICON] = gi.imageindex ("p_envirosuit"); ent->client->ps.stats[STAT_TIMER] = (ent->client->enviro_framenum - level.framenum) / 10; } else if (ent->client->breather_framenum > level.framenum) { ent->client->ps.stats[STAT_TIMER_ICON] = gi.imageindex ("p_rebreather"); ent->client->ps.stats[STAT_TIMER] = (ent->client->breather_framenum - level.framenum) / 10; } else { ent->client->ps.stats[STAT_TIMER_ICON] = 0; ent->client->ps.stats[STAT_TIMER] = 0; } // // selected item // if (ent->client->pers.selected_item == -1) ent->client->ps.stats[STAT_SELECTED_ICON] = 0; else ent->client->ps.stats[STAT_SELECTED_ICON] = gi.imageindex (itemlist[ent->client->pers.selected_item].icon); ent->client->ps.stats[STAT_SELECTED_ITEM] = ent->client->pers.selected_item; // // frags // ent->client->ps.stats[STAT_FRAGS] = ent->client->resp.score; // // help icon / current weapon if not shown // if (ent->client->resp.helpchanged && (level.framenum & 8)) ent->client->ps.stats[STAT_HELPICON] = gi.imageindex ("i_help"); else if ((ent->client->pers.hand == CENTER_HANDED || ent->client->ps.fov > 91) && ent->client->pers.weapon) ent->client->ps.stats[STAT_HELPICON] = gi.imageindex (ent->client->pers.weapon->icon); else ent->client->ps.stats[STAT_HELPICON] = 0; } // TNG: Show health icon when bandaging (thanks to Dome for this code) if (ent->client->weaponstate == WEAPON_BANDAGING || ent->client->bandaging || ent->client->bandage_stopped) { ent->client->ps.stats[STAT_HELPICON] = gi.imageindex ("i_health"); } // // layouts // ent->client->ps.stats[STAT_LAYOUTS] = 0; if (deathmatch->value) { if (ent->client->pers.health <= 0 || level.intermissiontime || ent->client->showscores) ent->client->ps.stats[STAT_LAYOUTS] |= 1; if (ent->client->showinventory && ent->client->pers.health > 0) ent->client->ps.stats[STAT_LAYOUTS] |= 2; } else { if (ent->client->showscores || ent->client->showhelp) ent->client->ps.stats[STAT_LAYOUTS] |= 1; if (ent->client->showinventory && ent->client->pers.health > 0) ent->client->ps.stats[STAT_LAYOUTS] |= 2; } SetIDView (ent); //FIREBLADE if (ctf->value) SetCTFStats (ent); else if (teamplay->value) A_Scoreboard (ent); //FIREBLADE }
565
./aq2-tng/source/tng_stats.c
//----------------------------------------------------------------------------- // Statistics Related Code // // $Id: tng_stats.c,v 1.33 2004/05/18 20:35:45 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: tng_stats.c,v $ // Revision 1.33 2004/05/18 20:35:45 slicerdw // Fixed a bug on stats command // // Revision 1.32 2002/04/03 15:05:03 freud // My indenting broke something, rolled the source back. // // Revision 1.30 2002/04/01 16:08:59 freud // Fix in hits/shots counter for each weapon // // Revision 1.29 2002/04/01 15:30:38 freud // Small stat fix // // Revision 1.28 2002/04/01 15:16:06 freud // Stats code redone, tng_stats now much more smarter. Removed a few global // variables regarding stats code and added kevlar hits to stats. // // Revision 1.27 2002/03/28 12:10:12 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.26 2002/03/15 19:28:36 deathwatch // Updated with stats rifle name fix // // Revision 1.25 2002/02/26 23:09:20 freud // Stats <playerid> not working, fixed. // // Revision 1.24 2002/02/21 23:38:39 freud // Fix to a BAD stats bug. CRASH // // Revision 1.23 2002/02/18 23:47:33 freud // Fixed FPM if time was 0 // // Revision 1.22 2002/02/18 19:31:40 freud // FPM fix. // // Revision 1.21 2002/02/18 17:21:14 freud // Changed Knife in stats to Slashing Knife // // Revision 1.20 2002/02/17 21:48:56 freud // Changed/Fixed allignment of Scoreboard // // Revision 1.19 2002/02/05 09:27:17 freud // Weapon name changes and better alignment in "stats list" // // Revision 1.18 2002/02/03 01:07:28 freud // more fixes with stats // // Revision 1.14 2002/01/24 11:29:34 ra // Cleanup's in stats code // // Revision 1.13 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.12 2001/12/31 13:29:06 deathwatch // Added revision header // // //----------------------------------------------------------------------------- #include "g_local.h" /* Stats Command */ void ResetStats(edict_t *ent) { int i; if(!ent->client) return; ent->client->resp.stats_shots_t = 0; ent->client->resp.stats_shots_h = 0; for(i=0; i<10; i++) ent->client->resp.stats_locations[i] = 0; for(i=0; i<100; i++) { ent->client->resp.stats_shots[i] = 0; ent->client->resp.stats_hits[i] = 0; ent->client->resp.stats_headshot[i] = 0; } } void Cmd_Stats_f (edict_t *targetent, char *arg) { /* Variables Used: * * stats_shots_t - Total nr of Shots * * stats_shots_h - Total nr of Hits * * headshots - Total nr of Headshots * * */ double perc_hit; int total, hits, i, y, len; char location[64]; char stathead[64], current_weapon[64]; edict_t *ent, *cl_ent; if (!targetent->inuse) return; if (arg[0] != '\0') { if (strcmp (arg, "list") == 0) { gi.cprintf (targetent, PRINT_HIGH, "\n¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); gi.cprintf (targetent, PRINT_HIGH, "PlayerID Name Accuracy\n"); for (i = 0; i < game.maxclients; i++) { cl_ent = &g_edicts[1 + i]; if (!cl_ent->inuse || Info_ValueForKey(cl_ent->client->pers.userinfo, "mvdspec")[0] != '\0') continue; hits = total = 0; for (y = 0; y < 100 ; y++) { hits += cl_ent->client->resp.stats_hits[y]; total += cl_ent->client->resp.stats_shots[y]; } if (hits > 0) perc_hit = (((double) hits / (double) total) * 100.0); else perc_hit = 0.0; gi.cprintf (targetent, PRINT_HIGH, " %-3i %-16s %6.2f\n", i, cl_ent->client->pers.netname, perc_hit); } gi.cprintf (targetent, PRINT_HIGH, "\n Use \"stats <PlayerID>\" for\n individual stats\n¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); return; } i = atoi (arg); //SLIC2 if(i < 0 || i >= game.maxclients) ent = targetent; else ent = &g_edicts[1 + i]; if (!ent->inuse || Info_ValueForKey(ent->client->pers.userinfo, "mvdspec")[0] != '\0') ent = targetent; //SLIC2 END } else { ent = targetent; } // Global Stats: hits = total = 0; for (y = 0; y < 100 ; y++) { hits += ent->client->resp.stats_hits[y]; total += ent->client->resp.stats_shots[y]; } sprintf(stathead, "\n¥₧₧₧₧₧₧₧₧₧ƒ Statistics for %s ¥", ent->client->pers.netname); len = strlen(stathead); for (i = len; i < 50; i++) { stathead[i] = '₧'; } stathead[i] = 0; strcat(stathead, "ƒ\n"); gi.cprintf (targetent, PRINT_HIGH, "%s", stathead); if (!total) { gi.cprintf (targetent, PRINT_HIGH, "\n Player has not fired a shot.\n"); gi.cprintf (targetent, PRINT_HIGH, "\n¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n\n"); return; } gi.cprintf (targetent, PRINT_HIGH, "Weapon Accuracy Hits/Shots Headshots\n"); for (y = 0; y < 100 ; y++) { if (ent->client->resp.stats_shots[y] <= 0) continue; if (y == MOD_MK23) strcpy(current_weapon, "Pistol "); else if (y == MOD_DUAL) strcpy(current_weapon, "Dual Pistols "); else if (y == MOD_KNIFE) strcpy(current_weapon, "Slashing Knife "); else if (y == MOD_KNIFE_THROWN) strcpy(current_weapon, "Throwing Knife "); else if (y == MOD_M4) strcpy(current_weapon, "M4 Assault Rifle "); else if (y == MOD_MP5) strcpy(current_weapon, "MP5 Submachinegun "); else if (y == MOD_SNIPER) strcpy(current_weapon, "Sniper Rifle "); else if (y == MOD_HC) strcpy(current_weapon, "Handcannon "); else if (y == MOD_M3) strcpy(current_weapon, "M3 Shotgun "); else strcpy(current_weapon, "Unknown Weapon "); perc_hit = (((double) ent->client->resp.stats_hits[y] / (double) ent->client->resp.stats_shots[y]) * 100.0); // Percentage of shots that hit gi.cprintf(targetent, PRINT_HIGH, "%s %6.2f %5i/%-5i %i\n", current_weapon, perc_hit, ent->client->resp.stats_hits[y], ent->client->resp.stats_shots[y], ent->client->resp.stats_headshot[y]); } gi.cprintf (targetent, PRINT_HIGH, "\n¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); // Final Part gi.cprintf (targetent, PRINT_HIGH, "Location Hits (%%)\n"); for (y = 0;y < 10;y++) { if (ent->client->resp.stats_locations[y] <= 0) continue; perc_hit = (((double) ent->client->resp.stats_locations[y] / (double) hits) * 100.0); if (y == LOC_HDAM) strcpy(location, "Head"); else if (y == LOC_CDAM) strcpy(location, "Chest"); else if (y == LOC_SDAM) strcpy(location, "Stomach"); else if (y == LOC_LDAM) strcpy(location, "Legs"); else if (y == LOC_KVLR_HELMET) strcpy(location, "Kevlar Helmet"); else if (y == LOC_KVLR_VEST) strcpy(location, "Kevlar Vest"); else if (y == LOC_NO) strcpy(location, "Spread (Shotgun/Handcannon)"); else strcpy(location, "Unknown"); gi.cprintf(targetent, PRINT_HIGH, "%-26s %10i (%6.2f)\n", location, ent->client->resp.stats_locations[y], perc_hit); } gi.cprintf (targetent, PRINT_HIGH, "\n"); if(hits > 0) perc_hit = (((double) hits / (double) total) * 100.0); else perc_hit = 0.0; gi.cprintf (targetent, PRINT_HIGH, "Average Accuracy: %.2f\n", perc_hit); // Average gi.cprintf (targetent, PRINT_HIGH, "\n¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n\n"); } void A_ScoreboardEndLevel (edict_t * ent, edict_t * killer) { char string[1400], damage[50]; edict_t *cl_ent; int maxsize = 1000, i, j, k; int total, score, ping, shots; double accuracy; double fpm; int sortedscores[MAX_CLIENTS], sorted[MAX_CLIENTS]; int totalplayers[TEAM_TOP] = {0}; int totalscore[TEAM_TOP] = {0}; int name_pos[TEAM_TOP]; ent->client->ps.stats[STAT_TEAM_HEADER] = gi.imageindex ("tag3"); for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse || game.clients[i].resp.team == NOTEAM) continue; totalscore[game.clients[i].resp.team] += game.clients[i].resp.score; totalplayers[game.clients[i].resp.team]++; } name_pos[TEAM1] = ((20 - strlen (teams[TEAM1].name)) / 2) * 8; if (name_pos[TEAM1] < 0) name_pos[TEAM1] = 0; name_pos[TEAM2] = ((20 - strlen (teams[TEAM2].name)) / 2) * 8; if (name_pos[TEAM2] < 0) name_pos[TEAM2] = 0; name_pos[TEAM3] = ((20 - strlen (teams[TEAM3].name)) / 2) * 8; if (name_pos[TEAM3] < 0) name_pos[TEAM3] = 0; if (use_3teams->value) { sprintf (string, // TEAM1 "if 24 xv -80 yv 8 pic 24 endif " "if 22 xv -48 yv 8 pic 22 endif " "xv -48 yv 28 string \"%4d/%-3d\" " "xv 10 yv 12 num 2 26 " "xv %d yv 0 string \"%s\" ", totalscore[TEAM1], totalplayers[TEAM1], name_pos[TEAM1] - 80, teams[TEAM1].name); sprintf (string + strlen (string), // TEAM2 "if 25 xv 80 yv 8 pic 25 endif " "if 22 xv 112 yv 8 pic 22 endif " "xv 112 yv 28 string \"%4d/%-3d\" " "xv 168 yv 12 num 2 27 " "xv %d yv 0 string \"%s\" ", totalscore[TEAM2], totalplayers[TEAM2], name_pos[TEAM2] + 80, teams[TEAM2].name); sprintf (string + strlen (string), // TEAM3 "if 30 xv 240 yv 8 pic 30 endif " "if 22 xv 272 yv 8 pic 22 endif " "xv 272 yv 28 string \"%4d/%-3d\" " "xv 328 yv 12 num 2 31 " "xv %d yv 0 string \"%s\" ", totalscore[TEAM3], totalplayers[TEAM3], name_pos[TEAM3] + 240, teams[TEAM3].name); } else { sprintf (string, // TEAM1 "if 24 xv 0 yv 8 pic 24 endif " "if 22 xv 32 yv 8 pic 22 endif " "xv 32 yv 28 string \"%4d/%-3d\" " "xv 90 yv 12 num 2 26 " "xv %d yv 0 string \"%s\" " // TEAM2 "if 25 xv 160 yv 8 pic 25 endif " "if 22 xv 192 yv 8 pic 22 endif " "xv 192 yv 28 string \"%4d/%-3d\" " "xv 248 yv 12 num 2 27 " "xv %d yv 0 string \"%s\" ", totalscore[TEAM1], totalplayers[TEAM1], name_pos[TEAM1], teams[TEAM1].name, totalscore[TEAM2], totalplayers[TEAM2], name_pos[TEAM2] + 160, teams[TEAM2].name); } total = score = 0; for (i = 0; i < game.maxclients; i++) { cl_ent = g_edicts + 1 + i; if (!cl_ent->inuse) continue; score = game.clients[i].resp.score; if (noscore->value) { j = total; } else { for (j = 0; j < total; j++) { if (score > sortedscores[j]) break; } for (k = total; k > j; k--) { sorted[k] = sorted[k - 1]; sortedscores[k] = sortedscores[k - 1]; } } sorted[j] = i; sortedscores[j] = score; total++; } sprintf (string + strlen (string), "xv 0 yv 40 string2 \"Frags Player Shots Acc FPM \" " "xv 0 yv 48 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧₧ƒ ¥₧₧₧ƒ ¥₧₧₧ƒ\" "); // strcpy (string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Kills\" " // "xv 0 yv 40 string2 \"¥₧₧₧ƒ ¥₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ ¥₧₧ƒ ¥₧₧ƒ ¥₧₧₧₧ƒ ¥₧₧₧ƒ\" "); /* { strcpy (string, "xv 0 yv 32 string2 \"Player Time Ping\" " "xv 0 yv 40 string2 \"--------------- ---- ----\" "); } else { strcpy (string, "xv 0 yv 32 string2 \"Frags Player Time Ping Damage Kills\" " "xv 0 yv 40 string2 \"----- --------------- ---- ---- ------ -----\" "); } */ // AQ2:TNG END for (i = 0; i < total; i++) { ping = game.clients[sorted[i]].ping; if (ping > 999) ping = 999; shots = game.clients[sorted[i]].resp.stats_shots_t; if (shots > 9999) shots = 9999; if (shots != 0) accuracy = (((double) game.clients[sorted[i]].resp.stats_shots_h / (double) shots) * 100.0); else accuracy = 0; if ((int) ((level.framenum - game.clients[sorted[i]].resp.enterframe) / 10)) fpm = (((double) sortedscores[i] / (double) ((level.framenum - game.clients[sorted[i]].resp.enterframe) / 10)) * 100.0); else fpm = 0.0; if (game.clients[sorted[i]].resp.damage_dealt < 1000000) sprintf (damage, "%d", game.clients[sorted[i]].resp.damage_dealt); else strcpy (damage, "******"); sprintf (string + strlen (string), "xv 0 yv %d string \"%5d %-15s %4d %5.1f %4.1f\" ", 56 + i * 8, sortedscores[i], game.clients[sorted[i]].pers.netname, shots, accuracy, fpm); if (strlen (string) > (maxsize - 100) && i < (total - 2)) { sprintf (string + strlen (string), "xv 0 yv %d string \"..and %d more\" ", 56 + (i + 1) * 8, (total - i - 1)); break; } } if (strlen (string) > 1023) // for debugging... { gi.dprintf ("Warning: scoreboard string neared or exceeded max length\nDump:\n%s\n---\n", string); string[1023] = '\0'; } gi.WriteByte (svc_layout); gi.WriteString (string); } void Cmd_Statmode_f(edict_t* ent, char *arg) { int i; char stuff[32]; // Ignore if there is no argument. if (!arg[0]) return; // Numerical i = atoi (arg); if (i > 2 || i < 0) { gi.dprintf("Warning: stat_mode set to %i by %s\n", i, ent->client->pers.netname); // Force the old mode if it is valid else force 0 if (ent->client->resp.stat_mode > 0 && ent->client->resp.stat_mode < 3) sprintf(stuff, "set stat_mode \"%i\"\n", ent->client->resp.stat_mode); else sprintf(stuff, "set stat_mode \"0\"\n"); } else { sprintf(stuff, "set stat_mode \"%i\"\n", i); ent->client->resp.stat_mode = i; } stuffcmd(ent, stuff); }
566
./aq2-tng/source/a_match.c
//----------------------------------------------------------------------------- // Matchmode related code // // $Id: a_match.c,v 1.18 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: a_match.c,v $ // Revision 1.18 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.17 2003/06/15 21:43:53 igor // added IRC client // // Revision 1.16 2003/02/10 02:12:25 ra // Zcam fixes, kick crashbug in CTF fixed and some code cleanup. // // Revision 1.15 2002/03/28 12:10:11 freud // Removed unused variables (compiler warnings). // Added cvar mm_allowlock. // // Revision 1.14 2002/03/28 11:46:03 freud // stat_mode 2 and timelimit 0 did not show stats at end of round. // Added lock/unlock. // A fix for use_oldspawns 1, crash bug. // // Revision 1.13 2002/03/25 23:34:06 slicerdw // Small tweak on var handling ( prevent overflows ) // // Revision 1.12 2001/12/05 15:27:35 igor_rock // improved my english (actual -> current :) // // Revision 1.11 2001/12/02 16:15:32 igor_rock // added console messages (for the IRC-Bot) to matchmode // // Revision 1.10 2001/11/25 19:09:25 slicerdw // Fixed Matchtime // // Revision 1.9 2001/09/28 15:44:29 ra // Removing Bill Gate's fingers from a_match.c // // Revision 1.8 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.7 2001/06/16 16:47:06 deathwatch // Matchmode Fixed // // Revision 1.6 2001/06/13 15:36:31 deathwatch // Small fix // // Revision 1.5 2001/06/13 07:55:17 igor_rock // Re-Added a_match.h and a_match.c // Added CTF Header for a_ctf.h and a_ctf.c // //----------------------------------------------------------------------------- #include "g_local.h" #include "a_match.h" float matchtime = 0; float realLtime = 0; //Need this because when paused level.time doenst inc void SendScores(void) { int mins, secs; mins = matchtime / 60; secs = (int)matchtime % 60; if(use_3teams->value) { gi.bprintf(PRINT_HIGH, "¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); gi.bprintf(PRINT_HIGH, " Team 1 Score - Team 2 Score - Team 3 Score\n"); gi.bprintf(PRINT_HIGH, " [%d] [%d] [%d]\n", teams[TEAM1].score, teams[TEAM2].score, teams[TEAM3].score); gi.bprintf(PRINT_HIGH, " Total Played Time: %d:%02d\n", mins, secs); gi.bprintf(PRINT_HIGH, "¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); } else { int team1score = 0, team2score = 0; if(ctf->value) GetCTFScores(&team1score, &team2score); else { team1score = teams[TEAM1].score; team2score = teams[TEAM2].score; } gi.bprintf(PRINT_HIGH, "¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); gi.bprintf(PRINT_HIGH, " Team 1 Score - Team 2 Score\n"); gi.bprintf(PRINT_HIGH, " [%d] [%d]\n", team1score, team2score); gi.bprintf(PRINT_HIGH, " Total Played Time: %d:%02d\n", mins, secs); gi.bprintf(PRINT_HIGH, "¥₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧₧ƒ\n"); } gi.bprintf(PRINT_HIGH, "Match is over, waiting for next map, please vote a new one..\n"); } void Cmd_Kill_f(edict_t * ent); // Used for killing people when they sub off void Cmd_Sub_f(edict_t * ent) { if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if (ent->client->resp.team == NOTEAM) { gi.cprintf(ent, PRINT_HIGH, "You need to be on a team for that...\n"); return; } if (!ent->client->resp.subteam) { Cmd_Kill_f(ent); // lets kill em. gi.bprintf(PRINT_HIGH, "%s is now a substitute for %s\n", ent->client->pers.netname, teams[ent->client->resp.team].name); ent->client->resp.subteam = ent->client->resp.team; return; } else { gi.bprintf(PRINT_HIGH, "%s is no longer a substitute for %s\n", ent->client->pers.netname, teams[ent->client->resp.team].name); ent->client->resp.subteam = 0; if(team_round_going && (teamdm->value || ctf->value)) { ResetKills (ent); //AQ2:TNG Slicer Last Damage Location ent->client->resp.last_damaged_part = 0; ent->client->resp.last_damaged_players[0] = '\0'; //AQ2:TNG END PutClientInServer (ent); AddToTransparentList (ent); } return; } } int TeamsReady(void) { int i; for(i = TEAM1; i <= teamCount; i++) { if(!teams[i].ready) return 0; } return 1; } int CheckForCaptains(int cteam) { edict_t *ent; int i; for (i = 1; i <= (int)(maxclients->value); i++) { ent = getEnt(i); if (ent->inuse) { if (ent->client->resp.captain == cteam) return 1; } } return 0; } void Cmd_Captain_f(edict_t * ent) { int otherTeam; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if (ent->client->resp.team == NOTEAM) { gi.cprintf(ent, PRINT_HIGH, "You need to be on a team for that...\n"); return; } if (ent->client->resp.captain) { gi.bprintf(PRINT_HIGH, "%s is no longer %s's Captain\n", ent->client->pers.netname, teams[ent->client->resp.captain].name); if(!team_round_going || (!teamdm->value && !ctf->value)) teams[ent->client->resp.captain].ready = 0; ent->client->resp.captain = 0; return; } if (CheckForCaptains(ent->client->resp.team)) { gi.cprintf(ent, PRINT_HIGH, "Your team already has a Captain\n"); return; } else { gi.bprintf(PRINT_HIGH, "%s is now %s's Captain\n", ent->client->pers.netname, teams[ent->client->resp.team].name); gi.sound(&g_edicts[0], CHAN_VOICE | CHAN_NO_PHS_ADD, gi.soundindex("misc/comp_up.wav"), 1.0, ATTN_NONE, 0.0); ent->client->resp.captain = ent->client->resp.team; if(ent->client->resp.team == TEAM1) otherTeam = TEAM2; else otherTeam = TEAM1; if(teams[otherTeam].wantReset) gi.cprintf(ent, PRINT_HIGH, "Team %i want to reset scores, type 'resetscores' to accept\n", otherTeam); } } //extern int started; // AQ2:M - Matchmode - Used for ready command void Cmd_Ready_f(edict_t * ent) { char temp[128]; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if (!ent->client->resp.captain) { gi.cprintf(ent, PRINT_HIGH, "You need to be a captain for that\n"); return; } if((teamdm->value || ctf->value) && team_round_going) { if(teamdm->value) gi.cprintf(ent, PRINT_HIGH, "You cant unready in teamdm, use 'pausegame' instead\n"); else gi.cprintf(ent, PRINT_HIGH, "You cant unready in ctf, use 'pausegame' instead\n"); return; } if (teams[ent->client->resp.captain].ready) { Com_sprintf(temp, sizeof(temp),"%s is no longer ready to play!", teams[ent->client->resp.captain].name); CenterPrintAll(temp); teams[ent->client->resp.captain].ready = 0; } else { Com_sprintf(temp, sizeof(temp), "%s is ready to play!", teams[ent->client->resp.captain].name); CenterPrintAll(temp); teams[ent->client->resp.captain].ready = 1; } } void Cmd_Teamname_f(edict_t * ent) { int i, u, team; char temp[32]; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if(ctf->value) { gi.cprintf(ent, PRINT_HIGH, "You cant change teamnames in ctf mode\n"); return; } if (!ent->client->resp.captain) { gi.cprintf(ent, PRINT_HIGH, "You need to be a captain for that\n"); return; } team = ent->client->resp.team; if (teams[team].ready) { gi.cprintf(ent, PRINT_HIGH, "You cannot use this while 'Ready'\n"); return; } if (team_round_going || team_game_going) { gi.cprintf(ent, PRINT_HIGH, "You cannot use this while playing\n"); return; } i = gi.argc(); if (i < 2) { gi.cprintf(ent, PRINT_HIGH, "Your Team Name is %s\n", teams[team].name); return; } Q_strncpyz(temp, gi.argv(1), sizeof(temp)); for (u = 2; u <= i; u++) { Q_strncatz(temp, " ", sizeof(temp)); Q_strncatz(temp, gi.argv(u), sizeof(temp)); } temp[18] = 0; gi.dprintf("%s (Team %i) is now known as %s\n", teams[team].name, team, temp); IRC_printf(IRC_T_GAME, "%n (Team %i) is now known as %n", teams[team].name, team, temp); strcpy(teams[team].name, temp); gi.cprintf(ent, PRINT_HIGH, "New Team Name: %s\n", teams[team].name); } void Cmd_Teamskin_f(edict_t * ent) { int team; char *s; /* int i; edict_t *e;*/ if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } team = ent->client->resp.team; if(team == NOTEAM) { gi.cprintf(ent, PRINT_HIGH, "You need to be on a team for that...\n"); return; } if (!ent->client->resp.captain) { gi.cprintf(ent, PRINT_HIGH, "You need to be a captain for that\n"); return; } if (teams[team].ready) { gi.cprintf(ent, PRINT_HIGH, "You cannot use this while 'Ready'\n"); return; } if (team_round_going || team_game_going) { gi.cprintf(ent, PRINT_HIGH, "You cannot use this while playing\n"); return; } if (gi.argc() < 2) { gi.cprintf(ent, PRINT_HIGH, "Your Team Skin is %s\n", teams[team].skin); return; } s = gi.argv(1); if(!strcmp(s, teams[team].skin)) { gi.cprintf(ent, PRINT_HIGH, "Your Team Skin is Already %s\n", s); return; } Q_strncpyz(teams[team].skin, s, sizeof(teams[team].skin)); if(ctf->value) { s = strchr(teams[team].skin, '/'); if(s) s[1] = 0; else strcpy(teams[team].skin, "male/"); Q_strncatz(teams[team].skin, team == 1 ? CTF_TEAM1_SKIN : CTF_TEAM2_SKIN, sizeof(teams[team].skin)); } sprintf(teams[team].skin_index, "../players/%s_i", teams[team].skin); /* for (i = 1; i <= maxclients->value; i++) { //lets update players skin e = g_edicts + i; if (!e->inuse) continue; if(e->client->resp.team == team) AssignSkin(e, teams[team].skin, false); }*/ gi.cprintf(ent, PRINT_HIGH, "New Team Skin: %s\n", teams[team].skin); } void Cmd_TeamLock_f(edict_t * ent, int a_switch) { char msg[128]; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if (!mm_allowlock->value) gi.cprintf(ent, PRINT_HIGH, "Team locking is disabled on this server\n"); else if (!ent->client->resp.team) gi.cprintf(ent, PRINT_HIGH, "You are not on a team\n"); else if (!ent->client->resp.captain) gi.cprintf(ent, PRINT_HIGH, "You are not the captain of your team\n"); else if (a_switch == 1 && teams[ent->client->resp.team].locked) gi.cprintf(ent, PRINT_HIGH, "Your team is already locked\n"); else if (a_switch == 0 && !teams[ent->client->resp.team].locked) gi.cprintf(ent, PRINT_HIGH, "Your team isn't locked\n"); else { teams[ent->client->resp.team].locked = a_switch; if (a_switch == 1) sprintf(msg, "%s locked", TeamName(ent->client->resp.team)); else sprintf(msg, "%s unlocked", TeamName(ent->client->resp.team)); CenterPrintAll(msg); } } void Cmd_SetAdmin_f (edict_t * ent) { if(!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "Matchmode is not enabled on this server.\n"); return; } if (gi.argc () < 2) { gi.cprintf (ent, PRINT_HIGH, "Usage: matchadmin <password>\n"); return; } if(strcmp (mm_adminpwd->string, "0") == 0) { gi.cprintf (ent, PRINT_HIGH, "Admin Mode is not enabled on this server..\n"); return; } if (strcmp (mm_adminpwd->string, gi.argv (1)) == 0) { if (ent->client->resp.admin) { gi.cprintf (ent, PRINT_HIGH, "You are no longer a match admin.\n"); gi.dprintf ("%s is no longer a Match Admin\n", ent->client->pers.netname); IRC_printf (IRC_T_GAME, "%n is no longer a Match Admin", ent->client->pers.netname); ent->client->resp.admin = 0; } else { gi.cprintf (ent, PRINT_HIGH, "You are now a match admin.\n"); gi.dprintf ("%s is now a Match Admin\n", ent->client->pers.netname); IRC_printf (IRC_T_GAME, "%n is now a Match Admin", ent->client->pers.netname); ent->client->resp.admin = 1; } } else gi.cprintf (ent, PRINT_HIGH, "Wrong password\n"); } void Cmd_ResetScores_f(edict_t * ent) { int i, otherCaptain = 0; edict_t *e; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if(ent->client->resp.admin) //Admins can resetscores { ResetScores(true); gi.bprintf(PRINT_HIGH, "Scores and time was resetted by match admin %s\n", ent->client->pers.netname); return; } if (ent->client->resp.team == NOTEAM) { gi.cprintf(ent, PRINT_HIGH, "You need to be on a team for that...\n"); return; } if (!ent->client->resp.captain) { gi.cprintf(ent, PRINT_HIGH, "You need to be a captain for that\n"); return; } if(teams[ent->client->resp.team].wantReset) { teams[ent->client->resp.team].wantReset = 0; for (i = 1; i <= maxclients->value; i++) { e = g_edicts + i; if (!e->inuse || !e->client->resp.captain) continue; if(e->client->resp.team != NOTEAM && e->client->resp.team != ent->client->resp.team) gi.cprintf(e, PRINT_HIGH, "Team %i doesnt want to reset afterall", ent->client->resp.team); } gi.cprintf(ent, PRINT_HIGH, "Your score reset request cancelled\n"); return; } teams[ent->client->resp.team].wantReset = 1; for(i = TEAM1; i<teamCount+1; i++) { if(!teams[i].wantReset) break; } if(i == teamCount+1) { ResetScores(true); gi.bprintf(PRINT_HIGH, "Scores and time was resetted by request of captains\n"); return; } for (i = 1; i <= maxclients->value; i++) { e = g_edicts + i; if (!e->inuse || !e->client->resp.captain) continue; if(e->client->resp.team != NOTEAM && e->client->resp.team != ent->client->resp.team) { gi.cprintf(e, PRINT_HIGH, "Team %i want to reset scores, type 'resetscores' to accept\n", ent->client->resp.team); otherCaptain = 1; } } if(otherCaptain) gi.cprintf(ent, PRINT_HIGH, "Your score reset request was send to other team captain\n"); else gi.cprintf(ent, PRINT_HIGH, "Other team need captain and his accept to reset the scores\n"); } void Cmd_TogglePause_f(edict_t * ent, qboolean pause) { static int lastPaused = 0; if (!matchmode->value) { gi.cprintf(ent, PRINT_HIGH, "This command need matchmode to be enabled\n"); return; } if ((int)mm_pausecount->value < 1) { gi.cprintf(ent, PRINT_HIGH, "Pause is disabled\n"); return; } if (ent->client->resp.team == NOTEAM) { gi.cprintf(ent, PRINT_HIGH, "You need to be on a team for that...\n"); return; } if (!team_round_going) { gi.cprintf(ent, PRINT_HIGH, "No match going so why pause?\n"); //return; } if (ent->client->resp.subteam) { gi.cprintf(ent, PRINT_HIGH, "You cant pause when substitute\n"); return; } if(pause) { if(pause_time > 0) { gi.cprintf(ent, PRINT_HIGH, "Game is already paused you silly\n", time); return; } if (level.intermissiontime) { gi.cprintf(ent, PRINT_HIGH, "Can't pause in an intermission.\n"); return; } if(teams[ent->client->resp.team].pauses_used >= (int)mm_pausecount->value) { gi.cprintf(ent, PRINT_HIGH, "Your team doesn't have any pauses left.\n"); return; } teams[ent->client->resp.team].pauses_used++; CenterPrintAll (va("Game paused by %s\nTeam %i has %i pauses left", ent->client->pers.netname, ent->client->resp.team, (int)mm_pausecount->value - teams[ent->client->resp.team].pauses_used)); pause_time = (int)mm_pausetime->value * 600; lastPaused = ent->client->resp.team; } else { if(!pause_time) { gi.cprintf(ent, PRINT_HIGH, "Game is not paused\n", time); return; } if(!lastPaused) { gi.cprintf(ent, PRINT_HIGH, "Already unpausing\n"); return; } if(lastPaused != ent->client->resp.team) { gi.cprintf(ent, PRINT_HIGH, "You cannot unpause when pause is made by other team\n"); return; } pause_time = 100; lastPaused = 0; } }
567
./aq2-tng/source/m_move.c
//----------------------------------------------------------------------------- // m_move.c -- monster movement // // $Id: m_move.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: m_move.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:29:29 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #define STEPSIZE 18 /* ============= M_CheckBottom Returns false if any part of the bottom of the entity is off an edge that is not a staircase. ============= */ int c_yes, c_no; qboolean M_CheckBottom (edict_t * ent) { vec3_t mins, maxs, start, stop; trace_t trace; int x, y; float mid, bottom; VectorAdd (ent->s.origin, ent->mins, mins); VectorAdd (ent->s.origin, ent->maxs, maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; for (x = 0; x <= 1; x++) for (y = 0; y <= 1; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (gi.pointcontents (start) != CONTENTS_SOLID) goto realcheck; } c_yes++; return true; // we got out easy realcheck: c_no++; // // check it for real... // start[2] = mins[2]; // the midpoint must be within 16 of the bottom start[0] = stop[0] = (mins[0] + maxs[0]) * 0.5; start[1] = stop[1] = (mins[1] + maxs[1]) * 0.5; stop[2] = start[2] - 2 * STEPSIZE; trace = gi.trace (start, vec3_origin, vec3_origin, stop, ent, MASK_MONSTERSOLID); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint for (x = 0; x <= 1; x++) for (y = 0; y <= 1; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; trace = gi.trace (start, vec3_origin, vec3_origin, stop, ent, MASK_MONSTERSOLID); if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } c_yes++; return true; } /* ============= SV_movestep Called by monster program code. The move will be adjusted for slopes and stairs, but if the move isn't possible, no move is done, false is returned, and pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ //FIXME since we need to test end position contents here, can we avoid doing //it again later in catagorize position? qboolean SV_movestep (edict_t * ent, vec3_t move, qboolean relink) { float dz; vec3_t oldorg, neworg, end; trace_t trace; int i; float stepsize; vec3_t test; int contents; // try the move VectorCopy (ent->s.origin, oldorg); VectorAdd (ent->s.origin, move, neworg); // flying monsters don't step up if (ent->flags & (FL_SWIM | FL_FLY)) { // try one move with vertical motion, then one without for (i = 0; i < 2; i++) { VectorAdd (ent->s.origin, move, neworg); if (i == 0 && ent->enemy) { if (!ent->goalentity) ent->goalentity = ent->enemy; dz = ent->s.origin[2] - ent->goalentity->s.origin[2]; if (ent->goalentity->client) { if (dz > 40) neworg[2] -= 8; if (!((ent->flags & FL_SWIM) && (ent->waterlevel < 2))) if (dz < 30) neworg[2] += 8; } else { if (dz > 8) neworg[2] -= 8; else if (dz > 0) neworg[2] -= dz; else if (dz < -8) neworg[2] += 8; else neworg[2] += dz; } } trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, neworg, ent, MASK_MONSTERSOLID); // fly monsters don't enter water voluntarily if (ent->flags & FL_FLY) { if (!ent->waterlevel) { test[0] = trace.endpos[0]; test[1] = trace.endpos[1]; test[2] = trace.endpos[2] + ent->mins[2] + 1; contents = gi.pointcontents (test); if (contents & MASK_WATER) return false; } } // swim monsters don't exit water voluntarily if (ent->flags & FL_SWIM) { if (ent->waterlevel < 2) { test[0] = trace.endpos[0]; test[1] = trace.endpos[1]; test[2] = trace.endpos[2] + ent->mins[2] + 1; contents = gi.pointcontents (test); if (!(contents & MASK_WATER)) return false; } } if (trace.fraction == 1) { VectorCopy (trace.endpos, ent->s.origin); if (relink) { gi.linkentity (ent); G_TouchTriggers (ent); } return true; } if (!ent->enemy) break; } return false; } // push down from a step height above the wished position if (!(ent->monsterinfo.aiflags & AI_NOSTEP)) stepsize = STEPSIZE; else stepsize = 1; neworg[2] += stepsize; VectorCopy (neworg, end); end[2] -= stepsize * 2; trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID); if (trace.allsolid) return false; if (trace.startsolid) { neworg[2] -= stepsize; trace = gi.trace (neworg, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID); if (trace.allsolid || trace.startsolid) return false; } // don't go in to water if (ent->waterlevel == 0) { test[0] = trace.endpos[0]; test[1] = trace.endpos[1]; test[2] = trace.endpos[2] + ent->mins[2] + 1; contents = gi.pointcontents (test); if (contents & MASK_WATER) return false; } if (trace.fraction == 1) { // if monster had the ground pulled out, go ahead and fall if (ent->flags & FL_PARTIALGROUND) { VectorAdd (ent->s.origin, move, ent->s.origin); if (relink) { gi.linkentity (ent); G_TouchTriggers (ent); } ent->groundentity = NULL; return true; } return false; // walked off an edge } // check point traces down for dangling corners VectorCopy (trace.endpos, ent->s.origin); if (!M_CheckBottom (ent)) { if (ent->flags & FL_PARTIALGROUND) { // entity had floor mostly pulled out from underneath it // and is trying to correct if (relink) { gi.linkentity (ent); G_TouchTriggers (ent); } return true; } VectorCopy (oldorg, ent->s.origin); return false; } if (ent->flags & FL_PARTIALGROUND) { ent->flags &= ~FL_PARTIALGROUND; } ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; // the move is ok if (relink) { gi.linkentity (ent); G_TouchTriggers (ent); } return true; } //============================================================================ /* =============== M_ChangeYaw =============== */ void M_ChangeYaw (edict_t * ent) { float ideal; float current; float move; float speed; current = anglemod (ent->s.angles[YAW]); ideal = ent->ideal_yaw; if (current == ideal) return; move = ideal - current; speed = ent->yaw_speed; if (ideal > current) { if (move >= 180) move = move - 360; } else { if (move <= -180) move = move + 360; } if (move > 0) { if (move > speed) move = speed; } else { if (move < -speed) move = -speed; } ent->s.angles[YAW] = anglemod (current + move); } /* ====================== SV_StepDirection Turns to the movement direction, and walks the current distance if facing it. ====================== */ qboolean SV_StepDirection (edict_t * ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; ent->ideal_yaw = yaw; M_ChangeYaw (ent); yaw = yaw * M_PI * 2 / 360; move[0] = cos (yaw) * dist; move[1] = sin (yaw) * dist; move[2] = 0; VectorCopy (ent->s.origin, oldorigin); if (SV_movestep (ent, move, false)) { delta = ent->s.angles[YAW] - ent->ideal_yaw; if (delta > 45 && delta < 315) { // not turned far enough, so don't take the step VectorCopy (oldorigin, ent->s.origin); } gi.linkentity (ent); G_TouchTriggers (ent); return true; } gi.linkentity (ent); G_TouchTriggers (ent); return false; } /* ====================== SV_FixCheckBottom ====================== */ void SV_FixCheckBottom (edict_t * ent) { ent->flags |= FL_PARTIALGROUND; } /* ================ SV_NewChaseDir ================ */ #define DI_NODIR -1 void SV_NewChaseDir (edict_t * actor, edict_t * enemy, float dist) { float deltax, deltay; float d[3]; float tdir, olddir, turnaround; //FIXME: how did we get here with no enemy if (!enemy) return; olddir = anglemod ((int) (actor->ideal_yaw / 45) * 45); turnaround = anglemod (olddir - 180); deltax = enemy->s.origin[0] - actor->s.origin[0]; deltay = enemy->s.origin[1] - actor->s.origin[1]; if (deltax > 10) d[1] = 0; else if (deltax < -10) d[1] = 180; else d[1] = DI_NODIR; if (deltay < -10) d[2] = 270; else if (deltay > 10) d[2] = 90; else d[2] = DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90 ? 45 : 315; else tdir = d[2] == 90 ? 135 : 215; if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) return; } // try other directions if (((rand () & 3) & 1) || abs (deltay) > abs (deltax)) { tdir = d[1]; d[1] = d[2]; d[2] = tdir; } if (d[1] != DI_NODIR && d[1] != turnaround && SV_StepDirection (actor, d[1], dist)) return; if (d[2] != DI_NODIR && d[2] != turnaround && SV_StepDirection (actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ if (olddir != DI_NODIR && SV_StepDirection (actor, olddir, dist)) return; if (rand () & 1) /*randomly determine direction of search */ { for (tdir = 0; tdir <= 315; tdir += 45) if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) return; } else { for (tdir = 315; tdir >= 0; tdir -= 45) if (tdir != turnaround && SV_StepDirection (actor, tdir, dist)) return; } if (turnaround != DI_NODIR && SV_StepDirection (actor, turnaround, dist)) return; actor->ideal_yaw = olddir; // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all if (!M_CheckBottom (actor)) SV_FixCheckBottom (actor); } /* ====================== SV_CloseEnough ====================== */ qboolean SV_CloseEnough (edict_t * ent, edict_t * goal, float dist) { int i; for (i = 0; i < 3; i++) { if (goal->absmin[i] > ent->absmax[i] + dist) return false; if (goal->absmax[i] < ent->absmin[i] - dist) return false; } return true; } /* ====================== M_MoveToGoal ====================== */ void M_MoveToGoal (edict_t * ent, float dist) { edict_t *goal; goal = ent->goalentity; if (!ent->groundentity && !(ent->flags & (FL_FLY | FL_SWIM))) return; // if the next step hits the enemy, return immediately if (ent->enemy && SV_CloseEnough (ent, ent->enemy, dist)) return; // bump around... if ((rand () & 3) == 1 || !SV_StepDirection (ent, ent->ideal_yaw, dist)) { if (ent->inuse) SV_NewChaseDir (ent, goal, dist); } } /* =============== M_walkmove =============== */ qboolean M_walkmove (edict_t * ent, float yaw, float dist) { vec3_t move; if (!ent->groundentity && !(ent->flags & (FL_FLY | FL_SWIM))) return false; yaw = yaw * M_PI * 2 / 360; move[0] = cos (yaw) * dist; move[1] = sin (yaw) * dist; move[2] = 0; return SV_movestep (ent, move, true); }
568
./aq2-tng/source/g_monster.c
//----------------------------------------------------------------------------- // g_monster.c // // $Id: g_monster.c,v 1.3 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_monster.c,v $ // Revision 1.3 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.2 2001/05/12 00:37:03 ra // // // Fixing various compilerwarnings. // // Revision 1.1.1.1 2001/05/06 17:31:40 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" // // monster weapons // //FIXME mosnters should call these with a totally accurate direction // and we can mess it up based on skill. Spread should be for normal // and we can tighten or loosen based on skill. We could muck with // the damages too, but I'm not sure that's such a good idea. void monster_fire_bullet (edict_t * self, vec3_t start, vec3_t dir, int damage, int kick, int hspread, int vspread, int flashtype) { fire_bullet (self, start, dir, damage, kick, hspread, vspread, MOD_UNKNOWN); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_shotgun (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int hspread, int vspread, int count, int flashtype) { fire_shotgun (self, start, aimdir, damage, kick, hspread, vspread, count, MOD_UNKNOWN); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_blaster (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype, int effect) { fire_blaster (self, start, dir, damage, speed, effect, false); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_grenade (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int speed, int flashtype) { fire_grenade (self, start, aimdir, damage, speed, 2.5, damage + 40); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_rocket (edict_t * self, vec3_t start, vec3_t dir, int damage, int speed, int flashtype) { fire_rocket (self, start, dir, damage, speed, damage + 20, damage); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_railgun (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int kick, int flashtype) { fire_rail (self, start, aimdir, damage, kick); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } void monster_fire_bfg (edict_t * self, vec3_t start, vec3_t aimdir, int damage, int speed, int kick, float damage_radius, int flashtype) { fire_bfg (self, start, aimdir, damage, speed, damage_radius); gi.WriteByte (svc_muzzleflash2); gi.WriteShort (self - g_edicts); gi.WriteByte (flashtype); gi.multicast (start, MULTICAST_PVS); } // // Monster utility functions // static void M_FliesOff (edict_t * self) { self->s.effects &= ~EF_FLIES; self->s.sound = 0; } static void M_FliesOn (edict_t * self) { if (self->waterlevel) return; self->s.effects |= EF_FLIES; self->s.sound = gi.soundindex ("infantry/inflies1.wav"); self->think = M_FliesOff; self->nextthink = level.time + 60; } void M_FlyCheck (edict_t * self) { if (self->waterlevel) return; if (random () > 0.5) return; self->think = M_FliesOn; self->nextthink = level.time + 5 + 10 * random (); } void AttackFinished (edict_t * self, float time) { self->monsterinfo.attack_finished = level.time + time; } void M_CheckGround (edict_t * ent) { vec3_t point; trace_t trace; if (ent->flags & (FL_SWIM | FL_FLY)) return; if (ent->velocity[2] > 100) { ent->groundentity = NULL; return; } // if the hull point one-quarter unit down is solid the entity is on ground point[0] = ent->s.origin[0]; point[1] = ent->s.origin[1]; point[2] = ent->s.origin[2] - 0.25; trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, point, ent, MASK_MONSTERSOLID); // check steepness if (trace.plane.normal[2] < 0.7 && !trace.startsolid) { ent->groundentity = NULL; return; } // ent->groundentity = trace.ent; // ent->groundentity_linkcount = trace.ent->linkcount; // if (!trace.startsolid && !trace.allsolid) // VectorCopy (trace.endpos, ent->s.origin); if (!trace.startsolid && !trace.allsolid) { VectorCopy (trace.endpos, ent->s.origin); ent->groundentity = trace.ent; ent->groundentity_linkcount = trace.ent->linkcount; ent->velocity[2] = 0; } } void M_CatagorizePosition (edict_t * ent) { vec3_t point; int cont; // // get waterlevel // point[0] = ent->s.origin[0]; point[1] = ent->s.origin[1]; point[2] = ent->s.origin[2] + ent->mins[2] + 1; cont = gi.pointcontents (point); if (!(cont & MASK_WATER)) { ent->waterlevel = 0; ent->watertype = 0; return; } ent->watertype = cont; ent->waterlevel = 1; point[2] += 26; cont = gi.pointcontents (point); if (!(cont & MASK_WATER)) return; ent->waterlevel = 2; point[2] += 22; cont = gi.pointcontents (point); if (cont & MASK_WATER) ent->waterlevel = 3; } void M_WorldEffects (edict_t * ent) { int dmg; if (ent->health > 0) { if (!(ent->flags & FL_SWIM)) { if (ent->waterlevel < 3) { ent->air_finished = level.time + 12; } else if (ent->air_finished < level.time) { // drown! if (ent->pain_debounce_time < level.time) { dmg = 2 + 2 * floor (level.time - ent->air_finished); if (dmg > 15) dmg = 15; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER); ent->pain_debounce_time = level.time + 1; } } } else { if (ent->waterlevel > 0) { ent->air_finished = level.time + 9; } else if (ent->air_finished < level.time) { // suffocate! if (ent->pain_debounce_time < level.time) { dmg = 2 + 2 * floor (level.time - ent->air_finished); if (dmg > 15) dmg = 15; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, dmg, 0, DAMAGE_NO_ARMOR, MOD_WATER); ent->pain_debounce_time = level.time + 1; } } } } if (ent->waterlevel == 0) { if (ent->flags & FL_INWATER) { gi.sound (ent, CHAN_BODY, gi.soundindex ("player/watr_out.wav"), 1, ATTN_NORM, 0); ent->flags &= ~FL_INWATER; } return; } if ((ent->watertype & CONTENTS_LAVA) && !(ent->flags & FL_IMMUNE_LAVA)) { if (ent->damage_debounce_time < level.time) { ent->damage_debounce_time = level.time + 0.2; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, 10 * ent->waterlevel, 0, 0, MOD_LAVA); } } if ((ent->watertype & CONTENTS_SLIME) && !(ent->flags & FL_IMMUNE_SLIME)) { if (ent->damage_debounce_time < level.time) { ent->damage_debounce_time = level.time + 1; T_Damage (ent, world, world, vec3_origin, ent->s.origin, vec3_origin, 4 * ent->waterlevel, 0, 0, MOD_SLIME); } } if (!(ent->flags & FL_INWATER)) { if (!(ent->svflags & SVF_DEADMONSTER)) { if (ent->watertype & CONTENTS_LAVA) if (random () <= 0.5) gi.sound (ent, CHAN_BODY, gi.soundindex ("player/lava1.wav"), 1, ATTN_NORM, 0); else gi.sound (ent, CHAN_BODY, gi.soundindex ("player/lava2.wav"), 1, ATTN_NORM, 0); else if (ent->watertype & CONTENTS_SLIME) gi.sound (ent, CHAN_BODY, gi.soundindex ("player/watr_in.wav"), 1, ATTN_NORM, 0); else if (ent->watertype & CONTENTS_WATER) gi.sound (ent, CHAN_BODY, gi.soundindex ("player/watr_in.wav"), 1, ATTN_NORM, 0); } ent->flags |= FL_INWATER; ent->damage_debounce_time = 0; } } void M_droptofloor (edict_t * ent) { vec3_t end; trace_t trace; ent->s.origin[2] += 1; VectorCopy (ent->s.origin, end); end[2] -= 256; trace = gi.trace (ent->s.origin, ent->mins, ent->maxs, end, ent, MASK_MONSTERSOLID); if (trace.fraction == 1 || trace.allsolid) return; VectorCopy (trace.endpos, ent->s.origin); gi.linkentity (ent); M_CheckGround (ent); M_CatagorizePosition (ent); } void M_SetEffects (edict_t * ent) { ent->s.effects &= ~(EF_COLOR_SHELL | EF_POWERSCREEN); ent->s.renderfx &= ~(RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE); if (ent->monsterinfo.aiflags & AI_RESURRECTING) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= RF_SHELL_RED; } if (ent->health <= 0) return; if (ent->powerarmor_time > level.time) { if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SCREEN) { ent->s.effects |= EF_POWERSCREEN; } else if (ent->monsterinfo.power_armor_type == POWER_ARMOR_SHIELD) { ent->s.effects |= EF_COLOR_SHELL; ent->s.renderfx |= RF_SHELL_GREEN; } } } void M_MoveFrame (edict_t * self) { mmove_t *move; int index; move = self->monsterinfo.currentmove; self->nextthink = level.time + FRAMETIME; if ((self->monsterinfo.nextframe) && (self->monsterinfo.nextframe >= move->firstframe) && (self->monsterinfo.nextframe <= move->lastframe)) { self->s.frame = self->monsterinfo.nextframe; self->monsterinfo.nextframe = 0; } else { if (self->s.frame == move->lastframe) { if (move->endfunc) { move->endfunc (self); // regrab move, endfunc is very likely to change it move = self->monsterinfo.currentmove; // check for death if (self->svflags & SVF_DEADMONSTER) return; } } if (self->s.frame < move->firstframe || self->s.frame > move->lastframe) { self->monsterinfo.aiflags &= ~AI_HOLD_FRAME; self->s.frame = move->firstframe; } else { if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME)) { self->s.frame++; if (self->s.frame > move->lastframe) self->s.frame = move->firstframe; } } } index = self->s.frame - move->firstframe; // AQ:TNG JBravo fixing compiler warning if (move->frame[index].aifunc) { if (!(self->monsterinfo.aiflags & AI_HOLD_FRAME)) move->frame[index].aifunc (self, move->frame[index].dist * self->monsterinfo.scale); else move->frame[index].aifunc (self, 0); } // End compilerwarningfix. if (move->frame[index].thinkfunc) move->frame[index].thinkfunc (self); } void monster_think (edict_t * self) { M_MoveFrame (self); if (self->linkcount != self->monsterinfo.linkcount) { self->monsterinfo.linkcount = self->linkcount; M_CheckGround (self); } M_CatagorizePosition (self); M_WorldEffects (self); M_SetEffects (self); } /* ================ monster_use Using a monster makes it angry at the current activator ================ */ void monster_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->enemy) return; if (self->health <= 0) return; if (activator->flags & FL_NOTARGET) return; if (!(activator->client) && !(activator->monsterinfo.aiflags & AI_GOOD_GUY)) return; // delay reaction so if the monster is teleported, its sound is still heard self->enemy = activator; FoundTarget (self); } void monster_start_go (edict_t * self); void monster_triggered_spawn (edict_t * self) { self->s.origin[2] += 1; KillBox (self); self->solid = SOLID_BBOX; self->movetype = MOVETYPE_STEP; self->svflags &= ~SVF_NOCLIENT; self->air_finished = level.time + 12; gi.linkentity (self); monster_start_go (self); if (self->enemy && !(self->spawnflags & 1) && !(self->enemy->flags & FL_NOTARGET)) { FoundTarget (self); } else { self->enemy = NULL; } } void monster_triggered_spawn_use (edict_t * self, edict_t * other, edict_t * activator) { // we have a one frame delay here so we don't telefrag the guy who activated us self->think = monster_triggered_spawn; self->nextthink = level.time + FRAMETIME; if (activator->client) self->enemy = activator; self->use = monster_use; } void monster_triggered_start (edict_t * self) { self->solid = SOLID_NOT; self->movetype = MOVETYPE_NONE; self->svflags |= SVF_NOCLIENT; self->nextthink = 0; self->use = monster_triggered_spawn_use; } /* ================ monster_death_use When a monster dies, it fires all of its targets with the current enemy as activator. ================ */ void monster_death_use (edict_t * self) { self->flags &= ~(FL_FLY | FL_SWIM); self->monsterinfo.aiflags &= AI_GOOD_GUY; if (self->item) { Drop_Item (self, self->item); self->item = NULL; } if (self->deathtarget) self->target = self->deathtarget; if (!self->target) return; G_UseTargets (self, self->enemy); } //============================================================================ qboolean monster_start (edict_t * self) { if (deathmatch->value) { G_FreeEdict (self); return false; } if ((self->spawnflags & 4) && !(self->monsterinfo.aiflags & AI_GOOD_GUY)) { self->spawnflags &= ~4; self->spawnflags |= 1; // gi.dprintf("fixed spawnflags on %s at %s\n", self->classname, vtos(self->s.origin)); } if (!(self->monsterinfo.aiflags & AI_GOOD_GUY)) level.total_monsters++; self->nextthink = level.time + FRAMETIME; self->svflags |= SVF_MONSTER; self->s.renderfx |= RF_FRAMELERP; self->takedamage = DAMAGE_AIM; self->air_finished = level.time + 12; self->use = monster_use; self->max_health = self->health; self->clipmask = MASK_MONSTERSOLID; self->s.skinnum = 0; self->deadflag = DEAD_NO; self->svflags &= ~SVF_DEADMONSTER; if (!self->monsterinfo.checkattack) self->monsterinfo.checkattack = M_CheckAttack; VectorCopy (self->s.origin, self->s.old_origin); if (st.item) { self->item = FindItemByClassname (st.item); if (!self->item) gi.dprintf ("%s at %s has bad item: %s\n", self->classname, vtos (self->s.origin), st.item); } // randomize what frame they start on if (self->monsterinfo.currentmove) self->s.frame = self->monsterinfo.currentmove->firstframe + (rand () % (self->monsterinfo.currentmove->lastframe - self->monsterinfo.currentmove->firstframe + 1)); return true; } void monster_start_go (edict_t * self) { vec3_t v; if (self->health <= 0) return; // check for target to combat_point and change to combattarget if (self->target) { qboolean notcombat; qboolean fixup; edict_t *target; target = NULL; notcombat = false; fixup = false; while ((target = G_Find (target, FOFS (targetname), self->target)) != NULL) { if (strcmp (target->classname, "point_combat") == 0) { self->combattarget = self->target; fixup = true; } else { notcombat = true; } } if (notcombat && self->combattarget) gi.dprintf ("%s at %s has target with mixed types\n", self->classname, vtos (self->s.origin)); if (fixup) self->target = NULL; } // validate combattarget if (self->combattarget) { edict_t *target; target = NULL; while ((target = G_Find (target, FOFS (targetname), self->combattarget)) != NULL) { if (strcmp (target->classname, "point_combat") != 0) { gi. dprintf ("%s at (%i %i %i) has a bad combattarget %s : %s at (%i %i %i)\n", self->classname, (int) self->s.origin[0], (int) self->s.origin[1], (int) self->s.origin[2], self->combattarget, target->classname, (int) target->s.origin[0], (int) target->s.origin[1], (int) target->s.origin[2]); } } } if (self->target) { self->goalentity = self->movetarget = G_PickTarget (self->target); if (!self->movetarget) { gi.dprintf ("%s can't find target %s at %s\n", self->classname, self->target, vtos (self->s.origin)); self->target = NULL; self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } else if (strcmp (self->movetarget->classname, "path_corner") == 0) { VectorSubtract (self->goalentity->s.origin, self->s.origin, v); self->ideal_yaw = self->s.angles[YAW] = vectoyaw (v); self->monsterinfo.walk (self); self->target = NULL; } else { self->goalentity = self->movetarget = NULL; self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } } else { self->monsterinfo.pausetime = 100000000; self->monsterinfo.stand (self); } self->think = monster_think; self->nextthink = level.time + FRAMETIME; } void walkmonster_start_go (edict_t * self) { if (!(self->spawnflags & 2) && level.time < 1) { M_droptofloor (self); if (self->groundentity) if (!M_walkmove (self, 0, 0)) gi.dprintf ("%s in solid at %s\n", self->classname, vtos (self->s.origin)); } if (!self->yaw_speed) self->yaw_speed = 20; self->viewheight = 25; monster_start_go (self); if (self->spawnflags & 2) monster_triggered_start (self); } void walkmonster_start (edict_t * self) { self->think = walkmonster_start_go; monster_start (self); } void flymonster_start_go (edict_t * self) { if (!M_walkmove (self, 0, 0)) gi.dprintf ("%s in solid at %s\n", self->classname, vtos (self->s.origin)); if (!self->yaw_speed) self->yaw_speed = 10; self->viewheight = 25; monster_start_go (self); if (self->spawnflags & 2) monster_triggered_start (self); } void flymonster_start (edict_t * self) { self->flags |= FL_FLY; self->think = flymonster_start_go; monster_start (self); } void swimmonster_start_go (edict_t * self) { if (!self->yaw_speed) self->yaw_speed = 10; self->viewheight = 10; monster_start_go (self); if (self->spawnflags & 2) monster_triggered_start (self); } void swimmonster_start (edict_t * self) { self->flags |= FL_SWIM; self->think = swimmonster_start_go; monster_start (self); }
569
./aq2-tng/source/a_xvote.c
//----------------------------------------------------------------------------- // a_xvote.c // // $Id: a_xvote.c,v 1.4 2003/12/09 22:06:11 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: a_xvote.c,v $ // Revision 1.4 2003/12/09 22:06:11 igor_rock // added "ignorepart" commadn to ignore all players with the specified part in // their name (one shot function: if player changes his name/new palyers join, // the list will _not_ changed!) // // Revision 1.3 2002/03/26 21:49:01 ra // Bufferoverflow fixes // // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:29:27 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" //#define xvlistsize (sizeof(xvotelist)/sizeof(vote_t)) cvar_t *_InitLeaveTeam (ini_t * ini) { return teamplay; } vote_t xvotelist[] = { // mapvote { NULL, // cvar _InitMapVotelist, // InitGame NULL, // ExitGame NULL, // InitLevel _MapExitLevel, // ExitLevel _MapInitClient, // InitClient NULL, // ClientConnect _RemoveVoteFromMap, // ClientDisconnect _MapWithMostVotes, // Newround _CheckMapVotes, // CheckVote MAPMENUTITLE, // Votetitle MapVoteMenu, // VoteSelected { // commands {"votemap", Cmd_Votemap_f} , {"maplist", Cmd_Maplist_f} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} } } , // kickvote { NULL, // cvar _InitKickVote, // InitGame NULL, // ExitGame NULL, // InitLevel NULL, // ExitLevel _InitKickClient, // InitClient NULL, // ClientConnect _ClientKickDisconnect, // ClientDisconnect _CheckKickVote, // Newround NULL, // CheckVote KICKMENUTITLE, // Votetitle _KickVoteSelected, // VoteSelected { // commands {"votekick", Cmd_Votekick_f} , {"votekicknum", Cmd_Votekicknum_f} , {"kicklist", Cmd_Kicklist_f} , {NULL, NULL} , {NULL, NULL} } } , // ignore { NULL, // cvar NULL, // InitGame - no init, default cvar = deathmatch NULL, // ExitGame NULL, // InitLevel NULL, // ExitLevel _ClearIgnoreList, // InitClient NULL, // ClientConnect _ClrIgnoresOn, // ClientDisconnect NULL, // Newround NULL, // CheckVote IGNOREMENUTITLE, // Votetitle _IgnoreVoteSelected, // VoteSelected { // commands {"ignore", Cmd_Ignore_f} , {"ignorenum", Cmd_Ignorenum_f} , {"ignorelist", Cmd_Ignorelist_f} , {"ignoreclear", Cmd_Ignoreclear_f} , {"ignorepart", Cmd_IgnorePart_f} } } , // configvote { NULL, // cvar _InitConfiglist, // InitGame NULL, // ExitGame NULL, // InitLevel _ConfigExitLevel, // ExitLevel _ConfigInitClient, // InitClient NULL, // ClientConnect _RemoveVoteFromConfig, // ClientDisconnect _ConfigWithMostVotes, // Newround _CheckConfigVotes, // CheckVote CONFIGMENUTITLE, // Votetitle ConfigVoteMenu, // VoteSelected { // commands {"voteconfig", Cmd_Voteconfig_f} , {"configlist", Cmd_Configlist_f} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} } } , // Leave Team { NULL, // cvar _InitLeaveTeam, // InitGame NULL, // ExitGame NULL, // InitLevel NULL, // ExitLevel NULL, // InitClient NULL, // ClientConnect NULL, // ClientDisconnect NULL, // Newround NULL, // CheckVote "Leave Team", // Votetitle LeaveTeams, // VoteSelected { // commands {NULL, NULL} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} } } , // scramblevote { NULL, // cvar _InitScrambleVote, // InitGame NULL, // ExitGame NULL, // InitLevel NULL, // ExitLevel NULL, // InitClient NULL, // ClientConnect NULL, // ClientDisconnect _CheckScrambleVote, // Newround NULL, // CheckVote "Team Scramble", // Votetitle _VoteScrambleSelected, // VoteSelected { // commands {"votescramble", Cmd_Votescramble_f} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} , {NULL, NULL} } } }; static const int xvlistsize = (sizeof(xvotelist)/sizeof(vote_t)); /**/ void _AddVoteMenu (edict_t * ent, int fromix) { int i = 0, j = 0; qboolean erg = true; while (i < xvlistsize && erg == true) { if (xvotelist[i].VoteTitle && xvotelist[i].DependsOn->value && xvotelist[i].VoteSelected) { if (j >= fromix) { erg = xMenu_Add(ent, xvotelist[i].VoteTitle, xvotelist[i].VoteSelected); } j++; } i++; } } void vShowMenu (edict_t * ent, char *menu) { int i; char fixedmenu[128]; Q_strncpyz(fixedmenu, menu, sizeof(fixedmenu)); if (ent->client->menu) { PMenu_Close (ent); return; } if (!*fixedmenu) { // general menu if (xMenu_New (ent, "Menu", NULL, _AddVoteMenu) == false) { gi.cprintf (ent, PRINT_MEDIUM, "Nothing to choose.\n"); } } else { for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].DependsOn->value && xvotelist[i].VoteSelected && Q_stricmp (fixedmenu, xvotelist[i].VoteTitle) == 0) { xvotelist[i].VoteSelected (ent, NULL); return; } } gi.cprintf (ent, PRINT_MEDIUM, "No such menu: %s\n", fixedmenu); } } void vInitGame (void) { int i; ini_t ini; ini.pfile = NULL; if (OpenIniFile (IniPath (), &ini) == false) gi.dprintf ("Error opening ini file %s.\n", IniPath ()); for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].InitGame) xvotelist[i].DependsOn = xvotelist[i].InitGame (&ini); if (!xvotelist[i].DependsOn) xvotelist[i].DependsOn = deathmatch; } CloseIniFile (&ini); } void vExitGame (void) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].ExitGame) xvotelist[i].ExitGame (); } } void vInitLevel (void) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].InitLevel && xvotelist[i].DependsOn->value) xvotelist[i].InitLevel (); } } void vExitLevel (char *NextMap) { int i; for (i = 0; i < xvlistsize; i++) { // gi.dprintf("Checking %s\n", xvotelist[i].VoteTitle); if (xvotelist[i].ExitLevel && xvotelist[i].DependsOn->value) { // gi.dprintf("value ok.\n"); xvotelist[i].ExitLevel (NextMap); /* // first come, first serve.. if (NextMap[0]) return; */ } } } void vInitClient (edict_t * ent) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].InitClient && xvotelist[i].DependsOn->value) xvotelist[i].InitClient (ent); } } qboolean vClientConnect (edict_t * ent, char *userinfo) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].ClientConnect && xvotelist[i].DependsOn->value && xvotelist[i].ClientConnect (ent, userinfo) == false) return false; } return true; } void vClientDisconnect (edict_t * ent) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].ClientDisconnect && xvotelist[i].DependsOn->value) xvotelist[i].ClientDisconnect (ent); } } void vNewRound (void) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].NewRound && xvotelist[i].DependsOn->value) xvotelist[i].NewRound (); } } qboolean vCheckVote (void) { int i; for (i = 0; i < xvlistsize; i++) { if (xvotelist[i].CheckVote && xvotelist[i].DependsOn->value && xvotelist[i].CheckVote() == true) return true; } return false; } qboolean _vCommand (edict_t * ent, char *cmd, char *arg) { int i, j; for (i = 0; i < xvlistsize; i++) { // gi.dprintf("Checking %s\n", xvotelist[i].VoteTitle); if (xvotelist[i].DependsOn->value) { // gi.dprintf("value ok.\n"); j = 0; while (xvotelist[i].commands[j].cmd && j < VOTE_MAX_COMMANDS) { if (Q_stricmp (cmd, xvotelist[i].commands[j].cmd) == 0) { if (xvotelist[i].commands[j].cmdfunc) { xvotelist[i].commands[j].cmdfunc (ent, arg); return true; } } j++; } } } return false; } qboolean vCommand (edict_t * ent, char *cmd) { return _vCommand (ent, cmd, gi.args()); }
570
./aq2-tng/source/g_grapple.c
#include "g_local.h" /*------------------------------------------------------------------------*/ /* GRAPPLE */ /*------------------------------------------------------------------------*/ cvar_t *use_grapple; // ent is player void CTFPlayerResetGrapple(edict_t *ent) { if (ent->client && ent->client->ctf_grapple) CTFResetGrapple(ent->client->ctf_grapple); } // self is grapple, not player void CTFResetGrapple(edict_t *self) { if (self->owner->client->ctf_grapple) { float volume = 1.0; gclient_t *cl; if (self->owner->client->silencer_shots) volume = 0.2; gi.sound (self->owner, CHAN_RELIABLE+CHAN_WEAPON, gi.soundindex("weapons/grapple/grreset.wav"), volume, ATTN_NORM, 0); cl = self->owner->client; cl->ctf_grapple = NULL; cl->ctf_grapplereleasetime = level.time; cl->ctf_grapplestate = CTF_GRAPPLE_STATE_FLY; // we're firing, not on hook cl->ps.pmove.pm_flags &= ~PMF_NO_PREDICTION; G_FreeEdict(self); } } void CTFGrappleTouch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf) { float volume = 1.0; if (other == self->owner) return; if (self->owner->client->ctf_grapplestate != CTF_GRAPPLE_STATE_FLY) return; if (surf && (surf->flags & SURF_SKY)) { CTFResetGrapple(self); return; } VectorCopy(vec3_origin, self->velocity); PlayerNoise(self->owner, self->s.origin, PNOISE_IMPACT); if (other->takedamage) { T_Damage (other, self, self->owner, self->velocity, self->s.origin, plane->normal, self->dmg, 1, 0, MOD_GRAPPLE); CTFResetGrapple(self); return; } self->owner->client->ctf_grapplestate = CTF_GRAPPLE_STATE_PULL; // we're on hook self->enemy = other; self->solid = SOLID_NOT; if (self->owner->client->silencer_shots) volume = 0.2; gi.sound (self->owner, CHAN_RELIABLE+CHAN_WEAPON, gi.soundindex("weapons/grapple/grpull.wav"), volume, ATTN_NORM, 0); gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/grapple/grhit.wav"), volume, ATTN_NORM, 0); gi.WriteByte (svc_temp_entity); gi.WriteByte (TE_SPARKS); gi.WritePosition (self->s.origin); if (!plane) gi.WriteDir (vec3_origin); else gi.WriteDir (plane->normal); gi.multicast (self->s.origin, MULTICAST_PVS); } // draw beam between grapple and self void CTFGrappleDrawCable(edict_t *self) { vec3_t offset, start, end, f, r; vec3_t dir; float distance; AngleVectors (self->owner->client->v_angle, f, r, NULL); VectorSet(offset, 16, 16, self->owner->viewheight-8); P_ProjectSource (self->owner->client, self->owner->s.origin, offset, f, r, start); VectorSubtract(start, self->owner->s.origin, offset); VectorSubtract (start, self->s.origin, dir); distance = VectorLength(dir); // don't draw cable if close if (distance < 64) return; #if 0 if (distance > 256) return; // check for min/max pitch vectoangles (dir, angles); if (angles[0] < -180) angles[0] += 360; if (fabs(angles[0]) > 45) return; trace_t tr; //!! tr = gi.trace (start, NULL, NULL, self->s.origin, self, MASK_SHOT); if (tr.ent != self) { CTFResetGrapple(self); return; } #endif // adjust start for beam origin being in middle of a segment // VectorMA (start, 8, f, start); VectorCopy (self->s.origin, end); // adjust end z for end spot since the monster is currently dead // end[2] = self->absmin[2] + self->size[2] / 2; gi.WriteByte (svc_temp_entity); #if 1 //def USE_GRAPPLE_CABLE gi.WriteByte (TE_GRAPPLE_CABLE); gi.WriteShort (self->owner - g_edicts); gi.WritePosition (self->owner->s.origin); gi.WritePosition (end); gi.WritePosition (offset); #else gi.WriteByte (TE_MEDIC_CABLE_ATTACK); gi.WriteShort (self - g_edicts); gi.WritePosition (end); gi.WritePosition (start); #endif gi.multicast (self->s.origin, MULTICAST_PVS); } void SV_AddGravity (edict_t *ent); // pull the player toward the grapple void CTFGrapplePull(edict_t *self) { vec3_t hookdir, v; float vlen; if (strcmp(self->owner->client->pers.weapon->classname, "weapon_grapple") == 0 && !self->owner->client->newweapon && self->owner->client->weaponstate != WEAPON_FIRING && self->owner->client->weaponstate != WEAPON_ACTIVATING) { CTFResetGrapple(self); return; } if (self->enemy) { if (self->enemy->solid == SOLID_NOT) { CTFResetGrapple(self); return; } if (self->enemy->solid == SOLID_BBOX) { VectorScale(self->enemy->size, 0.5, v); VectorAdd(v, self->enemy->s.origin, v); VectorAdd(v, self->enemy->mins, self->s.origin); gi.linkentity (self); } else VectorCopy(self->enemy->velocity, self->velocity); if (self->enemy->takedamage && !CheckTeamDamage (self->enemy, self->owner)) { float volume = 1.0; if (self->owner->client->silencer_shots) volume = 0.2; T_Damage (self->enemy, self, self->owner, self->velocity, self->s.origin, vec3_origin, 1, 1, 0, MOD_GRAPPLE); gi.sound (self, CHAN_WEAPON, gi.soundindex("weapons/grapple/grhurt.wav"), volume, ATTN_NORM, 0); } if (self->enemy->deadflag) { // he died CTFResetGrapple(self); return; } } CTFGrappleDrawCable(self); if (self->owner->client->ctf_grapplestate > CTF_GRAPPLE_STATE_FLY) { // pull player toward grapple // this causes icky stuff with prediction, we need to extend // the prediction layer to include two new fields in the player // move stuff: a point and a velocity. The client should add // that velociy in the direction of the point vec3_t forward, up; AngleVectors (self->owner->client->v_angle, forward, NULL, up); VectorCopy(self->owner->s.origin, v); v[2] += self->owner->viewheight; VectorSubtract (self->s.origin, v, hookdir); vlen = VectorLength(hookdir); if (self->owner->client->ctf_grapplestate == CTF_GRAPPLE_STATE_PULL && vlen < 64) { float volume = 1.0; if (self->owner->client->silencer_shots) volume = 0.2; self->owner->client->ps.pmove.pm_flags |= PMF_NO_PREDICTION; gi.sound (self->owner, CHAN_RELIABLE+CHAN_WEAPON, gi.soundindex("weapons/grapple/grhang.wav"), volume, ATTN_NORM, 0); self->owner->client->ctf_grapplestate = CTF_GRAPPLE_STATE_HANG; } VectorNormalize (hookdir); VectorScale(hookdir, CTF_GRAPPLE_PULL_SPEED, hookdir); VectorCopy(hookdir, self->owner->velocity); SV_AddGravity(self->owner); } } void CTFFireGrapple (edict_t *self, vec3_t start, vec3_t dir, int damage, int speed, int effect) { edict_t *grapple; trace_t tr; VectorNormalize (dir); grapple = G_Spawn(); VectorCopy (start, grapple->s.origin); VectorCopy (start, grapple->s.old_origin); vectoangles (dir, grapple->s.angles); VectorScale (dir, speed, grapple->velocity); grapple->movetype = MOVETYPE_FLYMISSILE; grapple->clipmask = MASK_SHOT; grapple->solid = SOLID_BBOX; grapple->s.effects |= effect; VectorClear (grapple->mins); VectorClear (grapple->maxs); grapple->s.modelindex = gi.modelindex ("models/weapons/grapple/hook/tris.md2"); // grapple->s.sound = gi.soundindex ("misc/lasfly.wav"); grapple->owner = self; grapple->touch = CTFGrappleTouch; // grapple->nextthink = level.time + FRAMETIME; // grapple->think = CTFGrappleThink; grapple->dmg = damage; self->client->ctf_grapple = grapple; self->client->ctf_grapplestate = CTF_GRAPPLE_STATE_FLY; // we're firing, not on hook gi.linkentity (grapple); tr = gi.trace (self->s.origin, NULL, NULL, grapple->s.origin, grapple, MASK_SHOT); if (tr.fraction < 1.0) { VectorMA (grapple->s.origin, -10, dir, grapple->s.origin); grapple->touch (grapple, tr.ent, NULL, NULL); } } void CTFGrappleFire (edict_t *ent, vec3_t g_offset, int damage, int effect) { vec3_t forward, right; vec3_t start; vec3_t offset; vec3_t velocity; float volume = 1.0; float speed; if (ent->client->ctf_grapplestate > CTF_GRAPPLE_STATE_FLY) return; // it's already out AngleVectors (ent->client->v_angle, forward, right, NULL); // VectorSet(offset, 24, 16, ent->viewheight-8+2); VectorSet(offset, 24, 8, ent->viewheight-8+2); VectorAdd (offset, g_offset, offset); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -1; if (ent->client->silencer_shots) volume = 0.2; gi.sound (ent, CHAN_RELIABLE+CHAN_WEAPON, gi.soundindex("weapons/grapple/grfire.wav"), volume, ATTN_NORM, 0); // hifi: adjust grapple speed speed = CTF_GRAPPLE_SPEED; if(use_grapple->value > 1) { VectorCopy(ent->velocity, velocity); speed += VectorNormalize(velocity)/2; } CTFFireGrapple (ent, start, forward, damage, speed, effect); #if 0 // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_BLASTER); gi.multicast (ent->s.origin, MULTICAST_PVS); #endif PlayerNoise(ent, start, PNOISE_WEAPON); } void CTFWeapon_Grapple_Fire (edict_t *ent) { int damage; damage = 10; CTFGrappleFire (ent, vec3_origin, damage, 0); ent->client->ps.gunframe++; } void CTFWeapon_Grapple (edict_t *ent) { static int pause_frames[] = {10, 18, 27, 0}; static int fire_frames[] = {6, 0}; int prevstate; // if the the attack button is still down, stay in the firing frame if ((ent->client->buttons & BUTTON_ATTACK) && ent->client->weaponstate == WEAPON_FIRING && ent->client->ctf_grapple) ent->client->ps.gunframe = 9; if (!(ent->client->buttons & BUTTON_ATTACK) && ent->client->ctf_grapple) { CTFResetGrapple(ent->client->ctf_grapple); if (ent->client->weaponstate == WEAPON_FIRING) ent->client->weaponstate = WEAPON_READY; } if (ent->client->newweapon && ent->client->ctf_grapplestate > CTF_GRAPPLE_STATE_FLY && ent->client->weaponstate == WEAPON_FIRING) { // he wants to change weapons while grappled ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 32; } prevstate = ent->client->weaponstate; Weapon_Generic (ent, 5, 9, 31, 36, 0, 0, pause_frames, fire_frames, CTFWeapon_Grapple_Fire); // if we just switched back to grapple, immediately go to fire frame if (prevstate == WEAPON_ACTIVATING && ent->client->weaponstate == WEAPON_READY && ent->client->ctf_grapplestate > CTF_GRAPPLE_STATE_FLY) { if (!(ent->client->buttons & BUTTON_ATTACK)) ent->client->ps.gunframe = 9; else ent->client->ps.gunframe = 5; ent->client->weaponstate = WEAPON_FIRING; } }
571
./aq2-tng/source/a_xgame.c
//----------------------------------------------------------------------------- // PG BUND // a_xgame.c // // this module contains all new and changed functions from a_game.c // // REMARKS: // -------- // 1. You have to comment the original ParseSayText in // a_game.c completly out. // 2. Look for the DELETEIT comment. All comments // regarding DELETEIT are *not* really neccesary. // They were done because of my compiler (caused // compiling errors), and not because of functionality! // Try first to de-comment the DELETEIT sections, if // you get compiler errors too, comment them out like // I'd done. // // $Id: a_xgame.c,v 1.19 2004/04/08 23:19:51 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: a_xgame.c,v $ // Revision 1.19 2004/04/08 23:19:51 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.18 2003/12/09 20:54:16 igor_rock // Say: added %M for teammate in line of sight (as %E does for enemies) // // Revision 1.17 2002/02/19 10:28:43 freud // Added to %D hit in the kevlar vest and kevlar helmet, also body for handcannon // and shotgun. // // Revision 1.16 2002/02/18 13:55:35 freud // Added last damaged players %P // // Revision 1.15 2001/12/24 18:06:05 slicerdw // changed dynamic check for darkmatch only // // Revision 1.13 2001/12/09 14:02:11 slicerdw // Added gl_clear check -> video_check_glclear cvar // // Revision 1.12 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.11 2001/07/16 19:02:06 ra // Fixed compilerwarnings (-g -Wall). Only one remains. // // Revision 1.10 2001/06/25 11:44:47 slicerdw // New Video Check System - video_check and video_check_lockpvs no longer latched // // Revision 1.9 2001/06/21 00:05:30 slicerdw // New Video Check System done - might need some revision but works.. // // Revision 1.6 2001/06/19 18:56:38 deathwatch // New Last killed target system // // Revision 1.5 2001/05/20 15:00:19 slicerdw // Some minor fixes and changings on Video Checking system // // Revision 1.4 2001/05/11 12:21:18 slicerdw // Commented old Location support ( ADF ) With the ML/ETE Compatible one // // Revision 1.2 2001/05/07 21:18:34 slicerdw // Added Video Checking System // // Revision 1.1.1.1 2001/05/06 17:25:24 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" extern edict_t *DetermineViewedTeammate (edict_t * ent); /* Defined in a_radio.c */ //the whole map description //mapdesc_t mapdesc; //TempFile BEGIN //mapdescex_t mapdescex; AQ2:TNG - Slicer old location support, commented. /* support for .pg dropped 7/26/1999 int LoadPG(char *mapname) { FILE *pntlist; char buf[1024]; int i = 0; int j, bs; memset(&mapdesc, 0, sizeof(mapdesc)); sprintf(buf, "%s/maps/%s%s", GAMEVERSION, mapname, PG_LOCEXT); pntlist = fopen(buf, "r"); if (pntlist == NULL) { gi.dprintf("Warning: No location file for map %s\n", mapname); return 0; } while(fgets(buf, 1000, pntlist) != NULL) { //first remove trailing spaces for (bs = strlen(buf); bs > 0 && (buf[bs-1] == '\r' || buf[bs-1] == '\n' || buf[bs-1] == ' '); bs--) buf[bs-1] = '\0'; //check if it's a valid line if (bs > 0 && strncmp(buf, "#", 1) != 0 && strncmp(buf, "//", 2) != 0) { //a little bit dirty... :) sscanf(buf, "%f %f %f", &mapdesc[i].pos[0], &mapdesc[i].pos[1], &mapdesc[i].pos[2]); j = 0; for (bs = 0; bs <= strlen(buf) && j < 3; bs++) if (buf[bs] == ' ') j++; j = 0; while ((bs < strlen(buf)) && (j < LOC_STR_LEN-1)) mapdesc[i].desc[j++] = buf[bs++]; mapdesc[i].desc[LOC_STR_LEN-1] = '\0'; //max points reached? if (++i >= LOC_MAX_POINTS) { gi.dprintf("Warning: More than %i locations.\n", LOC_MAX_POINTS); break; } } } return i; } */ //initializes mapdesc, read a location file if available // modified by TempFile to support ADF format, see adf.txt //TempFile //FixCubeData() ensures that lower left is actually in the lower left //Called in DescListInit() and Cmd_AddCube_f() //AQ2:TNG Slicer commenting old location file support ( ADF ) /* int num_loccubes = 0; void FixCubeData (loccube_t * cube) { float tmp; int i; char *dimensions[3] = {"X", "Y", "Z"}; for (i = 0; i < 3; i++) { if (cube->lowerleft[i] > cube->upperright[i]) { //flip the two values tmp = cube->lowerleft[i]; cube->lowerleft[i] = cube->upperright[i]; cube->upperright[i] = tmp; } else if (cube->lowerleft[i] == cube->upperright[i]) { //an infinitely thin cube - no, that's not our style. cube->lowerleft[i] -= 10; //print a warning, those corrupted files aren't good. gi.dprintf ("WARNING: Infinitely small %s dimension in area cube %s detected.\n" "LOWERLEFT value decremented by 10.\n", dimensions[i], cube->desc); } } } void DescListInit (char *mapname) { FILE *pntlist; char buf[1024]; int i = 0; int j, bs; int num = 0; num_loccubes = 0; memset (&mapdescex, 0, sizeof (mapdescex)); sprintf (buf, "%s/location/%s%s", GAMEVERSION, mapname, PG_LOCEXTEX); pntlist = fopen (buf, "r"); if (!pntlist) { gi.dprintf ("Warning: No area definition file for map %s.\n", mapname); return; } while (fgets (buf, 1000, pntlist) != NULL) { //first remove trailing spaces for (bs = strlen (buf); bs > 0 && (buf[bs - 1] == '\r' || buf[bs - 1] == '\n' || buf[bs - 1] == ' '); bs--) buf[bs - 1] = '\0'; //check if it's a valid line if (bs > 0 && strncmp (buf, "#", 1) != 0 && strncmp (buf, "//", 2) != 0) { //a little bit dirty... :) sscanf (buf, "<%f %f %f> <%f %f %f>", &mapdescex[i].lowerleft[0], &mapdescex[i].lowerleft[1], &mapdescex[i].lowerleft[2], &mapdescex[i].upperright[0], &mapdescex[i].upperright[1], &mapdescex[i].upperright[2]); j = 0; for (bs = 0; bs <= strlen (buf) && j < 6; bs++) if (buf[bs] == ' ') j++; j = 0; while ((bs < strlen (buf)) && (j < LOC_STR_LEN - 1)) mapdescex[i].desc[j++] = buf[bs++]; mapdescex[i].desc[LOC_STR_LEN - 1] = '\0'; FixCubeData (&(mapdescex[i])); //max points reached? if (++i >= LOC_MAX_POINTS) { gi.dprintf ("Warning: More than %i locations.\n", LOC_MAX_POINTS); break; } } } if (!num) num = num_loccubes = i; fclose (pntlist); gi.dprintf ("%i map location%s read.\n", num, (num != 1) ? "s" : ""); } //returns wether mapdesc is empty or not qboolean DescListIsEmpty (void) { //if(using_mapdescex) //TempFile if (!*mapdescex[0].desc) return true; //if (!*mapdesc[0].desc) return true; return false; } //returns nearest description point. if < 0, no point is available. //before calling this function, check if mapdesc is empty via DescListIsEmpty(). //AQ:TNG - JBravo changed next line not to be a C style comment. // If this code is ever uncommented this must be fixed. / * see new function DescListCube() int DescListNearestPoint(vec3_t origin, vec_t *distance) { int i,j; vec_t dist, lowest; vec3_t line; j = -1; lowest = 10000.0; for (i = 0; i < LOC_MAX_POINTS; i++) { //any point without desc will not be recognized if (*mapdesc[i].desc) { VectorSubtract(mapdesc[i].pos, origin, line); dist = VectorLength(line); if (dist < lowest) { j = i; lowest = dist; } } } if (j >= 0) *distance = dist; else *distance = 0.0; return j; } //returns the index of the first found cube a point is located in. //if < 0, no cube was found. int DescListCube (vec3_t origin) { int i; loccube_t *cube; for (i = 0; i < num_loccubes; i++) { cube = &(mapdescex[i]); if ((cube->lowerleft[0] < origin[0]) && (cube->lowerleft[1] < origin[1]) && (cube->lowerleft[2] < origin[2]) && (cube->upperright[0] >= origin[0]) && (cube->upperright[1] >= origin[1]) && (cube->upperright[2] >= origin[2])) return i; } return -1; } //if a description is available, it'll be copied to buf and true is returned //else false is returned and buf remains unchanged. qboolean GetPositionText (vec3_t origin, char *buf) { int i; char firstword[64]; buf[0] = 0; // just for safety if (DescListIsEmpty () == false) { //i = DescListNearestPoint(origin, &dist); i = DescListCube (origin); if (i >= 0) { //TempFile - cool preposition detection sscanf (mapdescex[i].desc, "%s", firstword); if (Q_stricmp (firstword, "near") && Q_stricmp (firstword, "at") && Q_stricmp (firstword, "by") && Q_stricmp (firstword, "close") && Q_stricmp (firstword, "over") && Q_stricmp (firstword, "under") && Q_stricmp (firstword, "above") && Q_stricmp (firstword, "inside") && Q_stricmp (firstword, "outside") && Q_stricmp (firstword, "in") && // also "in front of..." Q_stricmp (firstword, "next") && // "next to..." Q_stricmp (firstword, "behind") && Q_stricmp (firstword, "on") && Q_stricmp (firstword, "down") && Q_stricmp (firstword, "up")) // enough? strcpy (buf, "near "); //AQ:TNG - JBravo changed next line not to be a C style comment. // If this code is ever uncommented this must be fixed. / *if(abs((int)(origin[2] - mapdesc[i].pos[2])) > 350) // TF - z limit to avoid level confusion return false; // removed, Z check is no longer needed with cubes strcat (buf, mapdescex[i].desc); return true; } } return false; } // TempFile END AQ2:TNG END */ // DetermineViewedEnemy: determine the current player you're viewing (only looks for live Enemy) // Modified from DetermineViewedTeammate (which is used in a_radio.c) edict_t *DetermineViewedEnemy (edict_t * ent) { vec3_t forward, dir; trace_t tr; edict_t *who, *best; float bd = 0, d; int i; AngleVectors (ent->client->v_angle, forward, NULL, NULL); VectorScale (forward, 8192, forward); VectorAdd (ent->s.origin, forward, forward); PRETRACE (); tr = gi.trace (ent->s.origin, NULL, NULL, forward, ent, MASK_SOLID); POSTTRACE (); if (tr.fraction < 1 && tr.ent && tr.ent->client) { return NULL; } AngleVectors (ent->client->v_angle, forward, NULL, NULL); best = NULL; for (i = 1; i <= maxclients->value; i++) { who = g_edicts + i; if (!who->inuse) continue; VectorSubtract (who->s.origin, ent->s.origin, dir); VectorNormalize (dir); d = DotProduct (forward, dir); if (d > bd && loc_CanSee (ent, who) && who->solid != SOLID_NOT && who->deadflag != DEAD_DEAD && !OnSameTeam (who, ent)) { bd = d; best = who; } } if (bd > 0.90) return best; return NULL; } //AQ2:TNG Slicer old location support ( ADF ) /* void GetViewedPosition (edict_t * ent, char *buf) { vec3_t forward, rel_pos; int rel_xy_pos; trace_t tr; AngleVectors (ent->client->v_angle, forward, NULL, NULL); VectorScale (forward, 8192, forward); VectorAdd (ent->s.origin, forward, forward); PRETRACE (); tr = gi.trace (ent->s.origin, NULL, NULL, forward, ent, MASK_ALL); POSTTRACE (); if (tr.fraction >= 1.0) { //gi.cprintf(ent, PRINT_HIGH, "GetViewedPosition: fraction >= 1.0\n"); strcpy (buf, "somewhere"); return; } if (GetPositionText (tr.endpos, buf) == false) { //creating relative vector from origin to destination VectorSubtract (ent->s.origin, tr.endpos, rel_pos); rel_xy_pos = 0; //checking bounds, if one direction is less than half the other, it may //be ignored... if (fabs (rel_pos[0]) > (fabs (rel_pos[1]) * 2)) //x width (EAST, WEST) is twice greater than y width (NORTH, SOUTH) rel_pos[1] = 0.0; if (fabs (rel_pos[1]) > (fabs (rel_pos[0]) * 2)) //y width (NORTH, SOUTH) is twice greater than x width (EAST, WEST) rel_pos[0] = 0.0; if (rel_pos[1] > 0.0) rel_xy_pos |= RP_NORTH; else if (rel_pos[1] < 0.0) rel_xy_pos |= RP_SOUTH; if (rel_pos[0] > 0.0) rel_xy_pos |= RP_EAST; else if (rel_pos[0] < 0.0) rel_xy_pos |= RP_WEST; //creating the text message, regarding to rel_xy_pos strcpy (buf, "in the "); if (rel_xy_pos & RP_NORTH) strcat (buf, "north"); if (rel_xy_pos & RP_SOUTH) strcat (buf, "south"); if (rel_xy_pos & RP_EAST) strcat (buf, "east"); if (rel_xy_pos & RP_WEST) strcat (buf, "west"); //gi.dprintf ("rel_xy_pos: %i\n", rel_xy_pos); //last but not least, the height, limit for up/down: 64 if (fabs (rel_pos[2]) > 64.0) { if (rel_pos[2] < 0.0) strcat (buf, ", up"); else strcat (buf, ", down"); } else strcat (buf, ", same height"); } } void GetOwnPosition (edict_t * self, char *buf) { if (GetPositionText (self->s.origin, buf) == false) { strcpy (buf, "somewhere"); } } void GetEnemyPosition (edict_t * self, char *buf) { edict_t *the_enemy; vec3_t rel_pos; int rel_xy_pos; the_enemy = DetermineViewedEnemy (self); if (the_enemy && the_enemy->client) { if (GetPositionText (the_enemy->s.origin, buf) == false) { //creating relative vector from origin to destination VectorSubtract (self->s.origin, the_enemy->s.origin, rel_pos); rel_xy_pos = 0; //checking bounds, if one direction is less than half the other, it may //be ignored... if (fabs (rel_pos[0]) > (fabs (rel_pos[1]) * 2)) //x width (EAST, WEST) is twice greater than y width (NORTH, SOUTH) rel_pos[1] = 0.0; if (fabs (rel_pos[1]) > (fabs (rel_pos[0]) * 2)) //y width (NORTH, SOUTH) is twice greater than x width (EAST, WEST) rel_pos[0] = 0.0; if (rel_pos[1] > 0.0) rel_xy_pos |= RP_NORTH; else if (rel_pos[1] < 0.0) rel_xy_pos |= RP_SOUTH; if (rel_pos[0] > 0.0) rel_xy_pos |= RP_EAST; else if (rel_pos[0] < 0.0) rel_xy_pos |= RP_WEST; //creating the text message, regarding to rel_xy_pos strcpy (buf, "in the "); if (rel_xy_pos & RP_NORTH) strcat (buf, "north"); if (rel_xy_pos & RP_SOUTH) strcat (buf, "south"); if (rel_xy_pos & RP_EAST) strcat (buf, "east"); if (rel_xy_pos & RP_WEST) strcat (buf, "west"); //gi.dprintf ("rel_xy_pos: %i\n", rel_xy_pos); //last but not least, the height of enemy, limit for up/down: 64 if (fabs (rel_pos[2]) > 64.0) { if (rel_pos[2] < 0.0) strcat (buf, ", above me"); else strcat (buf, ", under me"); } else strcat (buf, ", on the same level"); } } else { strcpy (buf, "somewhere"); } } */ //AQ2:TNG END void GetViewedEnemyName (edict_t * self, char *buf) { edict_t *the_enemy; the_enemy = DetermineViewedEnemy (self); if (the_enemy && the_enemy->client) strcpy (buf, the_enemy->client->pers.netname); else strcpy (buf, "no enemy"); } void GetViewedTeammateName (edict_t * self, char *buf) { edict_t *the_teammate; the_teammate = DetermineViewedTeammate (self); if (the_teammate && the_teammate->client) strcpy (buf, the_teammate->client->pers.netname); else strcpy (buf, "no teammate"); } void GetViewedEnemyWeapon (edict_t * self, char *buf) { edict_t *the_enemy; the_enemy = DetermineViewedEnemy (self); if (the_enemy && the_enemy->client) strcpy (buf, the_enemy->client->pers.weapon->pickup_name); else strcpy (buf, "no weapon"); } //AQ2:TNG SLICER Old support /* void GetLastKilledTarget (edict_t * self, char *buf) { if (self->client->resp.last_killed_target) { strcpy (buf, self->client->resp.last_killed_target->client->pers.netname); //We want to report...ONCE! :) self->client->resp.last_killed_target = NULL; } else { strcpy (buf, "nobody"); } } */ //AQ2:TNG END char *SeekBufEnd (char *buf) { while (*buf != 0) buf++; return buf; } void ParseSayText (edict_t * ent, char *text, size_t size) { char buf[PARSE_BUFSIZE + 256] = "\0"; //Parsebuf + chatpuf size char *p, *pbuf; p = text; pbuf = buf; while (*p != 0) { if (*p == '%') { switch (*(p + 1)) { case 'H': GetHealth (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'A': GetAmmo (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'W': GetWeaponName (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'I': GetItemName (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'T': GetNearbyTeammates (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'M': GetViewedTeammateName (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'E': GetViewedEnemyName (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'F': GetViewedEnemyWeapon (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'G': GetEnemyPosition (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'K': GetLastKilledTarget (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; //AQ2:TNG Slicer - New Location Code /* case 'L': GetOwnPosition (ent, infobuf); strcpy (pbuf, infobuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'S': GetViewedPosition (ent, infobuf); strcpy (pbuf, infobuf); pbuf = SeekBufEnd (pbuf); p += 2; break; */ case 'S': GetSightedLocation (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; case 'L': GetPlayerLocation (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; //AQ2:TNG Slicer Last Damage Location case 'D': GetLastDamagedPart (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; //AQ2:TNG END //AQ2:TNG Freud Last Player Damaged case 'P': GetLastDamagedPlayers (ent, pbuf); pbuf = SeekBufEnd (pbuf); p += 2; break; //AQ2:TNG END default: *pbuf++ = *p++; break; } } else { *pbuf++ = *p++; } if (buf[size-1]) { buf[size-1] = 0; break; } } *pbuf = 0; strcpy(text, buf); } // AQ2:TNG - Slicer Video Checks //float next_cheat_check; /* =========== VideoCheckClient =========== */ void VideoCheckClient (edict_t * ent) { if (!ent->client->resp.vidref) return; if (video_check_lockpvs->value) { if (ent->client->resp.gllockpvs != 0) { gi.cprintf (ent, PRINT_HIGH, "This server does not allow using that value for gl_lockpvs, set it to '0'\n"); gi.bprintf (PRINT_HIGH, "%s was using an illegal setting\n", ent->client->pers.netname); Kick_Client (ent); return; } } if (video_check_glclear->value) { if (ent->client->resp.glclear != 0) { gi.cprintf (ent, PRINT_HIGH, "This server does not allow using that value for gl_clear, set it to '0'\n"); gi.bprintf (PRINT_HIGH, "%s was using an illegal setting\n", ent->client->pers.netname); Kick_Client (ent); return; } } if (darkmatch->value) { if (ent->client->resp.gldynamic !=1) { gi.cprintf (ent, PRINT_HIGH, "This server does not allow using that value for gl_dynamic, set it to '1'\n"); gi.bprintf (PRINT_HIGH, "%s was using an illegal setting\n", ent->client->pers.netname); Kick_Client (ent); return; } } //Starting Modulate checks if(video_check->value) { if (Q_stricmp (ent->client->resp.gldriver, "3dfxgl") == 0) { if (ent->client->resp.glmodulate > video_max_3dfx->value) { gi.cprintf (ent, PRINT_HIGH, "Your gl_modulate value is too high for this server. Max Allowed is %.1f\n", video_max_3dfx->value); gi.bprintf (PRINT_HIGH, "%s is using a gl_modulated higher than allowed (%.1f)\n", ent->client->pers.netname, ent->client->resp.glmodulate); Kick_Client (ent); return; } return; } if (Q_stricmp (ent->client->resp.gldriver, "opengl32") == 0) { if (ent->client->resp.glmodulate > video_max_opengl->value) { gi.cprintf (ent, PRINT_HIGH, "Your gl_modulate value is too high for this server. Max Allowed is %.1f\n", video_max_opengl->value); gi.bprintf (PRINT_HIGH, "%s is using a gl_modulate higher than allowed (%.1f)\n", ent->client->pers.netname, ent->client->resp.glmodulate); Kick_Client (ent); return; } return; } if (Q_stricmp (ent->client->resp.gldriver, "3dfxglam") == 0) { if (ent->client->resp.glmodulate > video_max_3dfxam->value) { gi.cprintf (ent, PRINT_HIGH, "Your gl_modulate value is too high for this server. Max Allowed is %.1f\n", video_max_3dfxam->value); gi.bprintf (PRINT_HIGH, "%s is using a gl_modulate higher than allowed (%.1f)\n", ent->client->pers.netname, ent->client->resp.glmodulate); Kick_Client (ent); return; } return; } if (ent->client->resp.glmodulate > video_max_opengl->value) { gi.cprintf (ent, PRINT_HIGH, "Your gl_modulate value is too high for this server. Max Allowed is %.1f\n", video_max_opengl->value); gi.bprintf (PRINT_HIGH, "%s is using a gl_modulate higher than allowed (%.1f)\n", ent->client->pers.netname, ent->client->resp.glmodulate); Kick_Client (ent); return; } } } //AQ2:TNG - Slicer : Last Damage Location void GetLastDamagedPart (edict_t * self, char *buf) { switch(self->client->resp.last_damaged_part) { case LOC_HDAM: strcpy (buf, "head"); break; case LOC_CDAM: strcpy (buf, "chest"); break; case LOC_SDAM: strcpy (buf, "stomach"); break; case LOC_LDAM: strcpy (buf, "legs"); break; case LOC_KVLR_HELMET: strcpy (buf, "kevlar helmet"); break; case LOC_KVLR_VEST: strcpy (buf, "kevlar vest"); break; case LOC_NO: strcpy (buf, "body"); break; default: strcpy (buf, "nothing"); break; } self->client->resp.last_damaged_part = 0; } //AQ2:TNG END //AQ2:TNG add last damaged players - Freud void GetLastDamagedPlayers (edict_t * self, char *buf) { if (self->client->resp.last_damaged_players[0] == '\0') strcpy(buf, "nobody"); else Q_strncpyz(buf, self->client->resp.last_damaged_players, PARSE_BUFSIZE); self->client->resp.last_damaged_players[0] = '\0'; } // Gets the location string of a location (xo,yo,zo) // Modifies the the location areas by value of "mod" // in the coord-inside-area tests // qboolean GetLocation (int xo, int yo, int zo, int mod, char *buf) { int count; int lx, ly, lz, rlx, rly, rlz; count = ml_count; while (count--) { // get next location from location base lx = locationbase[count].x; ly = locationbase[count].y; lz = locationbase[count].z; rlx = locationbase[count].rx; rly = locationbase[count].ry; rlz = locationbase[count].rz; // Default X-range 1500 if (!rlx) rlx = 1500; // Default Y-range 1500 if (!rly) rly = 1500; // Test if the (xo,yo,zo) is inside the location if (xo >= lx - rlx - mod && xo <= lx + rlx - mod && yo >= ly - rly - mod && yo <= ly + rly - mod) { if (rlz && (zo < lz - rlz - mod || zo > lz + rlz + mod)) continue; strcpy (buf, locationbase[count].desc); return true; } } strcpy (buf, "around"); return false; } // Get the player location // qboolean GetPlayerLocation (edict_t * self, char *buf) { if (GetLocation((int)self->s.origin[0], (int)self->s.origin[1], (int)self->s.origin[2], 0, buf)) return true; return false; } // Get the sighted location // void GetSightedLocation (edict_t * self, char *buf) { vec3_t start, forward, right, end, up, offset; trace_t tr; AngleVectors (self->client->v_angle, forward, right, up); VectorSet (offset, 24, 8, self->viewheight); P_ProjectSource (self->client, self->s.origin, offset, forward, right, start); VectorMA (start, 8192, forward, end); PRETRACE (); tr = gi.trace (start, NULL, NULL, end, self, CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_DEADMONSTER); POSTTRACE (); GetLocation((int)tr.endpos[0], (int)tr.endpos[1], (int)tr.endpos[2], 10, buf); } void GetEnemyPosition (edict_t * self, char *buf) { edict_t *the_enemy; vec3_t rel_pos; int rel_xy_pos; the_enemy = DetermineViewedEnemy (self); if (the_enemy && the_enemy->client) { if (GetPlayerLocation (the_enemy, buf)) return; //creating relative vector from origin to destination VectorSubtract (self->s.origin, the_enemy->s.origin, rel_pos); rel_xy_pos = 0; //checking bounds, if one direction is less than half the other, it may //be ignored... if (fabs (rel_pos[0]) > (fabs (rel_pos[1]) * 2)) //x width (EAST, WEST) is twice greater than y width (NORTH, SOUTH) rel_pos[1] = 0.0; if (fabs (rel_pos[1]) > (fabs (rel_pos[0]) * 2)) //y width (NORTH, SOUTH) is twice greater than x width (EAST, WEST) rel_pos[0] = 0.0; if (rel_pos[1] > 0.0) rel_xy_pos |= RP_NORTH; else if (rel_pos[1] < 0.0) rel_xy_pos |= RP_SOUTH; if (rel_pos[0] > 0.0) rel_xy_pos |= RP_EAST; else if (rel_pos[0] < 0.0) rel_xy_pos |= RP_WEST; //creating the text message, regarding to rel_xy_pos strcpy (buf, "in the "); if (rel_xy_pos & RP_NORTH) strcat (buf, "north"); if (rel_xy_pos & RP_SOUTH) strcat (buf, "south"); if (rel_xy_pos & RP_EAST) strcat (buf, "east"); if (rel_xy_pos & RP_WEST) strcat (buf, "west"); //gi.dprintf ("rel_xy_pos: %i\n", rel_xy_pos); //last but not least, the height of enemy, limit for up/down: 64 if (fabs (rel_pos[2]) > 64.0) { if (rel_pos[2] < 0.0) strcat (buf, ", above me"); else strcat (buf, ", under me"); } else strcat (buf, ", on the same level"); } else { strcpy (buf, "somewhere"); } } //AQ2:TNG END //AQ2:TNG Slicer - New last killed target functions //SLIC2 Optimizations void ResetKills (edict_t * ent) { int i; for (i = 0; i < MAX_LAST_KILLED; i++) ent->client->resp.last_killed_target[i] = NULL; } int ReadKilledPlayers (edict_t * ent) { int results = 0; int i; for (i = 0; i < MAX_LAST_KILLED; i++) { if (!ent->client->resp.last_killed_target[i]) break; results++; } return results; } void AddKilledPlayer (edict_t * self, edict_t * ent) { int kills; kills = ReadKilledPlayers (self); self->client->resp.last_killed_target[kills % MAX_LAST_KILLED] = ent; } void GetLastKilledTarget (edict_t * self, char *buf) { int kills, i; kills = ReadKilledPlayers (self); if (!kills) { strcpy (buf, "nobody"); return; } strcpy (buf, self->client->resp.last_killed_target[0]->client->pers.netname); for (i = 1; i < kills; i++) { if (i == kills - 1) Q_strncatz(buf, " and ", PARSE_BUFSIZE); else Q_strncatz(buf, ", ", PARSE_BUFSIZE); Q_strncatz(buf, self->client->resp.last_killed_target[i]->client-> pers.netname, PARSE_BUFSIZE); } ResetKills (self); }
572
./aq2-tng/source/g_func.c
//----------------------------------------------------------------------------- // g_func.c // // $Id: g_func.c,v 1.5 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_func.c,v $ // Revision 1.5 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.4 2001/06/15 14:18:07 igor_rock // corrected bug with destroyed flags (won't be destroyed anymore, instead they // return to the base). // // Revision 1.3 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.2.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.2 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.1.1.1 2001/05/06 17:31:10 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" /* ========================================================= PLATS movement options: linear smooth start, hard stop smooth start, smooth stop start end acceleration speed deceleration begin sound end sound target fired when reaching end wait at end object characteristics that use move segments --------------------------------------------- movetype_push, or movetype_stop action when touched action when blocked action when used disabled? auto trigger spawning ========================================================= */ #define PLAT_LOW_TRIGGER 1 #define STATE_TOP 0 #define STATE_BOTTOM 1 #define STATE_UP 2 #define STATE_DOWN 3 #define DOOR_START_OPEN 1 #define DOOR_REVERSE 2 #define DOOR_CRUSHER 4 #define DOOR_NOMONSTER 8 #define DOOR_TOGGLE 32 #define DOOR_X_AXIS 64 #define DOOR_Y_AXIS 128 // zucc function to deal with special items that might get destroyed void Handle_Unique_Items (edict_t * ent) { if (!ent->item) return; switch(ent->item->typeNum) { case MP5_NUM: case M4_NUM: case M3_NUM: case HC_NUM: case SNIPER_NUM: ThinkSpecWeap (ent); break; case SIL_NUM: case SLIP_NUM: case BAND_NUM: case KEV_NUM: case HELM_NUM: case LASER_NUM: RespawnSpec (ent); break; } } // // Support routines for movement (changes in origin using velocity) // void Move_Done (edict_t * ent) { VectorClear (ent->velocity); ent->moveinfo.endfunc (ent); } void Move_Final (edict_t * ent) { if (ent->moveinfo.remaining_distance == 0) { Move_Done (ent); return; } VectorScale (ent->moveinfo.dir, ent->moveinfo.remaining_distance / FRAMETIME, ent->velocity); ent->think = Move_Done; ent->nextthink = level.time + FRAMETIME; } void Move_Begin (edict_t * ent) { float frames; if ((ent->moveinfo.speed * FRAMETIME) >= ent->moveinfo.remaining_distance) { Move_Final (ent); return; } VectorScale (ent->moveinfo.dir, ent->moveinfo.speed, ent->velocity); frames = floor ((ent->moveinfo.remaining_distance / ent->moveinfo.speed) / FRAMETIME); ent->moveinfo.remaining_distance -= frames * ent->moveinfo.speed * FRAMETIME; ent->nextthink = level.time + (frames * FRAMETIME); ent->think = Move_Final; } void Think_AccelMove (edict_t * ent); void Move_Calc (edict_t * ent, vec3_t dest, void (*func) (edict_t *)) { VectorClear (ent->velocity); VectorSubtract (dest, ent->s.origin, ent->moveinfo.dir); ent->moveinfo.remaining_distance = VectorNormalize (ent->moveinfo.dir); ent->moveinfo.endfunc = func; if (ent->moveinfo.speed == ent->moveinfo.accel && ent->moveinfo.speed == ent->moveinfo.decel) { if (level.current_entity == ((ent->flags & FL_TEAMSLAVE) ? ent->teammaster : ent)) { Move_Begin (ent); } else { ent->nextthink = level.time + FRAMETIME; ent->think = Move_Begin; } } else { // accelerative ent->moveinfo.current_speed = 0; ent->think = Think_AccelMove; ent->nextthink = level.time + FRAMETIME; } } // // Support routines for angular movement (changes in angle using avelocity) // void AngleMove_Done (edict_t * ent) { VectorClear (ent->avelocity); ent->moveinfo.endfunc (ent); } void AngleMove_Final (edict_t * ent) { vec3_t move; if (ent->moveinfo.state == STATE_UP) VectorSubtract (ent->moveinfo.end_angles, ent->s.angles, move); else VectorSubtract (ent->moveinfo.start_angles, ent->s.angles, move); if (VectorCompare (move, vec3_origin)) { AngleMove_Done (ent); return; } VectorScale (move, 1.0 / FRAMETIME, ent->avelocity); ent->think = AngleMove_Done; ent->nextthink = level.time + FRAMETIME; } void AngleMove_Begin (edict_t * ent) { vec3_t destdelta; float len; float traveltime; float frames; // set destdelta to the vector needed to move if (ent->moveinfo.state == STATE_UP) VectorSubtract (ent->moveinfo.end_angles, ent->s.angles, destdelta); else VectorSubtract (ent->moveinfo.start_angles, ent->s.angles, destdelta); // calculate length of vector len = VectorLength (destdelta); // divide by speed to get time to reach dest traveltime = len / ent->moveinfo.speed; if (traveltime < FRAMETIME) { AngleMove_Final (ent); return; } frames = floor (traveltime / FRAMETIME); // scale the destdelta vector by the time spent traveling to get velocity VectorScale (destdelta, 1.0 / traveltime, ent->avelocity); // set nextthink to trigger a think when dest is reached ent->nextthink = level.time + frames * FRAMETIME; ent->think = AngleMove_Final; } void AngleMove_Calc (edict_t * ent, void (*func) (edict_t *)) { VectorClear (ent->avelocity); ent->moveinfo.endfunc = func; if (level.current_entity == ((ent->flags & FL_TEAMSLAVE) ? ent->teammaster : ent)) { AngleMove_Begin (ent); } else { ent->nextthink = level.time + FRAMETIME; ent->think = AngleMove_Begin; } } /* ============== Think_AccelMove The team has completed a frame of movement, so change the speed for the next frame ============== */ #define AccelerationDistance(target, rate) (target * ((target / rate) + 1) / 2) void plat_CalcAcceleratedMove (moveinfo_t * moveinfo) { float accel_dist; float decel_dist; moveinfo->move_speed = moveinfo->speed; if (moveinfo->remaining_distance < moveinfo->accel) { moveinfo->current_speed = moveinfo->remaining_distance; return; } accel_dist = AccelerationDistance (moveinfo->speed, moveinfo->accel); decel_dist = AccelerationDistance (moveinfo->speed, moveinfo->decel); if ((moveinfo->remaining_distance - accel_dist - decel_dist) < 0) { float f; f = (moveinfo->accel + moveinfo->decel) / (moveinfo->accel * moveinfo->decel); moveinfo->move_speed = (-2 + sqrt (4 - 4 * f * (-2 * moveinfo->remaining_distance))) / (2 * f); decel_dist = AccelerationDistance (moveinfo->move_speed, moveinfo->decel); } moveinfo->decel_distance = decel_dist; }; void plat_Accelerate (moveinfo_t * moveinfo) { // are we decelerating? if (moveinfo->remaining_distance <= moveinfo->decel_distance) { if (moveinfo->remaining_distance < moveinfo->decel_distance) { if (moveinfo->next_speed) { moveinfo->current_speed = moveinfo->next_speed; moveinfo->next_speed = 0; return; } if (moveinfo->current_speed > moveinfo->decel) moveinfo->current_speed -= moveinfo->decel; } return; } // are we at full speed and need to start decelerating during this move? if (moveinfo->current_speed == moveinfo->move_speed) if ((moveinfo->remaining_distance - moveinfo->current_speed) < moveinfo->decel_distance) { float p1_distance; float p2_distance; float distance; p1_distance = moveinfo->remaining_distance - moveinfo->decel_distance; p2_distance = moveinfo->move_speed * (1.0 - (p1_distance / moveinfo->move_speed)); distance = p1_distance + p2_distance; moveinfo->current_speed = moveinfo->move_speed; moveinfo->next_speed = moveinfo->move_speed - moveinfo->decel * (p2_distance / distance); return; } // are we accelerating? if (moveinfo->current_speed < moveinfo->speed) { float old_speed; float p1_distance; float p1_speed; float p2_distance; float distance; old_speed = moveinfo->current_speed; // figure simple acceleration up to move_speed moveinfo->current_speed += moveinfo->accel; if (moveinfo->current_speed > moveinfo->speed) moveinfo->current_speed = moveinfo->speed; // are we accelerating throughout this entire move? if ((moveinfo->remaining_distance - moveinfo->current_speed) >= moveinfo->decel_distance) return; // during this move we will accelrate from current_speed to move_speed // and cross over the decel_distance; figure the average speed for the // entire move p1_distance = moveinfo->remaining_distance - moveinfo->decel_distance; p1_speed = (old_speed + moveinfo->move_speed) / 2.0; p2_distance = moveinfo->move_speed * (1.0 - (p1_distance / p1_speed)); distance = p1_distance + p2_distance; moveinfo->current_speed = (p1_speed * (p1_distance / distance)) + (moveinfo->move_speed * (p2_distance / distance)); moveinfo->next_speed = moveinfo->move_speed - moveinfo->decel * (p2_distance / distance); return; } // we are at constant velocity (move_speed) return; }; void Think_AccelMove (edict_t * ent) { ent->moveinfo.remaining_distance -= ent->moveinfo.current_speed; if (ent->moveinfo.current_speed == 0) // starting or blocked plat_CalcAcceleratedMove (&ent->moveinfo); plat_Accelerate (&ent->moveinfo); // will the entire move complete on next frame? if (ent->moveinfo.remaining_distance <= ent->moveinfo.current_speed) { Move_Final (ent); return; } VectorScale (ent->moveinfo.dir, ent->moveinfo.current_speed * 10, ent->velocity); ent->nextthink = level.time + FRAMETIME; ent->think = Think_AccelMove; } void plat_go_down (edict_t * ent); void plat_hit_top (edict_t * ent) { if (!(ent->flags & FL_TEAMSLAVE)) { if (ent->moveinfo.sound_end) gi.sound (ent, CHAN_NO_PHS_ADD + CHAN_VOICE, ent->moveinfo.sound_end, 1, ATTN_STATIC, 0); ent->s.sound = 0; } ent->moveinfo.state = STATE_TOP; ent->think = plat_go_down; ent->nextthink = level.time + 3; } void plat_hit_bottom (edict_t * ent) { if (!(ent->flags & FL_TEAMSLAVE)) { if (ent->moveinfo.sound_end) gi.sound (ent, CHAN_NO_PHS_ADD + CHAN_VOICE, ent->moveinfo.sound_end, 1, ATTN_STATIC, 0); ent->s.sound = 0; } ent->moveinfo.state = STATE_BOTTOM; } void plat_go_down (edict_t * ent) { if (!(ent->flags & FL_TEAMSLAVE)) { if (ent->moveinfo.sound_start) gi.sound (ent, CHAN_NO_PHS_ADD + CHAN_VOICE, ent->moveinfo.sound_start, 1, ATTN_STATIC, 0); ent->s.sound = ent->moveinfo.sound_middle; } ent->moveinfo.state = STATE_DOWN; Move_Calc (ent, ent->moveinfo.end_origin, plat_hit_bottom); } void plat_go_up (edict_t * ent) { if (!(ent->flags & FL_TEAMSLAVE)) { if (ent->moveinfo.sound_start) gi.sound (ent, CHAN_NO_PHS_ADD + CHAN_VOICE, ent->moveinfo.sound_start, 1, ATTN_STATIC, 0); ent->s.sound = ent->moveinfo.sound_middle; } ent->moveinfo.state = STATE_UP; Move_Calc (ent, ent->moveinfo.start_origin, plat_hit_top); } void plat_blocked (edict_t * self, edict_t * other) { if (!(other->svflags & SVF_MONSTER) && (!other->client)) { // give it a chance to go away on it's own terms (like gibs) T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, 100000, 1, 0, MOD_CRUSH); // if it's still there, nuke it if (other) { // DestroyFlag frees items other than flags Handle_Unique_Items (other); if (other) CTFDestroyFlag (other); } return; } T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); if (self->moveinfo.state == STATE_UP) plat_go_down (self); else if (self->moveinfo.state == STATE_DOWN) plat_go_up (self); } void Use_Plat (edict_t * ent, edict_t * other, edict_t * activator) { if (ent->think) return; // already down plat_go_down (ent); } void Touch_Plat_Center (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { if (!other->client) return; if (other->health <= 0) return; ent = ent->enemy; // now point at the plat, not the trigger if (ent->moveinfo.state == STATE_BOTTOM) plat_go_up (ent); else if (ent->moveinfo.state == STATE_TOP) ent->nextthink = level.time + 1; // the player is still on the plat, so delay going down } void plat_spawn_inside_trigger (edict_t * ent) { edict_t *trigger; vec3_t tmin, tmax; // // middle trigger // trigger = G_Spawn (); trigger->touch = Touch_Plat_Center; trigger->movetype = MOVETYPE_NONE; trigger->solid = SOLID_TRIGGER; trigger->enemy = ent; tmin[0] = ent->mins[0] + 25; tmin[1] = ent->mins[1] + 25; tmin[2] = ent->mins[2]; tmax[0] = ent->maxs[0] - 25; tmax[1] = ent->maxs[1] - 25; tmax[2] = ent->maxs[2] + 8; tmin[2] = tmax[2] - (ent->pos1[2] - ent->pos2[2] + st.lip); if (ent->spawnflags & PLAT_LOW_TRIGGER) tmax[2] = tmin[2] + 8; if (tmax[0] - tmin[0] <= 0) { tmin[0] = (ent->mins[0] + ent->maxs[0]) * 0.5; tmax[0] = tmin[0] + 1; } if (tmax[1] - tmin[1] <= 0) { tmin[1] = (ent->mins[1] + ent->maxs[1]) * 0.5; tmax[1] = tmin[1] + 1; } VectorCopy (tmin, trigger->mins); VectorCopy (tmax, trigger->maxs); gi.linkentity (trigger); } /*QUAKED func_plat (0 .5 .8) ? PLAT_LOW_TRIGGER speed default 150 Plats are always drawn in the extended position, so they will light correctly. If the plat is the target of another trigger or button, it will start out disabled in the extended position until it is trigger, when it will lower and become a normal plat. "speed" overrides default 200. "accel" overrides default 500 "lip" overrides default 8 pixel lip If the "height" key is set, that will determine the amount the plat moves, instead of being implicitly determoveinfoned by the model's height. Set "sounds" to one of the following: 1) base fast 2) chain slow */ void SP_func_plat (edict_t * ent) { VectorClear (ent->s.angles); ent->solid = SOLID_BSP; ent->movetype = MOVETYPE_PUSH; gi.setmodel (ent, ent->model); ent->blocked = plat_blocked; if (!ent->speed) ent->speed = 20; else ent->speed *= 0.1f; if (!ent->accel) ent->accel = 5; else ent->accel *= 0.1f; if (!ent->decel) ent->decel = 5; else ent->decel *= 0.1f; if (!ent->dmg) ent->dmg = 2; if (!st.lip) st.lip = 8; // pos1 is the top position, pos2 is the bottom VectorCopy (ent->s.origin, ent->pos1); VectorCopy (ent->s.origin, ent->pos2); if (st.height) ent->pos2[2] -= st.height; else ent->pos2[2] -= (ent->maxs[2] - ent->mins[2]) - st.lip; ent->use = Use_Plat; plat_spawn_inside_trigger (ent); // the "start moving" trigger if (ent->targetname) { ent->moveinfo.state = STATE_UP; } else { VectorCopy (ent->pos2, ent->s.origin); gi.linkentity (ent); ent->moveinfo.state = STATE_BOTTOM; } ent->moveinfo.speed = ent->speed; ent->moveinfo.accel = ent->accel; ent->moveinfo.decel = ent->decel; ent->moveinfo.wait = ent->wait; VectorCopy (ent->pos1, ent->moveinfo.start_origin); VectorCopy (ent->s.angles, ent->moveinfo.start_angles); VectorCopy (ent->pos2, ent->moveinfo.end_origin); VectorCopy (ent->s.angles, ent->moveinfo.end_angles); ent->moveinfo.sound_start = gi.soundindex ("plats/pt1_strt.wav"); ent->moveinfo.sound_middle = gi.soundindex ("plats/pt1_mid.wav"); ent->moveinfo.sound_end = gi.soundindex ("plats/pt1_end.wav"); } //==================================================================== /*QUAKED func_rotating (0 .5 .8) ? START_ON REVERSE X_AXIS Y_AXIS TOUCH_PAIN STOP ANIMATED ANIMATED_FAST You need to have an origin brush as part of this entity. The center of that brush will be the point around which it is rotated. It will rotate around the Z axis by default. You can check either the X_AXIS or Y_AXIS box to change that. "speed" determines how fast it moves; default value is 100. "dmg" damage to inflict when blocked (2 default) REVERSE will cause the it to rotate in the opposite direction. STOP mean it will stop moving instead of pushing entities */ void rotating_blocked (edict_t * self, edict_t * other) { T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); } void rotating_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (self->avelocity[0] || self->avelocity[1] || self->avelocity[2]) T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); } void rotating_use (edict_t * self, edict_t * other, edict_t * activator) { if (!VectorCompare (self->avelocity, vec3_origin)) { self->s.sound = 0; VectorClear (self->avelocity); self->touch = NULL; } else { self->s.sound = self->moveinfo.sound_middle; VectorScale (self->movedir, self->speed, self->avelocity); if (self->spawnflags & 16) self->touch = rotating_touch; } } void SP_func_rotating (edict_t * ent) { ent->solid = SOLID_BSP; if (ent->spawnflags & 32) ent->movetype = MOVETYPE_STOP; else ent->movetype = MOVETYPE_PUSH; // set the axis of rotation VectorClear (ent->movedir); if (ent->spawnflags & 4) ent->movedir[2] = 1.0; else if (ent->spawnflags & 8) ent->movedir[0] = 1.0; else // Z_AXIS ent->movedir[1] = 1.0; // check for reverse rotation if (ent->spawnflags & 2) VectorNegate (ent->movedir, ent->movedir); if (!ent->speed) ent->speed = 100; if (!ent->dmg) ent->dmg = 2; // ent->moveinfo.sound_middle = "doors/hydro1.wav"; ent->use = rotating_use; if (ent->dmg) ent->blocked = rotating_blocked; if (ent->spawnflags & 1) ent->use (ent, NULL, NULL); if (ent->spawnflags & 64) ent->s.effects |= EF_ANIM_ALL; if (ent->spawnflags & 128) ent->s.effects |= EF_ANIM_ALLFAST; gi.setmodel (ent, ent->model); gi.linkentity (ent); } /* ====================================================================== BUTTONS ====================================================================== */ /*QUAKED func_button (0 .5 .8) ? When a button is touched, it moves some distance in the direction of it's angle, triggers all of it's targets, waits some time, then returns to it's original position where it can be triggered again. "angle" determines the opening direction "target" all entities with a matching targetname will be used "speed" override the default 40 speed "wait" override the default 1 second wait (-1 = never return) "lip" override the default 4 pixel lip remaining at end of move "health" if set, the button must be killed instead of touched "sounds" 1) silent 2) steam metal 3) wooden clunk 4) metallic click 5) in-out */ void button_done (edict_t * self) { self->moveinfo.state = STATE_BOTTOM; self->s.effects &= ~EF_ANIM23; self->s.effects |= EF_ANIM01; } void button_return (edict_t * self) { self->moveinfo.state = STATE_DOWN; Move_Calc (self, self->moveinfo.start_origin, button_done); self->s.frame = 0; if (self->health) self->takedamage = DAMAGE_YES; } void button_wait (edict_t * self) { self->moveinfo.state = STATE_TOP; self->s.effects &= ~EF_ANIM01; self->s.effects |= EF_ANIM23; G_UseTargets (self, self->activator); self->s.frame = 1; if (self->moveinfo.wait >= 0) { self->nextthink = level.time + self->moveinfo.wait; self->think = button_return; } } void button_fire (edict_t * self) { if (self->moveinfo.state == STATE_UP || self->moveinfo.state == STATE_TOP) return; self->moveinfo.state = STATE_UP; if (self->moveinfo.sound_start && !(self->flags & FL_TEAMSLAVE)) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_start, 1, ATTN_STATIC, 0); Move_Calc (self, self->moveinfo.end_origin, button_wait); } void button_use (edict_t * self, edict_t * other, edict_t * activator) { self->activator = activator; button_fire (self); } void button_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (!other->client) return; if (other->health <= 0) return; self->activator = other; button_fire (self); } void button_killed (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { self->activator = attacker; self->health = self->max_health; self->takedamage = DAMAGE_NO; button_fire (self); } void SP_func_button (edict_t * ent) { vec3_t abs_movedir; float dist; G_SetMovedir (ent->s.angles, ent->movedir); ent->movetype = MOVETYPE_STOP; ent->solid = SOLID_BSP; gi.setmodel (ent, ent->model); if (ent->sounds != 1) ent->moveinfo.sound_start = gi.soundindex ("switches/butn2.wav"); if (!ent->speed) ent->speed = 40; if (!ent->accel) ent->accel = ent->speed; if (!ent->decel) ent->decel = ent->speed; if (!ent->wait) ent->wait = 3; if (!st.lip) st.lip = 4; VectorCopy (ent->s.origin, ent->pos1); abs_movedir[0] = fabs (ent->movedir[0]); abs_movedir[1] = fabs (ent->movedir[1]); abs_movedir[2] = fabs (ent->movedir[2]); dist = abs_movedir[0] * ent->size[0] + abs_movedir[1] * ent->size[1] + abs_movedir[2] * ent->size[2] - st.lip; VectorMA (ent->pos1, dist, ent->movedir, ent->pos2); ent->use = button_use; ent->s.effects |= EF_ANIM01; if (ent->health) { ent->max_health = ent->health; ent->die = button_killed; ent->takedamage = DAMAGE_YES; } else if (!ent->targetname) ent->touch = button_touch; ent->moveinfo.state = STATE_BOTTOM; ent->moveinfo.speed = ent->speed; ent->moveinfo.accel = ent->accel; ent->moveinfo.decel = ent->decel; ent->moveinfo.wait = ent->wait; VectorCopy (ent->pos1, ent->moveinfo.start_origin); VectorCopy (ent->s.angles, ent->moveinfo.start_angles); VectorCopy (ent->pos2, ent->moveinfo.end_origin); VectorCopy (ent->s.angles, ent->moveinfo.end_angles); gi.linkentity (ent); } /* ====================================================================== DOORS spawn a trigger surrounding the entire team unless it is already targeted by another ====================================================================== */ /*QUAKED func_door (0 .5 .8) ? START_OPEN x CRUSHER NOMONSTER ANIMATED TOGGLE ANIMATED_FAST TOGGLE wait in both the start and end states for a trigger event. START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors). NOMONSTER monsters will not trigger this door "message" is printed when the door is touched if it is a trigger door and it hasn't been fired yet "angle" determines the opening direction "targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door. "health" if set, door must be shot open "speed" movement speed (100 default) "wait" wait before returning (3 default, -1 = never return) "lip" lip remaining at end of move (8 default) "dmg" damage to inflict when blocked (2 default) "sounds" 1) silent 2) light 3) medium 4) heavy */ void door_use_areaportals (edict_t * self, qboolean open) { edict_t *t = NULL; if (!self->target) return; while ((t = G_Find (t, FOFS (targetname), self->target))) { if (Q_stricmp (t->classname, "func_areaportal") == 0) { gi.SetAreaPortalState (t->style, open); } } } void door_go_down (edict_t * self); void door_hit_top (edict_t * self) { if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_end) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_end, 1, ATTN_STATIC, 0); self->s.sound = 0; } self->moveinfo.state = STATE_TOP; if (self->spawnflags & DOOR_TOGGLE) return; if (self->moveinfo.wait >= 0) { self->think = door_go_down; self->nextthink = level.time + self->moveinfo.wait; } } void door_hit_bottom (edict_t * self) { if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_end) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_end, 1, ATTN_STATIC, 0); self->s.sound = 0; } self->moveinfo.state = STATE_BOTTOM; door_use_areaportals (self, false); } void door_go_down (edict_t * self) { if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_start) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_start, 1, ATTN_STATIC, 0); self->s.sound = self->moveinfo.sound_middle; } if (self->max_health) { self->takedamage = DAMAGE_YES; self->health = self->max_health; } self->moveinfo.state = STATE_DOWN; if (strcmp (self->classname, "func_door") == 0) Move_Calc (self, self->moveinfo.start_origin, door_hit_bottom); else if (strcmp (self->classname, "func_door_rotating") == 0) AngleMove_Calc (self, door_hit_bottom); } void door_go_up (edict_t * self, edict_t * activator) { if (self->moveinfo.state == STATE_UP) return; // already going up if (self->moveinfo.state == STATE_TOP) { // reset top wait time if (self->moveinfo.wait >= 0) self->nextthink = level.time + self->moveinfo.wait; return; } if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_start) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_start, 1, ATTN_STATIC, 0); self->s.sound = self->moveinfo.sound_middle; } self->moveinfo.state = STATE_UP; if (strcmp (self->classname, "func_door") == 0) Move_Calc (self, self->moveinfo.end_origin, door_hit_top); else if (strcmp (self->classname, "func_door_rotating") == 0) AngleMove_Calc (self, door_hit_top); G_UseTargets (self, activator); door_use_areaportals (self, true); } void door_use (edict_t * self, edict_t * other, edict_t * activator) { edict_t *ent; if (self->flags & FL_TEAMSLAVE) return; if (self->spawnflags & DOOR_TOGGLE) { if (self->moveinfo.state == STATE_UP || self->moveinfo.state == STATE_TOP) { // if ( other->client ) // gi.cprintf(other, PRINT_HIGH, "Client sending door down.\n"); // trigger all paired doors for (ent = self; ent; ent = ent->teamchain) { ent->message = NULL; ent->touch = NULL; door_go_down (ent); } return; } } // if ( other->client ) // gi.cprintf(other, PRINT_HIGH, "Client sending door up.\n"); // trigger all paired doors for (ent = self; ent; ent = ent->teamchain) { ent->message = NULL; ent->touch = NULL; door_go_up (ent, activator); } }; void Touch_DoorTrigger (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { // zucc needed so the doors respond quickly if (other->client && other->client->doortoggle) { //gi.cprintf(other, PRINT_HIGH, "Door trigger called.\n"); self->touch_debounce_time = 0.0; } if (other->health <= 0) return; if (!(other->svflags & SVF_MONSTER) && (!other->client)) return; if ((self->owner->spawnflags & DOOR_NOMONSTER) && (other->svflags & SVF_MONSTER)) return; if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 1.0; // zucc if (other->client) { if (other->client->doortoggle == 0) // player not trying to open the door { //gi.cprintf(other, PRINT_HIGH, "Client failed to open door.\n"); return; } else { //other->client->doortoggle = 0; door_use (self->owner, other, other); } } } void Think_CalcMoveSpeed (edict_t * self) { edict_t *ent; float min; float time; float newspeed; float ratio; float dist; if (self->flags & FL_TEAMSLAVE) return; // only the team master does this // find the smallest distance any member of the team will be moving min = fabs (self->moveinfo.distance); for (ent = self->teamchain; ent; ent = ent->teamchain) { dist = fabs (ent->moveinfo.distance); if (dist < min) min = dist; } time = min / self->moveinfo.speed; // adjust speeds so they will all complete at the same time for (ent = self; ent; ent = ent->teamchain) { newspeed = fabs (ent->moveinfo.distance) / time; ratio = newspeed / ent->moveinfo.speed; if (ent->moveinfo.accel == ent->moveinfo.speed) ent->moveinfo.accel = newspeed; else ent->moveinfo.accel *= ratio; if (ent->moveinfo.decel == ent->moveinfo.speed) ent->moveinfo.decel = newspeed; else ent->moveinfo.decel *= ratio; ent->moveinfo.speed = newspeed; } } void Think_SpawnDoorTrigger (edict_t * ent) { edict_t *other; vec3_t mins, maxs; if (ent->flags & FL_TEAMSLAVE) return; // only the team leader spawns a trigger VectorCopy (ent->absmin, mins); VectorCopy (ent->absmax, maxs); for (other = ent->teamchain; other; other = other->teamchain) { AddPointToBounds (other->absmin, mins, maxs); AddPointToBounds (other->absmax, mins, maxs); } // expand mins[0] -= 60; mins[1] -= 60; maxs[0] += 60; maxs[1] += 60; other = G_Spawn (); VectorCopy (mins, other->mins); VectorCopy (maxs, other->maxs); other->owner = ent; other->solid = SOLID_TRIGGER; other->movetype = MOVETYPE_NONE; other->touch = Touch_DoorTrigger; gi.linkentity (other); if (ent->spawnflags & DOOR_START_OPEN) door_use_areaportals (ent, true); Think_CalcMoveSpeed (ent); } void door_blocked (edict_t * self, edict_t * other) { edict_t *ent; if (!(other->svflags & SVF_MONSTER) && (!other->client)) { // give it a chance to go away on it's own terms (like gibs) T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, 100000, 1, 0, MOD_CRUSH); // if it's still there, nuke it if (other) { // DestroyFlag frees items other than flags Handle_Unique_Items (other); if (other) CTFDestroyFlag (other); } return; } //zucc stop the doors from damaging people //T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); if (self->spawnflags & DOOR_CRUSHER) return; // if a door has a negative wait, it would never come back if blocked, // so let it just squash the object to death real fast if (self->moveinfo.wait >= 0) { if (self->moveinfo.state == STATE_DOWN) { for (ent = self->teammaster; ent; ent = ent->teamchain) door_go_up (ent, ent->activator); } else { for (ent = self->teammaster; ent; ent = ent->teamchain) door_go_down (ent); } } } void door_killed (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { edict_t *ent; for (ent = self->teammaster; ent; ent = ent->teamchain) { ent->health = ent->max_health; ent->takedamage = DAMAGE_NO; } door_use (self->teammaster, attacker, attacker); } void door_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (!other->client) return; if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 5.0; gi.centerprintf (other, "%s", self->message); gi.sound (other, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } void SP_func_door (edict_t * ent) { vec3_t abs_movedir; if (ent->sounds != 1) { ent->moveinfo.sound_start = gi.soundindex ("doors/dr1_strt.wav"); ent->moveinfo.sound_middle = gi.soundindex ("doors/dr1_mid.wav"); ent->moveinfo.sound_end = gi.soundindex ("doors/dr1_end.wav"); } G_SetMovedir (ent->s.angles, ent->movedir); ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_BSP; gi.setmodel (ent, ent->model); ent->blocked = door_blocked; ent->use = door_use; if (!ent->speed) ent->speed = 100; if (deathmatch->value) ent->speed *= 2; if (!ent->accel) ent->accel = ent->speed; if (!ent->decel) ent->decel = ent->speed; if (!ent->wait) ent->wait = 3; if (!st.lip) st.lip = 8; if (!ent->dmg) ent->dmg = 2; // calculate second position VectorCopy (ent->s.origin, ent->pos1); abs_movedir[0] = fabs (ent->movedir[0]); abs_movedir[1] = fabs (ent->movedir[1]); abs_movedir[2] = fabs (ent->movedir[2]); ent->moveinfo.distance = abs_movedir[0] * ent->size[0] + abs_movedir[1] * ent->size[1] + abs_movedir[2] * ent->size[2] - st.lip; VectorMA (ent->pos1, ent->moveinfo.distance, ent->movedir, ent->pos2); // if it starts open, switch the positions if (ent->spawnflags & DOOR_START_OPEN) { VectorCopy (ent->pos2, ent->s.origin); VectorCopy (ent->pos1, ent->pos2); VectorCopy (ent->s.origin, ent->pos1); } ent->moveinfo.state = STATE_BOTTOM; if (ent->health) { ent->takedamage = DAMAGE_YES; ent->die = door_killed; ent->max_health = ent->health; } else if (ent->targetname && ent->message) { gi.soundindex ("misc/talk.wav"); ent->touch = door_touch; } ent->moveinfo.speed = ent->speed; ent->moveinfo.accel = ent->accel; ent->moveinfo.decel = ent->decel; ent->moveinfo.wait = ent->wait; VectorCopy (ent->pos1, ent->moveinfo.start_origin); VectorCopy (ent->s.angles, ent->moveinfo.start_angles); VectorCopy (ent->pos2, ent->moveinfo.end_origin); VectorCopy (ent->s.angles, ent->moveinfo.end_angles); if (ent->spawnflags & 16) ent->s.effects |= EF_ANIM_ALL; if (ent->spawnflags & 64) ent->s.effects |= EF_ANIM_ALLFAST; // to simplify logic elsewhere, make non-teamed doors into a team of one if (!ent->team) ent->teammaster = ent; gi.linkentity (ent); ent->nextthink = level.time + FRAMETIME; if (ent->health || ent->targetname) ent->think = Think_CalcMoveSpeed; else ent->think = Think_SpawnDoorTrigger; } /*QUAKED func_door_rotating (0 .5 .8) ? START_OPEN REVERSE CRUSHER NOMONSTER ANIMATED TOGGLE X_AXIS Y_AXIS TOGGLE causes the door to wait in both the start and end states for a trigger event. START_OPEN the door to moves to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not useful for touch or takedamage doors). NOMONSTER monsters will not trigger this door You need to have an origin brush as part of this entity. The center of that brush will be the point around which it is rotated. It will rotate around the Z axis by default. You can check either the X_AXIS or Y_AXIS box to change that. "distance" is how many degrees the door will be rotated. "speed" determines how fast the door moves; default value is 100. REVERSE will cause the door to rotate in the opposite direction. "message" is printed when the door is touched if it is a trigger door and it hasn't been fired yet "angle" determines the opening direction "targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door. "health" if set, door must be shot open "speed" movement speed (100 default) "wait" wait before returning (3 default, -1 = never return) "dmg" damage to inflict when blocked (2 default) "sounds" 1) silent 2) light 3) medium 4) heavy */ void SP_func_door_rotating (edict_t * ent) { VectorClear (ent->s.angles); // set the axis of rotation VectorClear (ent->movedir); if (ent->spawnflags & DOOR_X_AXIS) ent->movedir[2] = 1.0; else if (ent->spawnflags & DOOR_Y_AXIS) ent->movedir[0] = 1.0; else // Z_AXIS ent->movedir[1] = 1.0; // check for reverse rotation if (ent->spawnflags & DOOR_REVERSE) VectorNegate (ent->movedir, ent->movedir); if (!st.distance) { gi.dprintf ("%s at %s with no distance set\n", ent->classname, vtos (ent->s.origin)); st.distance = 90; } VectorCopy (ent->s.angles, ent->pos1); VectorMA (ent->s.angles, st.distance, ent->movedir, ent->pos2); ent->moveinfo.distance = st.distance; ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_BSP; gi.setmodel (ent, ent->model); ent->blocked = door_blocked; ent->use = door_use; if (!ent->speed) ent->speed = 100; if (!ent->accel) ent->accel = ent->speed; if (!ent->decel) ent->decel = ent->speed; if (!ent->wait) ent->wait = 3; if (!ent->dmg) ent->dmg = 2; if (ent->sounds != 1) { ent->moveinfo.sound_start = gi.soundindex ("doors/dr1_strt.wav"); ent->moveinfo.sound_middle = gi.soundindex ("doors/dr1_mid.wav"); ent->moveinfo.sound_end = gi.soundindex ("doors/dr1_end.wav"); } // if it starts open, switch the positions if (ent->spawnflags & DOOR_START_OPEN) { VectorCopy (ent->pos2, ent->s.angles); VectorCopy (ent->pos1, ent->pos2); VectorCopy (ent->s.angles, ent->pos1); VectorNegate (ent->movedir, ent->movedir); } if (ent->health) { ent->takedamage = DAMAGE_YES; ent->die = door_killed; ent->max_health = ent->health; } if (ent->targetname && ent->message) { gi.soundindex ("misc/talk.wav"); ent->touch = door_touch; } ent->moveinfo.state = STATE_BOTTOM; ent->moveinfo.speed = ent->speed; ent->moveinfo.accel = ent->accel; ent->moveinfo.decel = ent->decel; ent->moveinfo.wait = ent->wait; VectorCopy (ent->s.origin, ent->moveinfo.start_origin); VectorCopy (ent->pos1, ent->moveinfo.start_angles); VectorCopy (ent->s.origin, ent->moveinfo.end_origin); VectorCopy (ent->pos2, ent->moveinfo.end_angles); if (ent->spawnflags & 16) ent->s.effects |= EF_ANIM_ALL; // to simplify logic elsewhere, make non-teamed doors into a team of one if (!ent->team) ent->teammaster = ent; gi.linkentity (ent); ent->nextthink = level.time + FRAMETIME; if (ent->health || ent->targetname) ent->think = Think_CalcMoveSpeed; else ent->think = Think_SpawnDoorTrigger; } /*QUAKED func_water (0 .5 .8) ? START_OPEN func_water is a moveable water brush. It must be targeted to operate. Use a non-water texture at your own risk. START_OPEN causes the water to move to its destination when spawned and operate in reverse. "angle" determines the opening direction (up or down only) "speed" movement speed (25 default) "wait" wait before returning (-1 default, -1 = TOGGLE) "lip" lip remaining at end of move (0 default) "sounds" (yes, these need to be changed) 0) no sound 1) water 2) lava */ void SP_func_water (edict_t * self) { vec3_t abs_movedir; G_SetMovedir (self->s.angles, self->movedir); self->movetype = MOVETYPE_PUSH; self->solid = SOLID_BSP; gi.setmodel (self, self->model); switch (self->sounds) { default: break; case 1: // water self->moveinfo.sound_start = gi.soundindex ("world/mov_watr.wav"); self->moveinfo.sound_end = gi.soundindex ("world/stp_watr.wav"); break; case 2: // lava self->moveinfo.sound_start = gi.soundindex ("world/mov_watr.wav"); self->moveinfo.sound_end = gi.soundindex ("world/stp_watr.wav"); break; } // calculate second position VectorCopy (self->s.origin, self->pos1); abs_movedir[0] = fabs (self->movedir[0]); abs_movedir[1] = fabs (self->movedir[1]); abs_movedir[2] = fabs (self->movedir[2]); self->moveinfo.distance = abs_movedir[0] * self->size[0] + abs_movedir[1] * self->size[1] + abs_movedir[2] * self->size[2] - st.lip; VectorMA (self->pos1, self->moveinfo.distance, self->movedir, self->pos2); // if it starts open, switch the positions if (self->spawnflags & DOOR_START_OPEN) { VectorCopy (self->pos2, self->s.origin); VectorCopy (self->pos1, self->pos2); VectorCopy (self->s.origin, self->pos1); } VectorCopy (self->pos1, self->moveinfo.start_origin); VectorCopy (self->s.angles, self->moveinfo.start_angles); VectorCopy (self->pos2, self->moveinfo.end_origin); VectorCopy (self->s.angles, self->moveinfo.end_angles); self->moveinfo.state = STATE_BOTTOM; if (!self->speed) self->speed = 25; self->moveinfo.accel = self->moveinfo.decel = self->moveinfo.speed = self->speed; if (!self->wait) self->wait = -1; self->moveinfo.wait = self->wait; self->use = door_use; if (self->wait == -1) self->spawnflags |= DOOR_TOGGLE; self->classname = "func_door"; gi.linkentity (self); } #define TRAIN_START_ON 1 #define TRAIN_TOGGLE 2 #define TRAIN_BLOCK_STOPS 4 /*QUAKED func_train (0 .5 .8) ? START_ON TOGGLE BLOCK_STOPS Trains are moving platforms that players can ride. The targets origin specifies the min point of the train at each corner. The train spawns at the first target it is pointing at. If the train is the target of a button or trigger, it will not begin moving until activated. speed default 100 dmg default 2 noise looping sound to play when the train is in motion */ void train_next (edict_t * self); void train_blocked (edict_t * self, edict_t * other) { if (!(other->svflags & SVF_MONSTER) && (!other->client)) { // give it a chance to go away on it's own terms (like gibs) T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, 100000, 1, 0, MOD_CRUSH); // if it's still there, nuke it if (other) { // DestroyFlag frees items other than flags Handle_Unique_Items (other); if (other) CTFDestroyFlag (other); } return; } if (level.time < self->touch_debounce_time) return; if (!self->dmg) return; self->touch_debounce_time = level.time + 0.5; T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); } void train_wait (edict_t * self) { if (self->target_ent->pathtarget) { char *savetarget; edict_t *ent; ent = self->target_ent; savetarget = ent->target; ent->target = ent->pathtarget; G_UseTargets (ent, self->activator); ent->target = savetarget; // make sure we didn't get killed by a killtarget if (!self->inuse) return; } if (self->moveinfo.wait) { if (self->moveinfo.wait > 0) { self->nextthink = level.time + self->moveinfo.wait; self->think = train_next; } else if (self->spawnflags & TRAIN_TOGGLE) // && wait < 0 { train_next (self); self->spawnflags &= ~TRAIN_START_ON; VectorClear (self->velocity); self->nextthink = 0; } if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_end) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_end, 1, ATTN_STATIC, 0); self->s.sound = 0; } } else { train_next (self); } } void train_next (edict_t * self) { edict_t *ent; vec3_t dest; qboolean first; first = true; again: if (!self->target) { // gi.dprintf ("train_next: no next target\n"); return; } ent = G_PickTarget (self->target); if (!ent) { gi.dprintf ("train_next: bad target %s\n", self->target); return; } self->target = ent->target; // check for a teleport path_corner if (ent->spawnflags & 1) { if (!first) { gi.dprintf ("connected teleport path_corners, see %s at %s\n", ent->classname, vtos (ent->s.origin)); return; } first = false; VectorSubtract (ent->s.origin, self->mins, self->s.origin); VectorCopy (self->s.origin, self->s.old_origin); gi.linkentity (self); goto again; } self->moveinfo.wait = ent->wait; self->target_ent = ent; if (!(self->flags & FL_TEAMSLAVE)) { if (self->moveinfo.sound_start) gi.sound (self, CHAN_NO_PHS_ADD + CHAN_VOICE, self->moveinfo.sound_start, 1, ATTN_STATIC, 0); self->s.sound = self->moveinfo.sound_middle; } VectorSubtract (ent->s.origin, self->mins, dest); self->moveinfo.state = STATE_TOP; VectorCopy (self->s.origin, self->moveinfo.start_origin); VectorCopy (dest, self->moveinfo.end_origin); Move_Calc (self, dest, train_wait); self->spawnflags |= TRAIN_START_ON; } void train_resume (edict_t * self) { edict_t *ent; vec3_t dest; ent = self->target_ent; VectorSubtract (ent->s.origin, self->mins, dest); self->moveinfo.state = STATE_TOP; VectorCopy (self->s.origin, self->moveinfo.start_origin); VectorCopy (dest, self->moveinfo.end_origin); Move_Calc (self, dest, train_wait); self->spawnflags |= TRAIN_START_ON; } void func_train_find (edict_t * self) { edict_t *ent; if (!self->target) { gi.dprintf ("train_find: no target\n"); return; } ent = G_PickTarget (self->target); if (!ent) { gi.dprintf ("train_find: target %s not found\n", self->target); return; } self->target = ent->target; VectorSubtract (ent->s.origin, self->mins, self->s.origin); gi.linkentity (self); // if not triggered, start immediately if (!self->targetname) self->spawnflags |= TRAIN_START_ON; if (self->spawnflags & TRAIN_START_ON) { self->nextthink = level.time + FRAMETIME; self->think = train_next; self->activator = self; } } void train_use (edict_t * self, edict_t * other, edict_t * activator) { self->activator = activator; if (self->spawnflags & TRAIN_START_ON) { if (!(self->spawnflags & TRAIN_TOGGLE)) return; self->spawnflags &= ~TRAIN_START_ON; VectorClear (self->velocity); self->nextthink = 0; } else { if (self->target_ent) train_resume (self); else train_next (self); } } void SP_func_train (edict_t * self) { self->movetype = MOVETYPE_PUSH; VectorClear (self->s.angles); self->blocked = train_blocked; if (self->spawnflags & TRAIN_BLOCK_STOPS) self->dmg = 0; else { if (!self->dmg) self->dmg = 100; } self->solid = SOLID_BSP; gi.setmodel (self, self->model); if (st.noise) self->moveinfo.sound_middle = gi.soundindex (st.noise); if (!self->speed) self->speed = 100; self->moveinfo.speed = self->speed; self->moveinfo.accel = self->moveinfo.decel = self->moveinfo.speed; self->use = train_use; gi.linkentity (self); if (self->target) { // start trains on the second frame, to make sure their targets have had // a chance to spawn self->nextthink = level.time + FRAMETIME; self->think = func_train_find; } else { gi.dprintf ("func_train without a target at %s\n", vtos (self->absmin)); } } /*QUAKED trigger_elevator (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) */ void trigger_elevator_use (edict_t * self, edict_t * other, edict_t * activator) { edict_t *target; if (self->movetarget->nextthink) { // gi.dprintf("elevator busy\n"); return; } if (!other->pathtarget) { gi.dprintf ("elevator used with no pathtarget\n"); return; } target = G_PickTarget (other->pathtarget); if (!target) { gi.dprintf ("elevator used with bad pathtarget: %s\n", other->pathtarget); return; } self->movetarget->target_ent = target; train_resume (self->movetarget); } void trigger_elevator_init (edict_t * self) { if (!self->target) { gi.dprintf ("trigger_elevator has no target\n"); return; } self->movetarget = G_PickTarget (self->target); if (!self->movetarget) { gi.dprintf ("trigger_elevator unable to find target %s\n", self->target); return; } if (strcmp (self->movetarget->classname, "func_train") != 0) { gi.dprintf ("trigger_elevator target %s is not a train\n", self->target); return; } self->use = trigger_elevator_use; self->svflags = SVF_NOCLIENT; } void SP_trigger_elevator (edict_t * self) { self->think = trigger_elevator_init; self->nextthink = level.time + FRAMETIME; } /*QUAKED func_timer (0.3 0.1 0.6) (-8 -8 -8) (8 8 8) START_ON "wait" base time between triggering all targets, default is 1 "random" wait variance, default is 0 so, the basic time between firing is a random time between (wait - random) and (wait + random) "delay" delay before first firing when turned on, default is 0 "pausetime" additional delay used only the very first time and only if spawned with START_ON These can used but not touched. */ void func_timer_think (edict_t * self) { G_UseTargets (self, self->activator); self->nextthink = level.time + self->wait + crandom () * self->random; } void func_timer_use (edict_t * self, edict_t * other, edict_t * activator) { self->activator = activator; // if on, turn it off if (self->nextthink) { self->nextthink = 0; return; } // turn it on if (self->delay) self->nextthink = level.time + self->delay; else func_timer_think (self); } void SP_func_timer (edict_t * self) { if (!self->wait) self->wait = 1.0; self->use = func_timer_use; self->think = func_timer_think; if (self->random >= self->wait) { self->random = self->wait - FRAMETIME; gi.dprintf ("func_timer at %s has random >= wait\n", vtos (self->s.origin)); } if (self->spawnflags & 1) { self->nextthink = level.time + 1.0 + st.pausetime + self->delay + self->wait + crandom () * self->random; self->activator = self; } self->svflags = SVF_NOCLIENT; } /*QUAKED func_conveyor (0 .5 .8) ? START_ON TOGGLE Conveyors are stationary brushes that move what's on them. The brush should be have a surface with at least one current content enabled. speed default 100 */ void func_conveyor_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->spawnflags & 1) { self->speed = 0; self->spawnflags &= ~1; } else { self->speed = self->count; self->spawnflags |= 1; } if (!(self->spawnflags & 2)) self->count = 0; } void SP_func_conveyor (edict_t * self) { if (!self->speed) self->speed = 100; if (!(self->spawnflags & 1)) { self->count = self->speed; self->speed = 0; } self->use = func_conveyor_use; gi.setmodel (self, self->model); self->solid = SOLID_BSP; gi.linkentity (self); } /*QUAKED func_door_secret (0 .5 .8) ? always_shoot 1st_left 1st_down A secret door. Slide back and then to the side. open_once doors never closes 1st_left 1st move is left of arrow 1st_down 1st move is down from arrow always_shoot door is shootebale even if targeted "angle" determines the direction "dmg" damage to inflic when blocked (default 2) "wait" how long to hold in the open position (default 5, -1 means hold) */ #define SECRET_ALWAYS_SHOOT 1 #define SECRET_1ST_LEFT 2 #define SECRET_1ST_DOWN 4 void door_secret_move1 (edict_t * self); void door_secret_move2 (edict_t * self); void door_secret_move3 (edict_t * self); void door_secret_move4 (edict_t * self); void door_secret_move5 (edict_t * self); void door_secret_move6 (edict_t * self); void door_secret_done (edict_t * self); void door_secret_use (edict_t * self, edict_t * other, edict_t * activator) { // make sure we're not already moving if (!VectorCompare (self->s.origin, vec3_origin)) return; Move_Calc (self, self->pos1, door_secret_move1); door_use_areaportals (self, true); } void door_secret_move1 (edict_t * self) { self->nextthink = level.time + 1.0; self->think = door_secret_move2; } void door_secret_move2 (edict_t * self) { Move_Calc (self, self->pos2, door_secret_move3); } void door_secret_move3 (edict_t * self) { if (self->wait == -1) return; self->nextthink = level.time + self->wait; self->think = door_secret_move4; } void door_secret_move4 (edict_t * self) { Move_Calc (self, self->pos1, door_secret_move5); } void door_secret_move5 (edict_t * self) { self->nextthink = level.time + 1.0; self->think = door_secret_move6; } void door_secret_move6 (edict_t * self) { Move_Calc (self, vec3_origin, door_secret_done); } void door_secret_done (edict_t * self) { if (!(self->targetname) || (self->spawnflags & SECRET_ALWAYS_SHOOT)) { self->health = 0; self->takedamage = DAMAGE_YES; } door_use_areaportals (self, false); } void door_secret_blocked (edict_t * self, edict_t * other) { if (!(other->svflags & SVF_MONSTER) && (!other->client)) { // give it a chance to go away on it's own terms (like gibs) T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, 100000, 1, 0, MOD_CRUSH); // if it's still there, nuke it if (other) { // DestroyFlag frees items other than flags Handle_Unique_Items (other); if (other) CTFDestroyFlag (other); } return; } if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 0.5; T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH); } void door_secret_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { self->takedamage = DAMAGE_NO; door_secret_use (self, attacker, attacker); } void SP_func_door_secret (edict_t * ent) { vec3_t forward, right, up; float side; float width; float length; ent->moveinfo.sound_start = gi.soundindex ("doors/dr1_strt.wav"); ent->moveinfo.sound_middle = gi.soundindex ("doors/dr1_mid.wav"); ent->moveinfo.sound_end = gi.soundindex ("doors/dr1_end.wav"); ent->movetype = MOVETYPE_PUSH; ent->solid = SOLID_BSP; gi.setmodel (ent, ent->model); ent->blocked = door_secret_blocked; ent->use = door_secret_use; if (!(ent->targetname) || (ent->spawnflags & SECRET_ALWAYS_SHOOT)) { ent->health = 0; ent->takedamage = DAMAGE_YES; ent->die = door_secret_die; } if (!ent->dmg) ent->dmg = 2; if (!ent->wait) ent->wait = 5; ent->moveinfo.accel = ent->moveinfo.decel = ent->moveinfo.speed = 50; // calculate positions AngleVectors (ent->s.angles, forward, right, up); VectorClear (ent->s.angles); side = 1.0 - (ent->spawnflags & SECRET_1ST_LEFT); if (ent->spawnflags & SECRET_1ST_DOWN) width = fabs (DotProduct (up, ent->size)); else width = fabs (DotProduct (right, ent->size)); length = fabs (DotProduct (forward, ent->size)); if (ent->spawnflags & SECRET_1ST_DOWN) VectorMA (ent->s.origin, -1 * width, up, ent->pos1); else VectorMA (ent->s.origin, side * width, right, ent->pos1); VectorMA (ent->pos1, length, forward, ent->pos2); if (ent->health) { ent->takedamage = DAMAGE_YES; ent->die = door_killed; ent->max_health = ent->health; } else if (ent->targetname && ent->message) { gi.soundindex ("misc/talk.wav"); ent->touch = door_touch; } ent->classname = "func_door"; gi.linkentity (ent); } /*QUAKED func_killbox (1 0 0) ? Kills everything inside when fired, irrespective of protection. */ void use_killbox (edict_t * self, edict_t * other, edict_t * activator) { KillBox (self); } void SP_func_killbox (edict_t * ent) { gi.setmodel (ent, ent->model); ent->use = use_killbox; ent->svflags = SVF_NOCLIENT; }
573
./aq2-tng/source/cgf_sfx_glass.c
/****************************************************************************/ /* */ /* project : CGF (c) 1999 William van der Sterren */ /* parts (c) 1998 id software */ /* */ /* file : cgf_sfx_glass.cpp "special effects for glass entities" */ /* author(s): William van der Sterren */ /* version : 0.5 */ /* */ /* date (last revision): Jun 12, 99 */ /* date (creation) : Jun 04, 99 */ /* */ /* */ /* revision history */ /* -- date ---- | -- revision ---------------------- | -- revisor -- */ /* Jun 12, 1999 | fixed knife slash breaks glass | William */ /* Jun 08, 1999 | improved fragment limit | William */ /* */ /******* http://www.botepidemic.com/aid/cgf for CGF for Action Quake2 *******/ // // $Id: cgf_sfx_glass.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: cgf_sfx_glass.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:29:34 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #ifdef __cplusplus // VC++, for CGF #include <cmath> // prevent problems between C and STL extern "C" { #include "g_local.h" #include "cgf_sfx_glass.h" } #else // C, for other AQ2 variants #include "g_local.h" #include "cgf_sfx_glass.h" #endif // cvar for breaking glass static cvar_t *breakableglass = 0; // cvar for max glass fragment count static cvar_t *glassfragmentlimit = 0; static int glassfragmentcount = 0; // additional functions - Q2 expects C calling convention #ifdef __cplusplus extern "C" { #endif void CGF_SFX_TouchGlass (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf); // called whenever an entity hits the trigger spawned for the glass void CGF_SFX_EmitGlass (edict_t * aGlassPane, edict_t * anInflictor, vec3_t aPoint); // emits glass fragments from aPoint, to show effects of firing thru window void CGF_SFX_BreakGlass (edict_t * aGlassPane, edict_t * anOther, edict_t * anAttacker, int aDamage, vec3_t aPoint, vec_t aPaneDestructDelay); // breaks glass void CGF_SFX_InstallBreakableGlass (edict_t * aGlassPane); // when working on a glass pane for the first time, just install trigger // when working on a glass pane again (after a game ended), move // glass back to original location void CGF_SFX_HideBreakableGlass (edict_t * aGlassPane); // after being broken, the pane cannot be removed as it is needed in // subsequent missions/games, so hide it at about z = -1000 void CGF_SFX_ApplyGlassFragmentLimit (const char *aClassName); // updates glassfragmentcount and removes oldest glass fragement if // necessary to meet limit void CGF_SFX_MiscGlassUse (edict_t * self, edict_t * other, edict_t * activator); // catches use from unforeseen objects (weapons, debris, // etc. touching the window) void CGF_SFX_MiscGlassDie (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point); // catches die calls caused by unforeseen objects (weapons, debris, // etc. damaging the window) void CGF_SFX_GlassThrowDebris (edict_t * self, char *modelname, float speed, vec3_t origin); // variant of id software's ThrowDebris, now numbering the entity (for later removal) extern // from a_game.c edict_t *FindEdictByClassnum (char *classname, int classnum); // declaration from g_misc.c extern // from g_misc.c void debris_die (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point); #ifdef __cplusplus } #endif void CGF_SFX_InstallGlassSupport () { breakableglass = gi.cvar ("breakableglass", "0", 0); glassfragmentlimit = gi.cvar ("glassfragmentlimit", "30", 0); } int CGF_SFX_IsBreakableGlassEnabled () { // returns whether breakable glass is enabled (cvar) and allowed (dm mode) return breakableglass->value; } void CGF_SFX_TestBreakableGlassAndRemoveIfNot_Think (edict_t * aPossibleGlassEntity) { // at level.time == 0.1 the entity has been introduced in the game, // and we can use gi.pointcontents and gi.trace to check the entity vec3_t origin; int breakingglass; trace_t trace; // test for cvar if (!CGF_SFX_IsBreakableGlassEnabled ()) { G_FreeEdict (aPossibleGlassEntity); return; } VectorAdd (aPossibleGlassEntity->absmax, aPossibleGlassEntity->absmin, origin); VectorScale (origin, 0.5, origin); // detect glass (does not work for complex shapes, // for example, the glass window near the satellite // dish at Q2 base3 breakingglass = (gi.pointcontents (origin) & CONTENTS_TRANSLUCENT); if (!breakingglass) { // test for complex brushes that happen to be // hollow in their origin (for instance, the // window at Q2 base3, near the satellite dish trace = gi.trace (origin, vec3_origin, vec3_origin, aPossibleGlassEntity->absmax, 0, MASK_PLAYERSOLID); breakingglass = ((trace.ent == aPossibleGlassEntity) && (trace.contents & CONTENTS_TRANSLUCENT)); trace = gi.trace (origin, vec3_origin, vec3_origin, aPossibleGlassEntity->absmin, 0, MASK_PLAYERSOLID); breakingglass = ((breakingglass) || ((trace.ent == aPossibleGlassEntity) && (trace.contents & CONTENTS_TRANSLUCENT))); } if (!breakingglass) { // do remove other func_explosives G_FreeEdict (aPossibleGlassEntity); return; } // discovered some glass - now make store the origin // we need that after hiding the glass VectorCopy (aPossibleGlassEntity->s.origin, aPossibleGlassEntity->pos1); // IMPORTANT! // make a backup of the health in light_level aPossibleGlassEntity->light_level = aPossibleGlassEntity->health; // install the glass CGF_SFX_InstallBreakableGlass (aPossibleGlassEntity); } void CGF_SFX_InstallBreakableGlass (edict_t * aGlassPane) { // when working on a glass pane for the first time, just install trigger // when working on a glass pane again (after a game ended), move // glass back to original location edict_t *trigger; vec3_t maxs; vec3_t mins; // reset origin based on aGlassPane->pos1 VectorCopy (aGlassPane->pos1, aGlassPane->s.origin); // reset health based on aGlassPane->light_level aGlassPane->health = aGlassPane->light_level; // replace die and use functions by glass specific ones aGlassPane->die = CGF_SFX_MiscGlassDie; aGlassPane->use = CGF_SFX_MiscGlassUse; // reset some pane attributes aGlassPane->takedamage = DAMAGE_YES; aGlassPane->solid = SOLID_BSP; aGlassPane->movetype = MOVETYPE_FLYMISSILE; // for other movetypes, cannot move pane to hidden location and back // try to establish size VectorCopy (aGlassPane->maxs, maxs); VectorCopy (aGlassPane->mins, mins); // set up trigger, similar to triggers for doors // but with a smaller box mins[0] -= 24; mins[1] -= 24; mins[2] -= 24; maxs[0] += 24; maxs[1] += 24; maxs[2] += 24; // adjust some settings trigger = G_Spawn (); trigger->classname = "breakableglass_trigger"; VectorCopy (mins, trigger->mins); VectorCopy (maxs, trigger->maxs); trigger->owner = aGlassPane; trigger->solid = SOLID_TRIGGER; trigger->movetype = MOVETYPE_NONE; trigger->touch = CGF_SFX_TouchGlass; gi.linkentity (trigger); } void CGF_SFX_ShootBreakableGlass (edict_t * aGlassPane, edict_t * anAttacker, /*trace_t* */ void *tr, int mod) { // process gunshots thru glass edict_t *trigger; int destruct; // depending on mod, destroy window or emit fragments switch (mod) { // break for ap, shotgun, handcannon, and kick, destory window case MOD_M3: case MOD_HC: case MOD_SNIPER: case MOD_KICK: case MOD_GRENADE: case MOD_G_SPLASH: case MOD_HANDGRENADE: case MOD_HG_SPLASH: case MOD_KNIFE: // slash damage destruct = true; break; default: destruct = (rand () % 3 == 0); break; }; if (destruct) { // break glass (and hurt if doing kick) CGF_SFX_BreakGlass (aGlassPane, anAttacker, 0, aGlassPane->health, vec3_origin, FRAMETIME); if (mod == MOD_KICK) { vec3_t bloodorigin; vec3_t dir; vec3_t normal; VectorAdd (aGlassPane->absmax, aGlassPane->absmin, bloodorigin); VectorScale (bloodorigin, 0.5, bloodorigin); VectorSubtract (bloodorigin, anAttacker->s.origin, dir); VectorNormalize (dir); VectorMA (anAttacker->s.origin, 32.0, dir, bloodorigin); VectorSet (normal, 0, 0, -1); T_Damage (anAttacker, aGlassPane, anAttacker, dir, bloodorigin, normal, 15.0, 0, 0, MOD_BREAKINGGLASS); } // remove corresponding trigger trigger = 0; while ( (trigger = G_Find (trigger, FOFS (classname), "breakableglass_trigger"))) { if (trigger->owner == aGlassPane) { // remove it G_FreeEdict (trigger); // only one to be found break; } } } else { // add decal (if not grenade) if ((mod != MOD_HANDGRENADE) && (mod != MOD_HG_SPLASH) && (mod != MOD_GRENADE) && (mod != MOD_G_SPLASH)) { AddDecal (anAttacker, (trace_t *) tr); } // and emit glass CGF_SFX_EmitGlass (aGlassPane, anAttacker, ((trace_t *) tr)->endpos); } } void CGF_SFX_TouchGlass (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { // called whenever an entity hits the trigger spawned for the glass vec3_t origin; vec3_t normal; vec3_t spot; trace_t trace; edict_t *glass; vec3_t velocity; vec_t speed; vec_t projected_speed; int is_hgrenade; int is_knife; is_hgrenade = is_knife = false; // ignore non-clients-non-grenade-non-knife if (!other->client) { is_knife = (0 == Q_stricmp ("weapon_knife", other->classname)); if (!is_knife) { is_hgrenade = (0 == Q_stricmp ("hgrenade", other->classname)); } if ((!is_knife) && (!is_hgrenade)) return; if (is_knife) goto knife_and_grenade_handling; } // test whether other really hits the glass - deal with // the special case that other hits some boundary close to the border of the glass pane // // // ....trigger....... // +++++++++ +++++++++++ // .+---glass------+. // wall .+--------------+.wall // +++++++++ +++++++++++ // ----->.................. // wrong ^ ^ // | | // wrong ok // glass = self->owner; // hack - set glass' movetype to MOVETYPE_PUSH as it is not // moving as long as the trigger is active glass->movetype = MOVETYPE_PUSH; VectorAdd (glass->absmax, glass->absmin, origin); VectorScale (origin, 0.5, origin); // other needs to be able to trace to glass origin trace = gi.trace (other->s.origin, vec3_origin, vec3_origin, origin, other, MASK_PLAYERSOLID); if (trace.ent != glass) return; // we can reach the glass origin, so we have the normal of // the glass plane VectorCopy (trace.plane.normal, normal); // we need to check if client is not running into wall next // to the glass (the trigger stretches into the wall) VectorScale (normal, -1000.0, spot); VectorAdd (spot, other->s.origin, spot); // line between other->s.origin and spot (perpendicular to glass // surface should not hit wall but glass instead trace = gi.trace (other->s.origin, vec3_origin, vec3_origin, spot, other, MASK_PLAYERSOLID); if (trace.ent != glass) return; // now, we check if the client's speed perpendicular to // the glass plane, exceeds the required 175 // (speed should be < -200, as the plane's normal // points towards the client VectorCopy (other->velocity, velocity); speed = VectorNormalize (velocity); projected_speed = speed * DotProduct (velocity, normal); // bump projected speed for grenades - they should break // the window more easily if (is_hgrenade) projected_speed *= 1.5f; // if hitting the glass with sufficient speed (project < -175), // being jumpkicked (speed > 700, project < -5) break the window if (!((projected_speed < -175.0) || ((projected_speed < -5) && (speed > 700)))) goto knife_and_grenade_handling; // break glass CGF_SFX_BreakGlass (glass, other, other, glass->health, vec3_origin, 3.0f * FRAMETIME); // glass can take care of itself, but the trigger isn't needed anymore G_FreeEdict (self); /* not needed // reduce momentum of the client (he just broke the window // so he should lose speed. in addition, it doesn't feel // right if he overtakes the glass fragments // VectorScale(normal, 200.0, velocity); // VectorAdd(other->velocity, velocity, other->velocity); */ // make sure client takes damage T_Damage (other, glass, other, normal, other->s.origin, normal, 15.0, 0, 0, MOD_BREAKINGGLASS); return; // goto label knife_and_grenade_handling: // if knife or grenade, bounce them if ((is_knife) || (is_hgrenade)) { // change clipmask to bounce of glass other->clipmask = MASK_SOLID; } } void CGF_SFX_BreakGlass (edict_t * aGlassPane, edict_t * anInflictor, edict_t * anAttacker, int aDamage, vec3_t aPoint, vec_t aPaneDestructDelay) { // based on func_explode, but with lotsa subtle differences vec3_t origin; vec3_t old_origin; vec3_t chunkorigin; vec3_t size; int count; int mass; // bmodel origins are (0 0 0), we need to adjust that here VectorCopy (aGlassPane->s.origin, old_origin); VectorScale (aGlassPane->size, 0.5, size); VectorAdd (aGlassPane->absmin, size, origin); VectorCopy (origin, aGlassPane->s.origin); aGlassPane->takedamage = DAMAGE_NO; VectorSubtract (aGlassPane->s.origin, anInflictor->s.origin, aGlassPane->velocity); VectorNormalize (aGlassPane->velocity); // use speed 250 instead of 150 for funkier glass spray VectorScale (aGlassPane->velocity, 250.0, aGlassPane->velocity); // start chunks towards the center VectorScale (size, 0.75, size); mass = aGlassPane->mass; if (!mass) mass = 75; // big chunks if (mass >= 100) { count = mass / 100; if (count > 8) count = 8; while (count--) { CGF_SFX_ApplyGlassFragmentLimit ("debris"); chunkorigin[0] = origin[0] + crandom () * size[0]; chunkorigin[1] = origin[1] + crandom () * size[1]; chunkorigin[2] = origin[2] + crandom () * size[2]; CGF_SFX_GlassThrowDebris (aGlassPane, "models/objects/debris1/tris.md2", 1, chunkorigin); } } // small chunks count = mass / 25; if (count > 16) count = 16; while (count--) { CGF_SFX_ApplyGlassFragmentLimit ("debris"); chunkorigin[0] = origin[0] + crandom () * size[0]; chunkorigin[1] = origin[1] + crandom () * size[1]; chunkorigin[2] = origin[2] + crandom () * size[2]; CGF_SFX_GlassThrowDebris (aGlassPane, "models/objects/debris2/tris.md2", 2, chunkorigin); } // clear velocity, reset origin (that has been abused in ThrowDebris) VectorClear (aGlassPane->velocity); VectorCopy (old_origin, aGlassPane->s.origin); if (anAttacker) { // jumping thru G_UseTargets (aGlassPane, anAttacker); } else { // firing thru - the pane has no direct attacker to hurt, // but G_UseTargets expects one. So make it a DIY G_UseTargets (aGlassPane, aGlassPane); } // have glass plane be visible for two more frames, // and have it self-destruct then // meanwhile, make sure the player can move thru aGlassPane->solid = SOLID_NOT; aGlassPane->think = CGF_SFX_HideBreakableGlass; aGlassPane->nextthink = level.time + aPaneDestructDelay; } void CGF_SFX_EmitGlass (edict_t * aGlassPane, edict_t * anInflictor, vec3_t aPoint) { // based on func_explode, but with lotsa subtle differences vec3_t old_origin; vec3_t chunkorigin; vec3_t size; int count; // bmodel origins are (0 0 0), we need to adjust that here VectorCopy (aGlassPane->s.origin, old_origin); VectorCopy (aPoint, aGlassPane->s.origin); VectorSubtract (aGlassPane->s.origin, anInflictor->s.origin, aGlassPane->velocity); VectorNormalize (aGlassPane->velocity); // use speed 250 instead of 150 for funkier glass spray VectorScale (aGlassPane->velocity, 250.0, aGlassPane->velocity); // start chunks towards the center VectorScale (aGlassPane->size, 0.25, size); count = 4; while (count--) { CGF_SFX_ApplyGlassFragmentLimit ("debris"); chunkorigin[0] = aPoint[0] + crandom () * size[0]; chunkorigin[1] = aPoint[1] + crandom () * size[1]; chunkorigin[2] = aPoint[2] + crandom () * size[2]; CGF_SFX_GlassThrowDebris (aGlassPane, "models/objects/debris2/tris.md2", 2, chunkorigin); } // clear velocity, reset origin (that has been abused in ThrowDebris) VectorClear (aGlassPane->velocity); VectorCopy (old_origin, aGlassPane->s.origin); // firing thru - the pane has no direct attacker to hurt, // but G_UseTargets expects one. So make it a DIY G_UseTargets (aGlassPane, aGlassPane); } void CGF_SFX_HideBreakableGlass (edict_t * aGlassPane) { // remove all attached decals edict_t *decal; decal = 0; while ((decal = G_Find (decal, FOFS (classname), "decal"))) { if (decal->owner == aGlassPane) { // make it goaway in the next frame decal->nextthink = level.time + FRAMETIME; } } while ((decal = G_Find (decal, FOFS (classname), "splat"))) { if (decal->owner == aGlassPane) { // make it goaway in the next frame decal->nextthink = level.time + FRAMETIME; } } // after being broken, the pane cannot be freed as it is needed in // subsequent missions/games, so hide it at about z = -1000 lower aGlassPane->movetype = MOVETYPE_FLYMISSILE; VectorCopy (aGlassPane->s.origin, aGlassPane->pos1); aGlassPane->s.origin[2] -= 1000.0; } void CGF_SFX_AttachDecalToGlass (edict_t * aGlassPane, edict_t * aDecal) { // just set aDecal's owner to be the glass pane aDecal->owner = aGlassPane; } void CGF_SFX_RebuildAllBrokenGlass () { // iterate over all func_explosives edict_t *glass; glass = 0; while ((glass = G_Find (glass, FOFS (classname), "func_explosive"))) { // glass is broken if solid != SOLID_BSP if (glass->solid != SOLID_BSP) { CGF_SFX_InstallBreakableGlass (glass); } } } void CGF_SFX_ApplyGlassFragmentLimit (const char *aClassName) { edict_t *oldfragment; glassfragmentcount++; if (glassfragmentcount > glassfragmentlimit->value) glassfragmentcount = 1; // remove fragment with corresponding number if any oldfragment = FindEdictByClassnum ((char *) aClassName, glassfragmentcount); if (oldfragment) { // oldfragment->nextthink = level.time + FRAMETIME; G_FreeEdict (oldfragment); } } void CGF_SFX_MiscGlassUse (edict_t * self, edict_t * other, edict_t * activator) { #ifdef _DEBUG const char *classname; classname = other->classname; #endif } void CGF_SFX_MiscGlassDie (edict_t * self, edict_t * inflictor, edict_t * attacker, int damage, vec3_t point) { #ifdef _DEBUG const char *classname; classname = inflictor->classname; #endif } static vec_t previous_throw_time = 0; static int this_throw_count = 0; void CGF_SFX_GlassThrowDebris (edict_t * self, char *modelname, float speed, vec3_t origin) { // based on ThrowDebris from id software - now returns debris created edict_t *chunk; vec3_t v; if (level.time != previous_throw_time) { previous_throw_time = level.time; this_throw_count = 0; } else { this_throw_count++; if (this_throw_count > glassfragmentlimit->value) return; } chunk = G_Spawn (); VectorCopy (origin, chunk->s.origin); gi.setmodel (chunk, modelname); v[0] = 100 * crandom (); v[1] = 100 * crandom (); v[2] = 100 + 100 * crandom (); VectorMA (self->velocity, speed, v, chunk->velocity); chunk->movetype = MOVETYPE_BOUNCE; chunk->solid = SOLID_NOT; chunk->avelocity[0] = random () * 600; chunk->avelocity[1] = random () * 600; chunk->avelocity[2] = random () * 600; chunk->think = G_FreeEdict; chunk->nextthink = level.time + 5 + random () * 5; chunk->s.frame = 0; chunk->flags = 0; chunk->classname = "debris"; chunk->takedamage = DAMAGE_YES; chunk->die = debris_die; gi.linkentity (chunk); // number chunk chunk->classnum = glassfragmentcount; }
574
./aq2-tng/source/p_weapon.c
//----------------------------------------------------------------------------- // g_weapon.c // // $Id: p_weapon.c,v 1.20 2004/04/08 23:19:52 slicerdw Exp $ // //----------------------------------------------------------------------------- // $Log: p_weapon.c,v $ // Revision 1.20 2004/04/08 23:19:52 slicerdw // Optimized some code, added a couple of features and fixed minor bugs // // Revision 1.19 2002/04/16 16:47:46 freud // Fixed the use grenades, drop bandolier bug with use_buggy_bandolier 0 // // Revision 1.18 2002/03/27 15:16:56 freud // Original 1.52 spawn code implemented for use_newspawns 0. // Teamplay, when dropping bandolier, your drop the grenades. // Teamplay, cannot pick up grenades unless wearing bandolier. // // Revision 1.17 2002/02/01 17:49:56 freud // Heavy changes in stats code. Removed lots of variables and replaced them // with int arrays of MODs. This cleaned tng_stats.c up a whole lots and // everything looks well, might need more testing. // // Revision 1.16 2002/01/24 02:24:56 deathwatch // Major update to Stats code (thanks to Freud) // new cvars: // stats_afterround - will display the stats after a round ends or map ends // stats_endmap - if on (1) will display the stats scoreboard when the map ends // // Revision 1.15 2002/01/22 14:13:37 deathwatch // Fixed spread (back to original) // // Revision 1.14 2001/12/29 00:52:10 deathwatch // Fixed HC sound bug (not making a sound when hc_single was 0) // // Revision 1.13 2001/12/23 21:19:41 deathwatch // Updated stats with location and average // cleaned it up a bit as well // // Revision 1.12 2001/12/23 16:30:51 ra // 2.5 ready. New stats from Freud. HC and shotgun gibbing seperated. // // Revision 1.11 2001/11/08 20:56:24 igor_rock // - changed some things related to wp_flags // - corrected use_punch bug when player only has an empty weapon left // // Revision 1.10 2001/09/28 13:48:35 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.9 2001/09/02 20:33:34 deathwatch // Added use_classic and fixed an issue with ff_afterround, also updated version // nr and cleaned up some commands. // // Updated the VC Project to output the release build correctly. // // Revision 1.8 2001/08/17 21:31:37 deathwatch // Added support for stats // // Revision 1.7 2001/08/06 14:38:45 ra // Adding UVtime for ctf // // Revision 1.6 2001/07/18 15:19:11 slicerdw // Time for weapons and items dissapearing is set to "6" to prevent lag on ctf // // Revision 1.5 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.4.2.3 2001/05/27 17:24:10 igor_rock // changed spawnpoint behavior in CTF // // Revision 1.4.2.2 2001/05/25 18:59:53 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.4.2.1 2001/05/20 15:17:32 igor_rock // removed the old ctf code completly // // Revision 1.4 2001/05/13 01:23:01 deathwatch // Added Single Barreled Handcannon mode, made the menus and scoreboards // look nicer and made the voice command a bit less loud. // // Revision 1.3 2001/05/11 16:07:26 mort // Various CTF bits and pieces... // // Revision 1.2 2001/05/07 01:38:51 ra // // // Added fixes for Ammo and Weaponsfarming. // // Revision 1.1.1.1 2001/05/06 17:25:06 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" #include "m_player.h" static qboolean is_quad; static byte is_silenced; void setFFState (edict_t * ent); void weapon_grenade_fire (edict_t * ent, qboolean held); void P_ProjectSource (gclient_t * client, vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result) { vec3_t _distance; VectorCopy (distance, _distance); if (client->pers.firing_style == ACTION_FIRING_CLASSIC || client->pers.firing_style == ACTION_FIRING_CLASSIC_HIGH) { if (client->pers.hand == LEFT_HANDED) _distance[1] *= -1; else if (client->pers.hand == CENTER_HANDED) _distance[1] = 0; } else { _distance[1] = 0; // fire from center always } G_ProjectSource (point, _distance, forward, right, result); } // used for setting up the positions of the guns in shell ejection void Old_ProjectSource (gclient_t * client, vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result) { vec3_t _distance; VectorCopy (distance, _distance); if (client->pers.hand == LEFT_HANDED) _distance[1] = -1; // changed from = to *= // Fireblade 2/28/99 // zucc reversed, this is only used for setting up shell ejection and // since those look good this shouldn't be changed else if (client->pers.hand == CENTER_HANDED) _distance[1] = 0; G_ProjectSource (point, _distance, forward, right, result); } // this one is the real old project source void Knife_ProjectSource (gclient_t * client, vec3_t point, vec3_t distance, vec3_t forward, vec3_t right, vec3_t result) { vec3_t _distance; VectorCopy (distance, _distance); if (client->pers.hand == LEFT_HANDED) _distance[1] *= -1; // changed from = to *= else if (client->pers.hand == CENTER_HANDED) _distance[1] = 0; G_ProjectSource (point, _distance, forward, right, result); } /* =============== PlayerNoise Each player can have two noise objects associated with it: a personal noise (jumping, pain, weapon firing), and a weapon target noise (bullet wall impacts) Monsters that don't directly see the player can move to a noise in hopes of seeing the player from there. =============== */ void PlayerNoise (edict_t * who, vec3_t where, int type) { edict_t *noise; if (type == PNOISE_WEAPON) { if (who->client->silencer_shots) { who->client->silencer_shots--; return; } } if (deathmatch->value) return; if (who->flags & FL_NOTARGET) return; if (!who->mynoise) { noise = G_Spawn (); noise->classname = "player_noise"; VectorSet (noise->mins, -8, -8, -8); VectorSet (noise->maxs, 8, 8, 8); noise->owner = who; noise->svflags = SVF_NOCLIENT; who->mynoise = noise; noise = G_Spawn (); noise->classname = "player_noise"; VectorSet (noise->mins, -8, -8, -8); VectorSet (noise->maxs, 8, 8, 8); noise->owner = who; noise->svflags = SVF_NOCLIENT; who->mynoise2 = noise; } if (type == PNOISE_SELF || type == PNOISE_WEAPON) { noise = who->mynoise; level.sound_entity = noise; level.sound_entity_framenum = level.framenum; } else // type == PNOISE_IMPACT { noise = who->mynoise2; level.sound2_entity = noise; level.sound2_entity_framenum = level.framenum; } VectorCopy (where, noise->s.origin); VectorSubtract (where, noise->maxs, noise->absmin); VectorAdd (where, noise->maxs, noise->absmax); noise->teleport_time = level.time; gi.linkentity (noise); } void PlaceHolder (edict_t * ent) { ent->nextthink = level.time + 1000; } // keep the entity around so we can find it later if we need to respawn the weapon there void SetSpecWeapHolder (edict_t * ent) { ent->flags |= FL_RESPAWN; ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; ent->think = PlaceHolder; gi.linkentity (ent); } qboolean Pickup_Weapon (edict_t * ent, edict_t * other) { int index, index2; gitem_t *ammo; qboolean addAmmo; int special = 0; int band = 0; index = ITEM_INDEX (ent->item); if ((((int)dmflags->value & DF_WEAPONS_STAY) || coop->value) && other->client->pers.inventory[index]) { if (!(ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM))) return false; // leave the weapon for others to pickup } // find out if they have a bandolier if (INV_AMMO(other, BAND_NUM)) band = 1; else band = 0; // zucc special cases for picking up weapons // the mk23 should never be dropped, probably if (ent->item->typeNum == MK23_NUM) { if (!((int)wp_flags->value & WPF_MK23)) return false; if (other->client->pers.inventory[index]) // already has one { if (!(ent->spawnflags & DROPPED_ITEM)) { ammo = FindItem (ent->item->ammo); addAmmo = Add_Ammo (other, ammo, ammo->quantity); if(addAmmo && !(ent->spawnflags & DROPPED_PLAYER_ITEM)) SetRespawn (ent, weapon_respawn->value); return addAmmo; } } other->client->pers.inventory[index]++; if (!(ent->spawnflags & DROPPED_ITEM)) { other->client->mk23_rds = other->client->mk23_max; if(!(ent->spawnflags & DROPPED_PLAYER_ITEM)) SetRespawn (ent, weapon_respawn->value); } return true; } else if (ent->item->typeNum == MP5_NUM) { if (other->client->unique_weapon_total >= unique_weapons->value + band) return false; // we can't get it other->client->pers.inventory[index]++; other->client->unique_weapon_total++; if (!(ent->spawnflags & DROPPED_ITEM)) { other->client->mp5_rds = other->client->mp5_max; } special = 1; gi.cprintf (other, PRINT_HIGH, "%s - Unique Weapon\n", ent->item->pickup_name); } else if (ent->item->typeNum == M4_NUM) { if (other->client->unique_weapon_total >= unique_weapons->value + band) return false; // we can't get it other->client->pers.inventory[index]++; other->client->unique_weapon_total++; if (!(ent->spawnflags & DROPPED_ITEM)) { other->client->m4_rds = other->client->m4_max; } special = 1; gi.cprintf (other, PRINT_HIGH, "%s - Unique Weapon\n", ent->item->pickup_name); } else if (ent->item->typeNum == M3_NUM) { if (other->client->unique_weapon_total >= unique_weapons->value + band) return false; // we can't get it other->client->pers.inventory[index]++; other->client->unique_weapon_total++; if (!(ent->spawnflags & DROPPED_ITEM)) { // any weapon that doesn't completely fill up each reload can //end up in a state where it has a full weapon and pending reload(s) if (other->client->weaponstate == WEAPON_RELOADING && other->client->curr_weap == M3_NUM) { if (other->client->fast_reload) other->client->shot_rds = other->client->shot_max - 2; else other->client->shot_rds = other->client->shot_max - 1; } else { other->client->shot_rds = other->client->shot_max; } } special = 1; gi.cprintf (other, PRINT_HIGH, "%s - Unique Weapon\n", ent->item->pickup_name); } else if (ent->item->typeNum == HC_NUM) { if (other->client->unique_weapon_total >= unique_weapons->value + band) return false; // we can't get it other->client->pers.inventory[index]++; other->client->unique_weapon_total++; if (!(ent->spawnflags & DROPPED_ITEM)) { other->client->cannon_rds = other->client->cannon_max; index2 = ITEM_INDEX (FindItem (ent->item->ammo)); if (other->client->pers.inventory[index2] + 5 > other->client->pers.max_shells) other->client->pers.inventory[index2] = other->client->pers.max_shells; else other->client->pers.inventory[index2] += 5; } gi.cprintf (other, PRINT_HIGH, "%s - Unique Weapon\n", ent->item->pickup_name); special = 1; } else if (ent->item->typeNum == SNIPER_NUM) { if (other->client->unique_weapon_total >= unique_weapons->value + band) return false; // we can't get it other->client->pers.inventory[index]++; other->client->unique_weapon_total++; if (!(ent->spawnflags & DROPPED_ITEM)) { if (other->client->weaponstate == WEAPON_RELOADING && other->client->curr_weap == SNIPER_NUM) { if (other->client->fast_reload) other->client->sniper_rds = other->client->sniper_max - 2; else other->client->sniper_rds = other->client->sniper_max - 1; } else { other->client->sniper_rds = other->client->sniper_max; } } special = 1; gi.cprintf (other, PRINT_HIGH, "%s - Unique Weapon\n", ent->item->pickup_name); } else if (ent->item->typeNum == DUAL_NUM) { if (!((int)wp_flags->value & WPF_MK23)) return false; if (other->client->pers.inventory[index]) // already has one { if (!(ent->spawnflags & DROPPED_ITEM)) { ammo = FindItem (ent->item->ammo); addAmmo = Add_Ammo (other, ammo, ammo->quantity); if(addAmmo && !(ent->spawnflags & DROPPED_PLAYER_ITEM)) SetRespawn (ent, weapon_respawn->value); return addAmmo; } } other->client->pers.inventory[index]++; if (!(ent->spawnflags & DROPPED_ITEM)) { other->client->dual_rds += other->client->mk23_max; // assume the player uses the new (full) pistol other->client->mk23_rds = other->client->mk23_max; if(!(ent->spawnflags & DROPPED_PLAYER_ITEM)) SetRespawn (ent, weapon_respawn->value); } return true; } else if (ent->item->typeNum == KNIFE_NUM) { if (other->client->pers.inventory[index] < other->client->knife_max) { other->client->pers.inventory[index]++; return true; } return false; } else if (ent->item->typeNum == GRENADE_NUM) { if (teamplay->value && !teamdm->value && ctf->value != 2 && !band) return false; if (other->client->pers.inventory[index] >= other->client->grenade_max) return false; other->client->pers.inventory[index]++; if (!(ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM))) { if (deathmatch->value) { if ((int)(dmflags->value) & DF_WEAPONS_STAY) ent->flags |= FL_RESPAWN; else SetRespawn (ent, ammo_respawn->value); } if (coop->value) ent->flags |= FL_RESPAWN; } return true; } else { other->client->pers.inventory[index]++; if (!(ent->spawnflags & DROPPED_ITEM)) { // give them some ammo with it ammo = FindItem (ent->item->ammo); if ((int)dmflags->value & DF_INFINITE_AMMO) Add_Ammo (other, ammo, 1000); else Add_Ammo (other, ammo, ammo->quantity); if (!(ent->spawnflags & DROPPED_PLAYER_ITEM)) { if (deathmatch->value) { if ((int)dmflags->value & DF_WEAPONS_STAY) ent->flags |= FL_RESPAWN; else SetRespawn (ent, 30); } if (coop->value) ent->flags |= FL_RESPAWN; } } } /* zucc - don't want auto switching if (other->client->pers.weapon != ent->item && (other->client->pers.inventory[index] == 1) && ( !deathmatch->value || other->client->pers.weapon == FindItem("blaster") ) ) other->client->newweapon = ent->item; */ if (!(ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM)) && (SPEC_WEAPON_RESPAWN) && special) { if(((int)dmflags->value & DF_WEAPON_RESPAWN) && (!teamplay->value || teamdm->value || ctf->value == 2)) SetRespawn (ent, weapon_respawn->value); else SetSpecWeapHolder (ent); } return true; } // zucc vwep 3.17(?) vwep support void ShowGun (edict_t * ent) { int nIndex; char *pszIcon; // No weapon? if (!ent->client->pers.weapon) { ent->s.modelindex2 = 0; return; } // Determine the weapon's precache index. nIndex = 0; pszIcon = ent->client->pers.weapon->icon; if (strcmp (pszIcon, "w_mk23") == 0) nIndex = 1; else if (strcmp (pszIcon, "w_mp5") == 0) nIndex = 2; else if (strcmp (pszIcon, "w_m4") == 0) nIndex = 3; else if (strcmp (pszIcon, "w_cannon") == 0) nIndex = 4; else if (strcmp (pszIcon, "w_super90") == 0) nIndex = 5; else if (strcmp (pszIcon, "w_sniper") == 0) nIndex = 6; else if (strcmp (pszIcon, "w_akimbo") == 0) nIndex = 7; else if (strcmp (pszIcon, "w_knife") == 0) nIndex = 8; else if (strcmp (pszIcon, "a_m61frag") == 0) nIndex = 9; // Clear previous weapon model. ent->s.skinnum &= 255; // Set new weapon model. ent->s.skinnum |= (nIndex << 8); ent->s.modelindex2 = 255; /* char heldmodel[128]; int len; if(!ent->client->pers.weapon) { ent->s.modelindex2 = 0; return; } strcpy(heldmodel, "players/"); strcat(heldmodel, Info_ValueForKey (ent->client->pers.userinfo, "skin")); for(len = 8; heldmodel[len]; len++) { if(heldmodel[len] == '/') heldmodel[++len] = '\0'; } strcat(heldmodel, ent->client->pers.weapon->icon); strcat(heldmodel, ".md2"); //gi.dprintf ("%s\n", heldmodel); ent->s.modelindex2 = gi.modelindex(heldmodel); */ } //#define GRENADE_IDLE_FIRST 40 //#define GRENADE_IDLE_LAST 69 /* =============== ChangeWeapon The old weapon has been dropped all the way, so make the new one current =============== */ void ChangeWeapon (edict_t * ent) { if (ent->client->grenade_time) { ent->client->grenade_time = level.time; ent->client->weapon_sound = 0; weapon_grenade_fire (ent, false); ent->client->grenade_time = 0; } if(ent->client->ctf_grapple) CTFPlayerResetGrapple(ent); // zucc - prevent reloading queue for previous weapon from doing anything ent->client->reload_attempts = 0; ent->client->pers.lastweapon = ent->client->pers.weapon; ent->client->pers.weapon = ent->client->newweapon; ent->client->newweapon = NULL; ent->client->machinegun_shots = 0; if (ent->client->pers.weapon && ent->client->pers.weapon->ammo) ent->client->ammo_index = ITEM_INDEX (FindItem (ent->client->pers.weapon->ammo)); else ent->client->ammo_index = 0; if (!ent->client->pers.weapon || ent->s.modelindex != 255) // zucc vwep { // dead ent->client->ps.gunindex = 0; return; } ent->client->weaponstate = WEAPON_ACTIVATING; ent->client->ps.gunframe = 0; //FIREBLADE if (ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) return; //FIREBLADE ent->client->ps.gunindex = gi.modelindex (ent->client->pers.weapon->view_model); // zucc hentai's animation for vwep ent->client->anim_priority = ANIM_PAIN; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain1; ent->client->anim_end = FRAME_crpain4; } else { ent->s.frame = FRAME_pain301; ent->client->anim_end = FRAME_pain304; } ShowGun (ent); // zucc done switch(ent->client->pers.weapon->typeNum) { case MK23_NUM: case MP5_NUM: case M4_NUM: case M3_NUM: case HC_NUM: case SNIPER_NUM: case DUAL_NUM: case KNIFE_NUM: case GRAPPLE_NUM: ent->client->curr_weap = ent->client->pers.weapon->typeNum; break; case GRENADE_NUM: // Fix the "use grenades;drop bandolier" bug, caused infinite grenades. if (teamplay->value && INV_AMMO(ent, GRENADE_NUM) == 0) INV_AMMO(ent, GRENADE_NUM) = 1; ent->client->curr_weap = ent->client->pers.weapon->typeNum; break; } if (INV_AMMO(ent, LASER_NUM)) SP_LaserSight (ent, GET_ITEM(LASER_NUM)); //item->use(ent, item); } /* ================= NoAmmoWeaponChange ================= */ void NoAmmoWeaponChange (edict_t * ent) { if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("slugs"))] && ent->client->pers.inventory[ITEM_INDEX (FindItem ("railgun"))]) { ent->client->newweapon = FindItem ("railgun"); return; } if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("cells"))] && ent->client->pers.inventory[ITEM_INDEX (FindItem ("hyperblaster"))]) { ent->client->newweapon = FindItem ("hyperblaster"); return; } if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("bullets"))] && ent->client->pers.inventory[ITEM_INDEX (FindItem ("chaingun"))]) { ent->client->newweapon = FindItem ("chaingun"); return; } if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("bullets"))] && ent->client->pers.inventory[ITEM_INDEX (FindItem ("machinegun"))]) { ent->client->newweapon = FindItem ("machinegun"); return; } if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("shells"))] > 1 && ent->client->pers.inventory[ITEM_INDEX (FindItem ("super shotgun"))]) { ent->client->newweapon = FindItem ("super shotgun"); return; } if (ent->client->pers.inventory[ITEM_INDEX (FindItem ("shells"))] && ent->client->pers.inventory[ITEM_INDEX (FindItem ("shotgun"))]) { ent->client->newweapon = FindItem ("shotgun"); return; } ent->client->newweapon = FindItem ("blaster"); } /* ================= Think_Weapon Called by ClientBeginServerFrame and ClientThink ================= */ void Think_Weapon (edict_t * ent) { // if just died, put the weapon away if (ent->health < 1) { ent->client->newweapon = NULL; ChangeWeapon (ent); } // call active weapon think routine if (ent->client->pers.weapon && ent->client->pers.weapon->weaponthink) { is_quad = (ent->client->quad_framenum > level.framenum); if (ent->client->silencer_shots) is_silenced = MZ_SILENCED; else is_silenced = 0; ent->client->pers.weapon->weaponthink (ent); } } /* ================ Use_Weapon Make the weapon ready if there is ammo ================ */ void Use_Weapon (edict_t * ent, gitem_t * item) { //int ammo_index; //gitem_t *ammo_item; // if(ent->client->weaponstate == WEAPON_BANDAGING || ent->client->bandaging == 1 ) // return; // see if we're already using it if (item == ent->client->pers.weapon) return; // zucc - let them change if they want /*if (item->ammo && !g_select_empty->value && !(item->flags & IT_AMMO)) { ammo_item = FindItem(item->ammo); ammo_index = ITEM_INDEX(ammo_item); if (!ent->client->pers.inventory[ammo_index]) { gi.cprintf (ent, PRINT_HIGH, "No %s for %s.\n", ammo_item->pickup_name, item->pickup_name); return; } if (ent->client->pers.inventory[ammo_index] < item->quantity) { gi.cprintf (ent, PRINT_HIGH, "Not enough %s for %s.\n", ammo_item->pickup_name, item->pickup_name); return; } } */ // change to this weapon when down ent->client->newweapon = item; } edict_t * FindSpecWeapSpawn (edict_t * ent) { edict_t *spot = NULL; //gi.bprintf (PRINT_HIGH, "Calling the FindSpecWeapSpawn\n"); spot = G_Find (spot, FOFS (classname), ent->classname); //gi.bprintf (PRINT_HIGH, "spot = %p and spot->think = %p and playerholder = %p, spot, (spot ? spot->think : 0), PlaceHolder\n"); while (spot && spot->think != PlaceHolder) //(spot->spawnflags & DROPPED_ITEM ) && spot->think != PlaceHolder )//spot->solid == SOLID_NOT ) { // gi.bprintf (PRINT_HIGH, "Calling inside the loop FindSpecWeapSpawn\n"); spot = G_Find (spot, FOFS (classname), ent->classname); } /* if (!spot) { gi.bprintf(PRINT_HIGH, "Failed to find a spawn spot for %s\n", ent->classname); } else gi.bprintf(PRINT_HIGH, "Found a spawn spot for %s\n", ent->classname); */ return spot; } void ThinkSpecWeap (edict_t * ent); static void SpawnSpecWeap (gitem_t * item, edict_t * spot) { /* edict_t *ent; vec3_t forward, right; vec3_t angles; ent = G_Spawn(); ent->classname = item->classname; ent->item = item; ent->spawnflags = DROPPED_PLAYER_ITEM;//DROPPED_ITEM; ent->s.effects = item->world_model_flags; ent->s.renderfx = RF_GLOW; VectorSet (ent->mins, -15, -15, -15); VectorSet (ent->maxs, 15, 15, 15); gi.setmodel (ent, ent->item->world_model); ent->solid = SOLID_TRIGGER; ent->movetype = MOVETYPE_TOSS; ent->touch = Touch_Item; ent->owner = ent; angles[0] = 0; angles[1] = rand() % 360; angles[2] = 0; AngleVectors (angles, forward, right, NULL); VectorCopy (spot->s.origin, ent->s.origin); ent->s.origin[2] += 16; VectorScale (forward, 100, ent->velocity); ent->velocity[2] = 300; ent->think = NULL; gi.linkentity (ent); */ SetRespawn (spot, 1); gi.linkentity (spot); } void temp_think_specweap (edict_t * ent) { ent->touch = Touch_Item; if(((int)dmflags->value & DF_WEAPON_RESPAWN) && (!teamplay->value || teamdm->value || ctf->value == 2)) { ent->nextthink = level.time + (weapon_respawn->value * 0.6f); ent->think = G_FreeEdict; } else if (ctf->value || (dm_choose->value && !teamplay->value && deathmatch->value)) { ent->nextthink = level.time + 6; ent->think = ThinkSpecWeap; } else if (deathmatch->value && (!teamplay->value || teamdm->value) && !allweapon->value) { ent->nextthink = level.time + weapon_respawn->value; ent->think = ThinkSpecWeap; } else if (teamplay->value && !allweapon->value) { ent->nextthink = level.time + 1000; ent->think = PlaceHolder; } else // allweapon set { ent->nextthink = level.time + 1; ent->think = G_FreeEdict; } } // zucc make dropped weapons respawn elsewhere void ThinkSpecWeap (edict_t * ent) { edict_t *spot; if ((spot = FindSpecWeapSpawn (ent)) != NULL) { SpawnSpecWeap (ent->item, spot); G_FreeEdict (ent); } else { ent->nextthink = level.time + 1; ent->think = G_FreeEdict; } } /* ================ Drop_Weapon ================ */ void Drop_Weapon (edict_t * ent, gitem_t * item) { int index; gitem_t *replacement; edict_t *temp = NULL; if ((int) (dmflags->value) & DF_WEAPONS_STAY) return; // AQ:TNG - JBravo fixing weapon farming if (ent->client->weaponstate == WEAPON_DROPPING || ent->client->weaponstate == WEAPON_BUSY) return; // Weapon farming fix end. if (ent->client->weaponstate == WEAPON_BANDAGING || ent->client->bandaging == 1 || ent->client->bandage_stopped == 1) { gi.cprintf (ent, PRINT_HIGH, "You are too busy bandaging right now...\n"); return; } // don't let them drop this, causes duplication if (ent->client->newweapon == item) return; index = ITEM_INDEX (item); // see if we're already using it //zucc special cases for dropping if (item->typeNum == MK23_NUM) { gi.cprintf (ent, PRINT_HIGH, "Can't drop the %s.\n", MK23_NAME); return; } else if (item->typeNum == MP5_NUM) { if (ent->client->pers.weapon == item && (ent->client->pers.inventory[index] == 1)) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 51; //ChangeWeapon( ent ); } ent->client->unique_weapon_total--; // dropping 1 unique weapon temp = Drop_Item (ent, item); temp->think = temp_think_specweap; ent->client->pers.inventory[index]--; } else if (item->typeNum == M4_NUM) { if (ent->client->pers.weapon == item && (ent->client->pers.inventory[index] == 1)) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 44; //ChangeWeapon( ent ); } ent->client->unique_weapon_total--; // dropping 1 unique weapon temp = Drop_Item (ent, item); temp->think = temp_think_specweap; ent->client->pers.inventory[index]--; } else if (item->typeNum == M3_NUM) { if (ent->client->pers.weapon == item && (ent->client->pers.inventory[index] == 1)) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 41; //ChangeWeapon( ent ); } ent->client->unique_weapon_total--; // dropping 1 unique weapon temp = Drop_Item (ent, item); temp->think = temp_think_specweap; ent->client->pers.inventory[index]--; } else if (item->typeNum == HC_NUM) { if (ent->client->pers.weapon == item && (ent->client->pers.inventory[index] == 1)) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 61; //ChangeWeapon( ent ); } ent->client->unique_weapon_total--; // dropping 1 unique weapon temp = Drop_Item (ent, item); temp->think = temp_think_specweap; ent->client->pers.inventory[index]--; } else if (item->typeNum == SNIPER_NUM) { if (ent->client->pers.weapon == item && (ent->client->pers.inventory[index] == 1)) { // in case they are zoomed in ent->client->ps.fov = 90; ent->client->desired_fov = 90; replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 50; //ChangeWeapon( ent ); } ent->client->unique_weapon_total--; // dropping 1 unique weapon temp = Drop_Item (ent, item); temp->think = temp_think_specweap; ent->client->pers.inventory[index]--; } else if (item->typeNum == DUAL_NUM) { if (ent->client->pers.weapon == item) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 40; //ChangeWeapon( ent ); } ent->client->dual_rds = ent->client->mk23_rds; } else if (item->typeNum == KNIFE_NUM) { //gi.cprintf(ent, PRINT_HIGH, "Before checking knife inven frames = %d\n", ent->client->ps.gunframe); if (((ent->client->pers.weapon == item)) && (ent->client->pers.inventory[index] == 1)) { replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; if (ent->client->resp.knife_mode) // hack to avoid an error { ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 111; } else ChangeWeapon (ent); // gi.cprintf(ent, PRINT_HIGH, "After change weap from knife drop frames = %d\n", ent->client->ps.gunframe); } } else if (item->typeNum == GRENADE_NUM) { if ((ent->client->pers.weapon == item) && (ent->client->pers.inventory[index] == 1)) { if (((ent->client->ps.gunframe >= GRENADE_IDLE_FIRST) && (ent->client->ps.gunframe <= GRENADE_IDLE_LAST)) || ((ent->client->ps.gunframe >= GRENADE_THROW_FIRST && ent->client->ps.gunframe <= GRENADE_THROW_LAST))) { int damage; ent->client->ps.gunframe = 0; // Reset Grenade Damage to 1.52 when requested: if (use_classic->value) damage = 170; else damage = GRENADE_DAMRAD; if(ent->client->quad_framenum > level.framenum) damage *= 1.5f; fire_grenade2(ent, ent->s.origin, vec3_origin, damage, 0, 2, damage * 2, false); INV_AMMO(ent, GRENADE_NUM)--; ent->client->newweapon = GET_ITEM(MK23_NUM); ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 0; return; } replacement = GET_ITEM(MK23_NUM); // back to the pistol then ent->client->newweapon = replacement; ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = 0; //ChangeWeapon( ent ); } } else if ((item == ent->client->pers.weapon || item == ent->client->newweapon) && ent->client->pers.inventory[index] == 1) { gi.cprintf (ent, PRINT_HIGH, "Can't drop current weapon\n"); return; } // AQ:TNG - JBravo fixing weapon farming if (ent->client->unique_weapon_total < 0) ent->client->unique_weapon_total = 0; if (ent->client->pers.inventory[index] < 0) ent->client->pers.inventory[index] = 0; // Weapon farming fix end if (!temp) { temp = Drop_Item (ent, item); ent->client->pers.inventory[index]--; } } //zucc drop special weapon (only 1 of them) void DropSpecialWeapon (edict_t * ent) { // first check if their current weapon is a special weapon, if so, drop it. if (ent->client->pers.weapon->typeNum == MP5_NUM || ent->client->pers.weapon->typeNum == M4_NUM || ent->client->pers.weapon->typeNum == M3_NUM || ent->client->pers.weapon->typeNum == HC_NUM || ent->client->pers.weapon->typeNum == SNIPER_NUM) Drop_Weapon (ent, ent->client->pers.weapon); else if (INV_AMMO(ent, SNIPER_NUM) > 0) Drop_Weapon (ent, GET_ITEM(SNIPER_NUM)); else if (INV_AMMO(ent, HC_NUM) > 0) Drop_Weapon (ent, GET_ITEM(HC_NUM)); else if (INV_AMMO(ent, M3_NUM) > 0) Drop_Weapon (ent, GET_ITEM(M3_NUM)); else if (INV_AMMO(ent, MP5_NUM) > 0) Drop_Weapon (ent, GET_ITEM(MP5_NUM)); else if (INV_AMMO(ent, M4_NUM) > 0) Drop_Weapon (ent, GET_ITEM(M4_NUM)); // special case, aq does this, guess I can support it else if (ent->client->pers.weapon->typeNum == DUAL_NUM) ent->client->newweapon = GET_ITEM(MK23_NUM); } // used for when we want to force a player to drop an extra special weapon // for when they drop the bandolier and they are over the weapon limit void DropExtraSpecial (edict_t * ent) { gitem_t *item; if (ent->client->pers.weapon->typeNum == MP5_NUM || ent->client->pers.weapon->typeNum == M4_NUM || ent->client->pers.weapon->typeNum == M3_NUM || ent->client->pers.weapon->typeNum == HC_NUM || ent->client->pers.weapon->typeNum == SNIPER_NUM) { item = ent->client->pers.weapon; // if they have more than 1 then they are willing to drop one if (ent->client->pers.inventory[ITEM_INDEX (item)] > 1) { Drop_Weapon (ent, ent->client->pers.weapon); return; } } // otherwise drop some weapon they aren't using if (INV_AMMO(ent, SNIPER_NUM) > 0 && SNIPER_NUM != ent->client->pers.weapon->typeNum) Drop_Weapon (ent, GET_ITEM(SNIPER_NUM)); else if (INV_AMMO(ent, HC_NUM) > 0 && HC_NUM != ent->client->pers.weapon->typeNum) Drop_Weapon (ent, GET_ITEM(HC_NUM)); else if (INV_AMMO(ent, M3_NUM) > 0 && M3_NUM != ent->client->pers.weapon->typeNum) Drop_Weapon (ent, GET_ITEM(M3_NUM)); else if (INV_AMMO(ent, MP5_NUM) > 0 && MP5_NUM != ent->client->pers.weapon->typeNum) Drop_Weapon (ent, GET_ITEM(MP5_NUM)); else if (INV_AMMO(ent, M4_NUM) > 0 && M4_NUM != ent->client->pers.weapon->typeNum) Drop_Weapon (ent, GET_ITEM(M4_NUM)); else gi.dprintf ("Couldn't find the appropriate weapon to drop.\n"); } //zucc ready special weapon void ReadySpecialWeapon (edict_t * ent) { int weapons[5] = { MP5_NUM, M4_NUM, M3_NUM, HC_NUM, SNIPER_NUM }; int curr, i; int last; if (ent->client->weaponstate == WEAPON_BANDAGING || ent->client->bandaging == 1) return; for (curr = 0; curr < 5; curr++) { if (ent->client->curr_weap == weapons[curr]) break; } if (curr >= 5) { curr = -1; last = 5; } else { last = curr + 5; } for (i = (curr + 1); i != last; i = (i + 1)) { if (INV_AMMO(ent, weapons[i % 5])) { ent->client->newweapon = GET_ITEM(weapons[i % 5]); return; } } } /* ================ Weapon_Generic A generic function to handle the basics of weapon thinking ================ */ //zucc - copied in BD's code, modified for use with other weapons #define FRAME_FIRE_FIRST (FRAME_ACTIVATE_LAST + 1) #define FRAME_IDLE_FIRST (FRAME_FIRE_LAST + 1) #define FRAME_DEACTIVATE_FIRST (FRAME_IDLE_LAST + 1) #define FRAME_RELOAD_FIRST (FRAME_DEACTIVATE_LAST +1) #define FRAME_LASTRD_FIRST (FRAME_RELOAD_LAST +1) #define MK23MAG 12 #define MP5MAG 30 #define M4MAG 24 #define DUALMAG 24 void Weapon_Generic (edict_t * ent, int FRAME_ACTIVATE_LAST, int FRAME_FIRE_LAST, int FRAME_IDLE_LAST, int FRAME_DEACTIVATE_LAST, int FRAME_RELOAD_LAST, int FRAME_LASTRD_LAST, int *pause_frames, int *fire_frames, void (*fire) (edict_t * ent)) { int n; int bFire = 0; int bOut = 0; /* int bBursting = 0;*/ // zucc vwep if (ent->s.modelindex != 255) return; // not on client, so VWep animations could do wacky things if(ent->client->ctf_grapple) { if (Q_stricmp(ent->client->pers.weapon->pickup_name, "Grapple") == 0 && ent->client->weaponstate == WEAPON_FIRING) return; } //FIREBLADE if (ent->client->weaponstate == WEAPON_FIRING && ((ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) || lights_camera_action)) { ent->client->weaponstate = WEAPON_READY; } //FIREBLADE //+BD - Added Reloading weapon, done manually via a cmd if (ent->client->weaponstate == WEAPON_RELOADING) { if (ent->client->ps.gunframe < FRAME_RELOAD_FIRST || ent->client->ps.gunframe > FRAME_RELOAD_LAST) ent->client->ps.gunframe = FRAME_RELOAD_FIRST; else if (ent->client->ps.gunframe < FRAME_RELOAD_LAST) { ent->client->ps.gunframe++; switch (ent->client->curr_weap) { //+BD - Check weapon to find out when to play reload sounds case MK23_NUM: { if (ent->client->ps.gunframe == 46) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23out.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 53) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23in.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 59) // 3 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23slap.wav"), 1, ATTN_NORM, 0); break; } case MP5_NUM: { if (ent->client->ps.gunframe == 55) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mp5out.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 59) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mp5in.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 63) //61 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mp5slap.wav"), 1, ATTN_NORM, 0); break; } case M4_NUM: { if (ent->client->ps.gunframe == 52) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/m4a1out.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 58) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/m4a1in.wav"), 1, ATTN_NORM, 0); break; } case M3_NUM: { if (ent->client->shot_rds >= ent->client->shot_max) { ent->client->ps.gunframe = FRAME_IDLE_FIRST; ent->client->weaponstate = WEAPON_READY; return; } if (ent->client->ps.gunframe == 48) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/m3in.wav"), 1, ATTN_NORM, 0); } if (ent->client->ps.gunframe == 49) { if (ent->client->fast_reload == 1) { ent->client->fast_reload = 0; ent->client->shot_rds++; ent->client->ps.gunframe = 44; } } break; } case HC_NUM: { if (ent->client->ps.gunframe == 64) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/copen.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 67) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cout.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 76) //61 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cin.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 80) // 3 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cclose.wav"), 1, ATTN_NORM, 0); break; } case SNIPER_NUM: { if (ent->client->sniper_rds >= ent->client->sniper_max) { ent->client->ps.gunframe = FRAME_IDLE_FIRST; ent->client->weaponstate = WEAPON_READY; return; } if (ent->client->ps.gunframe == 59) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/ssgbolt.wav"), 1, ATTN_NORM, 0); } else if (ent->client->ps.gunframe == 71) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/ssgin.wav"), 1, ATTN_NORM, 0); } else if (ent->client->ps.gunframe == 73) { if (ent->client->fast_reload == 1) { ent->client->fast_reload = 0; ent->client->sniper_rds++; ent->client->ps.gunframe = 67; } } else if (ent->client->ps.gunframe == 76) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/ssgbolt.wav"), 1, ATTN_NORM, 0); } break; } case DUAL_NUM: { if (ent->client->ps.gunframe == 45) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23out.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 53) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23slap.wav"), 1, ATTN_NORM, 0); else if (ent->client->ps.gunframe == 60) // 3 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23slap.wav"), 1, ATTN_NORM, 0); break; } default: gi.dprintf ("No weapon choice for reloading (sounds).\n"); break; } } else { ent->client->ps.gunframe = FRAME_IDLE_FIRST; ent->client->weaponstate = WEAPON_READY; switch (ent->client->curr_weap) { case MK23_NUM: { ent->client->dual_rds -= ent->client->mk23_rds; ent->client->mk23_rds = ent->client->mk23_max; ent->client->dual_rds += ent->client->mk23_max; (ent->client->pers.inventory[ent->client->ammo_index])--; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } ent->client->fired = 0; // reset any firing delays break; //else // ent->client->mk23_rds = ent->client->pers.inventory[ent->client->ammo_index]; } case MP5_NUM: { ent->client->mp5_rds = ent->client->mp5_max; (ent->client->pers.inventory[ent->client->ammo_index])--; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } ent->client->fired = 0; // reset any firing delays ent->client->burst = 0; // reset any bursting break; } case M4_NUM: { ent->client->m4_rds = ent->client->m4_max; (ent->client->pers.inventory[ent->client->ammo_index])--; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } ent->client->fired = 0; // reset any firing delays ent->client->burst = 0; // reset any bursting ent->client->machinegun_shots = 0; break; } case M3_NUM: { ent->client->shot_rds++; (ent->client->pers.inventory[ent->client->ammo_index])--; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } break; } case HC_NUM: { if(hc_single->value) { int count = 0; if(ent->client->cannon_rds == 1) count = 1; else if ((ent->client->pers.inventory[ent->client->ammo_index]) == 1) count = 1; else count = ent->client->cannon_max; ent->client->cannon_rds += count; (ent->client->pers.inventory[ent->client->ammo_index]) -= count; } else { ent->client->cannon_rds = ent->client->cannon_max; (ent->client->pers.inventory[ent->client->ammo_index]) -= 2; } if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } break; } case SNIPER_NUM: { ent->client->sniper_rds++; (ent->client->pers.inventory[ent->client->ammo_index])--; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } return; } case DUAL_NUM: { ent->client->dual_rds = ent->client->dual_max; ent->client->mk23_rds = ent->client->mk23_max; (ent->client->pers.inventory[ent->client->ammo_index]) -= 2; if (ent->client->pers.inventory[ent->client->ammo_index] < 0) { ent->client->pers.inventory[ent->client->ammo_index] = 0; } break; } default: gi.dprintf ("No weapon choice for reloading.\n"); break; } } } if (ent->client->weaponstate == WEAPON_END_MAG) { if (ent->client->ps.gunframe < FRAME_LASTRD_LAST) ent->client->ps.gunframe++; else ent->client->ps.gunframe = FRAME_LASTRD_LAST; // see if our weapon has ammo (from something other than reloading) if ( ((ent->client->curr_weap == MK23_NUM) && (ent->client->mk23_rds > 0)) || ((ent->client->curr_weap == MP5_NUM) && (ent->client->mp5_rds > 0)) || ((ent->client->curr_weap == M4_NUM) && (ent->client->m4_rds > 0)) || ((ent->client->curr_weap == M3_NUM) && (ent->client->shot_rds > 0)) || ((ent->client->curr_weap == HC_NUM) && (ent->client->cannon_rds > 0)) || ((ent->client->curr_weap == SNIPER_NUM) && (ent->client->sniper_rds > 0)) || ((ent->client->curr_weap == DUAL_NUM) && (ent->client->dual_rds > 0))) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE_FIRST; } if ( ((ent-> client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK) //FIREBLADE // AQ2:TNG - JBravo adding UVtime && (ent->solid != SOLID_NOT || ent->deadflag == DEAD_DEAD) && !lights_camera_action && !ent->client->ctf_uvtime) //FIREBLADE { ent->client->latched_buttons &= ~BUTTON_ATTACK; { if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } } } } if (ent->client->weaponstate == WEAPON_DROPPING) { if (ent->client->ps.gunframe == FRAME_DEACTIVATE_LAST) { ChangeWeapon (ent); return; } // zucc for vwep else if ((FRAME_DEACTIVATE_LAST - ent->client->ps.gunframe) == 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } ent->client->ps.gunframe++; return; } if (ent->client->weaponstate == WEAPON_BANDAGING) { if (ent->client->ps.gunframe == FRAME_DEACTIVATE_LAST) { ent->client->weaponstate = WEAPON_BUSY; ent->client->idle_weapon = BANDAGE_TIME; return; } ent->client->ps.gunframe++; return; } if (ent->client->weaponstate == WEAPON_ACTIVATING) { if (ent->client->ps.gunframe == FRAME_ACTIVATE_LAST) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE_FIRST; return; } // sounds for activation? switch (ent->client->curr_weap) { case MK23_NUM: { if (ent->client->dual_rds >= ent->client->mk23_max) ent->client->mk23_rds = ent->client->mk23_max; else ent->client->mk23_rds = ent->client->dual_rds; if (ent->client->ps.gunframe == 3) // 3 { if (ent->client->mk23_rds > 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23slide.wav"), 1, ATTN_NORM, 0); } else { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); //mk23slap ent->client->ps.gunframe = 62; ent->client->weaponstate = WEAPON_END_MAG; } } ent->client->fired = 0; //reset any firing delays break; } case MP5_NUM: { if (ent->client->ps.gunframe == 3) // 3 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mp5slide.wav"), 1, ATTN_NORM, 0); ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; break; } case M4_NUM: { if (ent->client->ps.gunframe == 3) // 3 gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/m4a1slide.wav"), 1, ATTN_NORM, 0); ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; ent->client->machinegun_shots = 0; break; } case M3_NUM: { ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; ent->client->fast_reload = 0; break; } case HC_NUM: { ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; break; } case SNIPER_NUM: { ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; ent->client->fast_reload = 0; break; } case DUAL_NUM: { if (ent->client->dual_rds <= 0 && ent->client->ps.gunframe == 3) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); if (ent->client->dual_rds <= 0 && ent->client->ps.gunframe == 4) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->client->ps.gunframe = 68; ent->client->weaponstate = WEAPON_END_MAG; ent->client->resp.sniper_mode = 0; ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; return; } ent->client->fired = 0; //reset any firing delays ent->client->burst = 0; break; } case GRAPPLE_NUM: break; default: gi.dprintf ("Activated unknown weapon.\n"); break; } ent->client->resp.sniper_mode = 0; // has to be here for dropping the sniper rifle, in the drop command didn't work... ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->ps.gunframe++; return; } if (ent->client->weaponstate == WEAPON_BUSY) { if (ent->client->bandaging == 1) { if (!(ent->client->idle_weapon)) { Bandage (ent); return; } else { (ent->client->idle_weapon)--; return; } } // for after bandaging delay if (!(ent->client->idle_weapon) && ent->client->bandage_stopped) { ent->client->weaponstate = WEAPON_ACTIVATING; ent->client->ps.gunframe = 0; ent->client->bandage_stopped = 0; return; } else if (ent->client->bandage_stopped) { (ent->client->idle_weapon)--; return; } if (ent->client->curr_weap == SNIPER_NUM) { if (ent->client->desired_fov == 90) { ent->client->ps.fov = 90; ent->client->weaponstate = WEAPON_READY; ent->client->idle_weapon = 0; } if (!(ent->client->idle_weapon) && ent->client->desired_fov != 90) { ent->client->ps.fov = ent->client->desired_fov; ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunindex = 0; return; } else (ent->client->idle_weapon)--; } } if ((ent->client->newweapon) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BURSTING) && (ent->client->bandage_stopped == 0)) { ent->client->weaponstate = WEAPON_DROPPING; ent->client->ps.gunframe = FRAME_DEACTIVATE_FIRST; ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->resp.sniper_mode = 0; if (ent->client->pers.weapon) ent->client->ps.gunindex = gi.modelindex (ent->client->pers.weapon->view_model); // zucc more vwep stuff if ((FRAME_DEACTIVATE_LAST - FRAME_DEACTIVATE_FIRST) < 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } return; } // bandaging case if ((ent->client->bandaging) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BURSTING) && (ent->client->weaponstate != WEAPON_BUSY) && (ent->client->weaponstate != WEAPON_BANDAGING)) { ent->client->weaponstate = WEAPON_BANDAGING; ent->client->ps.gunframe = FRAME_DEACTIVATE_FIRST; return; } if (ent->client->weaponstate == WEAPON_READY) { if ( ((ent-> client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK) //FIREBLADE // AQ2:TNG - JBravo adding UVtime && (ent->solid != SOLID_NOT || ent->deadflag == DEAD_DEAD) && !lights_camera_action && (!ent->client->ctf_uvtime || dm_shield->value > 1)) //FIREBLADE { if (ent->client->ctf_uvtime) { ent->client->ctf_uvtime = 0; gi.centerprintf(ent, "Shields are DOWN!"); } ent->client->latched_buttons &= ~BUTTON_ATTACK; switch (ent->client->curr_weap) { case MK23_NUM: { // gi.cprintf (ent, PRINT_HIGH, "Calling ammo check %d\n", ent->client->mk23_rds); if (ent->client->mk23_rds > 0) { // gi.cprintf(ent, PRINT_HIGH, "Entered fire selection\n"); if (ent->client->resp.mk23_mode != 0 && ent->client->fired == 0) { ent->client->fired = 1; bFire = 1; } else if (ent->client->resp.mk23_mode == 0) { bFire = 1; } } else bOut = 1; break; } case MP5_NUM: { if (ent->client->mp5_rds > 0) { if (ent->client->resp.mp5_mode != 0 && ent->client->fired == 0 && ent->client->burst == 0) { ent->client->fired = 1; ent->client->ps.gunframe = 70; ent->client->burst = 1; ent->client->weaponstate = WEAPON_BURSTING; // start the animation ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - 1; ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - 1; ent->client->anim_end = FRAME_attack8; } } else if (ent->client->resp.mp5_mode == 0 && ent->client->fired == 0) { bFire = 1; } } else bOut = 1; break; } case M4_NUM: { if (ent->client->m4_rds > 0) { if (ent->client->resp.m4_mode != 0 && ent->client->fired == 0 && ent->client->burst == 0) { ent->client->fired = 1; ent->client->ps.gunframe = 64; ent->client->burst = 1; ent->client->weaponstate = WEAPON_BURSTING; // start the animation ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - 1; ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - 1; ent->client->anim_end = FRAME_attack8; } } else if (ent->client->resp.m4_mode == 0 && ent->client->fired == 0) { bFire = 1; } } else bOut = 1; break; } case M3_NUM: { if (ent->client->shot_rds > 0) { bFire = 1; } else bOut = 1; break; } // AQ2:TNG Deathwatch - Single Barreled HC // DW: SingleBarrel HC case HC_NUM: //if client is set to single shot mode, then allow //fire if only have 1 round left { if (ent->client->resp.hc_mode) { if (ent->client->cannon_rds > 0) { bFire = 1; } else bOut = 1; } else { if (ent->client->cannon_rds == 2) { bFire = 1; } else bOut = 1; } break; } /* case HC_NUM: { if ( ent->client->cannon_rds == 2 ) { bFire = 1; } else bOut = 1; break; } */ // AQ2:TNG END case SNIPER_NUM: { if (ent->client->ps.fov != ent->client->desired_fov) ent->client->ps.fov = ent->client->desired_fov; // if they aren't at 90 then they must be zoomed, so remove their weapon from view if (ent->client->ps.fov != 90) { ent->client->ps.gunindex = 0; ent->client->no_sniper_display = 0; } if (ent->client->sniper_rds > 0) { bFire = 1; } else bOut = 1; break; } case DUAL_NUM: { if (ent->client->dual_rds > 0) { bFire = 1; } else bOut = 1; break; } case GRAPPLE_NUM: bFire = 1; bOut = 0; break; default: { gi.cprintf (ent, PRINT_HIGH, "Calling non specific ammo code\n"); if ((!ent->client->ammo_index) || (ent->client->pers. inventory[ent->client->ammo_index] >= ent->client->pers.weapon->quantity)) { bFire = 1; } else { bFire = 0; bOut = 1; } } } if (bFire) { ent->client->ps.gunframe = FRAME_FIRE_FIRST; ent->client->weaponstate = WEAPON_FIRING; // start the animation ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - 1; ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - 1; ent->client->anim_end = FRAME_attack8; } } else if (bOut) // out of ammo { if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //+BD - Disabled for manual weapon change //NoAmmoWeaponChange (ent); } } else { if (ent->client->ps.fov != ent->client->desired_fov) ent->client->ps.fov = ent->client->desired_fov; // if they aren't at 90 then they must be zoomed, so remove their weapon from view if (ent->client->ps.fov != 90) { ent->client->ps.gunindex = 0; ent->client->no_sniper_display = 0; } if (ent->client->ps.gunframe == FRAME_IDLE_LAST) { ent->client->ps.gunframe = FRAME_IDLE_FIRST; return; } /* if (pause_frames) { for (n = 0; pause_frames[n]; n++) { if (ent->client->ps.gunframe == pause_frames[n]) { if (rand()&15) return; } } } */ ent->client->ps.gunframe++; ent->client->fired = 0; // weapon ready and button not down, now they can fire again ent->client->burst = 0; ent->client->machinegun_shots = 0; return; } } if (ent->client->weaponstate == WEAPON_FIRING) { for (n = 0; fire_frames[n]; n++) { if (ent->client->ps.gunframe == fire_frames[n]) { if (ent->client->quad_framenum > level.framenum) gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/damage3.wav"), 1, ATTN_NORM, 0); fire (ent); break; } } if (!fire_frames[n]) ent->client->ps.gunframe++; if (ent->client->ps.gunframe == FRAME_IDLE_FIRST + 1) ent->client->weaponstate = WEAPON_READY; } // player switched into if (ent->client->weaponstate == WEAPON_BURSTING) { for (n = 0; fire_frames[n]; n++) { if (ent->client->ps.gunframe == fire_frames[n]) { if (ent->client->quad_framenum > level.framenum) gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/damage3.wav"), 1, ATTN_NORM, 0); { // gi.cprintf (ent, PRINT_HIGH, "Calling fire code, frame = %d.\n", ent->client->ps.gunframe); fire (ent); } break; } } if (!fire_frames[n]) ent->client->ps.gunframe++; //gi.cprintf (ent, PRINT_HIGH, "Calling Q_stricmp, frame = %d.\n", ent->client->ps.gunframe); if (ent->client->ps.gunframe == FRAME_IDLE_FIRST + 1) ent->client->weaponstate = WEAPON_READY; if (ent->client->curr_weap == MP5_NUM) { if (ent->client->ps.gunframe >= 76) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE_FIRST + 1; } // gi.cprintf (ent, PRINT_HIGH, "Succes Q_stricmp now: frame = %d.\n", ent->client->ps.gunframe); } if (ent->client->curr_weap == M4_NUM) { if (ent->client->ps.gunframe >= 69) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE_FIRST + 1; } // gi.cprintf (ent, PRINT_HIGH, "Succes Q_stricmp now: frame = %d.\n", ent->client->ps.gunframe); } } } /* ====================================================================== GRENADE ====================================================================== */ #define GRENADE_TIMER 3.0 #define GRENADE_MINSPEED 400 #define GRENADE_MAXSPEED 800 void weapon_grenade_fire (edict_t * ent, qboolean held) { vec3_t offset; vec3_t forward, right; vec3_t start; int damage = 125; float timer; int speed; float radius; radius = damage + 40; if (is_quad) damage *= 4; VectorSet (offset, 8, 8, ent->viewheight - 8); AngleVectors (ent->client->v_angle, forward, right, NULL); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); timer = ent->client->grenade_time - level.time; speed = GRENADE_MINSPEED + (GRENADE_TIMER - timer) * ((GRENADE_MAXSPEED - GRENADE_MINSPEED) / GRENADE_TIMER); // Reset Grenade Damage to 1.52 when requested: if (use_classic->value) fire_grenade2 (ent, start, forward, 170, speed, timer, 170 * 2, held); else fire_grenade2 (ent, start, forward, GRENADE_DAMRAD, speed, timer, GRENADE_DAMRAD * 2, held); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; ent->client->grenade_time = level.time + 1.0; } void Weapon_Grenade (edict_t * ent) { if ((ent->client->newweapon) && (ent->client->weaponstate == WEAPON_READY)) { ChangeWeapon (ent); return; } if (ent->client->weaponstate == WEAPON_ACTIVATING) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = 16; return; } if (ent->client->weaponstate == WEAPON_READY) { if ( ((ent-> client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK)) { ent->client->latched_buttons &= ~BUTTON_ATTACK; if (ent->client->pers.inventory[ent->client->ammo_index]) { ent->client->ps.gunframe = 1; ent->client->weaponstate = WEAPON_FIRING; ent->client->grenade_time = 0; } else { if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } NoAmmoWeaponChange (ent); } return; } if ((ent->client->ps.gunframe == 29) || (ent->client->ps.gunframe == 34) || (ent->client->ps.gunframe == 39) || (ent->client->ps.gunframe == 48)) { if (rand () & 15) return; } if (++ent->client->ps.gunframe > 48) ent->client->ps.gunframe = 16; return; } if (ent->client->weaponstate == WEAPON_FIRING) { if (ent->client->ps.gunframe == 5) gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/hgrena1b.wav"), 1, ATTN_NORM, 0); if (ent->client->ps.gunframe == 11) { if (!ent->client->grenade_time) { ent->client->grenade_time = level.time + GRENADE_TIMER + 0.2; ent->client->weapon_sound = gi.soundindex ("weapons/hgrenc1b.wav"); //ent->client->weapon_sound = gi.soundindex("weapons/grenlb1b.wav"); } // they waited too long, detonate it in their hand if (!ent->client->grenade_blew_up && level.time >= ent->client->grenade_time) { ent->client->weapon_sound = 0; weapon_grenade_fire (ent, true); ent->client->grenade_blew_up = true; } if (ent->client->buttons & BUTTON_ATTACK) return; if (ent->client->grenade_blew_up) { if (level.time >= ent->client->grenade_time) { ent->client->ps.gunframe = 15; ent->client->grenade_blew_up = false; } else { return; } } } if (ent->client->ps.gunframe == 12) { ent->client->weapon_sound = 0; weapon_grenade_fire (ent, false); } if ((ent->client->ps.gunframe == 15) && (level.time < ent->client->grenade_time)) return; ent->client->ps.gunframe++; if (ent->client->ps.gunframe == 16) { ent->client->grenade_time = 0; ent->client->weaponstate = WEAPON_READY; } } } /* ====================================================================== GRENADE LAUNCHER ====================================================================== */ void weapon_grenadelauncher_fire (edict_t * ent) { vec3_t offset; vec3_t forward, right; vec3_t start; int damage = 120; float radius; radius = damage + 40; if (is_quad) damage *= 4; VectorSet (offset, 8, 8, ent->viewheight - 8); AngleVectors (ent->client->v_angle, forward, right, NULL); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -1; fire_grenade (ent, start, forward, damage, 600, 2.5, radius); gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_GRENADE | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } void Weapon_GrenadeLauncher (edict_t * ent) { static int pause_frames[] = { 34, 51, 59, 0 }; static int fire_frames[] = { 6, 0 }; Weapon_Generic (ent, 5, 16, 59, 64, 0, 0, pause_frames, fire_frames, weapon_grenadelauncher_fire); } /* ====================================================================== ROCKET ====================================================================== */ void Weapon_RocketLauncher_Fire (edict_t * ent) { vec3_t offset, start; vec3_t forward, right; int damage; float damage_radius; int radius_damage; damage = 100 + (int) (random () * 20.0); radius_damage = 120; damage_radius = 120; if (is_quad) { damage *= 4; radius_damage *= 4; } AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -1; VectorSet (offset, 8, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_rocket (ent, start, forward, damage, 650, damage_radius, radius_damage); // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_ROCKET | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } void Weapon_RocketLauncher (edict_t * ent) { static int pause_frames[] = { 25, 33, 42, 50, 0 }; static int fire_frames[] = { 5, 0 }; Weapon_Generic (ent, 4, 12, 50, 54, 0, 0, pause_frames, fire_frames, Weapon_RocketLauncher_Fire); } /* ====================================================================== BLASTER / HYPERBLASTER ====================================================================== */ //SLIC2 changed argument name hyper to hyperb void Blaster_Fire (edict_t * ent, vec3_t g_offset, int damage, qboolean hyperb, int effect) { vec3_t forward, right; vec3_t start; vec3_t offset; if (is_quad) damage *= 4; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorSet (offset, 24, 8, ent->viewheight - 8); VectorAdd (offset, g_offset, offset); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -1; fire_blaster (ent, start, forward, damage, 1000, effect, hyperb); // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); if (hyperb) gi.WriteByte (MZ_HYPERBLASTER | is_silenced); else gi.WriteByte (MZ_BLASTER | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_Blaster_Fire (edict_t * ent) { int damage; if (deathmatch->value) damage = 15; else damage = 10; Blaster_Fire (ent, vec3_origin, damage, false, EF_BLASTER); ent->client->ps.gunframe++; } void Weapon_Blaster (edict_t * ent) { static int pause_frames[] = { 19, 32, 0 }; static int fire_frames[] = { 5, 0 }; Weapon_Generic (ent, 4, 8, 52, 55, 0, 0, pause_frames, fire_frames, Weapon_Blaster_Fire); } void Weapon_HyperBlaster_Fire (edict_t * ent) { float rotation; vec3_t offset; int effect; int damage; ent->client->weapon_sound = gi.soundindex ("weapons/hyprbl1a.wav"); if (!(ent->client->buttons & BUTTON_ATTACK)) { ent->client->ps.gunframe++; } else { if (!ent->client->pers.inventory[ent->client->ammo_index]) { if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } NoAmmoWeaponChange (ent); } else { rotation = (ent->client->ps.gunframe - 5) * 2 * M_PI / 6; offset[0] = -4 * sin (rotation); offset[1] = 0; offset[2] = 4 * cos (rotation); if ((ent->client->ps.gunframe == 6) || (ent->client->ps.gunframe == 9)) effect = EF_HYPERBLASTER; else effect = 0; if (deathmatch->value) damage = 15; else damage = 20; Blaster_Fire (ent, offset, damage, true, effect); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } ent->client->ps.gunframe++; if (ent->client->ps.gunframe == 12 && ent->client->pers.inventory[ent->client->ammo_index]) ent->client->ps.gunframe = 6; } if (ent->client->ps.gunframe == 12) { gi.sound (ent, CHAN_AUTO, gi.soundindex ("weapons/hyprbd1a.wav"), 1, ATTN_NORM, 0); ent->client->weapon_sound = 0; } } void Weapon_HyperBlaster (edict_t * ent) { static int pause_frames[] = { 0 }; static int fire_frames[] = { 6, 7, 8, 9, 10, 11, 0 }; Weapon_Generic (ent, 5, 20, 49, 53, 0, 0, pause_frames, fire_frames, Weapon_HyperBlaster_Fire); } /* ====================================================================== MACHINEGUN / CHAINGUN ====================================================================== */ void Machinegun_Fire (edict_t * ent) { int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 8; int kick = 2; vec3_t offset; if (!(ent->client->buttons & BUTTON_ATTACK)) { ent->client->machinegun_shots = 0; ent->client->ps.gunframe++; return; } if (ent->client->ps.gunframe == 5) ent->client->ps.gunframe = 4; else ent->client->ps.gunframe = 5; if (ent->client->pers.inventory[ent->client->ammo_index] < 1) { ent->client->ps.gunframe = 6; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } NoAmmoWeaponChange (ent); return; } if (is_quad) { damage *= 4; kick *= 4; } for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.35; ent->client->kick_angles[i] = crandom () * 0.7; } ent->client->kick_origin[0] = crandom () * 0.35; ent->client->kick_angles[0] = ent->client->machinegun_shots * -1.5; // raise the gun as it is firing if (!deathmatch->value) { ent->client->machinegun_shots++; if (ent->client->machinegun_shots > 9) ent->client->machinegun_shots = 9; } // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); VectorSet (offset, 0, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_bullet (ent, start, forward, damage, kick, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, MOD_MACHINEGUN); gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_MACHINEGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } void Weapon_Machinegun (edict_t * ent) { static int pause_frames[] = { 23, 45, 0 }; static int fire_frames[] = { 4, 5, 0 }; Weapon_Generic (ent, 3, 5, 45, 49, 0, 0, pause_frames, fire_frames, Machinegun_Fire); } void Chaingun_Fire (edict_t * ent) { int i; int shots; vec3_t start; vec3_t forward, right, up; float r, u; vec3_t offset; int damage; int kick = 2; if (deathmatch->value) damage = 6; else damage = 8; if (ent->client->ps.gunframe == 5) gi.sound (ent, CHAN_AUTO, gi.soundindex ("weapons/chngnu1a.wav"), 1, ATTN_IDLE, 0); if ((ent->client->ps.gunframe == 14) && !(ent->client->buttons & BUTTON_ATTACK)) { ent->client->ps.gunframe = 32; ent->client->weapon_sound = 0; return; } else if ((ent->client->ps.gunframe == 21) && (ent->client->buttons & BUTTON_ATTACK) && ent->client->pers.inventory[ent->client->ammo_index]) { ent->client->ps.gunframe = 15; } else { ent->client->ps.gunframe++; } if (ent->client->ps.gunframe == 22) { ent->client->weapon_sound = 0; gi.sound (ent, CHAN_AUTO, gi.soundindex ("weapons/chngnd1a.wav"), 1, ATTN_IDLE, 0); } else { ent->client->weapon_sound = gi.soundindex ("weapons/chngnl1a.wav"); } if (ent->client->ps.gunframe <= 9) shots = 1; else if (ent->client->ps.gunframe <= 14) { if (ent->client->buttons & BUTTON_ATTACK) shots = 2; else shots = 1; } else shots = 3; if (ent->client->pers.inventory[ent->client->ammo_index] < shots) shots = ent->client->pers.inventory[ent->client->ammo_index]; if (!shots) { if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } NoAmmoWeaponChange (ent); return; } if (is_quad) { damage *= 4; kick *= 4; } for (i = 0; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.35; ent->client->kick_angles[i] = crandom () * 0.7; } for (i = 0; i < shots; i++) { // get start / end positions AngleVectors (ent->client->v_angle, forward, right, up); r = 7 + crandom () * 4; u = crandom () * 4; VectorSet (offset, 0, r, u + ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_bullet (ent, start, forward, damage, kick, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, MOD_CHAINGUN); } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte ((MZ_CHAINGUN1 + shots - 1) | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index] -= shots; } void Weapon_Chaingun (edict_t * ent) { static int pause_frames[] = { 38, 43, 51, 61, 0 }; static int fire_frames[] = { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 0 }; Weapon_Generic (ent, 4, 31, 61, 64, 0, 0, pause_frames, fire_frames, Chaingun_Fire); } /* ====================================================================== SHOTGUN / SUPERSHOTGUN ====================================================================== */ void weapon_shotgun_fire (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; int damage = 4; int kick = 8; if (ent->client->ps.gunframe == 9) { ent->client->ps.gunframe++; return; } AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -2; VectorSet (offset, 0, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (is_quad) { damage *= 4; kick *= 4; } if (deathmatch->value) fire_shotgun (ent, start, forward, damage, kick, 500, 500, DEFAULT_DEATHMATCH_SHOTGUN_COUNT, MOD_SHOTGUN); else fire_shotgun (ent, start, forward, damage, kick, 500, 500, DEFAULT_SHOTGUN_COUNT, MOD_SHOTGUN); // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } void Weapon_Shotgun (edict_t * ent) { static int pause_frames[] = { 22, 28, 34, 0 }; static int fire_frames[] = { 8, 9, 0 }; Weapon_Generic (ent, 7, 18, 36, 39, 0, 0, pause_frames, fire_frames, weapon_shotgun_fire); } void weapon_supershotgun_fire (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; vec3_t v; int damage = 6; int kick = 12; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -2; VectorSet (offset, 0, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (is_quad) { damage *= 4; kick *= 4; } v[PITCH] = ent->client->v_angle[PITCH]; v[YAW] = ent->client->v_angle[YAW] - 5; v[ROLL] = ent->client->v_angle[ROLL]; AngleVectors (v, forward, NULL, NULL); fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD, DEFAULT_SHOTGUN_VSPREAD, DEFAULT_SSHOTGUN_COUNT / 2, MOD_SSHOTGUN); v[YAW] = ent->client->v_angle[YAW] + 5; AngleVectors (v, forward, NULL, NULL); fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD, DEFAULT_SHOTGUN_VSPREAD, DEFAULT_SSHOTGUN_COUNT / 2, MOD_SSHOTGUN); // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SSHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index] -= 2; } void Weapon_SuperShotgun (edict_t * ent) { static int pause_frames[] = { 29, 42, 57, 0 }; static int fire_frames[] = { 7, 0 }; Weapon_Generic (ent, 6, 17, 57, 61, 0, 0, pause_frames, fire_frames, weapon_supershotgun_fire); } /* ====================================================================== RAILGUN ====================================================================== */ void weapon_railgun_fire (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; int damage; int kick; if (deathmatch->value) { // normal damage is too extreme in dm damage = 100; kick = 200; } else { damage = 150; kick = 250; } if (is_quad) { damage *= 4; kick *= 4; } AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -3, ent->client->kick_origin); ent->client->kick_angles[0] = -3; VectorSet (offset, 0, 7, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_rail (ent, start, forward, damage, kick); // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_RAILGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index]--; } void Weapon_Railgun (edict_t * ent) { static int pause_frames[] = { 56, 0 }; static int fire_frames[] = { 4, 0 }; Weapon_Generic (ent, 3, 18, 56, 61, 0, 0, pause_frames, fire_frames, weapon_railgun_fire); } /* ====================================================================== BFG10K ====================================================================== */ void weapon_bfg_fire (edict_t * ent) { vec3_t offset, start; vec3_t forward, right; int damage; float damage_radius = 1000; if (deathmatch->value) damage = 200; else damage = 500; if (ent->client->ps.gunframe == 9) { // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_BFG | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); return; } // cells can go down during windup (from power armor hits), so // check again and abort firing if we don't have enough now if (ent->client->pers.inventory[ent->client->ammo_index] < 50) { ent->client->ps.gunframe++; return; } if (is_quad) damage *= 4; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); // make a big pitch kick with an inverse fall ent->client->v_dmg_pitch = -40; ent->client->v_dmg_roll = crandom () * 8; ent->client->v_dmg_time = level.time + DAMAGE_TIME; VectorSet (offset, 8, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_bfg (ent, start, forward, damage, 400, damage_radius); ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); if (!((int) dmflags->value & DF_INFINITE_AMMO)) ent->client->pers.inventory[ent->client->ammo_index] -= 50; } void Weapon_BFG (edict_t * ent) { static int pause_frames[] = { 39, 45, 50, 55, 0 }; static int fire_frames[] = { 9, 17, 0 }; Weapon_Generic (ent, 8, 32, 55, 58, 0, 0, pause_frames, fire_frames, weapon_bfg_fire); } #define MK23_SPREAD 140 #define MP5_SPREAD 250 // DW: Changed this back to original from Edition's 240 #define M4_SPREAD 300 #define SNIPER_SPREAD 425 #define DUAL_SPREAD 300 // DW: Changed this back to original from Edition's 275 int AdjustSpread (edict_t * ent, int spread) { int running = 225; // minimum speed for running int walking = 10; // minimum speed for walking int laser = 0; float factor[] = { .7f, 1, 2, 6 }; int stage = 0; // 225 is running // < 10 will be standing float xyspeed = (ent->velocity[0] * ent->velocity[0] + ent->velocity[1] * ent->velocity[1]); if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) // crouching return (spread * .65); if (INV_AMMO(ent, LASER_NUM) && (ent->client->curr_weap == MK23_NUM || ent->client->curr_weap == MP5_NUM || ent->client->curr_weap == M4_NUM)) laser = 1; // running if (xyspeed > running * running) stage = 3; // walking else if (xyspeed >= walking * walking) stage = 2; // standing else stage = 1; // laser advantage if (laser) { if (stage == 1) stage = 0; else stage = 1; } return (int) (spread * factor[stage]); } //====================================================================== //====================================================================== // mk23 derived from tutorial by GreyBear void Pistol_Fire (edict_t * ent) { int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 90; int kick = 150; vec3_t offset; int spread = MK23_SPREAD; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; //If the user isn't pressing the attack button, advance the frame and go away.... if (!(ent->client->buttons & BUTTON_ATTACK)) { ent->client->ps.gunframe++; return; } ent->client->ps.gunframe++; //Oops! Out of ammo! if (ent->client->mk23_rds < 1) { ent->client->ps.gunframe = 13; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } //Calculate the kick angles for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.35; ent->client->kick_angles[i] = crandom () * 0.7; } ent->client->kick_origin[0] = crandom () * 0.35; ent->client->kick_angles[0] = ent->client->machinegun_shots * -1.5; // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); VectorSet (offset, 0, 8, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 0); } spread = AdjustSpread (ent, spread); if (ent->client->resp.mk23_mode) spread *= .7; // gi.cprintf(ent, PRINT_HIGH, "Spread is %d\n", spread); if ((ent->client->mk23_rds == 1)) { //Hard coded for reload only. ent->client->ps.gunframe = 62; ent->client->weaponstate = WEAPON_END_MAG; } fire_bullet (ent, start, forward, damage, kick, spread, spread, MOD_MK23); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_MK23] += 1; // TNG Stats, +1 hit } ent->client->mk23_rds--; ent->client->dual_rds--; // silencer suppresses both sound and muzzle flash if (INV_AMMO(ent, SIL_NUM)) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("misc/silencer.wav"), 1, ATTN_NORM, 0); return; } if (llsound->value) { //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_BLASTER | is_silenced); } else { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23fire.wav"), 1, ATTN_NORM, 0); //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); //If not silenced, play a shot sound for everyone else gi.WriteByte (MZ_MACHINEGUN | is_silenced); } gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_MK23 (edict_t * ent) { //Idle animation entry points - These make the fidgeting look more random static int pause_frames[] = { 13, 22, 40 }; //The frames at which the weapon will fire static int fire_frames[] = { 10, 0 }; //The call is made... Weapon_Generic (ent, 9, 12, 37, 40, 61, 65, pause_frames, fire_frames, Pistol_Fire); } void MP5_Fire (edict_t * ent) { int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 55; int kick = 90; vec3_t offset; int spread = MP5_SPREAD; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; // If requested, use 1.52 spread if (use_classic->value) spread = 250; else spread = MP5_SPREAD; //If the user isn't pressing the attack button, advance the frame and go away.... if (!(ent->client->buttons & BUTTON_ATTACK) && !(ent->client->burst)) { ent->client->ps.gunframe++; return; } if (ent->client->burst == 0 && !(ent->client->resp.mp5_mode)) { if (ent->client->ps.gunframe == 12) ent->client->ps.gunframe = 11; else ent->client->ps.gunframe = 12; } //burst mode else if (ent->client->burst == 0 && ent->client->resp.mp5_mode) { ent->client->ps.gunframe = 72; ent->client->weaponstate = WEAPON_BURSTING; ent->client->burst = 1; ent->client->fired = 1; } else if (ent->client->ps.gunframe >= 70 && ent->client->ps.gunframe <= 75) { ent->client->ps.gunframe++; } //Oops! Out of ammo! if (ent->client->mp5_rds < 1) { ent->client->ps.gunframe = 13; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } spread = AdjustSpread (ent, spread); if (ent->client->burst) spread *= .7; //Calculate the kick angles for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.25; ent->client->kick_angles[i] = crandom () * 0.5; } ent->client->kick_origin[0] = crandom () * 0.35; ent->client->kick_angles[0] = ent->client->machinegun_shots * -1.5; // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); VectorSet (offset, 0, 8, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); fire_bullet (ent, start, forward, damage, kick, spread, spread, MOD_MP5); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_MP5] += 1; // TNG Stats, +1 hit } ent->client->mp5_rds--; if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 0); } // zucc vwep ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - (int) (random () + 0.25); ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - (int) (random () + 0.25); ent->client->anim_end = FRAME_attack8; } // zucc vwep done // silencer suppresses both sound and muzzle flash if (INV_AMMO(ent, SIL_NUM)) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("misc/silencer.wav"), 1, ATTN_NORM, 0); return; } if (llsound->value == 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mp5fire1.wav"), 1, ATTN_NORM, 0); } //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); //If not silenced, play a shot sound for everyone else gi.WriteByte (MZ_MACHINEGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_MP5 (edict_t * ent) { //Idle animation entry points - These make the fidgeting look more random static int pause_frames[] = { 13, 30, 47 }; //The frames at which the weapon will fire static int fire_frames[] = { 11, 12, 71, 72, 73, 0 }; //The call is made... Weapon_Generic (ent, 10, 12, 47, 51, 69, 77, pause_frames, fire_frames, MP5_Fire); } void M4_Fire (edict_t * ent) { int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 90; int kick = 90; vec3_t offset; int spread = M4_SPREAD; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; //If the user isn't pressing the attack button, advance the frame and go away.... if (!(ent->client->buttons & BUTTON_ATTACK) && !(ent->client->burst)) { ent->client->ps.gunframe++; ent->client->machinegun_shots = 0; return; } if (ent->client->burst == 0 && !(ent->client->resp.m4_mode)) { if (ent->client->ps.gunframe == 12) ent->client->ps.gunframe = 11; else ent->client->ps.gunframe = 12; } //burst mode else if (ent->client->burst == 0 && ent->client->resp.m4_mode) { ent->client->ps.gunframe = 66; ent->client->weaponstate = WEAPON_BURSTING; ent->client->burst = 1; ent->client->fired = 1; } else if (ent->client->ps.gunframe >= 64 && ent->client->ps.gunframe <= 69) { ent->client->ps.gunframe++; } //Oops! Out of ammo! if (ent->client->m4_rds < 1) { ent->client->ps.gunframe = 13; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } // causes the ride up if (ent->client->weaponstate != WEAPON_BURSTING) { ent->client->machinegun_shots++; if (ent->client->machinegun_shots > 23) ent->client->machinegun_shots = 23; } else // no kick when in burst mode { ent->client->machinegun_shots = 0; } spread = AdjustSpread (ent, spread); if (ent->client->burst) spread *= .7; // gi.cprintf(ent, PRINT_HIGH, "Spread is %d\n", spread); //Calculate the kick angles for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.25; ent->client->kick_angles[i] = crandom () * 0.5; } ent->client->kick_origin[0] = crandom () * 0.35; ent->client->kick_angles[0] = ent->client->machinegun_shots * -.7; // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); VectorSet (offset, 0, 8, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (is_quad) damage *= 1.5f; fire_bullet_sparks (ent, start, forward, damage, kick, spread, spread, MOD_M4); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_M4] += 1; // TNG Stats, +1 hit } ent->client->m4_rds--; if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 0); } // zucc vwep ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - (int) (random () + 0.25); ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - (int) (random () + 0.25); ent->client->anim_end = FRAME_attack8; } // zucc vwep done if (llsound->value) { //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_ROCKET | is_silenced); } else { //If not silenced, play a shot sound for everyone else gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/m4a1fire.wav"), 1, ATTN_NORM, 0); //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_MACHINEGUN | is_silenced); } gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_M4 (edict_t * ent) { //Idle animation entry points - These make the fidgeting look more random static int pause_frames[] = { 13, 24, 39 }; //The frames at which the weapon will fire static int fire_frames[] = { 11, 12, 65, 66, 67, 0 }; //The call is made... Weapon_Generic (ent, 10, 12, 39, 44, 63, 71, pause_frames, fire_frames, M4_Fire); } void InitShotgunDamageReport (); void ProduceShotgunDamageReport (edict_t *); void M3_Fire (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; int damage = 17; //actionquake is 15 standard int kick = 20; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; if (ent->client->ps.gunframe == 9) { ent->client->ps.gunframe++; return; } AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -2; VectorSet (offset, 0, 8, ent->viewheight - height); if (ent->client->ps.gunframe == 14) { if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 0); } ent->client->ps.gunframe++; return; } P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (is_quad) { damage *= 1.5f; kick *= 1.5f; } setFFState (ent); InitShotgunDamageReport (); //FB 6/3/99 if (deathmatch->value) fire_shotgun (ent, start, forward, damage, kick, 800, 800, 12 /*DEFAULT_DEATHMATCH_SHOTGUN_COUNT */ , MOD_M3); else fire_shotgun (ent, start, forward, damage, kick, 800, 800, 12 /*DEFAULT_SHOTGUN_COUNT */ , MOD_M3); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_M3] += 1; // TNG Stats, +1 hit } if (llsound->value == 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/shotgf1b.wav"), 1, ATTN_NORM, 0); } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ProduceShotgunDamageReport (ent); //FB 6/3/99 ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); //if (! ( (int)dmflags->value & DF_INFINITE_AMMO ) ) // ent->client->pers.inventory[ent->client->ammo_index]--; ent->client->shot_rds--; } void Weapon_M3 (edict_t * ent) { static int pause_frames[] = { 22, 28, 0 }; static int fire_frames[] = { 8, 9, 14, 0 }; Weapon_Generic (ent, 7, 15, 35, 41, 52, 60, pause_frames, fire_frames, M3_Fire); } // AQ2:TNG Deathwatch - Modified to use Single Barreled HC Mode void HC_Fire (edict_t * ent) { vec3_t start; vec3_t forward, right; vec3_t offset; vec3_t v; int sngl_damage = 15; int sngl_kick = 30; int damage = 20; int kick = 40; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -2; VectorSet (offset, 0, 8, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (is_quad) { damage *= 1.5f; kick *= 1.5f; } v[PITCH] = ent->client->v_angle[PITCH]; // DW: Single Barreled HC if (ent->client->resp.hc_mode) { if (ent->client->cannon_rds == 2) v[YAW] = ent->client->v_angle[YAW] - ((0.5) / 2); else v[YAW] = ent->client->v_angle[YAW] + ((0.5) / 2); } else v[YAW] = ent->client->v_angle[YAW] - 0.5; // v[YAW] = ent->client->v_angle[YAW] - 5; v[ROLL] = ent->client->v_angle[ROLL]; AngleVectors (v, forward, NULL, NULL); // default hspread is 1k and default vspread is 500 setFFState (ent); InitShotgunDamageReport (); //FB 6/3/99 if (ent->client->resp.hc_mode) { //half the spread, half the pellets? fire_shotgun (ent, start, forward, sngl_damage, sngl_kick, DEFAULT_SHOTGUN_HSPREAD * 2.5, DEFAULT_SHOTGUN_VSPREAD * 2.5, 34 / 2, MOD_HC); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_HC] += 1; // TNG Stats, +1 hit } if (llsound->value == 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cannon_fire.wav"), 1, ATTN_NORM, 0); } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SSHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); } else { //sound on both WEAPON and ITEM to produce a louder 'boom' fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD * 4, DEFAULT_SHOTGUN_VSPREAD * 4, 34 / 2, MOD_HC); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_HC] += 1; // TNG Stats, +1 hit } //only produce this extra sound if single shot is available if (hc_single->value) { if (llsound->value == 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cannon_fire.wav"), 1, ATTN_NORM, 0); } } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SSHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); v[YAW] = ent->client->v_angle[YAW] + 5; AngleVectors (v, forward, NULL, NULL); //was *5 here? fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD * 4, DEFAULT_SHOTGUN_VSPREAD * 4, 34 / 2, MOD_HC); if (llsound->value == 0) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/cannon_fire.wav"), 1, ATTN_NORM, 0); } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_SSHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); } ProduceShotgunDamageReport (ent); //FB 6/3/99 ent->client->ps.gunframe++; PlayerNoise (ent, start, PNOISE_WEAPON); // if (! ( (int)dmflags->value & DF_INFINITE_AMMO ) ) // ent->client->pers.inventory[ent->client->ammo_index] -= 2; if (ent->client->resp.hc_mode) ent->client->cannon_rds -= 1; else ent->client->cannon_rds -= 2; } /* v[YAW] = ent->client->v_angle[YAW] - 5; v[ROLL] = ent->client->v_angle[ROLL]; AngleVectors (v, forward, NULL, NULL); // default hspread is 1k and default vspread is 500 setFFState(ent); InitShotgunDamageReport(); //FB 6/3/99 fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD*4, DEFAULT_SHOTGUN_VSPREAD*4, 34/2, MOD_HC); v[YAW] = ent->client->v_angle[YAW] + 5; AngleVectors (v, forward, NULL, NULL); fire_shotgun (ent, start, forward, damage, kick, DEFAULT_SHOTGUN_HSPREAD*4, DEFAULT_SHOTGUN_VSPREAD*5, 34/2, MOD_HC); if (llsound->value == 0) { gi.sound(ent, CHAN_WEAPON, gi.soundindex("weapons/cannon_fire.wav"), 1, ATTN_NORM, 0); } // send muzzle flash gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent-g_edicts); gi.WriteByte (MZ_SSHOTGUN | is_silenced); gi.multicast (ent->s.origin, MULTICAST_PVS); ProduceShotgunDamageReport(ent); //FB 6/3/99 ent->client->ps.gunframe++; PlayerNoise(ent, start, PNOISE_WEAPON); // if (! ( (int)dmflags->value & DF_INFINITE_AMMO ) ) // ent->client->pers.inventory[ent->client->ammo_index] -= 2; ent->client->cannon_rds -= 2; } */ // AQ2:TNG END void Weapon_HC (edict_t * ent) { static int pause_frames[] = { 29, 42, 57, 0 }; static int fire_frames[] = { 7, 0 }; Weapon_Generic (ent, 6, 17, 57, 61, 82, 83, pause_frames, fire_frames, HC_Fire); } void Sniper_Fire (edict_t * ent) { //int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 250; int kick = 200; vec3_t offset; int spread = SNIPER_SPREAD; if (ent->client->ps.gunframe == 13) { gi.sound (ent, CHAN_AUTO, gi.soundindex ("weapons/ssgbolt.wav"), 1, ATTN_NORM, 0); ent->client->ps.gunframe++; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorSet (offset, 0, 0, ent->viewheight - 0); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); EjectShell (ent, start, 0); return; } if (ent->client->ps.gunframe == 21) { if (ent->client->ps.fov != ent->client->desired_fov) ent->client->ps.fov = ent->client->desired_fov; // if they aren't at 90 then they must be zoomed, so remove their weapon from view if (ent->client->ps.fov != 90) { ent->client->ps.gunindex = 0; ent->client->no_sniper_display = 0; } ent->client->ps.gunframe++; return; } //If the user isn't pressing the attack button, advance the frame and go away.... if (!(ent->client->buttons & BUTTON_ATTACK)) { ent->client->ps.gunframe++; return; } ent->client->ps.gunframe++; //Oops! Out of ammo! if (ent->client->sniper_rds < 1) { ent->client->ps.gunframe = 22; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } spread = AdjustSpread (ent, spread); if (ent->client->resp.sniper_mode == SNIPER_2X) spread = 0; else if (ent->client->resp.sniper_mode == SNIPER_4X) spread = 0; else if (ent->client->resp.sniper_mode == SNIPER_6X) spread = 0; if (is_quad) damage *= 1.5f; //Calculate the kick angles /*for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0; ent->client->kick_angles[i] = crandom () * 0; } ent->client->kick_origin[0] = crandom () * 0; ent->client->kick_angles[0] = ent->client->machinegun_shots * 0;*/ VectorClear(ent->client->kick_origin); VectorClear(ent->client->kick_angles); // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (ent->client->v_angle, forward, right, NULL); VectorSet (offset, 0, 0, ent->viewheight - 0); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); //If no reload, fire normally. fire_bullet_sniper (ent, start, forward, damage, kick, spread, spread, MOD_SNIPER); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_SNIPER] += 1; // TNG Stats, +1 hit } ent->client->sniper_rds--; ent->client->ps.fov = 90; // so we can watch the next round get chambered ent->client->ps.gunindex = gi.modelindex (ent->client->pers.weapon->view_model); ent->client->no_sniper_display = 1; // silencer suppresses both sound and muzzle flash if (INV_AMMO(ent, SIL_NUM)) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("misc/silencer.wav"), 1, ATTN_NORM, 0); return; } if (llsound->value) { //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_HYPERBLASTER | is_silenced); } else { //If not silenced, play a shot sound for everyone else gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/ssgfire.wav"), 1, ATTN_NORM, 0); //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_MACHINEGUN | is_silenced); } gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_Sniper (edict_t * ent) { //Idle animation entry points - These make the fidgeting look more random static int pause_frames[] = { 21, 40 }; //The frames at which the weapon will fire static int fire_frames[] = { 9, 13, 21, 0 }; //The call is made... Weapon_Generic (ent, 8, 21, 41, 50, 81, 95, pause_frames, fire_frames, Sniper_Fire); } void Dual_Fire (edict_t * ent) { int i; vec3_t start; vec3_t forward, right; vec3_t angles; int damage = 90; int kick = 90; vec3_t offset; int spread = DUAL_SPREAD; int height; if (ent->client->pers.firing_style == ACTION_FIRING_CLASSIC) height = 8; else height = 0; // Reset spread to 1.52 when requested if (use_classic->value) spread = 300; else spread = DUAL_SPREAD; spread = AdjustSpread (ent, spread); if (ent->client->dual_rds < 1) { ent->client->ps.gunframe = 68; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } if (is_quad) damage *= 1.5f; //If the user isn't pressing the attack button, advance the frame and go away.... if (ent->client->ps.gunframe == 8) { //gi.sound(ent, CHAN_WEAPON, gi.soundindex("weapons/mk23fire.wav"), 1, ATTN_NORM, 0); ent->client->ps.gunframe++; VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); VectorSet (offset, 0, 8, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (ent->client->dual_rds > 1) { fire_bullet (ent, start, forward, damage, kick, spread, spread, MOD_DUAL); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_DUAL] += 1; // TNG Stats, +1 hit } if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 2); } if (ent->client->dual_rds > ent->client->mk23_max + 1) { ent->client->dual_rds -= 2; } else if (ent->client->dual_rds > ent->client->mk23_max) // 13 rounds left { ent->client->dual_rds -= 2; ent->client->mk23_rds--; } else { ent->client->dual_rds -= 2; ent->client->mk23_rds -= 2; } gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23fire.wav"), 1, ATTN_NORM, 0); if (ent->client->dual_rds == 0) { ent->client->ps.gunframe = 68; ent->client->weaponstate = WEAPON_END_MAG; } } else { ent->client->dual_rds = 0; ent->client->mk23_rds = 0; gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); //ent->pain_debounce_time = level.time + 1; ent->client->ps.gunframe = 68; ent->client->weaponstate = WEAPON_END_MAG; } return; } if (ent->client->ps.gunframe == 9) { ent->client->ps.gunframe += 2; return; } /*if (!(ent->client->buttons & BUTTON_ATTACK)) { ent->client->ps.gunframe++; return; } */ ent->client->ps.gunframe++; //Oops! Out of ammo! if (ent->client->dual_rds < 1) { ent->client->ps.gunframe = 12; if (level.time >= ent->pain_debounce_time) { gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/noammo.wav"), 1, ATTN_NORM, 0); ent->pain_debounce_time = level.time + 1; } //NoAmmoWeaponChange (ent); return; } //Calculate the kick angles for (i = 1; i < 3; i++) { ent->client->kick_origin[i] = crandom () * 0.25; ent->client->kick_angles[i] = crandom () * 0.5; } ent->client->kick_origin[0] = crandom () * 0.35; // get start / end positions VectorAdd (ent->client->v_angle, ent->client->kick_angles, angles); AngleVectors (angles, forward, right, NULL); // first set up for left firing VectorSet (offset, 0, -20, ent->viewheight - height); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); if (!sv_shelloff->value) { vec3_t result; Old_ProjectSource (ent->client, ent->s.origin, offset, forward, right, result); EjectShell (ent, result, 1); } //If no reload, fire normally. fire_bullet (ent, start, forward, damage, kick, spread, spread, MOD_DUAL); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_DUAL] += 1; // TNG Stats, +1 hit } if (llsound->value) { //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_BLASTER | is_silenced); } else { //If not silenced, play a shot sound for everyone else gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/mk23fire.wav"), 1, ATTN_NORM, 0); //Display the yellow muzzleflash light effect gi.WriteByte (svc_muzzleflash); gi.WriteShort (ent - g_edicts); gi.WriteByte (MZ_MACHINEGUN | is_silenced); } gi.multicast (ent->s.origin, MULTICAST_PVS); PlayerNoise (ent, start, PNOISE_WEAPON); } void Weapon_Dual (edict_t * ent) { //Idle animation entry points - These make the fidgeting look more random static int pause_frames[] = { 13, 22, 32 }; //The frames at which the weapon will fire static int fire_frames[] = { 7, 8, 9, 0 }; //The call is made... Weapon_Generic (ent, 6, 10, 32, 40, 65, 68, pause_frames, fire_frames, Dual_Fire); } //zucc #define FRAME_PREPARETHROW_FIRST (FRAME_DEACTIVATE_LAST +1) #define FRAME_IDLE2_FIRST (FRAME_PREPARETHROW_LAST +1) #define FRAME_THROW_FIRST (FRAME_IDLE2_LAST +1) #define FRAME_STOPTHROW_FIRST (FRAME_THROW_LAST +1) #define FRAME_NEWKNIFE_FIRST (FRAME_STOPTHROW_LAST +1) void Weapon_Generic_Knife (edict_t * ent, int FRAME_ACTIVATE_LAST, int FRAME_FIRE_LAST, int FRAME_IDLE_LAST, int FRAME_DEACTIVATE_LAST, int FRAME_PREPARETHROW_LAST, int FRAME_IDLE2_LAST, int FRAME_THROW_LAST, int FRAME_STOPTHROW_LAST, int FRAME_NEWKNIFE_LAST, int *pause_frames, int *fire_frames, int (*fire) (edict_t * ent)) { if (ent->s.modelindex != 255) // zucc vwep return; // not on client, so VWep animations could do wacky things //FIREBLADE if (ent->client->weaponstate == WEAPON_FIRING && ((ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) || lights_camera_action)) { ent->client->weaponstate = WEAPON_READY; } //FIREBLADE if (ent->client->weaponstate == WEAPON_RELOADING) { if (ent->client->ps.gunframe < FRAME_NEWKNIFE_LAST) { ent->client->ps.gunframe++; } else { ent->client->ps.gunframe = FRAME_IDLE2_FIRST; ent->client->weaponstate = WEAPON_READY; } } if (ent->client->weaponstate == WEAPON_DROPPING) { if (ent->client->resp.knife_mode == 1) { if (ent->client->ps.gunframe == FRAME_NEWKNIFE_FIRST) { ChangeWeapon (ent); return; } else { // zucc going to have to do this a bit different because // of the way I roll gunframes backwards for the thrownknife position if ((ent->client->ps.gunframe - FRAME_NEWKNIFE_FIRST) == 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } ent->client->ps.gunframe--; } } else { if (ent->client->ps.gunframe == FRAME_DEACTIVATE_LAST) { ChangeWeapon (ent); return; } else if ((FRAME_DEACTIVATE_LAST - ent->client->ps.gunframe) == 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } ent->client->ps.gunframe++; } return; } if (ent->client->weaponstate == WEAPON_ACTIVATING) { if (ent->client->resp.knife_mode == 1 && ent->client->ps.gunframe == 0) { // gi.cprintf(ent, PRINT_HIGH, "NewKnifeFirst\n"); ent->client->ps.gunframe = FRAME_PREPARETHROW_FIRST; return; } if (ent->client->ps.gunframe == FRAME_ACTIVATE_LAST || ent->client->ps.gunframe == FRAME_STOPTHROW_LAST) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE_FIRST; return; } if (ent->client->ps.gunframe == FRAME_PREPARETHROW_LAST) { ent->client->weaponstate = WEAPON_READY; ent->client->ps.gunframe = FRAME_IDLE2_FIRST; return; } ent->client->resp.sniper_mode = 0; // has to be here for dropping the sniper rifle, in the drop command didn't work... ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->ps.gunframe++; // gi.cprintf(ent, PRINT_HIGH, "After increment frames = %d\n", ent->client->ps.gunframe); return; } // bandaging case if ((ent->client->bandaging) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BURSTING) && (ent->client->weaponstate != WEAPON_BUSY) && (ent->client->weaponstate != WEAPON_BANDAGING)) { ent->client->weaponstate = WEAPON_BANDAGING; ent->client->ps.gunframe = FRAME_DEACTIVATE_FIRST; return; } if (ent->client->weaponstate == WEAPON_BUSY) { if (ent->client->bandaging == 1) { if (!(ent->client->idle_weapon)) { Bandage (ent); //ent->client->weaponstate = WEAPON_ACTIVATING; // ent->client->ps.gunframe = 0; } else (ent->client->idle_weapon)--; return; } // for after bandaging delay if (!(ent->client->idle_weapon) && ent->client->bandage_stopped) { ent->client->weaponstate = WEAPON_ACTIVATING; ent->client->ps.gunframe = 0; ent->client->bandage_stopped = 0; return; } else if (ent->client->bandage_stopped == 1) { (ent->client->idle_weapon)--; return; } if (ent->client->ps.gunframe == 98) { ent->client->weaponstate = WEAPON_READY; return; } else ent->client->ps.gunframe++; } if (ent->client->weaponstate == WEAPON_BANDAGING) { if (ent->client->ps.gunframe == FRAME_DEACTIVATE_LAST) { ent->client->weaponstate = WEAPON_BUSY; ent->client->idle_weapon = BANDAGE_TIME; return; } ent->client->ps.gunframe++; return; } if ((ent->client->newweapon) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BUSY)) { if (ent->client->resp.knife_mode == 1) // throwing mode { ent->client->ps.gunframe = FRAME_NEWKNIFE_LAST; // zucc more vwep stuff if ((FRAME_NEWKNIFE_LAST - FRAME_NEWKNIFE_FIRST) < 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } } else // not in throwing mode { ent->client->ps.gunframe = FRAME_DEACTIVATE_FIRST; // zucc more vwep stuff if ((FRAME_DEACTIVATE_LAST - FRAME_DEACTIVATE_FIRST) < 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } } ent->client->weaponstate = WEAPON_DROPPING; return; } if (ent->client->weaponstate == WEAPON_READY) { if (((ent->client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK) //FIREBLADE // AQ2:TNG - JBravo adding UVtime && (ent->solid != SOLID_NOT || ent->deadflag == DEAD_DEAD) && !lights_camera_action && !ent->client->ctf_uvtime) //FIREBLADE { ent->client->latched_buttons &= ~BUTTON_ATTACK; if (ent->client->resp.knife_mode == 1) { ent->client->ps.gunframe = FRAME_THROW_FIRST; } else { ent->client->ps.gunframe = FRAME_FIRE_FIRST; } ent->client->weaponstate = WEAPON_FIRING; // start the animation ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - 1; ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - 1; ent->client->anim_end = FRAME_attack8; } return; } if (ent->client->ps.gunframe == FRAME_IDLE_LAST) { ent->client->ps.gunframe = FRAME_IDLE_FIRST; return; } if (ent->client->ps.gunframe == FRAME_IDLE2_LAST) { ent->client->ps.gunframe = FRAME_IDLE2_FIRST; return; } /* // zucc this causes you to not be able to throw a knife while it is flipping if ( ent->client->ps.gunframe == 93 ) { ent->client->weaponstate = WEAPON_BUSY; return; } */ //gi.cprintf(ent, PRINT_HIGH, "Before a gunframe additon frames = %d\n", ent->client->ps.gunframe); ent->client->ps.gunframe++; return; } if (ent->client->weaponstate == WEAPON_FIRING) { int n; for (n = 0; fire_frames[n]; n++) { if (ent->client->ps.gunframe == fire_frames[n]) { if (ent->client->quad_framenum > level.framenum) gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/damage3.wav"), 1, ATTN_NORM, 0); if (fire (ent)) break; else // we ran out of knives and switched weapons return; } } if (!fire_frames[n]) ent->client->ps.gunframe++; /*if ( ent->client->ps.gunframe == FRAME_STOPTHROW_FIRST + 1 ) { ent->client->ps.gunframe = FRAME_NEWKNIFE_FIRST; ent->client->weaponstate = WEAPON_RELOADING; } */ if (ent->client->ps.gunframe == FRAME_IDLE_FIRST + 1 || ent->client->ps.gunframe == FRAME_IDLE2_FIRST + 1) ent->client->weaponstate = WEAPON_READY; } } int Knife_Fire (edict_t * ent) { vec3_t start, v; vec3_t forward, right; vec3_t offset; int damage = 200; int throwndamage = 250; int kick = 50; // doesn't throw them back much.. int knife_return = 3; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -2; VectorSet (offset, 0, 8, ent->viewheight - 8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); v[PITCH] = ent->client->v_angle[PITCH]; v[ROLL] = ent->client->v_angle[ROLL]; // zucc updated these to not have offsets anymore for 1.51, // this should fix the complaints about the knife not // doing enough damage if (ent->client->ps.gunframe == 6) { v[YAW] = ent->client->v_angle[YAW]; // + 5; AngleVectors (v, forward, NULL, NULL); } else if (ent->client->ps.gunframe == 7) { v[YAW] = ent->client->v_angle[YAW]; // + 2; AngleVectors (v, forward, NULL, NULL); } else if (ent->client->ps.gunframe == 8) { v[YAW] = ent->client->v_angle[YAW]; AngleVectors (v, forward, NULL, NULL); } else if (ent->client->ps.gunframe == 9) { v[YAW] = ent->client->v_angle[YAW]; // - 2; AngleVectors (v, forward, NULL, NULL); } else if (ent->client->ps.gunframe == 10) { v[YAW] = ent->client->v_angle[YAW]; //-5; AngleVectors (v, forward, NULL, NULL); } if (ent->client->resp.knife_mode == 0) { if (is_quad) damage *= 1.5f; knife_return = knife_attack (ent, start, forward, damage, kick); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_KNIFE] += 1; // TNG Stats, +1 hit } if (knife_return < ent->client->knife_sound) ent->client->knife_sound = knife_return; if (ent->client->ps.gunframe == 8) // last slicing frame, time for some sound { if (ent->client->knife_sound == -2) { // we hit a player gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/stab.wav"), 1, ATTN_NORM, 0); } else if (ent->client->knife_sound == -1) { // we hit a wall gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/clank.wav"), 1, ATTN_NORM, 0); } else // we missed { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/swish.wav"), 1, ATTN_NORM, 0); } ent->client->knife_sound = 0; } } else { // do throwing stuff here damage = throwndamage; if (is_quad) damage *= 1.5f; // throwing sound gi.sound (ent, CHAN_WEAPON, gi.soundindex ("weapons/throw.wav"), 1, ATTN_NORM, 0); // below is exact code from action for how it sets the knife up AngleVectors (ent->client->v_angle, forward, right, NULL); VectorSet (offset, 24, 8, ent->viewheight - 8); VectorAdd (offset, vec3_origin, offset); forward[2] += .17f; // zucc using old style because the knife coming straight out looks // pretty stupid Knife_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); INV_AMMO(ent, KNIFE_NUM)--; if (INV_AMMO(ent, KNIFE_NUM) <= 0) { ent->client->newweapon = GET_ITEM(MK23_NUM); ChangeWeapon (ent); // zucc was at 1250, dropping speed to 1200 knife_throw (ent, start, forward, damage, 1200); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_KNIFE_THROWN] += 1; // TNG Stats, +1 hit } return 0; } else { ent->client->weaponstate = WEAPON_RELOADING; ent->client->ps.gunframe = 111; } /*AngleVectors (ent->client->v_angle, forward, right, NULL); VectorScale (forward, -2, ent->client->kick_origin); ent->client->kick_angles[0] = -1; VectorSet(offset, 8, 8, ent->viewheight-8); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); */ // fire_rocket (ent, start, forward, damage, 650, 200, 200); knife_throw (ent, start, forward, damage, 1200); if (!teamplay->value || team_round_going || stats_afterround->value) { ent->client->resp.stats_shots_t += 1; // TNG Stats, +1 hit ent->client->resp.stats_shots[MOD_KNIFE_THROWN] += 1; // TNG Stats, +1 hit } // } ent->client->ps.gunframe++; if (ent->client->ps.gunframe == 106) // over the throwing frame limit ent->client->ps.gunframe = 64; // the idle animation frame for throwing // not sure why the frames weren't ordered // with throwing first, unwise. PlayerNoise (ent, start, PNOISE_WEAPON); return 1; } void Weapon_Knife (edict_t * ent) { static int pause_frames[] = { 22, 28, 0 }; static int fire_frames[] = { 6, 7, 8, 9, 10, 105, 0 }; // I think we need a special version of the generic function for this... Weapon_Generic_Knife (ent, 5, 12, 52, 59, 63, 102, 105, 110, 117, pause_frames, fire_frames, Knife_Fire); } // zucc - I thought about doing a gas grenade and even experimented with it some. It // didn't work out that great though, so I just changed this code to be the standard // action grenade. So the function name is just misleading... void gas_fire (edict_t * ent) { vec3_t offset; vec3_t forward, right; vec3_t start; int damage = GRENADE_DAMRAD; float timer; int speed; /* int held = false;*/ // Reset Grenade Damage to 1.52 when requested: if (use_classic->value) damage = 170; else damage = GRENADE_DAMRAD; if(is_quad) damage *= 1.5f; VectorSet (offset, 8, 8, ent->viewheight - 8); AngleVectors (ent->client->v_angle, forward, right, NULL); P_ProjectSource (ent->client, ent->s.origin, offset, forward, right, start); timer = 2.0; if (ent->client->resp.grenade_mode == 0) speed = 400; else if (ent->client->resp.grenade_mode == 1) speed = 720; else speed = 920; fire_grenade2 (ent, start, forward, damage, speed, timer, damage * 2, false); INV_AMMO(ent, GRENADE_NUM)--; if (INV_AMMO(ent, GRENADE_NUM) <= 0) { ent->client->newweapon = GET_ITEM(MK23_NUM); ChangeWeapon (ent); return; } else { ent->client->weaponstate = WEAPON_RELOADING; ent->client->ps.gunframe = 0; } // ent->client->grenade_time = level.time + 1.0; ent->client->ps.gunframe++; } #define GRENADE_ACTIVATE_LAST 3 #define GRENADE_PULL_FIRST 72 #define GRENADE_PULL_LAST 79 //#define GRENADE_THROW_FIRST 4 //#define GRENADE_THROW_LAST 9 // throw it on frame 8? #define GRENADE_PINIDLE_FIRST 10 #define GRENADE_PINIDLE_LAST 39 // moved these up in the file (actually now in g_local.h) //#define GRENADE_IDLE_FIRST 40 //#define GRENADE_IDLE_LAST 69 // the 2 deactivation frames are a joke, they look like shit, probably best to roll // the activation frames backwards. Aren't really enough of them either. void Weapon_Gas (edict_t * ent) { if (ent->s.modelindex != 255) // zucc vwep return; // not on client, so VWep animations could do wacky things //FIREBLADE if (ent->client->weaponstate == WEAPON_FIRING && ((ent->solid == SOLID_NOT && ent->deadflag != DEAD_DEAD) || lights_camera_action)) { ent->client->weaponstate = WEAPON_READY; } //FIREBLADE if (ent->client->weaponstate == WEAPON_RELOADING) { if (ent->client->ps.gunframe < GRENADE_ACTIVATE_LAST) { ent->client->ps.gunframe++; } else { ent->client->ps.gunframe = GRENADE_PINIDLE_FIRST; ent->client->weaponstate = WEAPON_READY; } } if (ent->client->weaponstate == WEAPON_DROPPING) { if (ent->client->ps.gunframe == 0) { ChangeWeapon (ent); return; } else { // zucc going to have to do this a bit different because // of the way I roll gunframes backwards for the thrownknife position if ((ent->client->ps.gunframe) == 3) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } ent->client->ps.gunframe--; return; } } if (ent->client->weaponstate == WEAPON_ACTIVATING) { if (ent->client->ps.gunframe == GRENADE_ACTIVATE_LAST) { ent->client->ps.gunframe = GRENADE_PINIDLE_FIRST; ent->client->weaponstate = WEAPON_READY; return; } if (ent->client->ps.gunframe == GRENADE_PULL_LAST) { ent->client->ps.gunframe = GRENADE_IDLE_FIRST; ent->client->weaponstate = WEAPON_READY; gi.cprintf (ent, PRINT_HIGH, "Pin pulled, ready for %s range throw\n", ent->client->resp.grenade_mode == 0 ? "short" : (ent->client->resp.grenade_mode == 1 ? "medium" : "long")); return; } if (ent->client->ps.gunframe == 75) { gi.sound (ent, CHAN_WEAPON, gi.soundindex ("misc/grenade.wav"), 1, ATTN_NORM, 0); } ent->client->resp.sniper_mode = 0; // has to be here for dropping the sniper rifle, in the drop command didn't work... ent->client->desired_fov = 90; ent->client->ps.fov = 90; ent->client->ps.gunframe++; // gi.cprintf(ent, PRINT_HIGH, "After increment frames = %d\n", ent->client->ps.gunframe); return; } // bandaging case if ((ent->client->bandaging) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BURSTING) && (ent->client->weaponstate != WEAPON_BUSY) && (ent->client->weaponstate != WEAPON_BANDAGING)) { ent->client->weaponstate = WEAPON_BANDAGING; ent->client->ps.gunframe = GRENADE_ACTIVATE_LAST; return; } if (ent->client->weaponstate == WEAPON_BUSY) { if (ent->client->bandaging == 1) { if (!(ent->client->idle_weapon)) { Bandage (ent); } else (ent->client->idle_weapon)--; return; } // for after bandaging delay if (!(ent->client->idle_weapon) && ent->client->bandage_stopped) { if (INV_AMMO(ent, GRENADE_NUM) <= 0) { ent->client->newweapon = GET_ITEM(MK23_NUM); ent->client->bandage_stopped = 0; ChangeWeapon (ent); return; } ent->client->weaponstate = WEAPON_ACTIVATING; ent->client->ps.gunframe = 0; ent->client->bandage_stopped = 0; } else if (ent->client->bandage_stopped) (ent->client->idle_weapon)--; } if (ent->client->weaponstate == WEAPON_BANDAGING) { if (ent->client->ps.gunframe == 0) { ent->client->weaponstate = WEAPON_BUSY; ent->client->idle_weapon = BANDAGE_TIME; return; } ent->client->ps.gunframe--; return; } if ((ent->client->newweapon) && (ent->client->weaponstate != WEAPON_FIRING) && (ent->client->weaponstate != WEAPON_BUSY)) { // zucc - check if they have a primed grenade if (ent->client->curr_weap == GRENADE_NUM && ((ent->client->ps.gunframe >= GRENADE_IDLE_FIRST && ent->client->ps.gunframe <= GRENADE_IDLE_LAST) || (ent->client->ps.gunframe >= GRENADE_THROW_FIRST && ent->client->ps.gunframe <= GRENADE_THROW_LAST))) { int damage; // Reset Grenade Damage to 1.52 when requested: if (use_classic->value) damage = 170; else damage = GRENADE_DAMRAD; if(is_quad) damage *= 1.5f; fire_grenade2(ent, ent->s.origin, vec3_origin, damage, 0, 2, damage * 2, false); INV_AMMO(ent, GRENADE_NUM)--; if (INV_AMMO(ent, GRENADE_NUM) <= 0) { ent->client->newweapon = GET_ITEM(MK23_NUM); ChangeWeapon (ent); return; } } ent->client->ps.gunframe = GRENADE_ACTIVATE_LAST; // zucc more vwep stuff if ((GRENADE_ACTIVATE_LAST) < 4) { ent->client->anim_priority = ANIM_REVERSE; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crpain4 + 1; ent->client->anim_end = FRAME_crpain1; } else { ent->s.frame = FRAME_pain304 + 1; ent->client->anim_end = FRAME_pain301; } } ent->client->weaponstate = WEAPON_DROPPING; return; } if (ent->client->weaponstate == WEAPON_READY) { if (((ent->client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK) //FIREBLADE // AQ2:TNG - JBravo adding UVtime && (ent->solid != SOLID_NOT || ent->deadflag == DEAD_DEAD) && !lights_camera_action && !ent->client->ctf_uvtime) //FIREBLADE { if (ent->client->ps.gunframe <= GRENADE_PINIDLE_LAST && ent->client->ps.gunframe >= GRENADE_PINIDLE_FIRST) { ent->client->ps.gunframe = GRENADE_PULL_FIRST; ent->client->weaponstate = WEAPON_ACTIVATING; ent->client->latched_buttons &= ~BUTTON_ATTACK; } else { if (ent->client->ps.gunframe == GRENADE_IDLE_LAST) { ent->client->ps.gunframe = GRENADE_IDLE_FIRST; return; } ent->client->ps.gunframe++; return; } } if (ent->client->ps.gunframe >= GRENADE_IDLE_FIRST && ent->client->ps.gunframe <= GRENADE_IDLE_LAST) { ent->client->ps.gunframe = GRENADE_THROW_FIRST; ent->client->anim_priority = ANIM_ATTACK; if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) { ent->s.frame = FRAME_crattak1 - 1; ent->client->anim_end = FRAME_crattak9; } else { ent->s.frame = FRAME_attack1 - 1; ent->client->anim_end = FRAME_attack8; } ent->client->weaponstate = WEAPON_FIRING; return; } if (ent->client->ps.gunframe == GRENADE_PINIDLE_LAST) { ent->client->ps.gunframe = GRENADE_PINIDLE_FIRST; return; } ent->client->ps.gunframe++; return; } if (ent->client->weaponstate == WEAPON_FIRING) { if (ent->client->ps.gunframe == 8) { gas_fire (ent); return; } ent->client->ps.gunframe++; if (ent->client->ps.gunframe == GRENADE_IDLE_FIRST + 1 || ent->client->ps.gunframe == GRENADE_PINIDLE_FIRST + 1) ent->client->weaponstate = WEAPON_READY; } }
575
./aq2-tng/source/g_items.c
//----------------------------------------------------------------------------- // g_itmes.c // // $Id: g_items.c,v 1.13 2002/12/31 17:07:22 igor_rock Exp $ // //----------------------------------------------------------------------------- // $Log: g_items.c,v $ // Revision 1.13 2002/12/31 17:07:22 igor_rock // - corrected the Add_Ammo function to regard wp_flags // // Revision 1.12 2002/03/30 17:20:59 ra // New cvar use_buggy_bandolier to control behavior of dropping bando and grenades // // Revision 1.11 2002/03/28 20:28:56 ra // Forgot a } // // Revision 1.10 2002/03/28 20:24:08 ra // I overfixed the bug... // // Revision 1.9 2002/03/28 20:20:30 ra // Nasty grenade bug fixed. // // Revision 1.8 2002/03/27 15:16:56 freud // Original 1.52 spawn code implemented for use_newspawns 0. // Teamplay, when dropping bandolier, your drop the grenades. // Teamplay, cannot pick up grenades unless wearing bandolier. // // Revision 1.7 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.6 2001/07/18 15:19:11 slicerdw // Time for weapons and items dissapearing is set to "6" to prevent lag on ctf // // Revision 1.5 2001/05/31 16:58:14 igor_rock // conflicts resolved // // Revision 1.4.2.4 2001/05/26 13:04:34 igor_rock // added some sound to the precache list for flags // // Revision 1.4.2.3 2001/05/25 18:59:52 igor_rock // Added CTF Mode completly :) // Support for .flg files is still missing, but with "real" CTF maps like // tq2gtd1 the ctf works fine. // (I hope that all other modes still work, just tested DM and teamplay) // // Revision 1.4.2.2 2001/05/20 18:54:19 igor_rock // added original ctf code snippets from zoid. lib compilesand runs but // doesn't function the right way. // Jsut committing these to have a base to return to if something wents // awfully wrong. // // Revision 1.4.2.1 2001/05/20 15:17:31 igor_rock // removed the old ctf code completly // // Revision 1.4 2001/05/15 15:49:14 igor_rock // added itm_flags for deathmatch // // Revision 1.3 2001/05/14 21:10:16 igor_rock // added wp_flags support (and itm_flags skeleton - doesn't disturb in the moment) // // Revision 1.2 2001/05/11 16:07:25 mort // Various CTF bits and pieces... // // Revision 1.1.1.1 2001/05/06 17:31:33 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" qboolean Pickup_Weapon (edict_t * ent, edict_t * other); void Use_Weapon (edict_t * ent, gitem_t * inv); void Drop_Weapon (edict_t * ent, gitem_t * inv); void Weapon_Blaster (edict_t * ent); void Weapon_Shotgun (edict_t * ent); void Weapon_SuperShotgun (edict_t * ent); void Weapon_Machinegun (edict_t * ent); void Weapon_Chaingun (edict_t * ent); void Weapon_HyperBlaster (edict_t * ent); void Weapon_RocketLauncher (edict_t * ent); void Weapon_Grenade (edict_t * ent); void Weapon_GrenadeLauncher (edict_t * ent); void Weapon_Railgun (edict_t * ent); void Weapon_BFG (edict_t * ent); // zucc void Weapon_MK23 (edict_t * ent); void Weapon_MP5 (edict_t * ent); void Weapon_M4 (edict_t * ent); void Weapon_M3 (edict_t * ent); void Weapon_HC (edict_t * ent); void Weapon_Sniper (edict_t * ent); void Weapon_Dual (edict_t * ent); void Weapon_Knife (edict_t * ent); void Weapon_Gas (edict_t * ent); gitem_armor_t jacketarmor_info = { 25, 50, .30f, .00f, ARMOR_JACKET }; gitem_armor_t combatarmor_info = { 50, 100, .60f, .30f, ARMOR_COMBAT }; gitem_armor_t bodyarmor_info = { 100, 200, .80f, .60f, ARMOR_BODY }; static int jacket_armor_index; static int combat_armor_index; static int body_armor_index; static int power_screen_index; static int power_shield_index; #define HEALTH_IGNORE_MAX 1 #define HEALTH_TIMED 2 void Use_Quad (edict_t * ent, gitem_t * item); static int quad_drop_timeout_hack; //====================================================================== /* =============== GetItemByIndex =============== */ gitem_t *GetItemByIndex (int index) { if (index == 0 || index >= game.num_items) return NULL; return &itemlist[index]; } gitem_t *FindItemByNum (int num) { int i; gitem_t *it; it = itemlist+1; for (i = 1; i < game.num_items; i++, it++) { if (it->typeNum == num) return it; } return NULL; } /* =============== FindItemByClassname =============== */ gitem_t *FindItemByClassname (char *classname) { int i; gitem_t *it; it = itemlist+1; for (i = 1; i < game.num_items; i++, it++) { if (!it->classname) continue; if (!Q_stricmp (it->classname, classname)) return it; } return NULL; } /* =============== FindItem =============== */ gitem_t *FindItem (char *pickup_name) { int i; gitem_t *it; it = itemlist+1; for (i = 1; i < game.num_items; i++, it++) { if (!it->pickup_name) continue; if (!Q_stricmp (it->pickup_name, pickup_name)) return it; } return NULL; } //====================================================================== void DoRespawn (edict_t * ent) { if (ent->team) { edict_t *master; int count; int choice; master = ent->teammaster; //in ctf, when we are weapons stay, only the master of a team of weapons //is spawned // if (ctf->value && // ((int)dmflags->value & DF_WEAPONS_STAY) && // master->item && (master->item->flags & IT_WEAPON)) // ent = master; //else { for (count = 0, ent = master; ent; ent = ent->chain, count++) ; choice = rand () % count; for (count = 0, ent = master; count < choice; ent = ent->chain, count++) ; //} } ent->svflags &= ~SVF_NOCLIENT; ent->solid = SOLID_TRIGGER; gi.linkentity (ent); // send an effect ent->s.event = EV_ITEM_RESPAWN; } void SetRespawn (edict_t * ent, float delay) { ent->flags |= FL_RESPAWN; ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; ent->nextthink = level.time + delay; ent->think = DoRespawn; gi.linkentity (ent); } //====================================================================== qboolean Pickup_Powerup (edict_t * ent, edict_t * other) { int quantity; quantity = other->client->pers.inventory[ITEM_INDEX (ent->item)]; if ((skill->value == 1 && quantity >= 2) || (skill->value >= 2 && quantity >= 1)) return false; if ((coop->value) && (ent->item->flags & IT_STAY_COOP) && (quantity > 0)) return false; other->client->pers.inventory[ITEM_INDEX (ent->item)]++; if (deathmatch->value) { if (!(ent->spawnflags & DROPPED_ITEM)) SetRespawn (ent, ent->item->quantity); //if (((int)dmflags->value & DF_INSTANT_ITEMS) // || ((ent->item->use == Use_Quad) && (ent->spawnflags & DROPPED_PLAYER_ITEM))) //{ if ((ent->item->use == Use_Quad) && (ent->spawnflags & DROPPED_PLAYER_ITEM)) quad_drop_timeout_hack = (ent->nextthink - level.time) / FRAMETIME; ent->item->use (other, ent->item); //} } return true; } void AddItem(edict_t *ent, gitem_t *item) { ent->client->pers.inventory[ITEM_INDEX (item)]++; ent->client->unique_item_total++; if (item->typeNum == LASER_NUM) { ent->client->have_laser = 1; SP_LaserSight (ent, item); //ent->item->use(other, ent->item); } else if (item->typeNum == BAND_NUM) { if (ent->client->pers.max_bullets < 4) ent->client->pers.max_bullets = 4; if (ent->client->pers.max_shells < 28) ent->client->pers.max_shells = 28; if (ent->client->pers.max_cells < 2) ent->client->pers.max_cells = 2; if (ent->client->pers.max_slugs < 40) ent->client->pers.max_slugs = 40; if (ent->client->pers.max_grenades < 6) ent->client->pers.max_grenades = 6; if (ent->client->pers.max_rockets < 4) ent->client->pers.max_rockets = 4; if (ent->client->knife_max < 20) ent->client->knife_max = 20; if (ent->client->grenade_max < 4) ent->client->grenade_max = 4; // zucc for ir /*if ( ir->value && other->client->resp.ir == 0 ) { other->client->ps.rdflags |= RDF_IRGOGGLES; } */ } } qboolean Pickup_ItemPack (edict_t * ent, edict_t * other) { gitem_t *spec; int count = 0; int item; while(count < 2) { item = newrand(ITEM_COUNT); if (INV_AMMO(ent, tnums[item]) > 0 || !((int)itm_flags->value & items[tnums[item]].flag)) continue; spec = GET_ITEM(tnums[item]); AddItem(other, spec); count++; } SetRespawn (ent, item_respawn->value); return true; } //zucc pickup function for special items qboolean Pickup_Special (edict_t * ent, edict_t * other) { if (other->client->unique_item_total >= unique_items->value) return false; AddItem(other, ent->item); if(!(ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM)) && item_respawnmode->value) SetRespawn (ent, item_respawn->value); return true; } void Drop_Special (edict_t * ent, gitem_t * item) { int count; ent->client->unique_item_total--; /* if ( Q_stricmp( item->pickup_name, LASER_NAME ) == 0 && ent->client->pers.inventory[ITEM_INDEX(item)] <= 1 ) { ent->client->have_laser = 0; item->use(ent, item); } */ if (item->typeNum == BAND_NUM && INV_AMMO(ent, BAND_NUM) <= 1) { if(teamplay->value && !teamdm->value) count = 1; else count = 2; ent->client->pers.max_bullets = count; if (INV_AMMO(ent, MK23_ANUM) > count) INV_AMMO(ent, MK23_ANUM) = count; if(teamplay->value && !teamdm->value) { if(ent->client->resp.weapon->typeNum == HC_NUM) count = 12; else count = 7; } else { count = 14; } ent->client->pers.max_shells = count; if (INV_AMMO(ent, SHELL_ANUM) > count) INV_AMMO(ent, SHELL_ANUM) = count; ent->client->pers.max_cells = 1; if (INV_AMMO(ent, M4_ANUM) > 1) INV_AMMO(ent, M4_ANUM) = 1; ent->client->grenade_max = 2; if (use_buggy_bandolier->value == 0) { if ((!teamplay->value || teamdm->value) && INV_AMMO(ent, GRENADE_NUM) > 2) INV_AMMO(ent, GRENADE_NUM) = 2; else if (teamplay->value) { if (ent->client->curr_weap == GRENADE_NUM) INV_AMMO(ent, GRENADE_NUM) = 1; else INV_AMMO(ent, GRENADE_NUM) = 0; } } else { if (INV_AMMO(ent, GRENADE_NUM) > 2) INV_AMMO(ent, GRENADE_NUM) = 2; } if(teamplay->value && !teamdm->value) count = 1; else count = 2; ent->client->pers.max_rockets = count; if (INV_AMMO(ent, MP5_ANUM) > count) INV_AMMO(ent, MP5_ANUM) = count; ent->client->knife_max = 10; if (INV_AMMO(ent, KNIFE_NUM) > 10) INV_AMMO(ent, KNIFE_NUM) = 10; if(teamplay->value && !teamdm->value) count = 10; else count = 20; ent->client->pers.max_slugs = count; if (INV_AMMO(ent, SNIPER_ANUM) > count) INV_AMMO(ent, SNIPER_ANUM) = count; if (ent->client->unique_weapon_total > unique_weapons->value && !allweapon->value) { DropExtraSpecial (ent); gi.cprintf (ent, PRINT_HIGH, "One of your guns is dropped with the bandolier.\n"); } } Drop_Spec (ent, item); ValidateSelectedItem (ent); SP_LaserSight (ent, item); } // called by the "drop item" command void DropSpecialItem (edict_t * ent) { // this is the order I'd probably want to drop them in... if (INV_AMMO(ent, BAND_NUM)) Drop_Special (ent, GET_ITEM(BAND_NUM)); else if (INV_AMMO(ent, SLIP_NUM)) Drop_Special (ent, GET_ITEM(SLIP_NUM)); else if (INV_AMMO(ent, SIL_NUM)) Drop_Special (ent, GET_ITEM(SIL_NUM)); else if (INV_AMMO(ent, LASER_NUM)) Drop_Special (ent, GET_ITEM(LASER_NUM)); else if (INV_AMMO(ent, HELM_NUM)) Drop_Special (ent, GET_ITEM(HELM_NUM)); else if (INV_AMMO(ent, KEV_NUM)) Drop_Special (ent, GET_ITEM(KEV_NUM)); } void Drop_General (edict_t * ent, gitem_t * item) { Drop_Item (ent, item); ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); } //====================================================================== qboolean Pickup_Adrenaline (edict_t * ent, edict_t * other) { if (!deathmatch->value) other->max_health += 1; if (other->health < other->max_health) other->health = other->max_health; if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, ent->item->quantity); return true; } qboolean Pickup_AncientHead (edict_t * ent, edict_t * other) { other->max_health += 2; if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, ent->item->quantity); return true; } qboolean Pickup_Bandolier (edict_t * ent, edict_t * other) { gitem_t *item; int index; if (other->client->pers.max_bullets < 250) other->client->pers.max_bullets = 250; if (other->client->pers.max_shells < 150) other->client->pers.max_shells = 150; if (other->client->pers.max_cells < 250) other->client->pers.max_cells = 250; if (other->client->pers.max_slugs < 75) other->client->pers.max_slugs = 75; item = FindItem ("Bullets"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_bullets) other->client->pers.inventory[index] = other->client->pers.max_bullets; } item = FindItem ("Shells"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_shells) other->client->pers.inventory[index] = other->client->pers.max_shells; } if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, ent->item->quantity); return true; } qboolean Pickup_Pack (edict_t * ent, edict_t * other) { gitem_t *item; int index; if (other->client->pers.max_bullets < 300) other->client->pers.max_bullets = 300; if (other->client->pers.max_shells < 200) other->client->pers.max_shells = 200; if (other->client->pers.max_rockets < 100) other->client->pers.max_rockets = 100; if (other->client->pers.max_grenades < 100) other->client->pers.max_grenades = 100; if (other->client->pers.max_cells < 300) other->client->pers.max_cells = 300; if (other->client->pers.max_slugs < 100) other->client->pers.max_slugs = 100; item = FindItem ("Bullets"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_bullets) other->client->pers.inventory[index] = other->client->pers.max_bullets; } item = FindItem ("Shells"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_shells) other->client->pers.inventory[index] = other->client->pers.max_shells; } item = FindItem ("Cells"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_cells) other->client->pers.inventory[index] = other->client->pers.max_cells; } item = FindItem ("Grenades"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_grenades) other->client->pers.inventory[index] = other->client->pers.max_grenades; } item = FindItem ("Rockets"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_rockets) other->client->pers.inventory[index] = other->client->pers.max_rockets; } item = FindItem ("Slugs"); if (item) { index = ITEM_INDEX (item); other->client->pers.inventory[index] += item->quantity; if (other->client->pers.inventory[index] > other->client->pers.max_slugs) other->client->pers.inventory[index] = other->client->pers.max_slugs; } if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, ent->item->quantity); return true; } //====================================================================== void Use_Quad (edict_t * ent, gitem_t * item) { int timeout; ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); if (quad_drop_timeout_hack) { timeout = quad_drop_timeout_hack; quad_drop_timeout_hack = 0; } else { timeout = 300; } if (ent->client->quad_framenum > level.framenum) ent->client->quad_framenum += timeout; else ent->client->quad_framenum = level.framenum + timeout; gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/damage.wav"), 1, ATTN_NORM, 0); } //====================================================================== void Use_Breather (edict_t * ent, gitem_t * item) { ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); if (ent->client->breather_framenum > level.framenum) ent->client->breather_framenum += 300; else ent->client->breather_framenum = level.framenum + 300; // gi.sound(ent, CHAN_ITEM, gi.soundindex("items/damage.wav"), 1, ATTN_NORM, 0); } //====================================================================== void Use_Envirosuit (edict_t * ent, gitem_t * item) { ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); if (ent->client->enviro_framenum > level.framenum) ent->client->enviro_framenum += 300; else ent->client->enviro_framenum = level.framenum + 300; // gi.sound(ent, CHAN_ITEM, gi.soundindex("items/damage.wav"), 1, ATTN_NORM, 0); } //====================================================================== void Use_Invulnerability (edict_t * ent, gitem_t * item) { ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); if (ent->client->invincible_framenum > level.framenum) ent->client->invincible_framenum += 300; else ent->client->invincible_framenum = level.framenum + 300; gi.sound (ent, CHAN_ITEM, gi.soundindex ("items/protect.wav"), 1, ATTN_NORM, 0); } //====================================================================== void Use_Silencer (edict_t * ent, gitem_t * item) { ent->client->pers.inventory[ITEM_INDEX (item)]--; ValidateSelectedItem (ent); ent->client->silencer_shots += 30; // gi.sound(ent, CHAN_ITEM, gi.soundindex("items/damage.wav"), 1, ATTN_NORM, 0); } //====================================================================== qboolean Pickup_Key (edict_t * ent, edict_t * other) { if (coop->value) { if (strcmp (ent->classname, "key_power_cube") == 0) { if (other->client->pers.power_cubes & ((ent->spawnflags & 0x0000ff00) >> 8)) return false; other->client->pers.inventory[ITEM_INDEX (ent->item)]++; other->client->pers.power_cubes |= ((ent->spawnflags & 0x0000ff00) >> 8); } else { if (other->client->pers.inventory[ITEM_INDEX (ent->item)]) return false; other->client->pers.inventory[ITEM_INDEX (ent->item)] = 1; } return true; } other->client->pers.inventory[ITEM_INDEX (ent->item)]++; return true; } //====================================================================== qboolean Add_Ammo (edict_t * ent, gitem_t * item, int count) { int index; int max = 0; if (!ent->client) return false; switch(item->tag) { case AMMO_BULLETS: if (((int)wp_flags->value & WPF_MK23) || ((int)wp_flags->value & WPF_DUAL)) max = ent->client->pers.max_bullets; break; case AMMO_SHELLS: if (((int)wp_flags->value & WPF_M3) || ((int)wp_flags->value & WPF_HC)) max = ent->client->pers.max_shells; break; case AMMO_ROCKETS: if ((int)wp_flags->value & WPF_MP5) max = ent->client->pers.max_rockets; break; case AMMO_GRENADES: if ((int)wp_flags->value & WPF_GRENADE) max = ent->client->pers.max_grenades; break; case AMMO_CELLS: if ((int)wp_flags->value & WPF_M4) max = ent->client->pers.max_cells; break; case AMMO_SLUGS: if ((int)wp_flags->value & WPF_SNIPER) max = ent->client->pers.max_slugs; break; default: return false; } index = ITEM_INDEX (item); if (ent->client->pers.inventory[index] == max) return false; ent->client->pers.inventory[index] += count; if (ent->client->pers.inventory[index] > max) ent->client->pers.inventory[index] = max; return true; } qboolean Pickup_Ammo (edict_t * ent, edict_t * other) { int oldcount; int count; qboolean weapon; weapon = (ent->item->flags & IT_WEAPON); if ((weapon) && ((int) dmflags->value & DF_INFINITE_AMMO)) count = 1000; else if (ent->count) count = ent->count; else count = ent->item->quantity; oldcount = other->client->pers.inventory[ITEM_INDEX (ent->item)]; if (!Add_Ammo (other, ent->item, count)) return false; if (weapon && !oldcount) { if (other->client->pers.weapon != ent->item && (!deathmatch->value || other->client->pers.weapon == FindItem("blaster"))) other->client->newweapon = ent->item; } if (!(ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM)) && (deathmatch->value)) SetRespawn (ent, ammo_respawn->value); return true; } void Drop_Ammo (edict_t * ent, gitem_t * item) { edict_t *dropped; int index; if (ent->client->weaponstate == WEAPON_RELOADING) { gi.cprintf (ent, PRINT_HIGH, "Cant drop ammo while reloading\n"); return; } index = ITEM_INDEX (item); dropped = Drop_Item (ent, item); if (ent->client->pers.inventory[index] >= item->quantity) dropped->count = item->quantity; else dropped->count = ent->client->pers.inventory[index]; ent->client->pers.inventory[index] -= dropped->count; ValidateSelectedItem (ent); } //====================================================================== void MegaHealth_think (edict_t * self) { if (self->owner->health > self->owner->max_health) { self->nextthink = level.time + 1; self->owner->health -= 1; return; } if (!(self->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (self, 20); else G_FreeEdict (self); } qboolean Pickup_Health (edict_t * ent, edict_t * other) { if (!(ent->style & HEALTH_IGNORE_MAX)) if (other->health >= other->max_health) return false; other->health += ent->count; if (ent->count == 2) ent->item->pickup_sound = "items/s_health.wav"; else if (ent->count == 10) ent->item->pickup_sound = "items/n_health.wav"; else if (ent->count == 25) ent->item->pickup_sound = "items/l_health.wav"; else // (ent->count == 100) ent->item->pickup_sound = "items/m_health.wav"; if (!(ent->style & HEALTH_IGNORE_MAX)) { if (other->health > other->max_health) other->health = other->max_health; } if (ent->style & HEALTH_TIMED) { ent->think = MegaHealth_think; ent->nextthink = level.time + 5; ent->owner = other; ent->flags |= FL_RESPAWN; ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; } else { if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, 30); } return true; } //====================================================================== int ArmorIndex (edict_t * ent) { if (!ent->client) return 0; if (ent->client->pers.inventory[jacket_armor_index] > 0) return jacket_armor_index; if (ent->client->pers.inventory[combat_armor_index] > 0) return combat_armor_index; if (ent->client->pers.inventory[body_armor_index] > 0) return body_armor_index; return 0; } qboolean Pickup_Armor (edict_t * ent, edict_t * other) { int old_armor_index; gitem_armor_t *oldinfo; gitem_armor_t *newinfo; int newcount; float salvage; int salvagecount; // get info on new armor newinfo = (gitem_armor_t *) ent->item->info; old_armor_index = ArmorIndex (other); // handle armor shards specially if (ent->item->tag == ARMOR_SHARD) { if (!old_armor_index) other->client->pers.inventory[jacket_armor_index] = 2; else other->client->pers.inventory[old_armor_index] += 2; } // if player has no armor, just use it else if (!old_armor_index) { other->client->pers.inventory[ITEM_INDEX (ent->item)] = newinfo->base_count; } // use the better armor else { // get info on old armor if (old_armor_index == jacket_armor_index) oldinfo = &jacketarmor_info; else if (old_armor_index == combat_armor_index) oldinfo = &combatarmor_info; else // (old_armor_index == body_armor_index) oldinfo = &bodyarmor_info; if (newinfo->normal_protection > oldinfo->normal_protection) { // calc new armor values salvage = oldinfo->normal_protection / newinfo->normal_protection; salvagecount = salvage * other->client->pers.inventory[old_armor_index]; newcount = newinfo->base_count + salvagecount; if (newcount > newinfo->max_count) newcount = newinfo->max_count; // zero count of old armor so it goes away other->client->pers.inventory[old_armor_index] = 0; // change armor to new item with computed value other->client->pers.inventory[ITEM_INDEX (ent->item)] = newcount; } else { // calc new armor values salvage = newinfo->normal_protection / oldinfo->normal_protection; salvagecount = salvage * newinfo->base_count; newcount = other->client->pers.inventory[old_armor_index] + salvagecount; if (newcount > oldinfo->max_count) newcount = oldinfo->max_count; // if we're already maxed out then we don't need the new armor if (other->client->pers.inventory[old_armor_index] >= newcount) return false; // update current armor value other->client->pers.inventory[old_armor_index] = newcount; } } if (!(ent->spawnflags & DROPPED_ITEM) && (deathmatch->value)) SetRespawn (ent, 20); return true; } //====================================================================== int PowerArmorType (edict_t * ent) { if (!ent->client) return POWER_ARMOR_NONE; if (!(ent->flags & FL_POWER_ARMOR)) return POWER_ARMOR_NONE; if (ent->client->pers.inventory[power_shield_index] > 0) return POWER_ARMOR_SHIELD; if (ent->client->pers.inventory[power_screen_index] > 0) return POWER_ARMOR_SCREEN; return POWER_ARMOR_NONE; } void Use_PowerArmor (edict_t * ent, gitem_t * item) { int index; if (ent->flags & FL_POWER_ARMOR) { ent->flags &= ~FL_POWER_ARMOR; gi.sound (ent, CHAN_AUTO, gi.soundindex ("misc/power2.wav"), 1, ATTN_NORM, 0); } else { index = ITEM_INDEX (FindItem ("cells")); if (!ent->client->pers.inventory[index]) { gi.cprintf (ent, PRINT_HIGH, "No cells for power armor.\n"); return; } ent->flags |= FL_POWER_ARMOR; gi.sound (ent, CHAN_AUTO, gi.soundindex ("misc/power1.wav"), 1, ATTN_NORM, 0); } } qboolean Pickup_PowerArmor (edict_t * ent, edict_t * other) { int quantity; quantity = other->client->pers.inventory[ITEM_INDEX (ent->item)]; other->client->pers.inventory[ITEM_INDEX (ent->item)]++; if (deathmatch->value) { if (!(ent->spawnflags & DROPPED_ITEM)) SetRespawn (ent, ent->item->quantity); // auto-use for DM only if we didn't already have one if (!quantity) ent->item->use (other, ent->item); } return true; } void Drop_PowerArmor (edict_t * ent, gitem_t * item) { if ((ent->flags & FL_POWER_ARMOR) && (ent->client->pers.inventory[ITEM_INDEX (item)] == 1)) Use_PowerArmor (ent, item); Drop_General (ent, item); } //====================================================================== /* =============== Touch_Item =============== */ void Touch_Item (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { qboolean taken; if (!other->client) return; if (other->health < 1) return; // dead people can't pickup if (!ent->item->pickup) return; // not a grabbable item? taken = ent->item->pickup (ent, other); if (taken) { // flash the screen other->client->bonus_alpha = 0.25; // show icon and name on status bar //FIREBLADE (debug code) if (!ent->item->icon || strlen (ent->item->icon) == 0) { if (ent->item->classname) gi.dprintf ("Warning: null icon filename (classname = %s)\n", ent->item->classname); else gi.dprintf ("Warning: null icon filename (no classname)\n"); } //FIREBLADE other->client->ps.stats[STAT_PICKUP_ICON] = gi.imageindex (ent->item->icon); other->client->ps.stats[STAT_PICKUP_STRING] = CS_ITEMS + ITEM_INDEX (ent->item); other->client->pickup_msg_time = level.time + 3.0; // change selected item if (ent->item->use) other->client->pers.selected_item = other->client->ps.stats[STAT_SELECTED_ITEM] = ITEM_INDEX (ent->item); else gi.sound (other, CHAN_ITEM, gi.soundindex (ent->item->pickup_sound), 1, ATTN_NORM, 0); } if (!(ent->spawnflags & ITEM_TARGETS_USED)) { G_UseTargets (ent, other); ent->spawnflags |= ITEM_TARGETS_USED; } if (!taken) return; if (!((coop->value) && (ent->item->flags & IT_STAY_COOP)) || (ent->spawnflags & (DROPPED_ITEM | DROPPED_PLAYER_ITEM))) { if (ent->flags & FL_RESPAWN) ent->flags &= ~FL_RESPAWN; else G_FreeEdict (ent); } } //====================================================================== static void drop_temp_touch (edict_t * ent, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other == ent->owner) return; Touch_Item (ent, other, plane, surf); } static void drop_make_touchable (edict_t * ent) { ent->touch = Touch_Item; if (deathmatch->value) { //AQ2:TNG - Slicer if (ctf->value) { ent->nextthink = level.time + 6; ent->think = G_FreeEdict; } else { ent->nextthink = level.time + 119; ent->think = G_FreeEdict; } } } edict_t *Drop_Item (edict_t * ent, gitem_t * item) { edict_t *dropped; vec3_t forward, right; vec3_t offset; dropped = G_Spawn (); dropped->classname = item->classname; dropped->typeNum = item->typeNum; dropped->item = item; dropped->spawnflags = DROPPED_ITEM; dropped->s.effects = item->world_model_flags; dropped->s.renderfx = RF_GLOW; VectorSet (dropped->mins, -15, -15, -15); VectorSet (dropped->maxs, 15, 15, 15); // zucc dumb hack to make knife look like it is on the ground if (item->typeNum == KNIFE_NUM || item->typeNum == LASER_NUM || item->typeNum == GRENADE_NUM) { VectorSet (dropped->mins, -15, -15, -1); VectorSet (dropped->maxs, 15, 15, 1); } // spin? VectorSet (dropped->avelocity, 0, 600, 0); gi.setmodel (dropped, dropped->item->world_model); dropped->solid = SOLID_TRIGGER; dropped->movetype = MOVETYPE_TOSS; dropped->touch = drop_temp_touch; dropped->owner = ent; if (ent->client) { trace_t trace; AngleVectors (ent->client->v_angle, forward, right, NULL); VectorSet (offset, 24, 0, -16); G_ProjectSource (ent->s.origin, offset, forward, right, dropped->s.origin); PRETRACE (); trace = gi.trace (ent->s.origin, dropped->mins, dropped->maxs, dropped->s.origin, ent, CONTENTS_SOLID); POSTTRACE (); VectorCopy (trace.endpos, dropped->s.origin); } else { AngleVectors (ent->s.angles, forward, right, NULL); VectorCopy (ent->s.origin, dropped->s.origin); } VectorScale (forward, 100, dropped->velocity); dropped->velocity[2] = 300; dropped->think = drop_make_touchable; dropped->nextthink = level.time + 1; gi.linkentity (dropped); return dropped; } void Use_Item (edict_t * ent, edict_t * other, edict_t * activator) { ent->svflags &= ~SVF_NOCLIENT; ent->use = NULL; if (ent->spawnflags & ITEM_NO_TOUCH) { ent->solid = SOLID_BBOX; ent->touch = NULL; } else { ent->solid = SOLID_TRIGGER; ent->touch = Touch_Item; } gi.linkentity (ent); } //====================================================================== /* ================ droptofloor ================ */ void droptofloor (edict_t * ent) { trace_t tr; vec3_t dest; VectorSet(ent->mins, -15, -15, -15); VectorSet(ent->maxs, 15, 15, 15); if (ent->item) { if (ent->item->typeNum == KNIFE_NUM || ent->item->typeNum == LASER_NUM || ent->item->typeNum == GRENADE_NUM) { VectorSet (ent->mins, -15, -15, -1); VectorSet (ent->maxs, 15, 15, 1); } } if (ent->model) gi.setmodel (ent, ent->model); else gi.setmodel (ent, ent->item->world_model); ent->solid = SOLID_TRIGGER; ent->movetype = MOVETYPE_TOSS; ent->touch = Touch_Item; VectorCopy(ent->s.origin, dest); dest[2] -= 128; PRETRACE (); tr = gi.trace (ent->s.origin, ent->mins, ent->maxs, dest, ent, MASK_SOLID); POSTTRACE (); if (tr.startsolid) { gi.dprintf ("droptofloor: %s startsolid at %s\n", ent->classname, vtos(ent->s.origin)); G_FreeEdict (ent); return; } VectorCopy (tr.endpos, ent->s.origin); if (ent->team) { ent->flags &= ~FL_TEAMSLAVE; ent->chain = ent->teamchain; ent->teamchain = NULL; ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; if (ent == ent->teammaster) { ent->nextthink = level.time + FRAMETIME; ent->think = DoRespawn; } } if (ent->spawnflags & ITEM_NO_TOUCH) { ent->solid = SOLID_BBOX; ent->touch = NULL; ent->s.effects &= ~EF_ROTATE; ent->s.renderfx &= ~RF_GLOW; } if (ent->spawnflags & ITEM_TRIGGER_SPAWN) { ent->svflags |= SVF_NOCLIENT; ent->solid = SOLID_NOT; ent->use = Use_Item; } gi.linkentity (ent); } /* =============== PrecacheItem Precaches all data needed for a given item. This will be called for each item spawned in a level, and for each item in each client's inventory. =============== */ void PrecacheItem (gitem_t * it) { char *s, *start; char data[MAX_QPATH]; int len; gitem_t *ammo; if (!it) return; if (it->pickup_sound) gi.soundindex (it->pickup_sound); if (it->world_model) gi.modelindex (it->world_model); if (it->view_model) gi.modelindex (it->view_model); if (it->icon) gi.imageindex (it->icon); // parse everything for its ammo if (it->ammo && it->ammo[0]) { ammo = FindItem (it->ammo); if (ammo != it) PrecacheItem (ammo); } // parse the space seperated precache string for other items s = it->precaches; if (!s || !s[0]) return; while (*s) { start = s; while (*s && *s != ' ') s++; len = s - start; if (len >= MAX_QPATH || len < 5) gi.error ("PrecacheItem: %s has bad precache string", it->classname); memcpy (data, start, len); data[len] = 0; if (*s) s++; // determine type based on extension if (!strcmp (data + len - 3, "md2")) gi.modelindex (data); else if (!strcmp (data + len - 3, "sp2")) gi.modelindex (data); else if (!strcmp (data + len - 3, "wav")) gi.soundindex (data); else if (!strcmp (data + len - 3, "pcx")) gi.imageindex (data); } } /* ============ PrecacheItems Makes sure the client loads all necessary data on connect to avoid lag. ============ */ void PrecacheItems () { PrecacheItem(FindItemByClassname("weapon_Mk23")); PrecacheItem(FindItemByClassname("weapon_MP5")); PrecacheItem(FindItemByClassname("weapon_M4")); PrecacheItem(FindItemByClassname("weapon_M3")); PrecacheItem(FindItemByClassname("weapon_HC")); PrecacheItem(FindItemByClassname("weapon_Sniper")); PrecacheItem(FindItemByClassname("weapon_Dual")); PrecacheItem(FindItemByClassname("weapon_Knife")); PrecacheItem(FindItemByClassname("weapon_Grenade")); PrecacheItem(FindItemByClassname("item_quiet")); PrecacheItem(FindItemByClassname("item_band")); PrecacheItem(FindItemByClassname("item_lasersight")); PrecacheItem(FindItemByClassname("item_slippers")); PrecacheItem(FindItemByClassname("item_vest")); PrecacheItem(FindItemByClassname("item_helmet")); PrecacheItem(FindItemByClassname("item_bandolier")); if (ctf->value) { PrecacheItem(FindItemByClassname("item_flag_team1")); PrecacheItem(FindItemByClassname("item_flag_team2")); } } /* ============ SpawnItem Sets the clipping size and plants the object on the floor. Items can't be immediately dropped to floor, because they might be on an entity that hasn't spawned yet. ============ */ void SpawnItem (edict_t * ent, gitem_t * item) { PrecacheItem (item); if (ent->spawnflags) { if (strcmp (ent->classname, "key_power_cube") != 0) { ent->spawnflags = 0; gi.dprintf ("%s at %s has invalid spawnflags set\n", ent->classname, vtos (ent->s.origin)); } } //AQ2:TNG - Igor adding wp_flags/itm_flags // Weapons and Ammo switch(item->typeNum) { case MK23_NUM: case MK23_ANUM: if (!((int)wp_flags->value & WPF_MK23)) { G_FreeEdict (ent); return; } break; case MP5_NUM: case MP5_ANUM: if (!((int)wp_flags->value & WPF_MP5)) { G_FreeEdict (ent); return; } break; case M4_NUM: case M4_ANUM: if (!((int)wp_flags->value & WPF_M4)) { G_FreeEdict (ent); return; } break; case M3_NUM: if (!((int)wp_flags->value & WPF_M3)) { G_FreeEdict (ent); return; } break; case HC_NUM: if (!((int)wp_flags->value & WPF_HC)) { G_FreeEdict (ent); return; } break; case SHELL_ANUM: if (!(((int)wp_flags->value & WPF_M3) || ((int)wp_flags->value & WPF_HC))) { G_FreeEdict (ent); return; } break; case SNIPER_NUM: case SNIPER_ANUM: if (!((int)wp_flags->value & WPF_SNIPER)) { G_FreeEdict (ent); return; } break; case DUAL_NUM: if (!((int)wp_flags->value & WPF_DUAL)) { G_FreeEdict (ent); return; } break; case KNIFE_NUM: if (!((int)wp_flags->value & WPF_KNIFE)) { G_FreeEdict (ent); return; } break; case GRENADE_NUM: if (!((int)wp_flags->value & WPF_GRENADE)) { G_FreeEdict (ent); return; } break; // Items case SIL_NUM: if (!((int)itm_flags->value & ITF_SIL)) { G_FreeEdict (ent); return; } break; case SLIP_NUM: if (!((int)itm_flags->value & ITF_SLIP)) { G_FreeEdict (ent); return; } break; case BAND_NUM: if (!((int)itm_flags->value & ITF_BAND)) { G_FreeEdict (ent); return; } break; case KEV_NUM: if (!((int)itm_flags->value & ITF_KEV)) { G_FreeEdict (ent); return; } break; case LASER_NUM: if (!((int)itm_flags->value & ITF_LASER)) { G_FreeEdict (ent); return; } break; case HELM_NUM: if (!((int)itm_flags->value & ITF_HELM)) { G_FreeEdict (ent); return; } break; } //AQ2:TNG End adding flags // some items will be prevented in deathmatch if (deathmatch->value) { if ((int) dmflags->value & DF_NO_ARMOR) { if (item->pickup == Pickup_Armor || item->pickup == Pickup_PowerArmor) { G_FreeEdict (ent); return; } } if ((int) dmflags->value & DF_NO_ITEMS) { if (item->pickup == Pickup_Powerup) { G_FreeEdict (ent); return; } } // zucc remove health from the game if (1 /*(int)dmflags->value & DF_NO_HEALTH */ ) { if (item->pickup == Pickup_Health || item->pickup == Pickup_Adrenaline || item->pickup == Pickup_AncientHead) { G_FreeEdict (ent); return; } } if ((int) dmflags->value & DF_INFINITE_AMMO) { if ((item->flags == IT_AMMO) || (strcmp (ent->classname, "weapon_bfg") == 0)) { G_FreeEdict (ent); return; } } } if (coop->value && (strcmp (ent->classname, "key_power_cube") == 0)) { ent->spawnflags |= (1 << (8 + level.power_cubes)); level.power_cubes++; } // don't let them drop items that stay in a coop game if ((coop->value) && (item->flags & IT_STAY_COOP)) { item->drop = NULL; } //Don't spawn the flags unless enabled if (!ctf->value && (item->typeNum == FLAG_T1_NUM || item->typeNum == FLAG_T2_NUM)) { G_FreeEdict (ent); return; } ent->item = item; ent->nextthink = level.time + 2 * FRAMETIME; // items start after other solids ent->think = droptofloor; ent->s.effects = item->world_model_flags; ent->s.renderfx = RF_GLOW; ent->typeNum = item->typeNum; if (ent->model) gi.modelindex (ent->model); //flags are server animated and have special handling if (ctf->value && (item->typeNum == FLAG_T1_NUM || item->typeNum == FLAG_T2_NUM)) { ent->think = CTFFlagSetup; } } //====================================================================== gitem_t itemlist[] = { { NULL} , // leave index 0 alone // // ARMOR // /*QUAKED item_armor_body (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_armor_body", Pickup_Armor, NULL, NULL, NULL, "misc/ar1_pkup.wav", "models/items/armor/body/tris.md2", EF_ROTATE, NULL, /* icon */ "i_bodyarmor", /* pickup */ "Body Armor", /* width */ 3, 0, NULL, IT_ARMOR, &bodyarmor_info, ARMOR_BODY, /* precache */ "", NO_NUM } , /*QUAKED item_armor_combat (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_armor_combat", Pickup_Armor, NULL, NULL, NULL, "misc/ar1_pkup.wav", "models/items/armor/combat/tris.md2", EF_ROTATE, NULL, /* icon */ "i_combatarmor", /* pickup */ "Combat Armor", /* width */ 3, 0, NULL, IT_ARMOR, &combatarmor_info, ARMOR_COMBAT, /* precache */ "", NO_NUM } , /*QUAKED item_armor_jacket (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_armor_jacket", Pickup_Armor, NULL, NULL, NULL, "misc/ar1_pkup.wav", "models/items/armor/jacket/tris.md2", EF_ROTATE, NULL, /* icon */ "i_jacketarmor", /* pickup */ "Jacket Armor", /* width */ 3, 0, NULL, IT_ARMOR, &jacketarmor_info, ARMOR_JACKET, /* precache */ "", NO_NUM } , /*QUAKED item_armor_shard (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_armor_shard", Pickup_Armor, NULL, NULL, NULL, "misc/ar2_pkup.wav", "models/items/armor/shard/tris.md2", EF_ROTATE, NULL, /* icon */ "i_jacketarmor", /* pickup */ "Armor Shard", /* width */ 3, 0, NULL, IT_ARMOR, NULL, ARMOR_SHARD, /* precache */ "", NO_NUM } , /*QUAKED item_power_screen (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_power_screen", Pickup_PowerArmor, Use_PowerArmor, Drop_PowerArmor, NULL, "misc/ar3_pkup.wav", "models/items/armor/screen/tris.md2", EF_ROTATE, NULL, /* icon */ "i_powerscreen", /* pickup */ "Power Screen", /* width */ 0, 60, NULL, IT_ARMOR, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED item_power_shield (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_power_shield", Pickup_PowerArmor, Use_PowerArmor, Drop_PowerArmor, NULL, "misc/ar3_pkup.wav", "models/items/armor/shield/tris.md2", EF_ROTATE, NULL, /* icon */ "i_powershield", /* pickup */ "Power Shield", /* width */ 0, 60, NULL, IT_ARMOR, NULL, 0, /* precache */ "", // "misc/power2.wav misc/power1.wav" NO_NUM } , // // WEAPONS // /* weapon_blaster (.3 .3 1) (-16 -16 -16) (16 16 16) always owned, never in the world */ { "weapon_blaster", NULL, Use_Weapon, NULL, Weapon_Blaster, "misc/w_pkup.wav", NULL, 0, "models/weapons/v_blast/tris.md2", /* icon */ "w_blaster", /* pickup */ "Blaster", 0, 0, NULL, 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", NO_NUM } , /* weapon_grapple (.3 .3 1) (-16 -16 -16) (16 16 16)^M always owned, never in the world^M */ { "weapon_grapple", NULL, Use_Weapon, NULL, CTFWeapon_Grapple, "misc/w_pkup.wav", NULL, 0, "models/weapons/grapple/tris.md2", /* icon */ "w_grapple", /* pickup */ "Grapple", 0, 0, NULL, IT_WEAPON, NULL, 0, /* precache */ "weapons/grapple/grfire.wav weapons/grapple/grpull.wav weapons/grapple/grhang.wav weapons/grapple/grreset.wav weapons/grapple/grhit.wav", GRAPPLE_NUM }, /*QUAKED weapon_shotgun (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_shotgun", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Shotgun, "misc/w_pkup.wav", "models/weapons/g_shotg/tris.md2", EF_ROTATE, "models/weapons/v_shotg/tris.md2", /* icon */ "w_shotgun", /* pickup */ "Shotgun", 0, 1, "Shells", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/shotgf1b.wav weapons/shotgr1b.wav" NO_NUM } , /*QUAKED weapon_supershotgun (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_supershotgun", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_SuperShotgun, "misc/w_pkup.wav", "models/weapons/g_shotg2/tris.md2", EF_ROTATE, "models/weapons/v_shotg2/tris.md2", /* icon */ "w_sshotgun", /* pickup */ "Super Shotgun", 0, 2, "Shells", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/sshotf1b.wav" NO_NUM } , /*QUAKED weapon_machinegun (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_machinegun", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Machinegun, "misc/w_pkup.wav", "models/weapons/g_machn/tris.md2", EF_ROTATE, "models/weapons/v_machn/tris.md2", /* icon */ "w_machinegun", /* pickup */ "Machinegun", 0, 1, "Bullets", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/machgf1b.wav weapons/machgf2b.wav weapons/machgf3b.wav weapons/machgf4b.wav weapons/machgf5b.wav" NO_NUM } , /*QUAKED weapon_chaingun (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_chaingun", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Chaingun, "misc/w_pkup.wav", "models/weapons/g_chain/tris.md2", EF_ROTATE, "models/weapons/v_chain/tris.md2", /* icon */ "w_chaingun", /* pickup */ "Chaingun", 0, 1, "Bullets", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/chngnu1a.wav weapons/chngnl1a.wav weapons/machgf3b.wav` weapons/chngnd1a.wav" NO_NUM } , /*QUAKED ammo_grenades (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_grenades", Pickup_Ammo, Use_Weapon, Drop_Ammo, Weapon_Grenade, "misc/am_pkup.wav", "models/items/ammo/grenades/medium/tris.md2", 0, "models/weapons/v_handgr/tris.md2", /* icon */ "a_grenades", /* pickup */ "Grenades", /* width */ 3, 5, "grenades", 0, //IT_AMMO|IT_WEAPON, NULL, AMMO_GRENADES, /* precache */ "weapons/hgrent1a.wav weapons/hgrena1b.wav weapons/hgrenc1b.wav weapons/hgrenb1a.wav weapons/hgrenb2a.wav weapons/grenlb1b.wav", NO_NUM } , /*QUAKED weapon_grenadelauncher (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_grenadelauncher", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_GrenadeLauncher, "misc/w_pkup.wav", "models/weapons/g_launch/tris.md2", EF_ROTATE, "models/weapons/v_launch/tris.md2", /* icon */ "w_glauncher", /* pickup */ "Grenade Launcher", 0, 1, "Grenades", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"models/objects/grenade/tris.md2 weapons/grenlf1a.wav weapons/grenlr1b.wav weapons/grenlb1b.wav" NO_NUM } , /*QUAKED weapon_rocketlauncher (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_rocketlauncher", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_RocketLauncher, "misc/w_pkup.wav", "models/weapons/g_rocket/tris.md2", EF_ROTATE, "models/weapons/v_rocket/tris.md2", /* icon */ "w_rlauncher", /* pickup */ "Rocket Launcher", 0, 1, "Rockets", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"models/objects/rocket/tris.md2 weapons/rockfly.wav weapons/rocklf1a.wav weapons/rocklr1b.wav models/objects/debris2/tris.md2" NO_NUM } , /*QUAKED weapon_hyperblaster (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_hyperblaster", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_HyperBlaster, "misc/w_pkup.wav", "models/weapons/g_hyperb/tris.md2", EF_ROTATE, "models/weapons/v_hyperb/tris.md2", /* icon */ "w_hyperblaster", /* pickup */ "HyperBlaster", 0, 1, "Cells", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/hyprbu1a.wav weapons/hyprbl1a.wav weapons/hyprbf1a.wav weapons/hyprbd1a.wav misc/lasfly.wav" NO_NUM } , /*QUAKED weapon_railgun (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_railgun", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Railgun, "misc/w_pkup.wav", "models/weapons/g_rail/tris.md2", EF_ROTATE, "models/weapons/v_rail/tris.md2", /* icon */ "w_railgun", /* pickup */ "Railgun", 0, 1, "Slugs", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"weapons/rg_hum.wav" NO_NUM } , /*QUAKED weapon_bfg (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "weapon_bfg", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_BFG, "misc/w_pkup.wav", "models/weapons/g_bfg/tris.md2", EF_ROTATE, "models/weapons/v_bfg/tris.md2", /* icon */ "w_bfg", /* pickup */ "BFG10K", 0, 50, "Cells", 0, //IT_WEAPON|IT_STAY_COOP, NULL, 0, /* precache */ "", //"sprites/s_bfg1.sp2 sprites/s_bfg2.sp2 sprites/s_bfg3.sp2 weapons/bfg__f1y.wav weapons/bfg__l1a.wav weapons/bfg__x1b.wav weapons/bfg_hum.wav" NO_NUM } , // zucc - New Weapons /* gitem_t referenced by 'entity_name->item.attribute' Name Type Notes ammo char * type of ammo to use classname char * name when spawning it count_width int number of digits to display by icon drop void function called when entity dropped flags int type of pickup : IT_WEAPON, IT_AMMO, IT_ARMOR icon char * filename of icon info void * ? unused pickup qboolean function called when entity picked up pickup_name char * displayed onscreen when item picked up pickup_sound char * filename of sound to play when picked up precaches char * string containing all models, sounds etc. needed by this item quantity int ammo gained by item/ammo used per shot by item tag int ? unused use void function called when entity used view_model char * filename of model when being held weaponthink void unused function world_model char * filename of model when item is sitting on level world_model_flags int copied to 'ent->s.effects' (see s.effects for values) */ { "weapon_Mk23", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_MK23, //"misc/w_pkup.wav", NULL, "models/weapons/g_dual/tris.md2", 0, "models/weapons/v_blast/tris.md2", "w_mk23", MK23_NAME, 0, 1, "Pistol Clip", IT_WEAPON, NULL, 0, "weapons/mk23fire.wav weapons/mk23in.wav weapons/mk23out.wav weapons/mk23slap.wav weapons/mk23slide.wav misc/click.wav weapons/machgf4b.wav weapons/blastf1a.wav", MK23_NUM} , { "weapon_MP5", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_MP5, //"misc/w_pkup.wav", NULL, "models/weapons/g_machn/tris.md2", 0, "models/weapons/v_machn/tris.md2", "w_mp5", MP5_NAME, 0, 0, "Machinegun Magazine", IT_WEAPON, NULL, 0, "weapons/mp5fire1.wav weapons/mp5in.wav weapons/mp5out.wav weapons/mp5slap.wav weapons/mp5slide.wav weapons/machgf1b.wav weapons/machgf2b.wav weapons/machgf3b.wav weapons/machgf5b.wav", MP5_NUM} , { "weapon_M4", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_M4, //"misc/w_pkup.wav", NULL, "models/weapons/g_m4/tris.md2", 0, "models/weapons/v_m4/tris.md2", "w_m4", M4_NAME, 0, 0, "M4 Clip", IT_WEAPON, NULL, 0, "weapons/m4a1fire.wav weapons/m4a1in.wav weapons/m4a1out.wav weapons/m4a1slide.wav weapons/rocklf1a.wav weapons/rocklr1b.wav", M4_NUM} , { "weapon_M3", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_M3, //"misc/w_pkup.wav", NULL, "models/weapons/g_shotg/tris.md2", 0, "models/weapons/v_shotg/tris.md2", "w_super90", M3_NAME, 0, 0, "12 Gauge Shells", IT_WEAPON, NULL, 0, "weapons/m3in.wav weapons/shotgr1b.wav weapons/shotgf1b.wav", M3_NUM} , { "weapon_HC", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_HC, //"misc/w_pkup.wav", NULL, "models/weapons/g_cannon/tris.md2", 0, "models/weapons/v_cannon/tris.md2", "w_cannon", HC_NAME, 0, 0, "12 Gauge Shells", IT_WEAPON, NULL, 0, "weapons/cannon_fire.wav weapons/sshotf1b.wav weapons/cclose.wav weapons/cin.wav weapons/cout.wav weapons/copen.wav", HC_NUM} , { "weapon_Sniper", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Sniper, //"misc/w_pkup.wav", NULL, "models/weapons/g_sniper/tris.md2", 0, "models/weapons/v_sniper/tris.md2", "w_sniper", SNIPER_NAME, 0, 0, "AP Sniper Ammo", IT_WEAPON, NULL, 0, "weapons/ssgbolt.wav weapons/ssgfire.wav weapons/ssgin.wav misc/lensflik.wav weapons/hyprbl1a.wav weapons/hyprbf1a.wav", SNIPER_NUM} , { "weapon_Dual", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Dual, //"misc/w_pkup.wav", NULL, "models/weapons/g_dual/tris.md2", 0, "models/weapons/v_dual/tris.md2", "w_akimbo", DUAL_NAME, 0, 0, "Pistol Clip", IT_WEAPON, NULL, 0, "weapons/mk23fire.wav weapons/mk23in.wav weapons/mk23out.wav weapons/mk23slap.wav weapons/mk23slide.wav", DUAL_NUM} , { "weapon_Knife", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Knife, NULL, "models/objects/knife/tris.md2", 0, "models/weapons/v_knife/tris.md2", "w_knife", KNIFE_NAME, 0, 0, NULL, IT_WEAPON, NULL, 0, "weapons/throw.wav weapons/stab.wav weapons/swish.wav weapons/clank.wav", KNIFE_NUM} , { "weapon_Grenade", Pickup_Weapon, Use_Weapon, Drop_Weapon, Weapon_Gas, NULL, "models/objects/grenade2/tris.md2", 0, "models/weapons/v_handgr/tris.md2", "a_m61frag", GRENADE_NAME, 0, 0, NULL, IT_WEAPON, NULL, 0, "misc/grenade.wav weapons/grenlb1b.wav weapons/hgrent1a.wav", GRENADE_NUM} , // // AMMO ITEMS // /*QUAKED ammo_shells (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_shells", Pickup_Ammo, NULL, Drop_Ammo, NULL, "misc/am_pkup.wav", "models/items/ammo/shells/medium/tris.md2", 0, NULL, /* icon */ "a_shells", /* pickup */ "Shells", /* width */ 3, 10, NULL, 0, //IT_AMMO, NULL, AMMO_SHELLS, /* precache */ "", NO_NUM } , /*QUAKED ammo_bullets (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_bullets", Pickup_Ammo, NULL, Drop_Ammo, NULL, "misc/am_pkup.wav", "models/items/ammo/bullets/medium/tris.md2", 0, NULL, /* icon */ "a_bullets", /* pickup */ "Bullets", /* width */ 3, 50, NULL, 0, //IT_AMMO, NULL, AMMO_BULLETS, /* precache */ "", NO_NUM } , /*QUAKED ammo_cells (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_cells", Pickup_Ammo, NULL, Drop_Ammo, NULL, "misc/am_pkup.wav", "models/items/ammo/cells/medium/tris.md2", 0, NULL, /* icon */ "a_cells", /* pickup */ "Cells", /* width */ 3, 50, NULL, 0, //IT_AMMO, NULL, AMMO_CELLS, /* precache */ "", NO_NUM } , /*QUAKED ammo_rockets (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_rockets", Pickup_Ammo, NULL, Drop_Ammo, NULL, "misc/am_pkup.wav", "models/items/ammo/rockets/medium/tris.md2", 0, NULL, /* icon */ "a_rockets", /* pickup */ "Rockets", /* width */ 3, 5, NULL, 0, //IT_AMMO, NULL, AMMO_ROCKETS, /* precache */ "", NO_NUM } , /*QUAKED ammo_slugs (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "ammo_slugs", Pickup_Ammo, NULL, Drop_Ammo, NULL, "misc/am_pkup.wav", "models/items/ammo/slugs/medium/tris.md2", 0, NULL, /* icon */ "a_slugs", /* pickup */ "Slugs", /* width */ 3, 10, NULL, 0, //IT_AMMO, NULL, AMMO_SLUGS, /* precache */ "", NO_NUM } , // zucc new ammo { "ammo_clip", Pickup_Ammo, NULL, Drop_Ammo, NULL, //"misc/click.wav", NULL, "models/items/ammo/clip/tris.md2", 0, NULL, /* icon */ "a_clip", /* pickup */ "Pistol Clip", /* width */ 3, 1, NULL, IT_AMMO, NULL, AMMO_BULLETS, /* precache */ "", MK23_ANUM } , { "ammo_mag", Pickup_Ammo, NULL, Drop_Ammo, NULL, //"misc/click.wav", NULL, "models/items/ammo/mag/tris.md2", 0, NULL, /* icon */ "a_mag", /* pickup */ "Machinegun Magazine", /* width */ 3, 1, NULL, IT_AMMO, NULL, AMMO_ROCKETS, /* precache */ "", MP5_ANUM } , { "ammo_m4", Pickup_Ammo, NULL, Drop_Ammo, NULL, //"misc/click.wav", NULL, "models/items/ammo/m4/tris.md2", 0, NULL, /* icon */ "a_m4", /* pickup */ "M4 Clip", /* width */ 3, 1, NULL, IT_AMMO, NULL, AMMO_CELLS, /* precache */ "", M4_ANUM } , { "ammo_m3", Pickup_Ammo, NULL, Drop_Ammo, NULL, //"misc/click.wav", NULL, "models/items/ammo/shells/medium/tris.md2", 0, NULL, /* icon */ "a_shells", /* pickup */ "12 Gauge Shells", /* width */ 3, 7, NULL, IT_AMMO, NULL, AMMO_SHELLS, /* precache */ "", SHELL_ANUM } , { "ammo_sniper", Pickup_Ammo, NULL, Drop_Ammo, NULL, //"misc/click.wav", NULL, "models/items/ammo/sniper/tris.md2", 0, NULL, /* icon */ "a_bullets", /* pickup */ "AP Sniper Ammo", /* width */ 3, 10, NULL, IT_AMMO, NULL, AMMO_SLUGS, /* precache */ "", SNIPER_ANUM } , // // POWERUP ITEMS // // zucc the main items { "item_quiet", Pickup_Special, NULL, Drop_Special, NULL, "misc/screw.wav", "models/items/quiet/tris.md2", 0, NULL, /* icon */ "p_silencer", /* pickup */ "Silencer", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", SIL_NUM } , { "item_slippers", Pickup_Special, NULL, Drop_Special, NULL, "misc/veston.wav", // sound "models/items/slippers/slippers.md2", 0, NULL, /* icon */ "slippers", /* pickup */ "Stealth Slippers", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", SLIP_NUM } , { "item_band", Pickup_Special, NULL, Drop_Special, NULL, "misc/veston.wav", // sound "models/items/band/tris.md2", 0, NULL, /* icon */ "p_bandolier", /* pickup */ "Bandolier", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", BAND_NUM } , { "item_vest", Pickup_Special, NULL, Drop_Special, NULL, "misc/veston.wav", // sound "models/items/armor/jacket/tris.md2", 0, NULL, /* icon */ "i_jacketarmor", /* pickup */ "Kevlar Vest", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", KEV_NUM } , { "item_lasersight", Pickup_Special, NULL, //SP_LaserSight, Drop_Special, NULL, "misc/lasersight.wav", // sound "models/items/laser/tris.md2", 0, NULL, /* icon */ "p_laser", /* pickup */ "Lasersight", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", LASER_NUM } , /*QUAKED item_quad (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_quad", Pickup_Powerup, Use_Quad, Drop_General, NULL, "items/pkup.wav", "models/items/quaddama/tris.md2", EF_ROTATE, NULL, /* icon */ "p_quad", /* pickup */ "Quad Damage", /* width */ 2, 60, NULL, IT_POWERUP, NULL, 0, /* precache */ "items/damage.wav items/damage2.wav items/damage3.wav", NO_NUM } , /*QUAKED item_invulnerability (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_invulnerability", Pickup_Powerup, Use_Invulnerability, Drop_General, NULL, "items/pkup.wav", "models/items/invulner/tris.md2", EF_ROTATE, NULL, /* icon */ "p_invulnerability", /* pickup */ "Invulnerability", /* width */ 2, 300, NULL, IT_POWERUP, NULL, 0, /* precache */ "items/protect.wav items/protect2.wav items/protect4.wav", NO_NUM } , /*QUAKED item_silencer (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_silencer", Pickup_Powerup, Use_Silencer, Drop_General, NULL, "items/pkup.wav", "models/items/silencer/tris.md2", EF_ROTATE, NULL, /* icon */ "p_silencer", /* pickup */ "Silencer", /* width */ 2, 60, NULL, 0, //IT_POWERUP, NULL, 0, /* precache */ "", NO_NUM } , { "item_helmet", Pickup_Special, NULL, Drop_Special, NULL, "misc/veston.wav", // sound "models/items/breather/tris.md2", 0, NULL, /* icon */ "p_rebreather", /* pickup */ "Kevlar Helmet", /* width */ 2, 60, NULL, IT_ITEM, NULL, 0, /* precache */ "", HELM_NUM } , /*QUAKED item_breather (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_breather", Pickup_Powerup, Use_Breather, Drop_General, NULL, "items/pkup.wav", "models/items/breather/tris.md2", EF_ROTATE, NULL, /* icon */ "p_rebreather", /* pickup */ "Rebreather", /* width */ 2, 60, NULL, 0, //IT_STAY_COOP | IT_POWERUP, NULL, 0, /* precache */ "items/airout.wav", NO_NUM } , /*QUAKED item_enviro (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_enviro", Pickup_Powerup, Use_Envirosuit, Drop_General, NULL, "items/pkup.wav", "models/items/enviro/tris.md2", EF_ROTATE, NULL, /* icon */ "p_envirosuit", /* pickup */ "Environment Suit", /* width */ 2, 60, NULL, 0, //IT_STAY_COOP|IT_POWERUP, NULL, 0, /* precache */ "items/airout.wav", NO_NUM } , /*QUAKED item_ancient_head (.3 .3 1) (-16 -16 -16) (16 16 16) Special item that gives +2 to maximum health */ { "item_ancient_head", Pickup_AncientHead, NULL, NULL, NULL, "items/pkup.wav", "models/items/c_head/tris.md2", EF_ROTATE, NULL, /* icon */ "i_fixme", /* pickup */ "Ancient Head", /* width */ 2, 60, NULL, 0, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED item_adrenaline (.3 .3 1) (-16 -16 -16) (16 16 16) gives +1 to maximum health */ { "item_adrenaline", Pickup_Adrenaline, NULL, NULL, NULL, "items/pkup.wav", "models/items/adrenal/tris.md2", EF_ROTATE, NULL, /* icon */ "p_adrenaline", /* pickup */ "Adrenaline", /* width */ 2, 60, NULL, 0, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED item_bandolier (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_bandolier", Pickup_Bandolier, NULL, NULL, NULL, "items/pkup.wav", "models/items/band/tris.md2", EF_ROTATE, NULL, /* icon */ "p_bandolier", /* pickup */ "NogBandolier", /* width */ 2, 60, NULL, 0, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED item_pack (.3 .3 1) (-16 -16 -16) (16 16 16) */ { "item_pack", Pickup_ItemPack, //Pickup_Pack, NULL, NULL, NULL, "items/pkup.wav", "models/items/pack/tris.md2", EF_ROTATE, NULL, /* icon */ "i_pack", /* pickup */ "Ammo Pack", /* width */ 2, 180, NULL, IT_ITEM, //0, NULL, 0, /* precache */ "", NO_NUM } , // // KEYS // /*QUAKED key_data_cd (0 .5 .8) (-16 -16 -16) (16 16 16) key for computer centers */ { "key_data_cd", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/data_cd/tris.md2", EF_ROTATE, NULL, "k_datacd", "Data CD", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_power_cube (0 .5 .8) (-16 -16 -16) (16 16 16) TRIGGER_SPAWN NO_TOUCH warehouse circuits */ { "key_power_cube", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/power/tris.md2", EF_ROTATE, NULL, "k_powercube", "Power Cube", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_pyramid (0 .5 .8) (-16 -16 -16) (16 16 16) key for the entrance of jail3 */ { "key_pyramid", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/pyramid/tris.md2", EF_ROTATE, NULL, "k_pyramid", "Pyramid Key", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_data_spinner (0 .5 .8) (-16 -16 -16) (16 16 16) key for the city computer */ { "key_data_spinner", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/spinner/tris.md2", EF_ROTATE, NULL, "k_dataspin", "Data Spinner", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_pass (0 .5 .8) (-16 -16 -16) (16 16 16) security pass for the security level */ { "key_pass", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/pass/tris.md2", EF_ROTATE, NULL, "k_security", "Security Pass", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_blue_key (0 .5 .8) (-16 -16 -16) (16 16 16) normal door key - blue */ { "key_blue_key", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/key/tris.md2", EF_ROTATE, NULL, "k_bluekey", "Blue Key", 2, 0, NULL, 0, // IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_red_key (0 .5 .8) (-16 -16 -16) (16 16 16) normal door key - red */ { "key_red_key", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/red_key/tris.md2", EF_ROTATE, NULL, "k_redkey", "Red Key", 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_commander_head (0 .5 .8) (-16 -16 -16) (16 16 16) tank commander's head */ { "key_commander_head", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/monsters/commandr/head/tris.md2", EF_GIB, NULL, /* icon */ "k_comhead", /* pickup */ "Commander's Head", /* width */ 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED key_airstrike_target (0 .5 .8) (-16 -16 -16) (16 16 16) tank commander's head */ { "key_airstrike_target", Pickup_Key, NULL, Drop_General, NULL, "items/pkup.wav", "models/items/keys/target/tris.md2", EF_ROTATE, NULL, /* icon */ "i_airstrike", /* pickup */ "Airstrike Marker", /* width */ 2, 0, NULL, 0, //IT_STAY_COOP | IT_KEY, NULL, 0, /* precache */ "", NO_NUM } , { NULL, Pickup_Health, NULL, NULL, NULL, "items/pkup.wav", NULL, 0, NULL, /* icon */ "i_health", /* pickup */ "Health", /* width */ 3, 0, NULL, 0, NULL, 0, /* precache */ "", NO_NUM } , /*QUAKED item_flag_team1 (1 0.2 0) (-16 -16 -24) (16 16 32) */ { "item_flag_team1", CTFPickup_Flag, NULL, CTFDrop_Flag, //Should this be null if we don't want players to drop it manually? NULL, "tng/flagtk.wav", "models/flags/flag1.md2", EF_FLAG1, NULL, /* icon */ "i_ctf1", /* pickup */ "Red Flag", /* width */ 2, 0, NULL, IT_FLAG, NULL, 0, /* precache */ "tng/flagcap.wav tng/flagret.wav", FLAG_T1_NUM } , /*QUAKED item_flag_team2 (1 0.2 0) (-16 -16 -24) (16 16 32) */ { "item_flag_team2", CTFPickup_Flag, NULL, CTFDrop_Flag, //Should this be null if we don't want players to drop it manually? NULL, "tng/flagtk.wav", "models/flags/flag2.md2", EF_FLAG2, NULL, /* icon */ "i_ctf2", /* pickup */ "Blue Flag", /* width */ 2, 0, NULL, IT_FLAG, NULL, 0, /* precache */ "tng/flagcap.wav tng/flagret.wav", FLAG_T2_NUM } , // end of list marker {NULL} }; /*QUAKED item_health (.3 .3 1) (-16 -16 -16) (16 16 16) */ void SP_item_health (edict_t * self) { if (1) //deathmatch->value && ((int)dmflags->value & DF_NO_HEALTH) ) { G_FreeEdict (self); return; } self->model = "models/items/healing/medium/tris.md2"; self->count = 10; SpawnItem (self, FindItem ("Health")); gi.soundindex ("items/n_health.wav"); } /*QUAKED item_health_small (.3 .3 1) (-16 -16 -16) (16 16 16) */ void SP_item_health_small (edict_t * self) { if (1) //deathmatch->value && ((int)dmflags->value & DF_NO_HEALTH) ) { G_FreeEdict (self); return; } self->model = "models/items/healing/stimpack/tris.md2"; self->count = 2; SpawnItem (self, FindItem ("Health")); self->style = HEALTH_IGNORE_MAX; gi.soundindex ("items/s_health.wav"); } /*QUAKED item_health_large (.3 .3 1) (-16 -16 -16) (16 16 16) */ void SP_item_health_large (edict_t * self) { if (1) //deathmatch->value && ((int)dmflags->value & DF_NO_HEALTH) ) { G_FreeEdict (self); return; } self->model = "models/items/healing/large/tris.md2"; self->count = 25; SpawnItem (self, FindItem ("Health")); gi.soundindex ("items/l_health.wav"); } /*QUAKED item_health_mega (.3 .3 1) (-16 -16 -16) (16 16 16) */ void SP_item_health_mega (edict_t * self) { if (1) //deathmatch->value && ((int)dmflags->value & DF_NO_HEALTH) ) { G_FreeEdict (self); return; } self->model = "models/items/mega_h/tris.md2"; self->count = 100; SpawnItem (self, FindItem ("Health")); gi.soundindex ("items/m_health.wav"); self->style = HEALTH_IGNORE_MAX | HEALTH_TIMED; } itemList_t items[ILIST_COUNT]; void InitItems (void) { int i; game.num_items = sizeof (itemlist) / sizeof (itemlist[0]) - 1; for(i=0; i<ILIST_COUNT; i++) { items[i].index = ITEM_INDEX(FindItemByNum(i)); items[i].flag = 0; } items[MK23_NUM].flag = WPF_MK23; items[MP5_NUM].flag = WPF_MP5; items[M4_NUM].flag = WPF_M4; items[M3_NUM].flag = WPF_M3; items[HC_NUM].flag = WPF_HC; items[SNIPER_NUM].flag = WPF_SNIPER; items[DUAL_NUM].flag = WPF_DUAL; items[KNIFE_NUM].flag = WPF_KNIFE; items[GRENADE_NUM].flag = WPF_GRENADE; items[SIL_NUM].flag = ITF_SIL; items[SLIP_NUM].flag = ITF_SLIP; items[BAND_NUM].flag = ITF_BAND; items[KEV_NUM].flag = ITF_KEV; items[LASER_NUM].flag = ITF_LASER; items[HELM_NUM].flag = ITF_HELM; } /* =============== SetItemNames Called by worldspawn =============== */ void SetItemNames (void) { int i; gitem_t *it; for (i = 0; i < game.num_items; i++) { it = &itemlist[i]; gi.configstring (CS_ITEMS + i, it->pickup_name); } jacket_armor_index = ITEM_INDEX (FindItem ("Jacket Armor")); combat_armor_index = ITEM_INDEX (FindItem ("Combat Armor")); body_armor_index = ITEM_INDEX (FindItem ("Body Armor")); power_screen_index = ITEM_INDEX (FindItem ("Power Screen")); power_shield_index = ITEM_INDEX (FindItem ("Power Shield")); }
576
./aq2-tng/source/g_trigger.c
//----------------------------------------------------------------------------- // g_trigger.c // // $Id: g_trigger.c,v 1.2 2001/09/28 13:48:34 ra Exp $ // //----------------------------------------------------------------------------- // $Log: g_trigger.c,v $ // Revision 1.2 2001/09/28 13:48:34 ra // I ran indent over the sources. All .c and .h files reindented. // // Revision 1.1.1.1 2001/05/06 17:30:53 igor_rock // This is the PG Bund Edition V1.25 with all stuff laying around here... // //----------------------------------------------------------------------------- #include "g_local.h" void InitTrigger (edict_t * self) { if (!VectorCompare (self->s.angles, vec3_origin)) G_SetMovedir (self->s.angles, self->movedir); self->solid = SOLID_TRIGGER; self->movetype = MOVETYPE_NONE; gi.setmodel (self, self->model); self->svflags = SVF_NOCLIENT; } // the wait time has passed, so set back up for another activation void multi_wait (edict_t * ent) { ent->nextthink = 0; } // the trigger was just activated // ent->activator should be set to the activator so it can be held through a delay // so wait for the delay time before firing void multi_trigger (edict_t * ent) { if (ent->nextthink) return; // already been triggered G_UseTargets (ent, ent->activator); if (ent->wait > 0) { ent->think = multi_wait; ent->nextthink = level.time + ent->wait; } else { // we can't just remove (self) here, because this is a touch function // called while looping through area links... ent->touch = NULL; ent->nextthink = level.time + FRAMETIME; ent->think = G_FreeEdict; } } void Use_Multi (edict_t * ent, edict_t * other, edict_t * activator) { ent->activator = activator; multi_trigger (ent); } void Touch_Multi (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other->client) { if (self->spawnflags & 2) return; } else if (other->svflags & SVF_MONSTER) { if (!(self->spawnflags & 1)) return; } else return; if (!VectorCompare (self->movedir, vec3_origin)) { vec3_t forward; AngleVectors (other->s.angles, forward, NULL, NULL); if (DotProduct (forward, self->movedir) < 0) return; } self->activator = other; multi_trigger (self); } /*QUAKED trigger_multiple (.5 .5 .5) ? MONSTER NOT_PLAYER TRIGGERED Variable sized repeatable trigger. Must be targeted at one or more entities. If "delay" is set, the trigger waits some time after activating before firing. "wait" : Seconds between triggerings. (.2 default) sounds 1) secret 2) beep beep 3) large switch 4) set "message" to text string */ void trigger_enable (edict_t * self, edict_t * other, edict_t * activator) { self->solid = SOLID_TRIGGER; self->use = Use_Multi; gi.linkentity (self); } void SP_trigger_multiple (edict_t * ent) { if (ent->sounds == 1) ent->noise_index = gi.soundindex ("misc/secret.wav"); else if (ent->sounds == 2) ent->noise_index = gi.soundindex ("misc/talk.wav"); else if (ent->sounds == 3) ent->noise_index = gi.soundindex ("misc/trigger1.wav"); if (!ent->wait) ent->wait = 0.2f; ent->touch = Touch_Multi; ent->movetype = MOVETYPE_NONE; ent->svflags |= SVF_NOCLIENT; if (ent->spawnflags & 4) { ent->solid = SOLID_NOT; ent->use = trigger_enable; } else { ent->solid = SOLID_TRIGGER; ent->use = Use_Multi; } if (!VectorCompare (ent->s.angles, vec3_origin)) G_SetMovedir (ent->s.angles, ent->movedir); gi.setmodel (ent, ent->model); gi.linkentity (ent); } /*QUAKED trigger_once (.5 .5 .5) ? x x TRIGGERED Triggers once, then removes itself. You must set the key "target" to the name of another object in the level that has a matching "targetname". If TRIGGERED, this trigger must be triggered before it is live. sounds 1) secret 2) beep beep 3) large switch 4) "message" string to be displayed when triggered */ void SP_trigger_once (edict_t * ent) { // make old maps work because I messed up on flag assignments here // triggered was on bit 1 when it should have been on bit 4 if (ent->spawnflags & 1) { vec3_t v; VectorMA (ent->mins, 0.5, ent->size, v); ent->spawnflags &= ~1; ent->spawnflags |= 4; gi.dprintf ("fixed TRIGGERED flag on %s at %s\n", ent->classname, vtos (v)); } ent->wait = -1; SP_trigger_multiple (ent); } /*QUAKED trigger_relay (.5 .5 .5) (-8 -8 -8) (8 8 8) This fixed size trigger cannot be touched, it can only be fired by other events. */ void trigger_relay_use (edict_t * self, edict_t * other, edict_t * activator) { G_UseTargets (self, activator); } void SP_trigger_relay (edict_t * self) { self->use = trigger_relay_use; } /* ============================================================================== trigger_key ============================================================================== */ /*QUAKED trigger_key (.5 .5 .5) (-8 -8 -8) (8 8 8) A relay trigger that only fires it's targets if player has the proper key. Use "item" to specify the required key, for example "key_data_cd" */ void trigger_key_use (edict_t * self, edict_t * other, edict_t * activator) { int index; if (!self->item) return; if (!activator->client) return; index = ITEM_INDEX (self->item); if (!activator->client->pers.inventory[index]) { if (level.time < self->touch_debounce_time) return; self->touch_debounce_time = level.time + 5.0; gi.centerprintf (activator, "You need the %s", self->item->pickup_name); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keytry.wav"), 1, ATTN_NORM, 0); return; } gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/keyuse.wav"), 1, ATTN_NORM, 0); if (coop->value) { int player; edict_t *ent; if (strcmp (self->item->classname, "key_power_cube") == 0) { int cube; for (cube = 0; cube < 8; cube++) if (activator->client->pers.power_cubes & (1 << cube)) break; for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; if (ent->client->pers.power_cubes & (1 << cube)) { ent->client->pers.inventory[index]--; ent->client->pers.power_cubes &= ~(1 << cube); } } } else { for (player = 1; player <= game.maxclients; player++) { ent = &g_edicts[player]; if (!ent->inuse) continue; if (!ent->client) continue; ent->client->pers.inventory[index] = 0; } } } else { activator->client->pers.inventory[index]--; } G_UseTargets (self, activator); self->use = NULL; } void SP_trigger_key (edict_t * self) { if (!st.item) { gi.dprintf ("no key item for trigger_key at %s\n", vtos (self->s.origin)); return; } self->item = FindItemByClassname (st.item); if (!self->item) { gi.dprintf ("item %s not found for trigger_key at %s\n", st.item, vtos (self->s.origin)); return; } if (!self->target) { gi.dprintf ("%s at %s has no target\n", self->classname, vtos (self->s.origin)); return; } gi.soundindex ("misc/keytry.wav"); gi.soundindex ("misc/keyuse.wav"); self->use = trigger_key_use; } /* ============================================================================== trigger_counter ============================================================================== */ /*QUAKED trigger_counter (.5 .5 .5) ? nomessage Acts as an intermediary for an action that takes multiple inputs. If nomessage is not set, t will print "1 more.. " etc when triggered and "sequence complete" when finished. After the counter has been triggered "count" times (default 2), it will fire all of it's targets and remove itself. */ void trigger_counter_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->count == 0) return; self->count--; if (self->count) { if (!(self->spawnflags & 1)) { gi.centerprintf (activator, "%i more to go...", self->count); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } return; } if (!(self->spawnflags & 1)) { gi.centerprintf (activator, "Sequence completed!"); gi.sound (activator, CHAN_AUTO, gi.soundindex ("misc/talk1.wav"), 1, ATTN_NORM, 0); } self->activator = activator; multi_trigger (self); } void SP_trigger_counter (edict_t * self) { self->wait = -1; if (!self->count) self->count = 2; self->use = trigger_counter_use; } /* ============================================================================== trigger_always ============================================================================== */ /*QUAKED trigger_always (.5 .5 .5) (-8 -8 -8) (8 8 8) This trigger will always fire. It is activated by the world. */ void SP_trigger_always (edict_t * ent) { // we must have some delay to make sure our use targets are present if (ent->delay < 0.2f) ent->delay = 0.2f; G_UseTargets (ent, ent); } /* ============================================================================== trigger_push ============================================================================== */ #define PUSH_ONCE 1 static int windsound; void trigger_push_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (strcmp (other->classname, "grenade") == 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); } else if (other->health > 0) { VectorScale (self->movedir, self->speed * 10, other->velocity); if (other->client) { // don't take falling damage immediately from this VectorCopy (other->velocity, other->client->oldvelocity); if (other->fly_sound_debounce_time < level.time) { other->fly_sound_debounce_time = level.time + 1.5; gi.sound (other, CHAN_AUTO, windsound, 1, ATTN_NORM, 0); } } } if (self->spawnflags & PUSH_ONCE) G_FreeEdict (self); } /*QUAKED trigger_push (.5 .5 .5) ? PUSH_ONCE Pushes the player "speed" defaults to 1000 */ void SP_trigger_push (edict_t * self) { InitTrigger (self); windsound = gi.soundindex ("misc/windfly.wav"); self->touch = trigger_push_touch; if (!self->speed) self->speed = 1000; gi.linkentity (self); } /* ============================================================================== trigger_hurt ============================================================================== */ /*QUAKED trigger_hurt (.5 .5 .5) ? START_OFF TOGGLE SILENT NO_PROTECTION SLOW Any entity that touches this will be hurt. It does dmg points of damage each server frame SILENT supresses playing the sound SLOW changes the damage rate to once per second NO_PROTECTION *nothing* stops the damage "dmg" default 5 (whole numbers only) */ void hurt_use (edict_t * self, edict_t * other, edict_t * activator) { if (self->solid == SOLID_NOT) self->solid = SOLID_TRIGGER; else self->solid = SOLID_NOT; gi.linkentity (self); if (!(self->spawnflags & 2)) self->use = NULL; } void hurt_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { int dflags; if (!other->takedamage) return; if (self->timestamp > level.time) return; if (self->spawnflags & 16) self->timestamp = level.time + 1; else self->timestamp = level.time + FRAMETIME; if (!(self->spawnflags & 4)) { if ((level.framenum % 10) == 0) gi.sound (other, CHAN_AUTO, self->noise_index, 1, ATTN_NORM, 0); } if (self->spawnflags & 8) dflags = DAMAGE_NO_PROTECTION; else dflags = 0; T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, self->dmg, dflags, MOD_TRIGGER_HURT); } void SP_trigger_hurt (edict_t * self) { InitTrigger (self); self->noise_index = gi.soundindex ("world/electro.wav"); self->touch = hurt_touch; if (!self->dmg) self->dmg = 5; if (self->spawnflags & 1) self->solid = SOLID_NOT; else self->solid = SOLID_TRIGGER; if (self->spawnflags & 2) self->use = hurt_use; gi.linkentity (self); } /* ============================================================================== trigger_gravity ============================================================================== */ /*QUAKED trigger_gravity (.5 .5 .5) ? Changes the touching entites gravity to the value of "gravity". 1.0 is standard gravity for the level. */ void trigger_gravity_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { other->gravity = self->gravity; } void SP_trigger_gravity (edict_t * self) { if (st.gravity == 0) { gi.dprintf ("trigger_gravity without gravity set at %s\n", vtos (self->s.origin)); G_FreeEdict (self); return; } InitTrigger (self); self->gravity = atoi (st.gravity); self->touch = trigger_gravity_touch; } /* ============================================================================== trigger_monsterjump ============================================================================== */ /*QUAKED trigger_monsterjump (.5 .5 .5) ? Walking monsters that touch this will jump in the direction of the trigger's angle "speed" default to 200, the speed thrown forward "height" default to 200, the speed thrown upwards */ void trigger_monsterjump_touch (edict_t * self, edict_t * other, cplane_t * plane, csurface_t * surf) { if (other->flags & (FL_FLY | FL_SWIM)) return; if (other->svflags & SVF_DEADMONSTER) return; if (!(other->svflags & SVF_MONSTER)) return; // set XY even if not on ground, so the jump will clear lips other->velocity[0] = self->movedir[0] * self->speed; other->velocity[1] = self->movedir[1] * self->speed; if (!other->groundentity) return; other->groundentity = NULL; other->velocity[2] = self->movedir[2]; } void SP_trigger_monsterjump (edict_t * self) { if (!self->speed) self->speed = 200; if (!st.height) st.height = 200; if (self->s.angles[YAW] == 0) self->s.angles[YAW] = 360; InitTrigger (self); self->touch = trigger_monsterjump_touch; self->movedir[2] = st.height; }
577
./aq2-tng/source/addons/tngbot/tngbot.c
/*---------------------------------------------------------------------------- * TNG IRC Bot for AQ2 Servers * (c) 2001 by Stefan Giesen aka Igor[Rock] * All rights reserved * * $Id: tngbot.c,v 1.9 2003/06/15 21:43:29 igor Exp $ * *---------------------------------------------------------------------------- * Usage: tngbot <ircserver>[:port] <channelname> <nickname> * <ircserver> - Name or IP address of IRC server * [:port] - Port for the IRC server, default is 6667 * <channel> - Channel to join (without leading '#') * <nickname> - Bot Nickname * * Example: * tngbot irc.barrysworld.com:6666 clanwar-tv MyTVBot * * would connect the bot to the irc server at barrysworld at port 6666 * with the Nickname "MyTVBot" and would join "#clanwar-tv" after connecting * * Features: * - Bot will reconnect automatically after disconnect * - No changes (beside setting the "logfile" variable) in your server config * necessary, the bot will use the standard text logfile. * - Unknown commands, some errors and all rcon/password related console * output is filtered out. * * Bugs/Missing features: * - The Bot has to be started in the action dir and the logfilename used is * the standard one from Q2: "qconsole.log" * This will be changed to a command line option later * - If the Nick already exists on IRC, the Bot won't be able to connect * - The Bot has to be started _after_ the AQ2 server itself (because the * logfile has to be opened for writing by AQ2) * *---------------------------------------------------------------------------- * $Log: tngbot.c,v $ * Revision 1.9 2003/06/15 21:43:29 igor * added some code for characters <32 * * Revision 1.8 2001/12/08 15:53:05 igor_rock * corrected a wrong offset * * Revision 1.7 2001/12/08 15:46:39 igor_rock * added the private message command "cycle" so the bot disconencts and * restarts after a 15 sec pause. * * Revision 1.6 2001/12/03 15:01:06 igor_rock * added password for joining the cahnnel if protected * * Revision 1.5 2001/12/03 14:52:01 igor_rock * fixed some bugs, added some features / channel modes * * Revision 1.4 2001/11/30 19:27:33 igor_rock * - added password to get op from the bot (with "/msg botname op password") * - the bot sets the +m flag so other people can't talk in the channel (which * would maybe cause lag on the game server itself, since the bot runs on the * gameserver) * * Revision 1.3 2001/11/29 18:43:16 igor_rock * added new format 'V' ("nickname FIXED_TEXT variable_text") * * Revision 1.2 2001/11/29 18:30:48 igor_rock * corrected a smaller bug * * Revision 1.1 2001/11/29 17:58:31 igor_rock * TNG IRC Bot - First Version * *---------------------------------------------------------------------------- */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #include <sys/time.h> #include <fcntl.h> #define IRC_PORT 6667 #define BUFLEN 2048 #define GREY "14" #define BLUE "12" #define GREEN "3" #define RED "4" #define ORANGE "7" static int sock; static int file; static char *version="TNG IRC Bot by Stefan Giesen (c)2001"; char logfile[] = "qconsole.log"; char colorfile[] = "tngbot.col"; char ircserver[BUFLEN]; char channel[BUFLEN]; char nickname[BUFLEN]; char password[BUFLEN]; char *txtbuffer; char **filtertxt; int filteranz; int port; int get_colorfile ( ) { int ret = 0; size_t size; int i; char *cp; FILE *fp; fp = fopen(colorfile, "r"); if (fp) { fseek (fp, 0, SEEK_END); size = (size_t) ftell (fp); fseek (fp, 0, SEEK_SET); if ((txtbuffer = (char *) calloc(size, sizeof(char))) == NULL) { fprintf (stderr, "Out of memory in get_colofile!\n"); exit (1); } if (fread (txtbuffer, sizeof(char), size, fp) != size) { fprintf (stderr, "Read Error in '%s'\n", colorfile); exit (1); } fclose (fp); filteranz = 1; for (cp = txtbuffer; cp < (txtbuffer + (int) size); cp++) { if (*cp == '\n') { filteranz++; } } if ((filtertxt = (char **) calloc(filteranz, sizeof(char *))) == NULL) { fprintf (stderr, "Out of memory in get_colorfile!\n"); exit (1); } i = 0; printf ("Filter count: %d\n", filteranz); filtertxt[i++] = txtbuffer; for (cp = txtbuffer; (cp < (txtbuffer + (int) size)) && (i < filteranz); cp++) { if (*cp == '\n') { *cp = 0; filtertxt[i++] = cp + 1; } } #ifdef DEBUG for (i=0; i < filteranz; i++) { printf ("Filter %2.2d: '%s'\n", i, filtertxt[i]); } #endif ret = 1; } else { fprintf (stderr, "Colorizing file 'tngbot.col' not found, colors not used\n"); ret = 0; } return (ret); } void colorize (char *inbuf, char *outbuf) { int i; int from; int to; int found = 0; char *cp; int done = 0; bzero (outbuf, BUFLEN); if (! done) { for (i = 0; (i < strlen (inbuf)) && (inbuf[i] != ' '); i++) ; if (i && (i < strlen(inbuf))) { if (inbuf[i-1] == ':') { sprintf (outbuf, "%c%s%s%c%s\n", 0x03, GREEN, inbuf, 0x03, GREY); done = 1; } } } if (!done) { for (i = 0; i < filteranz; i++ ) { if ((cp = strstr (inbuf, &filtertxt[i][1])) != NULL) { found = (int) (cp - inbuf); switch (filtertxt[i][0]) { case 'K': /* Kill */ sprintf (outbuf, "%c%s", 0x03, BLUE); for (from = 0, to = strlen(outbuf); from < found; from++, to++) { outbuf[to] = inbuf[from]; } sprintf (&outbuf[to], "%c%s%s%c%s", 0x03, GREY, &filtertxt[i][1], 0x03, BLUE); from += strlen (&filtertxt[i][1]); to = strlen(outbuf); if (inbuf[from] == ' ') { outbuf[to++] = ' '; outbuf[to] = 0; from++; } while ((inbuf[from] != ' ') && inbuf[from]){ outbuf[to++] = inbuf[from++]; } sprintf (&outbuf[to], "%c%s%s", 0x03, GREY, &inbuf[from]); done = 1; break; case 'D': /* Own Death */ sprintf (outbuf, "%c%s", 0x03, BLUE); for (from = 0, to = strlen(outbuf); from < found; from++, to++) { outbuf[to] = inbuf[from]; } sprintf (&outbuf[to], "%c%s%s\n", 0x03, GREY, &filtertxt[i][1]); done = 1; break; case 'V': /* Vote related */ sprintf (outbuf, "%c%s", 0x03, BLUE); for (from = 0, to = strlen(outbuf); from < found; from++, to++) { outbuf[to] = inbuf[from]; } sprintf (&outbuf[to], "%c%s%s\n", 0x03, GREY, &inbuf[from]); done = 1; break; case 'G': sprintf (outbuf, "%c%s%s%c%s\n", 0x03, RED, inbuf, 0x03, GREY); done = 1; break; case 'S': sprintf (outbuf, "%c%s%s%c%s\n", 0x03, ORANGE, inbuf, 0x03, GREY); done = 1; break; case '-': done = 1; break; default: strncpy (outbuf, inbuf, strlen(inbuf)); done = 1; break; } i = filteranz; } } } if (! done) { strncpy (outbuf, inbuf, strlen(inbuf)); } } int do_irc_reg( ) { char inbuf[BUFLEN]; char outbuf[BUFLEN]; char *newbuf; sprintf (outbuf, "NICK %s\n\r", nickname); write (sock, outbuf, strlen(outbuf)); fprintf(stderr, "Sent nick (%s)\n", nickname); while(1) { bzero(inbuf, sizeof(inbuf)); if ((read(sock, inbuf, sizeof(inbuf))) == 0) { close (sock); fprintf(stderr, "Dropped.\n"); sleep (15); return (0); } newbuf = inbuf; while(((strncmp(newbuf, "PING :", 6)) != 0) && (strlen(newbuf) > 0)) { newbuf++; } if ((strncmp(newbuf, "PING :", 6)) == 0){ printf("Ping - Pong\n"); sprintf(outbuf, "pong %s\n\r", &newbuf[6]); write(sock, outbuf, strlen(outbuf)); sprintf(outbuf, "user tngbot 12 * :%s\n\r", version); printf("User sent: %s\n", outbuf); write(sock, outbuf, strlen(outbuf)); break; } } if (password[0]) { sprintf(outbuf, "join #%s %s\n\r", channel, password); printf ("Joining #%s %s\n", channel, password); } else { sprintf(outbuf, "join #%s\n\r", channel); printf ("Joining #%s\n", channel); } write(sock, outbuf, strlen(outbuf)); if (password[0]) { sprintf (outbuf, "mode #%s +mntk %s\n", channel, password); } else { sprintf (outbuf, "mode #%s +mnt\n", channel); } write (sock, outbuf, strlen(outbuf)); return (1); } int parse_input (char *inbuf) { int ret = 0; int pos1; int pos2; char temp[BUFLEN]; char von[BUFLEN]; char outbuf[BUFLEN]; if ((inbuf[0] == ':') && (strstr(inbuf, "PRIVMSG") != NULL)) { for (pos1 = 1, pos2 = 0; (inbuf[pos1] != ' ') && (pos1 < strlen(inbuf)); pos1++, pos2++) { von[pos2] = inbuf[pos1]; } von[pos2] = 0; if (pos1 < strlen(inbuf)) { if (strstr (von, "!") != NULL) { /* user message */ for (pos2 = 0; (pos2 < strlen(von)) && (von[pos2] != '!'); pos2++) ; von[pos2] = 0; pos1 += strlen (" PRIVMSG "); if (strncmp (&inbuf[pos1], nickname, strlen(nickname)) == 0) { /* private message */ pos1 += strlen(nickname); pos1 += strlen (" :"); if (password[0]) { if (strncmp (&inbuf[pos1], "op ", 3) == 0) { pos1 += 3; if (strncmp (&inbuf[pos1], password, strlen (password)) == 0) { sprintf (outbuf, "MODE #%s +o %s\n", channel, von); write (sock, outbuf, strlen(outbuf)); } } else if (strncmp (&inbuf[pos1], "cycle ", 6) == 0) { pos1 += 6; if (strncmp (&inbuf[pos1], password, strlen (password)) == 0) { ret = 1; } } } } else { char *cp; for (cp = inbuf; *cp; cp++) { if (*cp < 32) { printf ("\\%3.3d", (int) *cp); } else { printf ("%c", *cp); } } printf ("\n"); /* public message, we ignore it */ } } else { /* server message */ /* we ignore these in the moment */ } } } else { sprintf (temp, " KICK #%s %s :", channel, nickname); if ((inbuf[0] == ':') && (strstr(inbuf, temp) != NULL)) { if (password[0]) { sprintf(outbuf, "join #%s %s\n\r", channel, password); printf ("Joining #%s %s\n", channel, password); } else { sprintf(outbuf, "join #%s\n\r", channel); printf ("Joining #%s\n", channel); } write(sock, outbuf, strlen(outbuf)); } else { printf ("%s\n", inbuf); } } return (ret); } void irc_loop ( ) { int i; int e; int anz = 0; int anz_net = 0; char inbuf[BUFLEN]; char colbuf[BUFLEN]; char outbuf[BUFLEN]; char filebuf[BUFLEN]; while((anz_net = read(sock, inbuf, sizeof(inbuf))) != 0) { anz = read(file, filebuf, sizeof(filebuf)); if (anz > 0) { for (i = 0, e = 0; e < anz; e++) { if (filebuf[e] == '\n') { filebuf[e] = 0; if ((filebuf[i] != '(')) { if (strncmp (&filebuf[i], "Unknown", 7) == 0) { } else if (strncmp (&filebuf[i], "\"password\"", 10) == 0) { } else if (strncmp (&filebuf[i], "\"rcon_password\"", 15) == 0) { } else if (strncmp (&filebuf[i], "rcon", 4) == 0) { } else if (strncmp (&filebuf[i], "[DEAD]", 6) == 0) { } else if (strncmp (&filebuf[i], "Sending ", 8) == 0) { } else if (strncmp (&filebuf[i], "droptofloor:", 12) == 0) { } else if (strncmp (&filebuf[i], "Error opening file", 18) == 0) { } else if (strstr (&filebuf[i], "doesn't have a spawn function") != NULL) { } else if (strstr (&filebuf[i], "with no distance set") != NULL) { } else { if (strlen(&filebuf[i]) > 0) { if (filteranz > 0) { bzero (colbuf, sizeof(colbuf)); colorize (&filebuf[i], colbuf); sprintf (outbuf, "PRIVMSG #%s :%s\n", channel, colbuf); }else { sprintf (outbuf, "PRIVMSG #%s :%s\n", channel, &filebuf[i]); } write (sock, outbuf, strlen(outbuf)); } } } i = e + 1; } } } if (anz_net == -1) { if (errno != EAGAIN) { printf ("System error occured (errno = %d)\n", errno); break; } } if (anz_net > 0) { if ((strncmp(inbuf, "PING :", 6)) == 0) { /* answer with a pong */ printf ("Ping - Pong\n"); sprintf(outbuf, "pong %s\n\r", &inbuf[6]); write(sock, outbuf, strlen(outbuf)); } else { if (parse_input (inbuf)) { break; } } bzero(inbuf, sizeof(inbuf)); bzero(outbuf, sizeof(outbuf)); bzero(filebuf, sizeof(filebuf)); } } close(sock); printf("Connection dropped.\n"); sleep(15); /* So we don't get throttled */ } void main(int argc, char *argv[]) { int flags; char *portstr; struct sockaddr_in hostaddress; struct in_addr ipnum; struct hostent *hostdata; fprintf (stderr, "AQ2 TNG IRC Bot v0.1 by Igor[Rock]\n"); fprintf (stderr, "EMail: [email protected]\n"); if (argc < 4) { fprintf (stderr, "Usage: tngbot <ircserver>[:port] <channelname> <nickname> [password]\n"); fprintf (stderr, "<ircserver> - Name or IP address of IRC server\n"); fprintf (stderr, "[:port] - Port for the IRC server\n"); fprintf (stderr, "<channel> - Channel to join (without leading '#')\n"); fprintf (stderr, "<nickname> - Bot Nickname\n"); fprintf (stderr, "[password] - OP-password for IRC\n\n"); exit (1); } get_colorfile(); strncpy (ircserver, argv[1], BUFLEN); strncpy (channel, argv[2], BUFLEN); strncpy (nickname, argv[3], BUFLEN); if (argc == 5) { strncpy (password, argv[4], BUFLEN); } else { password[0] = 0; } port = htons (IRC_PORT); portstr = strchr(argv[1], ':'); if (portstr) { *portstr++ = '\0'; port = htons(atoi(portstr)); } if (! inet_aton(argv[1], &ipnum)) { /* Maybe it's a FQDN */ hostdata = gethostbyname (ircserver); if (hostdata==NULL) { fprintf (stderr, "Invalid hostname or wrong address!\n"); fprintf (stderr, "Please use an existing hostname or,\n"); fprintf (stderr, "the xxx.xxx.xxx.xxx format.\n"); exit (1); } else { /* Seems I'm just to stupid to find the right functio for this... */ ((char *)&ipnum.s_addr)[0] = hostdata->h_addr_list[0][0]; ((char *)&ipnum.s_addr)[1] = hostdata->h_addr_list[0][1]; ((char *)&ipnum.s_addr)[2] = hostdata->h_addr_list[0][2]; ((char *)&ipnum.s_addr)[3] = hostdata->h_addr_list[0][3]; } } fprintf (stderr, "Using Server %s:%i\n", inet_ntoa(ipnum), ntohs(port)); bzero((char *) &hostaddress, sizeof(hostaddress)); hostaddress.sin_family = AF_INET; hostaddress.sin_addr.s_addr = ipnum.s_addr; hostaddress.sin_port = port; file = open (logfile, O_NONBLOCK | O_RDONLY); if (file != -1) { while (1) { if ((sock = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror ("Couldn't open socket"); exit (1); } else { if (connect(sock, (struct sockaddr *)&hostaddress, sizeof(hostaddress)) == -1) { perror ("Couldn't connect socket"); exit (1); } else { printf("Connected to %s:%s\n", ircserver, portstr ? portstr: "6667"); } } flags = fcntl(sock, F_GETFL); flags |= O_NONBLOCK; if (fcntl(sock, F_SETFL, (long) flags)) { printf ("Couldn't switch to non-blocking\n"); exit (1); } if (do_irc_reg()) { irc_loop(); } close (sock); } close (file); } else { fprintf (stderr, "Couldn't open file '%s'\n", logfile); } }
578
./ipc-bench/tcp_remote_lat.c
/* Measure latency of IPC using tcp sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <time.h> #include <stdint.h> #include <netdb.h> int main(int argc, char *argv[]) { int size; char *buf; int64_t count, i, delta; struct timeval start, stop; ssize_t len; size_t sofar; int yes = 1; int ret; struct sockaddr_storage their_addr; socklen_t addr_size; struct addrinfo hints; struct addrinfo *res; int sockfd, new_fd; if (argc != 6) { printf ("usage: tcp_lat <bind-to> <host> <port> <message-size> <roundtrip-count>\n"); return 1; } size = atoi(argv[4]); count = atol(argv[5]); buf = malloc(size); if (buf == NULL) { perror("malloc"); return 1; } printf("message size: %i octets\n", size); printf("roundtrip count: %lli\n", count); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((ret = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("bind"); exit(1); } if ((ret = getaddrinfo(argv[2], argv[3], &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("connect"); exit(1); } gettimeofday(&start); for (i = 0; i < count; i++) { if (write(sockfd, buf, size) != size) { perror("write"); return 1; } for (sofar = 0; sofar < size; ) { len = read(sockfd, buf, size - sofar); if (len == -1) { perror("read"); return 1; } sofar += len; } } gettimeofday(&stop); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average latency: %lli us\n", delta / (count * 2)); return 0; }
579
./ipc-bench/tcp_thr.c
/* Measure throughput of IPC using tcp sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <time.h> #include <stdint.h> #include <netdb.h> #include <netinet/tcp.h> int main(int argc, char *argv[]) { int size; char *buf; int64_t count, i, delta; struct timeval start, stop; ssize_t len; size_t sofar; int yes = 1; int ret; struct sockaddr_storage their_addr; socklen_t addr_size; struct addrinfo hints; struct addrinfo *res; int sockfd, new_fd; if (argc != 3) { printf ("usage: tcp_thr <message-size> <message-count>\n"); return 1; } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((ret = getaddrinfo("127.0.0.1", "3491", &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } printf("message size: %i octets\n", size); printf("message count: %lli\n", count); if (!fork()) { /* child */ if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("bind"); exit(1); } if (listen(sockfd, 1) == -1) { perror("listen"); exit(1); } addr_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size)) == -1) { perror("accept"); exit(1); } for (sofar = 0; sofar < (count * size);) { len = read(new_fd, buf, size); if (len == -1) { perror("read"); exit(1); } sofar += len; } } else { /* parent */ sleep(1); if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("connect"); exit(1); } if (setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(sockfd, buf, size) != size) { perror("write"); exit(1); } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average throughput: %lli msg/s\n", (count * (int64_t) 1e6) / delta); printf("average throughput: %lli Mb/s\n", (((count * (int64_t) 1e6) / delta) * size * 8) / (int64_t) 1e6); } return 0; }
580
./ipc-bench/tcp_local_lat.c
/* Measure latency of IPC using tcp sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <time.h> #include <stdint.h> #include <netdb.h> int main(int argc, char *argv[]) { int size; char *buf; int64_t count, i, delta; struct timeval start, stop; ssize_t len; size_t sofar; int yes = 1; int ret; struct sockaddr_storage their_addr; socklen_t addr_size; struct addrinfo hints; struct addrinfo *res; int sockfd, new_fd; if (argc != 5) { printf ("usage: tcp_local_lat <bind-to> <port> <message-size> <roundtrip-count>\n"); return 1; } size = atoi(argv[3]); count = atol(argv[4]); buf = malloc(size); if (buf == NULL) { perror("malloc"); return 1; } printf("message size: %i octets\n", size); printf("roundtrip count: %lli\n", count); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((ret = getaddrinfo(argv[1], argv[2], &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("bind"); exit(1); } if (listen(sockfd, 1) == -1) { perror("listen"); exit(1); } addr_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size)) == -1) { perror("accept"); exit(1); } for (i = 0; i < count; i++) { for (sofar = 0; sofar < size; ) { len = read(new_fd, buf, size - sofar); if (len == -1) { perror("read"); return 1; } sofar += len; } if (write(new_fd, buf, size) != size) { perror("write"); return 1; } } return 0; }
581
./ipc-bench/pipe_thr.c
/* Measure throughput of IPC using pipes Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <time.h> #include <stdint.h> int main(int argc, char *argv[]) { int fds[2]; int size; char *buf; int64_t count, i, delta; struct timeval start, stop; if (argc != 3) { printf ("usage: pipe_thr <message-size> <message-count>\n"); exit(1); } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); exit(1); } printf("message size: %i octets\n", size); printf("message count: %lli\n", count); if (pipe(fds) == -1) { perror("pipe"); exit(1); } if (!fork()) { /* child */ for (i = 0; i < count; i++) { if (read(fds[0], buf, size) != size) { perror("read"); exit(1); } } } else { /* parent */ gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(fds[1], buf, size) != size) { perror("write"); exit(1); } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average throughput: %lli msg/s\n", (count * (int64_t) 1e6) / delta); printf("average throughput: %lli Mb/s\n", (((count * (int64_t) 1e6) / delta) * size * 8) / (int64_t) 1e6); } return 0; }
582
./ipc-bench/shm.c
/* Measure latency of IPC using shm */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdint.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> int main(void) { int pfds[2]; char c; int shmid; key_t key; struct timespec *shm; struct timespec start, stop; int64_t delta; int64_t max = 0; int64_t min = INT64_MAX; int64_t sum = 0; int64_t count = 0; /* * We'll name our shared memory segment * "5678". */ key = 5678; if (!fork()) { /* * Create the segment. */ if ((shmid = shmget(key, 100, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } /* * Now we attach the segment to our data space. */ if ((shm = shmat(shmid, NULL, 0)) == (struct timespec*) -1) { perror("shmat"); exit(1); } while (1) { gettimeofday(shm, NULL); usleep(10000); } } else { sleep(1); /* * Locate the segment. */ if ((shmid = shmget(key, 100, 0666)) < 0) { perror("shmget"); exit(1); } /* * Now we attach the segment to our data space. */ if ((shm = shmat(shmid, NULL, 0)) == (struct timespec *) -1) { perror("shmat"); exit(1); } while (1) { while ((shm->tv_sec == start.tv_sec) && (shm->tv_nsec == start.tv_nsec)) {} gettimeofday(&stop, NULL); start = *shm; delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1000000000 + stop.tv_nsec - start.tv_nsec); if (delta > max) max = delta; else if (delta < min) min = delta; sum += delta; count++; if (!(count % 100)) { printf("%lli %lli %lli\n", max, min, sum / count); } } } return 0; }
583
./ipc-bench/pipe_lat.c
/* Measure latency of IPC using unix domain sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <time.h> #include <stdint.h> int main(int argc, char *argv[]) { int ofds[2]; int ifds[2]; int size; char *buf; int64_t count, i, delta; struct timeval start, stop; if (argc != 3) { printf ("usage: pipe_lat <message-size> <roundtrip-count>\n"); return 1; } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); return 1; } printf("message size: %i octets\n", size); printf("roundtrip count: %lli\n", count); if (pipe(ofds) == -1) { perror("pipe"); return 1; } if (pipe(ifds) == -1) { perror("pipe"); return 1; } if (!fork()) { /* child */ for (i = 0; i < count; i++) { if (read(ifds[0], buf, size) != size) { perror("read"); return 1; } if (write(ofds[1], buf, size) != size) { perror("write"); return 1; } } } else { /* parent */ gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(ifds[1], buf, size) != size) { perror("write"); return 1; } if (read(ofds[0], buf, size) != size) { perror("read"); return 1; } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1000000 + stop.tv_usec - start.tv_usec); printf("average latency: %lli us\n", delta / (count * 2)); } return 0; }
584
./ipc-bench/tcp_lat.c
/* Measure latency of IPC using tcp sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <time.h> #include <stdint.h> #include <netdb.h> int main(int argc, char *argv[]) { int size; char *buf; int64_t count, i, delta; struct timeval start, stop; ssize_t len; size_t sofar; int yes = 1; int ret; struct sockaddr_storage their_addr; socklen_t addr_size; struct addrinfo hints; struct addrinfo *res; int sockfd, new_fd; if (argc != 3) { printf ("usage: tcp_lat <message-size> <roundtrip-count>\n"); return 1; } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); return 1; } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // fill in my IP for me if ((ret = getaddrinfo("127.0.0.1", "3491", &hints, &res)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } printf("message size: %i octets\n", size); printf("roundtrip count: %lli\n", count); if (!fork()) { /* child */ if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("bind"); exit(1); } if (listen(sockfd, 1) == -1) { perror("listen"); exit(1); } addr_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size)) == -1) { perror("accept"); exit(1); } for (i = 0; i < count; i++) { for (sofar = 0; sofar < size; ) { len = read(new_fd, buf, size - sofar); if (len == -1) { perror("read"); return 1; } sofar += len; } if (write(new_fd, buf, size) != size) { perror("write"); return 1; } } } else { /* parent */ sleep(1); if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { perror("socket"); exit(1); } if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1) { perror("connect"); exit(1); } gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(sockfd, buf, size) != size) { perror("write"); return 1; } for (sofar = 0; sofar < size; ) { len = read(sockfd, buf, size - sofar); if (len == -1) { perror("read"); return 1; } sofar += len; } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average latency: %lli us\n", delta / (count * 2)); } return 0; }
585
./ipc-bench/unix_lat.c
/* Measure latency of IPC using unix domain sockets Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <time.h> #include <stdint.h> int main(int argc, char *argv[]) { int sv[2]; /* the pair of socket descriptors */ int size; char *buf; int64_t count, i, delta; struct timeval start, stop; if (argc != 3) { printf ("usage: unix_lat <message-size> <roundtrip-count>\n"); return 1; } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); return 1; } printf("message size: %i octets\n", size); printf("roundtrip count: %lli\n", count); if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) { perror("socketpair"); exit(1); } if (!fork()) { /* child */ for (i = 0; i < count; i++) { if (read(sv[1], buf, size) != size) { perror("read"); return 1; } if (write(sv[1], buf, size) != size) { perror("write"); return 1; } } } else { /* parent */ gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(sv[0], buf, size) != size) { perror("write"); return 1; } if (read(sv[0], buf, size) != size) { perror("read"); return 1; } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average latency: %lli us\n", delta / (count * 2)); } return 0; }
586
./ipc-bench/unix_thr.c
/* Measure throughput of IPC using unix domain sockets. Copyright (c) 2010 Erik Rigtorp <[email protected]> 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. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <time.h> #include <stdint.h> int main(int argc, char *argv[]) { int fds[2]; /* the pair of socket descriptors */ int size; char *buf; int64_t count, i, delta; struct timeval start, stop; if (argc != 3) { printf ("usage: unix_thr <message-size> <message-count>\n"); exit(1); } size = atoi(argv[1]); count = atol(argv[2]); buf = malloc(size); if (buf == NULL) { perror("malloc"); exit(1); } printf("message size: %i octets\n", size); printf("message count: %lli\n", count); if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) == -1) { perror("socketpair"); exit(1); } if (!fork()) { /* child */ for (i = 0; i < count; i++) { if (read(fds[1], buf, size) != size) { perror("read"); exit(1); } } } else { /* parent */ gettimeofday(&start, NULL); for (i = 0; i < count; i++) { if (write(fds[0], buf, size) != size) { perror("write"); exit(1); } } gettimeofday(&stop, NULL); delta = ((stop.tv_sec - start.tv_sec) * (int64_t) 1e6 + stop.tv_usec - start.tv_usec); printf("average throughput: %lli msg/s\n", (count * (int64_t) 1e6) / delta); printf("average throughput: %lli Mb/s\n", (((count * (int64_t) 1e6) / delta) * size * 8) / (int64_t) 1e6); } return 0; }
587
./intellij-community/native/fsNotifier/linux/inotify.c
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fsnotifier.h" #include <dirent.h> #include <errno.h> #include <linux/limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <sys/stat.h> #include <syslog.h> #include <unistd.h> #ifdef __amd64__ __asm__(".symver memcpy,memcpy@GLIBC_2.2.5"); #else __asm__(".symver memcpy,memcpy@GLIBC_2.0"); #endif #define WATCH_COUNT_NAME "/proc/sys/fs/inotify/max_user_watches" #define DEFAULT_SUBDIR_COUNT 5 typedef struct __watch_node { int wd; struct __watch_node* parent; array* kids; int path_len; char path[0]; } watch_node; static int inotify_fd = -1; static int watch_count = 0; static table* watches; static bool limit_reached = false; static void (* callback)(char*, int) = NULL; #define EVENT_SIZE (sizeof(struct inotify_event)) #define EVENT_BUF_LEN (2048 * (EVENT_SIZE + 16)) static char event_buf[EVENT_BUF_LEN]; static char path_buf[2 * PATH_MAX]; static void read_watch_descriptors_count(); static void watch_limit_reached(); bool init_inotify() { inotify_fd = inotify_init(); if (inotify_fd < 0) { int e = errno; userlog(LOG_ERR, "inotify_init: %s", strerror(e)); if (e == EMFILE) { message(MSG_INSTANCE_LIMIT); } return false; } userlog(LOG_DEBUG, "inotify fd: %d", get_inotify_fd()); read_watch_descriptors_count(); if (watch_count <= 0) { close(inotify_fd); inotify_fd = -1; return false; } userlog(LOG_INFO, "inotify watch descriptors: %d", watch_count); watches = table_create(watch_count); if (watches == NULL) { userlog(LOG_ERR, "out of memory"); close(inotify_fd); inotify_fd = -1; return false; } return true; } static void read_watch_descriptors_count() { FILE* f = fopen(WATCH_COUNT_NAME, "r"); if (f == NULL) { userlog(LOG_ERR, "can't open %s: %s", WATCH_COUNT_NAME, strerror(errno)); return; } char* str = read_line(f); if (str == NULL) { userlog(LOG_ERR, "can't read from %s", WATCH_COUNT_NAME); } else { watch_count = atoi(str); } fclose(f); } inline void set_inotify_callback(void (* _callback)(char*, int)) { callback = _callback; } inline int get_inotify_fd() { return inotify_fd; } #define EVENT_MASK IN_MODIFY | IN_ATTRIB | IN_CREATE | IN_DELETE | IN_MOVE | IN_DELETE_SELF | IN_MOVE_SELF static int add_watch(int path_len, watch_node* parent) { int wd = inotify_add_watch(inotify_fd, path_buf, EVENT_MASK); if (wd < 0) { if (errno == EACCES || errno == ENOENT) { userlog(LOG_DEBUG, "inotify_add_watch(%s): %s", path_buf, strerror(errno)); return ERR_IGNORE; } else if (errno == ENOSPC) { userlog(LOG_WARNING, "inotify_add_watch(%s): %s", path_buf, strerror(errno)); watch_limit_reached(); return ERR_CONTINUE; } else { userlog(LOG_ERR, "inotify_add_watch(%s): %s", path_buf, strerror(errno)); return ERR_ABORT; } } else { userlog(LOG_DEBUG, "watching %s: %d", path_buf, wd); } watch_node* node = table_get(watches, wd); if (node != NULL) { if (node->wd != wd) { userlog(LOG_ERR, "table error: corruption at %d:%s / %d:%s)", wd, path_buf, node->wd, node->path); return ERR_ABORT; } else if (strcmp(node->path, path_buf) != 0) { char buf1[PATH_MAX], buf2[PATH_MAX]; const char* normalized1 = realpath(node->path, buf1); const char* normalized2 = realpath(path_buf, buf2); if (normalized1 == NULL || normalized2 == NULL || strcmp(normalized1, normalized2) != 0) { userlog(LOG_ERR, "table error: collision at %d (new %s, existing %s)", wd, path_buf, node->path); return ERR_ABORT; } else { userlog(LOG_INFO, "intersection at %d: (new %s, existing %s, real %s)", wd, path_buf, node->path, normalized1); return ERR_IGNORE; } } return wd; } node = malloc(sizeof(watch_node) + path_len + 1); CHECK_NULL(node, ERR_ABORT); memcpy(node->path, path_buf, path_len + 1); node->path_len = path_len; node->wd = wd; node->parent = parent; node->kids = NULL; if (parent != NULL) { if (parent->kids == NULL) { parent->kids = array_create(DEFAULT_SUBDIR_COUNT); CHECK_NULL(parent->kids, ERR_ABORT); } CHECK_NULL(array_push(parent->kids, node), ERR_ABORT); } if (table_put(watches, wd, node) == NULL) { userlog(LOG_ERR, "table error: unable to put (%d:%s)", wd, path_buf); return ERR_ABORT; } return wd; } static void watch_limit_reached() { if (!limit_reached) { limit_reached = true; message(MSG_WATCH_LIMIT); } } static void rm_watch(int wd, bool update_parent) { watch_node* node = table_get(watches, wd); if (node == NULL) { return; } userlog(LOG_DEBUG, "unwatching %s: %d (%p)", node->path, node->wd, node); if (inotify_rm_watch(inotify_fd, node->wd) < 0) { userlog(LOG_DEBUG, "inotify_rm_watch(%d:%s): %s", node->wd, node->path, strerror(errno)); } for (int i=0; i<array_size(node->kids); i++) { watch_node* kid = array_get(node->kids, i); if (kid != NULL) { rm_watch(kid->wd, false); } } if (update_parent && node->parent != NULL) { for (int i=0; i<array_size(node->parent->kids); i++) { if (array_get(node->parent->kids, i) == node) { array_put(node->parent->kids, i, NULL); break; } } } array_delete(node->kids); free(node); table_put(watches, wd, NULL); } static int walk_tree(int path_len, watch_node* parent, bool recursive, array* mounts) { for (int j=0; j<array_size(mounts); j++) { char* mount = array_get(mounts, j); if (strncmp(path_buf, mount, strlen(mount)) == 0) { userlog(LOG_DEBUG, "watch path '%s' crossed mount point '%s' - skipping", path_buf, mount); return ERR_IGNORE; } } DIR* dir = NULL; if (recursive) { if ((dir = opendir(path_buf)) == NULL) { if (errno == EACCES || errno == ENOENT || errno == ENOTDIR) { userlog(LOG_DEBUG, "opendir(%s): %d", path_buf, errno); return ERR_IGNORE; } else { userlog(LOG_ERR, "opendir(%s): %s", path_buf, strerror(errno)); return ERR_CONTINUE; } } } int id = add_watch(path_len, parent); if (dir == NULL) { return id; } else if (id < 0) { closedir(dir); return id; } path_buf[path_len] = '/'; struct dirent* entry; while ((entry = readdir(dir)) != NULL) { if (entry->d_type != DT_DIR || strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } int name_len = strlen(entry->d_name); memcpy(path_buf + path_len + 1, entry->d_name, name_len + 1); int subdir_id = walk_tree(path_len + 1 + name_len, table_get(watches, id), recursive, mounts); if (subdir_id < 0 && subdir_id != ERR_IGNORE) { rm_watch(id, true); id = subdir_id; break; } } closedir(dir); return id; } int watch(const char* root, array* mounts) { bool recursive = true; if (root[0] == '|') { root++; recursive = false; } int path_len = strlen(root); if (root[path_len - 1] == '/') { --path_len; } struct stat st; if (stat(root, &st) != 0) { if (errno == ENOENT) { return ERR_MISSING; } else if (errno == EACCES || errno == ELOOP || errno == ENAMETOOLONG || errno == ENOTDIR) { userlog(LOG_INFO, "stat(%s): %s", root, strerror(errno)); return ERR_CONTINUE; } else { userlog(LOG_ERR, "stat(%s): %s", root, strerror(errno)); return ERR_ABORT; } } if (S_ISREG(st.st_mode)) { recursive = false; } else if (!S_ISDIR(st.st_mode)) { userlog(LOG_WARNING, "unexpected node type: %s, %d", root, st.st_mode); return ERR_IGNORE; } memcpy(path_buf, root, path_len); path_buf[path_len] = '\0'; return walk_tree(path_len, NULL, recursive, mounts); } void unwatch(int id) { rm_watch(id, true); } static bool process_inotify_event(struct inotify_event* event) { watch_node* node = table_get(watches, event->wd); if (node == NULL) { return true; } bool is_dir = (event->mask & IN_ISDIR) == IN_ISDIR; userlog(LOG_DEBUG, "inotify: wd=%d mask=%d dir=%d name=%s", event->wd, event->mask & (~IN_ISDIR), is_dir, node->path); memcpy(path_buf, node->path, node->path_len + 1); int path_len = node->path_len; if (event->len > 0) { path_buf[node->path_len] = '/'; int name_len = strlen(event->name); memcpy(path_buf + path_len + 1, event->name, name_len + 1); path_len += name_len + 1; } if (is_dir && event->mask & (IN_CREATE | IN_MOVED_TO)) { int result = walk_tree(path_len, node, true, NULL); if (result < 0 && result != ERR_IGNORE && result != ERR_CONTINUE) { return false; } } if (is_dir && event->mask & (IN_DELETE | IN_MOVED_FROM)) { for (int i=0; i<array_size(node->kids); i++) { watch_node* kid = array_get(node->kids, i); if (kid != NULL && strncmp(path_buf, kid->path, kid->path_len) == 0) { rm_watch(kid->wd, false); array_put(node->kids, i, NULL); break; } } } if (callback != NULL) { (*callback)(path_buf, event->mask); } return true; } bool process_inotify_input() { ssize_t len = read(inotify_fd, event_buf, EVENT_BUF_LEN); if (len < 0) { userlog(LOG_ERR, "read: %s", strerror(errno)); return false; } int i = 0; while (i < len) { struct inotify_event* event = (struct inotify_event*) &event_buf[i]; i += EVENT_SIZE + event->len; if (event->mask & IN_IGNORED) { continue; } if (event->mask & IN_Q_OVERFLOW) { userlog(LOG_INFO, "event queue overflow"); continue; } if (!process_inotify_event(event)) { return false; } } return true; } void close_inotify() { if (watches != NULL) { table_delete(watches); } if (inotify_fd >= 0) { close(inotify_fd); } }
588
./intellij-community/native/fsNotifier/linux/util.c
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fsnotifier.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define REALLOC_FACTOR 2 struct __array { void** data; int size; int capacity; }; static bool array_realloc(array* a) { if (a->size == a->capacity) { int new_cap = a->capacity * REALLOC_FACTOR; void* new_ptr = realloc(a->data, sizeof(void*) * new_cap); if (new_ptr == NULL) { return false; } a->capacity = new_cap; a->data = new_ptr; } return true; } array* array_create(int initial_capacity) { array* a = (array*) malloc(sizeof(array)); if (a == NULL) { return NULL; } a->data = calloc(sizeof(void*), initial_capacity); if (a->data == NULL) { free(a); return NULL; } a->capacity = initial_capacity; a->size = 0; return a; } inline int array_size(array* a) { return (a != NULL ? a->size : 0); } void* array_push(array* a, void* element) { if (a == NULL || !array_realloc(a)) { return NULL; } a->data[a->size++] = element; return element; } void* array_pop(array* a) { if (a != NULL && a->size > 0) { return a->data[--a->size]; } else { return NULL; } } void array_put(array* a, int index, void* element) { if (a != NULL && index >=0 && index < a->capacity) { a->data[index] = element; if (a->size <= index) { a->size = index + 1; } } } void* array_get(array* a, int index) { if (a != NULL && index >= 0 && index < a->size) { return a->data[index]; } else { return NULL; } } void array_delete(array* a) { if (a != NULL) { free(a->data); free(a); } } void array_delete_vs_data(array* a) { if (a != NULL) { array_delete_data(a); array_delete(a); } } void array_delete_data(array* a) { if (a != NULL) { for (int i=0; i<a->size; i++) { if (a->data[i] != NULL) { free(a->data[i]); } } a->size = 0; } } struct __table { void** data; int capacity; }; table* table_create(int capacity) { table* t = malloc(sizeof(table)); if (t == NULL) { return NULL; } t->data = calloc(sizeof(void*), capacity); if (t->data == NULL) { free(t); return NULL; } memset(t->data, 0, sizeof(void*) * capacity); t->capacity = capacity; return t; } static inline int wrap(int key, table* t) { return (t != NULL ? key % t->capacity : -1); } // todo: resolve collisions (?) void* table_put(table* t, int key, void* value) { int k = wrap(key, t); if (k < 0 || (value != NULL && t->data[k] != NULL)) { return NULL; } else { return t->data[k] = value; } } void* table_get(table* t, int key) { int k = wrap(key, t); if (k < 0) { return NULL; } else { return t->data[k]; } } void table_delete(table* t) { if (t != NULL) { free(t->data); free(t); } } #define INPUT_BUF_LEN 2048 static char input_buf[INPUT_BUF_LEN]; char* read_line(FILE* stream) { char* retval = fgets(input_buf, INPUT_BUF_LEN, stream); if (retval == NULL || feof(stream)) { return NULL; } int pos = strlen(input_buf) - 1; if (input_buf[pos] == '\n') { input_buf[pos] = '\0'; } return input_buf; } bool is_parent_path(const char* parent_path, const char* child_path) { size_t parent_len = strlen(parent_path); return strncmp(parent_path, child_path, parent_len) == 0 && (parent_len == strlen(child_path) || child_path[parent_len] == '/'); }
589
./intellij-community/native/fsNotifier/linux/main.c
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fsnotifier.h" #include <errno.h> #include <limits.h> #include <mntent.h> #include <paths.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <sys/select.h> #include <sys/stat.h> #include <syslog.h> #include <unistd.h> #define LOG_ENV "FSNOTIFIER_LOG_LEVEL" #define LOG_ENV_DEBUG "debug" #define LOG_ENV_INFO "info" #define LOG_ENV_WARNING "warning" #define LOG_ENV_ERROR "error" #define LOG_ENV_OFF "off" #define VERSION "20130617.1935" #define VERSION_MSG "fsnotifier " VERSION "\n" #define USAGE_MSG \ "fsnotifier - IntelliJ IDEA companion program for watching and reporting file and directory structure modifications.\n\n" \ "fsnotifier utilizes \"user\" facility of syslog(3) - messages usually can be found in /var/log/user.log.\n" \ "Verbosity is regulated via " LOG_ENV " environment variable, possible values are: " \ LOG_ENV_DEBUG ", " LOG_ENV_INFO ", " LOG_ENV_WARNING ", " LOG_ENV_ERROR ", " LOG_ENV_OFF "; default is " LOG_ENV_WARNING ".\n\n" \ "Use 'fsnotifier --selftest' to perform some self-diagnostics (output will be logged and printed to console).\n" #define HELP_MSG \ "Try 'fsnotifier --help' for more information.\n" #define INSTANCE_LIMIT_TEXT \ "The <b>inotify</b>(7) instances limit reached. " \ "<a href=\"http://confluence.jetbrains.net/display/IDEADEV/Inotify+Instances+Limit\">More details.</a>\n" #define WATCH_LIMIT_TEXT \ "The current <b>inotify</b>(7) watch limit is too low. " \ "<a href=\"http://confluence.jetbrains.net/display/IDEADEV/Inotify+Watches+Limit\">More details.</a>\n" #define MISSING_ROOT_TIMEOUT 1 #define UNFLATTEN(root) (root[0] == '|' ? root + 1 : root) typedef struct { char* path; int id; // negative value means missing root } watch_root; static array* roots = NULL; static int log_level = 0; static bool self_test = false; static void init_log(); static void run_self_test(); static bool main_loop(); static int read_input(); static bool update_roots(array* new_roots); static void unregister_roots(); static bool register_roots(array* new_roots, array* unwatchable, array* mounts); static array* unwatchable_mounts(); static void inotify_callback(char* path, int event); static void report_event(char* event, char* path); static void output(const char* format, ...); static void check_missing_roots(); static void check_root_removal(char*); int main(int argc, char** argv) { if (argc > 1) { if (strcmp(argv[1], "--help") == 0) { printf(USAGE_MSG); return 0; } else if (strcmp(argv[1], "--version") == 0) { printf(VERSION_MSG); return 0; } else if (strcmp(argv[1], "--selftest") == 0) { self_test = true; } else { printf("unrecognized option: %s\n", argv[1]); printf(HELP_MSG); return 1; } } init_log(); if (!self_test) { userlog(LOG_INFO, "started (v." VERSION ")"); } else { userlog(LOG_INFO, "started (self-test mode) (v." VERSION ")"); } setvbuf(stdin, NULL, _IONBF, 0); int rv = 0; roots = array_create(20); if (roots != NULL && init_inotify()) { set_inotify_callback(&inotify_callback); if (!self_test) { if (!main_loop()) { rv = 3; } } else { run_self_test(); } unregister_roots(); } else { output("GIVEUP\n"); rv = 2; } close_inotify(); array_delete(roots); userlog(LOG_INFO, "finished (%d)", rv); closelog(); return rv; } static void init_log() { int level = LOG_WARNING; char* env_level = getenv(LOG_ENV); if (env_level != NULL) { if (strcmp(env_level, LOG_ENV_DEBUG) == 0) level = LOG_DEBUG; else if (strcmp(env_level, LOG_ENV_INFO) == 0) level = LOG_INFO; else if (strcmp(env_level, LOG_ENV_WARNING) == 0) level = LOG_WARNING; else if (strcmp(env_level, LOG_ENV_ERROR) == 0) level = LOG_ERR; } if (self_test) { level = LOG_DEBUG; } char ident[32]; snprintf(ident, sizeof(ident), "fsnotifier[%d]", getpid()); openlog(ident, 0, LOG_USER); log_level = level; } void message(MSG id) { if (id == MSG_INSTANCE_LIMIT) { output("MESSAGE\n" INSTANCE_LIMIT_TEXT); } else if (id == MSG_WATCH_LIMIT) { output("MESSAGE\n" WATCH_LIMIT_TEXT); } else { userlog(LOG_ERR, "unknown message: %d", id); } } void userlog(int priority, const char* format, ...) { if (priority > log_level) { return; } va_list ap; va_start(ap, format); vsyslog(priority, format, ap); va_end(ap); if (self_test) { const char* level = "debug"; switch (priority) { case LOG_ERR: level = "error"; break; case LOG_WARNING: level = " warn"; break; case LOG_INFO: level = " info"; break; } printf("fsnotifier[%d] %s: ", getpid(), level); va_start(ap, format); vprintf(format, ap); va_end(ap); printf("\n"); } } static void run_self_test() { array* test_roots = array_create(1); char* cwd = malloc(PATH_MAX); if (getcwd(cwd, PATH_MAX) == NULL) { strncpy(cwd, ".", PATH_MAX); } array_push(test_roots, cwd); update_roots(test_roots); } static bool main_loop() { int input_fd = fileno(stdin), inotify_fd = get_inotify_fd(); int nfds = (inotify_fd > input_fd ? inotify_fd : input_fd) + 1; fd_set rfds; struct timeval timeout; while (true) { usleep(50000); FD_ZERO(&rfds); FD_SET(input_fd, &rfds); FD_SET(inotify_fd, &rfds); timeout = (struct timeval){MISSING_ROOT_TIMEOUT, 0}; if (select(nfds, &rfds, NULL, NULL, &timeout) < 0) { if (errno != EINTR) { userlog(LOG_ERR, "select: %s", strerror(errno)); return false; } } else if (FD_ISSET(input_fd, &rfds)) { int result = read_input(); if (result == 0) return true; else if (result != ERR_CONTINUE) return false; } else if (FD_ISSET(inotify_fd, &rfds)) { if (!process_inotify_input()) return false; } else { check_missing_roots(); } } } static int read_input() { char* line = read_line(stdin); userlog(LOG_DEBUG, "input: %s", (line ? line : "<null>")); if (line == NULL || strcmp(line, "EXIT") == 0) { userlog(LOG_INFO, "exiting: %s", line); return 0; } if (strcmp(line, "ROOTS") == 0) { array* new_roots = array_create(20); CHECK_NULL(new_roots, ERR_ABORT); while (1) { line = read_line(stdin); userlog(LOG_DEBUG, "input: %s", (line ? line : "<null>")); if (line == NULL || strlen(line) == 0) { return 0; } else if (strcmp(line, "#") == 0) { break; } else { int l = strlen(line); if (l > 1 && line[l-1] == '/') line[l-1] = '\0'; CHECK_NULL(array_push(new_roots, strdup(line)), ERR_ABORT); } } return update_roots(new_roots) ? ERR_CONTINUE : ERR_ABORT; } userlog(LOG_WARNING, "unrecognised command: %s", line); return ERR_CONTINUE; } static bool update_roots(array* new_roots) { userlog(LOG_INFO, "updating roots (curr:%d, new:%d)", array_size(roots), array_size(new_roots)); unregister_roots(); if (array_size(new_roots) == 0) { output("UNWATCHEABLE\n#\n"); array_delete(new_roots); return true; } else if (array_size(new_roots) == 1 && strcmp(array_get(new_roots, 0), "/") == 0) { // refuse to watch entire tree output("UNWATCHEABLE\n/\n#\n"); userlog(LOG_INFO, "unwatchable: /"); array_delete_vs_data(new_roots); return true; } array* mounts = unwatchable_mounts(); if (mounts == NULL) { return false; } array* unwatchable = array_create(20); if (!register_roots(new_roots, unwatchable, mounts)) { return false; } output("UNWATCHEABLE\n"); for (int i=0; i<array_size(unwatchable); i++) { char* s = array_get(unwatchable, i); output("%s\n", s); userlog(LOG_INFO, "unwatchable: %s", s); } output("#\n"); array_delete_vs_data(unwatchable); array_delete_vs_data(mounts); array_delete_vs_data(new_roots); return true; } static void unregister_roots() { watch_root* root; while ((root = array_pop(roots)) != NULL) { userlog(LOG_INFO, "unregistering root: %s", root->path); unwatch(root->id); free(root->path); free(root); }; } static bool register_roots(array* new_roots, array* unwatchable, array* mounts) { for (int i=0; i<array_size(new_roots); i++) { char* new_root = array_get(new_roots, i); char* unflattened = UNFLATTEN(new_root); userlog(LOG_INFO, "registering root: %s", new_root); if (unflattened[0] != '/') { userlog(LOG_WARNING, "invalid root: %s", new_root); continue; } array* inner_mounts = array_create(5); CHECK_NULL(inner_mounts, false); bool skip = false; for (int j=0; j<array_size(mounts); j++) { char* mount = array_get(mounts, j); if (is_parent_path(mount, unflattened)) { userlog(LOG_INFO, "watch root '%s' is under mount point '%s' - skipping", unflattened, mount); CHECK_NULL(array_push(unwatchable, strdup(unflattened)), false); skip = true; break; } else if (is_parent_path(unflattened, mount)) { userlog(LOG_INFO, "watch root '%s' contains mount point '%s' - partial watch", unflattened, mount); char* copy = strdup(mount); CHECK_NULL(array_push(unwatchable, copy), false); CHECK_NULL(array_push(inner_mounts, copy), false); } } if (skip) { continue; } int id = watch(new_root, inner_mounts); array_delete(inner_mounts); if (id >= 0 || id == ERR_MISSING) { watch_root* root = malloc(sizeof(watch_root)); CHECK_NULL(root, false); root->id = id; root->path = strdup(new_root); CHECK_NULL(root->path, false); CHECK_NULL(array_push(roots, root), false); } else if (id == ERR_ABORT) { return false; } else if (id != ERR_IGNORE) { userlog(LOG_WARNING, "watch root '%s' cannot be watched: %d", unflattened, id); CHECK_NULL(array_push(unwatchable, strdup(unflattened)), false); } } return true; } static bool is_watchable(const char* fs) { // don't watch special and network filesystems return !(strncmp(fs, "dev", 3) == 0 || strcmp(fs, "proc") == 0 || strcmp(fs, "sysfs") == 0 || strcmp(fs, MNTTYPE_SWAP) == 0 || (strncmp(fs, "fuse", 4) == 0 && strcmp(fs, "fuseblk") != 0) || strcmp(fs, "cifs") == 0 || strcmp(fs, MNTTYPE_NFS) == 0); } static array* unwatchable_mounts() { FILE* mtab = setmntent(_PATH_MOUNTED, "r"); if (mtab == NULL) { userlog(LOG_ERR, "cannot open " _PATH_MOUNTED); return NULL; } array* mounts = array_create(20); CHECK_NULL(mounts, NULL); struct mntent* ent; while ((ent = getmntent(mtab)) != NULL) { userlog(LOG_DEBUG, "mtab: %s : %s", ent->mnt_dir, ent->mnt_type); if (strcmp(ent->mnt_type, MNTTYPE_IGNORE) != 0 && !is_watchable(ent->mnt_type)) { CHECK_NULL(array_push(mounts, strdup(ent->mnt_dir)), NULL); } } endmntent(mtab); return mounts; } static void inotify_callback(char* path, int event) { if (event & (IN_CREATE | IN_MOVED_TO)) { report_event("CREATE", path); report_event("CHANGE", path); } else if (event & IN_MODIFY) { report_event("CHANGE", path); } else if (event & IN_ATTRIB) { report_event("STATS", path); } else if (event & (IN_DELETE | IN_MOVED_FROM)) { report_event("DELETE", path); } if (event & (IN_DELETE_SELF | IN_MOVE_SELF)) { check_root_removal(path); } else if (event & IN_UNMOUNT) { output("RESET\n"); userlog(LOG_DEBUG, "RESET"); } } static void report_event(char* event, char* path) { userlog(LOG_DEBUG, "%s: %s", event, path); int len = strlen(path); for (char* p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } fputs(event, stdout); fputc('\n', stdout); fwrite(path, len, 1, stdout); fputc('\n', stdout); fflush(stdout); } static void output(const char* format, ...) { if (self_test) { return; } va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); fflush(stdout); } static void check_missing_roots() { struct stat st; for (int i=0; i<array_size(roots); i++) { watch_root* root = array_get(roots, i); if (root->id < 0) { char* unflattened = UNFLATTEN(root->path); if (stat(unflattened, &st) == 0) { root->id = watch(root->path, NULL); userlog(LOG_INFO, "root restored: %s\n", root->path); report_event("CREATE", unflattened); report_event("CHANGE", unflattened); } } } } static void check_root_removal(char* path) { for (int i=0; i<array_size(roots); i++) { watch_root* root = array_get(roots, i); if (root->id >= 0 && strcmp(path, UNFLATTEN(root->path)) == 0) { unwatch(root->id); root->id = -1; userlog(LOG_INFO, "root deleted: %s\n", root->path); report_event("DELETE", path); } } }
590
./intellij-community/native/fsNotifier/mac/fsnotifier.c
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <CoreServices/CoreServices.h> #include <pthread.h> #include <sys/mount.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static void reportEvent(char *event, char *path) { int len = 0; if (path != NULL) { len = strlen(path); for (char* p = path; *p != '\0'; p++) { if (*p == '\n') { *p = '\0'; } } } pthread_mutex_lock(&lock); fputs(event, stdout); fputc('\n', stdout); if (path != NULL) { fwrite(path, len, 1, stdout); fputc('\n', stdout); } fflush(stdout); pthread_mutex_unlock(&lock); } static void callback(ConstFSEventStreamRef streamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags eventFlags[], const FSEventStreamEventId eventIds[]) { char **paths = eventPaths; for (int i = 0; i < numEvents; i++) { // TODO[max] Lion has much more detailed flags we need accurately process. For now just reduce to SL events range. FSEventStreamEventFlags flags = eventFlags[i] & 0xFF; if ((flags & kFSEventStreamEventFlagMustScanSubDirs) != 0) { reportEvent("RECDIRTY", paths[i]); } else if (flags != kFSEventStreamEventFlagNone) { reportEvent("RESET", NULL); } else { reportEvent("DIRTY", paths[i]); } } } static void * EventProcessingThread(void *data) { FSEventStreamRef stream = (FSEventStreamRef) data; FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); FSEventStreamStart(stream); CFRunLoopRun(); return NULL; } #define FS_FLAGS (MNT_LOCAL|MNT_JOURNALED) static void PrintMountedFileSystems(CFArrayRef roots) { int fsCount = getfsstat(NULL, 0, MNT_WAIT); if (fsCount == -1) return; struct statfs fs[fsCount]; fsCount = getfsstat(fs, sizeof(struct statfs) * fsCount, MNT_NOWAIT); if (fsCount == -1) return; CFMutableArrayRef mounts = CFArrayCreateMutable(NULL, 0, NULL); for (int i = 0; i < fsCount; i++) { if ((fs[i].f_flags & FS_FLAGS) != FS_FLAGS) { char *mount = fs[i].f_mntonname; int mountLen = strlen(mount); for (int j = 0; j < CFArrayGetCount(roots); j++) { char *root = (char *)CFArrayGetValueAtIndex(roots, j); int rootLen = strlen(root); if (rootLen >= mountLen && strncmp(root, mount, mountLen) == 0) { // root under mount point if (rootLen == mountLen || root[mountLen] == '/' || strcmp(mount, "/") == 0) { CFArrayAppendValue(mounts, root); } } else if (strncmp(root, mount, rootLen) == 0) { // root over mount point if (strcmp(root, "/") == 0 || mount[rootLen] == '/') { CFArrayAppendValue(mounts, mount); } } } } } pthread_mutex_lock(&lock); printf("UNWATCHEABLE\n"); for (int i = 0; i < CFArrayGetCount(mounts); i++) { char *mount = (char *)CFArrayGetValueAtIndex(mounts, i); printf("%s\n", mount); } printf("#\n"); fflush(stdout); pthread_mutex_unlock(&lock); CFRelease(mounts); } // Static buffer for fscanf. All of the are being performed from a single thread, so it's thread safe. static char command[2048]; static void ParseRoots() { CFMutableArrayRef roots = CFArrayCreateMutable(NULL, 0, NULL); while (TRUE) { fscanf(stdin, "%s", command); if (strcmp(command, "#") == 0 || feof(stdin)) break; char* path = command[0] == '|' ? command + 1 : command; CFArrayAppendValue(roots, strdup(path)); } PrintMountedFileSystems(roots); for (int i = 0; i < CFArrayGetCount(roots); i++) { void *value = (char *)CFArrayGetValueAtIndex(roots, i); free(value); } CFRelease(roots); } int main(const int argc, const char* argv[]) { // Checking if necessary API is available (need MacOS X 10.5 or later). if (FSEventStreamCreate == NULL) { printf("GIVEUP\n"); return 1; } CFStringRef path = CFSTR("/"); CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&path, 1, NULL); CFAbsoluteTime latency = 0.3; // Latency in seconds FSEventStreamRef stream = FSEventStreamCreate( NULL, &callback, NULL, pathsToWatch, kFSEventStreamEventIdSinceNow, latency, kFSEventStreamCreateFlagNoDefer ); if (stream == NULL) { printf("GIVEUP\n"); return 2; } pthread_t threadId; if (pthread_create(&threadId, NULL, EventProcessingThread, stream) != 0) { printf("GIVEUP\n"); return 3; } while (TRUE) { fscanf(stdin, "%s", command); if (strcmp(command, "EXIT") == 0 || feof(stdin)) break; if (strcmp(command, "ROOTS") == 0) ParseRoots(); } return 0; }
591
./intellij-community/native/breakgen/AppMain.c
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <jni.h> #if defined(WIN32) #include <windows.h> #else #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> int isKernel26OrHigher(); #endif JNIEXPORT void JNICALL Java_com_intellij_rt_execution_application_AppMain_triggerControlBreak (JNIEnv *env, jclass clazz) { #if defined(WIN32) GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, 0); #else if (isKernel26OrHigher()) { kill (getpid(), SIGQUIT); } else { int ppid = getppid(); char buffer[1024]; sprintf(buffer, "/proc/%d/status", ppid); FILE * fp; if ( (fp = fopen(buffer, "r")) != NULL ) { char s[124]; char * ppid_name = "PPid:"; while (fscanf (fp, "%s\n", s) > 0) { if (strcmp(s, ppid_name) == 0) { int pppid; fscanf(fp, "%d", &pppid); kill (pppid, SIGQUIT); break; } } fclose (fp); } } #endif } #ifndef WIN32 int isKernel26OrHigher() { char buffer[1024]; FILE * fp; if ( (fp = fopen("/proc/version", "r")) != NULL ) { int major; int minor; fscanf(fp, "Linux version %d.%d", &major, &minor); fclose (fp); if (major < 2) return 0; if (major == 2) return minor >= 6; return 1; } return 0; } #endif
592
./intellij-community/plugins/hg4idea/testData/bin/hgext/inotify/linux/_inotify.c
/* * _inotify.c - Python extension interfacing to the Linux inotify subsystem * * Copyright 2006 Bryan O'Sullivan <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General * Public License or any later version. */ #include <Python.h> #include <alloca.h> #include <sys/inotify.h> #include <stdint.h> #include <sys/ioctl.h> #include <unistd.h> #include <util.h> /* Variables used in the event string representation */ static PyObject *join; static PyObject *er_wm; static PyObject *er_wmc; static PyObject *er_wmn; static PyObject *er_wmcn; static PyObject *init(PyObject *self, PyObject *args) { PyObject *ret = NULL; int fd = -1; if (!PyArg_ParseTuple(args, ":init")) goto bail; Py_BEGIN_ALLOW_THREADS; fd = inotify_init(); Py_END_ALLOW_THREADS; if (fd == -1) { PyErr_SetFromErrno(PyExc_OSError); goto bail; } ret = PyInt_FromLong(fd); if (ret == NULL) goto bail; goto done; bail: if (fd != -1) close(fd); Py_CLEAR(ret); done: return ret; } PyDoc_STRVAR( init_doc, "init() -> fd\n" "\n" "Initialize an inotify instance.\n" "Return a file descriptor associated with a new inotify event queue."); static PyObject *add_watch(PyObject *self, PyObject *args) { PyObject *ret = NULL; uint32_t mask; int wd = -1; char *path; int fd; if (!PyArg_ParseTuple(args, "isI:add_watch", &fd, &path, &mask)) goto bail; Py_BEGIN_ALLOW_THREADS; wd = inotify_add_watch(fd, path, mask); Py_END_ALLOW_THREADS; if (wd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, path); goto bail; } ret = PyInt_FromLong(wd); if (ret == NULL) goto bail; goto done; bail: if (wd != -1) inotify_rm_watch(fd, wd); Py_CLEAR(ret); done: return ret; } PyDoc_STRVAR( add_watch_doc, "add_watch(fd, path, mask) -> wd\n" "\n" "Add a watch to an inotify instance, or modify an existing watch.\n" "\n" " fd: file descriptor returned by init()\n" " path: path to watch\n" " mask: mask of events to watch for\n" "\n" "Return a unique numeric watch descriptor for the inotify instance\n" "mapped by the file descriptor."); static PyObject *remove_watch(PyObject *self, PyObject *args) { uint32_t wd; int fd; int r; if (!PyArg_ParseTuple(args, "iI:remove_watch", &fd, &wd)) return NULL; Py_BEGIN_ALLOW_THREADS; r = inotify_rm_watch(fd, wd); Py_END_ALLOW_THREADS; if (r == -1) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } Py_INCREF(Py_None); return Py_None; } PyDoc_STRVAR( remove_watch_doc, "remove_watch(fd, wd)\n" "\n" " fd: file descriptor returned by init()\n" " wd: watch descriptor returned by add_watch()\n" "\n" "Remove a watch associated with the watch descriptor wd from the\n" "inotify instance associated with the file descriptor fd.\n" "\n" "Removing a watch causes an IN_IGNORED event to be generated for this\n" "watch descriptor."); #define bit_name(x) {x, #x} static struct { int bit; const char *name; PyObject *pyname; } bit_names[] = { bit_name(IN_ACCESS), bit_name(IN_MODIFY), bit_name(IN_ATTRIB), bit_name(IN_CLOSE_WRITE), bit_name(IN_CLOSE_NOWRITE), bit_name(IN_OPEN), bit_name(IN_MOVED_FROM), bit_name(IN_MOVED_TO), bit_name(IN_CREATE), bit_name(IN_DELETE), bit_name(IN_DELETE_SELF), bit_name(IN_MOVE_SELF), bit_name(IN_UNMOUNT), bit_name(IN_Q_OVERFLOW), bit_name(IN_IGNORED), bit_name(IN_ONLYDIR), bit_name(IN_DONT_FOLLOW), bit_name(IN_MASK_ADD), bit_name(IN_ISDIR), bit_name(IN_ONESHOT), {0} }; static PyObject *decode_mask(int mask) { PyObject *ret = PyList_New(0); int i; if (ret == NULL) goto bail; for (i = 0; bit_names[i].bit; i++) { if (mask & bit_names[i].bit) { if (bit_names[i].pyname == NULL) { bit_names[i].pyname = PyString_FromString(bit_names[i].name); if (bit_names[i].pyname == NULL) goto bail; } Py_INCREF(bit_names[i].pyname); if (PyList_Append(ret, bit_names[i].pyname) == -1) goto bail; } } goto done; bail: Py_CLEAR(ret); done: return ret; } static PyObject *pydecode_mask(PyObject *self, PyObject *args) { int mask; if (!PyArg_ParseTuple(args, "i:decode_mask", &mask)) return NULL; return decode_mask(mask); } PyDoc_STRVAR( decode_mask_doc, "decode_mask(mask) -> list_of_strings\n" "\n" "Decode an inotify mask value into a list of strings that give the\n" "name of each bit set in the mask."); static char doc[] = "Low-level inotify interface wrappers."; static void define_const(PyObject *dict, const char *name, uint32_t val) { PyObject *pyval = PyInt_FromLong(val); PyObject *pyname = PyString_FromString(name); if (!pyname || !pyval) goto bail; PyDict_SetItem(dict, pyname, pyval); bail: Py_XDECREF(pyname); Py_XDECREF(pyval); } static void define_consts(PyObject *dict) { define_const(dict, "IN_ACCESS", IN_ACCESS); define_const(dict, "IN_MODIFY", IN_MODIFY); define_const(dict, "IN_ATTRIB", IN_ATTRIB); define_const(dict, "IN_CLOSE_WRITE", IN_CLOSE_WRITE); define_const(dict, "IN_CLOSE_NOWRITE", IN_CLOSE_NOWRITE); define_const(dict, "IN_OPEN", IN_OPEN); define_const(dict, "IN_MOVED_FROM", IN_MOVED_FROM); define_const(dict, "IN_MOVED_TO", IN_MOVED_TO); define_const(dict, "IN_CLOSE", IN_CLOSE); define_const(dict, "IN_MOVE", IN_MOVE); define_const(dict, "IN_CREATE", IN_CREATE); define_const(dict, "IN_DELETE", IN_DELETE); define_const(dict, "IN_DELETE_SELF", IN_DELETE_SELF); define_const(dict, "IN_MOVE_SELF", IN_MOVE_SELF); define_const(dict, "IN_UNMOUNT", IN_UNMOUNT); define_const(dict, "IN_Q_OVERFLOW", IN_Q_OVERFLOW); define_const(dict, "IN_IGNORED", IN_IGNORED); define_const(dict, "IN_ONLYDIR", IN_ONLYDIR); define_const(dict, "IN_DONT_FOLLOW", IN_DONT_FOLLOW); define_const(dict, "IN_MASK_ADD", IN_MASK_ADD); define_const(dict, "IN_ISDIR", IN_ISDIR); define_const(dict, "IN_ONESHOT", IN_ONESHOT); define_const(dict, "IN_ALL_EVENTS", IN_ALL_EVENTS); } struct event { PyObject_HEAD PyObject *wd; PyObject *mask; PyObject *cookie; PyObject *name; }; static PyObject *event_wd(PyObject *self, void *x) { struct event *evt = (struct event *)self; Py_INCREF(evt->wd); return evt->wd; } static PyObject *event_mask(PyObject *self, void *x) { struct event *evt = (struct event *)self; Py_INCREF(evt->mask); return evt->mask; } static PyObject *event_cookie(PyObject *self, void *x) { struct event *evt = (struct event *)self; Py_INCREF(evt->cookie); return evt->cookie; } static PyObject *event_name(PyObject *self, void *x) { struct event *evt = (struct event *)self; Py_INCREF(evt->name); return evt->name; } static struct PyGetSetDef event_getsets[] = { {"wd", event_wd, NULL, "watch descriptor"}, {"mask", event_mask, NULL, "event mask"}, {"cookie", event_cookie, NULL, "rename cookie, if rename-related event"}, {"name", event_name, NULL, "file name"}, {NULL} }; PyDoc_STRVAR( event_doc, "event: Structure describing an inotify event."); static PyObject *event_new(PyTypeObject *t, PyObject *a, PyObject *k) { return (*t->tp_alloc)(t, 0); } static void event_dealloc(struct event *evt) { Py_XDECREF(evt->wd); Py_XDECREF(evt->mask); Py_XDECREF(evt->cookie); Py_XDECREF(evt->name); Py_TYPE(evt)->tp_free(evt); } static PyObject *event_repr(struct event *evt) { int cookie = evt->cookie == Py_None ? -1 : PyInt_AsLong(evt->cookie); PyObject *ret = NULL, *pymasks = NULL, *pymask = NULL; PyObject *tuple = NULL, *formatstr = NULL; pymasks = decode_mask(PyInt_AsLong(evt->mask)); if (pymasks == NULL) goto bail; pymask = _PyString_Join(join, pymasks); if (pymask == NULL) goto bail; if (evt->name != Py_None) { if (cookie == -1) { formatstr = er_wmn; tuple = PyTuple_Pack(3, evt->wd, pymask, evt->name); } else { formatstr = er_wmcn; tuple = PyTuple_Pack(4, evt->wd, pymask, evt->cookie, evt->name); } } else { if (cookie == -1) { formatstr = er_wm; tuple = PyTuple_Pack(2, evt->wd, pymask); } else { formatstr = er_wmc; tuple = PyTuple_Pack(3, evt->wd, pymask, evt->cookie); } } if (tuple == NULL) goto bail; ret = PyNumber_Remainder(formatstr, tuple); if (ret == NULL) goto bail; goto done; bail: Py_CLEAR(ret); done: Py_XDECREF(pymask); Py_XDECREF(pymasks); Py_XDECREF(tuple); return ret; } static PyTypeObject event_type = { PyVarObject_HEAD_INIT(NULL, 0) "_inotify.event", /*tp_name*/ sizeof(struct event), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)event_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ (reprfunc)event_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ event_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ event_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ event_new, /* tp_new */ }; PyObject *read_events(PyObject *self, PyObject *args) { PyObject *ctor_args = NULL; PyObject *pybufsize = NULL; PyObject *ret = NULL; int bufsize = 65536; char *buf = NULL; int nread, pos; int fd; if (!PyArg_ParseTuple(args, "i|O:read", &fd, &pybufsize)) goto bail; if (pybufsize && pybufsize != Py_None) bufsize = PyInt_AsLong(pybufsize); ret = PyList_New(0); if (ret == NULL) goto bail; if (bufsize <= 0) { int r; Py_BEGIN_ALLOW_THREADS; r = ioctl(fd, FIONREAD, &bufsize); Py_END_ALLOW_THREADS; if (r == -1) { PyErr_SetFromErrno(PyExc_OSError); goto bail; } if (bufsize == 0) goto done; } else { static long name_max; static long name_fd = -1; long min; if (name_fd != fd) { name_fd = fd; Py_BEGIN_ALLOW_THREADS; name_max = fpathconf(fd, _PC_NAME_MAX); Py_END_ALLOW_THREADS; } min = sizeof(struct inotify_event) + name_max + 1; if (bufsize < min) { PyErr_Format(PyExc_ValueError, "bufsize must be at least %d", (int)min); goto bail; } } buf = alloca(bufsize); Py_BEGIN_ALLOW_THREADS; nread = read(fd, buf, bufsize); Py_END_ALLOW_THREADS; if (nread == -1) { PyErr_SetFromErrno(PyExc_OSError); goto bail; } ctor_args = PyTuple_New(0); if (ctor_args == NULL) goto bail; pos = 0; while (pos < nread) { struct inotify_event *in = (struct inotify_event *)(buf + pos); struct event *evt; PyObject *obj; obj = PyObject_CallObject((PyObject *)&event_type, ctor_args); if (obj == NULL) goto bail; evt = (struct event *)obj; evt->wd = PyInt_FromLong(in->wd); evt->mask = PyInt_FromLong(in->mask); if (in->mask & IN_MOVE) evt->cookie = PyInt_FromLong(in->cookie); else { Py_INCREF(Py_None); evt->cookie = Py_None; } if (in->len) evt->name = PyString_FromString(in->name); else { Py_INCREF(Py_None); evt->name = Py_None; } if (!evt->wd || !evt->mask || !evt->cookie || !evt->name) goto mybail; if (PyList_Append(ret, obj) == -1) goto mybail; pos += sizeof(struct inotify_event) + in->len; continue; mybail: Py_CLEAR(evt->wd); Py_CLEAR(evt->mask); Py_CLEAR(evt->cookie); Py_CLEAR(evt->name); Py_DECREF(obj); goto bail; } goto done; bail: Py_CLEAR(ret); done: Py_XDECREF(ctor_args); return ret; } static int init_globals(void) { join = PyString_FromString("|"); er_wm = PyString_FromString("event(wd=%d, mask=%s)"); er_wmn = PyString_FromString("event(wd=%d, mask=%s, name=%s)"); er_wmc = PyString_FromString("event(wd=%d, mask=%s, cookie=0x%x)"); er_wmcn = PyString_FromString("event(wd=%d, mask=%s, cookie=0x%x, name=%s)"); return join && er_wm && er_wmn && er_wmc && er_wmcn; } PyDoc_STRVAR( read_doc, "read(fd, bufsize[=65536]) -> list_of_events\n" "\n" "\nRead inotify events from a file descriptor.\n" "\n" " fd: file descriptor returned by init()\n" " bufsize: size of buffer to read into, in bytes\n" "\n" "Return a list of event objects.\n" "\n" "If bufsize is > 0, block until events are available to be read.\n" "Otherwise, immediately return all events that can be read without\n" "blocking."); static PyMethodDef methods[] = { {"init", init, METH_VARARGS, init_doc}, {"add_watch", add_watch, METH_VARARGS, add_watch_doc}, {"remove_watch", remove_watch, METH_VARARGS, remove_watch_doc}, {"read", read_events, METH_VARARGS, read_doc}, {"decode_mask", pydecode_mask, METH_VARARGS, decode_mask_doc}, {NULL}, }; #ifdef IS_PY3K static struct PyModuleDef _inotify_module = { PyModuleDef_HEAD_INIT, "_inotify", doc, -1, methods }; PyMODINIT_FUNC PyInit__inotify(void) { PyObject *mod, *dict; mod = PyModule_Create(&_inotify_module); if (mod == NULL) return NULL; if (!init_globals()) return; dict = PyModule_GetDict(mod); if (dict) define_consts(dict); return mod; } #else void init_inotify(void) { PyObject *mod, *dict; if (PyType_Ready(&event_type) == -1) return; if (!init_globals()) return; mod = Py_InitModule3("_inotify", methods, doc); dict = PyModule_GetDict(mod); if (dict) define_consts(dict); } #endif
593
./intellij-community/plugins/hg4idea/testData/bin/mercurial/osutil.c
/* osutil.c - native operating system services Copyright 2007 Matt Mackall and others This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #define _ATFILE_SOURCE #include <Python.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <errno.h> #ifdef _WIN32 #include <windows.h> #include <io.h> #else #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #endif #include "util.h" /* some platforms lack the PATH_MAX definition (eg. GNU/Hurd) */ #ifndef PATH_MAX #define PATH_MAX 4096 #endif #ifdef _WIN32 /* stat struct compatible with hg expectations Mercurial only uses st_mode, st_size and st_mtime the rest is kept to minimize changes between implementations */ struct hg_stat { int st_dev; int st_mode; int st_nlink; __int64 st_size; int st_mtime; int st_ctime; }; struct listdir_stat { PyObject_HEAD struct hg_stat st; }; #else struct listdir_stat { PyObject_HEAD struct stat st; }; #endif #define listdir_slot(name) \ static PyObject *listdir_stat_##name(PyObject *self, void *x) \ { \ return PyInt_FromLong(((struct listdir_stat *)self)->st.name); \ } listdir_slot(st_dev) listdir_slot(st_mode) listdir_slot(st_nlink) #ifdef _WIN32 static PyObject *listdir_stat_st_size(PyObject *self, void *x) { return PyLong_FromLongLong( (PY_LONG_LONG)((struct listdir_stat *)self)->st.st_size); } #else listdir_slot(st_size) #endif listdir_slot(st_mtime) listdir_slot(st_ctime) static struct PyGetSetDef listdir_stat_getsets[] = { {"st_dev", listdir_stat_st_dev, 0, 0, 0}, {"st_mode", listdir_stat_st_mode, 0, 0, 0}, {"st_nlink", listdir_stat_st_nlink, 0, 0, 0}, {"st_size", listdir_stat_st_size, 0, 0, 0}, {"st_mtime", listdir_stat_st_mtime, 0, 0, 0}, {"st_ctime", listdir_stat_st_ctime, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PyObject *listdir_stat_new(PyTypeObject *t, PyObject *a, PyObject *k) { return t->tp_alloc(t, 0); } static void listdir_stat_dealloc(PyObject *o) { o->ob_type->tp_free(o); } static PyTypeObject listdir_stat_type = { PyVarObject_HEAD_INIT(NULL, 0) "osutil.stat", /*tp_name*/ sizeof(struct listdir_stat), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)listdir_stat_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "stat objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ listdir_stat_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ listdir_stat_new, /* tp_new */ }; #ifdef _WIN32 static int to_python_time(const FILETIME *tm) { /* number of seconds between epoch and January 1 1601 */ const __int64 a0 = (__int64)134774L * (__int64)24L * (__int64)3600L; /* conversion factor from 100ns to 1s */ const __int64 a1 = 10000000; /* explicit (int) cast to suspend compiler warnings */ return (int)((((__int64)tm->dwHighDateTime << 32) + tm->dwLowDateTime) / a1 - a0); } static PyObject *make_item(const WIN32_FIND_DATAA *fd, int wantstat) { PyObject *py_st; struct hg_stat *stp; int kind = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? _S_IFDIR : _S_IFREG; if (!wantstat) return Py_BuildValue("si", fd->cFileName, kind); py_st = PyObject_CallObject((PyObject *)&listdir_stat_type, NULL); if (!py_st) return NULL; stp = &((struct listdir_stat *)py_st)->st; /* use kind as st_mode rwx bits on Win32 are meaningless and Hg does not use them anyway */ stp->st_mode = kind; stp->st_mtime = to_python_time(&fd->ftLastWriteTime); stp->st_ctime = to_python_time(&fd->ftCreationTime); if (kind == _S_IFREG) stp->st_size = ((__int64)fd->nFileSizeHigh << 32) + fd->nFileSizeLow; return Py_BuildValue("siN", fd->cFileName, kind, py_st); } static PyObject *_listdir(char *path, int plen, int wantstat, char *skip) { PyObject *rval = NULL; /* initialize - return value */ PyObject *list; HANDLE fh; WIN32_FIND_DATAA fd; char *pattern; /* build the path + \* pattern string */ pattern = malloc(plen + 3); /* path + \* + \0 */ if (!pattern) { PyErr_NoMemory(); goto error_nomem; } strcpy(pattern, path); if (plen > 0) { char c = path[plen-1]; if (c != ':' && c != '/' && c != '\\') pattern[plen++] = '\\'; } strcpy(pattern + plen, "*"); fh = FindFirstFileA(pattern, &fd); if (fh == INVALID_HANDLE_VALUE) { PyErr_SetFromWindowsErrWithFilename(GetLastError(), path); goto error_file; } list = PyList_New(0); if (!list) goto error_list; do { PyObject *item; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue; if (skip && !strcmp(fd.cFileName, skip)) { rval = PyList_New(0); goto error; } } item = make_item(&fd, wantstat); if (!item) goto error; if (PyList_Append(list, item)) { Py_XDECREF(item); goto error; } Py_XDECREF(item); } while (FindNextFileA(fh, &fd)); if (GetLastError() != ERROR_NO_MORE_FILES) { PyErr_SetFromWindowsErrWithFilename(GetLastError(), path); goto error; } rval = list; Py_XINCREF(rval); error: Py_XDECREF(list); error_list: FindClose(fh); error_file: free(pattern); error_nomem: return rval; } #else int entkind(struct dirent *ent) { #ifdef DT_REG switch (ent->d_type) { case DT_REG: return S_IFREG; case DT_DIR: return S_IFDIR; case DT_LNK: return S_IFLNK; case DT_BLK: return S_IFBLK; case DT_CHR: return S_IFCHR; case DT_FIFO: return S_IFIFO; case DT_SOCK: return S_IFSOCK; } #endif return -1; } static PyObject *makestat(const struct stat *st) { PyObject *stat; stat = PyObject_CallObject((PyObject *)&listdir_stat_type, NULL); if (stat) memcpy(&((struct listdir_stat *)stat)->st, st, sizeof(*st)); return stat; } static PyObject *_listdir(char *path, int pathlen, int keepstat, char *skip) { PyObject *list, *elem, *stat, *ret = NULL; char fullpath[PATH_MAX + 10]; int kind, err; struct stat st; struct dirent *ent; DIR *dir; #ifdef AT_SYMLINK_NOFOLLOW int dfd = -1; #endif if (pathlen >= PATH_MAX) { errno = ENAMETOOLONG; PyErr_SetFromErrnoWithFilename(PyExc_OSError, path); goto error_value; } strncpy(fullpath, path, PATH_MAX); fullpath[pathlen] = '/'; #ifdef AT_SYMLINK_NOFOLLOW dfd = open(path, O_RDONLY); if (dfd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, path); goto error_value; } dir = fdopendir(dfd); #else dir = opendir(path); #endif if (!dir) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, path); goto error_dir; } list = PyList_New(0); if (!list) goto error_list; while ((ent = readdir(dir))) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) continue; kind = entkind(ent); if (kind == -1 || keepstat) { #ifdef AT_SYMLINK_NOFOLLOW err = fstatat(dfd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW); #else strncpy(fullpath + pathlen + 1, ent->d_name, PATH_MAX - pathlen); fullpath[PATH_MAX] = 0; err = lstat(fullpath, &st); #endif if (err == -1) { /* race with file deletion? */ if (errno == ENOENT) continue; strncpy(fullpath + pathlen + 1, ent->d_name, PATH_MAX - pathlen); fullpath[PATH_MAX] = 0; PyErr_SetFromErrnoWithFilename(PyExc_OSError, fullpath); goto error; } kind = st.st_mode & S_IFMT; } /* quit early? */ if (skip && kind == S_IFDIR && !strcmp(ent->d_name, skip)) { ret = PyList_New(0); goto error; } if (keepstat) { stat = makestat(&st); if (!stat) goto error; elem = Py_BuildValue("siN", ent->d_name, kind, stat); } else elem = Py_BuildValue("si", ent->d_name, kind); if (!elem) goto error; PyList_Append(list, elem); Py_DECREF(elem); } ret = list; Py_INCREF(ret); error: Py_DECREF(list); error_list: closedir(dir); error_dir: #ifdef AT_SYMLINK_NOFOLLOW close(dfd); #endif error_value: return ret; } static PyObject *statfiles(PyObject *self, PyObject *args) { PyObject *names, *stats; Py_ssize_t i, count; if (!PyArg_ParseTuple(args, "O:statfiles", &names)) return NULL; count = PySequence_Length(names); if (count == -1) { PyErr_SetString(PyExc_TypeError, "not a sequence"); return NULL; } stats = PyList_New(count); if (stats == NULL) return NULL; for (i = 0; i < count; i++) { PyObject *stat; struct stat st; int ret, kind; char *path; path = PyString_AsString(PySequence_GetItem(names, i)); if (path == NULL) { PyErr_SetString(PyExc_TypeError, "not a string"); goto bail; } ret = lstat(path, &st); kind = st.st_mode & S_IFMT; if (ret != -1 && (kind == S_IFREG || kind == S_IFLNK)) { stat = makestat(&st); if (stat == NULL) goto bail; PyList_SET_ITEM(stats, i, stat); } else { Py_INCREF(Py_None); PyList_SET_ITEM(stats, i, Py_None); } } return stats; bail: Py_DECREF(stats); return NULL; } #endif /* ndef _WIN32 */ static PyObject *listdir(PyObject *self, PyObject *args, PyObject *kwargs) { PyObject *statobj = NULL; /* initialize - optional arg */ PyObject *skipobj = NULL; /* initialize - optional arg */ char *path, *skip = NULL; int wantstat, plen; static char *kwlist[] = {"path", "stat", "skip", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s#|OO:listdir", kwlist, &path, &plen, &statobj, &skipobj)) return NULL; wantstat = statobj && PyObject_IsTrue(statobj); if (skipobj && skipobj != Py_None) { skip = PyBytes_AsString(skipobj); if (!skip) return NULL; } return _listdir(path, plen, wantstat, skip); } #ifdef _WIN32 static PyObject *posixfile(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "mode", "buffering", NULL}; PyObject *file_obj = NULL; char *name = NULL; char *mode = "rb"; DWORD access = 0; DWORD creation; HANDLE handle; int fd, flags = 0; int bufsize = -1; char m0, m1, m2; char fpmode[4]; int fppos = 0; int plus; FILE *fp; if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:posixfile", kwlist, Py_FileSystemDefaultEncoding, &name, &mode, &bufsize)) return NULL; m0 = mode[0]; m1 = m0 ? mode[1] : '\0'; m2 = m1 ? mode[2] : '\0'; plus = m1 == '+' || m2 == '+'; fpmode[fppos++] = m0; if (m1 == 'b' || m2 == 'b') { flags = _O_BINARY; fpmode[fppos++] = 'b'; } else flags = _O_TEXT; if (m0 == 'r' && !plus) { flags |= _O_RDONLY; access = GENERIC_READ; } else { /* work around http://support.microsoft.com/kb/899149 and set _O_RDWR for 'w' and 'a', even if mode has no '+' */ flags |= _O_RDWR; access = GENERIC_READ | GENERIC_WRITE; fpmode[fppos++] = '+'; } fpmode[fppos++] = '\0'; switch (m0) { case 'r': creation = OPEN_EXISTING; break; case 'w': creation = CREATE_ALWAYS; break; case 'a': creation = OPEN_ALWAYS; flags |= _O_APPEND; break; default: PyErr_Format(PyExc_ValueError, "mode string must begin with one of 'r', 'w', " "or 'a', not '%c'", m0); goto bail; } handle = CreateFile(name, access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0); if (handle == INVALID_HANDLE_VALUE) { PyErr_SetFromWindowsErrWithFilename(GetLastError(), name); goto bail; } fd = _open_osfhandle((intptr_t)handle, flags); if (fd == -1) { CloseHandle(handle); PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); goto bail; } #ifndef IS_PY3K fp = _fdopen(fd, fpmode); if (fp == NULL) { _close(fd); PyErr_SetFromErrnoWithFilename(PyExc_IOError, name); goto bail; } file_obj = PyFile_FromFile(fp, name, mode, fclose); if (file_obj == NULL) { fclose(fp); goto bail; } PyFile_SetBufSize(file_obj, bufsize); #else file_obj = PyFile_FromFd(fd, name, mode, bufsize, NULL, NULL, NULL, 1); if (file_obj == NULL) goto bail; #endif bail: PyMem_Free(name); return file_obj; } #endif #ifdef __APPLE__ #include <ApplicationServices/ApplicationServices.h> static PyObject *isgui(PyObject *self) { CFDictionaryRef dict = CGSessionCopyCurrentDictionary(); if (dict != NULL) { CFRelease(dict); Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif static char osutil_doc[] = "Native operating system services."; static PyMethodDef methods[] = { {"listdir", (PyCFunction)listdir, METH_VARARGS | METH_KEYWORDS, "list a directory\n"}, #ifdef _WIN32 {"posixfile", (PyCFunction)posixfile, METH_VARARGS | METH_KEYWORDS, "Open a file with POSIX-like semantics.\n" "On error, this function may raise either a WindowsError or an IOError."}, #else {"statfiles", (PyCFunction)statfiles, METH_VARARGS | METH_KEYWORDS, "stat a series of files or symlinks\n" "Returns None for non-existent entries and entries of other types.\n"}, #endif #ifdef __APPLE__ { "isgui", (PyCFunction)isgui, METH_NOARGS, "Is a CoreGraphics session available?" }, #endif {NULL, NULL} }; #ifdef IS_PY3K static struct PyModuleDef osutil_module = { PyModuleDef_HEAD_INIT, "osutil", osutil_doc, -1, methods }; PyMODINIT_FUNC PyInit_osutil(void) { if (PyType_Ready(&listdir_stat_type) < 0) return NULL; return PyModule_Create(&osutil_module); } #else PyMODINIT_FUNC initosutil(void) { if (PyType_Ready(&listdir_stat_type) == -1) return; Py_InitModule3("osutil", methods, osutil_doc); } #endif
594
./intellij-community/plugins/hg4idea/testData/bin/mercurial/base85.c
/* base85 codec Copyright 2006 Brendan Cully <[email protected]> This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Largely based on git's implementation */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include "util.h" static const char b85chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"; static char b85dec[256]; static void b85prep(void) { int i; memset(b85dec, 0, sizeof(b85dec)); for (i = 0; i < sizeof(b85chars); i++) b85dec[(int)(b85chars[i])] = i + 1; } static PyObject * b85encode(PyObject *self, PyObject *args) { const unsigned char *text; PyObject *out; char *dst; Py_ssize_t len, olen, i; unsigned int acc, val, ch; int pad = 0; if (!PyArg_ParseTuple(args, "s#|i", &text, &len, &pad)) return NULL; if (pad) olen = ((len + 3) / 4 * 5) - 3; else { olen = len % 4; if (olen) olen++; olen += len / 4 * 5; } if (!(out = PyBytes_FromStringAndSize(NULL, olen + 3))) return NULL; dst = PyBytes_AsString(out); while (len) { acc = 0; for (i = 24; i >= 0; i -= 8) { ch = *text++; acc |= ch << i; if (--len == 0) break; } for (i = 4; i >= 0; i--) { val = acc % 85; acc /= 85; dst[i] = b85chars[val]; } dst += 5; } if (!pad) _PyBytes_Resize(&out, olen); return out; } static PyObject * b85decode(PyObject *self, PyObject *args) { PyObject *out; const char *text; char *dst; Py_ssize_t len, i, j, olen, cap; int c; unsigned int acc; if (!PyArg_ParseTuple(args, "s#", &text, &len)) return NULL; olen = len / 5 * 4; i = len % 5; if (i) olen += i - 1; if (!(out = PyBytes_FromStringAndSize(NULL, olen))) return NULL; dst = PyBytes_AsString(out); i = 0; while (i < len) { acc = 0; cap = len - i - 1; if (cap > 4) cap = 4; for (j = 0; j < cap; i++, j++) { c = b85dec[(int)*text++] - 1; if (c < 0) return PyErr_Format( PyExc_ValueError, "bad base85 character at position %d", (int)i); acc = acc * 85 + c; } if (i++ < len) { c = b85dec[(int)*text++] - 1; if (c < 0) return PyErr_Format( PyExc_ValueError, "bad base85 character at position %d", (int)i); /* overflow detection: 0xffffffff == "|NsC0", * "|NsC" == 0x03030303 */ if (acc > 0x03030303 || (acc *= 85) > 0xffffffff - c) return PyErr_Format( PyExc_ValueError, "bad base85 sequence at position %d", (int)i); acc += c; } cap = olen < 4 ? olen : 4; olen -= cap; for (j = 0; j < 4 - cap; j++) acc *= 85; if (cap && cap < 4) acc += 0xffffff >> (cap - 1) * 8; for (j = 0; j < cap; j++) { acc = (acc << 8) | (acc >> 24); *dst++ = acc; } } return out; } static char base85_doc[] = "Base85 Data Encoding"; static PyMethodDef methods[] = { {"b85encode", b85encode, METH_VARARGS, "Encode text in base85.\n\n" "If the second parameter is true, pad the result to a multiple of " "five characters.\n"}, {"b85decode", b85decode, METH_VARARGS, "Decode base85 text.\n"}, {NULL, NULL} }; #ifdef IS_PY3K static struct PyModuleDef base85_module = { PyModuleDef_HEAD_INIT, "base85", base85_doc, -1, methods }; PyMODINIT_FUNC PyInit_base85(void) { b85prep(); return PyModule_Create(&base85_module); } #else PyMODINIT_FUNC initbase85(void) { Py_InitModule3("base85", methods, base85_doc); b85prep(); } #endif
595
./intellij-community/plugins/hg4idea/testData/bin/mercurial/bdiff.c
/* bdiff.c - efficient binary diff extension for Mercurial Copyright 2005, 2006 Matt Mackall <[email protected]> This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Based roughly on Python difflib */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "util.h" struct line { int hash, n, e; Py_ssize_t len; const char *l; }; struct pos { int pos, len; }; struct hunk; struct hunk { int a1, a2, b1, b2; struct hunk *next; }; static int splitlines(const char *a, Py_ssize_t len, struct line **lr) { unsigned hash; int i; const char *p, *b = a; const char * const plast = a + len - 1; struct line *l; /* count the lines */ i = 1; /* extra line for sentinel */ for (p = a; p < a + len; p++) if (*p == '\n' || p == plast) i++; *lr = l = (struct line *)malloc(sizeof(struct line) * i); if (!l) return -1; /* build the line array and calculate hashes */ hash = 0; for (p = a; p < a + len; p++) { /* Leonid Yuriev's hash */ hash = (hash * 1664525) + (unsigned char)*p + 1013904223; if (*p == '\n' || p == plast) { l->hash = hash; hash = 0; l->len = p - b + 1; l->l = b; l->n = INT_MAX; l++; b = p + 1; } } /* set up a sentinel */ l->hash = 0; l->len = 0; l->l = a + len; return i - 1; } static inline int cmp(struct line *a, struct line *b) { return a->hash != b->hash || a->len != b->len || memcmp(a->l, b->l, a->len); } static int equatelines(struct line *a, int an, struct line *b, int bn) { int i, j, buckets = 1, t, scale; struct pos *h = NULL; /* build a hash table of the next highest power of 2 */ while (buckets < bn + 1) buckets *= 2; /* try to allocate a large hash table to avoid collisions */ for (scale = 4; scale; scale /= 2) { h = (struct pos *)malloc(scale * buckets * sizeof(struct pos)); if (h) break; } if (!h) return 0; buckets = buckets * scale - 1; /* clear the hash table */ for (i = 0; i <= buckets; i++) { h[i].pos = INT_MAX; h[i].len = 0; } /* add lines to the hash table chains */ for (i = bn - 1; i >= 0; i--) { /* find the equivalence class */ for (j = b[i].hash & buckets; h[j].pos != INT_MAX; j = (j + 1) & buckets) if (!cmp(b + i, b + h[j].pos)) break; /* add to the head of the equivalence class */ b[i].n = h[j].pos; b[i].e = j; h[j].pos = i; h[j].len++; /* keep track of popularity */ } /* compute popularity threshold */ t = (bn >= 31000) ? bn / 1000 : 1000000 / (bn + 1); /* match items in a to their equivalence class in b */ for (i = 0; i < an; i++) { /* find the equivalence class */ for (j = a[i].hash & buckets; h[j].pos != INT_MAX; j = (j + 1) & buckets) if (!cmp(a + i, b + h[j].pos)) break; a[i].e = j; /* use equivalence class for quick compare */ if (h[j].len <= t) a[i].n = h[j].pos; /* point to head of match list */ else a[i].n = INT_MAX; /* too popular */ } /* discard hash tables */ free(h); return 1; } static int longest_match(struct line *a, struct line *b, struct pos *pos, int a1, int a2, int b1, int b2, int *omi, int *omj) { int mi = a1, mj = b1, mk = 0, mb = 0, i, j, k; for (i = a1; i < a2; i++) { /* skip things before the current block */ for (j = a[i].n; j < b1; j = b[j].n) ; /* loop through all lines match a[i] in b */ for (; j < b2; j = b[j].n) { /* does this extend an earlier match? */ if (i > a1 && j > b1 && pos[j - 1].pos == i - 1) k = pos[j - 1].len + 1; else k = 1; pos[j].pos = i; pos[j].len = k; /* best match so far? */ if (k > mk) { mi = i; mj = j; mk = k; } } } if (mk) { mi = mi - mk + 1; mj = mj - mk + 1; } /* expand match to include neighboring popular lines */ while (mi - mb > a1 && mj - mb > b1 && a[mi - mb - 1].e == b[mj - mb - 1].e) mb++; while (mi + mk < a2 && mj + mk < b2 && a[mi + mk].e == b[mj + mk].e) mk++; *omi = mi - mb; *omj = mj - mb; return mk + mb; } static struct hunk *recurse(struct line *a, struct line *b, struct pos *pos, int a1, int a2, int b1, int b2, struct hunk *l) { int i, j, k; while (1) { /* find the longest match in this chunk */ k = longest_match(a, b, pos, a1, a2, b1, b2, &i, &j); if (!k) return l; /* and recurse on the remaining chunks on either side */ l = recurse(a, b, pos, a1, i, b1, j, l); if (!l) return NULL; l->next = (struct hunk *)malloc(sizeof(struct hunk)); if (!l->next) return NULL; l = l->next; l->a1 = i; l->a2 = i + k; l->b1 = j; l->b2 = j + k; l->next = NULL; /* tail-recursion didn't happen, so do equivalent iteration */ a1 = i + k; b1 = j + k; } } static int diff(struct line *a, int an, struct line *b, int bn, struct hunk *base) { struct hunk *curr; struct pos *pos; int t, count = 0; /* allocate and fill arrays */ t = equatelines(a, an, b, bn); pos = (struct pos *)calloc(bn ? bn : 1, sizeof(struct pos)); if (pos && t) { /* generate the matching block list */ curr = recurse(a, b, pos, 0, an, 0, bn, base); if (!curr) return -1; /* sentinel end hunk */ curr->next = (struct hunk *)malloc(sizeof(struct hunk)); if (!curr->next) return -1; curr = curr->next; curr->a1 = curr->a2 = an; curr->b1 = curr->b2 = bn; curr->next = NULL; } free(pos); /* normalize the hunk list, try to push each hunk towards the end */ for (curr = base->next; curr; curr = curr->next) { struct hunk *next = curr->next; int shift = 0; if (!next) break; if (curr->a2 == next->a1) while (curr->a2 + shift < an && curr->b2 + shift < bn && !cmp(a + curr->a2 + shift, b + curr->b2 + shift)) shift++; else if (curr->b2 == next->b1) while (curr->b2 + shift < bn && curr->a2 + shift < an && !cmp(b + curr->b2 + shift, a + curr->a2 + shift)) shift++; if (!shift) continue; curr->b2 += shift; next->b1 += shift; curr->a2 += shift; next->a1 += shift; } for (curr = base->next; curr; curr = curr->next) count++; return count; } static void freehunks(struct hunk *l) { struct hunk *n; for (; l; l = n) { n = l->next; free(l); } } static PyObject *blocks(PyObject *self, PyObject *args) { PyObject *sa, *sb, *rl = NULL, *m; struct line *a, *b; struct hunk l, *h; int an, bn, count, pos = 0; if (!PyArg_ParseTuple(args, "SS:bdiff", &sa, &sb)) return NULL; an = splitlines(PyBytes_AsString(sa), PyBytes_Size(sa), &a); bn = splitlines(PyBytes_AsString(sb), PyBytes_Size(sb), &b); if (!a || !b) goto nomem; l.next = NULL; count = diff(a, an, b, bn, &l); if (count < 0) goto nomem; rl = PyList_New(count); if (!rl) goto nomem; for (h = l.next; h; h = h->next) { m = Py_BuildValue("iiii", h->a1, h->a2, h->b1, h->b2); PyList_SetItem(rl, pos, m); pos++; } nomem: free(a); free(b); freehunks(l.next); return rl ? rl : PyErr_NoMemory(); } static PyObject *bdiff(PyObject *self, PyObject *args) { char *sa, *sb, *rb; PyObject *result = NULL; struct line *al, *bl; struct hunk l, *h; int an, bn, count; Py_ssize_t len = 0, la, lb; PyThreadState *_save; if (!PyArg_ParseTuple(args, "s#s#:bdiff", &sa, &la, &sb, &lb)) return NULL; if (la > UINT_MAX || lb > UINT_MAX) { PyErr_SetString(PyExc_ValueError, "bdiff inputs too large"); return NULL; } _save = PyEval_SaveThread(); an = splitlines(sa, la, &al); bn = splitlines(sb, lb, &bl); if (!al || !bl) goto nomem; l.next = NULL; count = diff(al, an, bl, bn, &l); if (count < 0) goto nomem; /* calculate length of output */ la = lb = 0; for (h = l.next; h; h = h->next) { if (h->a1 != la || h->b1 != lb) len += 12 + bl[h->b1].l - bl[lb].l; la = h->a2; lb = h->b2; } PyEval_RestoreThread(_save); _save = NULL; result = PyBytes_FromStringAndSize(NULL, len); if (!result) goto nomem; /* build binary patch */ rb = PyBytes_AsString(result); la = lb = 0; for (h = l.next; h; h = h->next) { if (h->a1 != la || h->b1 != lb) { len = bl[h->b1].l - bl[lb].l; putbe32((uint32_t)(al[la].l - al->l), rb); putbe32((uint32_t)(al[h->a1].l - al->l), rb + 4); putbe32((uint32_t)len, rb + 8); memcpy(rb + 12, bl[lb].l, len); rb += 12 + len; } la = h->a2; lb = h->b2; } nomem: if (_save) PyEval_RestoreThread(_save); free(al); free(bl); freehunks(l.next); return result ? result : PyErr_NoMemory(); } /* * If allws != 0, remove all whitespace (' ', \t and \r). Otherwise, * reduce whitespace sequences to a single space and trim remaining whitespace * from end of lines. */ static PyObject *fixws(PyObject *self, PyObject *args) { PyObject *s, *result = NULL; char allws, c; const char *r; Py_ssize_t i, rlen, wlen = 0; char *w; if (!PyArg_ParseTuple(args, "Sb:fixws", &s, &allws)) return NULL; r = PyBytes_AsString(s); rlen = PyBytes_Size(s); w = (char *)malloc(rlen ? rlen : 1); if (!w) goto nomem; for (i = 0; i != rlen; i++) { c = r[i]; if (c == ' ' || c == '\t' || c == '\r') { if (!allws && (wlen == 0 || w[wlen - 1] != ' ')) w[wlen++] = ' '; } else if (c == '\n' && !allws && wlen > 0 && w[wlen - 1] == ' ') { w[wlen - 1] = '\n'; } else { w[wlen++] = c; } } result = PyBytes_FromStringAndSize(w, wlen); nomem: free(w); return result ? result : PyErr_NoMemory(); } static char mdiff_doc[] = "Efficient binary diff."; static PyMethodDef methods[] = { {"bdiff", bdiff, METH_VARARGS, "calculate a binary diff\n"}, {"blocks", blocks, METH_VARARGS, "find a list of matching lines\n"}, {"fixws", fixws, METH_VARARGS, "normalize diff whitespaces\n"}, {NULL, NULL} }; #ifdef IS_PY3K static struct PyModuleDef bdiff_module = { PyModuleDef_HEAD_INIT, "bdiff", mdiff_doc, -1, methods }; PyMODINIT_FUNC PyInit_bdiff(void) { return PyModule_Create(&bdiff_module); } #else PyMODINIT_FUNC initbdiff(void) { Py_InitModule3("bdiff", methods, mdiff_doc); } #endif
596
./intellij-community/plugins/hg4idea/testData/bin/mercurial/diffhelpers.c
/* * diffhelpers.c - helper routines for mpatch * * Copyright 2007 Chris Mason <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License v2, incorporated herein by reference. */ #include <Python.h> #include <stdlib.h> #include <string.h> #include "util.h" static char diffhelpers_doc[] = "Efficient diff parsing"; static PyObject *diffhelpers_Error; /* fixup the last lines of a and b when the patch has no newline at eof */ static void _fix_newline(PyObject *hunk, PyObject *a, PyObject *b) { Py_ssize_t hunksz = PyList_Size(hunk); PyObject *s = PyList_GET_ITEM(hunk, hunksz-1); char *l = PyBytes_AsString(s); Py_ssize_t alen = PyList_Size(a); Py_ssize_t blen = PyList_Size(b); char c = l[0]; PyObject *hline; Py_ssize_t sz = PyBytes_GET_SIZE(s); if (sz > 1 && l[sz-2] == '\r') /* tolerate CRLF in last line */ sz -= 1; hline = PyBytes_FromStringAndSize(l, sz-1); if (c == ' ' || c == '+') { PyObject *rline = PyBytes_FromStringAndSize(l + 1, sz - 2); PyList_SetItem(b, blen-1, rline); } if (c == ' ' || c == '-') { Py_INCREF(hline); PyList_SetItem(a, alen-1, hline); } PyList_SetItem(hunk, hunksz-1, hline); } /* python callable form of _fix_newline */ static PyObject * fix_newline(PyObject *self, PyObject *args) { PyObject *hunk, *a, *b; if (!PyArg_ParseTuple(args, "OOO", &hunk, &a, &b)) return NULL; _fix_newline(hunk, a, b); return Py_BuildValue("l", 0); } #if (PY_VERSION_HEX < 0x02050000) static const char *addlines_format = "OOiiOO"; #else static const char *addlines_format = "OOnnOO"; #endif /* * read lines from fp into the hunk. The hunk is parsed into two arrays * a and b. a gets the old state of the text, b gets the new state * The control char from the hunk is saved when inserting into a, but not b * (for performance while deleting files) */ static PyObject * addlines(PyObject *self, PyObject *args) { PyObject *fp, *hunk, *a, *b, *x; Py_ssize_t i; Py_ssize_t lena, lenb; Py_ssize_t num; Py_ssize_t todoa, todob; char *s, c; PyObject *l; if (!PyArg_ParseTuple(args, addlines_format, &fp, &hunk, &lena, &lenb, &a, &b)) return NULL; while (1) { todoa = lena - PyList_Size(a); todob = lenb - PyList_Size(b); num = todoa > todob ? todoa : todob; if (num == 0) break; for (i = 0; i < num; i++) { x = PyFile_GetLine(fp, 0); s = PyBytes_AsString(x); c = *s; if (strcmp(s, "\\ No newline at end of file\n") == 0) { _fix_newline(hunk, a, b); continue; } if (c == '\n') { /* Some patches may be missing the control char * on empty lines. Supply a leading space. */ Py_DECREF(x); x = PyBytes_FromString(" \n"); } PyList_Append(hunk, x); if (c == '+') { l = PyBytes_FromString(s + 1); PyList_Append(b, l); Py_DECREF(l); } else if (c == '-') { PyList_Append(a, x); } else { l = PyBytes_FromString(s + 1); PyList_Append(b, l); Py_DECREF(l); PyList_Append(a, x); } Py_DECREF(x); } } return Py_BuildValue("l", 0); } /* * compare the lines in a with the lines in b. a is assumed to have * a control char at the start of each line, this char is ignored in the * compare */ static PyObject * testhunk(PyObject *self, PyObject *args) { PyObject *a, *b; long bstart; Py_ssize_t alen, blen; Py_ssize_t i; char *sa, *sb; if (!PyArg_ParseTuple(args, "OOl", &a, &b, &bstart)) return NULL; alen = PyList_Size(a); blen = PyList_Size(b); if (alen > blen - bstart || bstart < 0) { return Py_BuildValue("l", -1); } for (i = 0; i < alen; i++) { sa = PyBytes_AsString(PyList_GET_ITEM(a, i)); sb = PyBytes_AsString(PyList_GET_ITEM(b, i + bstart)); if (strcmp(sa + 1, sb) != 0) return Py_BuildValue("l", -1); } return Py_BuildValue("l", 0); } static PyMethodDef methods[] = { {"addlines", addlines, METH_VARARGS, "add lines to a hunk\n"}, {"fix_newline", fix_newline, METH_VARARGS, "fixup newline counters\n"}, {"testhunk", testhunk, METH_VARARGS, "test lines in a hunk\n"}, {NULL, NULL} }; #ifdef IS_PY3K static struct PyModuleDef diffhelpers_module = { PyModuleDef_HEAD_INIT, "diffhelpers", diffhelpers_doc, -1, methods }; PyMODINIT_FUNC PyInit_diffhelpers(void) { PyObject *m; m = PyModule_Create(&diffhelpers_module); if (m == NULL) return NULL; diffhelpers_Error = PyErr_NewException("diffhelpers.diffhelpersError", NULL, NULL); Py_INCREF(diffhelpers_Error); PyModule_AddObject(m, "diffhelpersError", diffhelpers_Error); return m; } #else PyMODINIT_FUNC initdiffhelpers(void) { Py_InitModule3("diffhelpers", methods, diffhelpers_doc); diffhelpers_Error = PyErr_NewException("diffhelpers.diffhelpersError", NULL, NULL); } #endif
597
./intellij-community/plugins/hg4idea/testData/bin/mercurial/pathencode.c
/* pathencode.c - efficient path name encoding Copyright 2012 Facebook This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ /* * An implementation of the name encoding scheme used by the fncache * store. The common case is of a path < 120 bytes long, which is * handled either in a single pass with no allocations or two passes * with a single allocation. For longer paths, multiple passes are * required. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <assert.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include "util.h" /* state machine for the fast path */ enum path_state { START, /* first byte of a path component */ A, /* "AUX" */ AU, THIRD, /* third of a 3-byte sequence, e.g. "AUX", "NUL" */ C, /* "CON" or "COMn" */ CO, COMLPT, /* "COM" or "LPT" */ COMLPTn, L, LP, N, NU, P, /* "PRN" */ PR, LDOT, /* leading '.' */ DOT, /* '.' in a non-leading position */ H, /* ".h" */ HGDI, /* ".hg", ".d", or ".i" */ SPACE, DEFAULT /* byte of a path component after the first */ }; /* state machine for dir-encoding */ enum dir_state { DDOT, DH, DHGDI, DDEFAULT }; static inline int inset(const uint32_t bitset[], char c) { return bitset[((uint8_t)c) >> 5] & (1 << (((uint8_t)c) & 31)); } static inline void charcopy(char *dest, Py_ssize_t *destlen, size_t destsize, char c) { if (dest) { assert(*destlen < destsize); dest[*destlen] = c; } (*destlen)++; } static inline void memcopy(char *dest, Py_ssize_t *destlen, size_t destsize, const void *src, Py_ssize_t len) { if (dest) { assert(*destlen + len < destsize); memcpy((void *)&dest[*destlen], src, len); } *destlen += len; } static inline void hexencode(char *dest, Py_ssize_t *destlen, size_t destsize, uint8_t c) { static const char hexdigit[] = "0123456789abcdef"; charcopy(dest, destlen, destsize, hexdigit[c >> 4]); charcopy(dest, destlen, destsize, hexdigit[c & 15]); } /* 3-byte escape: tilde followed by two hex digits */ static inline void escape3(char *dest, Py_ssize_t *destlen, size_t destsize, char c) { charcopy(dest, destlen, destsize, '~'); hexencode(dest, destlen, destsize, c); } static Py_ssize_t _encodedir(char *dest, size_t destsize, const char *src, Py_ssize_t len) { enum dir_state state = DDEFAULT; Py_ssize_t i = 0, destlen = 0; while (i < len) { switch (state) { case DDOT: switch (src[i]) { case 'd': case 'i': state = DHGDI; charcopy(dest, &destlen, destsize, src[i++]); break; case 'h': state = DH; charcopy(dest, &destlen, destsize, src[i++]); break; default: state = DDEFAULT; break; } break; case DH: if (src[i] == 'g') { state = DHGDI; charcopy(dest, &destlen, destsize, src[i++]); } else state = DDEFAULT; break; case DHGDI: if (src[i] == '/') { memcopy(dest, &destlen, destsize, ".hg", 3); charcopy(dest, &destlen, destsize, src[i++]); } state = DDEFAULT; break; case DDEFAULT: if (src[i] == '.') state = DDOT; charcopy(dest, &destlen, destsize, src[i++]); break; } } return destlen; } PyObject *encodedir(PyObject *self, PyObject *args) { Py_ssize_t len, newlen; PyObject *pathobj, *newobj; char *path; if (!PyArg_ParseTuple(args, "O:encodedir", &pathobj)) return NULL; if (PyString_AsStringAndSize(pathobj, &path, &len) == -1) { PyErr_SetString(PyExc_TypeError, "expected a string"); return NULL; } newlen = len ? _encodedir(NULL, 0, path, len + 1) : 1; if (newlen == len + 1) { Py_INCREF(pathobj); return pathobj; } newobj = PyString_FromStringAndSize(NULL, newlen); if (newobj) { PyString_GET_SIZE(newobj)--; _encodedir(PyString_AS_STRING(newobj), newlen, path, len + 1); } return newobj; } static Py_ssize_t _encode(const uint32_t twobytes[8], const uint32_t onebyte[8], char *dest, Py_ssize_t destlen, size_t destsize, const char *src, Py_ssize_t len, int encodedir) { enum path_state state = START; Py_ssize_t i = 0; /* * Python strings end with a zero byte, which we use as a * terminal token as they are not valid inside path names. */ while (i < len) { switch (state) { case START: switch (src[i]) { case '/': charcopy(dest, &destlen, destsize, src[i++]); break; case '.': state = LDOT; escape3(dest, &destlen, destsize, src[i++]); break; case ' ': state = DEFAULT; escape3(dest, &destlen, destsize, src[i++]); break; case 'a': state = A; charcopy(dest, &destlen, destsize, src[i++]); break; case 'c': state = C; charcopy(dest, &destlen, destsize, src[i++]); break; case 'l': state = L; charcopy(dest, &destlen, destsize, src[i++]); break; case 'n': state = N; charcopy(dest, &destlen, destsize, src[i++]); break; case 'p': state = P; charcopy(dest, &destlen, destsize, src[i++]); break; default: state = DEFAULT; break; } break; case A: if (src[i] == 'u') { state = AU; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case AU: if (src[i] == 'x') { state = THIRD; i++; } else state = DEFAULT; break; case THIRD: state = DEFAULT; switch (src[i]) { case '.': case '/': case '\0': escape3(dest, &destlen, destsize, src[i - 1]); break; default: i--; break; } break; case C: if (src[i] == 'o') { state = CO; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case CO: if (src[i] == 'm') { state = COMLPT; i++; } else if (src[i] == 'n') { state = THIRD; i++; } else state = DEFAULT; break; case COMLPT: switch (src[i]) { case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': state = COMLPTn; i++; break; default: state = DEFAULT; charcopy(dest, &destlen, destsize, src[i - 1]); break; } break; case COMLPTn: state = DEFAULT; switch (src[i]) { case '.': case '/': case '\0': escape3(dest, &destlen, destsize, src[i - 2]); charcopy(dest, &destlen, destsize, src[i - 1]); break; default: memcopy(dest, &destlen, destsize, &src[i - 2], 2); break; } break; case L: if (src[i] == 'p') { state = LP; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case LP: if (src[i] == 't') { state = COMLPT; i++; } else state = DEFAULT; break; case N: if (src[i] == 'u') { state = NU; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case NU: if (src[i] == 'l') { state = THIRD; i++; } else state = DEFAULT; break; case P: if (src[i] == 'r') { state = PR; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case PR: if (src[i] == 'n') { state = THIRD; i++; } else state = DEFAULT; break; case LDOT: switch (src[i]) { case 'd': case 'i': state = HGDI; charcopy(dest, &destlen, destsize, src[i++]); break; case 'h': state = H; charcopy(dest, &destlen, destsize, src[i++]); break; default: state = DEFAULT; break; } break; case DOT: switch (src[i]) { case '/': case '\0': state = START; memcopy(dest, &destlen, destsize, "~2e", 3); charcopy(dest, &destlen, destsize, src[i++]); break; case 'd': case 'i': state = HGDI; charcopy(dest, &destlen, destsize, '.'); charcopy(dest, &destlen, destsize, src[i++]); break; case 'h': state = H; memcopy(dest, &destlen, destsize, ".h", 2); i++; break; default: state = DEFAULT; charcopy(dest, &destlen, destsize, '.'); break; } break; case H: if (src[i] == 'g') { state = HGDI; charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case HGDI: if (src[i] == '/') { state = START; if (encodedir) memcopy(dest, &destlen, destsize, ".hg", 3); charcopy(dest, &destlen, destsize, src[i++]); } else state = DEFAULT; break; case SPACE: switch (src[i]) { case '/': case '\0': state = START; memcopy(dest, &destlen, destsize, "~20", 3); charcopy(dest, &destlen, destsize, src[i++]); break; default: state = DEFAULT; charcopy(dest, &destlen, destsize, ' '); break; } break; case DEFAULT: while (inset(onebyte, src[i])) { charcopy(dest, &destlen, destsize, src[i++]); if (i == len) goto done; } switch (src[i]) { case '.': state = DOT; i++; break; case ' ': state = SPACE; i++; break; case '/': state = START; charcopy(dest, &destlen, destsize, '/'); i++; break; default: if (inset(onebyte, src[i])) { do { charcopy(dest, &destlen, destsize, src[i++]); } while (i < len && inset(onebyte, src[i])); } else if (inset(twobytes, src[i])) { char c = src[i++]; charcopy(dest, &destlen, destsize, '_'); charcopy(dest, &destlen, destsize, c == '_' ? '_' : c + 32); } else escape3(dest, &destlen, destsize, src[i++]); break; } break; } } done: return destlen; } static Py_ssize_t basicencode(char *dest, size_t destsize, const char *src, Py_ssize_t len) { static const uint32_t twobytes[8] = { 0, 0, 0x87fffffe }; static const uint32_t onebyte[8] = { 1, 0x2bff3bfa, 0x68000001, 0x2fffffff, }; Py_ssize_t destlen = 0; return _encode(twobytes, onebyte, dest, destlen, destsize, src, len, 1); } static const Py_ssize_t maxstorepathlen = 120; static Py_ssize_t _lowerencode(char *dest, size_t destsize, const char *src, Py_ssize_t len) { static const uint32_t onebyte[8] = { 1, 0x2bfffbfb, 0xe8000001, 0x2fffffff }; static const uint32_t lower[8] = { 0, 0, 0x7fffffe }; Py_ssize_t i, destlen = 0; for (i = 0; i < len; i++) { if (inset(onebyte, src[i])) charcopy(dest, &destlen, destsize, src[i]); else if (inset(lower, src[i])) charcopy(dest, &destlen, destsize, src[i] + 32); else escape3(dest, &destlen, destsize, src[i]); } return destlen; } PyObject *lowerencode(PyObject *self, PyObject *args) { char *path; Py_ssize_t len, newlen; PyObject *ret; if (!PyArg_ParseTuple(args, "s#:lowerencode", &path, &len)) return NULL; newlen = _lowerencode(NULL, 0, path, len); ret = PyString_FromStringAndSize(NULL, newlen); if (ret) newlen = _lowerencode(PyString_AS_STRING(ret), newlen, path, len); return ret; } /* See store.py:_auxencode for a description. */ static Py_ssize_t auxencode(char *dest, size_t destsize, const char *src, Py_ssize_t len) { static const uint32_t twobytes[8]; static const uint32_t onebyte[8] = { ~0, 0xffff3ffe, ~0, ~0, ~0, ~0, ~0, ~0, }; return _encode(twobytes, onebyte, dest, 0, destsize, src, len, 0); } static PyObject *hashmangle(const char *src, Py_ssize_t len, const char sha[20]) { static const Py_ssize_t dirprefixlen = 8; static const Py_ssize_t maxshortdirslen = 68; char *dest; PyObject *ret; Py_ssize_t i, d, p, lastslash = len - 1, lastdot = -1; Py_ssize_t destsize, destlen = 0, slop, used; while (lastslash >= 0 && src[lastslash] != '/') { if (src[lastslash] == '.' && lastdot == -1) lastdot = lastslash; lastslash--; } #if 0 /* All paths should end in a suffix of ".i" or ".d". Unfortunately, the file names in test-hybridencode.py violate this rule. */ if (lastdot != len - 3) { PyErr_SetString(PyExc_ValueError, "suffix missing or wrong length"); return NULL; } #endif /* If src contains a suffix, we will append it to the end of the new string, so make room. */ destsize = 120; if (lastdot >= 0) destsize += len - lastdot - 1; ret = PyString_FromStringAndSize(NULL, destsize); if (ret == NULL) return NULL; dest = PyString_AS_STRING(ret); memcopy(dest, &destlen, destsize, "dh/", 3); /* Copy up to dirprefixlen bytes of each path component, up to a limit of maxshortdirslen bytes. */ for (i = d = p = 0; i < lastslash; i++, p++) { if (src[i] == '/') { char d = dest[destlen - 1]; /* After truncation, a directory name may end in a space or dot, which are unportable. */ if (d == '.' || d == ' ') dest[destlen - 1] = '_'; if (destlen > maxshortdirslen) break; charcopy(dest, &destlen, destsize, src[i]); p = -1; } else if (p < dirprefixlen) charcopy(dest, &destlen, destsize, src[i]); } /* Rewind to just before the last slash copied. */ if (destlen > maxshortdirslen + 3) do { destlen--; } while (destlen > 0 && dest[destlen] != '/'); if (destlen > 3) { if (lastslash > 0) { char d = dest[destlen - 1]; /* The last directory component may be truncated, so make it safe. */ if (d == '.' || d == ' ') dest[destlen - 1] = '_'; } charcopy(dest, &destlen, destsize, '/'); } /* Add a prefix of the original file's name. Its length depends on the number of bytes left after accounting for hash and suffix. */ used = destlen + 40; if (lastdot >= 0) used += len - lastdot - 1; slop = maxstorepathlen - used; if (slop > 0) { Py_ssize_t basenamelen = lastslash >= 0 ? len - lastslash - 2 : len - 1; if (basenamelen > slop) basenamelen = slop; if (basenamelen > 0) memcopy(dest, &destlen, destsize, &src[lastslash + 1], basenamelen); } /* Add hash and suffix. */ for (i = 0; i < 20; i++) hexencode(dest, &destlen, destsize, sha[i]); if (lastdot >= 0) memcopy(dest, &destlen, destsize, &src[lastdot], len - lastdot - 1); PyString_GET_SIZE(ret) = destlen; return ret; } /* * Avoiding a trip through Python would improve performance by 50%, * but we don't encounter enough long names to be worth the code. */ static int sha1hash(char hash[20], const char *str, Py_ssize_t len) { static PyObject *shafunc; PyObject *shaobj, *hashobj; if (shafunc == NULL) { PyObject *util, *name = PyString_FromString("mercurial.util"); if (name == NULL) return -1; util = PyImport_Import(name); Py_DECREF(name); if (util == NULL) { PyErr_SetString(PyExc_ImportError, "mercurial.util"); return -1; } shafunc = PyObject_GetAttrString(util, "sha1"); Py_DECREF(util); if (shafunc == NULL) { PyErr_SetString(PyExc_AttributeError, "module 'mercurial.util' has no " "attribute 'sha1'"); return -1; } } shaobj = PyObject_CallFunction(shafunc, "s#", str, len); if (shaobj == NULL) return -1; hashobj = PyObject_CallMethod(shaobj, "digest", ""); Py_DECREF(shaobj); if (!PyString_Check(hashobj) || PyString_GET_SIZE(hashobj) != 20) { PyErr_SetString(PyExc_TypeError, "result of digest is not a 20-byte hash"); Py_DECREF(hashobj); return -1; } memcpy(hash, PyString_AS_STRING(hashobj), 20); Py_DECREF(hashobj); return 0; } #define MAXENCODE 4096 * 4 static PyObject *hashencode(const char *src, Py_ssize_t len) { char dired[MAXENCODE]; char lowered[MAXENCODE]; char auxed[MAXENCODE]; Py_ssize_t dirlen, lowerlen, auxlen, baselen; char sha[20]; baselen = (len - 5) * 3; if (baselen >= MAXENCODE) { PyErr_SetString(PyExc_ValueError, "string too long"); return NULL; } dirlen = _encodedir(dired, baselen, src, len); if (sha1hash(sha, dired, dirlen - 1) == -1) return NULL; lowerlen = _lowerencode(lowered, baselen, dired + 5, dirlen - 5); auxlen = auxencode(auxed, baselen, lowered, lowerlen); return hashmangle(auxed, auxlen, sha); } PyObject *pathencode(PyObject *self, PyObject *args) { Py_ssize_t len, newlen; PyObject *pathobj, *newobj; char *path; if (!PyArg_ParseTuple(args, "O:pathencode", &pathobj)) return NULL; if (PyString_AsStringAndSize(pathobj, &path, &len) == -1) { PyErr_SetString(PyExc_TypeError, "expected a string"); return NULL; } if (len > maxstorepathlen) newlen = maxstorepathlen + 2; else newlen = len ? basicencode(NULL, 0, path, len + 1) : 1; if (newlen <= maxstorepathlen + 1) { if (newlen == len + 1) { Py_INCREF(pathobj); return pathobj; } newobj = PyString_FromStringAndSize(NULL, newlen); if (newobj) { PyString_GET_SIZE(newobj)--; basicencode(PyString_AS_STRING(newobj), newlen, path, len + 1); } } else newobj = hashencode(path, len + 1); return newobj; }
598
./intellij-community/plugins/hg4idea/testData/bin/mercurial/parsers.c
/* parsers.c - efficient content parsing Copyright 2008 Matt Mackall <[email protected]> and others This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #include <Python.h> #include <ctype.h> #include <stddef.h> #include <string.h> #include "util.h" static inline int hexdigit(const char *p, Py_ssize_t off) { char c = p[off]; if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; PyErr_SetString(PyExc_ValueError, "input contains non-hex character"); return 0; } /* * Turn a hex-encoded string into binary. */ static PyObject *unhexlify(const char *str, int len) { PyObject *ret; char *d; int i; ret = PyBytes_FromStringAndSize(NULL, len / 2); if (!ret) return NULL; d = PyBytes_AsString(ret); for (i = 0; i < len;) { int hi = hexdigit(str, i++); int lo = hexdigit(str, i++); *d++ = (hi << 4) | lo; } return ret; } /* * This code assumes that a manifest is stitched together with newline * ('\n') characters. */ static PyObject *parse_manifest(PyObject *self, PyObject *args) { PyObject *mfdict, *fdict; char *str, *cur, *start, *zero; int len; if (!PyArg_ParseTuple(args, "O!O!s#:parse_manifest", &PyDict_Type, &mfdict, &PyDict_Type, &fdict, &str, &len)) goto quit; for (start = cur = str, zero = NULL; cur < str + len; cur++) { PyObject *file = NULL, *node = NULL; PyObject *flags = NULL; ptrdiff_t nlen; if (!*cur) { zero = cur; continue; } else if (*cur != '\n') continue; if (!zero) { PyErr_SetString(PyExc_ValueError, "manifest entry has no separator"); goto quit; } file = PyBytes_FromStringAndSize(start, zero - start); if (!file) goto bail; nlen = cur - zero - 1; node = unhexlify(zero + 1, nlen > 40 ? 40 : (int)nlen); if (!node) goto bail; if (nlen > 40) { flags = PyBytes_FromStringAndSize(zero + 41, nlen - 40); if (!flags) goto bail; if (PyDict_SetItem(fdict, file, flags) == -1) goto bail; } if (PyDict_SetItem(mfdict, file, node) == -1) goto bail; start = cur + 1; zero = NULL; Py_XDECREF(flags); Py_XDECREF(node); Py_XDECREF(file); continue; bail: Py_XDECREF(flags); Py_XDECREF(node); Py_XDECREF(file); goto quit; } if (len > 0 && *(cur - 1) != '\n') { PyErr_SetString(PyExc_ValueError, "manifest contains trailing garbage"); goto quit; } Py_INCREF(Py_None); return Py_None; quit: return NULL; } static PyObject *parse_dirstate(PyObject *self, PyObject *args) { PyObject *dmap, *cmap, *parents = NULL, *ret = NULL; PyObject *fname = NULL, *cname = NULL, *entry = NULL; char *str, *cur, *end, *cpos; int state, mode, size, mtime; unsigned int flen; int len; if (!PyArg_ParseTuple(args, "O!O!s#:parse_dirstate", &PyDict_Type, &dmap, &PyDict_Type, &cmap, &str, &len)) goto quit; /* read parents */ if (len < 40) goto quit; parents = Py_BuildValue("s#s#", str, 20, str + 20, 20); if (!parents) goto quit; /* read filenames */ cur = str + 40; end = str + len; while (cur < end - 17) { /* unpack header */ state = *cur; mode = getbe32(cur + 1); size = getbe32(cur + 5); mtime = getbe32(cur + 9); flen = getbe32(cur + 13); cur += 17; if (cur + flen > end || cur + flen < cur) { PyErr_SetString(PyExc_ValueError, "overflow in dirstate"); goto quit; } entry = Py_BuildValue("ciii", state, mode, size, mtime); if (!entry) goto quit; PyObject_GC_UnTrack(entry); /* don't waste time with this */ cpos = memchr(cur, 0, flen); if (cpos) { fname = PyBytes_FromStringAndSize(cur, cpos - cur); cname = PyBytes_FromStringAndSize(cpos + 1, flen - (cpos - cur) - 1); if (!fname || !cname || PyDict_SetItem(cmap, fname, cname) == -1 || PyDict_SetItem(dmap, fname, entry) == -1) goto quit; Py_DECREF(cname); } else { fname = PyBytes_FromStringAndSize(cur, flen); if (!fname || PyDict_SetItem(dmap, fname, entry) == -1) goto quit; } cur += flen; Py_DECREF(fname); Py_DECREF(entry); fname = cname = entry = NULL; } ret = parents; Py_INCREF(ret); quit: Py_XDECREF(fname); Py_XDECREF(cname); Py_XDECREF(entry); Py_XDECREF(parents); return ret; } static inline int getintat(PyObject *tuple, int off, uint32_t *v) { PyObject *o = PyTuple_GET_ITEM(tuple, off); long val; if (PyInt_Check(o)) val = PyInt_AS_LONG(o); else if (PyLong_Check(o)) { val = PyLong_AsLong(o); if (val == -1 && PyErr_Occurred()) return -1; } else { PyErr_SetString(PyExc_TypeError, "expected an int or long"); return -1; } if (LONG_MAX > INT_MAX && (val > INT_MAX || val < INT_MIN)) { PyErr_SetString(PyExc_OverflowError, "Python value to large to convert to uint32_t"); return -1; } *v = (uint32_t)val; return 0; } static PyObject *dirstate_unset; /* * Efficiently pack a dirstate object into its on-disk format. */ static PyObject *pack_dirstate(PyObject *self, PyObject *args) { PyObject *packobj = NULL; PyObject *map, *copymap, *pl; Py_ssize_t nbytes, pos, l; PyObject *k, *v, *pn; char *p, *s; double now; if (!PyArg_ParseTuple(args, "O!O!Od:pack_dirstate", &PyDict_Type, &map, &PyDict_Type, &copymap, &pl, &now)) return NULL; if (!PySequence_Check(pl) || PySequence_Size(pl) != 2) { PyErr_SetString(PyExc_TypeError, "expected 2-element sequence"); return NULL; } /* Figure out how much we need to allocate. */ for (nbytes = 40, pos = 0; PyDict_Next(map, &pos, &k, &v);) { PyObject *c; if (!PyString_Check(k)) { PyErr_SetString(PyExc_TypeError, "expected string key"); goto bail; } nbytes += PyString_GET_SIZE(k) + 17; c = PyDict_GetItem(copymap, k); if (c) { if (!PyString_Check(c)) { PyErr_SetString(PyExc_TypeError, "expected string key"); goto bail; } nbytes += PyString_GET_SIZE(c) + 1; } } packobj = PyString_FromStringAndSize(NULL, nbytes); if (packobj == NULL) goto bail; p = PyString_AS_STRING(packobj); pn = PySequence_ITEM(pl, 0); if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) { PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash"); goto bail; } memcpy(p, s, l); p += 20; pn = PySequence_ITEM(pl, 1); if (PyString_AsStringAndSize(pn, &s, &l) == -1 || l != 20) { PyErr_SetString(PyExc_TypeError, "expected a 20-byte hash"); goto bail; } memcpy(p, s, l); p += 20; for (pos = 0; PyDict_Next(map, &pos, &k, &v); ) { uint32_t mode, size, mtime; Py_ssize_t len, l; PyObject *o; char *s, *t; if (!PyTuple_Check(v) || PyTuple_GET_SIZE(v) != 4) { PyErr_SetString(PyExc_TypeError, "expected a 4-tuple"); goto bail; } o = PyTuple_GET_ITEM(v, 0); if (PyString_AsStringAndSize(o, &s, &l) == -1 || l != 1) { PyErr_SetString(PyExc_TypeError, "expected one byte"); goto bail; } *p++ = *s; if (getintat(v, 1, &mode) == -1) goto bail; if (getintat(v, 2, &size) == -1) goto bail; if (getintat(v, 3, &mtime) == -1) goto bail; if (*s == 'n' && mtime == (uint32_t)now) { /* See pure/parsers.py:pack_dirstate for why we do * this. */ if (PyDict_SetItem(map, k, dirstate_unset) == -1) goto bail; mode = 0, size = -1, mtime = -1; } putbe32(mode, p); putbe32(size, p + 4); putbe32(mtime, p + 8); t = p + 12; p += 16; len = PyString_GET_SIZE(k); memcpy(p, PyString_AS_STRING(k), len); p += len; o = PyDict_GetItem(copymap, k); if (o) { *p++ = '\0'; l = PyString_GET_SIZE(o); memcpy(p, PyString_AS_STRING(o), l); p += l; len += l + 1; } putbe32((uint32_t)len, t); } pos = p - PyString_AS_STRING(packobj); if (pos != nbytes) { PyErr_Format(PyExc_SystemError, "bad dirstate size: %ld != %ld", (long)pos, (long)nbytes); goto bail; } return packobj; bail: Py_XDECREF(packobj); return NULL; } /* * A base-16 trie for fast node->rev mapping. * * Positive value is index of the next node in the trie * Negative value is a leaf: -(rev + 1) * Zero is empty */ typedef struct { int children[16]; } nodetree; /* * This class has two behaviours. * * When used in a list-like way (with integer keys), we decode an * entry in a RevlogNG index file on demand. Our last entry is a * sentinel, always a nullid. We have limited support for * integer-keyed insert and delete, only at elements right before the * sentinel. * * With string keys, we lazily perform a reverse mapping from node to * rev, using a base-16 trie. */ typedef struct { PyObject_HEAD /* Type-specific fields go here. */ PyObject *data; /* raw bytes of index */ PyObject **cache; /* cached tuples */ const char **offsets; /* populated on demand */ Py_ssize_t raw_length; /* original number of elements */ Py_ssize_t length; /* current number of elements */ PyObject *added; /* populated on demand */ PyObject *headrevs; /* cache, invalidated on changes */ nodetree *nt; /* base-16 trie */ int ntlength; /* # nodes in use */ int ntcapacity; /* # nodes allocated */ int ntdepth; /* maximum depth of tree */ int ntsplits; /* # splits performed */ int ntrev; /* last rev scanned */ int ntlookups; /* # lookups */ int ntmisses; /* # lookups that miss the cache */ int inlined; } indexObject; static Py_ssize_t index_length(const indexObject *self) { if (self->added == NULL) return self->length; return self->length + PyList_GET_SIZE(self->added); } static PyObject *nullentry; static const char nullid[20]; static long inline_scan(indexObject *self, const char **offsets); #if LONG_MAX == 0x7fffffffL static char *tuple_format = "Kiiiiiis#"; #else static char *tuple_format = "kiiiiiis#"; #endif /* A RevlogNG v1 index entry is 64 bytes long. */ static const long v1_hdrsize = 64; /* * Return a pointer to the beginning of a RevlogNG record. */ static const char *index_deref(indexObject *self, Py_ssize_t pos) { if (self->inlined && pos > 0) { if (self->offsets == NULL) { self->offsets = malloc(self->raw_length * sizeof(*self->offsets)); if (self->offsets == NULL) return (const char *)PyErr_NoMemory(); inline_scan(self, self->offsets); } return self->offsets[pos]; } return PyString_AS_STRING(self->data) + pos * v1_hdrsize; } /* * RevlogNG format (all in big endian, data may be inlined): * 6 bytes: offset * 2 bytes: flags * 4 bytes: compressed length * 4 bytes: uncompressed length * 4 bytes: base revision * 4 bytes: link revision * 4 bytes: parent 1 revision * 4 bytes: parent 2 revision * 32 bytes: nodeid (only 20 bytes used) */ static PyObject *index_get(indexObject *self, Py_ssize_t pos) { uint64_t offset_flags; int comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2; const char *c_node_id; const char *data; Py_ssize_t length = index_length(self); PyObject *entry; if (pos < 0) pos += length; if (pos < 0 || pos >= length) { PyErr_SetString(PyExc_IndexError, "revlog index out of range"); return NULL; } if (pos == length - 1) { Py_INCREF(nullentry); return nullentry; } if (pos >= self->length - 1) { PyObject *obj; obj = PyList_GET_ITEM(self->added, pos - self->length + 1); Py_INCREF(obj); return obj; } if (self->cache) { if (self->cache[pos]) { Py_INCREF(self->cache[pos]); return self->cache[pos]; } } else { self->cache = calloc(self->raw_length, sizeof(PyObject *)); if (self->cache == NULL) return PyErr_NoMemory(); } data = index_deref(self, pos); if (data == NULL) return NULL; offset_flags = getbe32(data + 4); if (pos == 0) /* mask out version number for the first entry */ offset_flags &= 0xFFFF; else { uint32_t offset_high = getbe32(data); offset_flags |= ((uint64_t)offset_high) << 32; } comp_len = getbe32(data + 8); uncomp_len = getbe32(data + 12); base_rev = getbe32(data + 16); link_rev = getbe32(data + 20); parent_1 = getbe32(data + 24); parent_2 = getbe32(data + 28); c_node_id = data + 32; entry = Py_BuildValue(tuple_format, offset_flags, comp_len, uncomp_len, base_rev, link_rev, parent_1, parent_2, c_node_id, 20); if (entry) PyObject_GC_UnTrack(entry); self->cache[pos] = entry; Py_INCREF(entry); return entry; } /* * Return the 20-byte SHA of the node corresponding to the given rev. */ static const char *index_node(indexObject *self, Py_ssize_t pos) { Py_ssize_t length = index_length(self); const char *data; if (pos == length - 1 || pos == INT_MAX) return nullid; if (pos >= length) return NULL; if (pos >= self->length - 1) { PyObject *tuple, *str; tuple = PyList_GET_ITEM(self->added, pos - self->length + 1); str = PyTuple_GetItem(tuple, 7); return str ? PyString_AS_STRING(str) : NULL; } data = index_deref(self, pos); return data ? data + 32 : NULL; } static int nt_insert(indexObject *self, const char *node, int rev); static int node_check(PyObject *obj, char **node, Py_ssize_t *nodelen) { if (PyString_AsStringAndSize(obj, node, nodelen) == -1) return -1; if (*nodelen == 20) return 0; PyErr_SetString(PyExc_ValueError, "20-byte hash required"); return -1; } static PyObject *index_insert(indexObject *self, PyObject *args) { PyObject *obj; char *node; long offset; Py_ssize_t len, nodelen; if (!PyArg_ParseTuple(args, "lO", &offset, &obj)) return NULL; if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 8) { PyErr_SetString(PyExc_TypeError, "8-tuple required"); return NULL; } if (node_check(PyTuple_GET_ITEM(obj, 7), &node, &nodelen) == -1) return NULL; len = index_length(self); if (offset < 0) offset += len; if (offset != len - 1) { PyErr_SetString(PyExc_IndexError, "insert only supported at index -1"); return NULL; } if (offset > INT_MAX) { PyErr_SetString(PyExc_ValueError, "currently only 2**31 revs supported"); return NULL; } if (self->added == NULL) { self->added = PyList_New(0); if (self->added == NULL) return NULL; } if (PyList_Append(self->added, obj) == -1) return NULL; if (self->nt) nt_insert(self, node, (int)offset); Py_CLEAR(self->headrevs); Py_RETURN_NONE; } static void _index_clearcaches(indexObject *self) { if (self->cache) { Py_ssize_t i; for (i = 0; i < self->raw_length; i++) Py_CLEAR(self->cache[i]); free(self->cache); self->cache = NULL; } if (self->offsets) { free(self->offsets); self->offsets = NULL; } if (self->nt) { free(self->nt); self->nt = NULL; } Py_CLEAR(self->headrevs); } static PyObject *index_clearcaches(indexObject *self) { _index_clearcaches(self); self->ntlength = self->ntcapacity = 0; self->ntdepth = self->ntsplits = 0; self->ntrev = -1; self->ntlookups = self->ntmisses = 0; Py_RETURN_NONE; } static PyObject *index_stats(indexObject *self) { PyObject *obj = PyDict_New(); if (obj == NULL) return NULL; #define istat(__n, __d) \ if (PyDict_SetItemString(obj, __d, PyInt_FromSsize_t(self->__n)) == -1) \ goto bail; if (self->added) { Py_ssize_t len = PyList_GET_SIZE(self->added); if (PyDict_SetItemString(obj, "index entries added", PyInt_FromSsize_t(len)) == -1) goto bail; } if (self->raw_length != self->length - 1) istat(raw_length, "revs on disk"); istat(length, "revs in memory"); istat(ntcapacity, "node trie capacity"); istat(ntdepth, "node trie depth"); istat(ntlength, "node trie count"); istat(ntlookups, "node trie lookups"); istat(ntmisses, "node trie misses"); istat(ntrev, "node trie last rev scanned"); istat(ntsplits, "node trie splits"); #undef istat return obj; bail: Py_XDECREF(obj); return NULL; } /* * When we cache a list, we want to be sure the caller can't mutate * the cached copy. */ static PyObject *list_copy(PyObject *list) { Py_ssize_t len = PyList_GET_SIZE(list); PyObject *newlist = PyList_New(len); Py_ssize_t i; if (newlist == NULL) return NULL; for (i = 0; i < len; i++) { PyObject *obj = PyList_GET_ITEM(list, i); Py_INCREF(obj); PyList_SET_ITEM(newlist, i, obj); } return newlist; } static PyObject *index_headrevs(indexObject *self) { Py_ssize_t i, len, addlen; char *nothead = NULL; PyObject *heads; if (self->headrevs) return list_copy(self->headrevs); len = index_length(self) - 1; heads = PyList_New(0); if (heads == NULL) goto bail; if (len == 0) { PyObject *nullid = PyInt_FromLong(-1); if (nullid == NULL || PyList_Append(heads, nullid) == -1) { Py_XDECREF(nullid); goto bail; } goto done; } nothead = calloc(len, 1); if (nothead == NULL) goto bail; for (i = 0; i < self->raw_length; i++) { const char *data = index_deref(self, i); int parent_1 = getbe32(data + 24); int parent_2 = getbe32(data + 28); if (parent_1 >= 0) nothead[parent_1] = 1; if (parent_2 >= 0) nothead[parent_2] = 1; } addlen = self->added ? PyList_GET_SIZE(self->added) : 0; for (i = 0; i < addlen; i++) { PyObject *rev = PyList_GET_ITEM(self->added, i); PyObject *p1 = PyTuple_GET_ITEM(rev, 5); PyObject *p2 = PyTuple_GET_ITEM(rev, 6); long parent_1, parent_2; if (!PyInt_Check(p1) || !PyInt_Check(p2)) { PyErr_SetString(PyExc_TypeError, "revlog parents are invalid"); goto bail; } parent_1 = PyInt_AS_LONG(p1); parent_2 = PyInt_AS_LONG(p2); if (parent_1 >= 0) nothead[parent_1] = 1; if (parent_2 >= 0) nothead[parent_2] = 1; } for (i = 0; i < len; i++) { PyObject *head; if (nothead[i]) continue; head = PyInt_FromLong(i); if (head == NULL || PyList_Append(heads, head) == -1) { Py_XDECREF(head); goto bail; } } done: self->headrevs = heads; free(nothead); return list_copy(self->headrevs); bail: Py_XDECREF(heads); free(nothead); return NULL; } static inline int nt_level(const char *node, Py_ssize_t level) { int v = node[level>>1]; if (!(level & 1)) v >>= 4; return v & 0xf; } /* * Return values: * * -4: match is ambiguous (multiple candidates) * -2: not found * rest: valid rev */ static int nt_find(indexObject *self, const char *node, Py_ssize_t nodelen, int hex) { int (*getnybble)(const char *, Py_ssize_t) = hex ? hexdigit : nt_level; int level, maxlevel, off; if (nodelen == 20 && node[0] == '\0' && memcmp(node, nullid, 20) == 0) return -1; if (self->nt == NULL) return -2; if (hex) maxlevel = nodelen > 40 ? 40 : (int)nodelen; else maxlevel = nodelen > 20 ? 40 : ((int)nodelen * 2); for (level = off = 0; level < maxlevel; level++) { int k = getnybble(node, level); nodetree *n = &self->nt[off]; int v = n->children[k]; if (v < 0) { const char *n; Py_ssize_t i; v = -v - 1; n = index_node(self, v); if (n == NULL) return -2; for (i = level; i < maxlevel; i++) if (getnybble(node, i) != nt_level(n, i)) return -2; return v; } if (v == 0) return -2; off = v; } /* multiple matches against an ambiguous prefix */ return -4; } static int nt_new(indexObject *self) { if (self->ntlength == self->ntcapacity) { self->ntcapacity *= 2; self->nt = realloc(self->nt, self->ntcapacity * sizeof(nodetree)); if (self->nt == NULL) { PyErr_SetString(PyExc_MemoryError, "out of memory"); return -1; } memset(&self->nt[self->ntlength], 0, sizeof(nodetree) * (self->ntcapacity - self->ntlength)); } return self->ntlength++; } static int nt_insert(indexObject *self, const char *node, int rev) { int level = 0; int off = 0; while (level < 40) { int k = nt_level(node, level); nodetree *n; int v; n = &self->nt[off]; v = n->children[k]; if (v == 0) { n->children[k] = -rev - 1; return 0; } if (v < 0) { const char *oldnode = index_node(self, -v - 1); int noff; if (!oldnode || !memcmp(oldnode, node, 20)) { n->children[k] = -rev - 1; return 0; } noff = nt_new(self); if (noff == -1) return -1; /* self->nt may have been changed by realloc */ self->nt[off].children[k] = noff; off = noff; n = &self->nt[off]; n->children[nt_level(oldnode, ++level)] = v; if (level > self->ntdepth) self->ntdepth = level; self->ntsplits += 1; } else { level += 1; off = v; } } return -1; } static int nt_init(indexObject *self) { if (self->nt == NULL) { self->ntcapacity = self->raw_length < 4 ? 4 : self->raw_length / 2; self->nt = calloc(self->ntcapacity, sizeof(nodetree)); if (self->nt == NULL) { PyErr_NoMemory(); return -1; } self->ntlength = 1; self->ntrev = (int)index_length(self) - 1; self->ntlookups = 1; self->ntmisses = 0; if (nt_insert(self, nullid, INT_MAX) == -1) return -1; } return 0; } /* * Return values: * * -3: error (exception set) * -2: not found (no exception set) * rest: valid rev */ static int index_find_node(indexObject *self, const char *node, Py_ssize_t nodelen) { int rev; self->ntlookups++; rev = nt_find(self, node, nodelen, 0); if (rev >= -1) return rev; if (nt_init(self) == -1) return -3; /* * For the first handful of lookups, we scan the entire index, * and cache only the matching nodes. This optimizes for cases * like "hg tip", where only a few nodes are accessed. * * After that, we cache every node we visit, using a single * scan amortized over multiple lookups. This gives the best * bulk performance, e.g. for "hg log". */ if (self->ntmisses++ < 4) { for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node(self, rev); if (n == NULL) return -2; if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) { if (nt_insert(self, n, rev) == -1) return -3; break; } } } else { for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node(self, rev); if (n == NULL) { self->ntrev = rev + 1; return -2; } if (nt_insert(self, n, rev) == -1) { self->ntrev = rev + 1; return -3; } if (memcmp(node, n, nodelen > 20 ? 20 : nodelen) == 0) { break; } } self->ntrev = rev; } if (rev >= 0) return rev; return -2; } static PyObject *raise_revlog_error(void) { static PyObject *errclass; PyObject *mod = NULL, *errobj; if (errclass == NULL) { PyObject *dict; mod = PyImport_ImportModule("mercurial.error"); if (mod == NULL) goto classfail; dict = PyModule_GetDict(mod); if (dict == NULL) goto classfail; errclass = PyDict_GetItemString(dict, "RevlogError"); if (errclass == NULL) { PyErr_SetString(PyExc_SystemError, "could not find RevlogError"); goto classfail; } Py_INCREF(errclass); } errobj = PyObject_CallFunction(errclass, NULL); if (errobj == NULL) return NULL; PyErr_SetObject(errclass, errobj); return errobj; classfail: Py_XDECREF(mod); return NULL; } static PyObject *index_getitem(indexObject *self, PyObject *value) { char *node; Py_ssize_t nodelen; int rev; if (PyInt_Check(value)) return index_get(self, PyInt_AS_LONG(value)); if (node_check(value, &node, &nodelen) == -1) return NULL; rev = index_find_node(self, node, nodelen); if (rev >= -1) return PyInt_FromLong(rev); if (rev == -2) raise_revlog_error(); return NULL; } static int nt_partialmatch(indexObject *self, const char *node, Py_ssize_t nodelen) { int rev; if (nt_init(self) == -1) return -3; if (self->ntrev > 0) { /* ensure that the radix tree is fully populated */ for (rev = self->ntrev - 1; rev >= 0; rev--) { const char *n = index_node(self, rev); if (n == NULL) return -2; if (nt_insert(self, n, rev) == -1) return -3; } self->ntrev = rev; } return nt_find(self, node, nodelen, 1); } static PyObject *index_partialmatch(indexObject *self, PyObject *args) { const char *fullnode; int nodelen; char *node; int rev, i; if (!PyArg_ParseTuple(args, "s#", &node, &nodelen)) return NULL; if (nodelen < 4) { PyErr_SetString(PyExc_ValueError, "key too short"); return NULL; } if (nodelen > 40) { PyErr_SetString(PyExc_ValueError, "key too long"); return NULL; } for (i = 0; i < nodelen; i++) hexdigit(node, i); if (PyErr_Occurred()) { /* input contains non-hex characters */ PyErr_Clear(); Py_RETURN_NONE; } rev = nt_partialmatch(self, node, nodelen); switch (rev) { case -4: raise_revlog_error(); case -3: return NULL; case -2: Py_RETURN_NONE; case -1: return PyString_FromStringAndSize(nullid, 20); } fullnode = index_node(self, rev); if (fullnode == NULL) { PyErr_Format(PyExc_IndexError, "could not access rev %d", rev); return NULL; } return PyString_FromStringAndSize(fullnode, 20); } static PyObject *index_m_get(indexObject *self, PyObject *args) { Py_ssize_t nodelen; PyObject *val; char *node; int rev; if (!PyArg_ParseTuple(args, "O", &val)) return NULL; if (node_check(val, &node, &nodelen) == -1) return NULL; rev = index_find_node(self, node, nodelen); if (rev == -3) return NULL; if (rev == -2) Py_RETURN_NONE; return PyInt_FromLong(rev); } static int index_contains(indexObject *self, PyObject *value) { char *node; Py_ssize_t nodelen; if (PyInt_Check(value)) { long rev = PyInt_AS_LONG(value); return rev >= -1 && rev < index_length(self); } if (node_check(value, &node, &nodelen) == -1) return -1; switch (index_find_node(self, node, nodelen)) { case -3: return -1; case -2: return 0; default: return 1; } } static inline void index_get_parents(indexObject *self, int rev, int *ps) { if (rev >= self->length - 1) { PyObject *tuple = PyList_GET_ITEM(self->added, rev - self->length + 1); ps[0] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 5)); ps[1] = (int)PyInt_AS_LONG(PyTuple_GET_ITEM(tuple, 6)); } else { const char *data = index_deref(self, rev); ps[0] = getbe32(data + 24); ps[1] = getbe32(data + 28); } } typedef uint64_t bitmask; /* * Given a disjoint set of revs, return all candidates for the * greatest common ancestor. In revset notation, this is the set * "heads(::a and ::b and ...)" */ static PyObject *find_gca_candidates(indexObject *self, const int *revs, int revcount) { const bitmask allseen = (1ull << revcount) - 1; const bitmask poison = 1ull << revcount; PyObject *gca = PyList_New(0); int i, v, interesting, left; int maxrev = -1; long sp; bitmask *seen; for (i = 0; i < revcount; i++) { if (revs[i] > maxrev) maxrev = revs[i]; } seen = calloc(sizeof(*seen), maxrev + 1); if (seen == NULL) return PyErr_NoMemory(); for (i = 0; i < revcount; i++) seen[revs[i]] = 1ull << i; interesting = left = revcount; for (v = maxrev; v >= 0 && interesting; v--) { long sv = seen[v]; int parents[2]; if (!sv) continue; if (sv < poison) { interesting -= 1; if (sv == allseen) { PyObject *obj = PyInt_FromLong(v); if (obj == NULL) goto bail; if (PyList_Append(gca, obj) == -1) { Py_DECREF(obj); goto bail; } sv |= poison; for (i = 0; i < revcount; i++) { if (revs[i] == v) { if (--left <= 1) goto done; break; } } } } index_get_parents(self, v, parents); for (i = 0; i < 2; i++) { int p = parents[i]; if (p == -1) continue; sp = seen[p]; if (sv < poison) { if (sp == 0) { seen[p] = sv; interesting++; } else if (sp != sv) seen[p] |= sv; } else { if (sp && sp < poison) interesting--; seen[p] = sv; } } } done: free(seen); return gca; bail: free(seen); Py_XDECREF(gca); return NULL; } /* * Given a disjoint set of revs, return the subset with the longest * path to the root. */ static PyObject *find_deepest(indexObject *self, PyObject *revs) { const Py_ssize_t revcount = PyList_GET_SIZE(revs); static const Py_ssize_t capacity = 24; int *depth, *interesting = NULL; int i, j, v, ninteresting; PyObject *dict = NULL, *keys; long *seen = NULL; int maxrev = -1; long final; if (revcount > capacity) { PyErr_Format(PyExc_OverflowError, "bitset size (%ld) > capacity (%ld)", (long)revcount, (long)capacity); return NULL; } for (i = 0; i < revcount; i++) { int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i)); if (n > maxrev) maxrev = n; } depth = calloc(sizeof(*depth), maxrev + 1); if (depth == NULL) return PyErr_NoMemory(); seen = calloc(sizeof(*seen), maxrev + 1); if (seen == NULL) { PyErr_NoMemory(); goto bail; } interesting = calloc(sizeof(*interesting), 2 << revcount); if (interesting == NULL) { PyErr_NoMemory(); goto bail; } for (i = 0; i < revcount; i++) { int n = (int)PyInt_AsLong(PyList_GET_ITEM(revs, i)); long b = 1l << i; depth[n] = 1; seen[n] = b; interesting[b] = 1; } ninteresting = (int)revcount; for (v = maxrev; v >= 0 && ninteresting > 1; v--) { int dv = depth[v]; int parents[2]; long sv; if (dv == 0) continue; sv = seen[v]; index_get_parents(self, v, parents); for (i = 0; i < 2; i++) { int p = parents[i]; long nsp, sp; int dp; if (p == -1) continue; dp = depth[p]; nsp = sp = seen[p]; if (dp <= dv) { depth[p] = dv + 1; if (sp != sv) { interesting[sv] += 1; nsp = seen[p] = sv; if (sp) { interesting[sp] -= 1; if (interesting[sp] == 0) ninteresting -= 1; } } } else if (dv == dp - 1) { nsp = sp | sv; if (nsp == sp) continue; seen[p] = nsp; interesting[nsp] += 1; interesting[sp] -= 1; if (interesting[sp] == 0) ninteresting -= 1; } } interesting[sv] -= 1; if (interesting[sv] == 0) ninteresting -= 1; } final = 0; j = ninteresting; for (i = 0; i < (int)(2 << revcount) && j > 0; i++) { if (interesting[i] == 0) continue; final |= i; j -= 1; } if (final == 0) return PyList_New(0); dict = PyDict_New(); if (dict == NULL) goto bail; j = ninteresting; for (i = 0; i < revcount && j > 0; i++) { PyObject *key; if ((final & (1 << i)) == 0) continue; key = PyList_GET_ITEM(revs, i); Py_INCREF(key); Py_INCREF(Py_None); if (PyDict_SetItem(dict, key, Py_None) == -1) { Py_DECREF(key); Py_DECREF(Py_None); goto bail; } j -= 1; } keys = PyDict_Keys(dict); free(depth); free(seen); free(interesting); Py_DECREF(dict); return keys; bail: free(depth); free(seen); free(interesting); Py_XDECREF(dict); return NULL; } /* * Given a (possibly overlapping) set of revs, return the greatest * common ancestors: those with the longest path to the root. */ static PyObject *index_ancestors(indexObject *self, PyObject *args) { PyObject *ret = NULL, *gca = NULL; Py_ssize_t argcount, i, len; bitmask repeat = 0; int revcount = 0; int *revs; argcount = PySequence_Length(args); revs = malloc(argcount * sizeof(*revs)); if (argcount > 0 && revs == NULL) return PyErr_NoMemory(); len = index_length(self) - 1; for (i = 0; i < argcount; i++) { static const int capacity = 24; PyObject *obj = PySequence_GetItem(args, i); bitmask x; long val; if (!PyInt_Check(obj)) { PyErr_SetString(PyExc_TypeError, "arguments must all be ints"); goto bail; } val = PyInt_AsLong(obj); if (val == -1) { ret = PyList_New(0); goto done; } if (val < 0 || val >= len) { PyErr_SetString(PyExc_IndexError, "index out of range"); goto bail; } /* this cheesy bloom filter lets us avoid some more * expensive duplicate checks in the common set-is-disjoint * case */ x = 1ull << (val & 0x3f); if (repeat & x) { int k; for (k = 0; k < revcount; k++) { if (val == revs[k]) goto duplicate; } } else repeat |= x; if (revcount >= capacity) { PyErr_Format(PyExc_OverflowError, "bitset size (%d) > capacity (%d)", revcount, capacity); goto bail; } revs[revcount++] = (int)val; duplicate:; } if (revcount == 0) { ret = PyList_New(0); goto done; } if (revcount == 1) { PyObject *obj; ret = PyList_New(1); if (ret == NULL) goto bail; obj = PyInt_FromLong(revs[0]); if (obj == NULL) goto bail; PyList_SET_ITEM(ret, 0, obj); goto done; } gca = find_gca_candidates(self, revs, revcount); if (gca == NULL) goto bail; if (PyList_GET_SIZE(gca) <= 1) { ret = gca; Py_INCREF(gca); } else if (PyList_GET_SIZE(gca) == 1) { ret = PyList_GET_ITEM(gca, 0); Py_INCREF(ret); } else ret = find_deepest(self, gca); done: free(revs); Py_XDECREF(gca); return ret; bail: free(revs); Py_XDECREF(gca); Py_XDECREF(ret); return NULL; } /* * Invalidate any trie entries introduced by added revs. */ static void nt_invalidate_added(indexObject *self, Py_ssize_t start) { Py_ssize_t i, len = PyList_GET_SIZE(self->added); for (i = start; i < len; i++) { PyObject *tuple = PyList_GET_ITEM(self->added, i); PyObject *node = PyTuple_GET_ITEM(tuple, 7); nt_insert(self, PyString_AS_STRING(node), -1); } if (start == 0) Py_CLEAR(self->added); } /* * Delete a numeric range of revs, which must be at the end of the * range, but exclude the sentinel nullid entry. */ static int index_slice_del(indexObject *self, PyObject *item) { Py_ssize_t start, stop, step, slicelength; Py_ssize_t length = index_length(self); int ret = 0; if (PySlice_GetIndicesEx((PySliceObject*)item, length, &start, &stop, &step, &slicelength) < 0) return -1; if (slicelength <= 0) return 0; if ((step < 0 && start < stop) || (step > 0 && start > stop)) stop = start; if (step < 0) { stop = start + 1; start = stop + step*(slicelength - 1) - 1; step = -step; } if (step != 1) { PyErr_SetString(PyExc_ValueError, "revlog index delete requires step size of 1"); return -1; } if (stop != length - 1) { PyErr_SetString(PyExc_IndexError, "revlog index deletion indices are invalid"); return -1; } if (start < self->length - 1) { if (self->nt) { Py_ssize_t i; for (i = start + 1; i < self->length - 1; i++) { const char *node = index_node(self, i); if (node) nt_insert(self, node, -1); } if (self->added) nt_invalidate_added(self, 0); if (self->ntrev > start) self->ntrev = (int)start; } self->length = start + 1; if (start < self->raw_length) { if (self->cache) { Py_ssize_t i; for (i = start; i < self->raw_length; i++) Py_CLEAR(self->cache[i]); } self->raw_length = start; } goto done; } if (self->nt) { nt_invalidate_added(self, start - self->length + 1); if (self->ntrev > start) self->ntrev = (int)start; } if (self->added) ret = PyList_SetSlice(self->added, start - self->length + 1, PyList_GET_SIZE(self->added), NULL); done: Py_CLEAR(self->headrevs); return ret; } /* * Supported ops: * * slice deletion * string assignment (extend node->rev mapping) * string deletion (shrink node->rev mapping) */ static int index_assign_subscript(indexObject *self, PyObject *item, PyObject *value) { char *node; Py_ssize_t nodelen; long rev; if (PySlice_Check(item) && value == NULL) return index_slice_del(self, item); if (node_check(item, &node, &nodelen) == -1) return -1; if (value == NULL) return self->nt ? nt_insert(self, node, -1) : 0; rev = PyInt_AsLong(value); if (rev > INT_MAX || rev < 0) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "rev out of range"); return -1; } return nt_insert(self, node, (int)rev); } /* * Find all RevlogNG entries in an index that has inline data. Update * the optional "offsets" table with those entries. */ static long inline_scan(indexObject *self, const char **offsets) { const char *data = PyString_AS_STRING(self->data); const char *end = data + PyString_GET_SIZE(self->data); long incr = v1_hdrsize; Py_ssize_t len = 0; while (data + v1_hdrsize <= end) { uint32_t comp_len; const char *old_data; /* 3rd element of header is length of compressed inline data */ comp_len = getbe32(data + 8); incr = v1_hdrsize + comp_len; if (incr < v1_hdrsize) break; if (offsets) offsets[len] = data; len++; old_data = data; data += incr; if (data <= old_data) break; } if (data != end && data + v1_hdrsize != end) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_ValueError, "corrupt index file"); return -1; } return len; } static int index_init(indexObject *self, PyObject *args) { PyObject *data_obj, *inlined_obj; Py_ssize_t size; if (!PyArg_ParseTuple(args, "OO", &data_obj, &inlined_obj)) return -1; if (!PyString_Check(data_obj)) { PyErr_SetString(PyExc_TypeError, "data is not a string"); return -1; } size = PyString_GET_SIZE(data_obj); self->inlined = inlined_obj && PyObject_IsTrue(inlined_obj); self->data = data_obj; self->cache = NULL; self->added = NULL; self->headrevs = NULL; self->offsets = NULL; self->nt = NULL; self->ntlength = self->ntcapacity = 0; self->ntdepth = self->ntsplits = 0; self->ntlookups = self->ntmisses = 0; self->ntrev = -1; Py_INCREF(self->data); if (self->inlined) { long len = inline_scan(self, NULL); if (len == -1) goto bail; self->raw_length = len; self->length = len + 1; } else { if (size % v1_hdrsize) { PyErr_SetString(PyExc_ValueError, "corrupt index file"); goto bail; } self->raw_length = size / v1_hdrsize; self->length = self->raw_length + 1; } return 0; bail: return -1; } static PyObject *index_nodemap(indexObject *self) { Py_INCREF(self); return (PyObject *)self; } static void index_dealloc(indexObject *self) { _index_clearcaches(self); Py_DECREF(self->data); Py_XDECREF(self->added); PyObject_Del(self); } static PySequenceMethods index_sequence_methods = { (lenfunc)index_length, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (ssizeargfunc)index_get, /* sq_item */ 0, /* sq_slice */ 0, /* sq_ass_item */ 0, /* sq_ass_slice */ (objobjproc)index_contains, /* sq_contains */ }; static PyMappingMethods index_mapping_methods = { (lenfunc)index_length, /* mp_length */ (binaryfunc)index_getitem, /* mp_subscript */ (objobjargproc)index_assign_subscript, /* mp_ass_subscript */ }; static PyMethodDef index_methods[] = { {"ancestors", (PyCFunction)index_ancestors, METH_VARARGS, "return the gca set of the given revs"}, {"clearcaches", (PyCFunction)index_clearcaches, METH_NOARGS, "clear the index caches"}, {"get", (PyCFunction)index_m_get, METH_VARARGS, "get an index entry"}, {"headrevs", (PyCFunction)index_headrevs, METH_NOARGS, "get head revisions"}, {"insert", (PyCFunction)index_insert, METH_VARARGS, "insert an index entry"}, {"partialmatch", (PyCFunction)index_partialmatch, METH_VARARGS, "match a potentially ambiguous node ID"}, {"stats", (PyCFunction)index_stats, METH_NOARGS, "stats for the index"}, {NULL} /* Sentinel */ }; static PyGetSetDef index_getset[] = { {"nodemap", (getter)index_nodemap, NULL, "nodemap", NULL}, {NULL} /* Sentinel */ }; static PyTypeObject indexType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "parsers.index", /* tp_name */ sizeof(indexObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)index_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ &index_sequence_methods, /* tp_as_sequence */ &index_mapping_methods, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "revlog index", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ index_methods, /* tp_methods */ 0, /* tp_members */ index_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)index_init, /* tp_init */ 0, /* tp_alloc */ }; /* * returns a tuple of the form (index, index, cache) with elements as * follows: * * index: an index object that lazily parses RevlogNG records * cache: if data is inlined, a tuple (index_file_content, 0), else None * * added complications are for backwards compatibility */ static PyObject *parse_index2(PyObject *self, PyObject *args) { PyObject *tuple = NULL, *cache = NULL; indexObject *idx; int ret; idx = PyObject_New(indexObject, &indexType); if (idx == NULL) goto bail; ret = index_init(idx, args); if (ret == -1) goto bail; if (idx->inlined) { cache = Py_BuildValue("iO", 0, idx->data); if (cache == NULL) goto bail; } else { cache = Py_None; Py_INCREF(cache); } tuple = Py_BuildValue("NN", idx, cache); if (!tuple) goto bail; return tuple; bail: Py_XDECREF(idx); Py_XDECREF(cache); Py_XDECREF(tuple); return NULL; } static char parsers_doc[] = "Efficient content parsing."; PyObject *encodedir(PyObject *self, PyObject *args); PyObject *pathencode(PyObject *self, PyObject *args); PyObject *lowerencode(PyObject *self, PyObject *args); static PyMethodDef methods[] = { {"pack_dirstate", pack_dirstate, METH_VARARGS, "pack a dirstate\n"}, {"parse_manifest", parse_manifest, METH_VARARGS, "parse a manifest\n"}, {"parse_dirstate", parse_dirstate, METH_VARARGS, "parse a dirstate\n"}, {"parse_index2", parse_index2, METH_VARARGS, "parse a revlog index\n"}, {"encodedir", encodedir, METH_VARARGS, "encodedir a path\n"}, {"pathencode", pathencode, METH_VARARGS, "fncache-encode a path\n"}, {"lowerencode", lowerencode, METH_VARARGS, "lower-encode a path\n"}, {NULL, NULL} }; void dirs_module_init(PyObject *mod); static void module_init(PyObject *mod) { dirs_module_init(mod); indexType.tp_new = PyType_GenericNew; if (PyType_Ready(&indexType) < 0) return; Py_INCREF(&indexType); PyModule_AddObject(mod, "index", (PyObject *)&indexType); nullentry = Py_BuildValue("iiiiiiis#", 0, 0, 0, -1, -1, -1, -1, nullid, 20); if (nullentry) PyObject_GC_UnTrack(nullentry); dirstate_unset = Py_BuildValue("ciii", 'n', 0, -1, -1); } #ifdef IS_PY3K static struct PyModuleDef parsers_module = { PyModuleDef_HEAD_INIT, "parsers", parsers_doc, -1, methods }; PyMODINIT_FUNC PyInit_parsers(void) { PyObject *mod = PyModule_Create(&parsers_module); module_init(mod); return mod; } #else PyMODINIT_FUNC initparsers(void) { PyObject *mod = Py_InitModule3("parsers", methods, parsers_doc); module_init(mod); } #endif
599
./intellij-community/plugins/hg4idea/testData/bin/mercurial/mpatch.c
/* mpatch.c - efficient binary patching for Mercurial This implements a patch algorithm that's O(m + nlog n) where m is the size of the output and n is the number of patches. Given a list of binary patches, it unpacks each into a hunk list, then combines the hunk lists with a treewise recursion to form a single hunk list. This hunk list is then applied to the original text. The text (or binary) fragments are copied directly from their source Python objects into a preallocated output string to avoid the allocation of intermediate Python objects. Working memory is about 2x the total number of hunks. Copyright 2005, 2006 Matt Mackall <[email protected]> This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include <stdlib.h> #include <string.h> #include "util.h" static char mpatch_doc[] = "Efficient binary patching."; static PyObject *mpatch_Error; struct frag { int start, end, len; const char *data; }; struct flist { struct frag *base, *head, *tail; }; static struct flist *lalloc(Py_ssize_t size) { struct flist *a = NULL; if (size < 1) size = 1; a = (struct flist *)malloc(sizeof(struct flist)); if (a) { a->base = (struct frag *)malloc(sizeof(struct frag) * size); if (a->base) { a->head = a->tail = a->base; return a; } free(a); a = NULL; } if (!PyErr_Occurred()) PyErr_NoMemory(); return NULL; } static void lfree(struct flist *a) { if (a) { free(a->base); free(a); } } static Py_ssize_t lsize(struct flist *a) { return a->tail - a->head; } /* move hunks in source that are less cut to dest, compensating for changes in offset. the last hunk may be split if necessary. */ static int gather(struct flist *dest, struct flist *src, int cut, int offset) { struct frag *d = dest->tail, *s = src->head; int postend, c, l; while (s != src->tail) { if (s->start + offset >= cut) break; /* we've gone far enough */ postend = offset + s->start + s->len; if (postend <= cut) { /* save this hunk */ offset += s->start + s->len - s->end; *d++ = *s++; } else { /* break up this hunk */ c = cut - offset; if (s->end < c) c = s->end; l = cut - offset - s->start; if (s->len < l) l = s->len; offset += s->start + l - c; d->start = s->start; d->end = c; d->len = l; d->data = s->data; d++; s->start = c; s->len = s->len - l; s->data = s->data + l; break; } } dest->tail = d; src->head = s; return offset; } /* like gather, but with no output list */ static int discard(struct flist *src, int cut, int offset) { struct frag *s = src->head; int postend, c, l; while (s != src->tail) { if (s->start + offset >= cut) break; postend = offset + s->start + s->len; if (postend <= cut) { offset += s->start + s->len - s->end; s++; } else { c = cut - offset; if (s->end < c) c = s->end; l = cut - offset - s->start; if (s->len < l) l = s->len; offset += s->start + l - c; s->start = c; s->len = s->len - l; s->data = s->data + l; break; } } src->head = s; return offset; } /* combine hunk lists a and b, while adjusting b for offset changes in a/ this deletes a and b and returns the resultant list. */ static struct flist *combine(struct flist *a, struct flist *b) { struct flist *c = NULL; struct frag *bh, *ct; int offset = 0, post; if (a && b) c = lalloc((lsize(a) + lsize(b)) * 2); if (c) { for (bh = b->head; bh != b->tail; bh++) { /* save old hunks */ offset = gather(c, a, bh->start, offset); /* discard replaced hunks */ post = discard(a, bh->end, offset); /* insert new hunk */ ct = c->tail; ct->start = bh->start - offset; ct->end = bh->end - post; ct->len = bh->len; ct->data = bh->data; c->tail++; offset = post; } /* hold on to tail from a */ memcpy(c->tail, a->head, sizeof(struct frag) * lsize(a)); c->tail += lsize(a); } lfree(a); lfree(b); return c; } /* decode a binary patch into a hunk list */ static struct flist *decode(const char *bin, Py_ssize_t len) { struct flist *l; struct frag *lt; const char *data = bin + 12, *end = bin + len; /* assume worst case size, we won't have many of these lists */ l = lalloc(len / 12); if (!l) return NULL; lt = l->tail; while (data <= end) { lt->start = getbe32(bin); lt->end = getbe32(bin + 4); lt->len = getbe32(bin + 8); if (lt->start > lt->end) break; /* sanity check */ bin = data + lt->len; if (bin < data) break; /* big data + big (bogus) len can wrap around */ lt->data = data; data = bin + 12; lt++; } if (bin != end) { if (!PyErr_Occurred()) PyErr_SetString(mpatch_Error, "patch cannot be decoded"); lfree(l); return NULL; } l->tail = lt; return l; } /* calculate the size of resultant text */ static Py_ssize_t calcsize(Py_ssize_t len, struct flist *l) { Py_ssize_t outlen = 0, last = 0; struct frag *f = l->head; while (f != l->tail) { if (f->start < last || f->end > len) { if (!PyErr_Occurred()) PyErr_SetString(mpatch_Error, "invalid patch"); return -1; } outlen += f->start - last; last = f->end; outlen += f->len; f++; } outlen += len - last; return outlen; } static int apply(char *buf, const char *orig, Py_ssize_t len, struct flist *l) { struct frag *f = l->head; int last = 0; char *p = buf; while (f != l->tail) { if (f->start < last || f->end > len) { if (!PyErr_Occurred()) PyErr_SetString(mpatch_Error, "invalid patch"); return 0; } memcpy(p, orig + last, f->start - last); p += f->start - last; memcpy(p, f->data, f->len); last = f->end; p += f->len; f++; } memcpy(p, orig + last, len - last); return 1; } /* recursively generate a patch of all bins between start and end */ static struct flist *fold(PyObject *bins, Py_ssize_t start, Py_ssize_t end) { Py_ssize_t len, blen; const char *buffer; if (start + 1 == end) { /* trivial case, output a decoded list */ PyObject *tmp = PyList_GetItem(bins, start); if (!tmp) return NULL; if (PyObject_AsCharBuffer(tmp, &buffer, &blen)) return NULL; return decode(buffer, blen); } /* divide and conquer, memory management is elsewhere */ len = (end - start) / 2; return combine(fold(bins, start, start + len), fold(bins, start + len, end)); } static PyObject * patches(PyObject *self, PyObject *args) { PyObject *text, *bins, *result; struct flist *patch; const char *in; char *out; Py_ssize_t len, outlen, inlen; if (!PyArg_ParseTuple(args, "OO:mpatch", &text, &bins)) return NULL; len = PyList_Size(bins); if (!len) { /* nothing to do */ Py_INCREF(text); return text; } if (PyObject_AsCharBuffer(text, &in, &inlen)) return NULL; patch = fold(bins, 0, len); if (!patch) return NULL; outlen = calcsize(inlen, patch); if (outlen < 0) { result = NULL; goto cleanup; } result = PyBytes_FromStringAndSize(NULL, outlen); if (!result) { result = NULL; goto cleanup; } out = PyBytes_AsString(result); if (!apply(out, in, inlen, patch)) { Py_DECREF(result); result = NULL; } cleanup: lfree(patch); return result; } /* calculate size of a patched file directly */ static PyObject * patchedsize(PyObject *self, PyObject *args) { long orig, start, end, len, outlen = 0, last = 0; Py_ssize_t patchlen; char *bin, *binend, *data; if (!PyArg_ParseTuple(args, "ls#", &orig, &bin, &patchlen)) return NULL; binend = bin + patchlen; data = bin + 12; while (data <= binend) { start = getbe32(bin); end = getbe32(bin + 4); len = getbe32(bin + 8); if (start > end) break; /* sanity check */ bin = data + len; if (bin < data) break; /* big data + big (bogus) len can wrap around */ data = bin + 12; outlen += start - last; last = end; outlen += len; } if (bin != binend) { if (!PyErr_Occurred()) PyErr_SetString(mpatch_Error, "patch cannot be decoded"); return NULL; } outlen += orig - last; return Py_BuildValue("l", outlen); } static PyMethodDef methods[] = { {"patches", patches, METH_VARARGS, "apply a series of patches\n"}, {"patchedsize", patchedsize, METH_VARARGS, "calculed patched size\n"}, {NULL, NULL} }; #ifdef IS_PY3K static struct PyModuleDef mpatch_module = { PyModuleDef_HEAD_INIT, "mpatch", mpatch_doc, -1, methods }; PyMODINIT_FUNC PyInit_mpatch(void) { PyObject *m; m = PyModule_Create(&mpatch_module); if (m == NULL) return NULL; mpatch_Error = PyErr_NewException("mpatch.mpatchError", NULL, NULL); Py_INCREF(mpatch_Error); PyModule_AddObject(m, "mpatchError", mpatch_Error); return m; } #else PyMODINIT_FUNC initmpatch(void) { Py_InitModule3("mpatch", methods, mpatch_doc); mpatch_Error = PyErr_NewException("mpatch.mpatchError", NULL, NULL); } #endif
600
./intellij-community/plugins/hg4idea/testData/bin/mercurial/dirs.c
/* dirs.c - dynamic directory diddling for dirstates Copyright 2013 Facebook This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include "util.h" /* * This is a multiset of directory names, built from the files that * appear in a dirstate or manifest. * * A few implementation notes: * * We modify Python integers for refcounting, but those integers are * never visible to Python code. * * We mutate strings in-place, but leave them immutable once they can * be seen by Python code. */ typedef struct { PyObject_HEAD PyObject *dict; } dirsObject; static inline Py_ssize_t _finddir(PyObject *path, Py_ssize_t pos) { const char *s = PyString_AS_STRING(path); while (pos != -1) { if (s[pos] == '/') break; pos -= 1; } return pos; } static int _addpath(PyObject *dirs, PyObject *path) { const char *cpath = PyString_AS_STRING(path); Py_ssize_t pos = PyString_GET_SIZE(path); PyObject *key = NULL; int ret = -1; while ((pos = _finddir(path, pos - 1)) != -1) { PyObject *val; /* It's likely that every prefix already has an entry in our dict. Try to avoid allocating and deallocating a string for each prefix we check. */ if (key != NULL) ((PyStringObject *)key)->ob_shash = -1; else { /* Force Python to not reuse a small shared string. */ key = PyString_FromStringAndSize(cpath, pos < 2 ? 2 : pos); if (key == NULL) goto bail; } PyString_GET_SIZE(key) = pos; PyString_AS_STRING(key)[pos] = '\0'; val = PyDict_GetItem(dirs, key); if (val != NULL) { PyInt_AS_LONG(val) += 1; continue; } /* Force Python to not reuse a small shared int. */ val = PyInt_FromLong(0x1eadbeef); if (val == NULL) goto bail; PyInt_AS_LONG(val) = 1; ret = PyDict_SetItem(dirs, key, val); Py_DECREF(val); if (ret == -1) goto bail; Py_CLEAR(key); } ret = 0; bail: Py_XDECREF(key); return ret; } static int _delpath(PyObject *dirs, PyObject *path) { Py_ssize_t pos = PyString_GET_SIZE(path); PyObject *key = NULL; int ret = -1; while ((pos = _finddir(path, pos - 1)) != -1) { PyObject *val; key = PyString_FromStringAndSize(PyString_AS_STRING(path), pos); if (key == NULL) goto bail; val = PyDict_GetItem(dirs, key); if (val == NULL) { PyErr_SetString(PyExc_ValueError, "expected a value, found none"); goto bail; } if (--PyInt_AS_LONG(val) <= 0 && PyDict_DelItem(dirs, key) == -1) goto bail; Py_CLEAR(key); } ret = 0; bail: Py_XDECREF(key); return ret; } static int dirs_fromdict(PyObject *dirs, PyObject *source, char skipchar) { PyObject *key, *value; Py_ssize_t pos = 0; while (PyDict_Next(source, &pos, &key, &value)) { if (!PyString_Check(key)) { PyErr_SetString(PyExc_TypeError, "expected string key"); return -1; } if (skipchar) { PyObject *st; if (!PyTuple_Check(value) || PyTuple_GET_SIZE(value) == 0) { PyErr_SetString(PyExc_TypeError, "expected non-empty tuple"); return -1; } st = PyTuple_GET_ITEM(value, 0); if (!PyString_Check(st) || PyString_GET_SIZE(st) == 0) { PyErr_SetString(PyExc_TypeError, "expected non-empty string " "at tuple index 0"); return -1; } if (PyString_AS_STRING(st)[0] == skipchar) continue; } if (_addpath(dirs, key) == -1) return -1; } return 0; } static int dirs_fromiter(PyObject *dirs, PyObject *source) { PyObject *iter, *item = NULL; int ret; iter = PyObject_GetIter(source); if (iter == NULL) return -1; while ((item = PyIter_Next(iter)) != NULL) { if (!PyString_Check(item)) { PyErr_SetString(PyExc_TypeError, "expected string"); break; } if (_addpath(dirs, item) == -1) break; Py_CLEAR(item); } ret = PyErr_Occurred() ? -1 : 0; Py_XDECREF(item); return ret; } /* * Calculate a refcounted set of directory names for the files in a * dirstate. */ static int dirs_init(dirsObject *self, PyObject *args) { PyObject *dirs = NULL, *source = NULL; char skipchar = 0; int ret = -1; self->dict = NULL; if (!PyArg_ParseTuple(args, "|Oc:__init__", &source, &skipchar)) return -1; dirs = PyDict_New(); if (dirs == NULL) return -1; if (source == NULL) ret = 0; else if (PyDict_Check(source)) ret = dirs_fromdict(dirs, source, skipchar); else if (skipchar) PyErr_SetString(PyExc_ValueError, "skip character is only supported " "with a dict source"); else ret = dirs_fromiter(dirs, source); if (ret == -1) Py_XDECREF(dirs); else self->dict = dirs; return ret; } PyObject *dirs_addpath(dirsObject *self, PyObject *args) { PyObject *path; if (!PyArg_ParseTuple(args, "O!:addpath", &PyString_Type, &path)) return NULL; if (_addpath(self->dict, path) == -1) return NULL; Py_RETURN_NONE; } static PyObject *dirs_delpath(dirsObject *self, PyObject *args) { PyObject *path; if (!PyArg_ParseTuple(args, "O!:delpath", &PyString_Type, &path)) return NULL; if (_delpath(self->dict, path) == -1) return NULL; Py_RETURN_NONE; } static int dirs_contains(dirsObject *self, PyObject *value) { return PyString_Check(value) ? PyDict_Contains(self->dict, value) : 0; } static void dirs_dealloc(dirsObject *self) { Py_XDECREF(self->dict); PyObject_Del(self); } static PyObject *dirs_iter(dirsObject *self) { return PyObject_GetIter(self->dict); } static PySequenceMethods dirs_sequence_methods; static PyMethodDef dirs_methods[] = { {"addpath", (PyCFunction)dirs_addpath, METH_VARARGS, "add a path"}, {"delpath", (PyCFunction)dirs_delpath, METH_VARARGS, "remove a path"}, {NULL} /* Sentinel */ }; static PyTypeObject dirsType = { PyObject_HEAD_INIT(NULL) }; void dirs_module_init(PyObject *mod) { dirs_sequence_methods.sq_contains = (objobjproc)dirs_contains; dirsType.tp_name = "parsers.dirs"; dirsType.tp_new = PyType_GenericNew; dirsType.tp_basicsize = sizeof(dirsObject); dirsType.tp_dealloc = (destructor)dirs_dealloc; dirsType.tp_as_sequence = &dirs_sequence_methods; dirsType.tp_flags = Py_TPFLAGS_DEFAULT; dirsType.tp_doc = "dirs"; dirsType.tp_iter = (getiterfunc)dirs_iter; dirsType.tp_methods = dirs_methods; dirsType.tp_init = (initproc)dirs_init; if (PyType_Ready(&dirsType) < 0) return; Py_INCREF(&dirsType); PyModule_AddObject(mod, "dirs", (PyObject *)&dirsType); }