// Decryption and Verification procedure int crypto_aead_decrypt( unsigned char *m, unsigned long long *mlen, unsigned char *nsec, const unsigned char *c, unsigned long long clen, const unsigned char *ad, unsigned long long adlen, const unsigned char *npub, const unsigned char *k ) { //... //... the code for the cipher implementation goes here, //... generating a plaintext m[0],m[1],...,m[*mlen-1] //... and secret message number nsec[0],nsec[1],... //... from a ciphertext c[0],c[1],...,c[clen-1] //... and associated data ad[0],ad[1],...,ad[adlen-1] //... and public message number npub[0],npub[1],... //... and secret key k[0],k[1],... //... // some 64-bit temp variables u_int64_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13; // more 64-bit temp variables u_int64_t x0, x1, x2, x3, y0, y1, y2, y3, z0, z1, z2, z3; // more 64-bit temp variables u_int64_t pom1, pom2, pom3, pom4, nu1, nu2, nu3, nu4; // more 64-bit temp variables u_int64_t IS0, IS1, IS2, IS3, IS4, IS5, IS6, IS7, IS8, IS9, IS10, IS11, IS12, IS13, IS14, IS15; // more 64-bit temp variables u_int64_t preCompIS0, preCompIS1, preCompIS2, preCompIS3, preCompIS4, preCompIS5, preCompIS6, preCompIS7, preCompIS8, preCompIS9, preCompIS10, preCompIS11, preCompIS12, preCompIS13, preCompIS14, preCompIS15; // pointers to 64-bit variables u_int64_t *c64, *m64, *ad64, *nsec64, *npub64, *k64; // an array for storing some temporal values for the Tag computation u_int64_t tempTag[CRYPTO_ABYTES / W] = { 0 }; // counter ctr is a 64-bit variable in all variants of PiCipher u_int64_t ctr = 0x0000000000000000ull; // an array for the Common Internal State u_int64_t CIS[IS_SIZE] = { 0 }; u_int64_t CIS1[IS_SIZE] = { 0 }; // pointers that look at the used data arrays as arrays of bytes u_int8_t *InternalState8, *CommonInternalState8, *tempTag8; // variables for dealing with various lengths of the plaintext and associated data int LastMessageChunkLength, LastADChunkLength; // different iterator variables unsigned long long i, j, jj, ii, b, i1, j1, a, cblocks, ii1, ii2, b1; c64 = (u_int64_t *)c; m64 = (u_int64_t *)m; ad64 = (u_int64_t *)ad; nsec64 = (u_int64_t *)nsec; npub64 = (u_int64_t *)npub; k64 = (u_int64_t *)k; InternalState8 = (u_int8_t *)IS; CommonInternalState8 = (u_int8_t *)CIS; tempTag8 = (u_int8_t *)tempTag; // phase 1: Initialization /* for (i = 0; i < IS_SIZE; i++) { IS[i] = 0; } */ IS[0] = 0; IS[1] = 0; IS[2] = 0; IS[3] = 0; IS[4] = 0; IS[5] = 0; IS[6] = 0; IS[7] = 0; IS[8] = 0; IS[9] = 0; IS[10] = 0; IS[11] = 0; IS[12] = 0; IS[13] = 0; IS[14] = 0; IS[15] = 0; // injection of the key /*for (i = 0; i < CRYPTO_KEYBYTES; i++) { InternalState8[i] = k[i]; }*/ IS[0] = k64[0]; IS[1] = k64[1]; IS[2] = k64[2]; IS[3] = k64[3]; // injection of the nonce (public message number - PMN) /*for (j = 0; j < CRYPTO_NPUBBYTES; j++) { InternalState8[i++] = npub[j]; }*/ IS[4] = npub64[0]; IS[5] = npub64[1]; // appending a single 1 to the concatenated value of the key and PMN InternalState8[48] = 0x01; // applying the permutation function pi pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // initialization of the Common Internal State (CIS), common for all parallel invocations of pi() with different ctrs /* for (i = 0; i < IS_SIZE; i++) { CIS[i] = IS[i]; } */ CIS[0] = IS[0]; CIS[1] = IS[1]; CIS[2] = IS[2]; CIS[3] = IS[3]; CIS[4] = IS[4]; CIS[5] = IS[5]; CIS[6] = IS[6]; CIS[7] = IS[7]; CIS[8] = IS[8]; CIS[9] = IS[9]; CIS[10] = IS[10]; CIS[11] = IS[11]; CIS[12] = IS[12]; CIS[13] = IS[13]; CIS[14] = IS[14]; CIS[15] = IS[15]; // initialization of the ctr obtained from the first 64 bits of the capacity of CIS ctr = CIS[4]; // phase 2: Processing the associated data nu64(CIS[4], CIS[5], CIS[6], CIS[7], CIS1[4], CIS1[5], CIS1[6], CIS1[7]); nu64(CIS[8], CIS[9], CIS[10], CIS[11], CIS1[8], CIS1[9], CIS1[10], CIS1[11]); nu64(CIS[12], CIS[13], CIS[14], CIS[15], CIS1[12], CIS1[13], CIS1[14], CIS1[15]); nu1 = 0x8D8B87787472716C + CIS[2] + CIS[3]; nu2 = 0x6A696665635C5A59 + CIS[1] + CIS[2] + CIS[3]; nu2 = rotl64((nu2), 23); nu3 = 0x5655534E4D4B473C + CIS[1] + CIS[2]; nu4 = 0x3A393635332E2D2B + CIS[1] + CIS[3]; b = 0; a = adlen / RATE; for (j = 0; j < a; j++) { // IS for the triplex component is initialized by the CIS for every AD block /* for (i = 0; i < IS_SIZE; i++) { IS[i] = CIS[i]; } */ IS[0] = CIS[0]; IS[1] = CIS[1]; IS[2] = CIS[2]; IS[3] = CIS[3]; IS[4] = CIS1[4]; IS[5] = CIS1[5]; IS[6] = CIS1[6]; IS[7] = CIS1[7]; IS[8] = CIS1[8]; IS[9] = CIS1[9]; IS[10] = CIS1[10]; IS[11] = CIS1[11]; IS[12] = CIS1[12]; IS[13] = CIS1[13]; IS[14] = CIS1[14]; IS[15] = CIS1[15]; ctr++; // Inject ctr + j in IS IS[0] = IS[0] ^ ctr; pi1(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15], nu1, nu2, nu3, nu4); //pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // process the AD block // Inject the AD block /* for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { IS[ii1] = IS[ii1] ^ ad64[b]; b++; ii1++; } } */ IS[0] = IS[0] ^ ad64[b]; b++; IS[1] = IS[1] ^ ad64[b]; b++; IS[2] = IS[2] ^ ad64[b]; b++; IS[3] = IS[3] ^ ad64[b]; b++; IS[8] = IS[8] ^ ad64[b]; b++; IS[9] = IS[9] ^ ad64[b]; b++; IS[10] = IS[10] ^ ad64[b]; b++; IS[11] = IS[11] ^ ad64[b]; b++; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // Collect the tag for this block // Sum of the tags componentwise, where the length of one component is W /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { tempTag[jj] = tempTag[jj] + IS[ii1]; jj++; ii1++; } } */ tempTag[0] = tempTag[0] + IS[0]; tempTag[1] = tempTag[1] + IS[1]; tempTag[2] = tempTag[2] + IS[2]; tempTag[3] = tempTag[3] + IS[3]; tempTag[4] = tempTag[4] + IS[8]; tempTag[5] = tempTag[5] + IS[9]; tempTag[6] = tempTag[6] + IS[10]; tempTag[7] = tempTag[7] + IS[11]; } // if the last AD block is not the full block, we process it byte by byte LastADChunkLength = adlen % RATE; if (LastADChunkLength) { b = b * W; i1 = 0; /* for (i = 0; i < IS_SIZE; i++) { IS[i] = CIS[i]; } */ IS[0] = CIS[0]; IS[1] = CIS[1]; IS[2] = CIS[2]; IS[3] = CIS[3]; IS[4] = CIS1[4]; IS[5] = CIS1[5]; IS[6] = CIS1[6]; IS[7] = CIS1[7]; IS[8] = CIS1[8]; IS[9] = CIS1[9]; IS[10] = CIS1[10]; IS[11] = CIS1[11]; IS[12] = CIS1[12]; IS[13] = CIS1[13]; IS[14] = CIS1[14]; IS[15] = CIS1[15]; ctr++; IS[0] = IS[0] ^ ctr; pi1(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15], nu1, nu2, nu3, nu4); //pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); for (i = 0; i < LastADChunkLength; i++) { InternalState8[i1] = InternalState8[i1] ^ ad[b]; i1++; if (i1 % (RATE_OUT) == 0) i1 += RATE_OUT; b++; } // padding with 10* InternalState8[LastADChunkLength] = InternalState8[LastADChunkLength] ^ 0x01; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); //updating the tag /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { tempTag[jj] = tempTag[jj] + IS[ii1]; jj++; ii1++; } } */ tempTag[0] = tempTag[0] + IS[0]; tempTag[1] = tempTag[1] + IS[1]; tempTag[2] = tempTag[2] + IS[2]; tempTag[3] = tempTag[3] + IS[3]; tempTag[4] = tempTag[4] + IS[8]; tempTag[5] = tempTag[5] + IS[9]; tempTag[6] = tempTag[6] + IS[10]; tempTag[7] = tempTag[7] + IS[11]; } // updating the Common Internal State by injection of the tag (tempTag) obtained from the associated data /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; ii2 = (i + 1) * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { IS[ii1] = CIS[ii1] ^ tempTag[jj]; IS[ii2] = CIS[ii2]; jj++; ii1++; ii2++; } } */ IS[0] = CIS[0] ^ tempTag[0]; IS[1] = CIS[1] ^ tempTag[1]; IS[2] = CIS[2] ^ tempTag[2]; IS[3] = CIS[3] ^ tempTag[3]; IS[4] = CIS[4]; IS[5] = CIS[5]; IS[6] = CIS[6]; IS[7] = CIS[7]; IS[8] = CIS[8] ^ tempTag[4]; IS[9] = CIS[9] ^ tempTag[5]; IS[10] = CIS[10] ^ tempTag[6]; IS[11] = CIS[11] ^ tempTag[7]; IS[12] = CIS[12]; IS[13] = CIS[13]; IS[14] = CIS[14]; IS[15] = CIS[15]; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); /* for (i = 0; i < IS_SIZE; i++) { CIS[i] = IS[i]; } */ CIS[0] = IS[0]; CIS[1] = IS[1]; CIS[2] = IS[2]; CIS[3] = IS[3]; CIS[4] = IS[4]; CIS[5] = IS[5]; CIS[6] = IS[6]; CIS[7] = IS[7]; CIS[8] = IS[8]; CIS[9] = IS[9]; CIS[10] = IS[10]; CIS[11] = IS[11]; CIS[12] = IS[12]; CIS[13] = IS[13]; CIS[14] = IS[14]; CIS[15] = IS[15]; // phase 3: Processing the secret messge number if (CRYPTO_NSECBYTES > 0) { nu64(CIS[4], CIS[5], CIS[6], CIS[7], CIS[4], CIS[5], CIS[6], CIS[7]); nu64(CIS[8], CIS[9], CIS[10], CIS[11], CIS[8], CIS[9], CIS[10], CIS[11]); nu64(CIS[12], CIS[13], CIS[14], CIS[15], CIS[12], CIS[13], CIS[14], CIS[15]); nu1 = 0x8D8B87787472716C + CIS[2] + CIS[3]; nu2 = 0x6A696665635C5A59 + CIS[1] + CIS[2] + CIS[3]; nu2 = rotl64((nu2), 23); nu3 = 0x5655534E4D4B473C + CIS[1] + CIS[2]; nu4 = 0x3A393635332E2D2B + CIS[1] + CIS[3]; /* for (i = 0; i < IS_SIZE; i++) { IS[i] = CIS[i]; } */ IS[0] = CIS[0]; IS[1] = CIS[1]; IS[2] = CIS[2]; IS[3] = CIS[3]; IS[4] = CIS[4]; IS[5] = CIS[5]; IS[6] = CIS[6]; IS[7] = CIS[7]; IS[8] = CIS[8]; IS[9] = CIS[9]; IS[10] = CIS[10]; IS[11] = CIS[11]; IS[12] = CIS[12]; IS[13] = CIS[13]; IS[14] = CIS[14]; IS[15] = CIS[15]; ctr++; IS[0] = IS[0] ^ ctr; pi1(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15], nu1, nu2, nu3, nu4); //pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // decrypt the SMN // Inject the SMN b = 0; /* for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { nsec64[b] = IS[ii1] ^ c64[b]; IS[ii1] = c64[b]; b++; ii1++; } } */ nsec64[b] = IS[0] ^ c64[b]; IS[0] = c64[b]; b++; nsec64[b] = IS[1] ^ c64[b]; IS[1] = c64[b]; b++; nsec64[b] = IS[2] ^ c64[b]; IS[2] = c64[b]; b++; nsec64[b] = IS[3] ^ c64[b]; IS[3] = c64[b]; b++; nsec64[b] = IS[8] ^ c64[b]; IS[8] = c64[b]; b++; nsec64[b] = IS[9] ^ c64[b]; IS[9] = c64[b]; b++; nsec64[b] = IS[10] ^ c64[b]; IS[10] = c64[b]; b++; nsec64[b] = IS[11] ^ c64[b]; IS[11] = c64[b]; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // updating the Common Internal State after decrypting the SMN /* for (i = 0; i < IS_SIZE; i++) { CIS[i] = IS[i]; } */ CIS[0] = IS[0]; CIS[1] = IS[1]; CIS[2] = IS[2]; CIS[3] = IS[3]; CIS[4] = IS[4]; CIS[5] = IS[5]; CIS[6] = IS[6]; CIS[7] = IS[7]; CIS[8] = IS[8]; CIS[9] = IS[9]; CIS[10] = IS[10]; CIS[11] = IS[11]; CIS[12] = IS[12]; CIS[13] = IS[13]; CIS[14] = IS[14]; CIS[15] = IS[15]; // Collect the tag from this encryption and update the tempTag /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { tempTag[jj] = tempTag[jj] + IS[ii1]; jj++; ii1++; } } */ tempTag[0] = tempTag[0] + IS[0]; tempTag[1] = tempTag[1] + IS[1]; tempTag[2] = tempTag[2] + IS[2]; tempTag[3] = tempTag[3] + IS[3]; tempTag[4] = tempTag[4] + IS[8]; tempTag[5] = tempTag[5] + IS[9]; tempTag[6] = tempTag[6] + IS[10]; tempTag[7] = tempTag[7] + IS[11]; } //phase 4: Processing the ciphertext nu64(CIS[4], CIS[5], CIS[6], CIS[7], CIS[4], CIS[5], CIS[6], CIS[7]); nu64(CIS[8], CIS[9], CIS[10], CIS[11], CIS[8], CIS[9], CIS[10], CIS[11]); nu64(CIS[12], CIS[13], CIS[14], CIS[15], CIS[12], CIS[13], CIS[14], CIS[15]); nu1 = 0x8D8B87787472716C + CIS[2] + CIS[3]; nu2 = 0x6A696665635C5A59 + CIS[1] + CIS[2] + CIS[3]; nu2 = rotl64((nu2), 23); nu3 = 0x5655534E4D4B473C + CIS[1] + CIS[2]; nu4 = 0x3A393635332E2D2B + CIS[1] + CIS[3]; cblocks = (clen - CRYPTO_ABYTES - CRYPTO_NSECBYTES) / RATE; b = 0; b1 = bSMN; for (j = 0; j < cblocks; j++) { /* for (i = 0; i < IS_SIZE; i++) { IS[i] = CIS[i]; } */ IS[0] = CIS[0]; IS[1] = CIS[1]; IS[2] = CIS[2]; IS[3] = CIS[3]; IS[4] = CIS[4]; IS[5] = CIS[5]; IS[6] = CIS[6]; IS[7] = CIS[7]; IS[8] = CIS[8]; IS[9] = CIS[9]; IS[10] = CIS[10]; IS[11] = CIS[11]; IS[12] = CIS[12]; IS[13] = CIS[13]; IS[14] = CIS[14]; IS[15] = CIS[15]; ctr++; IS[0] = IS[0] ^ ctr; pi1(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15], nu1, nu2, nu3, nu4); //pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // decrypt the ciphertext c /* for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { // XOR the IS_bitrate (InternalState[0], InternalSate[2], ...) with the c to obtain m m64[b] = IS[ii1] ^ c64[b1]; // in order to proceed for tag computation, put the ciphertext data in the InternalState IS[ii1] = c64[b1]; b++; b1++; ii1++; } } */ m64[b] = IS[0] ^ c64[b1]; IS[0] = c64[b1]; b++; b1++; m64[b] = IS[1] ^ c64[b1]; IS[1] = c64[b1]; b++; b1++; m64[b] = IS[2] ^ c64[b1]; IS[2] = c64[b1]; b++; b1++; m64[b] = IS[3] ^ c64[b1]; IS[3] = c64[b1]; b++; b1++; m64[b] = IS[8] ^ c64[b1]; IS[8] = c64[b1]; b++; b1++; m64[b] = IS[9] ^ c64[b1]; IS[9] = c64[b1]; b++; b1++; m64[b] = IS[10] ^ c64[b1]; IS[10] = c64[b1]; b++; b1++; m64[b] = IS[11] ^ c64[b1]; IS[11] = c64[b1]; b++; b1++; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // Collect the tag from this decryption and update the tempTag /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { tempTag[jj] = tempTag[jj] + IS[ii1]; jj++; ii1++; } } */ tempTag[0] = tempTag[0] + IS[0]; tempTag[1] = tempTag[1] + IS[1]; tempTag[2] = tempTag[2] + IS[2]; tempTag[3] = tempTag[3] + IS[3]; tempTag[4] = tempTag[4] + IS[8]; tempTag[5] = tempTag[5] + IS[9]; tempTag[6] = tempTag[6] + IS[10]; tempTag[7] = tempTag[7] + IS[11]; } // if the last ciphertext block is not the full block, we process it byte by byte LastMessageChunkLength = (clen - CRYPTO_ABYTES - CRYPTO_NSECBYTES) % RATE; if (LastMessageChunkLength) { b = b * W; b1 = CRYPTO_NSECBYTES + b; i1 = 0; /* for (i = 0; i < IS_SIZE; i++) { IS[i] = CIS[i]; } */ IS[0] = CIS[0]; IS[1] = CIS[1]; IS[2] = CIS[2]; IS[3] = CIS[3]; IS[4] = CIS[4]; IS[5] = CIS[5]; IS[6] = CIS[6]; IS[7] = CIS[7]; IS[8] = CIS[8]; IS[9] = CIS[9]; IS[10] = CIS[10]; IS[11] = CIS[11]; IS[12] = CIS[12]; IS[13] = CIS[13]; IS[14] = CIS[14]; IS[15] = CIS[15]; ctr++; IS[0] = IS[0] ^ ctr; pi1(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15], nu1, nu2, nu3, nu4); //pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); for (i = 0; i < LastMessageChunkLength; i++) { m[b] = InternalState8[i1] ^ c[b1]; InternalState8[i1] = c[b1]; i1++; if (i1 % (RATE_OUT) == 0) i1 += RATE_OUT; b++; b1++; } // padding with 10* InternalState8[LastMessageChunkLength] = InternalState8[LastMessageChunkLength] ^ 0x01; pi(IS[0], IS[1], IS[2], IS[3], IS[4], IS[5], IS[6], IS[7], IS[8], IS[9], IS[10], IS[11], IS[12], IS[13], IS[14], IS[15]); // updating the tag /* jj = 0; for (i = 0; i < N; i += 2) { ii1 = i * WORDS_CHUNK; for (i1 = 0; i1 < WORDS_CHUNK; i1++) { tempTag[jj] = tempTag[jj] + IS[ii1]; jj++; ii1++; } } */ tempTag[0] = tempTag[0] + IS[0]; tempTag[1] = tempTag[1] + IS[1]; tempTag[2] = tempTag[2] + IS[2]; tempTag[3] = tempTag[3] + IS[3]; tempTag[4] = tempTag[4] + IS[8]; tempTag[5] = tempTag[5] + IS[9]; tempTag[6] = tempTag[6] + IS[10]; tempTag[7] = tempTag[7] + IS[11]; } //updating the lenght of the message *mlen = clen - CRYPTO_ABYTES - CRYPTO_NSECBYTES; // tag verification b = (*mlen + CRYPTO_NSECBYTES); for (ii = b; ii < clen; ii++) { if (c[ii] != tempTag8[ii - b]) return -1; } return 0; }

