static enum piglit_result test(void) { static const GLfloat dest_color[4] = { 0.75, 0.25, 0.25, 0.5 }; static const GLfloat test_color[4] = { 1.0, 0.25, 0.75, 0.25 }; static const GLfloat test_color1[4] = { 0.5, 0.5, 0.5, 0.5 }; GLfloat expected[4]; GLuint prog; GLuint vs; GLuint fs; int i, j, k, o; if (max_ds_buffers > 1) { printf("Test only supports 1 dual source blending color buffer\n"); max_ds_buffers = 1; } prog = glCreateProgram(); vs = piglit_compile_shader_text(GL_VERTEX_SHADER, vs_text); fs = piglit_compile_shader_text(GL_FRAGMENT_SHADER, fs_text); glAttachShader(prog, vs); glAttachShader(prog, fs); piglit_check_gl_error(GL_NO_ERROR); glBindFragDataLocationIndexed(prog, 0, 0, "col0"); glBindFragDataLocationIndexed(prog, 0, 1, "col1"); create_fbo(); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); glLinkProgram(prog); glUseProgram(prog); uniform_src0 = glGetUniformLocation(prog, "src0"); uniform_src1 = glGetUniformLocation(prog, "src1"); /* Setup blend modes and compute expected result color. * We only test two simple blending modes. A more elaborate * test would exercise a much wider variety of modes. */ for (o = 0; o < ARRAY_SIZE(operators); o++) { for (i = 0; i < ARRAY_SIZE(srcFactors); i++) { for (j = 0; j < ARRAY_SIZE(dstFactors); j++) { blend_expected(expected, test_color, test_color1, dest_color, srcFactors[i], dstFactors[j], operators[o]); blend(test_color, test_color1, dest_color, srcFactors[i], dstFactors[j], operators[o]); for (k = 0; k < max_ds_buffers; k++) { glReadBuffer(GL_COLOR_ATTACHMENT0_EXT + k); check_error(__LINE__); if (!piglit_probe_pixel_rgba(5, 5, expected)) { printf("For src/dst %d %d %d\n", i, j, o); return PIGLIT_FAIL; } } } } } return PIGLIT_PASS; }
/* Monitor a pipe for input */ void read_pipe_poll (HANDLE hStop, void *_data) { DWORD res; DWORD event; DWORD n; LPSELECTQUERY iterQuery; LPSELECTDATA lpSelectData; DWORD i; DWORD wait; /* Poll pipe */ event = 0; n = 0; lpSelectData = (LPSELECTDATA)_data; wait = 1; DEBUG_PRINT("Checking data pipe"); while (lpSelectData->EState == SELECT_STATE_NONE) { for (i = 0; i < lpSelectData->nQueriesCount; i++) { iterQuery = &(lpSelectData->aQueries[i]); res = PeekNamedPipe( iterQuery->hFileDescr, NULL, 0, NULL, &n, NULL); if (check_error(lpSelectData, (res == 0) && (GetLastError() != ERROR_BROKEN_PIPE))) { break; }; if ((n > 0) || (res == 0)) { lpSelectData->EState = SELECT_STATE_SIGNALED; select_data_result_add(lpSelectData, iterQuery->EMode, iterQuery->lpOrigIdx); }; }; /* Alas, nothing except polling seems to work for pipes. Check the state & stop_worker_event every 10 ms */ if (lpSelectData->EState == SELECT_STATE_NONE) { event = WaitForSingleObject(hStop, wait); /* Fast start: begin to wait 1, 2, 4, 8 and then 10 ms. * If we are working with the output of a program there is * a chance that one of the 4 first calls succeed. */ wait = 2 * wait; if (wait > 10) { wait = 10; }; if (event == WAIT_OBJECT_0 || check_error(lpSelectData, event == WAIT_FAILED)) { break; } } } DEBUG_PRINT("Finish checking data on pipe"); }
void YCbCrInput::set_gl_state(GLuint glsl_program_num, const string& prefix, unsigned *sampler_num) { for (unsigned channel = 0; channel < num_channels; ++channel) { glActiveTexture(GL_TEXTURE0 + *sampler_num + channel); check_error(); if (texture_num[channel] == 0) { GLenum format, internal_format; if (channel == 1 && ycbcr_input_splitting == YCBCR_INPUT_SPLIT_Y_AND_CBCR) { format = GL_RG; internal_format = GL_RG8; } else { format = GL_RED; internal_format = GL_R8; } // (Re-)upload the texture. texture_num[channel] = resource_pool->create_2d_texture(internal_format, widths[channel], heights[channel]); glBindTexture(GL_TEXTURE_2D, texture_num[channel]); check_error(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); check_error(); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbos[channel]); check_error(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); check_error(); glPixelStorei(GL_UNPACK_ROW_LENGTH, pitch[channel]); check_error(); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, widths[channel], heights[channel], format, GL_UNSIGNED_BYTE, pixel_data[channel]); check_error(); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); check_error(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); check_error(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); check_error(); owns_texture[channel] = true; } else { glBindTexture(GL_TEXTURE_2D, texture_num[channel]); check_error(); } } glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0); check_error(); // Bind samplers. uniform_tex_y = *sampler_num + 0; uniform_tex_cb = *sampler_num + 1; if (ycbcr_input_splitting == YCBCR_INPUT_PLANAR) { uniform_tex_cr = *sampler_num + 2; } *sampler_num += num_channels; }
// Initialize the connection to KWallet static gboolean init_kwallet(backend_kwallet_context_t *context) { GError* error = NULL; // Make a proxy to KWallet. if(context->proxy) g_object_unref(context->proxy); context->proxy = g_dbus_proxy_new_sync(context->connection, G_DBUS_PROXY_FLAGS_NONE, NULL, kwallet_service_name, kwallet_path, kwallet_interface, NULL, &error); if(check_error(error)) { context->proxy = NULL; return FALSE; } // Check KWallet is enabled. GVariant *ret = g_dbus_proxy_call_sync(context->proxy, "isEnabled", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(!ret) return FALSE; GVariant *child = g_variant_get_child_value(ret, 0); gboolean is_enabled = g_variant_get_boolean(child); g_variant_unref(child); g_variant_unref(ret); if(check_error(error) || !is_enabled) return FALSE; // Get the wallet name. if(context->wallet_name) g_free(context->wallet_name); ret = g_dbus_proxy_call_sync(context->proxy, "networkWallet", NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); child = g_variant_get_child_value(ret, 0); context->wallet_name = g_variant_dup_string(child, NULL); g_variant_unref(child); g_variant_unref(ret); if(check_error(error) || !context->wallet_name) { context->wallet_name = NULL; // yes, it's stupid. go figure. return FALSE; } return TRUE; }
// Store (key,value) pairs from a GHashTable in the kwallet. // Every 'slot' has to take care of it's own data. gboolean dt_pwstorage_kwallet_set(const backend_kwallet_context_t *context, const gchar* slot, GHashTable* table) { printf("slot %s\n", slot); GArray* byte_array = g_array_new(FALSE, FALSE, sizeof(gchar)); GHashTableIter iter; g_hash_table_iter_init (&iter, table); gpointer key, value; guint size = g_hash_table_size(table); size = GINT_TO_BE(size); g_array_append_vals(byte_array, &size, sizeof(guint)/sizeof(gchar)); while (g_hash_table_iter_next (&iter, &key, &value)) { dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] storing (%s, %s)\n",(gchar*)key, (gchar*)value); gsize length; gchar* new_key = char2qstring(key, &length); if(new_key == NULL) { g_free(g_array_free(byte_array, FALSE)); return FALSE; } g_array_append_vals(byte_array, new_key, length); g_free(new_key); gchar* new_value = char2qstring(value, &length); if(new_value == NULL) { g_free(g_array_free(byte_array, FALSE)); return FALSE; } g_array_append_vals(byte_array, new_value, length); g_free(new_value); } int wallet_handle = get_wallet_handle(context); GError* error = NULL; /* signature: * * in i handle, * in s folder, * in s key, * in ay value, * in s appid, * * out i arg_0 */ GVariant *ret = g_dbus_proxy_call_sync(context->proxy, "writeMap", g_variant_new("(iss@ays)", wallet_handle, kwallet_folder, slot, g_variant_new_from_data(G_VARIANT_TYPE_BYTESTRING, byte_array->data, byte_array->len, TRUE, g_free, byte_array->data), app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); g_array_free(byte_array, FALSE); if(check_error(error)) { g_variant_unref(ret); return FALSE; } GVariant *child = g_variant_get_child_value(ret, 0); int return_code = g_variant_get_int32(child); g_variant_unref(child); g_variant_unref(ret); if (return_code != 0) dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_set] Warning: bad return code %d from kwallet\n", return_code); return return_code == 0; }
void cuda_free(float *x_gpu) { cudaError_t status = cudaFree(x_gpu); check_error(status); }
void cuda_pull_array(float *x_gpu, float *x, size_t n) { size_t size = sizeof(float)*n; cudaError_t status = cudaMemcpy(x, x_gpu, size, cudaMemcpyDeviceToHost); check_error(status); }
/* ------------------------------------------------------------- */ PJXNODE jx_sqlFormatRow (PJXSQL pSQL) { int i; PJXNODE pRow; if ( pSQL->rc == SQL_SUCCESS) { pRow = jx_NewObject(NULL); for (i = 0; i < pSQL->nresultcols; i++) { PJXCOL pCol = &pSQL->cols[i]; if (pCol->outlen != SQL_NULL_DATA) { switch( pCol->coltype) { case SQL_WCHAR: case SQL_WVARCHAR: case SQL_GRAPHIC: case SQL_VARGRAPHIC: { UCHAR temp [32768]; PUCHAR pInBuf = pCol->data; size_t OutLen; size_t inbytesleft; for (inbytesleft = pCol->collen; inbytesleft > 0 ; inbytesleft -= 2) { if ( * (PSHORT) (pInBuf + inbytesleft - 2) > 0x0020) break; } OutLen = XlateXdBuf (pConnection->pCd, temp , pInBuf, inbytesleft); temp[OutLen] = '\0'; jx_NodeAdd (pRow , RL_LAST_CHILD, pCol->colname , temp, pCol->nodeType ); break; } case SQL_NUMERIC: case SQL_DECIMAL: case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE: { PUCHAR p = pCol->data; int len = strTrimLen(p); p[len] = '\0'; // Have to fix .00 numeric as 0.00 if (*p == '.') { memmove (p+1 , p, len+1); *p = '0'; } jx_NodeAdd (pRow , RL_LAST_CHILD, pCol->colname , p, pCol->nodeType ); break ; } default: { PUCHAR p = pCol->data; int len; if (pCol->coltype != SQL_BLOB && pCol->coltype != SQL_CLOB) { len = strTrimLen(p); p[len] = '\0'; } // trigger new parsing of JSON-objects in columns: // Predicts json data i columns if (pConnection->options.autoParseContent == ON) { if (*p == BraBeg || *p == CurBeg) { PJXNODE pNode = jx_ParseString(p, NULL); if (pNode) { jx_NodeRename(pNode, pCol->colname); jx_NodeAddChildTail (pRow, pNode); break; } } } jx_NodeAdd (pRow , RL_LAST_CHILD, pCol->colname , p, pCol->nodeType ); break; } } } } return pRow; // Found } else { if (pSQL->rc != SQL_NO_DATA_FOUND ) { check_error (pSQL); } } return NULL; // not found }
/* ------------------------------------------------------------- */ PJXNODE jx_buildMetaFields ( PJXSQL pSQL ) { LONG attrParm; PJXNODE pFields = jx_NewArray(NULL); int i; attrParm = SQL_TRUE; pSQL->rc = SQLSetStmtAttr (pSQL->hstmt, SQL_ATTR_EXTENDED_COL_INFO , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } for (i = 1; i <= pSQL->nresultcols; i++) { PJXNODE pField = jx_NewObject (NULL); PJXCOL pCol = &pSQL->cols[i-1]; PUCHAR type = "string"; UCHAR temp [256]; // Add name jx_NodeAdd (pField , RL_LAST_CHILD, "name" , pCol->colname, VALUE ); // Add type switch( pCol->coltype) { case SQL_BLOB: type = "blob" ; break; case SQL_CLOB: type = "clob" ; break; case SQL_CHAR: type = "char" ; break; case SQL_VARCHAR: type = "varchar" ; break; case SQL_DATETIME: type = "datetime" ; break; case SQL_DATE: type = "date" ; break; case SQL_TIME: type = "time" ; break; case SQL_TIMESTAMP: type = "timestamp" ; break; case SQL_WCHAR: type = "wchar" ; break; case SQL_WVARCHAR: type = "wvarchar" ; break; case SQL_GRAPHIC: type = "graphic" ; break; case SQL_VARGRAPHIC: type = "vargraphic" ; break; default: { if (pCol->coltype >= SQL_NUMERIC && pCol->coltype <= SQL_DOUBLE ) { if (pCol->scale > 0) { type = "dec" ; } else { type = "int" ; } } else { sprintf(temp ,"unknown%d" , pCol->coltype); type = temp; } } } jx_NodeAdd (pField , RL_LAST_CHILD, "datatype" , type, VALUE ); // Add size sprintf(temp , "%d" , pCol->displaysize); jx_NodeAdd (pField , RL_LAST_CHILD, "size" , temp, LITERAL ); // Add decimal precission if (pCol->coltype >= SQL_NUMERIC && pCol->coltype <= SQL_DOUBLE && pCol->scale > 0) { sprintf(temp , "%d" , pCol->scale); jx_NodeAdd (pField , RL_LAST_CHILD, "prec" , temp, LITERAL ); } // Push to array jx_ArrayPush (pFields , pField, FALSE); } // jx_Debug ("Fields:", pFields); return pFields; }
void do_clean_ups (MYSQL *mysql) { MYSQL_RES *res; MYSQL_ROW row; debug (1, "do_clean_ups"); /* auto logout */ /* alt where planet.mode & 0x0F = 2 */ res = do_query (mysql,"SELECT user.planet_id FROM user, planet " \ "WHERE planet.id=user.planet_id " \ "AND now() - INTERVAL 30 MINUTE > user.last "\ "AND (planet.mode = 0xF2 OR planet.mode = 2)"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query(mysql, "UPDATE user SET uptime=" \ "SEC_TO_TIME(UNIX_TIMESTAMP(last) - UNIX_TIMESTAMP(login_date) + TIME_TO_SEC(uptime)) " \ "WHERE planet_id='%s'", row[0]); vx_query (mysql, "UPDATE planet SET mode=((mode & 0xF0) + 1) WHERE id=%s", row[0]); do_log_id (mysql, atoi(row[0]), C_LOGOUT, T_AUTO, ""); } } check_error (mysql); mysql_free_result(res); /* protection */ /* alt where planet.mode & 0xF0 */ res = do_query (mysql,"SELECT user.planet_id FROM user,planet,general " \ "WHERE planet.id=user.planet_id " \ "AND planet.mode>127 " \ "AND general.tick>=user.first_tick+71"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "UPDATE planet SET mode=(mode & 0xF) WHERE id=%s", row[0]); } } check_error (mysql); mysql_free_result(res); /* sleeping */ /* alt where planet.mode & 0x0F = 3 */ res = do_query (mysql,"SELECT user.planet_id FROM user,planet " \ "WHERE planet.id=user.planet_id " \ "AND (planet.mode = 0xF3 OR planet.mode = 3) " \ "AND user.last_sleep < now() - INTERVAL 6 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "UPDATE planet SET mode=(mode & 0xF0)+1 WHERE id=%s", row[0]); do_log_id (mysql, atoi(row[0]), C_FLOW, T_SLEEP, ""); } } check_error (mysql); mysql_free_result(res); /* clean politics */ res = do_query (mysql,"SELECT id FROM politics " \ "WHERE now() - INTERVAL 7 DAY > date"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) { vx_query (mysql, "DELETE FROM politics WHERE id = %s", row[0]); vx_query (mysql, "DELETE FROM poltext WHERE thread_id = %s", row[0]); } } check_error (mysql); mysql_free_result(res); /* delete idle/old/test accounts */ /* only if mytick > 24 hours = 120*24 = 1440 */ if (mytick > 2880) { res = do_query (mysql, "SELECT planet.id FROM planet,user "\ "WHERE planet.id=user.planet_id "\ "AND planet.id>2 "\ "AND (metalroids+crystalroids+eoniumroids+uniniroids) < 4 " \ "AND (user.last < NOW() - INTERVAL 24 HOUR " \ "OR (user.last IS NULL "\ "AND user.signup < NOW() - INTERVAL 24 HOUR))"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } } /* delete deleted accounts */ res = do_query (mysql, "SELECT planet_id FROM user "\ "WHERE delete_date !=0 AND delete_date > last " \ "AND delete_date < NOW() - INTERVAL 12 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } check_error (mysql); mysql_free_result(res); /* delete banned accounts */ res = do_query (mysql, "SELECT planet.id FROM planet,user "\ "WHERE planet.id=user.planet_id AND mode=0 AND " \ "user.last < NOW() - INTERVAL 36 HOUR"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) delete_user(mysql, atoi(row[0])); } check_error (mysql); mysql_free_result(res); /* check for exiling */ res = do_query (mysql,"SELECT id, x, y, exile_id "\ "FROM galaxy WHERE exile_id>0 AND exile_date<now()"); if (res && mysql_num_rows(res)) { while ((row = mysql_fetch_row (res))) check_exile(mysql, atoi(row[0]), atoi(row[1]),atoi(row[2]),atoi(row[3])); } check_error (mysql); mysql_free_result(res); /* clean news */ do_query (mysql, "DELETE FROM news WHERE date < now() - INTERVAL 48 HOUR"); /* clean journal (1) */ do_query (mysql, "DELETE FROM journal WHERE hidden=1 AND date < NOW() - INTERVAL 10 MINUTE"); /* clean journal (2) */ do_query (mysql, "DELETE FROM journal WHERE hidden=0 AND date < NOW() - INTERVAL 48 HOUR"); /* fleet cleanup */ do_query (mysql, "DELETE FROM units WHERE num=0"); /* clear hostile */ }
/* ------------------------------------------------------------- */ PJXSQL jx_sqlOpen(PUCHAR sqlstmt , PJXNODE pSqlParms) { PNPMPARMLISTADDRP pParms = _NPMPARMLISTADDR(); // LONG format = (pParms->OpDescList->NbrOfParms >= 3) ? formatP : 0; // Status & result object LONG attrParm; LONG i; // PJXSQL pSQL = jx_sqlNewStatement (pParms->OpDescList->NbrOfParms >= 2 ? pSqlParms :NULL); PJXSQL pSQL = jx_sqlNewStatement (NULL); pSQL->rc = SQLAllocStmt(pConnection->hdbc, &pSQL->hstmt); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } attrParm = SQL_TRUE; pSQL->rc = SQLSetStmtAttr (pSQL->hstmt, SQL_ATTR_CURSOR_SCROLLABLE , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } /* attrParm = SQL_TRUE; pSQL->rc = SQLSetStmtAttr (pSQL->hstmt, SQL_ATTR_EXTENDED_COL_INFO , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } */ attrParm = SQL_CONCUR_READ_ONLY; pSQL->rc = SQLSetStmtAttr (pSQL->hstmt, SQL_ATTR_CONCURRENCY , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } // run the statement in "sqlstr" if (pParms->OpDescList->NbrOfParms >= 2 && pSqlParms ) { UCHAR sqlTempStmt[32766]; strFormat(sqlTempStmt , sqlstmt , pSqlParms); pSQL->sqlstmt = strdup(sqlTempStmt); } else { pSQL->sqlstmt = strdup(sqlstmt); } pSQL->rc = SQLExecDirect (pSQL->hstmt, pSQL->sqlstmt, SQL_NTS); if (pSQL->rc != SQL_SUCCESS && pSQL->rc != SQL_NO_DATA_FOUND) { check_error (pSQL); return NULL; // we have an error } // Number of rows? .. No does not work :( /* SQLGetDiagField(SQL_HANDLE_STMT,pSQL->hstmt, 0 ,SQL_DIAG_ROW_COUNT,&pSQL->rowcount,0, NULL); */ /* // Row count is only affected row in a "delete" or "update" ..TODO find a solution for select pSQL->rc = SQLRowCount (pSQL->hstmt, &pSQL->rowcount); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return; // we have an error } */ pSQL->rc = SQLNumResultCols (pSQL->hstmt, &pSQL->nresultcols); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return NULL; // we have an error } for (i = 0; i < pSQL->nresultcols; i++) { PJXCOL pCol = &pSQL->cols[i]; SQLDescribeCol (pSQL->hstmt, i+1, pCol->colname, sizeof (pCol->colname), &pCol->colnamelen, &pCol->coltype, &pCol->collen, &pCol->scale, &pCol->nullable); pCol->colname[pCol->colnamelen] = '\0'; if (OFF == jx_IsTrue (pConnection->pOptions ,"uppercasecolname")) { str2lower (pCol->colname , pCol->colname); } // get display label for column /**************** pSQL->rc = SQLColAttributes (hstmt, i+1, SQL_DESC_LABEL, Label , sizeof(Label) , &len , NULL); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return; // we have an error } ***********/ // get display length for column SQLColAttributes (pSQL->hstmt, i+1, SQL_DESC_PRECISION, NULL, 0,NULL, &pCol->displaysize); // set column length to max of display length, and column name // length. Plus one byte for null terminator // collen[i] = max(displaysize, collen[i]); // collen[i] = max(collen[i], strlen((char *) colname) ) + 1; // printf ("%-*.*s", collen[i], collen[i], colname); // allocate memory to bind column // bind columns to program vars, converting all types to CHAR //*SQLBindCol (hstmt, i+1, SQL_C_CHAR, data[i], collen[i], &outlen[i]); switch( pCol->coltype) { case SQL_BLOB: case SQL_CLOB: // pCol->collen = pCol->displaysize * 2; // pCol->data = (SQLCHAR *) malloc (pCol->collen); pCol->collen = 1048576; // 1MEGABYTES pCol->data = (SQLCHAR *) malloc (pCol->collen); // 1MEGABYTES SQLBindCol (pSQL->hstmt, i+1, SQL_C_BINARY , pCol->data, pCol->collen, &pCol->outlen); break; case SQL_WCHAR: case SQL_WVARCHAR: case SQL_GRAPHIC: case SQL_VARGRAPHIC: pCol->collen = pCol->displaysize * 2; pCol->data = (SQLCHAR *) malloc (pCol->collen); SQLBindCol (pSQL->hstmt, i+1, pCol->coltype, pCol->data, pCol->collen, &pCol->outlen); break; default: pCol->collen = pCol->displaysize + 3; // + . and , and zero term pCol->data = (SQLCHAR *) malloc (pCol->collen); SQLBindCol (pSQL->hstmt, i+1, SQL_C_CHAR, pCol->data, pCol->collen, &pCol->outlen); break; } if (pCol->coltype >= SQL_NUMERIC && pCol->coltype <= SQL_DOUBLE) { pCol->nodeType = JX_LITERAL; } else { pCol->nodeType = JX_VALUE; } } return pSQL; }
/* res = do_query (mysql,"SELECT id, x, y, exile_id "\ "FROM galaxy WHERE exile_id>0 AND exile_date<now()"); */ void check_exile (MYSQL *mysql, int gid, int x, int y, int pid) { static char c_fmt[] = "SELECT has_hostile, gal_hostile FROM planet WHERE id=%d"; static char q_fmt[] = "SELECT exile_vote FROM planet, user " \ "WHERE planet.x=%d AND planet.y=%d AND planet.id = user.planet_id " \ "AND user.last > now() - interval 36 HOUR AND mode not in (0, 4)"; MYSQL_RES *res; MYSQL_ROW row; int found=0, exile_cnt=0, active_cnt=0; debug (3, "check_exile"); /* target still there ? */ res = vx_query (mysql, c_fmt, pid); if (!res || mysql_num_rows(res)==0) { fprintf (logfile, "[Exile]: cancelled - planet gone [%d]\n", pid); fflush(logfile); remove_vote (mysql, gid, x, y, pid, -1); return; } row = mysql_fetch_row(res); if (atoi(row[0])!=0 || atoi(row[1])!=0) { /* under attack - wait a tick */ fprintf (logfile, "[Exile]: planet [%d] - gal under attack; delayed\n", pid); mysql_free_result(res); return; } check_error (mysql); mysql_free_result(res); /* vote succesfull ? */ res = vx_query (mysql, q_fmt, x, y); if (!res || mysql_num_rows(res)<1) return; while ((row = mysql_fetch_row (res))) { active_cnt++; if (atoi(row[0]) == 1) { exile_cnt++; } } check_error (mysql); mysql_free_result(res); fprintf (logfile, "[Exile]: (%d:%d) [%d], %d / %d\n", x, y, pid, exile_cnt, active_cnt); /* exile or not */ if ((exile_cnt*1.5) > active_cnt) { if (exile_planet (mysql, gid, pid)) { return; } found = 1; } /* remove_vote */ remove_vote (mysql, gid, x, y, pid, found); check_error (mysql); }
int get_new_coords (MYSQL *mysql, int *x, int *y, int *z, int *gid) { MYSQL_RES *res; MYSQL_ROW row; int low=1, high=1, max_high=0; int cnt=0, rval; debug (4, "get_new_coords"); /* universe size */ res = do_query (mysql, "SELECT x FROM galaxy ORDER BY x DESC LIMIT 1"); row = mysql_fetch_row (res); max_high = atoi(row[0]); check_error (mysql); mysql_free_result(res); /* lowest cluster w free planets */ res = vx_query (mysql, "SELECT x FROM galaxy WHERE members<%d AND !(x=1 AND y=1) "\ "ORDER BY x ASC LIMIT 1", GALAXY_SIZE); if (!res || mysql_num_rows(res)<1) { return 1; } row = mysql_fetch_row (res); low = atoi(row[0]); check_error (mysql); mysql_free_result(res); /* highest cluster w members */ res = vx_query (mysql, "SELECT x FROM galaxy WHERE members>0 "\ "ORDER BY x DESC LIMIT 1"); row = mysql_fetch_row (res); high = atoi(row[0]); check_error (mysql); mysql_free_result(res); if (high < low) high = low; /* check Open clusters */ do { res = vx_query (mysql, "SELECT x,y,id FROM galaxy WHERE x>=%d AND x<=%d "\ "AND members<%d AND !(x=1 and y=1) GROUP BY x, y", low, high, GALAXY_SIZE); if (!res) return 1; cnt = mysql_num_rows(res); if (cnt==0) { /* next cluster */ low = high + 1; if (low > max_high) return 1; high = low; } } while (cnt==0); if (cnt != 1) { /* generate random value */ srand ((time(NULL) * (*gid + 1))); rval = 1 + (int) (((float)cnt - 1.) * rand()/(RAND_MAX+1.0)); } else { rval = 1; } /* fetch bis zum nten */ while (rval>1) { row = mysql_fetch_row(res); rval--; } row = mysql_fetch_row(res); *x = atoi(row[0]); *y = atoi(row[1]); *gid = atoi(row[2]); mysql_free_result(res); res = vx_query (mysql, "SELECT z FROM planet WHERE x=%d AND y=%d "\ "ORDER BY z DESC LIMIT 1", *x, *y); if (res && mysql_num_rows(res)) { row = mysql_fetch_row(res); *z = 1 + atoi(row[0]); } else *z = 1; check_error (mysql); mysql_free_result(res); return 0; }
/** \return GL_TRUE for pass, GL_FALSE for fail */ static bool test_fbo(const struct format_info *info) { const int comps = num_components(info->BaseFormat); const GLenum type = get_datatype(info); GLint f; GLuint fbo, texObj; GLenum status; GLboolean intMode; GLint buf; bool pass = true; if (0) fprintf(stderr, "============ Testing format = %s ========\n", info->Name); /* Create texture */ glGenTextures(1, &texObj); glBindTexture(GL_TEXTURE_2D, texObj); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, info->IntFormat, TexWidth, TexHeight, 0, info->BaseFormat, type, NULL); if (check_error(__FILE__, __LINE__)) return GL_FALSE; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &f); assert(f == info->IntFormat); /* Create FBO to render to texture */ glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texObj, 0); if (check_error(__FILE__, __LINE__)) return GL_FALSE; status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { fprintf(stderr, "%s: failure: framebuffer incomplete.\n", TestName); return GL_FALSE; } glGetBooleanv(GL_RGBA_INTEGER_MODE_EXT, &intMode); if (check_error(__FILE__, __LINE__)) return GL_FALSE; if (!intMode) { fprintf(stderr, "%s: GL_RGBA_INTEGER_MODE_EXT return GL_FALSE\n", TestName); return GL_FALSE; } glGetIntegerv(GL_READ_BUFFER, &buf); assert(buf == GL_COLOR_ATTACHMENT0_EXT); glGetIntegerv(GL_DRAW_BUFFER, &buf); assert(buf == GL_COLOR_ATTACHMENT0_EXT); /* test clearing */ if (1) { /* clear with an integer - exp unsigned int */ static const GLint clr_i[4] = { 300000005, -7, 6, 5 }; static const GLuint exp_ui[4] = { 300000005, 0, 6, 5 }; /* clear with an unsigned integer - exp int */ static const GLuint clr_ui[4] = { 300000005, 0x80000007, 6, 5 }; static const GLint exp_i[4] = { 300000005, 0x7fffffff, 6, 5 }; GLint pix[4], i; GLuint pix_ui[4]; if (info->Signed) glClearColorIiEXT(clr_i[0], clr_i[1], clr_i[2], clr_i[3]); else glClearColorIuiEXT(clr_ui[0], clr_ui[1], clr_ui[2], clr_ui[3]); glClear(GL_COLOR_BUFFER_BIT); if (info->Signed) glReadPixels(5, 5, 1, 1, GL_RGBA_INTEGER_EXT, GL_UNSIGNED_INT, pix_ui); else glReadPixels(5, 5, 1, 1, GL_RGBA_INTEGER_EXT, GL_INT, pix); if (info->Signed) { for (i = 0; i < comps; i++) { if (pix_ui[i] != exp_ui[i]) { fprintf(stderr, "%s: glClear failed\n", TestName); fprintf(stderr, " Texture format = %s\n", info->Name); fprintf(stderr, " Expected %u, %u, %u, %u\n", exp_ui[0], exp_ui[1], exp_ui[2], exp_ui[3]); fprintf(stderr, " Found %u, %u, %u, %u\n", pix_ui[0], pix_ui[1], pix_ui[2], pix_ui[3]); pass = false; break; } } } else { for (i = 0; i < comps; i++) { if (pix[i] != exp_i[i]) { fprintf(stderr, "%s: glClear failed\n", TestName); fprintf(stderr, " Texture format = %s\n", info->Name); fprintf(stderr, " Expected %d, %d, %d, %d\n", exp_i[0], exp_i[1], exp_i[2], exp_i[3]); fprintf(stderr, " Found %d, %d, %d, %d\n", pix[0], pix[1], pix[2], pix[3]); pass = false; break; } } } } glutSwapBuffers(); glDeleteTextures(1, &texObj); glDeleteFramebuffers(1, &fbo); return pass; }
enum piglit_result piglit_display(void) { GLuint tex; static const float red[] = { 1, 0, 0, 1 }; static const float green[] = { 0, 1, 0, 1 }; static const float blue[] = { 0, 0, 1, 1 }; static const float cyan[] = { 0, 1, 1, 1 }; pass = GL_TRUE; extension_supported = piglit_is_extension_supported("GL_EXT_unpack_subimage"); if (!piglit_automatic) { if (extension_supported) printf("GL_EXT_unpack_subimage is supported\n"); else printf("GL_EXT_unpack_subimage is not supported\n"); } piglit_reset_gl_error(); if (!piglit_automatic) printf("Trying GL_UNPACK_ROW_LENGTH\n"); glPixelStorei(GL_UNPACK_ROW_LENGTH, 2); check_error(); piglit_reset_gl_error(); if (!piglit_automatic) printf("Trying GL_UNPACK_SKIP_PIXELS\n"); glPixelStorei(GL_UNPACK_SKIP_PIXELS, 1); check_error(); piglit_reset_gl_error(); if (!piglit_automatic) printf("Trying GL_UNPACK_SKIP_ROWS\n"); glPixelStorei(GL_UNPACK_SKIP_ROWS, 4); check_error(); glClear(GL_COLOR_BUFFER_BIT); /* Try creating a texture with the unpacking parameters we've set */ glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, /* level */ GL_RGBA, /* internalFormat */ 1, /* width */ 2, /* height */ 0, /* border */ GL_RGBA, /* format */ GL_UNSIGNED_BYTE, /* type */ tex_data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); make_program(vertex_shader, fragment_shader); piglit_draw_rect_tex(-1, -1, 2, 2, 0, 0, 1, 1); if (extension_supported) { pass &= piglit_probe_pixel_rgba(piglit_width / 2, piglit_height / 4, blue); pass &= piglit_probe_pixel_rgba(piglit_width / 2, piglit_height * 3 / 4, cyan); } else { pass &= piglit_probe_pixel_rgba(piglit_width / 2, piglit_height / 4, red); pass &= piglit_probe_pixel_rgba(piglit_width / 2, piglit_height * 3 / 4, green); } return pass ? PIGLIT_PASS : PIGLIT_FAIL; }
/* ------------------------------------------------------------- */ static PJXSQLCONNECT jx_sqlNewConnection(void ) { // static SQLHSTMT hstmt = 0 ; // SQLINTEGEREGER len; // UCHAR Label [256]; // LGL err = ON; // LONG rows =0; PJXSQLCONNECT pConnection; LONG attrParm; PUCHAR server = "*LOCAL"; int rc; PSQLOPTIONS po; pConnection = memAlloc(sizeof(JXSQLCONNECT)); memset(pConnection , 0 , sizeof(JXSQLCONNECT)); pConnection->pCd = XlateXdOpen (13488, 0); po = &pConnection->options; po->upperCaseColName = OFF; po->autoParseContent = ON; po->DecimalPoint = '.'; po->hexSort = OFF; po->sqlNaming = OFF; po->DateSep = '-'; po->DateFmt = 'y'; po->TimeSep = ':'; po->TimeFmt = 'H'; // allocate an environment handle rc = SQLAllocEnv (&pConnection->henv); if (rc != SQL_SUCCESS ) { check_error (NULL); jx_sqlDisconnect (pConnection); return NULL; // we have an error } // Note - this is invers: Default to IBMi naming attrParm = pConnection->options.sqlNaming == ON ? SQL_FALSE : SQL_TRUE; rc = SQLSetEnvAttr (pConnection->henv, SQL_ATTR_SYS_NAMING, &attrParm , 0); if (rc != SQL_SUCCESS ) { check_error (NULL); jx_sqlDisconnect (pConnection); return NULL; // we have an error } /* attrParm = SQL_TRUE; rc = SQLSetEnvAttr (pConnection->henv, SQL_ATTR_UTF8 , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { jx_sqlDisconnect (pConnection); return NULL; // we have an error } */ rc = SQLAllocConnect (pConnection->henv, &pConnection->hdbc); // allocate a connection handle if (rc != SQL_SUCCESS ) { check_error (NULL); jx_sqlDisconnect (pConnection); return NULL; // we have an error } attrParm = SQL_TXN_NO_COMMIT; rc = SQLSetConnectAttr (pConnection->hdbc, SQL_ATTR_COMMIT , &attrParm , 0); if (rc != SQL_SUCCESS ) { check_error (NULL); jx_sqlDisconnect (pConnection); return NULL; // we have an error } rc = SQLConnect (pConnection->hdbc, server , SQL_NTS, NULL, SQL_NTS, NULL, SQL_NTS); if (rc != SQL_SUCCESS ) { check_error (NULL); jx_sqlDisconnect (pConnection); return NULL; // we have an error } return pConnection; // we are ok }
void cuda_set_device(int n) { gpu_index = n; cudaError_t status = cudaSetDevice(n); check_error(status); }
/* ------------------------------------------------------------- */ LGL jx_sqlUpsert (BOOL update, PUCHAR table , PJXNODE pSqlParms , PUCHAR where) { LONG attrParm; LONG i; UCHAR sqlTempStmt[32766]; PUCHAR stmt = sqlTempStmt; PJXNODE pNode; PUCHAR comma = ""; PUCHAR name, value; SQLSMALLINT length; SQLHDBC hdbctmp; SQLHSTMT hstmttmp; SQLRETURN rc; PJXSQL pSQL = jx_sqlNewStatement (NULL); SQLCHUNK sqlChunk[32]; SHORT sqlChunkIx =0; PUCHAR sqlNullPtr = NULL; // First get the columen types - by now we use a select to mimic that // allocate a statement handle pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &hstmttmp); if (pSQL->rc != SQL_SUCCESS ) { SQLError( pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState , &pConnection->sqlCode, pConnection->sqlMsgDta , sizeof(pConnection->sqlMsgDta), &length); substr ( jxMessage , pConnection->sqlMsgDta , length); return ON; // we have an error } stmt = sqlTempStmt; stmt += sprintf (stmt , "select "); comma = ""; pNode = jx_GetNode(pSqlParms, "/"); while (pNode) { name = jx_GetNodeNamePtr (pNode); stmt += sprintf (stmt , "%s%s" , comma , name); comma = ","; pNode = jx_GetNodeNext(pNode); } stmt += sprintf (stmt , " from %s where 1=0" , table); // prepare the statement */ pSQL->rc = SQLPrepare(hstmttmp , sqlTempStmt, SQL_NTS); if (pSQL->rc != SQL_SUCCESS ) { SQLError( pConnection->henv, pConnection->hdbc , hstmttmp, pConnection->sqlState , &pConnection->sqlCode, pConnection->sqlMsgDta , sizeof(pConnection->sqlMsgDta), &length); substr ( jxMessage , pConnection->sqlMsgDta , length); SQLFreeStmt(hstmttmp, SQL_CLOSE); return ON; // we have an error } // Now we have the colume definitions - now build the update statement: // allocate a statement handle pSQL->rc = SQLAllocHandle(SQL_HANDLE_STMT, pConnection->hdbc , &pSQL->hstmt); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); SQLFreeStmt(hstmttmp, SQL_CLOSE); return ON; // we have an error } // This need to allow update attrParm = SQL_INSENSITIVE; pSQL->rc = SQLSetStmtAttr (pSQL->hstmt, SQL_ATTR_CURSOR_SENSITIVITY , &attrParm , 0); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return ON; // we have an error } if (update) { buildUpdate (hstmttmp, sqlTempStmt , table, pSqlParms , where); } else { buildInsert (hstmttmp, sqlTempStmt , table, pSqlParms , where); } // prepare the statement that provides the coloumn types pSQL->rc = SQLPrepare(pSQL->hstmt , sqlTempStmt, SQL_NTS); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); SQLFreeStmt(hstmttmp, SQL_CLOSE); return ON; // we have an error } // Take the description from the "select" and use it on the "update" pNode = jx_GetNode(pSqlParms, "/"); for (i=1; pNode; i++) { JXCOL Col; memset (&Col , 0 , sizeof(JXCOL)); value = jx_GetNodeValuePtr (pNode , NULL); pSQL->rc = SQLDescribeCol ( hstmttmp, i, Col.colname, sizeof (Col.colname), &Col.colnamelen, &Col.coltype, &Col.collen, &Col.scale, &Col.nullable ); if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return ON; // we have an error } // bind parameter to the statement if ( Col.coltype == SQL_BLOB || Col.coltype == SQL_CLOB ) { SQLINTEGER dataAtExec = SQL_DATA_AT_EXEC; // SQLLEN dataAtExec = SQL_LEN_DATA_AT_EXEC ( 0 ); PSQLCHUNK pSqlChunk = &sqlChunk[sqlChunkIx++]; pSqlChunk->actLen = strlen(value); pSqlChunk->offset = 0; pSqlChunk->chunkLen = min(pSqlChunk->actLen,16384); pSqlChunk->value = value; if (pSqlChunk->actLen == 0) { pSQL->rc = SQLBindParameter(pSQL->hstmt, i, SQL_PARAM_INPUT, SQL_C_BINARY, //SQL_C_CHAR, // SQL_C_BINARY, , // SQL_C_BINARY, //SQL_C_CHAR, SQL_LONGVARBINARY, // SQL_VARBINARY, // // SQL_LONGVARCHAR, 0 , // Col.collen, // pSqlChunk->actLen, pSqlChunk->chunkLen, pSqlChunk->chunkLen,//Col.collen, 0, // presition value, // Parm value 0 , // Buffer len - Not used NULL // no-chunk just direct access to NULL ); } else { pSQL->rc = SQLBindParameter(pSQL->hstmt, i, SQL_PARAM_INPUT, SQL_C_BINARY, //SQL_C_CHAR, // SQL_C_BINARY, , // SQL_C_BINARY, //SQL_C_CHAR, SQL_LONGVARBINARY, // SQL_VARBINARY, // // SQL_LONGVARCHAR, pSqlChunk->actLen,// Col.collen pSqlChunk->chunkLen, pSqlChunk->chunkLen,//Col.collen,//overall length 0, // presition (SQLPOINTER) pSqlChunk, // Parm value 0 , // Buffer len - Not used &dataAtExec // chunk size ); } } else { pSQL->rc = SQLBindParameter(pSQL->hstmt, i, SQL_PARAM_INPUT, SQL_C_CHAR, Col.coltype, Col.collen, // length Col.scale, // presition value, 0, NULL // pointer to length variable ); } if (pSQL->rc != SQL_SUCCESS ) { check_error (pSQL); return ON; // we have an error } pNode = jx_GetNodeNext(pNode); } // Now we are done with the select statement: rc = SQLFreeStmt(hstmttmp, SQL_CLOSE); // run the statement in "sqlstr" pSQL->rc = SQLExecute( pSQL->hstmt); // Has BLOB's ? while (pSQL->rc == SQL_NEED_DATA) { SQLPOINTER parmNo; PSQLCHUNK pSqlChunk; SHORT i; SQLINTEGER putLen; PUCHAR putBuf; pSQL->rc = SQLParamData(pSQL->hstmt, (SQLPOINTER) &pSqlChunk); if (pSQL->rc == SQL_NEED_DATA) { // iterate for each buffer chunk while (pSqlChunk->actLen > 0) { putLen = min(pSqlChunk->actLen , pSqlChunk->chunkLen); putBuf = pSqlChunk->value + pSqlChunk->offset; rc = SQLPutData(pSQL->hstmt, putBuf , putLen); pSqlChunk->offset += putLen; pSqlChunk->actLen -= putLen; } } } if (pSQL->rc != SQL_SUCCESS && pSQL->rc != SQL_NO_DATA_FOUND) { check_error (pSQL); return ON; // we have an error } jx_sqlClose (&pSQL); return OFF; }
void cuda_push_array(float *x_gpu, float *x, size_t n) { size_t size = sizeof(float)*n; cudaError_t status = cudaMemcpy(x_gpu, x, size, cudaMemcpyHostToDevice); check_error(status); }
void Sound::Initialize() { FMOD_RESULT result = FMOD_OK; result = FMOD_System_Create(&fmodSystem); check_error(result); unsigned int version; result = FMOD_System_GetVersion(fmodSystem, &version); check_error(result); if(version < FMOD_VERSION) { LOG_ISSUE("AUDIO ERROR: fmodex.dll is an older version than needed. " "FMOD version should be at least %u.", FMOD_VERSION); } int numDrivers; result = FMOD_System_GetNumDrivers(fmodSystem, &numDrivers); check_error(result); if(numDrivers == 0) { result = FMOD_System_SetOutput(fmodSystem, FMOD_OUTPUTTYPE_NOSOUND); check_error(result); } else { FMOD_CAPS capabilities; FMOD_SPEAKERMODE speakerMode; result = FMOD_System_GetDriverCaps(fmodSystem, 0, &capabilities, nullptr, &speakerMode); check_error(result); result = FMOD_System_SetSpeakerMode(fmodSystem, speakerMode); check_error(result); // if hardware acceleration is not available, // extend the buffer size to make sure there is enough room if(capabilities & FMOD_CAPS_HARDWARE_EMULATED) { result = FMOD_System_SetDSPBufferSize(fmodSystem, 1024, 10); check_error(result); } char name[256]; result = FMOD_System_GetDriverInfo(fmodSystem, 0, name, 256, nullptr); check_error(result); // SigmaTel sound devices crackle when the sound format is PCM 16-bit // PCM Floating-Point seems to fix it if(strstr(name, "SigmaTel")) { result = FMOD_System_SetSoftwareFormat(fmodSystem, 48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0, 0, FMOD_DSP_RESAMPLER_LINEAR); check_error(result); } } result = FMOD_System_Init(fmodSystem, MAX_CHANNELS, FMOD_INIT_NORMAL, 0); check_error(result); result = FMOD_System_CreateSoundGroup(fmodSystem, "Music", &musicGroup); check_error(result); result = FMOD_System_CreateSoundGroup(fmodSystem, "Sound Effects", &noiseGroup); check_error(result); numSounds = 0; for(int i = 0; i < MAX_SOUNDS; i++) sounds[i] = nullptr; }
int scf_update_exp(SCF *scf, const double x[], const double y[], double z) { int n_max = scf->n_max; int n = scf->n; double *f = scf->f; double *u = scf->u; int *p = scf->p; #if _GLPSCF_DEBUG double *c = scf->c; #endif double *un = scf->w; int i, ij, in, j, k, nj, ret = 0; double t; /* check if the factorization can be expanded */ if (n == n_max) { /* there is not enough room */ ret = SCF_ELIMIT; goto done; } /* increase the order of the factorization */ scf->n = ++n; /* fill new zero column of matrix F */ for (i = 1, in = f_loc(scf, i, n); i < n; i++, in += n_max) f[in] = 0.0; /* fill new zero row of matrix F */ for (j = 1, nj = f_loc(scf, n, j); j < n; j++, nj++) f[nj] = 0.0; /* fill new unity diagonal element of matrix F */ f[f_loc(scf, n, n)] = 1.0; /* compute new column of matrix U, which is (old F) * x */ for (i = 1; i < n; i++) { /* u[i,n] := (i-th row of old F) * x */ t = 0.0; for (j = 1, ij = f_loc(scf, i, 1); j < n; j++, ij++) t += f[ij] * x[j]; u[u_loc(scf, i, n)] = t; } /* compute new (spiked) row of matrix U, which is (old P) * y */ for (j = 1; j < n; j++) un[j] = y[p[j]]; /* store new diagonal element of matrix U, which is z */ un[n] = z; /* expand matrix P */ p[n] = n; #if _GLPSCF_DEBUG /* expand matrix C */ /* fill its new column, which is x */ for (i = 1, in = f_loc(scf, i, n); i < n; i++, in += n_max) c[in] = x[i]; /* fill its new row, which is y */ for (j = 1, nj = f_loc(scf, n, j); j < n; j++, nj++) c[nj] = y[j]; /* fill its new diagonal element, which is z */ c[f_loc(scf, n, n)] = z; #endif /* restore upper triangular structure of matrix U */ for (k = 1; k < n; k++) if (un[k] != 0.0) break; transform(scf, k, un); /* estimate the rank of matrices C and U */ scf->rank = estimate_rank(scf); if (scf->rank != n) ret = SCF_ESING; #if _GLPSCF_DEBUG /* check that the factorization is accurate enough */ check_error(scf, "scf_update_exp"); #endif done: return ret; }
/** * @brief Receive data from a UDP/IP socket * * Receives data like `recvfrom(2)`. Pointers may be `NULL`, then the information (e.g. the source port) is lost (you may use * NULL pointers if you're not interested in some information) * * @param sfd The socket file descriptor. * @param buffer Where the data will be written * @param size The size of `buffer` * @param src_host Where the sending host's name/IP will be stored * @param src_host_len `src_host`'s length * @param src_service Where the port on remote side will be written to * @param src_service_len `src_service`'s length * @param recvfrom_flags Flags for `recvfrom(2)` * @param numeric `LIBSOCKET_NUMERIC` if you want the names to remain unresolved. * * @retval n *n* bytes of data were received. * @retval 0 Peer sent EOF. * @retval <0 An error occurred. */ ssize_t recvfrom_inet_dgram_socket(int sfd, void* buffer, size_t size, char* src_host, size_t src_host_len, char* src_service, size_t src_service_len, int recvfrom_flags, int numeric) { struct sockaddr_storage client; # ifdef _TRADITIONAL_RDNS struct sockaddr_storage oldsockaddr; socklen_t oldsockaddrlen = sizeof(struct sockaddr_storage); struct hostent* he; void* addrptr; size_t addrlen; uint16_t sport = 0; # endif ssize_t bytes; # ifndef _TRADITIONAL_RDNS int retval; # endif # ifdef VERBOSE const char* errstr; # endif if ( sfd < 0 ) return -1; if ( buffer == NULL || size == 0) return -1; else memset(buffer,0,size); if ( src_host ) memset(src_host,0,src_host_len); if ( src_service ) memset(src_service,0,src_service_len); socklen_t stor_addrlen = sizeof(struct sockaddr_storage); if ( -1 == check_error(bytes = recvfrom(sfd,buffer,size,recvfrom_flags,(struct sockaddr*)&client,&stor_addrlen))) return -1; if ( src_host_len > 0 || src_service_len > 0 ) // If one of the things is wanted. If you give a null pointer with a positive _len parameter, you won't get the address. { if ( numeric == LIBSOCKET_NUMERIC ) { numeric = NI_NUMERICHOST | NI_NUMERICSERV; } // getnameinfo() doesn't work on FreeBSD (here) # ifndef _TRADITIONAL_RDNS if ( 0 != (retval = getnameinfo((struct sockaddr*)&client,sizeof(struct sockaddr_storage),src_host,src_host_len,src_service,src_service_len,numeric)) ) // Write information to the provided memory { # ifdef VERBOSE errstr = gai_strerror(retval); debug_write(errstr); # endif return -1; } # endif // so use traditional methods # ifdef _TRADITIONAL_RDNS if ( -1 == check_error(getsockname(sfd,(struct sockaddr*)&oldsockaddr,&oldsockaddrlen)) ) return -1; if ( oldsockaddrlen > sizeof(struct sockaddr_storage) ) // If getsockname truncated the struct return -1; if ( oldsockaddr.ss_family == AF_INET ) { addrptr = &(((struct sockaddr_in*)&client)->sin_addr); addrlen = sizeof(struct in_addr); sport = ntohs(((struct sockaddr_in*)&client)->sin_port); } else if ( oldsockaddr.ss_family == AF_INET6 ) { addrptr = &(((struct sockaddr_in6*)&client)->sin6_addr); addrlen = sizeof(struct in6_addr); sport = ntohs(((struct sockaddr_in6*)&client)->sin6_port); } if ( NULL == (he = gethostbyaddr(addrptr,addrlen,oldsockaddr.ss_family) ) ) { check_error(-1); return -1; } strncpy(src_host,he->h_name,src_host_len); snprintf(src_service,src_service_len,"%u",sport); # endif } return bytes; }
// get the handle for connections to KWallet static int get_wallet_handle(const backend_kwallet_context_t *context) { // Open the wallet. int handle = invalid_kwallet_handle; GError* error = NULL; /* signature: * * in s wallet, * in x wId, * in s appid, * * out i arg_0 */ GVariant *ret = g_dbus_proxy_call_sync(context->proxy, "open", g_variant_new("(sxs)", context->wallet_name, 0LL, app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(check_error(error)) { g_variant_unref(ret); return invalid_kwallet_handle; } GVariant *child = g_variant_get_child_value(ret, 0); handle = g_variant_get_int32(child); g_variant_unref(child); g_variant_unref(ret); // Check if our folder exists. gboolean has_folder = FALSE; /* signature: * * in i handle, * in s folder, * in s appid, * * out b arg_0 */ ret = g_dbus_proxy_call_sync(context->proxy, "hasFolder", g_variant_new("(iss)", handle, kwallet_folder, app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(check_error(error)) { g_variant_unref(ret); return invalid_kwallet_handle; } child = g_variant_get_child_value(ret, 0); has_folder = g_variant_get_boolean(child); g_variant_unref(child); g_variant_unref(ret); // Create it if it didn't. if (!has_folder) { gboolean success = FALSE; /* signature: * * in i handle, * in s folder, * in s appid, * * out b arg_0 */ ret = g_dbus_proxy_call_sync(context->proxy, "createFolder", g_variant_new("(iss)", handle, kwallet_folder, app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(check_error(error)) { g_variant_unref(ret); return invalid_kwallet_handle; } GVariant *child = g_variant_get_child_value(ret, 0); success = g_variant_get_boolean(child); g_variant_unref(child); g_variant_unref(ret); if(!success) return invalid_kwallet_handle; } return handle; }
/** * @brief Connect a UDP socket. * * If a datagram socket is connected, all data written to it (using `write(2)`) is sent to the peer * connected to and all data `read(2)` from it is data sent by the peer. Usually used by clients only. * * @param sfd The socket file descriptor * @param host The host to connect to * @param service The port/service specifier * * @retval 0 Success * @retval -1 Error. */ int connect_inet_dgram_socket(int sfd, const char* host, const char* service) { struct addrinfo *result, *result_check, hint; struct sockaddr_storage oldsockaddr; struct sockaddr deconnect; socklen_t oldsockaddrlen = sizeof(struct sockaddr_storage); int return_value; # ifdef VERBOSE const char* errstring; # endif if ( sfd < 0 ) return -1; if ( host == NULL ) { // This does not work on FreeBSD systems. We pretend to disconnect the socket although we don't do so. This is not very severe for the application # ifndef __FreeBSD__ memset(&deconnect,0,sizeof(struct sockaddr)); deconnect.sa_family = AF_UNSPEC; if ( check_error(connect(sfd,&deconnect,sizeof(struct sockaddr))) ) return -1; # endif return 0; } if ( -1 == check_error(getsockname(sfd,(struct sockaddr*)&oldsockaddr,&oldsockaddrlen)) ) return -1; if ( oldsockaddrlen > sizeof(struct sockaddr_storage) ) // If getsockname truncated the struct return -1; memset(&hint,0,sizeof(struct addrinfo)); hint.ai_family = ((struct sockaddr_in*)&oldsockaddr)->sin_family; // AF_INET or AF_INET6 - offset is same at sockaddr_in and sockaddr_in6 hint.ai_socktype = SOCK_DGRAM; if ( 0 != (return_value = getaddrinfo(host,service,&hint,&result))) { # ifdef VERBOSE errstring = gai_strerror(return_value); debug_write(errstring); # endif return -1; } // As described in "The Linux Programming Interface", Michael Kerrisk 2010, chapter 59.11 (p. 1220ff) for ( result_check = result; result_check != NULL; result_check = result_check->ai_next ) // go through the linked list of struct addrinfo elements { if ( -1 != (return_value = connect(sfd,result_check->ai_addr,result_check->ai_addrlen))) // connected without error { break; } else { check_error(return_value); } } // We do now have a working (updated) socket connection to our target if ( result_check == NULL ) // or not? { # ifdef VERBOSE debug_write("connect_inet_dgram_socket: Could not connect to any address!\n"); # endif return -1; } freeaddrinfo(result); return 0; }
// Get the (key,value) pairs back from KWallet. GHashTable* dt_pwstorage_kwallet_get(const backend_kwallet_context_t *context, const gchar* slot) { GHashTable *table = g_hash_table_new(g_str_hash, g_str_equal); GError* error = NULL; // Is there an entry in the wallet? gboolean has_entry = FALSE; int wallet_handle = get_wallet_handle(context); /* signature: * * in i handle, * in s folder, * in s key, * in s appid, * * out b arg_0 */ GVariant *ret = g_dbus_proxy_call_sync(context->proxy, "hasEntry", g_variant_new("(isss)", wallet_handle, kwallet_folder, slot, app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(check_error(error)) { g_variant_unref(ret); return table; } GVariant *child = g_variant_get_child_value(ret, 0); has_entry = g_variant_get_boolean(child); g_variant_unref(child); g_variant_unref(ret); if(!has_entry) return table; /* signature: * * in i handle, * in s folder, * in s key, * in s appid, * * out a{sv} arg_0) */ ret = g_dbus_proxy_call_sync(context->proxy, "readMapList", g_variant_new("(isss)", wallet_handle, kwallet_folder, slot, app_id), G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if(check_error(error)) { g_variant_unref(ret); return table; } child = g_variant_get_child_value(ret, 0); // we are only interested in the first child. i am not even sure that there can legally be more than one if(g_variant_n_children(child)<1) { g_variant_unref(child); g_variant_unref(ret); return table; } GVariant *element = g_variant_get_child_value(child, 0); GVariant *v = NULL; g_variant_get(element, "{sv}", NULL, &v); const gchar *byte_array = g_variant_get_data(v); if(!byte_array) { g_variant_unref(v); g_variant_unref(element); g_variant_unref(child); g_variant_unref(ret); return table; } int entries = GINT_FROM_BE(*((int*)byte_array)); byte_array += sizeof(gint); for(int i=0; i<entries; i++) { guint length; gchar* key = array2string(byte_array, &length); byte_array += length; gchar* value = array2string(byte_array, &length); byte_array += length; dt_print(DT_DEBUG_PWSTORAGE,"[pwstorage_kwallet_get] reading (%s, %s)\n",(gchar*)key, (gchar*)value); g_hash_table_insert(table, key, value); } g_variant_unref(v); g_variant_unref(element); g_variant_unref(child); g_variant_unref(ret); return table; }
// Socket Src string Src str len Src service Src service len NUMERIC? int accept_inet_stream_socket(int sfd, char* src_host, size_t src_host_len, char* src_service, size_t src_service_len, int flags, int accept_flags) { struct sockaddr_storage client_info; int client_sfd; # ifndef _TRADITIONAL_RDNS int retval; # endif # ifdef _TRADITIONAL_RDNS struct sockaddr_storage oldsockaddr; socklen_t oldsockaddrlen = sizeof(struct sockaddr_storage); struct hostent* he; void* addrptr; size_t in_addrlen; uint16_t sport = 0; # endif # ifdef VERBOSE const char* errstr; # endif socklen_t addrlen = sizeof(struct sockaddr_storage); // Portable behavior # if LIBSOCKET_LINUX if ( -1 == check_error((client_sfd = accept4(sfd,(struct sockaddr*)&client_info,&addrlen,accept_flags)))) // blocks return -1; # else if ( -1 == check_error((client_sfd = accept(sfd,(struct sockaddr*)&client_info,&addrlen)))) // blocks return -1; # endif if ( src_host_len > 0 || src_service_len > 0 ) // If one of the things is wanted. If you give a null pointer with a positive _len parameter, you won't get the address. { if ( flags == LIBSOCKET_NUMERIC ) { flags = NI_NUMERICHOST | NI_NUMERICSERV; } else { flags = 0; // To prevent errors: Unknown flags are ignored } # ifndef _TRADITIONAL_RDNS if ( 0 != (retval = getnameinfo((struct sockaddr*)&client_info,sizeof(struct sockaddr_storage),src_host,src_host_len,src_service,src_service_len,flags)) ) // Write information to the provided memory { # ifdef VERBOSE errstr = gai_strerror(retval); debug_write(errstr); # endif } # endif # ifdef _TRADITIONAL_RDNS if ( -1 == check_error(getsockname(sfd,(struct sockaddr*)&oldsockaddr,&oldsockaddrlen)) ) return -1; if ( oldsockaddrlen > sizeof(struct sockaddr_storage) ) // If getsockname truncated the struct return -1; if ( oldsockaddr.ss_family == AF_INET ) { addrptr = &(((struct sockaddr_in*)&client_info)->sin_addr); in_addrlen = sizeof(struct in_addr); sport = ntohs(((struct sockaddr_in*)&client_info)->sin_port); } else if ( oldsockaddr.ss_family == AF_INET6 ) { addrptr = &(((struct sockaddr_in6*)&client_info)->sin6_addr); in_addrlen = sizeof(struct in6_addr); sport = ntohs(((struct sockaddr_in6*)&client_info)->sin6_port); } if ( NULL == (he = gethostbyaddr(addrptr,in_addrlen,oldsockaddr.ss_family) ) ) { check_error(-1); // Don't return with error on name resolution failure } strncpy(src_host,he->h_name,src_host_len); snprintf(src_service,src_service_len,"%u",sport); # endif } return client_sfd; }
/* Monitor socket */ void socket_poll (HANDLE hStop, void *_data) { LPSELECTDATA lpSelectData; LPSELECTQUERY iterQuery; HANDLE aEvents[MAXIMUM_SELECT_OBJECTS]; DWORD nEvents; long maskEvents; DWORD i; u_long iMode; SELECTMODE mode; WSANETWORKEVENTS events; lpSelectData = (LPSELECTDATA)_data; DEBUG_PRINT("Worker has %d queries to service", lpSelectData->nQueriesCount); for (nEvents = 0; nEvents < lpSelectData->nQueriesCount; nEvents++) { iterQuery = &(lpSelectData->aQueries[nEvents]); aEvents[nEvents] = CreateEvent(NULL, TRUE, FALSE, NULL); maskEvents = 0; mode = iterQuery->EMode; if ((mode & SELECT_MODE_READ) != 0) { DEBUG_PRINT("Polling read for %d", iterQuery->hFileDescr); maskEvents |= FD_READ | FD_ACCEPT | FD_CLOSE; } if ((mode & SELECT_MODE_WRITE) != 0) { DEBUG_PRINT("Polling write for %d", iterQuery->hFileDescr); maskEvents |= FD_WRITE | FD_CONNECT | FD_CLOSE; } if ((mode & SELECT_MODE_EXCEPT) != 0) { DEBUG_PRINT("Polling exceptions for %d", iterQuery->hFileDescr); maskEvents |= FD_OOB; } check_error(lpSelectData, WSAEventSelect( (SOCKET)(iterQuery->hFileDescr), aEvents[nEvents], maskEvents) == SOCKET_ERROR); } /* Add stop event */ aEvents[nEvents] = hStop; nEvents++; if (lpSelectData->nError == 0) { check_error(lpSelectData, WaitForMultipleObjects( nEvents, aEvents, FALSE, INFINITE) == WAIT_FAILED); }; if (lpSelectData->nError == 0) { for (i = 0; i < lpSelectData->nQueriesCount; i++) { iterQuery = &(lpSelectData->aQueries[i]); if (WaitForSingleObject(aEvents[i], 0) == WAIT_OBJECT_0) { DEBUG_PRINT("Socket %d has pending events", (i - 1)); if (iterQuery != NULL) { /* Find out what kind of events were raised */ if (WSAEnumNetworkEvents((SOCKET)(iterQuery->hFileDescr), aEvents[i], &events) == 0) { if ((iterQuery->EMode & SELECT_MODE_READ) != 0 && (events.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) != 0) { select_data_result_add(lpSelectData, SELECT_MODE_READ, iterQuery->lpOrigIdx); } if ((iterQuery->EMode & SELECT_MODE_WRITE) != 0 && (events.lNetworkEvents & (FD_WRITE | FD_CONNECT | FD_CLOSE)) != 0) { select_data_result_add(lpSelectData, SELECT_MODE_WRITE, iterQuery->lpOrigIdx); } if ((iterQuery->EMode & SELECT_MODE_EXCEPT) != 0 && (events.lNetworkEvents & FD_OOB) != 0) { select_data_result_add(lpSelectData, SELECT_MODE_EXCEPT, iterQuery->lpOrigIdx); } } } } /* WSAEventSelect() automatically sets socket to nonblocking mode. Restore the blocking one. */ if (iterQuery->uFlagsFd & FLAGS_FD_IS_BLOCKING) { DEBUG_PRINT("Restore a blocking socket"); iMode = 0; check_error(lpSelectData, WSAEventSelect((SOCKET)(iterQuery->hFileDescr), aEvents[i], 0) != 0 || ioctlsocket((SOCKET)(iterQuery->hFileDescr), FIONBIO, &iMode) != 0); } else { check_error(lpSelectData, WSAEventSelect((SOCKET)(iterQuery->hFileDescr), aEvents[i], 0) != 0); }; CloseHandle(aEvents[i]); aEvents[i] = INVALID_HANDLE_VALUE; } } }
int create_multicast_socket(const char* group, const char* port, const char* if_name) { int sfd, return_value; struct sockaddr maddr, localif; struct addrinfo hints, *result; struct ip_mreqn mreq4; struct ipv6_mreq mreq6; struct in_addr any; struct ifreq interface; memset(&maddr,0,sizeof(maddr)); memset(&localif,0,sizeof(localif)); memset(&mreq4,0,sizeof(mreq4)); memset(&mreq6,0,sizeof(mreq6)); memset(&hints,0,sizeof(hints)); memset(&interface,0,sizeof(interface)); if ( -1 == check_error(sfd = create_inet_server_socket(group,port,LIBSOCKET_UDP,LIBSOCKET_BOTH,0)) ) { return -1; } hints.ai_socktype = SOCK_DGRAM; hints.ai_family = AF_UNSPEC; if ( 0 != (return_value = getaddrinfo(group,port,&hints,&result)) ) { int errno_saved = errno; # ifdef VERBOSE const char* errstring = gai_strerror(return_value); debug_write(errstring); # endif close(sfd); errno = errno_saved; return -1; } if ( result->ai_family == AF_INET ) { // Result is IPv4 address. mreq4.imr_multiaddr = ((struct sockaddr_in*)result->ai_addr)->sin_addr; if ( if_name == NULL ) { mreq4.imr_ifindex = 0; any.s_addr = INADDR_ANY; mreq4.imr_address = any; } else { memcpy(interface.ifr_name,if_name,strlen(if_name) > IFNAMSIZ ? IFNAMSIZ : strlen(if_name)); if ( -1 == check_error(ioctl(sfd,SIOCGIFINDEX,&interface)) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } mreq4.imr_ifindex = interface.ifr_ifindex; } if ( -1 == check_error(setsockopt(sfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&mreq4,sizeof(struct ip_mreqn))) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } if ( -1 == check_error(setsockopt(sfd,IPPROTO_IP,IP_MULTICAST_IF,&mreq4,sizeof(struct ip_mreqn))) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } // Setup finished. // } else if ( result->ai_family == AF_INET6 ) { mreq6.ipv6mr_multiaddr = ((struct sockaddr_in6*)result->ai_addr)->sin6_addr; mreq6.ipv6mr_interface = 0; if ( if_name == NULL ) mreq6.ipv6mr_interface = 0; else { memcpy(interface.ifr_name,if_name,strlen(if_name) > IFNAMSIZ ? IFNAMSIZ : strlen(if_name)); if ( -1 == check_error(ioctl(sfd,SIOCGIFINDEX,&interface)) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } mreq6.ipv6mr_interface = interface.ifr_ifindex; } if ( -1 == check_error(setsockopt(sfd,IPPROTO_IPV6,IPV6_ADD_MEMBERSHIP,&mreq6,sizeof(struct ipv6_mreq))) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } if ( -1 == check_error(setsockopt(sfd,IPPROTO_IPV6,IPV6_MULTICAST_IF,&mreq6.ipv6mr_interface,sizeof(mreq6.ipv6mr_interface))) ) { int errno_saved = errno; close(sfd); errno = errno_saved; return -1; } } return sfd; }
void go_cl(config c) { cl_int error; cl_platform_id platform; cl_device_id device; cl_context context; cl_command_queue commands; cl_program program; cl_kernel kernel; cl_event ev; cl_mem mem; float *result = NULL; char buf[256]; int work_size[2] = { 128, 128 }; int offset[2]; int x, y; cl_float4 camera_pos = { c.camera_pos.x, c.camera_pos.y, c.camera_pos.z, 0 }; cl_float4 camera_dir = { c.camera_target.x - c.camera_pos.x, c.camera_target.y - c.camera_pos.y, c.camera_target.z - c.camera_pos.z, 0 }; cl_float4 light_pos = { c.light_pos.x, c.light_pos.y, c.light_pos.z, 0 }; cl_int2 image_size = { c.width, c.height }; sprintf(buf, "-DBAILOUT=%d -DSCALE=%f -DFOV=%f", c.bailout, c.scale, c.fov); printf("Starting\n"); init_cl(&platform, &device, &context, &commands); dump_info(platform, device); printf("Creating kernel\n"); program = load_program_from_file("kernel.cl", context, device, buf); kernel = create_kernel(program, "test"); printf("Setting memory\n"); mem = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * c.width * c.height, NULL, &error); check_error(error, "Could not allocate buffer"); error = clSetKernelArg(kernel, 0, sizeof(cl_mem), &mem); error = clSetKernelArg(kernel, 1, sizeof(cl_float4), &camera_pos); error = clSetKernelArg(kernel, 2, sizeof(cl_float4), &camera_dir); error = clSetKernelArg(kernel, 3, sizeof(cl_float4), &light_pos); error = clSetKernelArg(kernel, 4, sizeof(cl_int2), &image_size); clFinish(commands); printf("Running\n"); for (x = 0; x < c.width; x += work_size[0]) { for (y = 0; y < c.height; y += work_size[1]) { offset[0] = x; offset[1] = y; error = clEnqueueNDRangeKernel(commands, kernel, 2, offset, work_size, NULL, 0, NULL, &ev); printf("."); } } clFinish(commands); printf("\nWriting image\n"); result = malloc(sizeof(float) * c.width * c.height); error = clEnqueueReadBuffer(commands, mem, CL_TRUE, 0, sizeof(float) * c.width * c.height, result, 0, NULL, &ev); clFinish(commands); save(result, c, 0, 0); free(result); clReleaseMemObject(mem); release_cl(context, program, commands, kernel); }
/** \return GL_TRUE for pass, GL_FALSE for fail */ static GLboolean test_fbo(const struct format_info *info) { const int max = get_max_val(info); const int comps = num_components(info->BaseFormat); const GLenum type = get_datatype(info); GLint f; GLuint fbo, texObj; GLenum status; GLboolean intMode; GLint buf; if (0) fprintf(stderr, "============ Testing format = %s ========\n", info->Name); /* Create texture */ glGenTextures(1, &texObj); glBindTexture(GL_TEXTURE_2D, texObj); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, info->IntFormat, TexWidth, TexHeight, 0, info->BaseFormat, type, NULL); if (check_error(__FILE__, __LINE__)) return GL_FALSE; glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &f); assert(f == info->IntFormat); /* Create FBO to render to texture */ glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texObj, 0); if (check_error(__FILE__, __LINE__)) return GL_FALSE; status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT); if (status != GL_FRAMEBUFFER_COMPLETE_EXT) { fprintf(stderr, "%s: failure: framebuffer incomplete.\n", TestName); return GL_FALSE; } glGetBooleanv(GL_RGBA_INTEGER_MODE_EXT, &intMode); if (check_error(__FILE__, __LINE__)) return GL_FALSE; if (!intMode) { fprintf(stderr, "%s: GL_RGBA_INTEGER_MODE_EXT return GL_FALSE\n", TestName); return GL_FALSE; } glGetIntegerv(GL_READ_BUFFER, &buf); assert(buf == GL_COLOR_ATTACHMENT0_EXT); glGetIntegerv(GL_DRAW_BUFFER, &buf); assert(buf == GL_COLOR_ATTACHMENT0_EXT); /* test clearing */ if (1) { static const GLint clr[4] = { 8, 7, 6, 5 }; GLint pix[4], i; glClearColorIiEXT(clr[0], clr[1], clr[2], clr[3]); glClear(GL_COLOR_BUFFER_BIT); glReadPixels(5, 5, 1, 1, GL_RGBA_INTEGER_EXT, GL_INT, pix); for (i = 0; i < comps; i++) { if (pix[i] != clr[i]) { fprintf(stderr, "%s: glClear failed\n", TestName); fprintf(stderr, " Texture format = %s\n", info->Name); fprintf(stderr, " Expected %d, %d, %d, %d\n", clr[0], clr[1], clr[2], clr[3]); fprintf(stderr, " Found %d, %d, %d, %d\n", pix[0], pix[1], pix[2], pix[3]); return GL_FALSE; } } } /* Do glDraw/ReadPixels test */ if (1) { #define W 15 #define H 10 GLint image[H * W * 4], readback[H * W * 4]; GLint i; if (info->Signed) { for (i = 0; i < W * H * 4; i++) { image[i] = (i - 10) % max; assert(image[i] < max); } } else { for (i = 0; i < W * H * 4; i++) { image[i] = (i + 3) % max; assert(image[i] < max); } } glUseProgram(PassthroughProgram); if(0)glUseProgram(SimpleProgram); glWindowPos2i(1, 1); glDrawPixels(W, H, GL_RGBA_INTEGER_EXT, GL_INT, image); if (check_error(__FILE__, __LINE__)) return GL_FALSE; glReadPixels(1, 1, W, H, GL_RGBA_INTEGER_EXT, GL_INT, readback); if (check_error(__FILE__, __LINE__)) return GL_FALSE; for (i = 0; i < W * H * 4; i++) { if (readback[i] != image[i]) { if (comps == 3 && i % 4 == 3 && readback[i] == 1) continue; /* alpha = 1 if base format == RGB */ fprintf(stderr, "%s: glDraw/ReadPixels failed at %d. Expected %d, found %d\n", TestName, i, image[i], readback[i]); fprintf(stderr, "Texture format = %s\n", info->Name); assert(0); return GL_FALSE; } } #undef W #undef H } /* Do rendering test */ if (1) { GLint value[4], result[4], loc, w = piglit_width, h = piglit_height; GLint error = 1; /* XXX fix */ /* choose random value/color for polygon */ value[0] = rand() % 100; value[1] = rand() % 100; value[2] = rand() % 100; value[3] = rand() % 100; glUseProgram(SimpleProgram); check_error(__FILE__, __LINE__); loc = glGetUniformLocation(SimpleProgram, "value"); assert(loc >= 0); glUniform4iv(loc, 1, value); check_error(__FILE__, __LINE__); #if 0 /* allow testing on mesa until this is implemented */ loc = glGetFragDataLocationEXT(SimpleProgram, "out_color"); assert(loc >= 0); #endif glBegin(GL_POLYGON); glVertex2f(0, 0); glVertex2f(w, 0); glVertex2f(w, h); glVertex2f(0, h); glEnd(); check_error(__FILE__, __LINE__); glReadPixels(w/2, h/2, 1, 1, GL_RGBA_INTEGER, GL_INT, result); check_error(__FILE__, __LINE__); if (info->BaseFormat == GL_RGB_INTEGER_EXT) { value[3] = 1; } if (abs(result[0] - value[0]) > error || abs(result[1] - value[1]) > error || abs(result[2] - value[2]) > error || abs(result[3] - value[3]) > error) { fprintf(stderr, "%s: failure with format %s:\n", TestName, info->Name); fprintf(stderr, " input value = %d, %d, %d, %d\n", value[0], value[1], value[2], value[3]); fprintf(stderr, " result color = %d, %d, %d, %d\n", result[0], result[1], result[2], result[3]); return GL_FALSE; } } piglit_present_results(); glDeleteTextures(1, &texObj); glDeleteFramebuffers(1, &fbo); return GL_TRUE; }