/** * Handles the message sent for the creation of jewelry in the world. * * This function is called whenever jewelry should be created in the world for a client. * * @return cMessage - Returns a Create Object (0x0000F745) server message. */ cMessage cJewelry::CreatePacket( ) { cMessage cmReturn; cItemModels *pcModel = cItemModels::FindModel( m_dwItemModelID ); cObject *pcObject = cWorldManager::FindObject( m_dwGUID ); if( pcModel ) { cmReturn << 0xF745L << m_dwGUID << BYTE(0x11); //0x11 is a constant cmReturn << pcModel->m_bPaletteChange << pcModel->m_bTextureChange << pcModel->m_bModelChange; // The Model Vectors if ( pcModel->m_bPaletteChange != 0) { for (int i = 0; i < pcModel->m_bPaletteChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorPal[i],sizeof(pcModel->m_vectorPal[i])); } } if (pcModel->m_bPaletteChange != 0) { cmReturn << WORD( pcModel->m_wUnknown1 ); } if ( pcModel->m_bTextureChange != 0) { for (int i = 0; i < pcModel->m_bTextureChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorTex[i],sizeof(pcModel->m_vectorTex[i])); } } if ( pcModel->m_bModelChange != 0) { for (int i = 0; i < pcModel->m_bModelChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorMod[i],sizeof(pcModel->m_vectorMod[i])); } } } cmReturn.pasteAlign(4); cmReturn << pcModel->m_dwFlags1 << 0x414L << 0x65L; // MASK 0x00008000 -- Location if ( !m_fIsOwned ) cmReturn.CannedData( (BYTE *)&m_Location, sizeof( cLocation ) ); // MASK 0x00000800 -- Sound Set DWORD dwSoundSet = 0x20000000L + pcModel->m_wSoundSet; cmReturn << dwSoundSet; // MASK 0x00001000 -- Particle Effects (unknown_blue) cmReturn << 0x34000000 + pcModel->m_dwUnknown_Blue; // MASK 0x00000001 -- ModelNumber DWORD dwModel = 0x02000000L + pcModel->m_dwModelNumber; cmReturn << dwModel; // MASK 0x00000080 -- Scale cmReturn << float(1.0); // SeaGreens WORD wNuminteracts = 0x0; WORD wNumbubbles = 0x0; WORD wNumJumps = 0x0; WORD wNumOverrides = 0x0; WORD wUnkFlag8 = 0x0; WORD wUnkFlag10 = 0x0; cmReturn << m_wPositionSequence << m_wNumAnims //wNuminteracts << wNumbubbles << wNumJumps << m_wNumPortals << m_wNumAnims << wNumOverrides << wUnkFlag8 << m_wNumLogins << wUnkFlag10; // Flags2 //DWORD dwFlags2 = 0x81210018; cmReturn << pcModel->m_dwFlags2; cmReturn << Name( ); // Object's Name cmReturn << pcModel->m_wModel; // Object's Model cmReturn << this->m_wIcon; // Object's Icon cmReturn << pcModel->m_dwObjectFlags1; // Object Flags cmReturn << pcModel->m_dwObjectFlags2; // Object Flags // Masked against dwFlags2 // Mask 0x0008 - Value cmReturn << pcModel->m_dwValue; // Mask 0x0010 dwUnknown_v2 cmReturn << pcModel->m_dwUnknown_v2; // Mask 0x0080 - If Enchanted // Mask 0x10000 Equip Possible cmReturn << pcModel->m_dwEquipPossible; // Mask 0x00200000 - Burden cmReturn << pcModel->m_wBurden; //Mask 0x01000000 - Workmanship cmReturn << float(3.0); //Mask 0x80000000 - Material cmReturn << 0x05L; return cmReturn; }
/* * Function to decompress a compressed message */ static int mc_decompress(struct sip_msg* msg) { #define HDRS_TO_SKIP 4 int i; int j; int rc; int algo=-1; int hdrs_algo=-1; int b64_required=-1; str msg_body; str msg_final; str b64_decode={NULL, 0}; str hdr_b64_decode={NULL,0}; str uncomp_body={NULL,0}; str uncomp_hdrs={NULL,0}; char *new_buf; unsigned long temp; /* hdr_vec allows to sort the headers. This will help skipping these headers when building the new message */ struct hdr_field *hf; struct hdr_field *hdr_vec[HDRS_TO_SKIP]; /*hdr_vec : 0 Content-Length 1 Comp-Hdrs 2 Headers-Algo 3 Content-Encoding*/ memset(hdr_vec, 0, HDRS_TO_SKIP * sizeof(struct hdr_field*)); if (parse_headers(msg, HDR_EOH_F, 0) != 0) { LM_ERR("failed to parse SIP message\n"); return -1; } /*If compressed with this module there are great chances that Content-Encoding is last*/ hdr_vec[3] = msg->last_header; if (!is_content_encoding(hdr_vec[3])) { hdr_vec[3] = NULL; for (hf = msg->headers; hf; hf = hf->next) { if (is_content_encoding(hf)) { hdr_vec[3] = hf; continue; } if (hf->type == HDR_OTHER_T && !strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) { hdr_vec[1] = hf; continue; } if (hf->type == HDR_OTHER_T && !strncasecmp(hf->name.s, HDRS_ENCODING, sizeof(HDRS_ENCODING)-1)) { hdr_vec[2] = hf; } if (hdr_vec[1] && hdr_vec[2] && hdr_vec[3]) break; } } else { for (hf = msg->headers; hf; hf = hf->next) { if (!hdr_vec[1] && hf->type == HDR_OTHER_T && !strncasecmp(hf->name.s, COMP_HDRS,COMP_HDRS_LEN)) { hdr_vec[1] = hf; continue; } if (!hdr_vec[2] && hf->type == HDR_OTHER_T && !strncasecmp(hf->name.s, HDRS_ENCODING, sizeof(HDRS_ENCODING)-1)) hdr_vec[2] = hf; if (hdr_vec[2] && hdr_vec[3] && hdr_vec[1]) break; } } /* Only if content-encoding present, Content-Length will be replaced with the one in the compressed body or in compressed headers*/ if (hdr_vec[3]) { hdr_vec[0] = msg->content_length; parse_algo_hdr(hdr_vec[3], &algo, &b64_required); } if (b64_required > 0 && hdr_vec[3]) { msg_body.s = msg->last_header->name.s + msg->last_header->len + CRLF_LEN; msg_body.len = strlen(msg_body.s); /* Cutting CRLF'S at the end of the message */ while (WORD(msg_body.s + msg_body.len-CRLF_LEN) == PARSE_CRLF) { msg_body.len -= CRLF_LEN; } if (wrap_realloc(&body_in, calc_max_base64_decode_len(msg_body.len))) return -1; b64_decode.s = body_in.s; b64_decode.len = base64decode((unsigned char*)b64_decode.s, (unsigned char*)msg_body.s, msg_body.len); } else if (hdr_vec[3]) { if (get_body(msg, &msg_body) < 0) { LM_ERR("failed to get body\n"); return -1; } b64_decode.s = msg_body.s; b64_decode.len = msg_body.len; } b64_required=0; if (hdr_vec[2]) { parse_algo_hdr(hdr_vec[3], &algo, &b64_required); } if (b64_required > 0 && hdr_vec[1]) { if (wrap_realloc(&hdr_in, calc_max_base64_decode_len(hdr_vec[1]->body.len))) return -1; hdr_b64_decode.s = hdr_in.s; hdr_b64_decode.len = base64decode( (unsigned char*)hdr_b64_decode.s, (unsigned char*)hdr_vec[1]->body.s, hdr_vec[1]->body.len ); } else if (hdr_vec[1]) { hdr_b64_decode.s = hdr_vec[1]->body.s; hdr_b64_decode.len = hdr_vec[1]->body.len; } switch (hdrs_algo) { case 0: /* deflate */ temp = (unsigned long)BUFLEN; rc = uncompress((unsigned char*)hdr_buf, &temp, (unsigned char*)hdr_b64_decode.s, (unsigned long)hdr_b64_decode.len); uncomp_hdrs.s = hdr_buf; uncomp_hdrs.len = temp; if (check_zlib_rc(rc)) { LM_ERR("header decompression failed\n"); return -1; } break; case 1: /* gzip */ rc = gzip_uncompress( (unsigned char*)hdr_b64_decode.s, (unsigned long)hdr_b64_decode.len, &hdr_out, &temp); if (check_zlib_rc(rc)) { LM_ERR("header decompression failed\n"); return -1; } uncomp_hdrs.s = hdr_out.s; uncomp_hdrs.len = temp; break; case -1: break; default: return -1; } switch (algo) { case 0: /* deflate */ temp = (unsigned long)BUFLEN; rc = uncompress((unsigned char*)body_buf, &temp, (unsigned char*)b64_decode.s, (unsigned long)b64_decode.len); if (check_zlib_rc(rc)) { LM_ERR("body decompression failed\n"); return -1; } uncomp_body.s = body_buf; uncomp_body.len = temp; break; case 1: /* gzip */ rc = gzip_uncompress( (unsigned char*)b64_decode.s, (unsigned long)b64_decode.len, &body_out, &temp); if (check_zlib_rc(rc)) { LM_ERR("body decompression failed\n"); return -1; } uncomp_body.s = body_out.s; uncomp_body.len = temp; break; case -1: LM_DBG("no body\n"); break; default: LM_ERR("invalid algo\n"); return -1; } /* Sort to have the headers in order */ for (i = 0; i < HDRS_TO_SKIP - 1; i++) { for (j = i + 1; j < HDRS_TO_SKIP; j++) { if (!hdr_vec[j]) continue; if (!hdr_vec[i] && hdr_vec[j]) { hdr_vec[i] = hdr_vec[j]; hdr_vec[j] = NULL; } if ((hdr_vec[i] && hdr_vec[j]) && (hdr_vec[i]->name.s > hdr_vec[j]->name.s)) { hf = hdr_vec[i]; hdr_vec[i] = hdr_vec[j]; hdr_vec[j] = hf; } } } int msg_final_len = 0; int msg_ptr=0; for ( i = 0; i < HDRS_TO_SKIP; i++) { if (hdr_vec[i]) { msg_final_len += hdr_vec[i]->name.s - (msg->buf+msg_ptr); msg_ptr += hdr_vec[i]->name.s+hdr_vec[i]->len - (msg->buf+msg_ptr); } } msg_final_len += msg->last_header->name.s + msg->last_header->len - (msg->buf + msg_ptr); if (hdrs_algo >= 0) msg_final_len += uncomp_hdrs.len; if (algo >= 0) msg_final_len += uncomp_body.len; else msg_final_len += strlen(msg->eoh); if (wrap_realloc(&buf_out, msg_final_len)) return -1; msg_ptr = 0; msg_final.len = 0; msg_final.s = buf_out.s; for ( i = 0; i < HDRS_TO_SKIP; i++) { if (hdr_vec[i]) { wrap_copy_and_update(&msg_final.s, msg->buf+msg_ptr, hdr_vec[i]->name.s-(msg->buf+msg_ptr), &msg_final.len); msg_ptr += (hdr_vec[i]->name.s+hdr_vec[i]->len) - (msg->buf+msg_ptr); } } wrap_copy_and_update( &msg_final.s, msg->buf+msg_ptr, (msg->last_header->name.s+msg->last_header->len)- (msg->buf+msg_ptr), &msg_final.len ); if (hdrs_algo >= 0) { wrap_copy_and_update(&msg_final.s, uncomp_hdrs.s, uncomp_hdrs.len,&msg_final.len); } if (algo >= 0) { wrap_copy_and_update(&msg_final.s, uncomp_body.s, uncomp_body.len, &msg_final.len); } else { wrap_copy_and_update(&msg_final.s, msg->eoh, strlen(msg->eoh), &msg_final.len); } /* new buffer because msg_final(out_buf) will * be overwritten at next iteration */ #ifdef DYN_BUF new_buf = pkg_malloc(msg_final.len+1); if (new_buf == NULL) { LM_ERR("no more pkg mem\n"); return -1; } #else new_buf = msg->buf; #endif memcpy(new_buf, msg_final.s, msg_final.len); new_buf[msg_final.len] = '\0'; struct sip_msg tmp; memcpy(&tmp, msg, sizeof(struct sip_msg)); /*reset dst_uri and path_vec to avoid free*/ if (msg->dst_uri.s != NULL) { msg->dst_uri.s = NULL; msg->dst_uri.len = 0; } if (msg->path_vec.s != NULL) { msg->path_vec.s = NULL; msg->path_vec.len = 0; } free_sip_msg(msg); memset(msg, 0, sizeof(struct sip_msg)); /* restore msg fields */ msg->id = tmp.id; msg->rcv = tmp.rcv; msg->set_global_address = tmp.set_global_address; msg->set_global_port = tmp.set_global_port; msg->flags = tmp.flags; msg->msg_flags = tmp.msg_flags; msg->hash_index = tmp.hash_index; msg->force_send_socket = tmp.force_send_socket; msg->dst_uri = tmp.dst_uri; msg->path_vec = tmp.path_vec; /* set the new ones */ msg->buf = new_buf; msg->len = msg_final.len; /* reparse the message */ if (parse_msg(msg->buf, msg->len, msg) != 0) LM_ERR("parse_msg failed\n"); return 1; }
//用户消息 bool CPlazaViewItem::OnSocketMainUser(CMD_Command Command, void * pBuffer, WORD wDataSize) { ASSERT(Command.wMainCmdID == MDM_GP_USER); switch(Command.wSubCmdID) { case SUB_GP_USER_DOWNLOAD_FACE: //下载头像 { //类型转换 CMD_GP_DownloadFaceSuccess *pDownloadFaceSuccess = (CMD_GP_DownloadFaceSuccess*)pBuffer; //参数验证 WORD wSendSize = WORD(pDownloadFaceSuccess->dwCurrentSize + sizeof(CMD_GP_DownloadFaceSuccess) - sizeof(pDownloadFaceSuccess->bFaceData)); ASSERT(wDataSize == wSendSize); if ( wDataSize != wSendSize ) return false; //第一次判断 if ( m_CustomFace.pFaceData == NULL ) { if ( m_CustomFace.pFaceData != NULL ) delete[] m_CustomFace.pFaceData; m_CustomFace.pFaceData = new BYTE[pDownloadFaceSuccess->dwToltalSize]; if ( m_CustomFace.pFaceData == NULL ) return true; m_CustomFace.dwFaceSize = pDownloadFaceSuccess->dwToltalSize; m_CustomFace.dwUserID = pDownloadFaceSuccess->dwUserID; } //拷贝数据 CopyMemory(m_CustomFace.pFaceData+m_CustomFace.dwCurrentSize, pDownloadFaceSuccess->bFaceData, pDownloadFaceSuccess->dwCurrentSize); m_CustomFace.dwCurrentSize += pDownloadFaceSuccess->dwCurrentSize; //下载完毕 if ( m_CustomFace.dwFaceSize == m_CustomFace.dwCurrentSize ) { tagDownloadInfo &DownloadInfo = m_DownloadInfoArrary[0]; //创建目录 CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace"); CreateDirectory(strDirName, NULL) ; //写入文件 CFile fileFace; CString strZipFileName, strBmpFileName; strZipFileName.Format(TEXT("\\%ld_%d.zip"), DownloadInfo.dwUserID, DownloadInfo.bFaceVer); strBmpFileName.Format(TEXT("\\%ld_%d.bmp"), DownloadInfo.dwUserID, DownloadInfo.bFaceVer); if ( fileFace.Open(strDirName + strZipFileName, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary) ) { fileFace.Write(m_CustomFace.pFaceData, m_CustomFace.dwFaceSize); fileFace.Close(); //解压文件 CUnzip oUnzip( strDirName + strZipFileName ); oUnzip.SwapSize( strDirName + strBmpFileName ); //删除文件 CFile::Remove(strDirName + strZipFileName); } //自己判断 tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData(); if ( GlobalUserData.dwUserID == DownloadInfo.dwUserID ) { //更新界面 ((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo(); } //重置变量 m_CustomFace.Clear(); //删除元素 m_DownloadInfoArrary.RemoveAt(0); //继续判断 if ( 0 < m_DownloadInfoArrary.GetCount() ) { //状态判断 if ( m_ClientSocket->GetSocketStatus() != SOCKET_STATUS_CONNECT ) { //链接网络 if ( ! ConnectServer() ) return true; //设置标识 m_bDownloadConnect = true; } //投递请求 tagDownloadInfo &DownloadInfo = m_DownloadInfoArrary[0]; CMD_GP_DownloadFace DownloadFace; DownloadFace.dwUserID = DownloadInfo.dwUserID; m_ClientSocket->SendData(MDM_GP_USER, SUB_GP_USER_DOWNLOAD_FACE, &DownloadFace, sizeof(DownloadFace)); } else { //关闭链接 m_ClientSocket->CloseSocket(); //设置变量 m_bStartDownloadFace=false; } } return true; } case SUB_GP_UPLOAD_FACE_RESULT: //上传结果 { ASSERT(sizeof(CMD_GP_UploadFaceResult) == wDataSize); if ( sizeof(CMD_GP_UploadFaceResult) != wDataSize) return true; //显示消息 CMD_GP_UploadFaceResult *pUploadFaceResult = (CMD_GP_UploadFaceResult*)pBuffer; ShowMessageBox(pUploadFaceResult->szDescribeMsg, MB_ICONINFORMATION); //成功判断 if ( pUploadFaceResult->bOperateSuccess ) { //头像目录 CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace"); CString strOldFileName; strOldFileName = TEXT("\\MyFace.bmp"); //命名文件 tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData(); CString strNemFileName; strNemFileName.Format(TEXT("\\%ld_%d.bmp"), GlobalUserData.dwUserID, pUploadFaceResult->dwFaceVer); //删除文件 try { CFile::Remove(strDirName + strNemFileName); } catch(...){} //删除文件 CString strOldFile; strOldFile.Format(TEXT("\\%ld_%ld.bmp"), GlobalUserData.dwUserID, GlobalUserData.dwCustomFaceVer); try { CFile::Remove(strDirName + strOldFile); } catch(...){} try { CFile::Rename(strDirName + strOldFileName, strDirName + strNemFileName); //设置版本号 GlobalUserData.dwCustomFaceVer = pUploadFaceResult->dwFaceVer; ASSERT(GlobalUserData.dwCustomFaceVer!=0); //投递消息 for ( INT nIndex = 0; nIndex < MAX_SERVER; nIndex++ ) { CRoomViewItem *pRoomViewItem = ((CGameFrame*)AfxGetMainWnd())->m_pRoomViewItem[nIndex]; if ( pRoomViewItem == NULL ) continue; pRoomViewItem->SendMessage(WM_UPDATE_FACE, GlobalUserData.dwCustomFaceVer, GlobalUserData.dwUserID); } } catch(...) { ShowMessageBox(TEXT("头像文件命名失败,需要重新登录才可以显示新头像!"), MB_ICONINFORMATION); } //更新界面 ((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo(); //设置界面 CGameFrame *pGameFrame = (CGameFrame *)AfxGetMainWnd() ; CDlgCustomFace &DlgCustomFace = pGameFrame->m_DlgCustomFace; if ( DlgCustomFace.m_hWnd != NULL && DlgCustomFace.IsWindowVisible() ) { DlgCustomFace.UpdateControls(); DlgCustomFace.SetFocus(); } } //关闭链接 m_ClientSocket->CloseSocket(); return true; } case SUB_GP_DELETE_FACE_RESULT: //删除结果 { ASSERT(sizeof(CMD_GP_DeleteFaceResult) == wDataSize); if ( sizeof(CMD_GP_DeleteFaceResult) != wDataSize) return true; //显示消息 CMD_GP_DeleteFaceResult *pDeleteFaceResult = (CMD_GP_DeleteFaceResult*)pBuffer; ShowMessageBox(pDeleteFaceResult->szDescribeMsg, MB_ICONINFORMATION); //成功判断 if ( pDeleteFaceResult->bOperateSuccess ) { //获取信息 tagGlobalUserData &GlobalUserData = g_GlobalUnits.GetGolbalUserData(); //文件目录 CString strDirName = CString(g_GlobalUnits.GetWorkDirectory()) + TEXT("\\CustomFace"); //文件名字 CString strFileName; strFileName.Format(TEXT("\\%ld_%d.bmp"), GlobalUserData.dwUserID, pDeleteFaceResult->dwFaceVer); //删除文件 try { CFile::Remove(strDirName + strFileName); } catch(...){} //更新界面 ((CGameFrame*)AfxGetMainWnd())->m_UserInfoView.UpdateUserInfo(); //设置界面 CGameFrame *pGameFrame = (CGameFrame *)AfxGetMainWnd() ; CDlgCustomFace &DlgCustomFace = pGameFrame->m_DlgCustomFace; if ( DlgCustomFace.m_hWnd != NULL && DlgCustomFace.IsWindowVisible() ) { DlgCustomFace.UpdateControls(); DlgCustomFace.SetFocus(); } //投递消息 for ( INT nIndex = 0; nIndex < MAX_SERVER; nIndex++ ) { CRoomViewItem *pRoomViewItem = ((CGameFrame*)AfxGetMainWnd())->m_pRoomViewItem[nIndex]; if ( pRoomViewItem == NULL ) continue; pRoomViewItem->SendMessage(WM_UPDATE_FACE, GlobalUserData.dwCustomFaceVer, GlobalUserData.dwUserID); } } //关闭链接 m_ClientSocket->CloseSocket(); return true; } case SUB_GP_MODIFY_INDIVIDUAL_RESULT: //修改结果 { return true; } default: { ASSERT(FALSE); return false; } } return true; }
FPNGTexture::FPNGTexture (FileReader &lump, int lumpnum, const FString &filename, int width, int height, BYTE depth, BYTE colortype, BYTE interlace) : FTexture(NULL, lumpnum), SourceFile(filename), Pixels(0), Spans(0), BitDepth(depth), ColorType(colortype), Interlace(interlace), HaveTrans(false), PaletteMap(0), PaletteSize(0), StartOfIDAT(0) { union { DWORD palette[256]; BYTE pngpal[256][3]; } p; BYTE trans[256]; DWORD len, id; int i; if (lumpnum == -1) fr = &lump; UseType = TEX_MiscPatch; LeftOffset = 0; TopOffset = 0; bMasked = false; Width = width; Height = height; CalcBitSize (); memset(trans, 255, 256); // Parse pre-IDAT chunks. I skip the CRCs. Is that bad? lump.Seek(33, SEEK_SET); lump.Read(&len, 4); lump.Read(&id, 4); while (id != MAKE_ID('I','D','A','T') && id != MAKE_ID('I','E','N','D')) { len = BigLong((unsigned int)len); switch (id) { default: lump.Seek (len, SEEK_CUR); break; case MAKE_ID('g','r','A','b'): // This is like GRAB found in an ILBM, except coordinates use 4 bytes { DWORD hotx, hoty; int ihotx, ihoty; lump.Read(&hotx, 4); lump.Read(&hoty, 4); ihotx = BigLong((int)hotx); ihoty = BigLong((int)hoty); if (ihotx < -32768 || ihotx > 32767) { Printf ("X-Offset for PNG texture %s is bad: %d (0x%08x)\n", Wads.GetLumpFullName (lumpnum), ihotx, ihotx); ihotx = 0; } if (ihoty < -32768 || ihoty > 32767) { Printf ("Y-Offset for PNG texture %s is bad: %d (0x%08x)\n", Wads.GetLumpFullName (lumpnum), ihoty, ihoty); ihoty = 0; } LeftOffset = ihotx; TopOffset = ihoty; } break; case MAKE_ID('P','L','T','E'): PaletteSize = MIN<int> (len / 3, 256); lump.Read (p.pngpal, PaletteSize * 3); if (PaletteSize * 3 != (int)len) { lump.Seek (len - PaletteSize * 3, SEEK_CUR); } for (i = PaletteSize - 1; i >= 0; --i) { p.palette[i] = MAKERGB(p.pngpal[i][0], p.pngpal[i][1], p.pngpal[i][2]); } break; case MAKE_ID('t','R','N','S'): lump.Read (trans, len); HaveTrans = true; // Save for colortype 2 NonPaletteTrans[0] = WORD(trans[0] * 256 + trans[1]); NonPaletteTrans[1] = WORD(trans[2] * 256 + trans[3]); NonPaletteTrans[2] = WORD(trans[4] * 256 + trans[5]); break; case MAKE_ID('a','l','P','h'): bAlphaTexture = true; bMasked = true; break; } lump.Seek(4, SEEK_CUR); // Skip CRC lump.Read(&len, 4); id = MAKE_ID('I','E','N','D'); lump.Read(&id, 4); } StartOfIDAT = lump.Tell() - 8; switch (colortype) { case 4: // Grayscale + Alpha bMasked = true; // intentional fall-through case 0: // Grayscale if (!bAlphaTexture) { if (colortype == 0 && HaveTrans && NonPaletteTrans[0] < 256) { bMasked = true; PaletteSize = 256; PaletteMap = new BYTE[256]; memcpy (PaletteMap, GrayMap, 256); PaletteMap[NonPaletteTrans[0]] = 0; } else { PaletteMap = GrayMap; } } break; case 3: // Paletted PaletteMap = new BYTE[PaletteSize]; GPalette.MakeRemap (p.palette, PaletteMap, trans, PaletteSize); for (i = 0; i < PaletteSize; ++i) { if (trans[i] == 0) { bMasked = true; PaletteMap[i] = 0; } } break; case 6: // RGB + Alpha bMasked = true; break; case 2: // RGB bMasked = HaveTrans; break; } }
CString DSoundBuf::Init( DSound &ds, DSoundBuf::hw hardware, int iChannels, int iSampleRate, int iSampleBits, int iWriteAhead ) { m_iChannels = iChannels; m_iSampleRate = iSampleRate; m_iSampleBits = iSampleBits; m_iWriteAhead = iWriteAhead * bytes_per_frame(); m_iVolume = -1; /* unset */ m_bBufferLocked = false; m_iWriteCursorPos = m_iWriteCursor = m_iBufferBytesFilled = 0; m_iExtraWriteahead = 0; m_iLastPosition = 0; m_bPlaying = false; ZERO( m_iLastCursors ); /* The size of the actual DSound buffer. This can be large; we generally * won't fill it completely. */ m_iBufferSize = 1024*64; m_iBufferSize = max( m_iBufferSize, m_iWriteAhead ); WAVEFORMATEX waveformat; memset( &waveformat, 0, sizeof(waveformat) ); waveformat.cbSize = 0; waveformat.wFormatTag = WAVE_FORMAT_PCM; bool NeedCtrlFrequency = false; if( m_iSampleRate == DYNAMIC_SAMPLERATE ) { m_iSampleRate = 44100; NeedCtrlFrequency = true; } int bytes = m_iSampleBits / 8; waveformat.wBitsPerSample = WORD(m_iSampleBits); waveformat.nChannels = WORD(m_iChannels); waveformat.nSamplesPerSec = DWORD(m_iSampleRate); waveformat.nBlockAlign = WORD(bytes*m_iChannels); waveformat.nAvgBytesPerSec = m_iSampleRate * bytes*m_iChannels; /* Try to create the secondary buffer */ DSBUFFERDESC format; memset( &format, 0, sizeof(format) ); format.dwSize = sizeof(format); #ifdef _XBOX format.dwFlags = 0; #else format.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLVOLUME; #endif #ifndef _XBOX /* Don't use DSBCAPS_STATIC. It's meant for static buffers, and we * only use streaming buffers. */ if( hardware == HW_HARDWARE ) format.dwFlags |= DSBCAPS_LOCHARDWARE; else format.dwFlags |= DSBCAPS_LOCSOFTWARE; #endif if( NeedCtrlFrequency ) format.dwFlags |= DSBCAPS_CTRLFREQUENCY; format.dwBufferBytes = m_iBufferSize; #ifndef _XBOX format.dwReserved = 0; #else DSMIXBINVOLUMEPAIR dsmbvp[8] = { { DSMIXBIN_FRONT_LEFT, DSBVOLUME_MAX }, // left channel { DSMIXBIN_FRONT_RIGHT, DSBVOLUME_MAX }, // right channel { DSMIXBIN_FRONT_CENTER, DSBVOLUME_MAX }, // left channel { DSMIXBIN_FRONT_CENTER, DSBVOLUME_MAX }, // right channel { DSMIXBIN_BACK_LEFT, DSBVOLUME_MAX }, // left channel { DSMIXBIN_BACK_RIGHT, DSBVOLUME_MAX }, // right channel { DSMIXBIN_LOW_FREQUENCY, DSBVOLUME_MAX }, // left channel { DSMIXBIN_LOW_FREQUENCY, DSBVOLUME_MAX } // right channel }; DSMIXBINS dsmb; dsmb.dwMixBinCount = 8; dsmb.lpMixBinVolumePairs = dsmbvp; format.lpMixBins = &dsmb; #endif format.lpwfxFormat = &waveformat; HRESULT hr = ds.GetDS()->CreateSoundBuffer( &format, &m_pBuffer, NULL ); if( FAILED(hr) ) return hr_ssprintf( hr, "CreateSoundBuffer failed" ); #ifndef _XBOX /* I'm not sure this should ever be needed, but ... */ DSBCAPS bcaps; bcaps.dwSize=sizeof(bcaps); hr = m_pBuffer->GetCaps( &bcaps ); if( FAILED(hr) ) return hr_ssprintf( hr, "m_pBuffer->GetCaps" ); if( int(bcaps.dwBufferBytes) != m_iBufferSize ) { LOG->Warn( "bcaps.dwBufferBytes (%i) != m_iBufferSize(%i); adjusting", bcaps.dwBufferBytes, m_iBufferSize ); m_iBufferSize = bcaps.dwBufferBytes; m_iWriteAhead = min( m_iWriteAhead, m_iBufferSize ); } if( !(bcaps.dwFlags & DSBCAPS_CTRLVOLUME) ) LOG->Warn( "Sound channel missing DSBCAPS_CTRLVOLUME" ); if( !(bcaps.dwFlags & DSBCAPS_GETCURRENTPOSITION2) ) LOG->Warn( "Sound channel missing DSBCAPS_GETCURRENTPOSITION2" ); DWORD got; hr = m_pBuffer->GetFormat( &waveformat, sizeof(waveformat), &got ); if( FAILED(hr) ) LOG->Warn( hr_ssprintf(hr, "GetFormat on secondary buffer") ); else if( (int) waveformat.nSamplesPerSec != m_iSampleRate ) LOG->Warn( "Secondary buffer set to %i instead of %i", waveformat.nSamplesPerSec, m_iSampleRate ); #endif m_pTempBuffer = new char[m_iBufferSize]; return ""; }
void fmpz_addmul_ui(fmpz_t f, const fmpz_t g, ulong x) { fmpz c1, r; c1 = *g; if ((x == 0) || (c1 == 0)) /* product is zero */ return; r = *f; if (r == 0) { fmpz_mul_ui(f, g, x); /* we are adding product to 0 */ return; } if (x == UWORD(1)) /* special case, adding g*1 to f */ { fmpz_add(f, f, g); return; } if (c1 == UWORD(1)) /* special case, adding 1*x to f */ { fmpz_add_ui(f, f, x); return; } if (!COEFF_IS_MPZ(c1)) /* c1 is small */ { mp_limb_t prod[2]; ulong uc1 = FLINT_ABS(c1); umul_ppmm(prod[1], prod[0], uc1, x); /* compute product */ if (prod[1] == 0) /* product fits in one limb */ { if (c1 < WORD(0)) fmpz_sub_ui(f, f, prod[0]); else fmpz_add_ui(f, f, prod[0]); return; } else if ((prod[1] == 1) && (!COEFF_IS_MPZ(r)) && ((r ^ c1) < WORD(0))) { /* only chance at cancellation is if product is one bit past a limb and res is small and opposite sign to this product */ ulong ur = FLINT_ABS(r); if (ur > prod[0]) /* cancellation will occur */ { fmpz_set_ui(f, prod[0] - ur); if (r > WORD(0)) fmpz_neg(f, f); return; } } /* in all remaining cases res is either big already, or will be big in the end */ { __mpz_struct * mpz_ptr = _fmpz_promote_val(f); mpz_t temp; /* set up a temporary, cheap mpz_t to contain prod */ temp->_mp_d = prod; temp->_mp_size = (c1 < WORD(0) ? -2 : 2); mpz_add(mpz_ptr, mpz_ptr, temp); _fmpz_demote_val(f); /* cancellation may have occurred */ } } else /* c1 is large */ { __mpz_struct * mpz_ptr = _fmpz_promote_val(f); flint_mpz_addmul_ui(mpz_ptr, COEFF_TO_PTR(c1), x); _fmpz_demote_val(f); /* cancellation may have occurred */ } }
bool CEditableObject::ExportLWO(LPCSTR fname) { CLWMemoryStream* F = xr_new<CLWMemoryStream>(); LPCSTRVec images; F->begin_save(); // tags F->open_chunk(ID_TAGS); for (SurfaceIt s_it=m_Surfaces.begin(); s_it!=m_Surfaces.end(); s_it++){ CSurface* S=*s_it; F->w_stringZ(S->_Name()); S->tag = s_it-m_Surfaces.begin(); if (FindLPCSTR(images,S->_Texture())<0) images.push_back(S->_Texture()); } F->close_chunk(); // images for (LPCSTRIt im_it=images.begin(); im_it!=images.end(); im_it++){ F->open_chunk(ID_CLIP); F->w_u32(im_it-images.begin()); F->open_subchunk(ID_STIL); F->w_stringZ(*im_it); F->close_subchunk(); F->close_chunk (); } // surfaces for (s_it=m_Surfaces.begin(); s_it!=m_Surfaces.end(); s_it++){ CSurface* S=*s_it; int im_idx=FindLPCSTR(images,S->_Texture()); R_ASSERT(im_idx>=0); LPCSTR vm_name=S->_VMap(); F->Wsurface(S->_Name(),S->m_Flags.is(CSurface::sf2Sided),(u16)im_idx,(vm_name&&vm_name[0])?vm_name:"Texture",S->_ShaderName(),S->_ShaderXRLCName()); } // meshes/layers for (EditMeshIt mesh_it=FirstMesh(); mesh_it!=LastMesh(); mesh_it++){ CEditableMesh* MESH=*mesh_it; F->w_layer(u16(mesh_it-FirstMesh()),MESH->Name().c_str()); // bounding box F->open_chunk(ID_BBOX); F->w_vector(MESH->m_Box.min); F->w_vector(MESH->m_Box.max); F->close_chunk(); // points F->open_chunk(ID_PNTS); for (u32 point_id=0; point_id<MESH->GetVCount(); point_id++) F->w_vector(MESH->GetVerts()[point_id]); F->close_chunk(); // polygons F->open_chunk(ID_POLS); F->w_u32(ID_FACE); for (u32 f_id=0; f_id<MESH->GetFCount(); f_id++) F->w_face3(MESH->GetFaces()[f_id].pv[0].pindex,MESH->GetFaces()[f_id].pv[1].pindex,MESH->GetFaces()[f_id].pv[2].pindex); F->close_chunk(); // surf<->face F->open_chunk(ID_PTAG); F->w_u32(ID_SURF); for (SurfFacesPairIt sf_it=MESH->m_SurfFaces.begin(); sf_it!=MESH->m_SurfFaces.end(); sf_it++){ IntVec& lst = sf_it->second; for (IntIt i_it=lst.begin(); i_it!=lst.end(); i_it++){ F->w_vx (*i_it); F->w_u16(WORD(sf_it->first->tag)); } } F->close_chunk(); // vmap&vmad for (VMapIt vm_it=MESH->m_VMaps.begin(); vm_it!=MESH->m_VMaps.end(); vm_it++){ st_VMap* vmap = *vm_it; F->begin_vmap(vmap->polymap, (vmap->type==vmtUV)?ID_TXUV:ID_WGHT, vmap->dim, vmap->name.c_str()); if (vmap->polymap) for (int k=0; k<vmap->size(); k++) F->w_vmad(vmap->vindices[k],vmap->pindices[k],vmap->dim,vmap->getVMdata(k)); else for (int k=0; k<vmap->size(); k++) F->w_vmap(vmap->vindices[k],vmap->dim,vmap->getVMdata(k)); F->end_vmap(); } } F->end_save(fname); xr_delete(F); return true; }
int main(void) { long l, len = 20; long runs[] = { 1000000, 1000000, 1000000, 1000000, 100000, 100000, 100000, 100000, 10000, 10000, 10000, 1000, 1000, 100, 100, 10, 10, 1, 1, 1 }; long N[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, WORD(1) << 11, WORD(1) << 12, WORD(1) << 13, WORD(1) << 14, WORD(1) << 15, WORD(1) << 16, WORD(1) << 17, WORD(1) << 18, WORD(1) << 19 }; long T[20] = {0}; flint_printf("Benchmark for p-adic Teichmuller.\n"); fflush(stdout); for (l = 0; l < len; l++) { FLINT_TEST_INIT(state); long n = N[l], r; clock_t c0, c1; long double cputime; fmpz_t p; padic_ctx_t ctx; padic_t c, z; fmpz_init_set_ui(p, 17); padic_ctx_init(ctx, p, n, n, PADIC_VAL_UNIT); padic_init(c); padic_init(z); fmpz_set_ui(padic_unit(c), 3); c0 = clock(); for (r = runs[l]; (r); r--) { padic_teichmuller(z, c, ctx); padic_zero(z); } c1 = clock(); cputime = (long double) (c1 - c0) / (long double) CLOCKS_PER_SEC; T[l] = (slong) (cputime * (1000000000 / runs[l])); flint_printf("%2ld, %4XYXYXYXY, %7ld, %wd\n", l, cputime, runs[l], T[l]); padic_clear(c); padic_clear(z); fmpz_clear(p); padic_ctx_clear(ctx); flint_randclear(state); } flint_printf("Output as a list:\n"); for (l = 0; l < len; l++) flint_printf("%wd, ", T[l]); flint_printf("\n"); }
mp_limb_t n_gcdinv(mp_limb_t * s, mp_limb_t x, mp_limb_t y) { mp_limb_signed_t v1 = UWORD(0); mp_limb_signed_t v2 = UWORD(1); mp_limb_signed_t t2; mp_limb_t u3, v3; mp_limb_t quot, rem; u3 = y, v3 = x; if (v3 > u3) { rem = u3; u3 = v3; t2 = v2; v2 = v1; v1 = t2; v3 = rem; } if ((mp_limb_signed_t) (y & x) < WORD(0)) /* y and x both have top bit set */ { quot = u3 - v3; t2 = v2; u3 = v3; v2 = v1 - v2; v1 = t2; v3 = quot; } while ((mp_limb_signed_t) (v3 << 1) < WORD(0)) /* second value has second msb set */ { quot = u3 - v3; if (quot < v3) { t2 = v2; u3 = v3; v2 = v1 - v2; v1 = t2; v3 = quot; } else if (quot < (v3 << 1)) { u3 = v3; t2 = v2; v2 = v1 - (v2 << 1); v1 = t2; v3 = quot - u3; } else { u3 = v3; t2 = v2; v2 = v1 - 3 * v2; v1 = t2; v3 = quot - (u3 << 1); } } while (v3) { if (u3 < (v3 << 2)) /* overflow not possible due to top 2 bits of v3 not being set */ { quot = u3 - v3; if (quot < v3) { t2 = v2; u3 = v3; v2 = v1 - v2; v1 = t2; v3 = quot; } else if (quot < (v3 << 1)) { u3 = v3; t2 = v2; v2 = v1 - (v2 << 1); v1 = t2; v3 = quot - u3; } else { u3 = v3; t2 = v2; v2 = v1 - 3 * v2; v1 = t2; v3 = quot - (u3 << 1); } } else { quot = u3 / v3; rem = u3 - v3 * quot; u3 = v3; t2 = v2; v2 = v1 - quot * v2; v1 = t2; v3 = rem; } } if (v1 < WORD(0)) v1 += y; (*s) = v1; return u3; }
bool CCDDAStream::Load(const WCHAR* fnw) { CString path(fnw); int iDriveLetter = path.Find(_T(":\\")) - 1; int iTrackIndex = CString(path).MakeLower().Find(_T(".cda")) - 1; if (iDriveLetter < 0 || iTrackIndex <= iDriveLetter) { return false; } CString drive = CString(_T("\\\\.\\")) + path[iDriveLetter] + _T(":"); while (iTrackIndex > 0 && _istdigit(path[iTrackIndex - 1])) { iTrackIndex--; } if (1 != _stscanf_s(path.Mid(iTrackIndex), _T("%d"), &iTrackIndex)) { return false; } if (m_hDrive != INVALID_HANDLE_VALUE) { CloseHandle(m_hDrive); m_hDrive = INVALID_HANDLE_VALUE; } m_hDrive = CreateFile(drive, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY | FILE_FLAG_SEQUENTIAL_SCAN, (HANDLE)nullptr); if (m_hDrive == INVALID_HANDLE_VALUE) { return false; } DWORD BytesReturned; if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC, nullptr, 0, &m_TOC, sizeof(m_TOC), &BytesReturned, 0) || !(m_TOC.FirstTrack <= iTrackIndex && iTrackIndex <= m_TOC.LastTrack)) { CloseHandle(m_hDrive); m_hDrive = INVALID_HANDLE_VALUE; return false; } // MMC-3 Draft Revision 10g: Table 222 - Q Sub-channel control field m_TOC.TrackData[iTrackIndex - 1].Control &= 5; if (!(m_TOC.TrackData[iTrackIndex - 1].Control == 0 || m_TOC.TrackData[iTrackIndex - 1].Control == 1)) { CloseHandle(m_hDrive); m_hDrive = INVALID_HANDLE_VALUE; return false; } if (m_TOC.TrackData[iTrackIndex - 1].Control & 8) { m_header.frm.pcm.wf.nChannels = 4; } m_nStartSector = MSF2UINT(m_TOC.TrackData[iTrackIndex - 1].Address) - 150; m_nStopSector = MSF2UINT(m_TOC.TrackData[iTrackIndex].Address) - 150; m_llLength = LONGLONG(m_nStopSector - m_nStartSector) * RAW_SECTOR_SIZE; m_header.riff.hdr.chunkSize = (long)(m_llLength + sizeof(m_header) - 8); m_header.data.hdr.chunkSize = (long)(m_llLength); // Detect DTS Music Disk m_bDTS = false; // DCA syncwords const DWORD DCA_MARKER_RAW_BE = 0x7FFE8001; const DWORD DCA_MARKER_RAW_LE = 0xFE7F0180; const DWORD DCA_MARKER_14B_BE = 0x1FFFE800; const DWORD DCA_MARKER_14B_LE = 0xFF1F00E8; UINT nMarkerFound = 0, nAttempt = 0; DWORD marker = DWORD_MAX; std::vector<BYTE> data(16384); DWORD dwSizeRead = 0; while (SUCCEEDED(Read(data.data(), (DWORD)data.size(), TRUE, &dwSizeRead)) && dwSizeRead && nAttempt < (4 + nMarkerFound)) { nAttempt++; for (DWORD i = 0; i < dwSizeRead; i++) { marker = (marker << 8) | data[i]; if ((marker == DCA_MARKER_14B_LE && (i < dwSizeRead - 2) && (data[i + 1] & 0xF0) == 0xF0 && data[i + 2] == 0x07) || (marker == DCA_MARKER_14B_BE && (i < dwSizeRead - 2) && data[i + 1] == 0x07 && (data[i + 2] & 0xF0) == 0xF0) || marker == DCA_MARKER_RAW_LE || marker == DCA_MARKER_RAW_BE) { nMarkerFound++; } } dwSizeRead = 0; if (nMarkerFound >= 4) { m_bDTS = true; break; } } SetPointer(0); CDROM_READ_TOC_EX TOCEx; ZeroMemory(&TOCEx, sizeof(TOCEx)); TOCEx.Format = CDROM_READ_TOC_EX_FORMAT_CDTEXT; BYTE header[4] = { 0 }; static_assert(sizeof(header) >= MINIMUM_CDROM_READ_TOC_EX_SIZE, "sizeof(header) must be greater or equal to MINIMUM_CDROM_READ_TOC_EX_SIZE"); if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC_EX, &TOCEx, sizeof(TOCEx), header, sizeof(header), &BytesReturned, 0)) { return true; } DWORD size = 2 + (WORD(header[0]) << 8) + header[1]; if (size <= 4) { // No cd-text information return true; } CAutoVectorPtr<BYTE> pCDTextData; if (!pCDTextData.Allocate(size)) { return true; } ZeroMemory(pCDTextData, size); if (!DeviceIoControl(m_hDrive, IOCTL_CDROM_READ_TOC_EX, &TOCEx, sizeof(TOCEx), pCDTextData, size, &BytesReturned, 0)) { return true; } size = (WORD)(BytesReturned - sizeof(CDROM_TOC_CD_TEXT_DATA)); CDROM_TOC_CD_TEXT_DATA_BLOCK* pDesc = ((CDROM_TOC_CD_TEXT_DATA*)(BYTE*)pCDTextData)->Descriptors; CStringArray str[16]; for (int i = 0; i < _countof(str); i++) { str[i].SetSize(1 + m_TOC.LastTrack); } CString last; for (int i = 0; size >= sizeof(CDROM_TOC_CD_TEXT_DATA_BLOCK); i++, size -= sizeof(CDROM_TOC_CD_TEXT_DATA_BLOCK), pDesc++) { if (pDesc->TrackNumber > m_TOC.LastTrack) { continue; } const int lenU = _countof(pDesc->Text); const int lenW = _countof(pDesc->WText); CString text = !pDesc->Unicode ? CString(CStringA((CHAR*)pDesc->Text, lenU)) : CString(CStringW((WCHAR*)pDesc->WText, lenW)); int tlen = text.GetLength(); CString tmp = (tlen < 12 - 1) ? (!pDesc->Unicode ? CString(CStringA((CHAR*)pDesc->Text + tlen + 1, lenU - (tlen + 1))) : CString(CStringW((WCHAR*)pDesc->WText + tlen + 1, lenW - (tlen + 1)))) : _T(""); if (pDesc->PackType < 0x80 || pDesc->PackType >= 0x80 + 0x10) { continue; } pDesc->PackType -= 0x80; if (pDesc->CharacterPosition == 0) { str[pDesc->PackType][pDesc->TrackNumber] = text; } else { // pDesc->CharacterPosition <= 0xf since CharacterPosition is a 4-bit field if (pDesc->CharacterPosition < 0xf && !last.IsEmpty()) { str[pDesc->PackType][pDesc->TrackNumber] = last + text; } else { str[pDesc->PackType][pDesc->TrackNumber] += text; } } last = tmp; } m_discTitle = str[0][0]; m_trackTitle = str[0][iTrackIndex]; m_discArtist = str[1][0]; m_trackArtist = str[1][iTrackIndex]; return true; }
int main(void) { int i; FLINT_TEST_INIT(state); flint_printf("reconstruct_fmpz_2...."); fflush(stdout); for (i = 0; i < 10000; i++) { int result; int modresult; int special_case; fmpq_t x, y; fmpz_t mod, res, N, D, t; mpz_t tmp; fmpq_init(x); fmpq_init(y); fmpz_init(mod); fmpz_init(res); fmpz_init(N); fmpz_init(D); fmpz_init(t); mpz_init(tmp); fmpq_randtest(x, state, 100); fmpz_abs(N, fmpq_numref(x)); fmpz_set(D, fmpq_denref(x)); /* Randomly generate larger bounds */ if (n_randint(state, 2)) { fmpz_randtest_not_zero(t, state, 100); fmpz_abs(t, t); fmpz_mul(N, N, t); } if (n_randint(state, 2)) { fmpz_randtest_not_zero(t, state, 100); fmpz_abs(t, t); fmpz_mul(D, D, t); } fmpz_mul(mod, N, D); fmpz_mul_ui(mod, mod, UWORD(2)); /* Next prime greater than or equal */ fmpz_get_mpz(tmp, mod); flint_mpz_sub_ui(tmp, tmp, UWORD(1)); mpz_nextprime(tmp, tmp); fmpz_set_mpz(mod, tmp); modresult = fmpq_mod_fmpz(res, x, mod); result = fmpq_reconstruct_fmpz_2(y, res, mod, N, D); /* Special case: both 1 and -1 have residue 1 mod 2. There's probably no particular reason to disallow this. */ special_case = (fmpz_cmp_ui(mod, UWORD(2)) == 0 && fmpz_get_si(&x->num) == WORD(-1) && fmpz_cmp_ui(&x->den, UWORD(1)) == 0); if (special_case) { if (!modresult || !result || !fmpz_is_one(&y->num) || !fmpz_is_one(&y->den)) { flint_printf("FAIL: special case: -1 mod 2\n"); abort(); } } else if (!modresult || !result || !fmpq_equal(x, y)) { flint_printf("FAIL: reconstruction failed\n"); flint_printf("input = "); fmpq_print(x); flint_printf("\nmodulus = "); fmpz_print(mod); flint_printf("\nresidue = "); fmpz_print(res); flint_printf("\nreconstructed = "); fmpq_print(y); flint_printf("\nfmpq_mod_fmpz return value = %d", modresult); flint_printf("\nfmpq_reconstruct_fmpz return value = %d", result); flint_printf("\n"); abort(); } fmpq_clear(x); fmpq_clear(y); fmpz_clear(mod); fmpz_clear(res); fmpz_clear(N); fmpz_clear(D); fmpz_clear(t); mpz_clear(tmp); } FLINT_TEST_CLEANUP(state); flint_printf("PASS\n"); return 0; }
//下载头像 bool CDataBaseSink::OnRequestDownloadFace(WORD wRequestID, DWORD dwContextID, VOID * pData, WORD wDataSize) { //校验参数 ASSERT(wDataSize == sizeof(DBR_GP_DownloadCustomFace)); if ( wDataSize != sizeof(DBR_GP_DownloadCustomFace)) return false; //类型转换 DBR_GP_DownloadCustomFace *pDownloadCustomFace = (DBR_GP_DownloadCustomFace*)pData; LONG lReturnValue=-1; long lSize=0; bool bRet = false; try { lReturnValue=SPDownloadFace(pDownloadCustomFace->dwUserID); //读取数据 if ( lReturnValue==0 ) { DWORD dwImageSize=0; dwImageSize=m_AccountsDBAide.GetValue_DWORD(TEXT("ImgSize")); //读取数据 IDataBase * pIDataBase=m_AccountsDBModule.GetInterface(); _variant_t vtFld; pIDataBase->GetRecordsetValue(TEXT("CustomFaceImage"), vtFld); BYTE * pcbBuf=NULL; SafeArrayAccessData(vtFld.parray,(LPVOID *)&pcbBuf); //投递请求 DBR_GP_DownloadFaceSuccess DownloadFaceSuccess; ZeroMemory(&DownloadFaceSuccess, sizeof(DownloadFaceSuccess)); DownloadFaceSuccess.dwToltalSize = dwImageSize; DownloadFaceSuccess.dwUserID = pDownloadCustomFace->dwUserID; DWORD dwSendSize = 0; while( dwSendSize <dwImageSize ) { //设置数据 if ( 1024 < dwImageSize - dwSendSize ) DownloadFaceSuccess.dwCurrentSize = 1024; else DownloadFaceSuccess.dwCurrentSize = dwImageSize - dwSendSize ; CopyMemory(DownloadFaceSuccess.bFaceData, pcbBuf+dwSendSize, DownloadFaceSuccess.dwCurrentSize); //投递消息 WORD wPostSize = WORD(sizeof(DownloadFaceSuccess)-sizeof(DownloadFaceSuccess.bFaceData)+DownloadFaceSuccess.dwCurrentSize); m_pIDataBaseEngineEvent->OnEventDataBaseResult(DBR_GP_DOWNLOADFACE_SUCCESS, dwContextID, &DownloadFaceSuccess, wPostSize); //递增变量 dwSendSize += DownloadFaceSuccess.dwCurrentSize; } //释放资源 SafeArrayUnaccessData(vtFld.parray); } } catch (IDataBaseException * pIException) { //错误信息 LPCTSTR pszDescribe=pIException->GetExceptionDescribe(); CTraceService::TraceString(pszDescribe,TraceLevel_Exception); } return true; }
ObjectLocation::ObjectLocation( void ) { keyID = INVALID_KEY; carouselID = DWORD(-1); moduleID = WORD(-1); }
bool cSmartCardVideoGuard2::Init(void) { static const unsigned char vg2Hist[] = { 'i',0xff,'J','P' }; if(atr->histLen<4 || memcmp(&atr->hist[3],vg2Hist,4)) { PRINTF(L_SC_INIT,"doesn't look like a VideoGuard2 card"); return false; } infoStr.Begin(); infoStr.Strcat("VideoGuard2 smartcard\n"); snprintf(idStr,sizeof(idStr),"%s (%c%c.%d)",SC_NAME,atr->hist[10],atr->hist[11],atr->hist[12]); ResetIdSet(); delete cmdList; cmdList=0; static unsigned char ins7401[] = { 0xD0,0x74,0x01,0x00,0x00 }; int l; if((l=ReadCmdLen(ins7401))<0) { PRINTF(L_SC_ERROR,"bogus answer. Now try delayed mode"); NewCardConfig(&cardCfgDelay); if((l=ReadCmdLen(ins7401))<0) return false; } ins7401[4]=l; unsigned char buff[256]; if(!IsoRead(ins7401,buff) || !Status()) { PRINTF(L_SC_ERROR,"failed to read cmd list"); return false; } cmdList=new CmdTable(buff,l); static const unsigned char ins7416[5] = { 0xD0,0x74,0x16,0x00,0x00 }; if(DoCmd(ins7416)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd 7416 failed"); return false; } static const unsigned char ins36[5] = { 0xD0,0x36,0x00,0x00,0x00 }; bool boxidOK=false; if((l=DoCmd(ins36,0,buff))>0 && Status()) for(int i=0; i<l ;i++) { if(buff[i]==0x00 && buff[i+1]==0xF3) { memcpy(&boxID,&buff[i+2],sizeof(boxID)); boxidOK=true; break; } } if(!boxidOK) { cSmartCardDataVideoGuard2 cd(dtBoxId); cSmartCardDataVideoGuard2 *entry=(cSmartCardDataVideoGuard2 *)smartcards.FindCardData(&cd); if(entry) { memcpy(&boxID,entry->boxid,sizeof(boxID)); boxidOK=true; } } if(!boxidOK) { PRINTF(L_SC_ERROR,"no boxID available"); return false; } static const unsigned char ins4C[5] = { 0xD0,0x4C,0x00,0x00,0x00 }; static unsigned char payload4C[9] = { 0,0,0,0, 3,0,0,2,4 }; memcpy(payload4C,boxID,4); if(DoCmd(ins4C,payload4C)<0 || !Status()) { PRINTF(L_SC_ERROR,"sending boxid failed"); return false; } static const unsigned char ins58[5] = { 0xD0,0x58,0x00,0x00,0x00 }; if(DoCmd(ins58,0,buff)<0 || !Status()) { PRINTF(L_SC_ERROR,"failed to read card details"); return false; } unsigned int c=WORD(buff,0x1D,0xFFFF); if(c!=CAID) CaidsChanged(); CAID=c; memcpy(&cardID,&buff[8],4); memcpy(&groupID,&buff[8],4); groupID[3]=0; SetCard(new cCardNDS(cardID)); AddProv(new cProviderNDS(groupID)); char str[20], str2[20]; infoStr.Printf("Cardtype: %c%c.%d\n" "BoxID %s Caid %04x CardID %s\n", atr->hist[10],atr->hist[11],atr->hist[12],HexStr(str,boxID,4),CAID,HexStr(str2,cardID,4)); PRINTF(L_SC_INIT,"cardtype: %c%c.%d boxID %s caid %04x cardID %s",atr->hist[10],atr->hist[11],atr->hist[12],HexStr(str,boxID,4),CAID,HexStr(str2,cardID,4)); cSmartCardDataVideoGuard2 cd(dtSeed); cSmartCardDataVideoGuard2 *entry=(cSmartCardDataVideoGuard2 *)smartcards.FindCardData(&cd); if(!entry) { PRINTF(L_SC_ERROR,"no NDS seed available"); return false; } state.SetSeed(entry->seed0,entry->seed1); unsigned char tbuff[64]; state.GetCamKey(tbuff); static const unsigned char insB4[5] = { 0xD0,0xB4,0x00,0x00,0x00 }; if(DoCmd(insB4,tbuff)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd D0B4 failed"); return false; } static const unsigned char insBC[5] = { 0xD0,0xBC,0x00,0x00,0x00 }; if(DoCmd(insBC)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd D0BC failed"); return false; } static const unsigned char insBE[5] = { 0xD3,0xBE,0x00,0x00,0x00 }; if(DoCmd(insBE)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd D3BE failed"); return false; } static const unsigned char ins58a[5] = { 0xD1,0x58,0x00,0x00,0x00 }; if(DoCmd(ins58a)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd D158 failed"); return false; } static const unsigned char ins4Ca[5] = { 0xD1,0x4C,0x00,0x00,0x00 }; if(DoCmd(ins4Ca,payload4C)<0 || !Status()) { PRINTF(L_SC_ERROR,"cmd D14C failed"); return false; } ReadTiers(); return true; }
HRESULT Grid::VRestore(Scene * pScene) { // Call the base class's restore SceneNode::VRestore(pScene); LPDIRECT3DDEVICE9 pDevice = pScene->m_pDevice; if( FAILED( D3DXCreateTextureFromFile( pDevice, const_cast<TCHAR *>(m_textureFile), &m_pTexture ) ) ) return E_FAIL; // Create the vertex buffer - we'll need enough verts // to populate the grid. If we want a 2x2 grid, we'll // need 3x3 set of verts. m_numVerts = (m_gridSize+1)*(m_gridSize+1); if( FAILED( pDevice->CreateVertexBuffer( m_numVerts*sizeof(COLORED_TEXTURED_VERTEX), D3DUSAGE_WRITEONLY, D3DFVF_COLORED_TEXTURED_VERTEX, D3DPOOL_MANAGED, &m_pVerts, NULL ) ) ) { return E_FAIL; } // Fill the vertex buffer. We are setting the tu and tv texture // coordinates, which range from 0.0 to 1.0 COLORED_TEXTURED_VERTEX* pVertices; if( FAILED( m_pVerts->Lock( 0, 0, (void**)&pVertices, 0 ) ) ) return E_FAIL; for( DWORD j=0; j<(m_gridSize+1); j++ ) { for (DWORD i=0; i<(m_gridSize+1); i++) { // Which vertex are we setting? int index = i + (j * (m_gridSize+1) ); COLORED_TEXTURED_VERTEX *vert = &pVertices[index]; // Default position of the grid is at the origin, flat on // the XZ plane. float x = (float)i; float y = (float)j; vert->position = ( x * D3DXVECTOR3(1,0,0) ) + ( y * D3DXVECTOR3(0,0,1) ); vert->color = m_color; // The texture coordinates are set to x,y to make the // texture tile along with units - 1.0, 2.0, 3.0, etc. vert->tu = x; vert->tv = y; } } m_pVerts->Unlock(); // The number of indicies equals the number of polygons times 3 // since there are 3 indicies per polygon. Each grid square contains // two polygons. The indicies are 16 bit, since our grids won't // be that big! m_numPolys = m_gridSize*m_gridSize*2; if( FAILED( pDevice->CreateIndexBuffer(sizeof(WORD) * m_numPolys * 3, D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_pIndices, NULL ) ) ) { return E_FAIL; } WORD *pIndices; if( FAILED( m_pIndices->Lock( 0, 0, (void**)&pIndices, 0 ) ) ) return E_FAIL; // Loop through the grid squares and calc the values // of each index. Each grid square has two triangles: // // A - B // | / | // C - D for( DWORD j=0; j<m_gridSize; j++ ) { for (DWORD i=0; i<m_gridSize; i++) { // Triangle #1 ACB *(pIndices) = WORD(i + (j*(m_gridSize+1))); *(pIndices+1) = WORD(i + ((j+1)*(m_gridSize+1))); *(pIndices+2) = WORD((i+1) + (j*(m_gridSize+1))); // Triangle #2 BCD *(pIndices+3) = WORD((i+1) + (j*(m_gridSize+1))); *(pIndices+4) = WORD(i + ((j+1)*(m_gridSize+1))); *(pIndices+5) = WORD((i+1) + ((j+1)*(m_gridSize+1))); pIndices+=6; } } m_pIndices->Unlock(); return S_OK; }
void xlog(int fd, int controller) { int i, n, code, fin; struct isdn_diagnostic_request req; u_int8_t data[DIAG_SIZE]; u_int8_t rc; printf("xlog:\n"); memset(&req, 0, sizeof(req)); req.controller = controller; req.cmd = LOG; req.out_param_len = DIAG_SIZE; req.out_param = &data; for (fin = 0; !fin; ) { if (ioctl(fd, I4B_ACTIVE_DIAGNOSTIC, &req) == -1) { perror("ioctl(I4B_ACTIVE_DIAGNOSTIC)"); fin = 1; break; } rc = data[OFF_LOG_RC]; if (rc == NO_EVENT) { fin = 1; printf("No log event\n"); break; } if (rc == MORE_EVENTS) { printf("More events...(0x%02x)\n", rc); fin = 0; } else if (rc == OK) { printf("Last event...(0x%02x)\n", rc); fin = 1; } else { printf("error: unknown rc = 0x%02x\n", rc); fin = 1; break; } /* print timestamp */ printf("%5d:%04d:%03d - ", WORD(data,OFF_LOG_TIMEH), WORD(data,OFF_LOG_TIMES), data[OFF_LOG_TIMEL2]*20 + data[OFF_LOG_TIMEL1]); code = data[OFF_LOG_CODE]; switch (code) { case 1: n = WORD(data, OFF_PAR_L1_LEN); printf("B-X(%03d) ",n); for (i=0; i<n && i<30; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 2: n = WORD(data, OFF_PAR_L1_LEN); printf("B-R(%03d) ", n); for (i=0; i<n && i<30; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 3: n = WORD(data, OFF_PAR_L1_LEN); printf("D-X(%03d) ",n); for (i=0; i<n && i<38; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 4: n = WORD(data, OFF_PAR_L1_LEN); printf("D-R(%03d) ",n); for (i=0; i<n && i<38; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 5: n = WORD(data, OFF_PAR_L2_LEN); printf("SIG-EVENT(%03d)%04X - ", n, WORD(data, OFF_PAR_L2_CODE)); for (i=0; i<n && i<28; i++) printf("%02X ", data[OFF_PAR_L2_I+i]); if (n>i) printf(" ..."); break; case 6: code = WORD(data, OFF_PAR_L2_CODE); if (code && code <= 10) printf("%s IND",ll_name[code-1]); else printf("UNKNOWN LL IND"); break; case 7: code = WORD(data, OFF_PAR_L2_CODE); if (code && code <= 10) printf("%s REQ",ll_name[code-1]); else printf("UNKNOWN LL REQ"); break; case 8: n = WORD(data, OFF_PAR_L2_LEN); printf("DEBUG%04X - ",WORD(data, OFF_PAR_L2_CODE)); for (i=0; i<n && i<38; i++) printf("%02X ", data[OFF_PAR_L2_I+i]); if (n>i) printf(" ..."); break; case 9: printf("MDL-ERROR(%s)",&data[OFF_PAR_TEXT]); break; case 10: printf("UTASK->PC(%02X)",WORD(data, OFF_PAR_L2_CODE)); break; case 11: printf("PC->UTASK(%02X)",WORD(data, OFF_PAR_L2_CODE)); break; case 12: n = WORD(data, OFF_PAR_L1_LEN); printf("X-X(%03d) ",n); for (i=0; i<n && i<30; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 13: n = WORD(data, OFF_PAR_L1_LEN); printf("X-R(%03d) ",n); for (i=0; i<n && i<30; i++) printf("%02X ", data[OFF_PAR_L1_I+i]); if (n>i) printf(" ..."); break; case 14: code = WORD(data, OFF_PAR_L2_CODE)-1; if ((code &0x0f)<=10) printf("%s IND",ns_name[code &0x0f]); else printf("UNKNOWN NS IND"); break; case 15: code = WORD(data, OFF_PAR_L2_CODE)-1; if ((code & 0x0f)<=10) printf("%s REQ",ns_name[code &0x0f]); else printf("UNKNOWN NS REQ"); break; case 16: printf("TASK %02i: %s", WORD(data, OFF_PAR_L2_CODE), &data[OFF_PAR_L2_I]); break; case 18: code = WORD(data, OFF_PAR_L2_CODE); printf("IO-REQ %02x",code); break; case 19: code = WORD(data, OFF_PAR_L2_CODE); printf("IO-CON %02x",code); break; default: printf("unknown event code = %d\n", code); break; } printf("\n"); } printf("\n"); }
void Object::writeToFile(FILE *fp, const FBMatrix &tm, const FBMatrix &pivotTm, const std::vector<int> &usedMaterials, bool optimizeVcache, bool factorPivot) const { std::vector<int> materials = getMaterialIndices(); /* // Common data FBMatrix relativeTransform = transform;// * parentTm.GetInverse(); Vector position = convert(relativeTransform.GetTranslation()); Rotation rotation = convert(relativeTransform.GetRotation()); Vector scale = convert(relativeTransform.GetScale()); FBMatrix inversePivot = pivotTm; //pivotTm.GetInverse(); */ Vector position = convert(tm.GetTranslation()); Rotation rotation = convert(tm.GetRotation()); Vector scale = convert(tm.GetScale()); for(unsigned int i = 0; i < materials.size(); ++i) { ++actualObjectAmount; // ToDo: generate some fancy names for splitted objects fwrite(name.c_str(), 1, name.size() + 1, fp); fwrite(parentName.c_str(), 1, parentName.size() + 1, fp); short int materialIndex = -1; for(unsigned int j = 0; j < usedMaterials.size(); ++j) { if(usedMaterials[j] == materials[i]) { materialIndex = static_cast<short int> (j); break; } } fwrite(&materialIndex, sizeof(short int), 1, fp); // Material index fwrite(&position, sizeof(float), 3, fp); // position fwrite(&rotation, sizeof(float), 4, fp); // rotation fwrite(&scale, sizeof(float), 3, fp); // scale char noCollision = 0; char noRender = 0; char isLightObject = 0; if(!cameraVisibility) noRender = 1; if(!collisionVisibility) noCollision = 1; if(lightObject) isLightObject = 1; fwrite(&noCollision, sizeof(char), 1, fp); // no_collision fwrite(&noRender, sizeof(char), 1, fp); // no_render fwrite(&isLightObject, sizeof(char), 1, fp); // lightobject // For this material std::vector<Face> tempFaces; std::vector<Vertex> tempVertices; char hasWeights = 0; // Build faces for(unsigned int j = 0; j < faces.size(); ++j) { if(faces[j].getMaterialId() == materials[i]) tempFaces.push_back(faces[j]); } std::vector<int> newVertexIndex(vertices.size()); std::hash_set<int> tempVertexIndices; for(unsigned int j = 0; j < tempFaces.size(); ++j) for(unsigned int k = 0; k < 3; ++k) { int index = tempFaces[j].getVertexIndex(k); assert(index >= 0 && index < int(vertices.size())); if(tempVertexIndices.find(index) == tempVertexIndices.end()) { tempVertexIndices.insert(index); if(vertices[index].hasBoneWeights() == true) hasWeights = 1; newVertexIndex[index] = tempVertices.size(); tempVertices.push_back(vertices[index]); } } for(unsigned int j = 0; j < tempFaces.size(); ++j) for(unsigned int k = 0; k < 3; ++k) { // Grab index and convert it to temp mesh vertex buffer int vertexIndex = tempFaces[j].getVertexIndex(k); int newIndex = newVertexIndex[vertexIndex]; assert(newIndex >= 0 && newIndex < int(tempVertices.size())); tempFaces[j].setVertexIndex(k, newIndex); } Lod lod(tempVertices, tempFaces, optimizeVcache); //if(generateLods) // lod.generateLods(lodDetail); const std::vector<Vertex> &lodVertices = lod.getVertices(); const std::vector<Face> &lodFaces = lod.getFaceBuffer(0); int vertexAmountInt = lodVertices.size(); WORD vertexAmount = static_cast<WORD> (lodVertices.size()); WORD faceAmount = static_cast<WORD> (lodFaces.size()); char hasLods = 0; //generateLods; fwrite(&vertexAmount, sizeof(WORD), 1, fp); // vertex count fwrite(&faceAmount, sizeof(WORD), 1, fp); // face count fwrite(&hasLods, sizeof(char), 1, fp); // lod info fwrite(&hasWeights, sizeof(char), 1, fp); // vertex weights // Vertex data for(int j = 0; j < vertexAmount; ++j) { FBVector positionTmp = lodVertices[j].getPosition(); Vector normal = convert(lodVertices[j].getNormal()); Vector2D uv = convert(lodVertices[j].getUv()); Vector2D uv2 = convert(lodVertices[j].getUv2()); if(factorPivot) pivotTm.TransformVector(positionTmp); Vector position = convert(positionTmp); fwrite(&position, sizeof(float), 3, fp); // position fwrite(&normal, sizeof(float), 3, fp); // normal fwrite(&uv, sizeof(float), 2, fp); // texture coordinates fwrite(&uv2, sizeof(float), 2, fp); // texture coordinates } // Face data for(int j = 0; int(j) < lod.getFaceBufferCount(); ++j) { const std::vector<Face> &lodFaces = lod.getFaceBuffer(j); WORD faceCount = lodFaces.size(); if(j > 0) { fwrite(&faceCount, sizeof(WORD), 1, fp); } for(unsigned int i = 0; i < faceAmount; ++i) for(unsigned int k = 0; k < 3; ++k) { const Face &face = lodFaces[i]; WORD vertexIndex = WORD(face.getVertexIndex(k)); int a = face.getVertexIndex(k); int b = int(lodVertices.size()); assert(face.getVertexIndex(k) < int(lodVertices.size())); assert(vertexIndex >= 0 && vertexIndex < vertexAmount); WORD index = vertexIndex; fwrite(&index, sizeof(WORD), 1, fp); } } // Weight data (if has) if(hasWeights == 1) { static const int MAX_WEIGHTS = 2; for(unsigned int j = 0; j < lodVertices.size(); ++j) { int indices[MAX_WEIGHTS] = { -1 }; signed char weights[MAX_WEIGHTS] = { 0 }; for(int k = 0; k < 2; ++k) { indices[k] = lodVertices[j].getBoneIndex(k); float weight = lodVertices[j].getBoneWeight(k); weights[k] = static_cast<signed char> (100.f * weight + .5f); } // Indices for(int k = 0; k < 2; ++k) fwrite(&indices[k], sizeof(int), 1, fp); // Weights for(int k = 0; k < 2; ++k) fwrite(&weights[k], sizeof(signed char), 1, fp); } } } }
void CChildView::OnPaint() { CPaintDC dcPaint( this ); CExtPaintManager::stat_ExcludeChildAreas( dcPaint.GetSafeHdc(), GetSafeHwnd() ); CExtMemoryDC dc( &dcPaint ); CGdiObject * pOld0, * pOld1; CExtWndShadow _shadow; WORD _PatternBits0[8],_PatternBits1[8]; for( INT iPatternLine=0; iPatternLine < 8; iPatternLine++ ) { _PatternBits0[iPatternLine] = ( iPatternLine & 1 ) ? WORD(0xFFFF) : WORD( ~ ( 5<<iPatternLine ) ) ; _PatternBits1[iPatternLine] = ( iPatternLine & 1 ) ? WORD(0xFFFF) : WORD( ~ ( 1<<(8-iPatternLine) ) ) ; } CBitmap bmpPattern0,bmpPattern1; CBrush brPattern0,brPattern1; VERIFY( bmpPattern0.CreateBitmap(8,8,1,1,_PatternBits0) ); VERIFY( bmpPattern1.CreateBitmap(8,8,1,1,_PatternBits1) ); VERIFY( brPattern0.CreatePatternBrush(&bmpPattern0) ); VERIFY( brPattern1.CreatePatternBrush(&bmpPattern1) ); CRect rcPattern0(10,10,180,150), rcPattern1(40,30,80,200); dc.FillRect(rcPattern0,&brPattern0); _shadow.Paint( dc, rcPattern0, CRect(0,0,0,0), CRect(0,0,0,0), CExtWndShadow::DEF_SHADOW_SIZE, CExtWndShadow::DEF_BRIGHTNESS_MIN, CExtWndShadow::DEF_BRIGHTNESS_MAX, false ); pOld0 = dc.SelectStockObject( NULL_BRUSH ); pOld1 = dc.SelectStockObject( BLACK_PEN ); dc.Rectangle( rcPattern0 ); if( pOld0 != NULL ) dc.SelectObject( pOld0 ); if( pOld1 != NULL ) dc.SelectObject( pOld1 ); dc.FillRect(rcPattern1,&brPattern1); _shadow.Paint( dc, rcPattern1, CRect(0,0,0,0), CRect(0,0,0,0), CExtWndShadow::DEF_SHADOW_SIZE, CExtWndShadow::DEF_BRIGHTNESS_MIN, CExtWndShadow::DEF_BRIGHTNESS_MAX, false ); pOld0 = dc.SelectStockObject( NULL_BRUSH ); pOld1 = dc.SelectStockObject( BLACK_PEN ); dc.Rectangle( rcPattern1 ); if( pOld0 != NULL ) dc.SelectObject( pOld0 ); if( pOld1 != NULL ) dc.SelectObject( pOld1 ); CRect rc0(20,50,160,80); CRect rc1(160,50,210,80); CRect rc2(rc0.left,rc0.top,rc1.right,rc1.bottom); COLORREF clrLeft = RGB(0,255,0); COLORREF clrMiddle = RGB(255,255,0); COLORREF clrRight = RGB(255,0,0); CExtPaintManager::stat_PaintGradientRect( dc, rc0, clrLeft, clrMiddle ); CExtPaintManager::stat_PaintGradientRect( dc, rc1, clrMiddle,clrRight ); _shadow.Paint( dc, rc2, CRect(0,0,0,0), CRect(0,0,0,0), CExtWndShadow::DEF_SHADOW_SIZE, CExtWndShadow::DEF_BRIGHTNESS_MIN, CExtWndShadow::DEF_BRIGHTNESS_MAX, false ); pOld0 = dc.SelectStockObject( NULL_BRUSH ); pOld1 = dc.SelectStockObject( BLACK_PEN ); dc.Rectangle(rc2); if( pOld0 != NULL ) dc.SelectObject( pOld0 ); if( pOld1 != NULL ) dc.SelectObject( pOld1 ); CRect rc3(120,40,150,80); CRect rc4(120,80,150,160); CRect rc5(rc3.left,rc3.top,rc4.right,rc4.bottom); COLORREF clrUpper = RGB(255,0,255); COLORREF clrMiddleV = RGB(255,255,255); COLORREF clrLower = RGB(0,0,255); CExtPaintManager::stat_PaintGradientRect( dc, rc3, clrMiddleV, clrUpper, TRUE ); CExtPaintManager::stat_PaintGradientRect( dc, rc4, clrLower, clrMiddleV, TRUE ); _shadow.Paint( dc, rc5, CRect(0,0,0,0), CRect(0,0,0,0), CExtWndShadow::DEF_SHADOW_SIZE, CExtWndShadow::DEF_BRIGHTNESS_MIN, CExtWndShadow::DEF_BRIGHTNESS_MAX, false ); pOld0 = dc.SelectStockObject( NULL_BRUSH ); pOld1 = dc.SelectStockObject( BLACK_PEN ); dc.Rectangle(rc5); if( pOld0 != NULL ) dc.SelectObject( pOld0 ); if( pOld1 != NULL ) dc.SelectObject( pOld1 ); }
void CResourceVersionInfo::ExportToStream(GrowBuf &strm, int Index) { DWORD v; WORD wSize; int p, p1; strm.resize(0); SaveVersionHeader(strm, 0, sizeof (VS_FIXEDFILEINFO), 0, L"VS_VERSION_INFO", &m_FixedInfo); DefineList *pChildStrings = m_ChildStringLists.get_strings(Index); if ( pChildStrings->getnum() > 0 ) { GrowBuf stringInfoStream; int codepage = m_ChildStringLists.get_codepage(Index); LANGID langid = m_ChildStringLists.get_lang(Index); wchar_t Buff[16]; _snwprintf(Buff, COUNTOF(Buff), L"%04x%04x", langid, codepage); SaveVersionHeader(stringInfoStream, 0, 0, 0, Buff, &ZEROS); for ( int i = 0; i < pChildStrings->getnum(); i++ ) { PadStream (stringInfoStream); WCToUTF16LEHlpr cnvName, cnvValue; if (!cnvName.Create(pChildStrings->getname(i), codepage)) throw std::runtime_error("Unicode conversion failed"); if (!cnvValue.Create(pChildStrings->getvalue(i), codepage)) throw std::runtime_error("Unicode conversion failed"); p = stringInfoStream.getlen(); SaveVersionHeaderUTF16LE(stringInfoStream, 0, WORD(StrLenUTF16(cnvValue.Get()) + 1), 1, cnvName.Get(), (void*)cnvValue.Get()); cnvName.Destroy(), cnvValue.Destroy(); wSize = WORD(stringInfoStream.getlen() - p); *(WORD*)((PBYTE)stringInfoStream.get()+p)=wSize; } wSize = WORD(stringInfoStream.getlen()); *(WORD*)((PBYTE)stringInfoStream.get())=wSize; PadStream (strm); p = strm.getlen(); SaveVersionHeader(strm, 0, 0, 0, L"StringFileInfo", &ZEROS); strm.add (stringInfoStream.get(), stringInfoStream.getlen()); wSize = WORD(strm.getlen() - p); *(WORD*)((PBYTE)strm.get()+p)=wSize; } // Show all languages avaiable using Var-Translations if ( m_ChildStringLists.getnum() > 0 ) { PadStream (strm); p = strm.getlen(); SaveVersionHeader(strm, 0, 0, 0, L"VarFileInfo", &ZEROS); PadStream (strm); p1 = strm.getlen(); SaveVersionHeader(strm, 0, 0, 0, L"Translation", &ZEROS); // First add selected code language translation v = MAKELONG(m_ChildStringLists.get_lang(Index), m_ChildStringLists.get_codepage(Index)); strm.add (&v, sizeof (v)); for ( int k =0; k < m_ChildStringLists.getnum(); k++ ) { if ( k != Index ) { v = MAKELONG(m_ChildStringLists.get_lang(k), m_ChildStringLists.get_codepage(k)); strm.add (&v, sizeof (v)); } } wSize = WORD(strm.getlen() - p1); *(WORD*)((PBYTE)strm.get()+p1)=wSize; wSize = WORD(sizeof (int) * m_ChildStringLists.getnum()); p1+=sizeof(WORD); *(WORD*)((PBYTE)strm.get()+p1)=wSize; wSize = WORD(strm.getlen() - p); *(WORD*)((PBYTE)strm.get()+p)=wSize; } wSize = WORD(strm.getlen()); *(WORD*)((PBYTE)strm.get())=wSize; }
void cDialogueList::ParsingLine(DWORD dwId, LPCTSTR buf) { DWORD dwColor = m_dwDefaultColor; WORD wLine = WORD(mMessageMap[dwId].size()); char wBuff[512] = {0}; int nCut = 0; int nStrLen = 0; #ifdef _TL_LOCAL_ BYTE brk[512]; int nBrkNum = 0; int nTextExtent = 0; #endif while( *buf ) // 버퍼의 정보가 유효하면, while문을 돌린다. { if( *buf == '$' ) // 버퍼가 '$'와 같으면, { if( nStrLen != 0 ) // 문자열 길이가 0과 같지 않으면, { AddLine( dwId, wBuff, dwColor, wLine, emLink_Null ); ZeroMemory( wBuff, sizeof(wBuff)); nStrLen = 0; } buf += 2; // 버퍼 포인터를 2증가한다. if( *buf == 's' || *buf == 'S' ) // 버퍼의 글자가 s또는 S이면, { dwColor = m_dwStressColor; // 색상을 스트레스 색상으로 세팅한다. } else // 그렇지 않을 경우, { dwColor = m_dwDefaultColor; // 일반 색상으로 세팅한다. } ++buf; // 버퍼 포인터를 증가한다. continue; // while 계속 진행. } #ifdef _TL_LOCAL_ //for WB //--- wBuff[nStrLen] = *buf; if( IsDBCSLeadByte( *buf ) ) { ++buf; ++nStrLen; ++nCut; wBuff[nStrLen] = *buf; } ++buf; ++nStrLen; ++nCut; nTextExtent = CFONT_OBJ->GetTextExtentEx( 0, wBuff, nCut ); if( nTextExtent > NPCDIALOG_TEXTWIDTH ) { nBrkNum = g_TBreak.FindThaiWordBreak( wBuff, nStrLen, brk, 512, FTWB_SEPARATESYMBOL ); if( nBrkNum > 1 ) { buf -= brk[nBrkNum-1]; wBuff[nStrLen-brk[nBrkNum-1]] = 0; } else { wBuff[nStrLen] = 0; } AddLine( dwId, wBuff, dwColor, wLine, emLink_Null ); memset( wBuff, 0, 512 ); nStrLen = 0; nCut = 0; ++wLine; if( *buf == ' ' ) { ++buf; } } //--- #else wBuff[nStrLen] = *buf; // 임시 버퍼의 문자열 길이의 위치에 버퍼의 값을 세팅한다. if( IsDBCSLeadByte( *buf ) ) // 버퍼의 값이 한글 바이트의 첫 바이트라면, { ++buf; // 버퍼 포인터를 증가한다. ++nStrLen; // 문자열 길이를 증가한다. ++nCut; // 컷팅 길이를 증가한다. wBuff[nStrLen] = *buf; // 임시 버퍼의 문자열 길이에 버퍼의 값을 세팅한다. } ++nCut; // 컷팅 정보를 증가한다. ++buf; // 버퍼 포인터를 증가한다. ++nStrLen; // 문자열 길이를 증가한다. // 091202 ShinJS --- NPC Script Dialog 의 대화 List Dialog의 Text Width와 문자열의 Width를 비교한다. cNpcScriptDialog* pNpcScriptDlg = GAMEIN->GetNpcScriptDialog(); WORD wListFontIdx = (pNpcScriptDlg != NULL ? pNpcScriptDlg->GetConversationListFontIdx() : 0); LONG textExtent = (pNpcScriptDlg != NULL ? CFONT_OBJ->GetTextExtentEx( wListFontIdx, wBuff, nCut ) : nCut); LONG listWidth = (pNpcScriptDlg != NULL ? pNpcScriptDlg->GetConversationListTextWidth() : NPCDIALOG_TEXTLEN); // 리스트의 문자열이 Text Width 보다 긴 경우 (NPC Script Dialog 를 못찾은 경우 기존방법 사용) if( textExtent > listWidth ) { if( nStrLen != 0 ) // 문자열 길이가 0이 아이념, { AddLine( dwId, wBuff, dwColor, wLine, emLink_Null ); // 라인을 추가한다. nStrLen = 0; ZeroMemory( wBuff, sizeof(wBuff)); } nCut = 0; ++wLine; } #endif } if( nStrLen != 0 ) // 문자열 길이가 0과 같지 않으면, { wBuff[nStrLen] = ' '; AddLine( dwId, wBuff, dwColor, wLine, emLink_Null ); } }
int main(void){ static char wave[DATALENGTH*2] ; char filename[16] = "temp.wav" ; char header[46] ; int i; clock_t start,finish ; FILE *fp ; OPLL *opll ; /* Create WAVE header */ chunkID(header,"RIFF") ; DWORD(header+4,DATALENGTH*2+36) ; chunkID(header+8,"WAVE") ; chunkID(header+12,"fmt ") ; DWORD(header+16,16) ; WORD(header+20,1) ; /* WAVE_FORMAT_PCM */ WORD(header+22,1) ; /* channel 1=mono,2=stereo */ DWORD(header+24,SAMPLERATE) ; /* samplesPerSec */ DWORD(header+28,2*SAMPLERATE) ; /* bytesPerSec */ WORD(header+32,2) ; /* blockSize */ WORD(header+34,16) ; /* bitsPerSample */ chunkID(header+36,"data") ; DWORD(header+40,2*DATALENGTH) ; opll = OPLL_new(MSX_CLK,SAMPLERATE) ; OPLL_reset(opll); OPLL_writeReg(opll,0x30,0x30) ; /* select PIANO Voice to ch1. */ OPLL_writeReg(opll,0x10,0x80) ; /* set F-Number(L). */ OPLL_writeReg(opll,0x20,0x15) ; /* set BLK & F-Number(H) and keyon. */ start = clock() ; i=0; for(i=0;i<DATALENGTH;i++) { WORD(wave+i*2,OPLL_calc(opll)); } finish = clock() ; OPLL_delete(opll) ; printf("It has been %f sec to calc %d waves.\n", (double)(finish-start)/CLOCKS_PER_SEC, DATALENGTH) ; printf("%f times faster than real YM2413.\n", ((double)DATALENGTH/SAMPLERATE)/((double)(finish-start)/CLOCKS_PER_SEC)) ; fp = fopen(filename,"wb") ; if(fp == NULL) return 1 ; fwrite(header,46,1,fp) ; fwrite(wave,DATALENGTH,2,fp) ; fclose(fp) ; printf("Wrote : %s\n",filename) ; return 0 ; }
void G_SerializeLevel (FArchive &arc, bool hubLoad) { int i = level.totaltime; Renderer->StartSerialize(arc); if (arc.IsLoading()) P_DestroyThinkers(hubLoad); gl_SerializeGlobals(arc); arc << level.flags << level.flags2 << level.fadeto << level.found_secrets << level.found_items << level.killed_monsters << level.gravity << level.aircontrol << level.teamdamage << level.maptime << i; // Hub transitions must keep the current total time if (!hubLoad) level.totaltime = i; arc << level.skytexture1 << level.skytexture2; if (arc.IsLoading()) { sky1texture = level.skytexture1; sky2texture = level.skytexture2; R_InitSkyMap(); } G_AirControlChanged (); BYTE t; // Does this level have scrollers? if (arc.IsStoring ()) { t = level.Scrolls ? 1 : 0; arc << t; } else { arc << t; if (level.Scrolls) { delete[] level.Scrolls; level.Scrolls = NULL; } if (t) { level.Scrolls = new FSectorScrollValues[numsectors]; memset (level.Scrolls, 0, sizeof(level.Scrolls)*numsectors); } } FBehavior::StaticSerializeModuleStates (arc); if (arc.IsLoading()) interpolator.ClearInterpolations(); P_SerializeWorld(arc); P_SerializeThinkers (arc, hubLoad); P_SerializeWorldActors(arc); // serializing actor pointers in the world data must be done after SerializeWorld has restored the entire sector state, otherwise LinkToWorld may fail. P_SerializePolyobjs (arc); P_SerializeSubsectors(arc); StatusBar->Serialize (arc); arc << level.total_monsters << level.total_items << level.total_secrets; // Does this level have custom translations? FRemapTable *trans; WORD w; if (arc.IsStoring ()) { for (unsigned int i = 0; i < translationtables[TRANSLATION_LevelScripted].Size(); ++i) { trans = translationtables[TRANSLATION_LevelScripted][i]; if (trans != NULL && !trans->IsIdentity()) { w = WORD(i); arc << w; trans->Serialize(arc); } } w = 0xffff; arc << w; } else { while (arc << w, w != 0xffff) { trans = translationtables[TRANSLATION_LevelScripted].GetVal(w); if (trans == NULL) { trans = new FRemapTable; translationtables[TRANSLATION_LevelScripted].SetVal(w, trans); } trans->Serialize(arc); } } // This must be saved, too, of course! FCanvasTextureInfo::Serialize (arc); AM_SerializeMarkers(arc); P_SerializePlayers (arc, hubLoad); P_SerializeSounds (arc); if (arc.IsLoading()) { for (i = 0; i < numsectors; i++) { P_Recalculate3DFloors(§ors[i]); } for (i = 0; i < MAXPLAYERS; ++i) { if (playeringame[i] && players[i].mo != NULL) { players[i].mo->SetupWeaponSlots(); } } } Renderer->EndSerialize(arc); }
static void _fmpz_mod_mat_det(fmpz_t rop, const fmpz *M, slong n, const fmpz_t pN) { fmpz *F; fmpz *a; fmpz *A; fmpz_t s; slong t, i, j, p, k; F = _fmpz_vec_init(n); a = _fmpz_vec_init((n-1) * n); A = _fmpz_vec_init(n); fmpz_init(s); fmpz_neg(F + 0, M + 0*n + 0); for (t = 1; t < n; t++) { for (i = 0; i <= t; i++) fmpz_set(a + 0*n + i, M + i*n + t); fmpz_set(A + 0, M + t*n + t); for (p = 1; p < t; p++) { for (i = 0; i <= t; i++) { fmpz_zero(s); for (j = 0; j <= t; j++) fmpz_addmul(s, M + i*n + j, a + (p-1)*n + j); fmpz_mod(a + p*n + i, s, pN); } fmpz_set(A + p, a + p*n + t); } fmpz_zero(s); for (j = 0; j <= t; j++) fmpz_addmul(s, M + t*n + j, a + (t-1)*n + j); fmpz_mod(A + t, s, pN); for (p = 0; p <= t; p++) { fmpz_sub(F + p, F + p, A + p); for (k = 0; k < p; k++) fmpz_submul(F + p, A + k, F + (p-k-1)); fmpz_mod(F + p, F + p, pN); } } /* Now [F{n-1}, F{n-2}, ..., F{0}, 1] is the characteristic polynomial of the matrix M. */ if (n % WORD(2) == 0) { fmpz_set(rop, F + (n-1)); } else { fmpz_neg(rop, F + (n-1)); fmpz_mod(rop, rop, pN); } _fmpz_vec_clear(F, n); _fmpz_vec_clear(a, (n-1)*n); _fmpz_vec_clear(A, n); fmpz_clear(s); }
/** * Handles the message sent for the creation of lockpicks in the world. * * This function is called whenever a lockpick should be created in the world for a client. * * @return cMessage - Returns a Create Object (0x0000F745) server message. */ cMessage cLockpicks::CreatePacket( ) { cMessage cmReturn; cItemModels *pcModel = cItemModels::FindModel( m_dwItemModelID ); cObject *pcObject = cWorldManager::FindObject( m_dwGUID ); if( pcModel ) { cmReturn << 0xF745L << m_dwGUID << BYTE(0x11); //0x11 is a constant cmReturn << pcModel->m_bPaletteChange << pcModel->m_bTextureChange << pcModel->m_bModelChange; // The Model Vectors if ( pcModel->m_bPaletteChange != 0) { for (int i = 0; i < pcModel->m_bPaletteChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorPal[i],sizeof(pcModel->m_vectorPal[i])); } } if (pcModel->m_bPaletteChange != 0) { //Cubem0j0: Test code for armor only. cmReturn << WORD( 0x0C50 ); } if ( pcModel->m_bTextureChange != 0) { for (int i = 0; i < pcModel->m_bTextureChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorTex[i],sizeof(pcModel->m_vectorTex[i])); } } if ( pcModel->m_bModelChange != 0) { for (int i = 0; i < pcModel->m_bModelChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorMod[i],sizeof(pcModel->m_vectorMod[i])); } } } cmReturn.pasteAlign(4); cmReturn << pcModel->m_dwFlags1 << 0x414L << 0x65L; // MASK 0x00008000 -- Location if ( !m_fIsOwned ) cmReturn.CannedData( (BYTE *)&m_Location, sizeof( cLocation ) ); // MASK 0x00000800 -- Sound Set DWORD dwSoundSet = 0x20000000L + pcModel->m_wSoundSet; cmReturn << dwSoundSet; // MASK 0x00001000 -- Particle Effects (unknown_blue) cmReturn << 0x34000000 + pcModel->m_dwUnknown_Blue; // MASK 0x00000001 -- ModelNumber DWORD dwModel = 0x02000000L + pcModel->m_dwModelNumber; cmReturn << dwModel; // SeaGreens WORD wNuminteracts = 0x0; WORD wNumbubbles = 0x0; WORD wNumJumps = 0x0; WORD wNumOverrides = 0x0; WORD wUnkFlag8 = 0x0; WORD wUnkFlag10 = 0x0; cmReturn << m_wPositionSequence << m_wNumAnims //wNuminteracts << wNumbubbles << wNumJumps << m_wNumPortals << m_wNumAnims << wNumOverrides << wUnkFlag8 << m_wNumLogins << wUnkFlag10; if(pcModel->m_dwContainerID != 0) { DWORD owned = pcModel->m_dwFlags2 & 0x00004000; cmReturn << owned; } else { cmReturn << pcModel->m_dwFlags2; // Object Flags } cmReturn << Name( ); // Object's Name cmReturn << pcModel->m_wModel; // Object's Model cmReturn << this->m_wIcon; // Object's Icon cmReturn << pcModel->m_dwObjectFlags1; // Object Flags cmReturn << pcModel->m_dwObjectFlags2; // Object Flags //Lockpicks flag2 - 00280c18 // Mask 0x0008 - Value if(pcModel->m_dwFlags2 & 0x00000008) { cmReturn << pcModel->m_dwValue; } // Mask 0x0010 dwUnknown_v2 if(pcModel->m_dwFlags2 & 0x00000010) cmReturn << DWORD(0x00200008); // Mask 0x80000 Usable on if(pcModel->m_dwFlags2 & 0x00080000) cmReturn << pcModel->m_dwUseableOn; // Mase 0x0400 Uses Remaining if(pcModel->m_dwFlags2 & 0x00000400) { cmReturn << pcModel->m_wUses; } // Mase 0x0800 Max # of uses if(pcModel->m_dwFlags2 & 0x00000800) { cmReturn << pcModel->m_wUseLimit; } // Mask 0x00200000 - Burden if(pcModel->m_dwFlags2 & 0x00200000) { cmReturn << pcModel->m_wBurden; } //Padding cmReturn << WORD(0x0000); return cmReturn; }
/** * Handles the message sent for the creation of a corpse in the world. * * This function is called whenever a corpse should be created in the world for a client. * @return cMessage - Returns a server message to the client. */ cMessage cCorpse::CreatePacket( ) { cMessage cmCreate; unsigned char bUnknown[] = { 0x00, 0x00, 0x3D, 0x00, 0x02, 0xF0, 0xB5, 0x02, 0x11, 0x00, 0x00, 0x00, }; cModels *pcMonster = cModels::FindModel(this->m_MonsterModelID); #ifdef _DEBUG cMasterServer::ServerMessage( ColorYellow,NULL,"m_dwModel = %d",this->m_MonsterModelID); #endif if(pcMonster) { cmCreate << 0xF745L << m_dwGUID << BYTE(0x11); //0x11 is a constant cmCreate << pcMonster->m_bPaletteChange << pcMonster->m_bTextureChange << pcMonster->m_bModelChange; // The Model Vectors if ( pcMonster->m_bPaletteChange != 0) { for (int i = 0; i < pcMonster->m_bPaletteChange; i++) { cmCreate.pasteData((UCHAR*)&pcMonster->m_vectorPal[i],sizeof(pcMonster->m_vectorPal[i])); } } if (pcMonster->m_bPaletteChange != 0) { cmCreate << WORD( pcMonster->m_wUnknown1 ); } if ( pcMonster->m_bTextureChange != 0) { for (int i = 0; i < pcMonster->m_bTextureChange; i++) { cmCreate.pasteData((UCHAR*)&pcMonster->m_vectorTex[i],sizeof(pcMonster->m_vectorTex[i])); } } if ( pcMonster->m_bModelChange != 0) { for (int i = 0; i < pcMonster->m_bModelChange; i++) { cmCreate.pasteData((UCHAR*)&pcMonster->m_vectorMod[i],sizeof(pcMonster->m_vectorMod[i])); } } } cmCreate.pasteAlign(4); DWORD dwFlags = 0x00019883L; cmCreate << dwFlags; cmCreate << WORD( 0x0414 ); cmCreate << WORD( 0x000C ); // MASK 0x00010000 unknown Bytes - Starting Animation cmCreate << 0x0CL; cmCreate.pasteData(bUnknown,sizeof(bUnknown)); cmCreate << 0x0L; // MASK 0x00008000 -- Location if ( !m_fIsOwned ) cmCreate.CannedData( (BYTE *)&m_Location, sizeof( cLocation ) ); // MASK 0x00000002 -- Animation Set DWORD dwAnimC = 0x09000000L + m_wAnimConfig; cmCreate << dwAnimC; // MASK 0x00000800 -- Sound Set DWORD dwSoundSet = 0x20000000L + m_wSoundSet; cmCreate << dwSoundSet; // MASK 0x00001000 -- Particle Effects (unknown_blue) cmCreate << 0x3400006EL;//0x00000000L; // MASK 0x00000001 -- ModelNumber DWORD dwModel = 0x02000000L + m_dwModel; cmCreate << dwModel; cmCreate << float(m_flScale); // SeaGreens WORD wNuminteracts = 0x0; WORD wNumbubbles = 0x0; WORD wNumJumps = 0x0; WORD wNumOverrides = 0x0; WORD wUnkFlag8 = 0x0; WORD wUnkFlag10 = 0x0; cmCreate << m_wPositionSequence << m_wNumAnims //wNuminteracts << wNumbubbles << wNumJumps << m_wNumPortals << m_wNumAnims << wNumOverrides << wUnkFlag8 << m_wNumLogins << wUnkFlag10; DWORD dwFlags2 = 0x00200036; cmCreate << dwFlags2 << m_strName.c_str( ) << WORD(m_wModel) << WORD(m_wIcon);//WORD( 0x019C ) << WORD( 0x1317 );;//WORD( 0x0116 ) << WORD( 0x1317 ); /* Category of object: 0x00000001 Melee Weapon 0x00000002 Armor 0x00000004 Clothing 0x00000008 Jewelry 0x00000010 Creature (Player/NPC/Monster) 0x00000020 Food 0x00000040 Pyreals 0x00000080 Miscellaneous 0x00000100 Missile Weapons/Ammunition 0x00000200 Containers 0x00000400 Wrapped Fletching Supplies, House Decorations 0x00000800 Gems, Pack dolls, Decorative Statues 0x00001000 Spell Components 0x00002000 Books, Parchment, Scrolls, Signs, Statues 0x00004000 Keys, Lockpicks 0x00008000 Casting Item (wand, orb, staff) 0x00010000 Portal 0x00020000 Lockable 0x00040000 Trade Notes 0x00080000 Mana Stones, Mana Charges 0x00100000 Services 0x00200000 unknown (no longer plants) 0x00400000 Cooking Ingredients and Supplies, Plants, Dye Pots 0x00800000 Loose Fletching Supplies 0x01000000 unknown 0x02000000 unknown 0x04000000 Alchemy Ingredients and Supplies, Oils, Dye Vials 0x08000000 unknown 0x10000000 Lifestone 0x20000000 Ust 0x40000000 Salvage 0x80000000 unknown */ DWORD dwObjectFlags1 = 0x0200L; cmCreate << dwObjectFlags1; /* Behavior of object: 0x00000001 can be opened (false if locked) 0x00000002 can be inscribed 0x00000004 cannot be picked up 0x00000008 is a player 0x00000010 is not an npc 0x00000020 unknown 0x00000040 unknown 0x00000080 cannot be selected 0x00000100 can be read 0x00000200 is a merchant 0x00000400 is a pk altar 0x00000800 is an npk altar 0x00001000 is a door 0x00002000 is a corpse 0x00004000 can be attuned to (lifestone) 0x00008000 adds to health, stamina or mana 0x00010000 is a healing kit 0x00020000 is a lockpick 0x00040000 is a portal 0x00800000 is a foci 0x04000000 has an extra flags DWORD */ DWORD dwObjectFlags2 = 0x2015L; cmCreate << dwObjectFlags2; /* Masked against dwFlags2 in reverse order: 0x00000002 - Item Slots 0x00000004 - Pack Slots 0x00000008 - Value 0x00000010 - Unknown1 0x00000020 - Approach Distance 0x00200000 - Burden */ cmCreate << BYTE (0x78); //78 is item slots. (120) cmCreate << BYTE (0x00); //00 is pack slots //cmCreate << DWORD (0x000009C4); //Value cmCreate << DWORD (0x00000030); //Unknown cmCreate << float(3.0); //Approach Distance. cmCreate << WORD (0x0000); //Burden return cmCreate; }
// [RH] Seperated out of R_InitSpriteDefs() static void R_InstallSprite (int num, spriteframewithrotate *sprtemp, int &maxframe) { int frame; int framestart; int rot; // int undefinedFix; if (maxframe == -1) { sprites[num].numframes = 0; return; } maxframe++; // [RH] If any frames are undefined, but there are some defined frames, map // them to the first defined frame. This is a fix for Doom Raider, which actually // worked with ZDoom 2.0.47, because of a bug here. It does not define frames A, // B, or C for the sprite PSBG, but because I had sprtemp[].rotate defined as a // bool, this code never detected that it was not actually present. After switching // to the unified texture system, this caused it to crash while loading the wad. // [RH] Let undefined frames actually be blank because LWM uses this in at least // one of her wads. // for (frame = 0; frame < maxframe && sprtemp[frame].rotate == -1; ++frame) // { } // // undefinedFix = frame; for (frame = 0; frame < maxframe; ++frame) { switch (sprtemp[frame].rotate) { case -1: // no rotations were found for that frame at all //I_FatalError ("R_InstallSprite: No patches found for %s frame %c", sprites[num].name, frame+'A'); break; case 0: // only the first rotation is needed for (rot = 1; rot < 16; ++rot) { sprtemp[frame].Texture[rot] = sprtemp[frame].Texture[0]; } // If the frame is flipped, they all should be if (sprtemp[frame].Flip & 1) { sprtemp[frame].Flip = 0xFFFF; } break; case 1: // must have all 8 frame pairs for (rot = 0; rot < 8; ++rot) { if (!sprtemp[frame].Texture[rot*2+1].isValid()) { sprtemp[frame].Texture[rot*2+1] = sprtemp[frame].Texture[rot*2]; if (sprtemp[frame].Flip & (1 << (rot*2))) { sprtemp[frame].Flip |= 1 << (rot*2+1); } } if (!sprtemp[frame].Texture[rot*2].isValid()) { sprtemp[frame].Texture[rot*2] = sprtemp[frame].Texture[rot*2+1]; if (sprtemp[frame].Flip & (1 << (rot*2+1))) { sprtemp[frame].Flip |= 1 << (rot*2); } } } for (rot = 0; rot < 16; ++rot) { if (!sprtemp[frame].Texture[rot].isValid()) I_FatalError ("R_InstallSprite: Sprite %s frame %c is missing rotations", sprites[num].name, frame+'A'); } break; } } for (frame = 0; frame < maxframe; ++frame) { if (sprtemp[frame].rotate == -1) { memset (&sprtemp[frame].Texture, 0, sizeof(sprtemp[0].Texture)); sprtemp[frame].Flip = 0; sprtemp[frame].rotate = 0; } } // allocate space for the frames present and copy sprtemp to it sprites[num].numframes = maxframe; sprites[num].spriteframes = WORD(framestart = SpriteFrames.Reserve (maxframe)); for (frame = 0; frame < maxframe; ++frame) { memcpy (SpriteFrames[framestart+frame].Texture, sprtemp[frame].Texture, sizeof(sprtemp[frame].Texture)); SpriteFrames[framestart+frame].Flip = sprtemp[frame].Flip; SpriteFrames[framestart+frame].Voxel = sprtemp[frame].Voxel; } // Let the textures know about the rotations for (frame = 0; frame < maxframe; ++frame) { if (sprtemp[frame].rotate == 1) { for (int rot = 0; rot < 16; ++rot) { TexMan[sprtemp[frame].Texture[rot]]->Rotations = framestart + frame; } } } }
static PCXHeader* ReadPCXHeader (FILE* F, const char* Name) /* Read a structured PCX header from the given file and return it */ { RawPCXHeader H; /* Allocate a new PCXHeader structure */ PCXHeader* P = NewPCXHeader (); /* Read the raw header */ ReadData (F, H, sizeof (H)); /* Convert the data into structured form */ P->Id = H[0]; P->FileVersion = H[1]; P->Compressed = H[2]; P->BPP = H[3]; P->XMin = WORD (H, 4); P->YMin = WORD (H, 6); P->XMax = WORD (H, 8); P->YMax = WORD (H, 10); P->XDPI = WORD (H, 12); P->YDPI = WORD (H, 14); P->Planes = H[65]; P->BytesPerPlane = WORD (H, 66); P->PalInfo = WORD (H, 68); P->ScreenWidth = WORD (H, 70); P->ScreenHeight = WORD (H, 72); P->Width = P->XMax - P->XMin + 1; P->Height = P->YMax - P->YMin + 1; /* Check the header data */ if (P->Id != PCX_MAGIC_ID || P->FileVersion == 1 || P->FileVersion > 5) { Error ("`%s' is not a PCX file", Name); } if (P->Compressed > 1) { Error ("Unsupported compression (%d) in PCX file `%s'", P->Compressed, Name); } /* We support: ** - one plane with either 1 or 8 bits per pixel ** - three planes with 8 bits per pixel ** - four planes with 8 bits per pixel (does this exist?) */ if (!((P->BPP == 1 && P->Planes == 1) || (P->BPP == 8 && (P->Planes == 1 || P->Planes == 3 || P->Planes == 4)))) { /* We could support others, but currently we don't */ Error ("Unsupported PCX format: %u planes, %u bpp in PCX file `%s'", P->Planes, P->BPP, Name); } if (P->PalInfo != 1 && P->PalInfo != 2) { Error ("Unsupported palette info (%u) in PCX file `%s'", P->PalInfo, Name); } if (!ValidBitmapSize (P->Width, P->Height)) { Error ("PCX file `%s' has an unsupported size (w=%u, h=%d)", Name, P->Width, P->Height); } /* Return the structured header */ return P; }
//--------------------------------------------------------------------------- bool TSTPort::Create(Str &ErrorText,Str &ErrorTitle,bool DoAlert) { Close(); bool Running=(runstate==RUNSTATE_RUNNING); LPPORTIOINFIRSTBYTEPROC FirstByteInProc=NULL; LPPORTIOOUTFINISHEDPROC LastByteOutProc=NULL; if (&MIDIPort==this){ FirstByteInProc=MidiInBufNotEmpty; }else if (&ParallelPort==this){ FirstByteInProc=ParallelInputNotify; LastByteOutProc=ParallelOutputNotify; }else if (&SerialPort==this){ FirstByteInProc=SerialInBufNotEmpty; } bool Error=0; switch (Type){ case PORTTYPE_FILE: f=fopen(File,"ab"); return true; case PORTTYPE_LOOP: LoopBuf=new CircularBuffer(PORT_LOOPBUFSIZE); return true; } #ifdef WIN32 EasyStr PortName=EasyStr("COM")+(COMNum+1); int AllowIn=true,AllowOut=true; switch (Type){ case PORTTYPE_MIDI: { bool MIDIOutErr=0,MIDIInErr=0; if (MIDIOutDevice>-2){ MIDI_Out=new TMIDIOut(MIDIOutDevice,WORD(Running ? MIDI_out_volume:0)); if (MIDI_Out->IsOpen()==0) MIDIOutErr=true; } if (MIDIInDevice>-1){ MIDI_In=new TMIDIIn(MIDIInDevice,Running,FirstByteInProc); if (MIDI_In->IsOpen()==0) MIDIInErr=true; } if (MIDIInErr && MIDIOutErr){ ErrorTitle=T("MIDI Errors"); ErrorText=T("MIDI Output Error")+"\n"+MIDI_Out->ErrorText+"\n\n"; ErrorText+=T("MIDI Input Error")+"\n"+MIDI_In->ErrorText; }else if (MIDIInErr){ ErrorTitle=T("MIDI Input Error"); ErrorText=MIDI_In->ErrorText; }else if (MIDIOutErr){ ErrorTitle=T("MIDI Output Error"); ErrorText=MIDI_Out->ErrorText; } if (MIDIOutErr){ delete MIDI_Out; MIDI_Out=NULL; } if (MIDIInErr){ delete MIDI_In; MIDI_In=NULL; } Error=(MIDIOutErr || MIDIInErr); break; } case PORTTYPE_PARALLEL: PortName=EasyStr("LPT")+(LPTNum+1); AllowIn=comline_allow_LPT_input; case PORTTYPE_COM: PCPort=new TPortIO(PortName,AllowIn,AllowOut); break; } #elif defined(UNIX) int PortIOType=GetPortIOType(Type); if (PortIOType>=0){ if (Type==PORTTYPE_LAN){ PCPort=new TPortIO(PortDev[PortIOType],true,0,PortIOType); PCPortIn=new TPortIO(LANPipeIn,0,true,PortIOType); }else{ PCPort=new TPortIO(PortDev[PortIOType],AllowIO[PortIOType][0],AllowIO[PortIOType][1],PortIOType); } } #endif if (PCPort){ if (PCPort->IsOpen()==0) Error=true; if (PCPortIn) if (PCPortIn->IsOpen()==0) Error=true; if (Error){ ErrorTitle=T("Port Error"); #ifdef WIN32 ErrorText=T("Could not open port ")+PortName+". "+ T("It may not exist or it could be in use by another program."); #else Str BadDev; ErrorText=""; if (PCPortIn){ if (PCPort->IsOpen()==0){ BadDev=PortDev[PortIOType]; }else{ BadDev=LANPipeIn; } }else if (AllowIO[PortIOType][0] || AllowIO[PortIOType][1]){ BadDev=PortDev[PortIOType]; } if (BadDev.NotEmpty()){ ErrorText=T("Could not open device")+" "+BadDev+"\n\n"+ T("It may not exist, it could be in use by another program or you may not have permission to access it."); } #endif delete PCPort;PCPort=NULL; if (PCPortIn) delete PCPortIn; PCPortIn=NULL; }else{ PCPort->lpInFirstByteProc=FirstByteInProc; PCPort->lpOutFinishedProc=LastByteOutProc; PCPort->OutPause=(Running==0); PCPort->InPause=(Running==0); if (PCPortIn){ PCPortIn->lpInFirstByteProc=FirstByteInProc; PCPortIn->InPause=(Running==0); } } } if (Running){ if (this==&ParallelPort){ UpdateCentronicsBusyBit(); }else if (this==&SerialPort){ SetDTR(psg_reg[PSGR_PORT_A] & BIT_4); SetRTS(psg_reg[PSGR_PORT_A] & BIT_3); } } if (DoAlert && Error && ErrorText.NotEmpty()){ Alert(ErrorText,ErrorTitle,MB_ICONEXCLAMATION | MB_OK); } CheckResetDisplay(); return Error==0; }
BOOL CreateNode(Fvector& vAt, vertex& N) { // *** Query and cache polygons for ray-casting Fvector PointUp; PointUp.set(vAt); PointUp.y += RCAST_Depth; SnapXZ (PointUp); Fvector PointDown; PointDown.set(vAt); PointDown.y -= RCAST_Depth; SnapXZ (PointDown); Fbox BB; BB.set (PointUp,PointUp); BB.grow(g_params.fPatchSize/2); // box 1 Fbox B2; B2.set (PointDown,PointDown); B2.grow(g_params.fPatchSize/2); // box 2 BB.merge(B2 ); BoxQuery(BB,false ); u32 dwCount = XRC.r_count(); if (dwCount==0) { // Log("chasm1"); return FALSE; // chasm? } // *** Transfer triangles and compute sector R_ASSERT(dwCount<RCAST_MaxTris); static svector<tri,RCAST_MaxTris> tris; tris.clear(); for (u32 i=0; i<dwCount; i++) { tri& D = tris.last(); CDB::RESULT &rp = XRC.r_begin()[i]; CDB::TRI& T = *(Level.get_tris()+rp.id); D.v[0].set (rp.verts[0]); D.v[1].set (rp.verts[1]); D.v[2].set (rp.verts[2]); D.sector = T.sector; D.N.mknormal(D.v[0],D.v[1],D.v[2]); if (D.N.y<=0) continue; tris.inc (); } if (tris.size()==0) { // Log("chasm2"); return FALSE; // chasm? } // *** Perform ray-casts and calculate sector WORD Sector = 0xfffe; // mark as first time static svector<Fvector,RCAST_Total> points; points.clear(); static svector<Fvector,RCAST_Total> normals; normals.clear(); Fvector P,D; D.set(0,-1,0); float coeff = 0.5f*g_params.fPatchSize/float(RCAST_Count); for (int x=-RCAST_Count; x<=RCAST_Count; x++) { P.x = vAt.x + coeff*float(x); for (int z=-RCAST_Count; z<=RCAST_Count; z++) { P.z = vAt.z + coeff*float(z); P.y = vAt.y + 10.f; float tri_min_range = flt_max; int tri_selected = -1; float range,u,v; for (i=0; i<u32(tris.size()); i++) { if (CDB::TestRayTri(P,D,tris[i].v,u,v,range,false)) { if (range<tri_min_range) { tri_min_range = range; tri_selected = i; } } } if (tri_selected>=0) { P.y -= tri_min_range; points.push_back(P); normals.push_back(tris[tri_selected].N); WORD TS = WORD(tris[tri_selected].sector); if (Sector==0xfffe) Sector = TS; else if (Sector!=TS) Sector=InvalidSector; } } } if (points.size()<3) { // Msg ("Failed to create node at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); return FALSE; } if (float(points.size())/float(RCAST_Total) < 0.7f) { // Msg ("Partial chasm at [%f,%f,%f].",vAt.x,vAt.y,vAt.z); return FALSE; } // *** Calc normal Fvector vNorm; vNorm.set(0,0,0); for (u32 n=0; n<normals.size(); n++) vNorm.add(normals[n]); vNorm.div(float(normals.size())); vNorm.normalize(); /* { // second algorithm (Magic) Fvector N,O; N.set(vNorm); O.set(points[0]); Mgc::OrthogonalPlaneFit( points.size(),(Mgc::Vector3*)points.begin(), *((Mgc::Vector3*)&O), *((Mgc::Vector3*)&N) ); if (N.y<0) N.invert(); N.normalize(); vNorm.lerp(vNorm,N,.3f); vNorm.normalize(); } */ // *** Align plane Fvector vOffs; vOffs.set(0,-1000,0); Fplane PL; PL.build(vOffs,vNorm); for (u32 p=0; p<points.size(); p++) { float dist = PL.classify(points[p]); if (dist>0) { vOffs = points[p]; PL.build(vOffs,vNorm); } } // *** Create node and register it N.Sector =Sector; // sector N.Plane.build (vOffs,vNorm); // build plane D.set (0,1,0); N.Plane.intersectRayPoint(PointDown,D,N.Pos); // "project" position // *** Validate results vNorm.set(0,1,0); if (vNorm.dotproduct(N.Plane.n)<_cos(deg2rad(60.f))) return FALSE; float y_old = vAt.y; float y_new = N.Pos.y; if (y_old>y_new) { // down if (y_old-y_new > g_params.fCanDOWN ) return FALSE; } else { // up if (y_new-y_old > g_params.fCanUP ) return FALSE; } // *** Validate plane { Fvector PLP; D.set(0,-1,0); int num_successed_rays = 0; for (int x=-RCAST_Count; x<=RCAST_Count; x++) { P.x = N.Pos.x + coeff*float(x); for (int z=-RCAST_Count; z<=RCAST_Count; z++) { P.z = N.Pos.z + coeff*float(z); P.y = N.Pos.y; N.Plane.intersectRayPoint(P,D,PLP); // "project" position P.y = PLP.y+RCAST_VALID*0.01f; float tri_min_range = flt_max; int tri_selected = -1; float range,u,v; for (i=0; i<float(tris.size()); i++) { if (CDB::TestRayTri(P,D,tris[i].v,u,v,range,false)) { if (range<tri_min_range) { tri_min_range = range; tri_selected = i; } } } if (tri_selected>=0) { if (tri_min_range<RCAST_VALID) num_successed_rays++; } } } float perc = float(num_successed_rays)/float(RCAST_Total); if (perc < 0.5f) { // Msg ("Floating node."); return FALSE; } } // *** Mask check // ??? return TRUE; }
/** * Handles the message sent for the creation of jewelry in a container. * * This function is called whenever jewelry should be created in the inventory of another object. * * @return cMessage - Returns a Create Object (0x0000F745) server message. */ cMessage cJewelry::CreatePacketContainer(DWORD Container, DWORD ItemModelID) { cMessage cmReturn; cItemModels *pcModel = cItemModels::FindModel( ItemModelID ); cObject *pcObject = cWorldManager::FindObject( m_dwGUID ); if( pcModel ) { cmReturn << 0xF745L << m_dwGUID << BYTE(0x11); //0x11 is a constant cmReturn << pcModel->m_bPaletteChange << pcModel->m_bTextureChange << pcModel->m_bModelChange; // The Model Vectors if ( pcModel->m_bPaletteChange != 0) { for (int i = 0; i < pcModel->m_bPaletteChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorPal[i],sizeof(pcModel->m_vectorPal[i])); } } if (pcModel->m_bPaletteChange != 0) { //Cubem0j0: Test code for armor only. cmReturn << WORD( pcModel->m_wUnknown_1 ); } if ( pcModel->m_bTextureChange != 0) { for (int i = 0; i < pcModel->m_bTextureChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorTex[i],sizeof(pcModel->m_vectorTex[i])); } } if ( pcModel->m_bModelChange != 0) { for (int i = 0; i < pcModel->m_bModelChange; i++) { cmReturn.pasteData((UCHAR*)&pcModel->m_vectorMod[i],sizeof(pcModel->m_vectorMod[i])); } } } cmReturn.pasteAlign(4); cmReturn << pcModel->m_dwFlags1 << 0x414L << 0x65L; // MASK 0x00000800 -- Sound Set DWORD dwSoundSet = 0x20000000L + pcModel->m_wSoundSet; cmReturn << dwSoundSet; // MASK 0x00001000 -- Particle Effects (unknown_blue) cmReturn << 0x34000000 + pcModel->m_dwUnknown_Blue; // MASK 0x00000001 -- ModelNumber DWORD dwModel = 0x02000000L + pcModel->m_dwModelNumber; cmReturn << dwModel; // MASK 0x00000080 -- Scale cmReturn << float(1.0); // SeaGreens WORD wNuminteracts = 0x0; WORD wNumbubbles = 0x0; WORD wNumJumps = 0x0; WORD wNumOverrides = 0x0; WORD wUnkFlag8 = 0x0; WORD wUnkFlag10 = 0x0; cmReturn << m_wPositionSequence << m_wNumAnims //wNuminteracts << wNumbubbles << wNumJumps << m_wNumPortals << m_wNumAnims << wNumOverrides << wUnkFlag8 << m_wNumLogins << wUnkFlag10; // Flags2 //DWORD dwFlags2 = 0x81214018; cmReturn << pcModel->m_dwFlags2; cmReturn << Name( ); // Object's Name cmReturn << pcModel->m_wModel; // Object's Model cmReturn << this->m_wIcon; // Object's Icon cmReturn << pcModel->m_dwObjectFlags1; // Object Flags cmReturn << pcModel->m_dwObjectFlags2; // Object Flags if(pcModel->m_dwFlags2 & 0x00000008) cmReturn << pcModel->m_dwValue; if(pcModel->m_dwFlags2 & 0x00000010) cmReturn << pcModel->m_dwUnknown_v2; if(pcModel->m_dwFlags2 & 0x00000080) cmReturn << pcModel->m_dwIconHighlight; if(pcModel->m_dwFlags2 & 0x00004000) cmReturn << Container; if(pcModel->m_dwFlags2 & 0x00010000) cmReturn << pcModel->m_dwEquipPossible; if(pcModel->m_dwFlags2 & 0x00200000) cmReturn << pcModel->m_wBurden; if(pcModel->m_dwFlags2 & 0x01000000) cmReturn << pcModel->m_wHooks; if(pcModel->m_dwFlags2 & 0x01000000) cmReturn << pcModel->m_fWorkmanship; if(pcModel->m_dwFlags2 & 0x80000000) cmReturn << pcModel->m_dwMaterialType; //cmReturn << WORD(0x0000); return cmReturn; }