int main (void) { printf ("Valor de PI: %f\n", pi () ); }

float Sphere::area() const { return (float)pi() * 4.0f * powf((float)radius, 2.0f); }

int main(){ //run-time instance volatile double mut_val=-3.1415926; value_tuple<bool, char, double, int, pi> tuple(pos<1>(false), pos<3>(mut_val), pos<2>('m')); std::cout << tuple.get<1>() << " " << tuple.get<2>() << " " << tuple.get<3>() << " " << tuple.get<4>() << " " << tuple.get<5>() << " " << std::endl; value_tuple<bool, char, double, pi> default_tuple; std::cout << default_tuple.get<1>() << " " << default_tuple.get<2>() << " " << default_tuple.get<3>() << " " << default_tuple.get<4>() << " " << std::endl; constexpr value_tuple<bool, char, double, int> ctuple(pos<1>(false), pos<3>(3.14), pos<2>('m')); static_assert(ctuple.get<1>()==false, "error"); static_assert(ctuple.get<2>()=='m', "error"); static_assert(ctuple.get<3>()==3.14, "error"); static_assert(ctuple.get<4>()==int(), "error"); // static_assert(c_tuple.get<4>()=='b', "error"); // This trigger an error //exercice: make the following tuple compile value_tuple<bool, short, std::string> tuple2(pos<1>(false), pos<2>(4), pos<3>(std::string("pink pig"))); tuple2.set<3>(std::string("black dog")); std::cout<<tuple2.get<3>()<<std::endl; //advanced exercice: //implement a tuple which expands the interface make_tuple<type, 5> to //value_tuple<type, type, type, type, type> make_value_tuple<int, 5> new_tuple(pos<5>(66), pos<4>(55), pos<3>(44), pos<2>(33),pos<1>(22)); std::cout << new_tuple.get<1>() << " " << new_tuple.get<2>() << " " << new_tuple.get<3>() << " " << new_tuple.get<4>() << " " << new_tuple.get<5>() << " " << std::endl; //very advanced exercice (probably not a good idea): //implement an interface which mixes run-time and compile-time components in an offset-tuple //using tuple_t = offset_tuple<int, 5> //using alias<pos<1>, 5> = new_tuple_t; //new_tuple_t(pos<4>(3)); detail_::integer_tuple_mixed< make_value_tuple<int,4>, pair<5, 44> > tmp; static_assert(detail_::get<5>(tmp)==44, "error"); static_assert(tmp.get<5>()==44, "error"); //the interface for generic tuple (not only integers) becomes a bit cumbersome detail_::value_tuple_mixed< make_value_tuple<int,4>, const value_tuple<int, char, pi>, c_tuple_> tmp2; static_assert(tmp2.get<3>().m_value==pi(10).m_value, "error"); }

unsigned int ompl::geometric::PathHybridization::recordPath(const base::PathPtr &pp, bool matchAcrossGaps) { auto *p = dynamic_cast<PathGeometric *>(pp.get()); if (!p) { OMPL_ERROR("Path hybridization only works for geometric paths"); return 0; } if (p->getSpaceInformation() != si_) { OMPL_ERROR("Paths for hybridization must be from the same space information"); return 0; } // skip empty paths if (p->getStateCount() == 0) return 0; PathInfo pi(pp); // if this path was previously included in the hybridization, skip it if (paths_.find(pi) != paths_.end()) return 0; // the number of connection attempts unsigned int nattempts = 0; // start from virtual root Vertex v0 = boost::add_vertex(g_); stateProperty_[v0] = pi.states_[0]; pi.vertices_.push_back(v0); // add all the vertices of the path, and the edges between them, to the HGraph // also compute the path length for future use (just for computational savings) const HGraph::edge_property_type prop0(0.0); boost::add_edge(root_, v0, prop0, g_); double length = 0.0; for (std::size_t j = 1; j < pi.states_.size(); ++j) { Vertex v1 = boost::add_vertex(g_); stateProperty_[v1] = pi.states_[j]; double weight = si_->distance(pi.states_[j - 1], pi.states_[j]); const HGraph::edge_property_type properties(weight); boost::add_edge(v0, v1, properties, g_); length += weight; pi.vertices_.push_back(v1); v0 = v1; } // connect to virtual goal boost::add_edge(v0, goal_, prop0, g_); pi.length_ = length; // find matches with previously added paths for (const auto &path : paths_) { const auto *q = static_cast<const PathGeometric *>(path.path_.get()); std::vector<int> indexP, indexQ; matchPaths(*p, *q, (pi.length_ + path.length_) / (2.0 / magic::GAP_COST_FRACTION), indexP, indexQ); if (matchAcrossGaps) { int lastP = -1; int lastQ = -1; int gapStartP = -1; int gapStartQ = -1; bool gapP = false; bool gapQ = false; for (std::size_t i = 0; i < indexP.size(); ++i) { // a gap is found in p if (indexP[i] < 0) { // remember this as the beginning of the gap, if needed if (!gapP) gapStartP = i; // mark the fact we are now in a gap on p gapP = true; } else { // check if a gap just ended; // if it did, try to match the endpoint with the elements in q if (gapP) for (std::size_t j = gapStartP; j < i; ++j) { attemptNewEdge(pi, path, indexP[i], indexQ[j]); ++nattempts; } // remember the last non-negative index in p lastP = i; gapP = false; } if (indexQ[i] < 0) { if (!gapQ) gapStartQ = i; gapQ = true; } else { if (gapQ) for (std::size_t j = gapStartQ; j < i; ++j) { attemptNewEdge(pi, path, indexP[j], indexQ[i]); ++nattempts; } lastQ = i; gapQ = false; } // try to match corresponding index values and gep beginnings if (lastP >= 0 && lastQ >= 0) { attemptNewEdge(pi, path, indexP[lastP], indexQ[lastQ]); ++nattempts; } } } else { // attempt new edge only when states align for (std::size_t i = 0; i < indexP.size(); ++i) if (indexP[i] >= 0 && indexQ[i] >= 0) { attemptNewEdge(pi, path, indexP[i], indexQ[i]); ++nattempts; } } } // remember this path is part of the hybridization paths_.insert(pi); return nattempts; }

void DrrnPsiClient::recv(Channel s0, Channel s1, span<block> inputs) { if (inputs.size() != mClientSetSize) throw std::runtime_error(LOCATION); Matrix<u64> bins(mNumSimpleBins, mBinSize); std::vector<u64> binSizes(mNumSimpleBins); u64 cuckooSlotsPerBin = (mCuckooParams.numBins() + mNumSimpleBins) / mNumSimpleBins; // Simple hashing with a PRP std::vector<block> hashs(inputs.size()); AES hasher(mHashingSeed); u64 numCuckooBins = mCuckooParams.numBins(); for (u64 i = 0; i < u64(inputs.size());) { auto min = std::min<u64>(inputs.size() - i, 8); auto end = i + min; hasher.ecbEncBlocks(inputs.data() + i, min, hashs.data() + i); for (; i < end; ++i) { hashs[i] = hashs[i] ^ inputs[i]; for (u64 j = 0; j < mCuckooParams.mNumHashes; ++j) { u64 idx = CuckooIndex<>::getHash(hashs[i], j, numCuckooBins) * mNumSimpleBins / mCuckooParams.numBins(); // insert this item in this bin. pack together the hash index and input index bins(idx, binSizes[idx]++) = (j << 56) | i; } //if (!i) //{ // ostreamLock(std::cout) << "cinput[" << i << "] = " << inputs[i] << " -> " << hashs[i] << " (" // << CuckooIndex<>::getHash(hashs[i], 0, numCuckooBins) << ", " // << CuckooIndex<>::getHash(hashs[i], 1, numCuckooBins) << ", " // << CuckooIndex<>::getHash(hashs[i], 2, numCuckooBins) << ")" // << std::endl; //} } } // power of 2 u64 numLeafBlocks = (cuckooSlotsPerBin + mBigBlockSize * 128 - 1) / (mBigBlockSize * 128); u64 gDepth = 2; u64 kDepth = std::max<u64>(gDepth, log2floor(numLeafBlocks)) - gDepth; u64 groupSize = (numLeafBlocks + (u64(1) << kDepth) - 1) / (u64(1) << kDepth); if (groupSize > 8) throw std::runtime_error(LOCATION); //std::cout << "kDepth: " << kDepth << std::endl; //std::cout << "mBinSize: " << mBinSize << std::endl; u64 numQueries = mNumSimpleBins * mBinSize; auto permSize = numQueries * mBigBlockSize; // mask generation block rSeed = CCBlock;// mPrng.get<block>(); AES rGen(rSeed); std::vector<block> shares(mClientSetSize * mCuckooParams.mNumHashes), r(permSize), piS1(permSize), s(permSize); //std::vector<u32> rIdxs(numQueries); //std::vector<u64> sharesIdx(shares.size()); //TODO("use real masks"); //memset(r.data(), 0, r.size() * sizeof(block)); rGen.ecbEncCounterMode(r.size() * 0, r.size(), r.data()); rGen.ecbEncCounterMode(r.size() * 1, r.size(), piS1.data()); rGen.ecbEncCounterMode(r.size() * 2, r.size(), s.data()); //auto encIter = enc.begin(); auto shareIter = shares.begin(); //auto shareIdxIter = sharesIdx.begin(); u64 queryIdx = 0, dummyPermIdx = mClientSetSize * mCuckooParams.mNumHashes; std::unordered_map<u64, u64> inputMap; inputMap.reserve(mClientSetSize * mCuckooParams.mNumHashes); std::vector<u32> pi(permSize); auto piIter = pi.begin(); u64 keySize = kDepth + 1 + groupSize; u64 mask = (u64(1) << 56) - 1; auto binIter = bins.begin(); for (u64 bIdx = 0; bIdx < mNumSimpleBins; ++bIdx) { u64 i = 0; auto binOffset = (bIdx * numCuckooBins + mNumSimpleBins - 1) / mNumSimpleBins; std::vector<block> k0(keySize * mBinSize), k1(keySize * mBinSize); //std::vector<u64> idx0(mBinSize), idx1(mBinSize); auto k0Iter = k0.data(), k1Iter = k1.data(); //auto idx0Iter = idx0.data(), idx1Iter = idx1.data(); for (; i < binSizes[bIdx]; ++i) { span<block> kk0(k0Iter, kDepth + 1), g0(k0Iter + kDepth + 1, groupSize), kk1(k1Iter, kDepth + 1), g1(k1Iter + kDepth + 1, groupSize); k0Iter += keySize; k1Iter += keySize; u8 hashIdx = *binIter >> 56; u64 itemIdx = *binIter & mask; u64 cuckooIdx = CuckooIndex<>::getHash(hashs[itemIdx], hashIdx, numCuckooBins) - binOffset; ++binIter; auto bigBlockoffset = cuckooIdx % mBigBlockSize; auto bigBlockIdx = cuckooIdx / mBigBlockSize; BgiPirClient::keyGen(bigBlockIdx, mPrng.get<block>(), kk0, g0, kk1, g1); // the index of the mask that will mask this item auto rIdx = *piIter = itemIdx * mCuckooParams.mNumHashes + hashIdx * mBigBlockSize + bigBlockoffset; // the masked value that will be inputted into the PSI *shareIter = r[rIdx] ^ inputs[itemIdx]; //*shareIter = inputs[itemIdx]; //if (itemIdx == 0) // ostreamLock(std::cout) // << "item[" << i << "] bin " << bIdx // << " block " << bigBlockIdx // << " offset " << bigBlockoffset // << " psi " << *shareIter << std::endl; // This will be used to map itemed items in the intersection back to their input item inputMap.insert({ queryIdx, itemIdx }); ++shareIter; ++piIter; ++queryIdx; } u64 rem = mBinSize - i; binIter += rem; for (u64 i = 0; i < rem; ++i) { *piIter++ = dummyPermIdx++; } //s0.asyncSendCopy(k0); //s0.asyncSendCopy(k1); //s1.asyncSendCopy(k1); //s1.asyncSendCopy(k0); s0.asyncSend(std::move(k0)); s1.asyncSend(std::move(k1)); } std::vector<u32> pi1(permSize), pi0(permSize), pi1Inv(permSize); for (u32 i = 0; i < pi1.size(); ++i) pi1[i] = i; PRNG prng(rSeed ^ OneBlock); std::random_shuffle(pi1.begin(), pi1.end(), prng); //std::vector<block> pi1RS(pi.size()); for (u64 i = 0; i < permSize; ++i) { //auto pi1i = pi1[i]; //pi1RS[i] = r[pi1i] ^ s[pi1i]; pi1Inv[pi1[i]] = i; //std::cout << "pi1(r + s)[" << i << "] " << pi1RS[i] << std::endl; } std::vector<block> piS0(r.size()); for (u64 i = 0; i < permSize; ++i) { //std::cout << "r[" << i << "] " << r[i] << std::endl; //std::cout << "pi(r + s)[" << i << "]=" << (r[pi[i]] ^ s[pi[i]]) << std::endl; pi0[i] = pi1Inv[pi[i]]; piS0[i] = piS1[i] ^ s[pi[i]]; //std::cout << "pi (r + s)[" << i << "] = " << (r[pi[i]] ^ s[pi[i]]) << " = " << r[pi[i]] << " ^ " << s[pi[i]] << " c " << pi[i] << std::endl; //std::cout << "pi`(r + s)[" << i << "] = " << pi1RS[pi0[i]] <<" c " << pi0[pi1[i]] << std::endl; } s0.asyncSend(std::move(pi0)); s0.asyncSend(std::move(piS0)); //rGen.ecbEncBlocks(r.data(), r.size(), r.data()); //for (u64 i = 0; i < shares.size(); ++i) //{ // std::cout << IoStream::lock << "cshares[" << i << "] " << shares[i] << " input[" << sharesIdx[i]<<"]" << std::endl << IoStream::unlock; //} mPsi.sendInput(shares, s0); mIntersection.reserve(mPsi.mIntersection.size()); for (u64 i = 0; i < mPsi.mIntersection.size(); ++i) { // divide index by #hashes mIntersection.emplace(inputMap[mPsi.mIntersection[i]]); } }

const double Gaussian2D::volume() const { return pow(sqrt(2.0 * pi()) * bandwidth_, 2.0); }

double radToDeg(double rad) { return rad * 180.0 / pi(); }

// Decryption and Verification procedure int crypto_aead_decrypt( unsigned char *m,unsigned long long *mlen, unsigned char *nsec, const unsigned char *c,unsigned long long clen, const unsigned char *ad,unsigned long long adlen, const unsigned char *npub, const unsigned char *k ) { //... //... the code for the cipher implementation goes here, //... generating a plaintext m[0],m[1],...,m[*mlen-1] //... and secret message number nsec[0],nsec[1],... //... from a ciphertext c[0],c[1],...,c[clen-1] //... and associated data ad[0],ad[1],...,ad[adlen-1] //... and public message number npub[0],npub[1],... //... and secret key k[0],k[1],... //... // some 64-bit temp variables u_int64_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13; // more 64-bit temp variables u_int64_t x0, x1, x2, x3, y0, y1, y2, y3, z0, z1, z2, z3; // pointers to 64-bit variables u_int64_t *c64, *m64, *ad64, *nsec64, *npub64, *k64; // an array for storing some temporal values for the Tag computation u_int64_t tempTag[CRYPTO_ABYTES/W] = {0}; // counter ctr is a 64-bit variable in all variants of PiCipher u_int64_t ctr = 0x0000000000000000ull; // an array for the Common Internal State u_int64_t CIS[IS_SIZE]={0}; // pointers that look at the used data arrays as arrays of bytes u_int8_t *InternalState8, *CommonInternalState8, *tempTag8; // variables for dealing with various lengths of the plaintext and associated data int LastMessageChunkLength, LastADChunkLength; // different iterator variables unsigned long long i, j, jj, ii, b, i1, j1, a; c64 = (u_int64_t *) c; m64 = (u_int64_t *) m; ad64 = (u_int64_t *) ad; nsec64 = (u_int64_t *) nsec; npub64 = (u_int64_t *) npub; k64 = (u_int64_t *) k; InternalState8 = (u_int8_t *) IS; CommonInternalState8 = (u_int8_t *) CIS; tempTag8 = (u_int8_t *) tempTag; // phase 1: Initialization for (i = 0; i < IS_SIZE; i++ ) { IS[i] = 0; } // injection of the key IS[0] = k64[0]; IS[1] = k64[1]; IS[2] = k64[2]; IS[3] = k64[3]; // injection of the nonce (public message number - PMN) IS[4] = npub64[0]; IS[5] = npub64[1]; IS[6] = npub64[2]; IS[7] = npub64[3]; IS[8] = npub64[4]; IS[9] = npub64[5]; IS[10] = npub64[6]; IS[11] = npub64[7]; // appending a single 1 to the concatenated value of the key and PMN InternalState8[96] = 0x01; // applying the permutation function pi pi(); // initialization of the Common Internal State (CIS), common for all parallel invocations of pi() with different ctrs for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // initialization of the ctr obtained from the first 64 bits of the capacity of CIS ctr = CIS[4]; // phase 2: Processing the associated data b = 0; a = adlen/RATE; for ( j = 0; j < a; j ++ ) { // IS for the triplex component is initialized by the CIS for every AD block for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr ++; // Inject ctr + j in IS IS[0] = IS[0] ^ ctr; pi(); // process the AD block // Inject the AD block for ( i = 0; i < N; i += 2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { IS[i*WORDS_CHUNK+i1] = IS[i*WORDS_CHUNK+i1] ^ ad64[b]; b++; } } pi(); // Collect the tag for this block // Sum of the tags componentwise, where the length of one component is W jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the last AD block is not the full block, we process it byte by byte LastADChunkLength = adlen % RATE; if ( LastADChunkLength ) { b = b * W; i1 = 0; for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); for ( i = 0; i < LastADChunkLength; i++ ) { InternalState8[i1] = InternalState8[i1] ^ ad[b+i]; i1++; if( i1 % (RATE_OUT) == 0 ) i1 += RATE_OUT; } // padding with 10* InternalState8[i1] = InternalState8[i1] ^ 0x01; pi(); //updating the tag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the AD is full blocks we still need to append 10* and it is done in an additional block else{ for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); // padding with 10* InternalState8[0] = InternalState8[0] ^ 0x01; pi(); //updating the tag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // updating the Common Internal State by injection of the tag (tempTag) obtained from the associated data jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { IS[i*WORDS_CHUNK+i1] = CIS[i*WORDS_CHUNK+i1] ^ tempTag[jj]; IS[(i+1)*WORDS_CHUNK+i1] = CIS[(i+1)*WORDS_CHUNK+i1]; jj++; } } pi(); for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // phase 3: Processing the secret message number if ( CRYPTO_NSECBYTES > 0 ) { for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); // decrypt the SMN // Inject the SMN i1 = 0; for ( i = 0; i < CRYPTO_NSECBYTES; i++ ) { nsec[i] = InternalState8[i1] ^ c[i]; InternalState8[i1] = c[i]; i1++; if( i1 % (RATE_OUT) == 0 ) i1 += RATE_OUT; } // padding with 10* InternalState8[CRYPTO_NSECBYTES] = InternalState8[CRYPTO_NSECBYTES] ^ 0x01; pi(); // updating the Common Internal State from the encrypted SMN for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // Collect the tag from this encryption and update the tempTag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } //phase 4: Processing the ciphertext b = 0; for ( j = 0; j < (clen-CRYPTO_ABYTES-CRYPTO_NSECBYTES)/RATE; j ++ ) { for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr ++; IS[0] = IS[0] ^ ctr; pi(); // decrypt the ciphertext c for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { // XOR the IS_bitrate (InternalState[0], InternalSate[2], ...) with the c to obtain m m64[b] = IS[i*WORDS_CHUNK+i1] ^ c64[bSMN+b]; // in order to proceed for tag computation, put the ciphertext data in the InternalState IS[i*WORDS_CHUNK+i1] = c64[bSMN+b]; b++; } } pi(); // Collect the tag from this decryption and update the tempTag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the last ciphertext block is not the full block, we process it byte by byte LastMessageChunkLength = (clen-CRYPTO_ABYTES-CRYPTO_NSECBYTES) % RATE; if ( LastMessageChunkLength ) { b = b * W; i1 = 0; for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr ++; IS[0] = IS[0] ^ ctr; pi(); for ( i = 0; i < LastMessageChunkLength; i++ ) { m[b+i] = InternalState8[i1] ^ c[CRYPTO_NSECBYTES+b+i]; InternalState8[i1] = c[CRYPTO_NSECBYTES+b+i]; i1++; if( i1 % (RATE_OUT) == 0 ) i1 += RATE_OUT; } // padding with 10* InternalState8[i1] = InternalState8[i1] ^ 0x01; pi(); // updating the tag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the message is full blocks we still need to append 10* and it is done in to an additional block else{ for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); // padding with 10* InternalState8[0] = InternalState8[0] ^ 0x01; pi(); //updating the tag jj = 0; for ( i = 0; i < NTag; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } //updating the length of the message *mlen = clen-CRYPTO_ABYTES-CRYPTO_NSECBYTES; // tag verification for ( ii = (*mlen + CRYPTO_NSECBYTES); ii < clen; ii ++ ) { if ( c[ii] != tempTag8[ii-(*mlen + CRYPTO_NSECBYTES)] ) return -1; } return 0; }

void Stokes::FACOps::smooth_Tackley_2D (SAMRAI::solv::SAMRAIVectorReal<double>& solution, const SAMRAI::solv::SAMRAIVectorReal<double>& residual, int ln, int num_sweeps, double residual_tolerance) { const int p_id(solution.getComponentDescriptorIndex(0)), p_rhs_id(residual.getComponentDescriptorIndex(0)), v_id(solution.getComponentDescriptorIndex(1)), v_rhs_id(residual.getComponentDescriptorIndex(1)); #ifdef DEBUG_CHECK_ASSERTIONS if (solution.getPatchHierarchy() != d_hierarchy || residual.getPatchHierarchy() != d_hierarchy) { TBOX_ERROR(d_object_name << ": Vector hierarchy does not match\n" "internal hierarchy."); } #endif boost::shared_ptr<SAMRAI::hier::PatchLevel> level = d_hierarchy->getPatchLevel(ln); /* Only need to sync the rhs once. This sync is needed because calculating a new pressure update requires computing in the ghost region so that the update for the velocity inside the box will be correct. */ p_refine_patch_strategy.setTargetDataId(p_id); v_refine_patch_strategy.setTargetDataId(v_id); set_boundaries(p_id,v_id,level,true); xeqScheduleGhostFillNoCoarse(p_rhs_id,v_rhs_id,ln); if (ln > d_ln_min) { /* * Perform a one-time transfer of data from coarser level, * to fill ghost boundaries that will not change through * the smoothing loop. */ xeqScheduleGhostFill(p_id, v_id, ln); } double theta_momentum=0.7; double theta_continuity=1.0; /* * Smooth the number of sweeps specified or until * the convergence is satisfactory. */ double maxres; /* * Instead of checking residual convergence globally, we check the * converged flag. This avoids possible round-off errors affecting * different processes differently, leading to disagreement on * whether to continue smoothing. */ const SAMRAI::hier::Index ip(1,0), jp(0,1); bool converged = false; for (int sweep=0; sweep < num_sweeps*(1<<(d_ln_max-ln)) && !converged; ++sweep) { maxres=0; /* vx sweep */ xeqScheduleGhostFillNoCoarse(p_id,invalid_id,ln); for(int rb=0;rb<2;++rb) { xeqScheduleGhostFillNoCoarse(invalid_id,v_id,ln); for (SAMRAI::hier::PatchLevel::Iterator pi(level->begin()); pi!=level->end(); ++pi) { boost::shared_ptr<SAMRAI::hier::Patch> patch = *pi; boost::shared_ptr<SAMRAI::pdat::CellData<double> > p_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(p_id)); SAMRAI::pdat::CellData<double> &p(*p_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_id)); SAMRAI::pdat::SideData<double> &v(*v_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_rhs_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_rhs_id)); SAMRAI::pdat::SideData<double> &v_rhs(*v_rhs_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > cell_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(cell_viscosity_id)); SAMRAI::pdat::CellData<double> &cell_viscosity(*cell_visc_ptr); boost::shared_ptr<SAMRAI::pdat::NodeData<double> > edge_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::NodeData<double> > (patch->getPatchData(edge_viscosity_id)); SAMRAI::pdat::NodeData<double> &edge_viscosity(*edge_visc_ptr); SAMRAI::hier::Box pbox=patch->getBox(); boost::shared_ptr<SAMRAI::geom::CartesianPatchGeometry> geom = boost::dynamic_pointer_cast<SAMRAI::geom::CartesianPatchGeometry> (patch->getPatchGeometry()); double dx = geom->getDx()[0]; double dy = geom->getDx()[1]; for(int j=pbox.lower(1); j<=pbox.upper(1); ++j) { /* Do the red-black skip */ int i_min=pbox.lower(0) + (abs(pbox.lower(0) + j + rb))%2; for(int i=i_min; i<=pbox.upper(0)+1; i+=2) { SAMRAI::pdat::CellIndex center(SAMRAI::tbox::Dimension(2)); center[0]=i; center[1]=j; /* Update v */ smooth_V_2D(0,pbox,geom,center,ip,jp, p,v,v_rhs,maxres,dx,dy,cell_viscosity, edge_viscosity,theta_momentum); } } } set_boundaries(invalid_id,v_id,level,true); } /* vy sweep */ for(int rb=0;rb<2;++rb) { xeqScheduleGhostFillNoCoarse(invalid_id,v_id,ln); for (SAMRAI::hier::PatchLevel::Iterator pi(level->begin()); pi!=level->end(); ++pi) { boost::shared_ptr<SAMRAI::hier::Patch> patch = *pi; boost::shared_ptr<SAMRAI::pdat::CellData<double> > p_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(p_id)); SAMRAI::pdat::CellData<double> &p(*p_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_id)); SAMRAI::pdat::SideData<double> &v(*v_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_rhs_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_rhs_id)); SAMRAI::pdat::SideData<double> &v_rhs(*v_rhs_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > cell_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(cell_viscosity_id)); SAMRAI::pdat::CellData<double> &cell_viscosity(*cell_visc_ptr); boost::shared_ptr<SAMRAI::pdat::NodeData<double> > edge_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::NodeData<double> > (patch->getPatchData(edge_viscosity_id)); SAMRAI::pdat::NodeData<double> &edge_viscosity(*edge_visc_ptr); SAMRAI::hier::Box pbox=patch->getBox(); boost::shared_ptr<SAMRAI::geom::CartesianPatchGeometry> geom = boost::dynamic_pointer_cast<SAMRAI::geom::CartesianPatchGeometry> (patch->getPatchGeometry()); double dx = geom->getDx()[0]; double dy = geom->getDx()[1]; for(int j=pbox.lower(1); j<=pbox.upper(1)+1; ++j) { /* Do the red-black skip */ int i_min=pbox.lower(0) + (abs(pbox.lower(0) + j + rb))%2; for(int i=i_min; i<=pbox.upper(0); i+=2) { SAMRAI::pdat::CellIndex center(SAMRAI::tbox::Dimension(2)); center[0]=i; center[1]=j; /* Update v */ smooth_V_2D(1,pbox,geom,center,jp,ip, p,v,v_rhs,maxres,dy,dx,cell_viscosity, edge_viscosity,theta_momentum); } } } set_boundaries(invalid_id,v_id,level,true); } /* p sweep No need for red-black, because dp does not depend on the pressure. */ xeqScheduleGhostFillNoCoarse(invalid_id,v_id,ln); for (SAMRAI::hier::PatchLevel::Iterator pi(level->begin()); pi!=level->end(); ++pi) { boost::shared_ptr<SAMRAI::hier::Patch> patch = *pi; boost::shared_ptr<SAMRAI::pdat::CellData<double> > p_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(p_id)); SAMRAI::pdat::CellData<double> &p(*p_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > dp_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(dp_id)); SAMRAI::pdat::CellData<double> &dp(*dp_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > p_rhs_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(p_rhs_id)); SAMRAI::pdat::CellData<double> &p_rhs(*p_rhs_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_id)); SAMRAI::pdat::SideData<double> &v(*v_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > cell_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(cell_viscosity_id)); SAMRAI::pdat::CellData<double> &cell_viscosity(*cell_visc_ptr); boost::shared_ptr<SAMRAI::pdat::NodeData<double> > edge_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::NodeData<double> > (patch->getPatchData(edge_viscosity_id)); SAMRAI::pdat::NodeData<double> &edge_viscosity(*edge_visc_ptr); SAMRAI::hier::Box pbox=patch->getBox(); boost::shared_ptr<SAMRAI::geom::CartesianPatchGeometry> geom = boost::dynamic_pointer_cast<SAMRAI::geom::CartesianPatchGeometry> (patch->getPatchGeometry()); double dx = geom->getDx()[0]; double dy = geom->getDx()[1]; SAMRAI::pdat::CellIterator cend(SAMRAI::pdat::CellGeometry::end(pbox)); for(SAMRAI::pdat::CellIterator ci(SAMRAI::pdat::CellGeometry::begin(pbox)); ci!=cend; ++ci) { const SAMRAI::pdat::CellIndex ¢er(*ci); const SAMRAI::pdat::SideIndex x(center,0,SAMRAI::pdat::SideIndex::Lower), y(center,1,SAMRAI::pdat::SideIndex::Lower); /* Update p */ double dvx_dx=(v(x+ip) - v(x))/dx; double dvy_dy=(v(y+jp) - v(y))/dy; double delta_R_continuity= p_rhs(center) - dvx_dx - dvy_dy; /* No scaling here, though there should be. */ maxres=std::max(maxres,std::fabs(delta_R_continuity)); dp(center)=delta_R_continuity*theta_continuity /Stokes_dRc_dp_2D(pbox,center,x,y,cell_viscosity,edge_viscosity,v,dx,dy); p(center)+=dp(center); } } set_boundaries(p_id,invalid_id,level,true); /* fix v sweep */ xeqScheduleGhostFillNoCoarse(dp_id,invalid_id,ln); for (SAMRAI::hier::PatchLevel::Iterator pi(level->begin()); pi!=level->end(); ++pi) { boost::shared_ptr<SAMRAI::hier::Patch> patch = *pi; boost::shared_ptr<SAMRAI::pdat::CellData<double> > dp_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(dp_id)); SAMRAI::pdat::CellData<double> &dp(*dp_ptr); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (patch->getPatchData(v_id)); SAMRAI::pdat::SideData<double> &v(*v_ptr); boost::shared_ptr<SAMRAI::pdat::CellData<double> > cell_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::CellData<double> > (patch->getPatchData(cell_viscosity_id)); SAMRAI::pdat::CellData<double> &cell_viscosity(*cell_visc_ptr); boost::shared_ptr<SAMRAI::pdat::NodeData<double> > edge_visc_ptr = boost::dynamic_pointer_cast<SAMRAI::pdat::NodeData<double> > (patch->getPatchData(edge_viscosity_id)); SAMRAI::pdat::NodeData<double> &edge_viscosity(*edge_visc_ptr); SAMRAI::hier::Box pbox=patch->getBox(); boost::shared_ptr<SAMRAI::geom::CartesianPatchGeometry> geom = boost::dynamic_pointer_cast<SAMRAI::geom::CartesianPatchGeometry> (patch->getPatchGeometry()); double dx = geom->getDx()[0]; double dy = geom->getDx()[1]; pbox.growUpper(SAMRAI::hier::IntVector::getOne(d_dim)); SAMRAI::pdat::CellIterator cend(SAMRAI::pdat::CellGeometry::end(pbox)); for(SAMRAI::pdat::CellIterator ci(SAMRAI::pdat::CellGeometry::begin(pbox)); ci!=cend; ++ci) { const SAMRAI::pdat::CellIndex ¢er(*ci); const SAMRAI::pdat::SideIndex x(center,0,SAMRAI::pdat::SideIndex::Lower), y(center,1,SAMRAI::pdat::SideIndex::Lower); const SAMRAI::pdat::NodeIndex edge(center,SAMRAI::pdat::NodeIndex::LowerLeft); /* Update v */ if(center[1]<pbox.upper(1)) { if(!((center[0]==pbox.lower(0) && v(x-ip)==boundary_value) || (center[0]==pbox.upper(0) && v(x+ip)==boundary_value))) v(x)+=(dp(center) - dp(center-ip)) /(dx*Stokes_dRm_dv_2D(cell_viscosity,edge_viscosity,center, center-ip,edge+jp,edge,dx,dy)); } if(center[0]<pbox.upper(0)) { if(!((center[1]==pbox.lower(1) && v(y-jp)==boundary_value) || (center[1]==pbox.upper(1) && v(y+jp)==boundary_value))) v(y)+=(dp(center) - dp(center-jp)) /(dy*Stokes_dRm_dv_2D(cell_viscosity,edge_viscosity,center, center-jp,edge+ip,edge,dy,dx)); } } } set_boundaries(invalid_id,v_id,level,true); // if (residual_tolerance >= 0.0) { /* * Check for early end of sweeps due to convergence * only if it is numerically possible (user gave a * non negative value for residual tolerance). */ converged = maxres < residual_tolerance; const SAMRAI::tbox::SAMRAI_MPI& mpi(d_hierarchy->getMPI()); int tmp= converged ? 1 : 0; if (mpi.getSize() > 1) { mpi.AllReduce(&tmp, 1, MPI_MIN); } converged=(tmp==1); // if (d_enable_logging) // SAMRAI::tbox::plog // // << d_object_name << "\n" // << "Tackley " << ln << " " << sweep << " : " << maxres << "\n"; // } } }

double degToRad(double deg) { return deg / 180.0 * pi(); }

//-***************************************************************************** Abc::Box3d PolyMesh::writeSample( const Abc::OSampleSelector &iSS ) { // First, call base class sample write, which will return bounds // of any children. Abc::index_t sampleIndex = iSS.getIndex(); Abc::Box3d bounds = Exportable::writeSample( iSS ); // If we're not deforming, don't bother with new sample. // Do calculate bounds and set them, though. if ( sampleIndex != 0 && !m_deforming ) { bounds.extendBy( m_firstSampleSelfBounds ); m_boundsProperty.set( bounds, iSS ); return bounds; } // Make a mesh MStatus status; MFnMesh mesh( m_dagPath, &status ); CHECK_MAYA_STATUS; mesh.updateSurface(); mesh.syncObject(); // Make a sample. Abc::OPolyMeshSchema::Sample abcPolyMeshSample; //-************************************************************************* // WRITE VERTICES //-************************************************************************* MPointArray vertices; mesh.getPoints( vertices ); size_t npoints = vertices.length(); std::vector<Abc::V3f> v3fVerts( npoints ); Abc::Box3d shapeBounds; shapeBounds.makeEmpty(); for ( size_t i = 0; i < npoints; ++i ) { const MPoint &vi = vertices[i]; Abc::V3f pi( vi.x, vi.y, vi.z ); v3fVerts[i] = pi; shapeBounds.extendBy( Abc::V3d( vi.x, vi.y, vi.z ) ); } if ( sampleIndex == 0 ) { m_firstSampleSelfBounds = shapeBounds; } bounds.extendBy( shapeBounds ); // Set the bounds sample. m_boundsProperty.set( bounds, iSS ); // Stuff the positions into the mesh sample. abcPolyMeshSample.setPositions( Abc::V3fArraySample( v3fVerts ) ); //-************************************************************************* // OTHER STUFF, FOR FIRST OR LATER VERTICES //-************************************************************************* std::vector<Abc::int32_t> abcIndices; std::vector<Abc::int32_t> abcCounts; std::vector<Abc::N3f> abcNormals; std::vector<Abc::V2f> abcUvs; //-************************************************************************* // GET MESH NORMALS & UVS //-************************************************************************* size_t nnormals = mesh.numNormals(); MFloatVectorArray meshNorms; if ( nnormals > 0 ) { mesh.getNormals( meshNorms, MSpace::kObject ); } size_t nuvs = mesh.numUVs(); MFloatArray meshU; MFloatArray meshV; if ( nuvs > 0 ) { mesh.getUVs( meshU, meshV ); } //-************************************************************************* // LOOP OVER FIRST OR SUBSEQUENT SAMPLES //-************************************************************************* if ( sampleIndex == 0 ) { // FIRST SAMPLE // Loop over polys. size_t npolys = mesh.numPolygons(); abcCounts.resize( npolys ); Abc::int32_t faceIndex = 0; Abc::int32_t faceStartVertexIndex = 0; for ( MItMeshPolygon piter( m_dagPath ); !piter.isDone(); piter.next(), ++faceIndex ) { Abc::int32_t faceCount = piter.polygonVertexCount(); abcCounts[faceIndex] = faceCount; faceStartVertexIndex += faceCount; for ( Abc::int32_t faceVertex = 0; faceVertex < faceCount; ++faceVertex ) { abcIndices.push_back( piter.vertexIndex( faceVertex ) ); if ( nnormals > 0 ) { size_t normIndex = piter.normalIndex( faceVertex ); const MFloatVector &norm = meshNorms[normIndex]; Abc::N3f abcNorm( norm[0], norm[1], norm[2] ); abcNormals.push_back( abcNorm ); } if ( nuvs > 0 ) { int uvIndex = 0; piter.getUVIndex( faceVertex, uvIndex ); Abc::V2f abcUv( meshU[uvIndex], meshV[uvIndex] ); abcUvs.push_back( abcUv ); } } } // We have now collected abcIndices, abcStarts, abcNormals, and abcUvs. // Put them into the sample. abcPolyMeshSample.setIndices( Abc::Int32ArraySample( abcIndices ) ); abcPolyMeshSample.setCounts( Abc::Int32ArraySample( abcCounts ) ); if ( nnormals > 0 && m_normals ) { m_normals.set( Abc::N3fArraySample( abcNormals ), iSS ); } if ( nuvs > 0 && m_sts ) { m_sts.set( Abc::V2fArraySample( abcUvs ), iSS ); } } else if ( ( nnormals > 0 && m_normals ) || ( nuvs > 0 && m_sts ) ) { // SUBSEQUENT SAMPLES // Just gathering normals and uvs. // (vertices handled above) // Loop over polys. Abc::int32_t faceIndex = 0; Abc::int32_t faceStartVertexIndex = 0; for ( MItMeshPolygon piter( m_dagPath ); !piter.isDone(); piter.next(), ++faceIndex ) { Abc::int32_t faceCount = piter.polygonVertexCount(); for ( Abc::int32_t faceVertex = 0; faceVertex < faceCount; ++faceVertex ) { if ( nnormals > 0 ) { size_t normIndex = piter.normalIndex( faceVertex ); const MFloatVector &norm = meshNorms[normIndex]; Abc::N3f abcNorm( norm[0], norm[1], norm[2] ); abcNormals.push_back( abcNorm ); } if ( nuvs > 0 ) { int uvIndex = 0; piter.getUVIndex( faceVertex, uvIndex ); Abc::V2f abcUv( meshU[uvIndex], meshV[uvIndex] ); abcUvs.push_back( abcUv ); } } } // We have now collected abcNormals, and abcUvs. // Put them into the sample. if ( nnormals > 0 && m_normals ) { m_normals.set( Abc::N3fArraySample( abcNormals ), iSS ); } if ( nuvs > 0 ) { m_sts.set( Abc::V2fArraySample( abcUvs ), iSS ); } } // Set the mesh sample. m_polyMesh.getSchema().set( abcPolyMeshSample, iSS ); return bounds; }

/** * Factor to convert from degrees to radians **********************************************************************/ static inline double degree() throw() { return pi() / 180; }

void IPCUninstallMcf::onProgress(uint64& prog) { MCFCore::Misc::ProgressInfo pi(prog); onProgressEvent(pi); }

bool PCB_EDIT_FRAME::AppendBoardFile( const wxString& aFullFileName, int aCtl ) { IO_MGR::PCB_FILE_T pluginType = plugin_type( aFullFileName, aCtl ); PLUGIN::RELEASER pi( IO_MGR::PluginFind( pluginType ) ); // keep trace of existing items, in order to know what are the new items // (for undo command for instance) // Tracks are inserted, not append, so mark existing tracks to know what are // the new tracks for( TRACK* track = GetBoard()->m_Track; track; track = track->Next() ) track->SetFlags( FLAG0 ); // Other items are append to the item list, so keep trace to the // last existing item is enough MODULE* module = GetBoard()->m_Modules.GetLast(); BOARD_ITEM* drawing = GetBoard()->m_Drawings.GetLast(); int zonescount = GetBoard()->GetAreaCount(); // Keep also the count of copper layers, because we can happen boards // with different copper layers counts, // and the enabled layers int initialCopperLayerCount = GetBoard()->GetCopperLayerCount(); LSET initialEnabledLayers = GetBoard()->GetEnabledLayers(); try { PROPERTIES props; char xbuf[30]; char ybuf[30]; // EAGLE_PLUGIN can use this info to center the BOARD, but it does not yet. sprintf( xbuf, "%d", GetPageSizeIU().x ); sprintf( ybuf, "%d", GetPageSizeIU().y ); props["page_width"] = xbuf; props["page_height"] = ybuf; GetDesignSettings().m_NetClasses.Clear(); pi->Load( aFullFileName, GetBoard(), &props ); } catch( const IO_ERROR& ioe ) { for( TRACK* track = GetBoard()->m_Track; track; track = track->Next() ) track->ClearFlags( FLAG0 ); wxString msg = wxString::Format( _( "Error loading board.\n%s" ), GetChars( ioe.errorText ) ); DisplayError( this, msg ); return false; } // Now prepare a block move command to place the new items, and // prepare the undo command. BLOCK_SELECTOR& blockmove = GetScreen()->m_BlockLocate; HandleBlockBegin( NULL, BLOCK_PRESELECT_MOVE, wxPoint( 0, 0) ); PICKED_ITEMS_LIST& blockitemsList = blockmove.GetItems(); PICKED_ITEMS_LIST undoListPicker; ITEM_PICKER picker( NULL, UR_NEW ); EDA_RECT bbox; // the new items bounding box, for block move bool bboxInit = true; // true until the bounding box is initialized for( TRACK* track = GetBoard()->m_Track; track; track = track->Next() ) { if( track->GetFlags() & FLAG0 ) { track->ClearFlags( FLAG0 ); continue; } track->SetFlags( IS_MOVED ); picker.SetItem( track ); undoListPicker.PushItem( picker ); blockitemsList.PushItem( picker ); if( bboxInit ) bbox = track->GetBoundingBox(); else bbox.Merge( track->GetBoundingBox() ); bboxInit = false; } if( module ) module = module->Next(); else module = GetBoard()->m_Modules; for( ; module; module = module->Next() ) { module->SetFlags( IS_MOVED ); picker.SetItem( module ); undoListPicker.PushItem( picker ); blockitemsList.PushItem( picker ); if( bboxInit ) bbox = module->GetBoundingBox(); else bbox.Merge( module->GetBoundingBox() ); bboxInit = false; } if( drawing ) drawing = drawing->Next(); else drawing = GetBoard()->m_Drawings; for( ; drawing; drawing = drawing->Next() ) { drawing->SetFlags( IS_MOVED ); picker.SetItem( drawing ); undoListPicker.PushItem( picker ); blockitemsList.PushItem( picker ); if( bboxInit ) bbox = drawing->GetBoundingBox(); else bbox.Merge( drawing->GetBoundingBox() ); bboxInit = false; } for( ZONE_CONTAINER* zone = GetBoard()->GetArea( zonescount ); zone; zone = GetBoard()->GetArea( zonescount ) ) { zone->SetFlags( IS_MOVED ); picker.SetItem( zone ); undoListPicker.PushItem( picker ); blockitemsList.PushItem( picker ); zonescount++; if( bboxInit ) bbox = zone->GetBoundingBox(); else bbox.Merge( zone->GetBoundingBox() ); bboxInit = false; } SaveCopyInUndoList( undoListPicker, UR_NEW ); // we should not ask PLUGINs to do these items: int copperLayerCount = GetBoard()->GetCopperLayerCount(); if( copperLayerCount > initialCopperLayerCount ) GetBoard()->SetCopperLayerCount( copperLayerCount ); // Enable all used layers, and make them visible: LSET enabledLayers = GetBoard()->GetEnabledLayers(); enabledLayers |= initialEnabledLayers; GetBoard()->SetEnabledLayers( enabledLayers ); GetBoard()->SetVisibleLayers( enabledLayers ); ReCreateLayerBox(); ReFillLayerWidget(); if( IsGalCanvasActive() ) static_cast<PCB_DRAW_PANEL_GAL*>( GetGalCanvas() )->SyncLayersVisibility( GetBoard() ); GetBoard()->BuildListOfNets(); GetBoard()->SynchronizeNetsAndNetClasses(); SetStatusText( wxEmptyString ); BestZoom(); // Finish block move command: wxPoint cpos = GetNearestGridPosition( bbox.Centre() ); blockmove.SetOrigin( bbox.GetOrigin() ); blockmove.SetSize( bbox.GetSize() ); blockmove.SetLastCursorPosition( cpos ); HandleBlockEnd( NULL ); return true; }

EVP_PKEY *pki_evp::decryptKey() const { unsigned char *p; const unsigned char *p1; int outl, decsize; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char ckey[EVP_MAX_KEY_LENGTH]; EVP_PKEY *tmpkey; EVP_CIPHER_CTX ctx; const EVP_CIPHER *cipher = EVP_des_ede3_cbc(); char ownPassBuf[MAX_PASS_LENGTH] = ""; if (isPubKey()) { unsigned char *q; outl = i2d_PUBKEY(key, NULL); p = q = (unsigned char *)OPENSSL_malloc(outl); check_oom(q); i2d_PUBKEY(key, &p); p = q; tmpkey = d2i_PUBKEY(NULL, (const unsigned char**)&p, outl); OPENSSL_free(q); return tmpkey; } /* This key has its own password */ if (ownPass == ptPrivate) { int ret; pass_info pi(XCA_TITLE, qApp->translate("MainWindow", "Please enter the password to decrypt the private key: '%1'").arg(getIntName())); ret = MainWindow::passRead(ownPassBuf, MAX_PASS_LENGTH, 0, &pi); if (ret < 0) throw errorEx(tr("Password input aborted"), class_name); } else if (ownPass == ptBogus) { // BOGUS pass ownPassBuf[0] = '\0'; } else { memcpy(ownPassBuf, passwd, MAX_PASS_LENGTH); //printf("Orig password: '%s' len:%d\n", passwd, strlen(passwd)); while (md5passwd(ownPassBuf) != passHash && sha512passwd(ownPassBuf, passHash) != passHash) { int ret; //printf("Passhash= '%s', new hash= '%s', passwd= '%s'\n", //CCHAR(passHash), CCHAR(md5passwd(ownPassBuf)), ownPassBuf); pass_info p(XCA_TITLE, tr("Please enter the database password for decrypting the key '%1'").arg(getIntName())); ret = MainWindow::passRead(ownPassBuf, MAX_PASS_LENGTH, 0, &p); if (ret < 0) throw errorEx(tr("Password input aborted"), class_name); } } //printf("Using decrypt Pass: %s\n", ownPassBuf); p = (unsigned char *)OPENSSL_malloc(encKey.count()); check_oom(p); pki_openssl_error(); p1 = p; memset(iv, 0, EVP_MAX_IV_LENGTH); memcpy(iv, encKey.constData(), 8); /* recover the iv */ /* generate the key */ EVP_BytesToKey(cipher, EVP_sha1(), iv, (unsigned char *)ownPassBuf, strlen(ownPassBuf), 1, ckey,NULL); /* we use sha1 as message digest, * because an md5 version of the password is * stored in the database... */ EVP_CIPHER_CTX_init(&ctx); EVP_DecryptInit(&ctx, cipher, ckey, iv); EVP_DecryptUpdate(&ctx, p , &outl, (const unsigned char*)encKey.constData() +8, encKey.count() -8); decsize = outl; EVP_DecryptFinal(&ctx, p + decsize , &outl); decsize += outl; //printf("Decrypt decsize=%d, encKey_len=%d\n", decsize, encKey_len); pki_openssl_error(); tmpkey = d2i_PrivateKey(key->type, NULL, &p1, decsize); pki_openssl_error(); OPENSSL_free(p); EVP_CIPHER_CTX_cleanup(&ctx); pki_openssl_error(); if (EVP_PKEY_type(tmpkey->type) == EVP_PKEY_RSA) RSA_blinding_on(tmpkey->pkey.rsa, NULL); return tmpkey; }

HANDLE WINAPI EXP_NAME(OpenPlugin)(int OpenFrom, INT_PTR Item) { // Options.Read(); AutoUTF cline; if (OpenFrom == OPEN_PLUGINSMENU) { FarPnl pi(PANEL_ACTIVE); if (pi.IsOK()) { AutoUTF buf(MAX_PATH_LEN, L'\0'); fsf.GetCurrentDirectory(buf.capacity(), (PWSTR)buf.c_str()); if (!buf.empty()) ::PathAddBackslash((PWSTR)buf.c_str()); PluginPanelItem &PPI = pi[pi.CurrentItem()]; buf += PPI.FindData.lpwszFileName; cline = buf; } } else if (OpenFrom == OPEN_COMMANDLINE) { cline = (PCWSTR)Item; } FarList users; if (InitUsers(users)) { enum { HEIGHT = 14, WIDTH = 48, }; InitDialogItemF Items[] = { {DI_DOUBLEBOX, 3, 1, WIDTH - 4, HEIGHT - 2, 0, (PCWSTR)DlgTitle}, {DI_TEXT, 5, 2, 0, 0, 0, (PCWSTR)MUsername}, {DI_COMBOBOX, 5, 3, 42, 0, DIF_SELECTONENTRY, L""}, {DI_TEXT, 5, 4, 0, 0, 0, (PCWSTR)MPasword}, {DI_PSWEDIT, 5, 5, 42, 0, 0, L""}, {DI_CHECKBOX , 5, 6, 42, 0, 0, (PCWSTR)MRestricted}, {DI_TEXT, 0, 7, 0, 0, DIF_SEPARATOR, L""}, {DI_TEXT, 5, 8, 0, 0, 0, (PCWSTR)MCommandLine}, {DI_EDIT, 5, 9, 42, 0, DIF_HISTORY, cline.c_str()}, {DI_TEXT, 0, HEIGHT - 4, 0, 0, DIF_SEPARATOR, L""}, {DI_BUTTON, 0, HEIGHT - 3, 0, 0, DIF_CENTERGROUP, (PCWSTR)txtBtnOk}, {DI_BUTTON, 0, HEIGHT - 3, 0, 0, DIF_CENTERGROUP, (PCWSTR)txtBtnCancel}, }; size_t size = sizeofa(Items); FarDialogItem FarItems[size]; InitDialogItemsF(Items, FarItems, size); FarItems[size - 2].DefaultButton = 1; FarItems[2].ListItems = &users; FarItems[8].History = L"runas.comline"; FarDlg hDlg; if (hDlg.Init(psi.ModuleNumber, -1, -1, WIDTH, HEIGHT, L"Contents", FarItems, size)) { HRESULT err = NO_ERROR; while (true) { int ret = hDlg.Run(); if (ret > 0 && Items[ret].Data == (PCWSTR)txtBtnOk) { AutoUTF cmd(hDlg.Str(8)); if (hDlg.Check(5)) { err = ExecRestricted(cmd.c_str()); } else { AutoUTF user(hDlg.Str(2)); AutoUTF pass(hDlg.Str(4)); err = ExecAsUser(cmd.c_str(), user.c_str(), pass.c_str()); } if (err == NO_ERROR) { break; } else { PCWSTR Msg[] = {GetMsg(MError), cmd.c_str(), L"", GetMsg(txtBtnOk), }; ::SetLastError(err); psi.Message(psi.ModuleNumber, FMSG_WARNING | FMSG_ERRORTYPE, L"Contents", Msg, sizeofa(Msg), 1); } } else { break; } } } FreeUsers(users); } return INVALID_HANDLE_VALUE; }

void CircleObject::setObjectArea(qreal area) { qreal radius = qSqrt(area/pi()); setObjectRadius(radius); }

const double Gaussian1D::width() const { return sqrt(2.0 * pi()) * bandwidth_; }

void CircleObject::setObjectCircumference(qreal circumference) { qreal diameter = circumference/pi(); setObjectDiameter(diameter); }

const double Gaussian::volume(const unsigned& d) const { return pow(sqrt(2.0 * pi()) * bandwidth_, (double)d); }

// // This method is currently under development // lbool Logic::simplifyTree(PTRef tr) { vec<pi> queue; Map<PTRef,bool,PTRefHash> processed; queue.push(pi(tr)); lbool last_val = l_Undef; while (queue.size() != 0) { // First find a node with all children processed. int i = queue.size()-1; if (processed.contains(queue[i].x)) { queue.pop(); continue; } bool unprocessed_children = false; if (queue[i].done == false) { #ifdef SIMPLIFY_DEBUG cerr << "looking at term num " << queue[i].x.x << endl; #endif Pterm& t = getPterm(queue[i].x); for (int j = 0; j < t.size(); j++) { PTRef cr = t[j]; if (!processed.contains(cr)) { unprocessed_children = true; queue.push(pi(cr)); #ifdef SIMPLIFY_DEBUG cerr << "pushing child " << cr.x << endl; #endif } } queue[i].done = true; } if (unprocessed_children) continue; #ifdef SIMPLIFY_DEBUG cerr << "Found a node " << queue[i].x.x << endl; cerr << "Before simplification it looks like " << term_store.printTerm(queue[i].x) << endl; #endif // (1) Check if my children (potentially simplified now) exist in // term store and if so, replace them with the term store // representative // (2) Simplify in place // (3) See if the simplifications resulted in me changing, and if so, // look up from the table whether I'm already listed somewhere and add // a mapping to the canonical representative, or create a new entry for // me in the map. Pterm& t = getPterm(queue[i].x); // (1) #ifdef SIMPLIFY_DEBUG if (t.size() > 0) cerr << "Now looking into the children of " << queue[i].x.x << endl; else cerr << "The node " << queue[i].x.x << " has no children" << endl; #endif for (int e = 0; e < t.size(); e++) { PTRef cr = t[e]; #ifdef SIMPLIFY_DEBUG cerr << "child n. " << e << " is " << cr.x << endl; #endif assert(cr != queue[i].x); Pterm& c = getPterm(cr); PTLKey k; k.sym = c.symb(); for (int j = 0; j < c.size(); j++) k.args.push(c[j]); if (!isBooleanOperator(k.sym)) { assert(term_store.cplx_map.contains(k)); #ifdef SIMPLIFY_DEBUG cerr << cr.x << " is not a boolean operator "; cerr << "and it maps to " << term_store.cplx_map[k].x << endl; #endif t[e] = term_store.cplx_map[k]; assert(t[e] != queue[i].x); } else { assert(term_store.bool_map.contains(k)); #ifdef SIMPLIFY_DEBUG cerr << cr.x << " is a boolean operator" << " and it maps to " << term_store.bool_map[k].x << endl; #endif t[e] = term_store.bool_map[k]; assert(t[e] != queue[i].x); } } #ifdef SIMPLIFY_DEBUG cerr << "After processing the children ended up with node " << term_store.printTerm(queue[i].x, true) << endl; #endif // (2) Simplify in place PTRef orig = queue[i].x; // We need to save the original type in case the term gets simplified simplify(queue[i].x); #ifdef SIMPLIFY_DEBUG cerr << "-> which was now simplified to " << term_store.printTerm(queue[i].x, true) << endl; // I don't seem to remember why this should be true or false? // if (orig != queue[i].x) { // assert(isTrue(queue[i].x) || isFalse(queue[i].x)); // assert(isAnd(orig) || isOr(orig) || isEquality(orig) || isNot(orig)); // } #endif processed.insert(orig, true); // Make sure my key is in term hash #ifdef SIMPLIFY_DEBUG cerr << "Making sure " << orig.x << " is in term_store hash" << endl; cerr << "Pushing symb " << t.symb().x << " to hash key" << endl; #endif PTLKey k; k.sym = t.symb(); for (int j = 0; j < t.size(); j++) { #ifdef SIMPLIFY_DEBUG cerr << "Pushing arg " << t[j].x << " to hash key" << endl; #endif k.args.push(t[j]); } if (!isBooleanOperator(k.sym)) { if (!term_store.cplx_map.contains(k)) { term_store.cplx_map.insert(k, queue[i].x); #ifdef SIMPLIFY_DEBUG cerr << "sym " << k.sym.x << " args <"; for (int j = 0; j < k.args.size(); j++) { cerr << k.args[j].x << " "; } cerr << "> maps to " << term_store.cplx_map[k].x << endl; #endif } PTRef l = term_store.cplx_map[k]; // This is being kept on record in case the root term gets simplified if (isTrue(l)) last_val = l_True; else if (isFalse(l)) last_val = l_False; else last_val = l_Undef; } else { if (!term_store.bool_map.contains(k)) { term_store.bool_map.insert(k, queue[i].x); #ifdef SIMPLIFY_DEBUG cerr << "sym " << k.sym.x << " args "; for (int j = 0; j < k.args.size(); j++) { cerr << k.args[j].x << " "; } cerr << "maps to " << term_store.bool_map[k].x << endl; #endif } PTRef l = term_store.bool_map[k]; // This is being kept on record in case the root term gets simplified if (isTrue(l)) last_val = l_True; else if (isFalse(l)) last_val = l_False; else last_val = l_Undef; } queue.pop(); } return last_val; }

/** * Builds a list of commands for the right click on Editor Chunk Item operation. * * @return Returns the list of commands. */ std::vector<std::string> PropertiesHelper::command() { propMap_.clear(); std::vector<std::string> links; int index = 0; for (int i=0; i < propCount(); i++) { DataDescription* pDD = pType()->property( i ); if (!pDD->editable()) continue; if ( isUserDataObjectLink(i) ) { PyObjectPtr ob( propGetPy( i ), PyObjectPtr::STEAL_REFERENCE ); std::string uniqueId = PyString_AsString( PyTuple_GetItem( ob.getObject(), 0 ) ); if ( !uniqueId.empty() ) { links.push_back( "#"+propName(i) ); links.push_back( "#"+uniqueId ); links.push_back( "Delete Link" ); propMap_[index++] = PropertyIndex( i ); links.push_back( "##" ); links.push_back( "##" ); } } else if ( isUserDataObjectLinkArray(i) ) { PyObjectPtr ob( propGetPy( i ), PyObjectPtr::STEAL_REFERENCE ); SequenceDataType* dataType = static_cast<SequenceDataType*>( pDD->dataType() ); ArrayPropertiesHelper propArray; propArray.init( pItem(), &(dataType->getElemType()), ob.getObject()); int numProps = propArray.propCount(); if ( numProps > 0 ) { links.push_back( "#"+propName(i) ); links.push_back( "Delete All" ); propMap_[index++] = PropertyIndex( i ); links.push_back( "" ); // Iterate through the array of links for(int j = 0; j < numProps; j++) { PyObjectPtr link( propArray.propGetPy( j ), PyObjectPtr::STEAL_REFERENCE ); std::string uniqueId = PyString_AsString( PyTuple_GetItem( link.getObject(), 0 ) ); if ( !uniqueId.empty() ) { links.push_back( "#"+uniqueId ); links.push_back( "Delete Link" ); PropertyIndex pi( i ); pi.append( j ); propMap_[index++] = pi; links.push_back( "##" ); } } links.push_back( "##" ); } } } return links; }

void LIB_EDIT_FRAME::OnExportPart( wxCommandEvent& event ) { wxString msg, title; LIB_PART* part = getTargetPart(); if( !part ) { DisplayError( this, _( "There is no symbol selected to save." ) ); return; } wxFileName fn; fn.SetName( part->GetName().Lower() ); fn.SetExt( SchematicLibraryFileExtension ); wxFileDialog dlg( this, _( "Export Symbol" ), m_mruPath, fn.GetFullName(), SchematicLibraryFileWildcard(), wxFD_SAVE ); if( dlg.ShowModal() == wxID_CANCEL ) return; fn = dlg.GetPath(); fn.MakeAbsolute(); LIB_PART* old_part = NULL; SCH_PLUGIN::SCH_PLUGIN_RELEASER pi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_LEGACY ) ); if( fn.FileExists() ) { try { LIB_ALIAS* alias = pi->LoadSymbol( fn.GetFullPath(), part->GetName() ); if( alias ) old_part = alias->GetPart(); } catch( const IO_ERROR& ioe ) { msg.Printf( _( "Error occurred attempting to load symbol library file \"%s\"" ), fn.GetFullPath() ); DisplayErrorMessage( this, msg, ioe.What() ); return; } if( old_part ) { msg.Printf( _( "Symbol \"%s\" already exists in \"%s\"." ), part->GetName(), fn.GetFullName() ); KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING ); errorDlg.SetOKLabel( _( "Overwrite" ) ); errorDlg.DoNotShowCheckbox( __FILE__, __LINE__ ); if( errorDlg.ShowModal() == wxID_CANCEL ) return; } } if( fn.Exists() && !fn.IsDirWritable() ) { msg.Printf( _( "Write permissions are required to save library \"%s\"." ), fn.GetFullPath() ); DisplayError( this, msg ); return; } try { if( !fn.FileExists() ) pi->CreateSymbolLib( fn.GetFullPath() ); pi->SaveSymbol( fn.GetFullPath(), new LIB_PART( *part ) ); } catch( const IO_ERROR& ioe ) { msg = _( "Failed to create symbol library file " ) + fn.GetFullPath(); DisplayErrorMessage( this, msg, ioe.What() ); msg.Printf( _( "Error creating symbol library \"%s\"" ), fn.GetFullName() ); SetStatusText( msg ); return; } m_mruPath = fn.GetPath(); m_lastDrawItem = NULL; SetDrawItem( NULL ); msg.Printf( _( "Symbol \"%s\" saved in library \"%s\"" ), part->GetName(), fn.GetFullPath() ); SetStatusText( msg ); // See if the user wants it added to a library table (global or project) SYMBOL_LIB_TABLE* libTable = selectSymLibTable( true ); if( libTable ) { if( !m_libMgr->AddLibrary( fn.GetFullPath(), libTable ) ) { DisplayError( this, _( "Could not open the library file." ) ); return; } bool globalTable = ( libTable == &SYMBOL_LIB_TABLE::GetGlobalLibTable() ); saveSymbolLibTables( globalTable, !globalTable ); } }

void s1::fun2() { pi(); printf("%s \n", "儿子1fun2函数"); }

void PrintFiles(FileList* SrcPanel) { _ALGO(CleverSysLog clv(L"Alt-F5 (PrintFiles)")); string strPrinterName; DWORD Needed = 0, Returned; DWORD FileAttr; string strSelName; size_t DirsCount=0; size_t SelCount=SrcPanel->GetSelCount(); if (!SelCount) { _ALGO(SysLog(L"Error: !SelCount")); return; } // проверка каталогов _ALGO(SysLog(L"Check for FILE_ATTRIBUTE_DIRECTORY")); SrcPanel->GetSelName(nullptr,FileAttr); while (SrcPanel->GetSelName(&strSelName,FileAttr)) { if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY)) DirsCount++; } if (DirsCount==SelCount) return; EnumPrinters(PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, nullptr, PRINTER_INFO_LEVEL, nullptr, 0, &Needed, &Returned); if (!Needed) return; block_ptr<PRINTER_INFO> pi(Needed); if (!EnumPrinters(PRINTER_ENUM_LOCAL|PRINTER_ENUM_CONNECTIONS,nullptr,PRINTER_INFO_LEVEL,(LPBYTE)pi.get(),Needed,&Needed,&Returned)) { Global->CatchError(); Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotEnumeratePrinters),MSG(MOk)); return; } { _ALGO(CleverSysLog clv2(L"Show Menu")); LangString strTitle; string strName; if (SelCount==1) { SrcPanel->GetSelName(nullptr,FileAttr); SrcPanel->GetSelName(&strName,FileAttr); strSelName = TruncStr(strName,50); strTitle = MPrintTo; strTitle << InsertQuote(strSelName); } else { _ALGO(SysLog(L"Correct: SelCount-=DirsCount")); SelCount-=DirsCount; strTitle = MPrintFilesTo; strTitle << SelCount; } VMenu2 PrinterList(strTitle,nullptr,0,ScrY-4); PrinterList.SetFlags(VMENU_WRAPMODE|VMENU_SHOWAMPERSAND); PrinterList.SetPosition(-1,-1,0,0); AddToPrintersMenu(&PrinterList,pi.get(),Returned); if (PrinterList.Run()<0) { _ALGO(SysLog(L"ESC")); return; } strPrinterName = NullToEmpty(static_cast<const wchar_t*>(PrinterList.GetUserData(nullptr, 0))); } HANDLE hPrinter; if (!OpenPrinter(UNSAFE_CSTR(strPrinterName), &hPrinter,nullptr)) { Global->CatchError(); Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MPrintTitle),MSG(MCannotOpenPrinter), strPrinterName.data(),MSG(MOk)); _ALGO(SysLog(L"Error: Cannot Open Printer")); return; } { _ALGO(CleverSysLog clv3(L"Print selected Files")); SCOPED_ACTION(SaveScreen); auto PR_PrintMsg = [](){ Message(0, 0, MSG(MPrintTitle), MSG(MPreparingForPrinting)); }; SCOPED_ACTION(TPreRedrawFuncGuard)(std::make_unique<PreRedrawItem>(PR_PrintMsg)); SetCursorType(false, 0); PR_PrintMsg(); auto hPlugin=SrcPanel->GetPluginHandle(); int PluginMode=SrcPanel->GetMode()==PLUGIN_PANEL && !Global->CtrlObject->Plugins->UseFarCommand(hPlugin,PLUGIN_FARGETFILE); SrcPanel->GetSelName(nullptr,FileAttr); while (SrcPanel->GetSelName(&strSelName,FileAttr)) { if (TestParentFolderName(strSelName) || (FileAttr & FILE_ATTRIBUTE_DIRECTORY)) continue; int Success=FALSE; string FileName; string strTempDir, strTempName; if (PluginMode) { if (FarMkTempEx(strTempDir)) { api::CreateDirectory(strTempDir,nullptr); auto ListItem = SrcPanel->GetLastSelectedItem(); if (ListItem) { PluginPanelItem PanelItem; FileList::FileListToPluginItem(*ListItem, &PanelItem); if (Global->CtrlObject->Plugins->GetFile(hPlugin,&PanelItem,strTempDir,strTempName,OPM_SILENT)) FileName = strTempName; else api::RemoveDirectory(strTempDir); FreePluginPanelItem(PanelItem); } } } else FileName = strSelName; api::File SrcFile; if(SrcFile.Open(FileName, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, nullptr, OPEN_EXISTING)) { DOC_INFO_1 di1 = {UNSAFE_CSTR(FileName)}; if (StartDocPrinter(hPrinter,1,(LPBYTE)&di1)) { char Buffer[8192]; DWORD Read,Written; Success=TRUE; while (SrcFile.Read(Buffer, sizeof(Buffer), Read) && Read > 0) if (!WritePrinter(hPrinter,Buffer,Read,&Written)) { Global->CatchError(); Success=FALSE; break; } EndDocPrinter(hPrinter); } SrcFile.Close(); } if (!strTempName.empty()) { DeleteFileWithFolder(strTempName); } if (Success) SrcPanel->ClearLastGetSelection(); else { if (Message(MSG_WARNING|MSG_ERRORTYPE,2,MSG(MPrintTitle),MSG(MCannotPrint), strSelName.data(),MSG(MSkip),MSG(MCancel))) break; } } ClosePrinter(hPrinter); } SrcPanel->Redraw(); }

float Sphere::volume() const { return (float)pi() * (4.0f / 3.0f) * powf((float)radius, 3.0f); }

int main(int argc, char **argv) { ros::init (argc, argv, "right_arm_pick_place"); ros::AsyncSpinner spinner(1); spinner.start(); ros::NodeHandle nh; Mesh_loader ml; Suturo_Manipulation_Planning_Scene_Interface pi(&nh); Grasp_Calculator calc(&pi); // Grasping grapser(&pi); std::vector<geometry_msgs::PoseStamped> poses; std::vector<geometry_msgs::PoseStamped> pre_poses; // moveit_msgs::CollisionObject co; // co.header.stamp = ros::Time::now(); // co.header.frame_id = "/base_footprint"; // co.id = "corny"; // co.meshes.resize(1); // co.meshes[0] = ml.load_corny_msg(); // co.mesh_poses.resize(1); // co.mesh_poses[0].position.x = 1; // co.mesh_poses[0].position.y = 0; // co.mesh_poses[0].position.z = 0; // co.mesh_poses[0].orientation.w = 1; // pi.addObject(co); // geometry_msgs::PoseStamped ps; // ps.header = co.header; // ps.pose = co.mesh_poses[0]; // // pi.publishMarkerPoint(ps); // calc.calcMeshGraspPosition(co, poses, pre_poses, Gripper::R_GRIPPER_PALM_LENGTH); moveit_msgs::CollisionObject co; // pi.getObject("box.stl", co); co.header.stamp = ros::Time::now(); co.header.frame_id = "/base_footprint"; co.id = "pancake"; co.meshes.resize(1); co.meshes[0] = ml.load_pancake_msg(); co.mesh_poses.resize(1); co.mesh_poses[0].position.x = 1; co.mesh_poses[0].position.y = 0; co.mesh_poses[0].position.z = 0; co.mesh_poses[0].orientation.w = 1; pi.addObject(co); geometry_msgs::PoseStamped ps; ps.header = co.header; ps.pose = co.mesh_poses[0]; calc.calcMeshGraspPosition(co, poses, pre_poses, Gripper::R_GRIPPER_PALM_LENGTH); // pi.check_group_object_collision("left_gripper", ps, co); // ROS_INFO_STREAM(ml.load_corny()); // ROS_INFO_STREAM("\n\n"); // ROS_INFO_STREAM(ml.load_pringles()); // ros::Publisher pub_co = nh.advertise<moveit_msgs::CollisionObject>("collision_object", 10); // ros::WallDuration(1.0).sleep(); // moveit_msgs::CollisionObject co; // co.header.stamp = ros::Time::now(); // co.header.frame_id = "/base_footprint"; // co.id = "corny"; // co.meshes.resize(1); // co.meshes[0] = ml.load_corny_msg(); // co.mesh_poses.resize(1); // co.mesh_poses[0].position.x = 2; // co.mesh_poses[0].position.y = 0; // co.mesh_poses[0].position.z = 2; // co.mesh_poses[0].orientation.w = 1; // co.operation = moveit_msgs::CollisionObject::REMOVE; // pub_co.publish(co); // ros::WallDuration(1.0).sleep(); // co.operation = moveit_msgs::CollisionObject::ADD; // pub_co.publish(co); // ros::WallDuration(1.0).sleep(); // shapes::Mesh *corny = ml.load_corny(); // corny->computeTriangleNormals(); // for (int i = 0; corny->triangle_count > i; i++){ // ROS_INFO_STREAM(" "); // ROS_INFO_STREAM(corny->triangle_normals[i*3]); // ROS_INFO_STREAM(corny->triangle_normals[(i*3) + 1]); // ROS_INFO_STREAM(corny->triangle_normals[(i*3) + 2]); // } // Gripper g; // if (argc == 2){ // g.open_l_gripper(); // } else if (argc == 3) { // g.close_l_gripper(); // } //~ geometry_msgs::PoseStamped p; //~ p.header.frame_id = "/base_footprint"; //~ p.pose.position.x = 0.40; //~ p.pose.position.y = 0; //~ p.pose.position.z = 0.625; //~ p.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,0); // ros::Publisher pub_co = nh.advertise<moveit_msgs::CollisionObject>("collision_object", 10); // putObjects(pub_co); // Suturo_Manipulation_Planning_Scene_Interface pi(&nh); // pi.allowCollision("r_gripper_l_finger_link", "corny"); // pi.allowCollision("r_gripper_l_finger_tip_link", "corny"); // pi.allowCollision("r_gripper_motor_accelerometer_link", "corny"); // pi.allowCollision("r_gripper_palm_link", "corny"); // pi.allowCollision("r_gripper_r_finger_link", "corny"); // pi.allowCollision("r_gripper_r_finger_tip_link", "corny"); // pi.allowCollision("l_gripper_l_finger_link", "cafetfilter"); // pi.allowCollision("l_gripper_l_finger_tip_link", "cafetfilter"); // pi.allowCollision("l_gripper_motor_accelerometer_link", "cafetfilter"); // pi.allowCollision("l_gripper_palm_link", "cafetfilter"); // pi.allowCollision("l_gripper_r_finger_link", "cafetfilter"); // pi.allowCollision("l_gripper_r_finger_tip_link", "cafetfilter"); // moveit_msgs::PlanningScene ps; // ROS_INFO_STREAM(pi.getPlanningScene(ps)); // ROS_INFO_STREAM(ps); // ps.robot_state.multi_dof_joint_state.joint_transforms[0].translation.x = 1; // geometry_msgs::PoseStamped targetPose; // targetPose.header.frame_id = "/odom_combined"; // targetPose.pose.position.x = atof(argv[1]); // targetPose.pose.position.y = atof(argv[2]); // targetPose.pose.position.z = atof(argv[3]); // targetPose.pose.orientation.w = 1; // Suturo_Manipulation_Move_Robot moveRobot(&nh); // ROS_INFO_STREAM("collision: " << (moveRobot.checkFullCollision(targetPose))); //~ ros::Publisher pub_co = nh.advertise<moveit_msgs::CollisionObject>("collision_object", 10); //~ putObjects(pub_co); //~ //~ Gripper g; //~ //~ if (argc == 2){ //~ g.open_l_gripper(); //~ } else if (argc == 3) { //~ g.close_l_gripper(); //~ } //~ move_group_interface::MoveGroup group("right_arm"); //~ geometry_msgs::PoseStamped p; //~ p.header.frame_id = "/base_footprint"; //~ p.pose.position.x = 0.40; //~ p.pose.position.y = 0; //~ p.pose.position.z = 0.625; //~ p.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0,0,0); //~ group.setPoseTarget(p); //~ group.move(); // move_group_interface::MoveGroup group("left_gripper"); // ROS_INFO_STREAM("gripper joints"); // std::vector<std::string> bla1 = group.getJoints(); // for (int i = 0; i < bla1.size(); i++) ROS_INFO_STREAM(bla1.at(i)); // ROS_INFO_STREAM("------"); // std::vector<double> bla = group.getCurrentJointValues(); // for (int i = 0; i < bla.size(); i++) ROS_INFO_STREAM(bla.at(i)); //~ //~ openhand(); //~ //~ bla = group.getCurrentJointValues(); //~ for (int i = 0; i < bla.size(); i++) ROS_INFO_STREAM(bla.at(i)); //~ //~ Suturo_Manipulation_Planning_Scene_Interface pi(&nh); //~ Grasping grasper(&pi); //~ grasper.drop(suturo_manipulation_msgs::RobotBodyPart::LEFT_ARM); //~ grasper.pick("dlink", suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ grasper.pick("dlink", suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ grasper.pick("corny", suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ ROS_INFO("done."); //~ grasper.pick("corny", suturo_manipulation_msgs::RobotBodyPart::LEFT_ARM); //~ ROS_INFO("done."); //~ move_group_interface::MoveGroup group("left_arm"); //~ geometry_msgs::PoseStamped p; //~ p.header.frame_id = "/base_footprint"; //~ p.pose.position.x = 0.5; //~ p.pose.position.y = 0.2; //~ p.pose.position.z = 1; //~ p.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(M_PI, 0, -M_PI_2); //~ group.setPoseTarget(p); //~ tf::Quaternion q; //~ double roll, pitch, yaw; //~ tf::quaternionMsgToTF(p.pose.orientation, q); //~ ROS_INFO_STREAM(p.pose.orientation); //~ tf::Matrix3x3(q).getRPY(roll, pitch, yaw); //~ ROS_INFO("RPY = (%lf, %lf, %lf)", roll, pitch, yaw); //~ if (!group.move()) return 0; //~ ROS_INFO("done."); //~ grasper.pick("corny", suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ ROS_INFO("done."); //~ ROS_INFO("done."); //~ grasper.pick("corny", suturo_manipulation_msgs::RobotBodyPart::LEFT_ARM); //~ grasper.drop(suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ grasper.drop(suturo_manipulation_msgs::RobotBodyPart::RIGHT_ARM); //~ grasper.drop("corny"); //~ openhand(); //~ moveit_msgs::PlanningScene ps; //~ pi.getPlanningScene(ps); //~ ROS_INFO_STREAM("ps: " << ps); //std::vector<moveit_msgs::AttachedCollisionObject> muh = pi.getAttachedObjects(); //ROS_INFO_STREAM("objects " << muh.at(0)); //~ grasper.drop("box2"); //geometry_msgs::PoseStamped p; //p.header.frame_id = "/base_footprint"; //p.pose.position.x = 0.65; //p.pose.position.y = -0.3; //p.pose.position.z = 0.821; //p.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(0, M_PI_2, M_PI_4); //grasper.l_arm_pick("box2"); //move_group_interface::MoveGroup group("right_arm"); //group.setPlanningTime(45.0); /*pick(group);*/ /*geometry_msgs::PoseStamped p; p.header.frame_id = "/base_footprint"; p.pose.position.x = 0.59; p.pose.position.y = 0; p.pose.position.z = 0.625; p.pose.orientation.x = 0; p.pose.orientation.y = 0; p.pose.orientation.z = 0; p.pose.orientation.w = 1;*/ //group.setPoseTarget(p); //group.move(); //move_group_interface::MoveGroup group("right_arm"); //pick(group); //Gripper g; //pi.attachObject("box1", "r_wrist_roll_link", Gripper::get_r_gripper_links()); //moveit_msgs::PlanningScene ps; //pi.getPlanningScene(ps); //std::vector<moveit_msgs::AttachedCollisionObject> muh = pi.getAttachedObjects(); //ROS_INFO_STREAM("objects " << muh.at(0)); //pi.detachObject("box1"); //muh = pi.getAttachedObjects(); //ROS_INFO_STREAM("objects " << muh.at(0)); //ROS_INFO_STREAM("ps " << ps.robot_state); //ros::Publisher pub2 = nh.advertise<moveit_msgs::PlanningScene>("planning_scene", 10); //pub2.publish(ps); //ROS_INFO_STREAM("dsads " << ps); // ROS_DEBUG_STREAM("finish"); ROS_INFO_STREAM("finish"); ros::waitForShutdown(); return 0; }

// Encrypton and authentication procedure int crypto_aead_encrypt( unsigned char *c,unsigned long long *clen, const unsigned char *m,unsigned long long mlen, const unsigned char *ad,unsigned long long adlen, const unsigned char *nsec, const unsigned char *npub, const unsigned char *k ) { //... //... the code for the cipher implementation goes here, //... generating a ciphertext c[0],c[1],...,c[*clen-1] //... from a plaintext m[0],m[1],...,m[mlen-1] //... and associated data ad[0],ad[1],...,ad[adlen-1] //... and secret message number nsec[0],nsec[1],... //... and public message number npub[0],npub[1],... //... and secret key k[0],k[1],... //... // some 64-bit temp variables u_int64_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13; // more 64-bit temp variables u_int64_t x0, x1, x2, x3, y0, y1, y2, y3, z0, z1, z2, z3; // pointers to 64-bit variables u_int64_t *c64, *m64, *ad64, *nsec64, *npub64, *k64; // counter ctr is a 64-bit variable in all variants of PiCipher u_int64_t ctr = 0x0000000000000000ull; // an array for storing some temporal values for the Tag computation u_int64_t tempTag[CRYPTO_TBYTES/W] = {0}; // an array for the Common Internal State u_int64_t CIS[IS_SIZE] = {0}; // pointers that look at the used data arrays as arrays of bytes u_int8_t *InternalState8, *CommonInternalState8, *tempTag8; // variables for dealing with various lengths of the plaintext and associated data int LastMessageChunkLength, LastADChunkLength; // different iterator variables unsigned long long i, j, jj, ii, b, i1, j1, a; c64 = (u_int64_t *) c; m64 = (u_int64_t *) m; ad64 = (u_int64_t *) ad; nsec64 = (u_int64_t *) nsec; npub64 = (u_int64_t *) npub; k64 = (u_int64_t *) k; InternalState8 = (u_int8_t *) IS; CommonInternalState8 = (u_int8_t *) CIS; tempTag8 = (u_int8_t *) tempTag; // phase 1: Initialization for (i = 0; i < IS_SIZE; i++ ) { IS[i] = 0; } // injection of the key for ( i = 0; i < CRYPTO_KEYBYTES; i++ ) { InternalState8[i] = k[i]; } // injection of the nonce (public message number - PMN) for ( j = 0; j < CRYPTO_NPUBBYTES; j++ ) { InternalState8[i++] = npub[j]; } // appending a single 1 to the concatenated value of the key and PMN InternalState8[i] = 0x01; // applying the permutation function pi pi(); // initialization of the Common Internal State (CIS), common for all parallel invocations of pi() with different ctrs for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // initialization of the ctr obtained from the first 64 bits of the capacity of CIS ctr = CIS[4]; // phase 2: Processing the associated data b = 0; a = adlen/RATE; for ( j = 0; j < a; j ++ ) { // IS for the triplex component is initialized by the CIS for every AD block for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr ++; // Inject ctr + j in IS IS[0] = IS[0] ^ ctr; pi(); // process the AD block // Inject the AD block for ( i = 0; i < N; i += 2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { IS[i*WORDS_CHUNK+i1] = IS[i*WORDS_CHUNK+i1] ^ ad64[b]; b++; } } pi(); // Collect the tag for this block // Sum of the tags componentwise, where the length of one component is W jj = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the last AD block is not the full block, we process it byte by byte LastADChunkLength = adlen % RATE; if ( LastADChunkLength ) { b = b * W; i1 = 0; for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); for ( i = 0; i < LastADChunkLength; i++ ) { InternalState8[i1] = InternalState8[i1++] ^ ad[b+i]; if( i1 % (WORDS_CHUNK*W) == 0 ) i1 += WORDS_CHUNK*W; } // padding with 10* InternalState8[LastADChunkLength] = InternalState8[LastADChunkLength] ^ 0x01; pi(); //updating the tag jj = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // updating the Common Internal State by injection of the tag (tempTag) obtained from the associated data jj = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { IS[i*WORDS_CHUNK+i1] = CIS[i*WORDS_CHUNK+i1] ^ tempTag[jj]; IS[(i+1)*WORDS_CHUNK+i1] = CIS[(i+1)*WORDS_CHUNK+i1]; jj++; } } pi(); for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // phase 3: Processing the secret messge number if ( CRYPTO_NSECBYTES > 0 ) { for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); // encrypt the SMN // Inject the SMN b = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { c64[b] = IS[i*WORDS_CHUNK+i1] = IS[i*WORDS_CHUNK+i1] ^ nsec64[b]; b++; } } pi(); // updating the Common Internal State from the encrypted SMN for ( i = 0; i < IS_SIZE; i++ ) { CIS[i] = IS[i]; } // Collect the tag from this encryption and update the tempTag jj = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } //phase 4: Processing the message b = 0; for ( j = 0; j < mlen/RATE ; j ++ ) { for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); // encrypt the message m // Inject a block of m for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { c64[bSMN+b] = IS[i*WORDS_CHUNK+i1] = IS[i*WORDS_CHUNK+i1] ^ m64[b]; b++; } } pi(); // Collect the tag from this encryption and update the tempTag jj = 0; for ( i = 0; i < N; i += 2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // if the last message block is not the full block, we process it byte by byte LastMessageChunkLength = mlen % RATE; if ( LastMessageChunkLength ) { b = b * W; i1 = 0; for ( i = 0; i < IS_SIZE; i++ ) { IS[i] = CIS[i]; } ctr++; IS[0] = IS[0] ^ ctr; pi(); for ( i = 0; i < LastMessageChunkLength; i++ ) { c[CRYPTO_NSECBYTES+b+i] = InternalState8[i1] = InternalState8[i1++] ^ m[b+i]; if( i1 % (WORDS_CHUNK*W) == 0 ) i1 += WORDS_CHUNK*W; } // padding with 10* InternalState8[LastMessageChunkLength] = InternalState8[LastMessageChunkLength] ^ 0x01; pi(); // updating the tag jj = 0; for ( i = 0; i < N; i+=2 ) { for ( i1 = 0; i1 < WORDS_CHUNK; i1++ ) { tempTag[jj] = tempTag[jj] + IS[i*WORDS_CHUNK+i1]; jj++; } } } // concatenation of the tag T to the ciphertext c for ( jj = 0; jj < CRYPTO_TBYTES; jj++ ) { c[CRYPTO_NSECBYTES+mlen+jj] = tempTag8[jj]; } //updating the lenght of the ciphertext *clen = mlen + CRYPTO_TBYTES + CRYPTO_NSECBYTES; return 0; }

static void flip(MdlObject *o) { for (PolyIterator pi(o);!pi.End();pi.Next()) if (pi->isSelected) pi->Flip (); }