blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
4df7d8354fd72496cac9a065951b9781ab4dca15
f9ed86de48cedc886178f9e8c7ee4fae816ed42d
/src/modifier.h
166787e14fcb392ed8316fdc62dd448373f75745
[ "MIT" ]
permissive
rehno-lindeque/Flower-of-Persia
bf78d144c8e60a6f30955f099fe76e4a694ec51a
b68af415a09b9048f8b8f4a4cdc0c65b46bcf6d2
refs/heads/master
2021-01-25T04:53:04.951376
2011-01-29T11:41:38
2011-01-29T11:41:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
150
h
#ifndef __MODIFIER_H__ #define __MODIFIER_H__ class Modifier { public: Vector3 apply(const Vector3& source); //returns a force }; #endif
[ [ [ 1, 10 ] ] ]
4bea6867da221fa1d6f3d14b1533cb1a2097c0fe
b12ad2200e97359ba5990010be345b974eec1f1c
/lib/perlclientapi.h
96bb4a100c08a450b89c07f514a6e6b7fb78bfd5
[]
no_license
gitpan/P4
f09fc02f300ba766736975c8b05aad35e9400abe
7aaf3a8a9ff3d51863fe1d31e3880eafcf54dcf7
refs/heads/master
2016-09-10T18:45:31.289861
2006-07-17T18:10:14
2014-10-26T13:35:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,045
h
/******************************************************************************* Copyright (c) 1997-2006, Perforce Software, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PERFORCE SOFTWARE, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ class ClientApi; class PerlClientUser; class PerlClientApi { public: PerlClientApi(); ~PerlClientApi(); SV * Connect(); SV * Disconnect(); SV * Dropped(); SV * Run( const char *cmd, int argc, char * const *argv ); void SetApiLevel( int level ); SV * SetCharset( const char *c ); void SetClient( const char *c ) { client->SetClient( c ); } void SetCwd( const char *c ) { client->SetCwd( c ); } void SetHost( const char *c ) { client->SetHost( c ); } void SetLanguage( const char *c ) { client->SetLanguage( c ); } void SetPassword( const char *c ) { client->SetPassword( c ); } void SetMaxResults( int v ) { maxResults = v; } void SetMaxScanRows( int v ) { maxScanRows = v; } void SetPort( const char *c ) { client->SetPort( c ); } void SetUser( const char *c ) { client->SetUser( c ); } void SetProg( const char *c ) { prog.Set( c ); } void SetInput( SV *i ); SV * GetCharset(); SV * GetClient(); SV * GetCwd(); SV * GetHost(); SV * GetLanguage(); SV * GetPassword(); SV * GetPort(); SV * GetUser(); // Base protocol ops void SetProtocol( const char *p, const char *v ); StrPtr * GetProtocol( const char *v ); // High-level protocol ops void Tagged(); void ParseForms(); int IsTagged(); int IsParseForms(); // // Handling command output // SV * MergeErrors( int merge = -1 ); SV * GetFirstOutput(); AV * GetOutput(); AV * GetWarnings(); AV * GetErrors(); I32 GetOutputCount(); I32 GetWarningCount(); I32 GetErrorCount(); // Spec parsing SV * ParseSpec( const char *type, const char *form ); SV * FormatSpec( const char *type, HV *hash ); // Debugging support void SetDebugLevel( int l ); int GetDebugLevel() { return debug; } int IsConnected() { return initCount; } // private: // Compatibility flags // enum { CPT_MERGED = 0x0001 }; // // Client mode settings // enum { PROTO_TAG = 0x01, PROTO_SPECSTRING = 0x02, MODE_PARSEFORMS = 0x03, PROTO_MASK = 0x0f }; StrPtr * FetchSpecDef( const char *type ); void RunCmd( const char *cmd, ClientUser *ui, int argc, char * const *argv ); private: ClientApi * client; PerlClientUser * ui; StrBufDict specDict; StrBuf prog; int server2; int mode; int initCount; int debug; int compatFlags; int maxResults; int maxScanRows; };
[ [ [ 1, 133 ] ] ]
f7280de356cd226faf7ffd502fd77b1f31a3dea0
93eac58e092f4e2a34034b8f14dcf847496d8a94
/ncl30-cpp/ncl30-generator/include/generables/RegionBaseGenerator.h
146b3d36c034f30fcc332e4258cf930b605752e7
[]
no_license
lince/ginga-srpp
f8154049c7e287573f10c472944315c1c7e9f378
5dce1f7cded43ef8486d2d1a71ab7878c8f120b4
refs/heads/master
2020-05-27T07:54:24.324156
2011-10-17T13:59:11
2011-10-17T13:59:11
2,576,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,756
h
/****************************************************************************** Este arquivo eh parte da implementacao do ambiente declarativo do middleware Ginga (Ginga-NCL). Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free Software Foundation. Este programa eh distribuido na expectativa de que seja util, porem, SEM NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do GNU versao 2 para mais detalhes. Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto com este programa; se nao, escreva para a Free Software Foundation, Inc., no endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA. Para maiores informacoes: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br ****************************************************************************** This file is part of the declarative environment of middleware Ginga (Ginga-NCL) Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License version 2 for more details. You should have received a copy of the GNU General Public License version 2 along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA For further information contact: [email protected] http://www.ncl.org.br http://www.ginga.org.br http://lince.dc.ufscar.br *******************************************************************************/ /** * @file RegionBaseGenerator.h * @author Caio Viel * @date 29-01-10 */ #ifndef REGIONBASEGENERATOR_H_ #define REGIONBASEGENERATOR_H_ #include <vector> #include "ncl/layout/RegionBase.h" using namespace ::br::pucrio::telemidia::ncl::layout; #include "Generable.h" #include "LayoutRegionGenerator.h" namespace br { namespace ufscar { namespace lince { namespace ncl { namespace generator { class RegionBaseGenerator: public RegionBase { public: /** * Gera o código XML da entidade NCL RegionBase. * @return Uma string contendo o código NCL gerado. */ string generateCode (); }; } } } } } #endif
[ [ [ 1, 86 ] ] ]
57dcfe34bbc4412c48b6ca291642ca9790eaaed3
84ca111e2739d866aac5f779824afd1f0bcf2842
/InfoPanel.cpp
792dc351a526fa25f3efd44948e7804c1f7795b9
[]
no_license
radtek/photoupload
0193989c016d35de774315acc562598ddb1ccf40
0291fd9fbed728aa07e1bebb578da58906fa0b8e
refs/heads/master
2020-09-27T13:13:47.706353
2009-09-24T22:20:11
2009-09-24T22:20:11
226,525,120
1
0
null
2019-12-07T14:15:57
2019-12-07T14:15:56
null
UTF-8
C++
false
false
6,770
cpp
#include "StdAfx.h" #include ".\infopanel.h" #include ".\style.h" #include ".\resource.h" #include ".\defines.h" using namespace Gdiplus; //CRect buttonRect(20,200,100+20,200+26+30); CRect buttonRect(20,200,100+20,200+26); #define IDSC_BUTTON1 1001 #define IDSC_BUTTON2 1002 CInfoPanel::CInfoPanel(void) : immuneMouseDown(false) { volatileMode = true; } CInfoPanel::~CInfoPanel(void) { } int CInfoPanel::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; Bitmap icon(AfxGetInstanceHandle(), MAKEINTRESOURCEW(IDB_ICON_INFO)); HBITMAP hicon; icon.GetHBITMAP(Color(0xF1,0xEC,0xE6), &hicon); staticIcon.Create(NULL, WS_CHILD|WS_VISIBLE|SS_BITMAP, CRect(10,20,25,25), this); staticIcon.SetBitmap(hicon); button.Create(_T(""), 0, buttonRect,this, IDSC_BUTTON2); return 0; } void CInfoPanel::OnDestroy() { CWnd::OnDestroy(); SAFE_DELETEOBJECT_NOL(staticIcon.GetBitmap()); } BEGIN_MESSAGE_MAP(CInfoPanel, CWnd) ON_WM_PAINT() ON_WM_CREATE() ON_WM_NCLBUTTONUP() ON_WM_LBUTTONUP() ON_WM_DESTROY() ON_WM_LBUTTONDOWN() ON_COMMAND(IDSC_BUTTON1, OnButton1Clicked) ON_COMMAND(IDSC_BUTTON2, OnButton2Clicked) ON_WM_MOUSEMOVE() END_MESSAGE_MAP() void CInfoPanel::OnPaint() { CPaintDC tempDC(this); Graphics g(tempDC.m_hDC); DoPaint(&g); } void CInfoPanel::DoPaint(Graphics* a_graphics) { Graphics& g = *a_graphics; ASSERT(text.GetLength()>0); ASSERT(title.GetLength()>0); CRect rect; GetClientRect(rect); Style& style = Style::Instance(); //Draw background { StyleObject<Brush> backgroundBrush = style.GetTipWindowBackground(rect); g.FillRectangle(backgroundBrush, Rect(0,0,rect.right,rect.bottom)); } //Draw main border { StyleObject<Pen> borderPen = style.GetTipWindowBorder(); Rect borderRect(1,1,rect.right-2,rect.bottom-2); g.DrawRectangle(borderPen, borderRect); } ///////////////////////////////////////////////////////////////////////////// // Draw text g.SetSmoothingMode(SmoothingModeHighQuality); g.SetTextRenderingHint(TextRenderingHintAntiAlias); StyleObject<Brush> textBrush = style.GetTipWindowTextBrush(); StringFormat format; //format.SetAlignment(StringAlignmentCenter); //Draw title Font titleFont(L"Trebuchet MS", 12, FontStyleBold, UnitPoint); RectF titleRect(40, 20, rect.right-10, 50.0f); g.DrawString( CT2W(title), title.GetLength(), &titleFont, titleRect, &format, textBrush); Font textFont(L"Trebuchet MS", 9, FontStyleBold, UnitPoint); RectF textRect(10,70,rect.right-10,rect.bottom-10); g.DrawString( CT2W(text), text.GetLength(), &textFont, textRect, &format, textBrush); } bool CInfoPanel:: RegisterRuntimeClass() { WNDCLASS wndcls; ZeroMemory(&wndcls, sizeof(WNDCLASS)); wndcls.style = CS_SAVEBITS|CS_BYTEALIGNCLIENT|CS_HREDRAW|CS_VREDRAW; #ifdef CS_DROPSHADOW wndcls.style |= CS_DROPSHADOW; #endif wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hbrBackground = (HBRUSH)::GetStockObject(WHITE_BRUSH); wndcls.hInstance = AfxGetInstanceHandle(); wndcls.lpszClassName = _T("MINAKORT_INFO_CONTROL_CLASS"); // Register the new class and exit if it fails if(!AfxRegisterClass(&wndcls)) { TRACE("Class Registration Failed\n"); return false; } return true; } BOOL CInfoPanel::Create(CWnd* pParentWnd, UINT nID) { static int a = RegisterRuntimeClass(); BOOL b = CWnd::CreateEx(WS_EX_TOPMOST , _T("MINAKORT_INFO_CONTROL_CLASS"), _T("INFO"), WS_CHILD, CRect(10, 10, 251, 244), pParentWnd, nID, NULL); return b; } void CInfoPanel::SetText(const CString& title, const CString& text) { this->title = title; this->text = text; this->Invalidate(); } void CInfoPanel::SetButtonText(const CString& button1Text, const CString& button2Text) { this->button.SetWindowText(button2Text); this->button.ShowWindow(button2Text.GetLength()>0?SW_SHOW:SW_HIDE); } void CInfoPanel::Show(const CPoint& position, DirectionMode posMode, bool volatileMode) { ASSERT(text.GetLength() > 0 && title.GetLength() > 0); this->volatileMode = volatileMode; button.SetForceHighlight(false); CRect rect; GetClientRect(rect); if(posMode==DirectionMode::Bottom) rect.MoveToXY(CPoint(position.x, position.y-rect.Height())); else rect.MoveToXY(CPoint(position.x, position.y)); MoveWindow(rect); ShowWindow(SW_SHOW); if(volatileMode) SetCapture(); } void CInfoPanel::ShowModal(CWnd* parent) { ASSERT(!this->GetSafeHwnd()); this->Create(parent); CRect rect; parent->GetClientRect(rect); int width = 241; int height = 234; int x = (rect.right-width)/2; int y = (rect.bottom-height)/2; this->Show(CPoint(x,y)); ReleaseCapture(); this->RunModalLoop(); } void CInfoPanel::Hide() { if(!GetSafeHwnd()) return; ReleaseCapture(); ShowWindow(SW_HIDE); button.SetForceHighlight(false); immuneMouseDown = false; // this->EndModalLoop(0); } void CInfoPanel::OnNcLButtonUp(UINT nHitTest, CPoint point) { if(volatileMode) Hide(); CWnd::OnNcLButtonDown(nHitTest, point); } void CInfoPanel::OnLButtonUp(UINT nFlags, CPoint point) { if(buttonRect.PtInRect(point)) { LPARAM lp = point.x+(point.y<<16); // button.SendMessage(WM_LBUTTONUP, 0, lp); // SetCapture(); // if(0!=0x0004&button.GetState()) if(button.GetForceHighligt()) OnButton2Clicked(); } else if(!immuneMouseDown) { if(volatileMode) Hide(); } immuneMouseDown = false; CWnd::OnLButtonDown(nFlags, point); } void CInfoPanel::OnLButtonDown(UINT nFlags, CPoint point) { if(buttonRect.PtInRect(point)) { button.SetForceHighlight(true); immuneMouseDown = true; // LPARAM lp = point.x+(point.y<<16); // button.SendMessage(WM_LBUTTONDOWN, 0, lp); // SetCapture(); } CWnd::OnLButtonDown(nFlags, point); } void CInfoPanel::OnButton2Clicked() { if(volatileMode) Hide(); if(this->GetDlgCtrlID()) { CWnd* parent = this->GetParent(); HWND hwnd = this->GetSafeHwnd(); LRESULT a = ::SendMessage(parent->m_hWnd, WM_COMMAND, MAKELONG(this->GetDlgCtrlID(), INFOCOMMAND_BUTTON2), (LPARAM)hwnd); } } void CInfoPanel::OnButton1Clicked() { if(volatileMode) Hide(); if(this->GetDlgCtrlID()) { CWnd* parent = this->GetParent(); HWND hwnd = this->GetSafeHwnd(); LRESULT a = ::SendMessage(parent->m_hWnd, WM_COMMAND, MAKELONG(this->GetDlgCtrlID(), INFOCOMMAND_BUTTON1), (LPARAM)hwnd); } } void CInfoPanel::OnMouseMove(UINT nFlags, CPoint point) { if(button.GetForceHighligt()) button.SetForceHighlight(buttonRect.PtInRect(point)?TRUE:FALSE); CWnd::OnMouseMove(nFlags, point); }
[ [ [ 1, 289 ] ] ]
44b50e73aa3c380a3f16030567ebd21010160fee
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
/tool/dressing/source/bindobject/colortext.h
e4fd0f9e4b7d171d1abd3b804352e1826ff30fcb
[]
no_license
roxygen/maid2
230319e05d6d6e2f345eda4c4d9d430fae574422
455b6b57c4e08f3678948827d074385dbc6c3f58
refs/heads/master
2021-01-23T17:19:44.876818
2010-07-02T02:43:45
2010-07-02T02:43:45
38,671,921
0
0
null
null
null
null
UTF-8
C++
false
false
806
h
#ifndef tool_dressing_bindobject_colortext_h #define tool_dressing_bindobject_colortext_h #include"cppdrawtype.h" class ColorText : public CppDrawType { public: static void Register(); float ColorR; float ColorG; float ColorB; float Alpha; int LayoutX; // テキストの配置位置 int LayoutY; // テキストの配置位置 Maid::String Text; Sqrat::string GetText() const; void SetText(const Sqrat::string& text); Sqrat::string GetFontName() const; void SetFontName(const Sqrat::string& name); int GetFontW() const; void SetFontW(const int& w); int GetFontH() const; void SetFontH(const int& h); Maid::Font hFont; ColorText(); virtual void Draw( float time, const Maid::POINT3DF& pos ); }; #endif
[ "renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00" ]
[ [ [ 1, 42 ] ] ]
bb012c1da9737faa53120b7d9e7df743ba4ab82f
62a5260bf242add996041111c92a795f2e5a4e8b
/ocgcore/scriptlib.h
d7d74c01bcaaee8bd446fbe352d9d473abd22152
[]
no_license
zh99998/ygocore
cc0d1f8d628ab37e5217aed543966f775d93a8d4
362daff35e17ea338b8873b9cc1ab8ee10bc2c7f
refs/heads/master
2021-01-22T05:24:24.120543
2011-11-27T13:21:34
2011-11-27T13:21:34
3,000,435
6
1
null
null
null
null
UTF-8
C++
false
false
21,458
h
/* * scriptlib.h * * Created on: 2009-1-20 * Author: Argon.Sun */ #ifndef SCRIPTLIB_H_ #define SCRIPTLIB_H_ #include "common.h" #include "interpreter.h" class scriptlib { public: static int32 check_param(lua_State* L, int32 param_type, int32 index, BOOL retfalse = FALSE); static int32 check_param_count(lua_State* L, int32 count); static int32 check_action_permission(lua_State* L); //bit static int32 bit_and(lua_State *L); static int32 bit_or(lua_State *L); static int32 bit_xor(lua_State *L); static int32 bit_ls(lua_State *L); static int32 bit_rs(lua_State *L); //card lib static int32 card_get_code(lua_State *L); static int32 card_get_origin_code(lua_State *L); static int32 card_is_set_card(lua_State *L); static int32 card_get_type(lua_State *L); static int32 card_get_origin_type(lua_State *L); static int32 card_get_level(lua_State *L); static int32 card_get_synchro_level(lua_State *L); static int32 card_get_ritual_level(lua_State *L); static int32 card_get_origin_level(lua_State *L); static int32 card_get_attribute(lua_State *L); static int32 card_get_origin_attribute(lua_State *L); static int32 card_get_race(lua_State *L); static int32 card_get_origin_race(lua_State *L); static int32 card_get_attack(lua_State *L); static int32 card_get_origin_attack(lua_State *L); static int32 card_get_text_attack(lua_State *L); static int32 card_get_defence(lua_State *L); static int32 card_get_origin_defence(lua_State *L); static int32 card_get_text_defence(lua_State *L); static int32 card_get_owner(lua_State *L); static int32 card_get_controler(lua_State *L); static int32 card_get_previous_controler(lua_State *L); static int32 card_get_reason(lua_State *L); static int32 card_get_reason_card(lua_State *L); static int32 card_get_reason_player(lua_State *L); static int32 card_get_reason_effect(lua_State *L); static int32 card_get_position(lua_State *L); static int32 card_get_previous_position(lua_State *L); static int32 card_get_battle_position(lua_State *L); static int32 card_get_location(lua_State *L); static int32 card_get_previous_location(lua_State *L); static int32 card_get_sequence(lua_State *L); static int32 card_get_previous_sequence(lua_State *L); static int32 card_get_summon_type(lua_State *L); static int32 card_get_summon_player(lua_State *L); static int32 card_get_destination(lua_State *L); static int32 card_get_turnid(lua_State *L); static int32 card_get_fieldid(lua_State *L); static int32 card_is_code(lua_State *L); static int32 card_is_type(lua_State *L); static int32 card_is_race(lua_State *L); static int32 card_is_attribute(lua_State *L); static int32 card_is_reason(lua_State *L); static int32 card_is_status(lua_State *L); static int32 card_is_not_tuner(lua_State *L); static int32 card_set_status(lua_State *L); static int32 card_is_dual_state(lua_State *L); static int32 card_enable_dual_state(lua_State *L); static int32 card_set_turn_counter(lua_State *L); static int32 card_get_turn_counter(lua_State *L); static int32 card_set_material(lua_State *L); static int32 card_get_material(lua_State *L); static int32 card_get_material_count(lua_State *L); static int32 card_get_equip_group(lua_State *L); static int32 card_get_equip_count(lua_State *L); static int32 card_get_equip_target(lua_State *L); static int32 card_get_pre_equip_target(lua_State *L); static int32 card_check_equip_target(lua_State *L); static int32 card_get_union_count(lua_State *L); static int32 card_get_overlay_group(lua_State *L); static int32 card_get_overlay_count(lua_State *L); static int32 card_check_remove_overlay_card(lua_State *L); static int32 card_remove_overlay_card(lua_State *L); static int32 card_get_attacked_group(lua_State *L); static int32 card_get_attacked_group_count(lua_State *L); static int32 card_get_attacked_count(lua_State *L); static int32 card_get_battled_group(lua_State *L); static int32 card_get_battled_group_count(lua_State *L); static int32 card_get_attack_announced_count(lua_State *L); static int32 card_is_direct_attacked(lua_State *L); static int32 card_set_card_target(lua_State *L); static int32 card_get_card_target(lua_State *L); static int32 card_get_first_card_target(lua_State *L); static int32 card_get_card_target_count(lua_State *L); static int32 card_is_has_card_target(lua_State *L); static int32 card_cancel_card_target(lua_State *L); static int32 card_get_owner_target(lua_State *L); static int32 card_get_owner_target_count(lua_State *L); static int32 card_get_activate_effect(lua_State *L); static int32 card_register_effect(lua_State *L); static int32 card_is_has_effect(lua_State *L); static int32 card_get_effect_count(lua_State *L); static int32 card_register_flag_effect(lua_State *L); static int32 card_get_flag_effect(lua_State *L); static int32 card_reset_flag_effect(lua_State *L); static int32 card_create_relation(lua_State *L); static int32 card_release_relation(lua_State *L); static int32 card_create_effect_relation(lua_State *L); static int32 card_is_relate_to_effect(lua_State *L); static int32 card_is_relate_to_card(lua_State *L); static int32 card_is_relate_to_battle(lua_State *L); static int32 card_copy_effect(lua_State *L); static int32 card_enable_revive_limit(lua_State *L); static int32 card_complete_procedure(lua_State *L); static int32 card_is_disabled(lua_State *L); static int32 card_is_destructable(lua_State *L); static int32 card_is_summonable(lua_State *L); static int32 card_is_msetable(lua_State *L); static int32 card_is_ssetable(lua_State *L); static int32 card_is_special_summonable(lua_State *L); static int32 card_is_synchro_summonable(lua_State *L); static int32 card_is_can_be_summoned(lua_State *L); static int32 card_is_can_be_special_summoned(lua_State *L); static int32 card_is_able_to_hand(lua_State *L); static int32 card_is_able_to_grave(lua_State *L); static int32 card_is_able_to_deck(lua_State *L); static int32 card_is_able_to_extra(lua_State *L); static int32 card_is_able_to_remove(lua_State *L); static int32 card_is_able_to_hand_as_cost(lua_State *L); static int32 card_is_able_to_grave_as_cost(lua_State *L); static int32 card_is_able_to_deck_as_cost(lua_State *L); static int32 card_is_able_to_extra_as_cost(lua_State *L); static int32 card_is_able_to_remove_as_cost(lua_State *L); static int32 card_is_releaseable(lua_State *L); static int32 card_is_discardable(lua_State *L); static int32 card_is_attackable(lua_State *L); static int32 card_is_chain_attackable(lua_State *L); static int32 card_is_faceup(lua_State *L); static int32 card_is_attack(lua_State *L); static int32 card_is_facedown(lua_State *L); static int32 card_is_defence(lua_State *L); static int32 card_is_position(lua_State *L); static int32 card_is_pre_position(lua_State *L); static int32 card_is_controler(lua_State *L); static int32 card_is_onfield(lua_State *L); static int32 card_is_location(lua_State *L); static int32 card_is_pre_location(lua_State *L); static int32 card_is_level_below(lua_State *L); static int32 card_is_level_above(lua_State *L); static int32 card_is_rank_below(lua_State *L); static int32 card_is_rank_above(lua_State *L); static int32 card_is_attack_below(lua_State *L); static int32 card_is_attack_above(lua_State *L); static int32 card_is_defence_below(lua_State *L); static int32 card_is_defence_above(lua_State *L); static int32 card_is_public(lua_State *L); static int32 card_is_forbidden(lua_State *L); static int32 card_is_able_to_change_controler(lua_State *L); static int32 card_is_controler_can_be_changed(lua_State *L); static int32 card_add_counter(lua_State *L); static int32 card_remove_counter(lua_State *L); static int32 card_get_counter(lua_State *L); static int32 card_enable_counter_permit(lua_State *L); static int32 card_set_counter_limit(lua_State *L); static int32 card_is_can_turn_set(lua_State *L); static int32 card_is_can_add_counter(lua_State *L); static int32 card_is_can_remove_counter(lua_State *L); static int32 card_is_can_be_fusion_material(lua_State *L); static int32 card_is_can_be_synchro_material(lua_State *L); static int32 card_is_can_be_xyz_material(lua_State *L); static int32 card_check_fusion_material(lua_State *L); static int32 card_is_immune_to_effect(lua_State *L); static int32 card_is_can_be_effect_target(lua_State *L); static int32 card_is_can_be_battle_target(lua_State *L); static int32 card_add_trap_monster_attribute(lua_State *L); static int32 card_cancel_to_grave(lua_State *L); static int32 card_get_tribute_requirement(lua_State *L); //Effect functions static int32 effect_new(lua_State *L); static int32 effect_clone(lua_State *L); static int32 effect_reset(lua_State *L); static int32 effect_set_description(lua_State *L); static int32 effect_set_code(lua_State *L); static int32 effect_set_range(lua_State *L); static int32 effect_set_target_range(lua_State *L); static int32 effect_set_absolute_range(lua_State *L); static int32 effect_set_count_limit(lua_State *L); static int32 effect_set_reset(lua_State *L); static int32 effect_set_type(lua_State *L); static int32 effect_set_property(lua_State *L); static int32 effect_set_label(lua_State *L); static int32 effect_set_label_object(lua_State *L); static int32 effect_set_category(lua_State *L); static int32 effect_set_hint_timing(lua_State *L); static int32 effect_set_condition(lua_State *L); static int32 effect_set_target(lua_State *L); static int32 effect_set_cost(lua_State *L); static int32 effect_set_value(lua_State *L); static int32 effect_set_operation(lua_State *L); static int32 effect_set_owner_player(lua_State *L); static int32 effect_get_description(lua_State *L); static int32 effect_get_code(lua_State *L); static int32 effect_get_type(lua_State *L); static int32 effect_get_property(lua_State *L); static int32 effect_get_label(lua_State *L); static int32 effect_get_label_object(lua_State *L); static int32 effect_get_category(lua_State *L); static int32 effect_get_owner(lua_State *L); static int32 effect_get_handler(lua_State *L); static int32 effect_get_owner_player(lua_State *L); static int32 effect_get_handler_player(lua_State *L); static int32 effect_get_condition(lua_State *L); static int32 effect_get_target(lua_State *L); static int32 effect_get_cost(lua_State *L); static int32 effect_get_value(lua_State *L); static int32 effect_get_operation(lua_State *L); static int32 effect_is_has_property(lua_State *L); static int32 effect_is_has_category(lua_State *L); static int32 effect_is_has_type(lua_State *L); //Group functions static int32 group_new(lua_State *L); static int32 group_clone(lua_State *L); static int32 group_from_cards(lua_State *L); static int32 group_delete(lua_State *L); static int32 group_keep_alive(lua_State *L); static int32 group_clear(lua_State *L); static int32 group_add_card(lua_State *L); static int32 group_remove_card(lua_State *L); static int32 group_get_next(lua_State *L); static int32 group_get_first(lua_State *L); static int32 group_get_count(lua_State *L); static int32 group_for_each(lua_State *L); static int32 group_filter(lua_State *L); static int32 group_filter_count(lua_State *L); static int32 group_filter_select(lua_State *L); static int32 group_select(lua_State *L); static int32 group_random_select(lua_State *L); static int32 group_is_exists(lua_State *L); static int32 group_check_with_sum_equal(lua_State *L); static int32 group_select_with_sum_equal(lua_State *L); static int32 group_check_with_sum_greater(lua_State *L); static int32 group_select_with_sum_greater(lua_State *L); static int32 group_get_min_group(lua_State *L); static int32 group_get_max_group(lua_State *L); static int32 group_get_sum(lua_State *L); static int32 group_get_class_count(lua_State *L); static int32 group_remove(lua_State *L); static int32 group_merge(lua_State *L); static int32 group_sub(lua_State *L); static int32 group_is_contains(lua_State *L); static int32 group_search_card(lua_State *L); //Duel functions static int32 duel_get_lp(lua_State *L); static int32 duel_set_lp(lua_State *L); static int32 duel_get_turn_player(lua_State *L); static int32 duel_get_turn_count(lua_State *L); static int32 duel_get_draw_count(lua_State *L); static int32 duel_debug_message(lua_State *L); static int32 duel_register_effect(lua_State *L); static int32 duel_register_flag_effect(lua_State *L); static int32 duel_reset_flag_effect(lua_State *L); static int32 duel_get_flag_effect(lua_State *L); static int32 duel_destroy(lua_State *L); static int32 duel_remove(lua_State *L); static int32 duel_sendto_grave(lua_State *L); static int32 duel_summon(lua_State *L); static int32 duel_special_summon_rule(lua_State *L); static int32 duel_synchro_summon(lua_State *L); static int32 duel_setm(lua_State *L); static int32 duel_sets(lua_State *L); static int32 duel_create_token(lua_State *L); static int32 duel_special_summon(lua_State *L); static int32 duel_special_summon_step(lua_State *L); static int32 duel_special_summon_complete(lua_State *L); static int32 duel_sendto_hand(lua_State *L); static int32 duel_sendto_deck(lua_State *L); static int32 duel_get_operated_group(lua_State *L); static int32 duel_remove_counter(lua_State *L); static int32 duel_is_can_remove_counter(lua_State *L); static int32 duel_get_counter(lua_State *L); static int32 duel_change_form(lua_State *L); static int32 duel_release(lua_State *L); static int32 duel_move_to_field(lua_State *L); static int32 duel_return_to_field(lua_State *L); static int32 duel_move_sequence(lua_State *L); static int32 duel_set_chain_limit(lua_State *L); static int32 duel_set_chain_limit_p(lua_State *L); static int32 duel_get_chain_material(lua_State *L); static int32 duel_confirm_decktop(lua_State *L); static int32 duel_confirm_cards(lua_State *L); static int32 duel_sort_decktop(lua_State *L); static int32 duel_check_event(lua_State *L); static int32 duel_raise_event(lua_State *L); static int32 duel_raise_single_event(lua_State *L); static int32 duel_check_timing(lua_State *L); static int32 duel_get_environment(lua_State *L); static int32 duel_win(lua_State *L); static int32 duel_draw(lua_State *L); static int32 duel_damage(lua_State *L); static int32 duel_recover(lua_State *L); static int32 duel_equip(lua_State *L); static int32 duel_get_control(lua_State *L); static int32 duel_swap_control(lua_State *L); static int32 duel_check_lp_cost(lua_State *L); static int32 duel_pay_lp_cost(lua_State *L); static int32 duel_discard_deck(lua_State *L); static int32 duel_discard_hand(lua_State *L); static int32 duel_disable_shuffle_check(lua_State *L); static int32 duel_shuffle_deck(lua_State *L); static int32 duel_shuffle_hand(lua_State *L); static int32 duel_shuffle_setcard(lua_State *L); static int32 duel_change_attacker(lua_State *L); static int32 duel_replace_attacker(lua_State *L); static int32 duel_change_attack_target(lua_State *L); static int32 duel_replace_attack_target(lua_State *L); static int32 duel_get_battle_damage(lua_State *L); static int32 duel_change_battle_damage(lua_State *L); static int32 duel_change_target(lua_State *L); static int32 duel_change_target_player(lua_State *L); static int32 duel_change_target_param(lua_State *L); static int32 duel_break_effect(lua_State *L); static int32 duel_change_effect(lua_State *L); static int32 duel_disable_activate(lua_State *L); static int32 duel_disable_effect(lua_State *L); static int32 duel_disable_summon(lua_State *L); static int32 duel_increase_summon_count(lua_State *L); static int32 duel_check_summon_count(lua_State *L); static int32 duel_get_location_count(lua_State *L); static int32 duel_get_field_card(lua_State *L); static int32 duel_check_location(lua_State *L); static int32 duel_get_current_chain(lua_State *L); static int32 duel_get_chain_info(lua_State *L); static int32 duel_get_first_target(lua_State *L); static int32 duel_get_current_phase(lua_State *L); static int32 duel_skip_phase(lua_State *L); static int32 duel_is_damage_calculated(lua_State *L); static int32 duel_get_attacker(lua_State *L); static int32 duel_get_attack_target(lua_State *L); static int32 duel_disable_attack(lua_State *L); static int32 duel_chain_attack(lua_State *L); static int32 duel_readjust(lua_State *L); static int32 duel_get_field_group(lua_State *L); static int32 duel_get_field_group_count(lua_State *L); static int32 duel_get_decktop_group(lua_State *L); static int32 duel_get_matching_group(lua_State *L); static int32 duel_get_matching_count(lua_State *L); static int32 duel_get_first_matching_card(lua_State *L); static int32 duel_is_existing_matching_card(lua_State *L); static int32 duel_select_matching_cards(lua_State *L); static int32 duel_get_release_group(lua_State *L); static int32 duel_get_release_group_count(lua_State *L); static int32 duel_check_release_group(lua_State *L); static int32 duel_select_release_group(lua_State *L); static int32 duel_get_tribute_group(lua_State *L); static int32 duel_get_tribute_count(lua_State *L); static int32 duel_select_tribute(lua_State *L); static int32 duel_get_target_count(lua_State *L); static int32 duel_is_existing_target(lua_State *L); static int32 duel_select_target(lua_State *L); static int32 duel_select_fusion_material(lua_State *L); static int32 duel_set_fusion_material(lua_State *L); static int32 duel_set_synchro_material(lua_State *L); static int32 duel_select_synchro_material(lua_State *L); static int32 duel_check_synchro_material(lua_State *L); static int32 duel_select_tuner_material(lua_State *L); static int32 duel_check_tuner_material(lua_State *L); static int32 duel_get_ritual_material(lua_State *L); static int32 duel_release_ritual_material(lua_State *L); static int32 duel_set_target_card(lua_State *L); static int32 duel_clear_target_card(lua_State *L); static int32 duel_set_target_player(lua_State *L); static int32 duel_set_target_param(lua_State *L); static int32 duel_set_operation_info(lua_State *L); static int32 duel_get_operation_info(lua_State *L); static int32 duel_get_operation_count(lua_State *L); static int32 duel_get_xyz_material(lua_State *L); static int32 duel_overlay(lua_State *L); static int32 duel_get_overlay_group(lua_State *L); static int32 duel_get_overlay_count(lua_State *L); static int32 duel_check_remove_overlay_card(lua_State *L); static int32 duel_remove_overlay_card(lua_State *L); static int32 duel_hint(lua_State *L); static int32 duel_select_effect_yesno(lua_State *L); static int32 duel_select_yesno(lua_State *L); static int32 duel_select_option(lua_State *L); static int32 duel_select_sequence(lua_State *L); static int32 duel_select_position(lua_State *L); static int32 duel_select_disable_field(lua_State *L); static int32 duel_announce_race(lua_State *L); static int32 duel_announce_attribute(lua_State *L); static int32 duel_announce_level(lua_State *L); static int32 duel_announce_card(lua_State *L); static int32 duel_announce_type(lua_State *L); static int32 duel_announce_number(lua_State *L); static int32 duel_announce_coin(lua_State *L); static int32 duel_toss_coin(lua_State *L); static int32 duel_toss_dice(lua_State *L); static int32 duel_set_coin_result(lua_State *L); static int32 duel_set_dice_result(lua_State *L); static int32 duel_is_player_affected_by_effect(lua_State *L); static int32 duel_is_player_can_draw(lua_State *L); static int32 duel_is_player_can_discard_deck(lua_State *L); static int32 duel_is_player_can_discard_deck_as_cost(lua_State *L); static int32 duel_is_player_can_summon(lua_State *L); static int32 duel_is_player_can_spsummon(lua_State *L); static int32 duel_is_player_can_flipsummon(lua_State *L); static int32 duel_is_player_can_spsummon_monster(lua_State *L); static int32 duel_is_player_can_release(lua_State *L); static int32 duel_is_player_can_remove(lua_State *L); static int32 duel_is_player_can_send_to_hand(lua_State *L); static int32 duel_is_player_can_send_to_grave(lua_State *L); static int32 duel_is_player_can_send_to_deck(lua_State *L); static int32 duel_is_chain_inactivatable(lua_State *L); static int32 duel_is_chain_disablable(lua_State *L); static int32 duel_check_chain_target(lua_State *L); static int32 duel_check_chain_uniqueness(lua_State *L); static int32 duel_check_summon_activity(lua_State *L); static int32 duel_check_normal_summon_activity(lua_State *L); static int32 duel_check_flip_summon_activity(lua_State *L); static int32 duel_check_special_summon_activity(lua_State *L); static int32 duel_check_attack_activity(lua_State *L); static int32 duel_check_phase_activity(lua_State *L); //specific card functions static int32 duel_venom_swamp_check(lua_State *L); static int32 duel_swap_deck_and_grave(lua_State *L); static int32 duel_majestic_copy(lua_State *L); }; #endif /* SCRIPTLIB_H_ */
[ "[email protected]@a812b692-228c-6283-38e5-8e5dc2e8e749" ]
[ [ [ 1, 442 ] ] ]
4ba243e133cf7eef623ad0390e64a67fa6499450
50f4c404a5bace0abf8970ed79623a9c18b3909b
/GameScene.h
057750c79121e93fcdeb328f00386665d4a4e294
[]
no_license
Fissuras/mugenformation
94fba15e08ee836db6948e16c0f6b2b552d10a80
9293988dd5032538646ef9db8639622ce038239c
refs/heads/master
2021-01-10T17:21:54.359790
2008-07-30T04:15:27
2008-07-30T04:15:27
49,397,123
0
0
null
null
null
null
UTF-8
C++
false
false
773
h
/** * Game scene. * * @author Francis BISSON */ // INCLUDES //////////////////////////////////////////////////////////////////// #include "Font.h" #include "Player.h" #include "Point.hpp" #include "Rectangle.h" #include "Scene.h" #include "Text.h" // FORWARD DECLARATIONS //////////////////////////////////////////////////////// class DisplayContext; class Game; // CLASS DEFINITION //////////////////////////////////////////////////////////// class GameScene : public Scene { public: GameScene(Game* game); virtual ~GameScene(); virtual bool Init(); virtual void Update(double deltaTime); virtual void Render(DisplayContext* displayContext); protected: PlayerPtr m_Player; FontPtr m_Font; Text m_FPS; };
[ "xezekielx@4c29ad15-fc4f-0410-bf84-09c4532b2003" ]
[ [ [ 1, 35 ] ] ]
4185ef9e278a146efe06ef88169702c8d2a850fe
e189580af7bb112473eaabce869b0f3358539713
/meditext.cpp
1754322fe1274fae9ef28bc787cd763488c59a26
[]
no_license
fmntf/MEdiText
eec79c88c901eb09bf319b93e8bdcfa33ea546a1
f8f75d5d5fd8c0a998d6bfb28fd551fe52071044
refs/heads/master
2020-04-05T13:47:56.985196
2011-12-05T16:49:01
2011-12-05T16:49:01
2,846,337
0
0
null
null
null
null
UTF-8
C++
false
false
5,748
cpp
#include <QtGui> #include <QFile> #include "background.cpp" #include "preferences.cpp" #include "meditext.h" // construction /** * Starts MEdiText with a blank document. */ MEdiText::MEdiText() { init(); this->currentDocument = QString(); } /** * Starts MEdiText preloading a file. * * @param filename Path to the text file to preload (by argv) */ MEdiText::MEdiText(char* filename) { init(); this->loadFromFilename(QString(filename)); } /** * Setups the UI: textarea transparency, preferences restore, signals&slots. */ void MEdiText::init() { // ui setupUi(this); showFullScreen(); this->textEdit->viewport()->setAutoFillBackground(false); // signal listening connect( newBtn, SIGNAL( clicked() ), this, SLOT( createNewDocument() ) ); connect( openBtn, SIGNAL( clicked() ), this, SLOT( openExistingDocument() ) ); connect( saveBtn, SIGNAL( clicked() ), this, SLOT( saveDocument() ) ); connect( quitBtn, SIGNAL( clicked() ), this, SLOT( closeIfSaved() ) ); connect( prefsBtn, SIGNAL( clicked() ), this, SLOT( openPreferences() ) ); // preference restore this->settings = new QSettings("MEdiText", "MEdiText"); QString path = this->settings->value("background_path", "mckenzie.jpg").toString(); int alpha = this->settings->value("background_alpha", 128).toInt(); this->setBackground(path, alpha); QString family = this->settings->value("font_family", "DejaVu Sans").toString(); int size = this->settings->value("font_size", 11).toInt(); this->setFont(family, size); } // text and ui handling /** * Empties the textarea to allow the user to write a new document. * If there are some unsaved changes, a prompt is showed to allow * the user to save the file. */ void MEdiText::createNewDocument() { if (this->changesCanBeSaved()) { this->textEdit->clear(); this->currentDocument = QString(); } } /** * Open a prompt to allow the user to select a document to load. * If there are some unsaved changes, a prompt is showed to allow * the user to save the file. */ void MEdiText::openExistingDocument() { if (this->changesCanBeSaved()) { QString fileName = QFileDialog::getOpenFileName(this, "Open file", QString(), "Text files (*.txt);;All files (*)"); if (!fileName.isEmpty()) { loadFromFilename(fileName); } } } /** * Saves the document to disk. * If there is a document previously saved, overwrites it. * It the document is totally new, opens a dialog to let the user to choose * a file name. * * @return false in case of failure */ bool MEdiText::saveDocument() { QString fileName; if (this->currentDocument.isEmpty()) { fileName = QFileDialog::getSaveFileName(this, "Save as", QString(), "Text files (*.txt);;All files (*)"); if (fileName.isEmpty()) { return false; } } else { fileName = this->currentDocument; } QTextDocumentWriter writer(fileName); bool hasSaved = writer.write(textEdit->document()); if (hasSaved) { this->currentDocument = fileName; textEdit->document()->setModified(false); return true; } else { QMessageBox::warning(this, "Cannot save", "It is not possibile to save your document.", QMessageBox::Ok); return false; } } /** * Checks if there are unsaved changes. * If yes, gives to the user the ability to save them. * * @return true if * - there are no changes * - the changes can be saved correctly * - the user want to discard them */ bool MEdiText::changesCanBeSaved() { if (textEdit->document()->isModified()) { int whatToDo = QMessageBox::question(this, "Unsaved changes", "Would you like to save your changes before to continue?", QMessageBox::Yes, QMessageBox::No|QMessageBox::Escape); if (whatToDo == QMessageBox::Yes) { bool saved = this->saveDocument(); if (!saved) { return false; } } } return true; } /** * Reads filename from the I/O and puts its content in the textarea. * Updates also the reference to the opened file to allow the user to * replace directly filename when saving. * * @param filename Path to the text */ void MEdiText::loadFromFilename(QString filename) { QFile file(filename); file.open(QIODevice::ReadOnly | QIODevice::Text); if (file.exists()) { QTextStream out(&file); QString output = out.readAll(); file.close(); textEdit->setPlainText(output); this->currentDocument = filename; } else { this->currentDocument = QString(); } } /** * Closes the window, after checking that there are no unsaved changes. */ void MEdiText::closeIfSaved() { if (this->changesCanBeSaved()) { this->close(); } } // preferences /** * Open the preferences window. * Listens backgroundChanged and fontChanged events to repaint this window. */ void MEdiText::openPreferences() { Preferences *dialog = new Preferences(this->settings); dialog->show(); connect( dialog, SIGNAL( backgroundChanged(QString, int) ), this, SLOT( setBackground(QString, int) ) ); connect( dialog, SIGNAL( fontChanged(QString, int) ), this, SLOT( setFont(QString, int) ) ); } /** * Changes the window background. * * @param path image file * @param alpha values between 0-255 */ void MEdiText::setBackground(QString path, int alpha) { Background back; QPalette palette; palette.setBrush(this->backgroundRole(), back.getBrush(path, alpha)); this->setPalette(palette); } /** * Changes the text font. * * @param family name * @param size in points */ void MEdiText::setFont(QString family, int size) { this->textEdit->setFont(QFont(family, size)); }
[ [ [ 1, 231 ] ] ]
c7c4de367db68912b0c21ef9eaa8ef2399214342
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/C++Primer中文版(第4版)/第一次-代码集合-20090414/第五章 表达式/20090120_测试5.7_条件操作符_1_避免条件操作符的深度嵌套.cpp
780c0413f57e43e6a3a986796e806451d9a41dc8
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
#include <iostream> using namespace std; int main() { int i,j,k; cout << "Enter three numbers:"; cin >> i >> j >> k; int max = i > j ? i > k ? i : k : j > k ? j : k; cout << "Max = " << max << endl; return 0; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 16 ] ] ]
4c95b5ccee3cbf5a021465373067f875cd3d1657
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Gfx/Ogl/OglGeometry.hpp
c0ccc2a3f7a5f10964b88ce7d4f9205446bb0cde
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
774
hpp
/*! */ #ifndef OGL_GEOMETRY_HPP #define OGL_GEOMETRY_HPP #include "../Geometry.hpp" #include "../GeometryTypeFwd.hpp" namespace Spiral { class OglGeometry : public Geometry { public: OglGeometry( const GeometryType& type ); private: virtual bool DoCreateHWVertexBuffer( const VertexFormat& format, boost::int32_t elementSize, boost::int32_t vertexCount, bool bManaged ); virtual bool DoCreateSWVertexBuffer( const VertexFormat& format, boost::int32_t elementSize, boost::int32_t vertexCount, bool bManaged ); virtual bool DoCreateSWIndexBuffer( const IndexFormat& format, boost::int32_t indexCount, bool bManaged ); virtual bool DoCreateHWIndexBuffer( const IndexFormat& format, boost::int32_t indexCount, bool bManaged ); }; } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 23 ] ] ]
eda694a02bc1906f5cda2f2e21d89af8a9593fa5
1c9f99b2b2e3835038aba7ec0abc3a228e24a558
/Projects/elastix/elastix_sources_v4/src/Components/Optimizers/AdaptiveStochasticGradientDescent/itkAdaptiveStochasticGradientDescentOptimizer.cxx
3d157231cad822e26982e3ad5ccb2fa98fca0902
[]
no_license
mijc/Diploma
95fa1b04801ba9afb6493b24b53383d0fbd00b33
bae131ed74f1b344b219c0ffe0fffcd90306aeb8
refs/heads/master
2021-01-18T13:57:42.223466
2011-02-15T14:19:49
2011-02-15T14:19:49
1,369,569
0
0
null
null
null
null
UTF-8
C++
false
false
2,896
cxx
/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __itkAdaptiveStochasticGradientDescentOptimizer_cxx #define __itkAdaptiveStochasticGradientDescentOptimizer_cxx #include "itkAdaptiveStochasticGradientDescentOptimizer.h" #include "vnl/vnl_math.h" #include "itkSigmoidImageFilter.h" namespace itk { /** * ************************* Constructor ************************ */ AdaptiveStochasticGradientDescentOptimizer ::AdaptiveStochasticGradientDescentOptimizer() { this->m_UseAdaptiveStepSizes = true; this->m_SigmoidMax = 1.0; this->m_SigmoidMin = -0.8; this->m_SigmoidScale = 1e-8; } // end Constructor /** * ************************** UpdateCurrentTime ******************** * * This function computes the input for the Compute_a function. */ void AdaptiveStochasticGradientDescentOptimizer ::UpdateCurrentTime( void ) { typedef itk::Function::Sigmoid<double, double> SigmoidType; if ( this->m_UseAdaptiveStepSizes ) { if ( this->GetCurrentIteration() > 0 ) { /** Make sigmoid function * Compute beta such that sigmoid(0)=0 * We assume Max>0, min<0 */ SigmoidType sigmoid; sigmoid.SetOutputMaximum( this->GetSigmoidMax() ); sigmoid.SetOutputMinimum( this->GetSigmoidMin() ); sigmoid.SetAlpha( this->GetSigmoidScale() ); const double beta = this->GetSigmoidScale() * vcl_log( - this->GetSigmoidMax() / this->GetSigmoidMin() ); sigmoid.SetBeta( beta ); /** Formula (2) in Cruz */ const double inprod = inner_product( this->m_PreviousGradient, this->GetGradient() ); this->m_CurrentTime += sigmoid(-inprod); this->m_CurrentTime = vnl_math_max( 0.0, this->m_CurrentTime ); } /** Save for next iteration */ this->m_PreviousGradient = this->GetGradient(); } else { /** Almost Robbins-Monro: time = time + E_0. * If you want the parameter estimation but no adaptive stuff, * this may be use useful: */ this->m_CurrentTime += ( this->GetSigmoidMax() + this->GetSigmoidMin() ) / 2.0; } } // end UpdateCurrentTime } // end namespace itk #endif // end #ifndef __itkAdaptiveStochasticGradientDescentOptimizer_cxx
[ [ [ 1, 90 ] ] ]
b3f08473c72d9b6511338cca185c7316665cda47
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nxsi/src/nxsi/nxsi_animation.cc
bb70bc71cbcf7b5aad3235176cc42d91765c384a
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
6,554
cc
//----------------------------------------------------------------------------- // Copyright (c) Ville Ruusutie, 2004. All Rights Reserved. //----------------------------------------------------------------------------- // See the file "nxsi_license.txt" for information on usage and redistribution // of this file, and for a DISCLAIMER OF ALL WARRANTIES. //----------------------------------------------------------------------------- // nXSI animation functions //----------------------------------------------------------------------------- #include "nxsi/nxsi.h" #include <scene/ntransformcurveanimator.h> #include <mathlib/quaternion.h> //----------------------------------------------------------------------------- nAnimBuilder::Curve BuildAnimationCurve( CSLTransform* node, vector3& basepose, nAnimBuilder::Curve::IpolType type, CSLTemplate::EFCurveType xType, CSLTemplate::EFCurveType yType, CSLTemplate::EFCurveType zType, float startKey, int keyCount) { nAnimBuilder::Curve curve; vector4 keyValue; float f; int k; // set curve infos curve.SetIpolType(type); curve.SetFirstKeyIndex(0); // get fcurves CSLFCurve* fcurves[3]; fcurves[0] = node->GetSpecificFCurve(xType); fcurves[1] = node->GetSpecificFCurve(yType); fcurves[2] = node->GetSpecificFCurve(zType); // add keys for (k = 0, f = startKey; k < keyCount; k++, f++) { nAnimBuilder::Key key; keyValue = basepose; if (fcurves[0] && (fcurves[0]->Evaluate(f) == SI_SUCCESS)) { keyValue.x = fcurves[0]->GetLastEvaluation(); } if (fcurves[1] && (fcurves[1]->Evaluate(f) == SI_SUCCESS)) { keyValue.y = fcurves[1]->GetLastEvaluation(); } if (fcurves[2] && (fcurves[2]->Evaluate(f) == SI_SUCCESS)) { keyValue.z = fcurves[2]->GetLastEvaluation(); } keyValue.w = 0.0f; if (type == nAnimBuilder::Curve::QUAT) { quaternion quat; quat.set_rotate_xyz(n_deg2rad(keyValue.x), n_deg2rad(keyValue.y), n_deg2rad(keyValue.z)); key.SetX(quat.x); key.SetY(quat.y); key.SetZ(quat.z); key.SetW(quat.w); } else { key.Set(keyValue); } curve.SetKey(k, key); } return curve; } //----------------------------------------------------------------------------- void nXSI::BuildJointAnimations(const nArray<CSLModel*>& jointList, int jointCount) { int j; float startKey = this->xsiScene.SceneInfo()->GetStart(); float endKey = this->xsiScene.SceneInfo()->GetEnd(); int keyCount = (int)(endKey - startKey + 1); float keyTime = 1.f / this->xsiScene.SceneInfo()->GetFrameRate(); // create animation group nAnimBuilder::Group group; group.SetLoopType(nAnimBuilder::Group::REPEAT); group.SetStartKey(0); group.SetNumKeys(keyCount); group.SetKeyTime(keyTime); group.SetKeyStride(1); // build key array for (j = 0; j < jointCount; j++) { CSLTransform* transform = jointList[j]->Transform(); vector3 translation = (vector3&)(transform->GetTranslation()); vector3 rotation = (vector3&)(transform->GetEulerRotation()); vector3 scale = (vector3&)(transform->GetScale()); // build translation curve group.AddCurve( BuildAnimationCurve( transform, translation, nAnimBuilder::Curve::LINEAR, CSLTemplate::SI_TRANSLATION_X, CSLTemplate::SI_TRANSLATION_Y, CSLTemplate::SI_TRANSLATION_Z, startKey, keyCount)); // build rotation curve group.AddCurve( BuildAnimationCurve( transform, rotation, nAnimBuilder::Curve::QUAT, CSLTemplate::SI_ROTATION_X, CSLTemplate::SI_ROTATION_Y, CSLTemplate::SI_ROTATION_Z, startKey, keyCount)); // build scaling curve group.AddCurve( BuildAnimationCurve( transform, scale, nAnimBuilder::Curve::LINEAR, CSLTemplate::SI_SCALING_X, CSLTemplate::SI_SCALING_Y, CSLTemplate::SI_SCALING_Z, startKey, keyCount)); } this->animBuilder.AddGroup(group); } bool nXSI::BuildTransformAnimation(CSLTransform* transform, nString& animName) { if (transform->GetFCurveCount() <= 0) return false; // create name animName.Append("_transformanimator"); // init anim infos float startKey = this->xsiScene.SceneInfo()->GetStart(); float endKey = this->xsiScene.SceneInfo()->GetEnd(); int keyCount = (int)(endKey - startKey + 1); float keyTime = 1.f / this->xsiScene.SceneInfo()->GetFrameRate(); // create animator nTransformCurveAnimator* newNode = (nTransformCurveAnimator*)this->kernelServer.New("ntransformcurveanimator", animName.Get()); newNode->SetChannel("time"); newNode->SetLoopType(nAnimator::Loop); newNode->SetAnimation(this->options.GetAnimFilename().Get()); newNode->SetAnimationGroup(this->animGroupId); // create animation group nAnimBuilder::Group group; group.SetLoopType(nAnimBuilder::Group::REPEAT); group.SetStartKey(0); group.SetNumKeys(keyCount); group.SetKeyTime(keyTime); group.SetKeyStride(1); // get basepose vector3 translation = (vector3&)(transform->GetTranslation()); vector3 rotation = (vector3&)(transform->GetEulerRotation()); vector3 scale = (vector3&)(transform->GetScale()); // build translation curve group.AddCurve( BuildAnimationCurve( transform, translation, nAnimBuilder::Curve::LINEAR, CSLTemplate::SI_TRANSLATION_X, CSLTemplate::SI_TRANSLATION_Y, CSLTemplate::SI_TRANSLATION_Z, startKey, keyCount)); // build rotation curve group.AddCurve( BuildAnimationCurve( transform, rotation, nAnimBuilder::Curve::QUAT, CSLTemplate::SI_ROTATION_X, CSLTemplate::SI_ROTATION_Y, CSLTemplate::SI_ROTATION_Z, startKey, keyCount)); // build scaling curve group.AddCurve( BuildAnimationCurve( transform, scale, nAnimBuilder::Curve::LINEAR, CSLTemplate::SI_SCALING_X, CSLTemplate::SI_SCALING_Y, CSLTemplate::SI_SCALING_Z, startKey, keyCount)); this->animBuilder.AddGroup(group); this->animGroupId++; return true; } //----------------------------------------------------------------------------- // Eof
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 179 ] ] ]
08361f3bfaf2c6bbfa0b42cf92a66f36be0dc4b0
27bde5e083cf5a32f75de64421ba541b3a23dd29
/source/Action.cpp
9212f511dc988b9eb710383007fc29b79c53d90f
[]
no_license
jbsheblak/fatal-inflation
229fc6111039aff4fd00bb1609964cf37e4303af
5d6c0a99e8c4791336cf529ed8ce63911a297a23
refs/heads/master
2021-03-12T19:22:31.878561
2006-10-20T21:48:17
2006-10-20T21:48:17
32,184,096
0
0
null
null
null
null
UTF-8
C++
false
false
962
cpp
//--------------------------------------------------- // Name: Game : Action // Desc: performs actions // Author: John Sheblak // Contact: [email protected] //--------------------------------------------------- #include "Action.h" #include "StateMachine.h" namespace Game { EASY_ACTION_IMPL( ActionQuit ) { GameX.Quit(); } StateChangeAction::StateChangeAction( std::string newState ) { mNewState = newState; } ToggleVisible::ToggleVisible( GuiElement* elem ) : mElem(elem) {} void ToggleVisible::Act() { if( mElem ) mElem->SetVisible( !mElem->IsVisible() ); } void StateChangeAction::Act() { SMachine.RequestStateChange( mNewState ); } ActionButton::ActionButton( Action* action ) { mAction = action; } ActionButton::~ActionButton() { delete mAction; } void ActionButton::OnClick( const jbsCommon::Vec2i& pos ) { mAction->Act(); } }; //end Game
[ "jbsheblak@5660b91f-811d-0410-8070-91869aa11e15" ]
[ [ [ 1, 53 ] ] ]
597b7142c97cbe1e940d1e5d22528e58f159126d
6581dacb25182f7f5d7afb39975dc622914defc7
/EDStock/Container.h
b39ea487d15e3efce272ad46c7523eaf95fe9f22
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
GB18030
C++
false
false
5,882
h
/* Cross Platform Core Code. Copyright(R) 2001-2002 Balang Software. All rights reserved. Using: class CStockInfoArray; class CStockContainer; class CDomain; class CDomainContainer; */ #if !defined( __STKLIB_CONTAINER_H__ ) #define __STKLIB_CONTAINER_H__ #include "Database.h" #define ID_STOCKCNTN_AVERAGE (-1) #define ID_STOCKCNTN_WEIGHTAVERAGE (-2) typedef struct variant_savevalue_t { UINT nVariantID; double Value; BOOL bNoValue; }VARIANT_SAVEVALUE; // 使用下句,将视包含Container.h的exe应用程序输出函数,其他相似语句类似 // template class __declspec(dllexport) CSPArray<CStockInfo, CStockInfo &>; typedef CSPArray<CStockInfo, CStockInfo &> CStockInfoArray; class CStrategy; #include "SPLock.h" /*** 股票信息数组类。 有一个股票信息数组的全局对象AfxGetStockContainer()保存所有股票的信息 */ class CStockContainer : public CStockInfoArray { public: CStockContainer(); virtual ~CStockContainer(); BOOL Lock(); BOOL UnLock(); static int SortFunction(const void *s1,const void *s2); static int StockInfoCompareFunc( const void *s1,const void *s2, CStockContainer * pContainer, int nSortVariantID ); // for access CStockInfoArray virtual int Add( CStockInfo &newElement ); virtual void SetSize(int nNewSize, int nGrowBy = -1) { CStockInfoArray::SetSize(nNewSize,nGrowBy); } // attributes enum StockTypes { typeNone = 0x00, typeMin = 0x01, typeIndex = 0x01, typeStrategy = 0x02, typeGroup = 0x03, typeDomain = 0x04, typeAll = 0x05, typeA = 0x06, typeBond = 0x07, typeFund = 0x08, typeClassShaa = 0x09, typeClassShab = 0x0A, typeClassSzna = 0x0B, typeClassSznb = 0x0C, typeClassShabond= 0x0D, typeClassSznbond= 0x0E, typeClassMsmall = 0x0F, typeRight = 0x10, typeMax = 0x10 }; // operations BOOL GetCurrentType( int *pType, CSPString * pDomain, DWORD *pdwDate ); BOOL GetPioneerTechDate( DWORD * pdwDate ); BOOL GetLatestTechDate( DWORD * pdwDate ); BOOL GetTechDateArray( CSPDWordArray & dwArray ); BOOL RetrieveFromStatic( int nType, LPCTSTR lpszDomain, CStrategy * pStrategy, DWORD dwDate ); BOOL ReRetrieveFromStatic( CStrategy * pStrategy, BOOL bUpToDate = FALSE ); BOOL RetrieveSpecify( CSPStringArray & astr ); BOOL GetStockInfo( const char * szCode, CStockInfo * pInfo, int * pid = NULL ); BOOL SetCurrentStock( int nStockIndex ); BOOL SetCurrentStock( const char * szCode ); BOOL GetCurrentStock( CStockInfo * pInfo ); BOOL GetPrevStock( CStockInfo * pInfo ); BOOL GetNextStock( CStockInfo * pInfo ); CStockInfo & GetStockInfoByID( int nID ); CStockInfo & GetStockInfoByIDSort( int nID ); CStockInfo & GetAverage( ); CStockInfo & GetWeightAverage( ); BOOL Load( CStDatabase * pDB, PROGRESS_CALLBACK fnCallback = NULL, void *cookie = NULL, int nProgStart = 0, int nProgEnd = STKLIB_MAX_PROGRESS ); void OnDataChanged( ); BOOL ReloadBase( CStDatabase * pDB ); BOOL SetMap( ); BOOL SetAverage( PROGRESS_CALLBACK fnCallback = NULL, void *cookie = NULL, int nProgStart = 0, int nProgEnd = STKLIB_MAX_PROGRESS ); BOOL Clear( ); void CopyData( CStockContainer & src ); static CStockContainer * m_pSortContainer; UINT m_nSortVariantID; BOOL m_bSortAscend; BOOL Sort( int nSortVariantID, BOOL bAscend ); void SetSortID( CSPDWordArray & auidsort ); BOOL GetMultiSortIDArray( CSPDWordArray & adwSortID, LONG lStockType, UINT nSLH, BOOL bAsc, int nCount ); BOOL GetVariantSaveValue( double *pValue, UINT nVariantID, CStockInfo &info, BOOL *pNoValue ); void SetVariantSaveValue( double Value, UINT nVariantID, CStockInfo &info, BOOL bNoValue ); void ClearVariantSaveValue( ); protected: int m_nType; DWORD m_dwDate; CSPString m_strDomain; int m_nCurrentStock; CSPString m_strCurrentStockCode; // 当m_nCurrentStock==-1时,即当前股票不在Container数组之内,则记录其StockCode CStockInfo m_infoAverage; CStockInfo m_infoWeightAverage; CStockInfo m_infoNull; CSPMapStringToPtr m_map; CSPPtrArray m_aptrSaveValueArray; CSPDWordArray m_auidSort; CSPMutex m_mutex; }; /*** 板块类,包含板块名称、板块中的股票代码 */ class CDomain : public CSPStringArray { public: CDomain( ); CDomain( const CDomain &src ); virtual ~CDomain( ); CSPString m_strName; BOOL AddStock( LPCTSTR lpszStockCode ); BOOL AddStockSort( LPCTSTR lpszStockCode ); BOOL RemoveStock( LPCTSTR lpszStockCode ); CDomain & operator = ( const CDomain &src ); int AddFxjDomain( LPCTSTR lpszFile ); }; //template class __declspec(dllexport) CSPArray<CDomain, CDomain &>; typedef CSPArray<CDomain, CDomain &> CDomainArray; /*** 板块数组类 */ class CDomainContainer : public CDomainArray { public: CDomainContainer( ); CDomainContainer( CDomainContainer & src ); virtual ~CDomainContainer( ); CDomainContainer & operator = ( CDomainContainer & src ); int AddDomain( LPCTSTR lpszDomainName ); int AddDomain( CDomain & newdomain ); int AddDomainReplace( CDomain & newdomain ); int AddDomainReplace( CDomainContainer & newdomains ); int RemoveDomain( LPCTSTR lpszDomainName ); BOOL AddDomainStock( LPCTSTR lpszDomainName, LPCTSTR lpszStockCode ); BOOL AddDomainStock( LPCTSTR lpszDomainName, CSPStringArray & astr ); BOOL RemoveDomainStock( LPCTSTR lpszDomainName, LPCTSTR lpszStockCode ); BOOL RemoveDomainStockAll( LPCTSTR lpszDomainName ); BOOL GetDomainStocks( LPCTSTR lpszDomain, CSPStringArray &astr ); BOOL GetDomains( CSPStringArray & astr ); BOOL GetAllDomainInfo( CStockContainer * pContainer, DWORD dwDate ); BOOL Load( LPCTSTR lpszFileName ); BOOL Store( LPCTSTR lpszFileName ); protected: }; #endif // __STKLIB_CONTAINER_H__
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 193 ] ] ]
42682286f4a06eaf9eb04b74cd23f3ca71fa402e
1ae750db1134b460b0e5aded33623886b5f0db6a
/7Zippo.cpp
3c2bf7e175e50a8ab8bbf2f36c47aec2847c3418
[]
no_license
pabru/7zippo
7fced5513ff6d8035b412130da74fd0e5ec1c949
ce8270ab39a1f3595cbbc6521b90953550a314b1
refs/heads/master
2016-09-05T23:53:45.239761
2009-04-22T05:09:17
2009-04-22T05:09:17
35,489,891
0
0
null
null
null
null
UTF-8
C++
false
false
12,974
cpp
// Client7z.cpp #include "StdAfx.h" #include <assert.h> #include <vector> #include <boost/thread.hpp> #include "Common/IntToString.h" #include "Common/MyInitGuid.h" #include "Common/StringConvert.h" #include "Windows/DLL.h" #include "Windows/FileDir.h" #include "Windows/FileFind.h" #include "Windows/FileName.h" #include "Windows/PropVariant.h" #include "Windows/PropVariantConversions.h" #include "../../Common/FileStreams.h" #include "../../Archive/IArchive.h" #include "../../IPassword.h" #include "../../MyVersion.h" #include "../Common/LoadCodecs.h" #include "CBuffer.h" using namespace std; using namespace NWindows; HINSTANCE g_hInstance = 0; static const char *kCopyrightString = "7-Zippo -- An Archive Convertor Based on 7-Zip"; static const char *kHelpString = "Usage: 7zippo.exe input-archive [output-archive]\n" "Examples:\n" " 7zippo a.zip : convert 'a.zip' to 'a.7z'\n" " 7zippo b.rar BB.7z : convert 'b.rar' to 'BB.7z'\n" " 7zippo c.docx : convert (zipped) document 'c.docx' to 'c.7z'\n"; #define DIM(a) (sizeof(a)/sizeof(a[0])) #ifdef _WIN32 #ifndef _UNICODE bool g_IsNT = false; static inline bool IsItWindowsNT() { OSVERSIONINFO versionInfo; versionInfo.dwOSVersionInfoSize = sizeof(versionInfo); if (!::GetVersionEx(&versionInfo)) return false; return (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT); } #endif #endif void PrintString(const UString &s) { printf("%s", (LPCSTR)GetOemString(s)); } void PrintString(const AString &s) { printf("%s", (LPCSTR)s); } void PrintNewLine() { PrintString("\n"); } void PrintStringLn(const AString &s) { PrintString(s); PrintNewLine(); } void PrintError(const AString &s) { PrintNewLine(); PrintString(s); PrintNewLine(); } static HRESULT IsArchiveItemProp(IInArchive *archive, UInt32 index, PROPID propID, bool &result) { NCOM::CPropVariant prop; RINOK(archive->GetProperty(index, propID, &prop)); if (prop.vt == VT_BOOL) result = VARIANT_BOOLToBool(prop.boolVal); else if (prop.vt == VT_EMPTY) result = false; else return E_FAIL; return S_OK; } static HRESULT IsArchiveItemFolder(IInArchive *archive, UInt32 index, bool &result) { return IsArchiveItemProp(archive, index, kpidIsDir, result); } static const wchar_t *kEmptyFileAlias = L"[Content]"; ////////////////////////////////////////////////////////////// // Archive Open callback class class CArchiveOpenCallback: public IArchiveOpenCallback, public ICryptoGetTextPassword, public CMyUnknownImp { public: MY_UNKNOWN_IMP1(ICryptoGetTextPassword); STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes); STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes); STDMETHOD(CryptoGetTextPassword)(BSTR *password); bool PasswordIsDefined; UString Password; CArchiveOpenCallback() : PasswordIsDefined(false) {} }; STDMETHODIMP CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */) { return S_OK; } STDMETHODIMP CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */) { return S_OK; } STDMETHODIMP CArchiveOpenCallback::CryptoGetTextPassword(BSTR *password) { if (!PasswordIsDefined) { // You can ask real password here from user // Password = GetPassword(OutStream); // PasswordIsDefined = true; PrintError("Password is not defined"); return E_ABORT; } return StringToBstr(Password, password); } ////////////////////////////////////////////////////////////// // Archive Extracting callback class static const wchar_t *kCantDeleteOutputFile = L"ERROR: Can not delete output file "; static const char *kTestingString = "Testing "; static const char *kExtractingString = "Extracting "; static const char *kSkippingString = "Skipping "; static const char *kUnsupportedMethod = "Unsupported Method"; static const char *kCRCFailed = "CRC Failed"; static const char *kDataError = "Data Error"; static const char *kUnknownError = "Unknown Error"; const static int prop_keys[7]={ kpidIsDir, kpidPath, kpidSize, kpidAttrib, kpidCTime, kpidATime, kpidMTime,}; struct Archive { vector<NWindows::NCOM::CPropVariant> props; CMyComPtr<IPipeBuffer> pipeStream; Archive() { //pipeStream = new_twice_buffer(); } ~Archive() { } }; CCodecs codecs; vector<Archive> archives; CInFileStream* inFile; COutFileStream *outFile; CMyComPtr<IInStream> inStream; CMyComPtr<ISequentialOutStream> outStream; #define CLS_ARC_ID_ITEM(cls) ((cls).Data4[5]) #include "../Common/OpenArchive.h" #include "../Common/ArchiveOpenCallback.h" void create_iarchive(CMyComPtr<IInArchive>& iarchive) { //static CObjectPool<IInArchive> pool; CArchiveOpenCallback openCallback; CIntVector formatIndices; // HRESULT result = MyOpenArchive(&codecs, formatIndices, archiveName, archiveLink, &openCallback); int r; UString s; openCallback.AddRef(); HRESULT h=OpenArchive(&codecs, -1, inStream, s, &iarchive, r, s, &openCallback); if (h!=S_OK) { PrintError("Can not get input class object"); getchar(); abort(); } } class CArchiveExtractCallback: public IArchiveExtractCallback, public ICryptoGetTextPassword, public CMyUnknownImp { public: MY_UNKNOWN_IMP1(ICryptoGetTextPassword); UInt32 NumErrors; CArchiveExtractCallback() { NumErrors=0; } // IProgress STDMETHOD(SetTotal)(UInt64 size) {return S_OK;} STDMETHOD(SetCompleted)(const UInt64 *completeValue) {return S_OK;} CMyComPtr<IPipeBuffer> _pipeStream; STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode) { assert(askExtractMode==::NArchive::NExtract::NAskMode::kExtract); *outStream = archives[index].pipeStream; (*outStream)->AddRef(); //_pipeStream = archives[index].pipeStream; return S_OK; } STDMETHOD(PrepareOperation)(Int32 askExtractMode) { //switch (askExtractMode) //{ //case NArchive::NExtract::NAskMode::kExtract: PrintString(kExtractingString); break; //case NArchive::NExtract::NAskMode::kTest: PrintString(kTestingString); break; //case NArchive::NExtract::NAskMode::kSkip: PrintString(kSkippingString); break; //}; return S_OK; } STDMETHOD(SetOperationResult)(Int32 operationResult) { switch(operationResult) { case NArchive::NExtract::NOperationResult::kOK: break; default: { NumErrors++; PrintString(" "); switch(operationResult) { case NArchive::NExtract::NOperationResult::kUnSupportedMethod: PrintString(kUnsupportedMethod); break; case NArchive::NExtract::NOperationResult::kCRCError: PrintString(kCRCFailed); break; case NArchive::NExtract::NOperationResult::kDataError: PrintString(kDataError); break; default: PrintString(kUnknownError); } } } //PrintNewLine(); //_pipeStream.Release(); return S_OK; } STDMETHOD(CryptoGetTextPassword)(BSTR *password) { return StringToBstr(L"", password); } }; void extract(UInt32 index) { CArchiveExtractCallback extractCallback; CMyComPtr<IInArchive> iarchive; create_iarchive(iarchive); extractCallback.AddRef(); iarchive->Extract( &index, 1, false, &extractCallback); } class CArchiveUpdateCallback: public IArchiveUpdateCallback, public ICryptoGetTextPassword2, public CMyUnknownImp { public: MY_UNKNOWN_IMP2(IArchiveUpdateCallback, ICryptoGetTextPassword2); UInt32 NumErrors; CArchiveUpdateCallback() { NumErrors=0; _count=0; } //IProgress STDMETHOD(SetTotal)(UInt64 size) {return S_OK;} STDMETHOD(SetCompleted)(const UInt64 *completeValue) {return S_OK;} STDMETHOD(EnumProperties)(IEnumSTATPROPSTG **enumerator) { return E_NOTIMPL; } STDMETHODIMP GetUpdateItemInfo(UInt32 /* index */, Int32 *newData, Int32 *newProperties, UInt32 *indexInArchive) { if (newData != NULL) *newData = BoolToInt(true); if (newProperties != NULL) *newProperties = BoolToInt(true); if (indexInArchive != NULL) *indexInArchive = (UInt32)-1; return S_OK; } STDMETHODIMP GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value) { NWindows::NCOM::CPropVariant prop; for (int i=0; i<DIM(prop_keys); ++i) if (prop_keys[i]==propID) { prop=archives[index].props[i]; break; } prop.Detach(value); return S_OK; } int _count; CMyComPtr<IPipeBuffer> _pipeStream; STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **inStream) { //printf("Index: %u\n", index); Archive& arc(archives[index]); PrintString(ConvertPropVariantToString(arc.props[1])); printf("\t\t%d/%d", ++_count, archives.size()); PrintNewLine(); arc.pipeStream = new_pipe_buffer(); arc.pipeStream->SetSize( ConvertPropVariantToUInt64(arc.props[2])); *inStream = arc.pipeStream; (*inStream)->AddRef(); //_pipeStream = arc.pipeStream; boost::thread start(&extract, index); return S_OK; } STDMETHOD(SetOperationResult)(Int32 operationResult) { switch(operationResult) { case NArchive::NExtract::NOperationResult::kOK: break; default: { NumErrors++; PrintString(" "); switch(operationResult) { case NArchive::NExtract::NOperationResult::kUnSupportedMethod: PrintString(kUnsupportedMethod); break; case NArchive::NExtract::NOperationResult::kCRCError: PrintString(kCRCFailed); break; case NArchive::NExtract::NOperationResult::kDataError: PrintString(kDataError); break; default: PrintString(kUnknownError); } } } //_pipeStream.Release(); return S_OK; } STDMETHOD(CryptoGetTextPassword2)(Int32 *passwordIsDefined, BSTR *password) { *passwordIsDefined = BoolToInt(false); return StringToBstr(L"", password); } }; UInt32 getProperites( CMyComPtr<IInArchive> iarchive ) { UInt32 NumItems; iarchive->GetNumberOfItems(&NumItems); for (UInt32 i=0; i<NumItems; ++i) { Archive task; task.props.resize(DIM(prop_keys)); for (UInt32 j=0; j<DIM(prop_keys); ++j) { iarchive->GetProperty( i, prop_keys[j], &task.props[j]); } archives.push_back(task); } return NumItems; } void convert(UString& ifn, UString& ofn) { PrintString("Input: "); PrintString(ifn); PrintNewLine(); PrintString("Output: "); PrintString(ofn); PrintNewLine(); inStream = inFile = new CInFileStream; if (!inFile->Open(ifn)) { PrintError("Can not open input file"); return; } CMyComPtr<IInArchive> iarchive; create_iarchive(iarchive); outStream = outFile = new COutFileStream; if (!outFile->Create(ofn, true)) { PrintError("can't create output archive file"); return; } CMyComPtr<IOutArchive> oarchive; if (codecs.CreateOutArchive(codecs.FindFormatForExtension(L"7z"), oarchive)!=S_OK) { PrintError("Can not get output class object"); return; } UInt32 NumItems = getProperites(iarchive); //boost::thread gogogo(&CArchiveCallback::extract, this, 0); CArchiveUpdateCallback update; update.AddRef(); HRESULT result = oarchive->UpdateItems(outStream, NumItems, &update); } void convert(char* inFile, char* outFile="") { UString ifn=GetUnicodeString(inFile, CP_OEMCP); UString ofn=GetUnicodeString(outFile, CP_OEMCP); if (ofn.IsEmpty()) for (int pos=ifn.Length()-1; pos>=0; --pos) if (ifn[pos]==L'/' || ifn[pos]==L'\\') { ofn = ifn + L".7z"; break; } else if (ifn[pos]==L'.') { ofn = ifn; ofn.Delete(pos, 10000); ofn += L".7z"; break; } convert(ifn, ofn); } ////////////////////////////////////////////////////////////////////////// // Main function #include <windows.h> #include <MMSystem.h> #pragma comment(lib, "winmm.lib") class Timer { public: Timer() { t0=::timeGetTime(); } ~Timer() { DWORD t=::timeGetTime()-t0; ShowTime(t); printf("\n"); } static void ShowTime( DWORD dt ) { if (dt<1000) printf("Time Consumed: %u ms\n", dt); else if (dt<60*1000) printf("Time Consumed: %0.3f s\n", double(dt)/1000); else if (dt<3600*1000) printf("Time Consumed: %u:%0.3f\n", dt/60000, double(dt%60000)/1000); else printf("Time Consumed: %u ms\n", dt); } protected: DWORD t0; }; int MY_CDECL main(int argc, char* argv[]) { #ifdef _WIN32 #ifndef _UNICODE g_IsNT = IsItWindowsNT(); #endif #endif PrintStringLn(kCopyrightString); if (argc<2 || argc >3) { PrintStringLn(kHelpString); return 1; } if (codecs.Load()!=S_OK) { PrintError("Can not load library"); return 1; } Timer timer; codecs.AddRef(); assert(argc==2 || argc==3); if (argc==2) convert(argv[1]); else convert(argv[1], argv[2]); return 0; }
[ "lihuiba@d7209f32-2e4b-11de-9b0f-33ff132f608d" ]
[ [ [ 1, 547 ] ] ]
66bd15174a40e755045470887505f5b8d3de85ca
a04058c189ce651b85f363c51f6c718eeb254229
/Src/Forms/NotImplementedForm.cpp
b844ac3510f4b8ca9a0356f419b212fcb45ec1d8
[]
no_license
kjk/moriarty-palm
090f42f61497ecf9cc232491c7f5351412fba1f3
a83570063700f26c3553d5f331968af7dd8ff869
refs/heads/master
2016-09-05T19:04:53.233536
2006-04-04T06:51:31
2006-04-04T06:51:31
18,799
4
1
null
null
null
null
UTF-8
C++
false
false
2,037
cpp
#include "NotImplementedForm.hpp" #include <SysUtils.hpp> #include <Geometry.hpp> #include <Text.hpp> #if defined(__MWERKS__) # pragma far_code #endif NotImplementedForm::~NotImplementedForm() { } NotImplementedForm::NotImplementedForm(MoriartyApplication& app): MoriartyForm(app, notImplementedForm), doneButton_(*this) {} void NotImplementedForm::attachControls() { MoriartyForm::attachControls(); doneButton_.attach(doneButton); } void NotImplementedForm::resize(const ArsRectangle& screenBounds) { ArsRectangle bounds; this->bounds(bounds); if (screenBounds==bounds) return; setBounds(screenBounds); bounds=screenBounds; bounds.explode(2, 17, -4, -37); doneButton_.bounds(bounds); bounds.y()=screenBounds.height()-14; doneButton_.setBounds(bounds); update(); } void NotImplementedForm::draw(UInt16 updateCode) { MoriartyForm::draw(updateCode); if (redrawAll!=updateCode) return; Graphics graphics(windowHandle()); ArsRectangle rect(bounds()); rect.explode(0, 15, 0, -33); graphics.erase(rect); Point point(rect.x(), rect.y()+20); PalmFont font(largeFont); Graphics::FontSetter setFont(graphics, font); graphics.drawCenteredText("Implement me!", point, rect.width()); } void NotImplementedForm::handleControlSelect(const EventType& event) { MoriartyApplication& app=application(); switch (event.data.ctlSelect.controlID) { case doneButton: application().runMainForm(); break; default: assert(false); } } bool NotImplementedForm::handleEvent(EventType& event) { bool handled=false; switch (event.eType) { case ctlSelectEvent: handleControlSelect(event); break; default: handled=MoriartyForm::handleEvent(event); } return handled; }
[ "andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c" ]
[ [ [ 1, 90 ] ] ]
44ad4ebd370be9404f54a883cafe7f7dc13f7d5d
48a5ca3c8319ddc1bbe36854ccdf5a8e4985dcee
/ht-chess/src/HttpTest.h
947d157cd6f75f872accbea67552888d2532018f
[]
no_license
MagnusPihl/ht-chess
0d873042ef9cd3047ba2b6fba1e70e1ccbb3a68b
2c8e636d9dde1769544617086def02c378ec83b0
refs/heads/master
2020-11-26T18:29:43.206540
2008-05-26T15:35:37
2008-05-26T15:35:37
32,142,844
0
0
null
null
null
null
UTF-8
C++
false
false
2,229
h
#ifndef HTTPTEST_H #define HTTPTEST_H #include "SDL_net.h" #include "HttpResponse.h" int clientThread(void *clientSocket) { TCPsocket socket = (TCPsocket)clientSocket; printf("Accepted a socket.\n"); char msg[4096]; SDLNet_TCP_Recv(socket, msg, 4095); printf("Receiving message:\n"); printf(msg); printf("\n"); int len, result; HttpResponse resp("Hello!"); printf("\nSending message:\n"); printf(resp()); len = strlen(resp()) + 1; // add one for the terminating NULL result = SDLNet_TCP_Send(socket, resp(), resp.getLength()); if( result < resp.getLength() ) printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); printf("\n\nMessage sent!\n"); return 0; } class HttpTest { public: HttpTest() { if(SDL_Init(0)==-1) { printf("SDL_Init: %s\n", SDL_GetError()); exit(1); } if(SDLNet_Init()==-1) { printf("SDLNet_Init: %s\n", SDLNet_GetError()); exit(2); } } ~HttpTest() { SDLNet_Quit(); } void run() { IPaddress ip; if(SDLNet_ResolveHost(&ip,NULL,9999)==-1) { printf("SDLNet_ResolveHost: %s\n", SDLNet_GetError()); exit(1); } TCPsocket tcpsock; tcpsock=SDLNet_TCP_Open(&ip); if(!tcpsock) { printf("SDLNet_TCP_Open: %s\n", SDLNet_GetError()); exit(2); } printf("Succesfully created a socket!\n"); /*while(true) {*/ TCPsocket clientSocket; while(!clientSocket) { clientSocket=SDLNet_TCP_Accept(tcpsock); } char msg[4096]; SDLNet_TCP_Recv(clientSocket, msg, 4095); printf("Receiving message:\n"); printf(msg); printf("\n"); int len, result; HttpResponse resp("Hello!"); printf("\nSending message:\n"); printf(resp()); len = strlen(resp()) + 1; // add one for the terminating NULL result = SDLNet_TCP_Send(clientSocket, resp(), resp.getLength()); if( result < resp.getLength() ) printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); printf("\n\nMessage sent!\n"); /* clientSocket=SDLNet_TCP_Accept(tcpsock); if(clientSocket != NULL) { SDL_Thread *client; client = SDL_CreateThread(clientThread, &clientSocket); } }*/ } }; #endif
[ "magnus.pihl@afdedcdd-3e49-0410-aff0-259e14133cc1" ]
[ [ [ 1, 110 ] ] ]
45bec28be37045f466bf24273a2b06ff95173e1b
5236606f2e6fb870fa7c41492327f3f8b0fa38dc
/nsrpc/include/nsrpc/p2p/detail/P2pRpcTypes.h
8839af027f173cd379c56876e0e85e56a79d0df4
[]
no_license
jcloudpld/srpc
aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88
f2483c8177d03834552053e8ecbe788e15b92ac0
refs/heads/master
2021-01-10T08:54:57.140800
2010-02-08T07:03:00
2010-02-08T07:03:00
44,454,693
0
0
null
null
null
null
UHC
C++
false
false
4,792
h
#ifndef NSRPC_P2PRPCTYPES_H #define NSRPC_P2PRPCTYPES_H #ifdef _MSC_VER # pragma once #endif #include "P2pAddress.h" #include "../P2pConfig.h" #include "../PeerId.h" #include <srpc/RpcContainers.h> #include <boost/scoped_array.hpp> namespace nsrpc { namespace detail { typedef srpc::RpcNumericType<P2pOptions, 8, srpc::UInt8> RP2pOptions; /** * @struct RP2pProperty * P2P 속성 */ struct RP2pProperty { srpc::UInt8 maxPeers_; srpc::RShortString sessionPassword_; bool hostMigration_; srpc::UInt32 sessionKey_; RPeerIds hostPrecedence_; RP2pProperty() { reset(); } void reset() { maxPeers_ = 0; sessionPassword_.clear(); hostMigration_ = false; sessionKey_ = 0; hostPrecedence_.clear(); } template <typename Stream> void serialize(Stream& ostream) { ostream & maxPeers_ & sessionPassword_ & hostMigration_ & sessionKey_ & hostPrecedence_; } }; /** * @struct RAddress * Peer의 주소 정보 */ struct RAddress : ACE_INET_Addr { RAddress() {} RAddress(srpc::UInt32 ip, srpc::UInt16 port) { set(port, ip); } RAddress(const ACE_INET_Addr& address) { set(address); } RAddress& operator=(const ACE_INET_Addr& address) { set(address); return *this; } void serialize(srpc::OStream& ostream) { ostream.write(srpc::UInt32(get_ip_address())); ostream.write(srpc::UInt16(get_port_number())); } void serialize(srpc::IStream& istream) { srpc::UInt32 ip; istream.read(ip); srpc::UInt16 port; istream.read(port); set(port, ip); } }; /// RpcType for PeerAddress list typedef srpc::RVector<RAddress> RAddresses; /// convert to RAddresses inline RAddresses toAddresses(const Addresses& addresses) { RAddresses peerAddresses; peerAddresses.reserve(addresses.size()); Addresses::const_iterator pos = addresses.begin(); const Addresses::const_iterator end = addresses.end(); for (; pos != end; ++pos) { peerAddresses.push_back(RAddress(*pos)); } return peerAddresses; } /// convert to Addresses inline Addresses toAddresses(const RAddresses& peerAddresses) { Addresses addresses; addresses.assign(peerAddresses.begin(), peerAddresses.end()); return addresses; } inline PeerAddress toPeerAddress(const RAddress& address) { return PeerAddress(address.get_host_addr(), address.get_port_number()); } inline PeerAddresses toPeerAddresses(const RAddresses& addresses) { PeerAddresses peerAddresses; peerAddresses.reserve(addresses.size()); RAddresses::const_iterator pos = addresses.begin(); const RAddresses::const_iterator end = addresses.end(); for (; pos != end; ++pos) { peerAddresses.push_back(toPeerAddress(*pos)); } return peerAddresses; } /** * @struct RMessageBuffer * RpcType for raw memory buffer */ struct RMessageBuffer { typedef srpc::UInt16 LengthType; typedef srpc::UInt8 DataType; const static LengthType maxBufferLength = P2pConfig::defaultMtu * 2; explicit RMessageBuffer(const void* buffer = 0, size_t length = 0) { assign(buffer, static_cast<LengthType>(length)); } RMessageBuffer(const RMessageBuffer& rhs) { assign(rhs); } RMessageBuffer& operator=(const RMessageBuffer& rhs) { assign(rhs); return *this; } const void* getBuffer() const { return buffer_; } LengthType getBufferLength() const { return bufferLength_; } void serialize(srpc::OStream& ostream) { assert(bufferLength_ <= maxBufferLength); ostream.write(bufferLength_); ostream.write(buffer_, bufferLength_); } void serialize(srpc::IStream& istream) { istream.read(bufferLength_); assert(bufferLength_ <= maxBufferLength); istream.read(buffer_, bufferLength_); } private: void copyBuffer(const void* buffer, srpc::UInt16 bufferLen) { memcpy(buffer_, buffer, bufferLen); } void assign(const RMessageBuffer& message) { assign(message.buffer_, message.bufferLength_); } void assign(const void* buffer, LengthType bufferLen) { assert(bufferLen <= maxBufferLength); bufferLength_ = bufferLen; copyBuffer(buffer, bufferLen); } private: DataType buffer_[maxBufferLength]; LengthType bufferLength_; }; /** @} */ // addtogroup p2p } // namespace detail } // namespace nsrpc #endif // NSRPC_P2PRPCTYPES_H
[ "kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4" ]
[ [ [ 1, 206 ] ] ]
78e08aa57a6a2a5905f4550bcc279fab94fc8df4
7a4dfb986f5bd5fbee2186fcf37a0a0a74ef6033
/SubtitleGrabber/HTTP.h
d942a0208e525d73b39b61d791c7b1c09eb4b059
[]
no_license
zsjoska/subtitle-grabber
cad96727e73d6d3ec58eb3ad5eb1dfbac0c646bd
8de1a741b2b7fdd2e7899738839516e729d23430
refs/heads/master
2016-09-06T19:14:26.133224
2007-05-30T09:20:55
2007-05-30T09:20:55
32,320,106
0
0
null
null
null
null
UTF-8
C++
false
false
500
h
#pragma once class CHTTPContent; class CHTTPResponse; class CHTTPRequest; #include "HTTPTransport.h" class CHTTP { public: static const TCHAR CRLF[3]; CHTTP(void); ~CHTTP(void); CHTTPResponse * ExecuteRequest(CHTTPRequest * request); inline int GetTransportError(){ return (m_pTransport == NULL ? ERROR_NOT_READY:m_pTransport->GetTransportError()); } private: BOOL m_bUseProxy; CString m_strLastServer; BOOL m_bKeepAlive; CHTTPTransport * m_pTransport; };
[ "zsjoska@a99920ad-ab31-0410-9f62-6da89933afc0" ]
[ [ [ 1, 27 ] ] ]
c422312c088c92b477748ce994ece69aee804529
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/properties/physicsproperty.cc
3bdb7c625cd42356a45c4562075b7df482738676
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
5,094
cc
//------------------------------------------------------------------------------ // properties/physicsproperty.cc // (C) 2006 RadonLabs GmbH //------------------------------------------------------------------------------ #include "properties/physicsproperty.h" #include "game/entity.h" #include "physics/server.h" #include "physics/level.h" #include "attr/attributes.h" #include "foundation/factory.h" #include "msg/settransform.h" namespace Properties { ImplementRtti(Properties::PhysicsProperty, AbstractPhysicsProperty); ImplementFactory(Properties::PhysicsProperty); using namespace Game; //------------------------------------------------------------------------------ /** */ PhysicsProperty::PhysicsProperty() { // empty } //------------------------------------------------------------------------------ /** */ PhysicsProperty::~PhysicsProperty() { n_assert(!this->physicsEntity.isvalid()); } //------------------------------------------------------------------------------ /** Get pointer to physics entity. Note that this method may return 0! */ Physics::Entity* PhysicsProperty::GetPhysicsEntity() const { return this->physicsEntity.get_unsafe(); } //------------------------------------------------------------------------------ /** */ void PhysicsProperty::SetupDefaultAttributes() { AbstractPhysicsProperty::SetupDefaultAttributes(); GetEntity()->SetVector3(Attr::VelocityVector, vector3(0.0f, 0.0f, 0.0f)); } //------------------------------------------------------------------------------ /** Called after the physics subsystem has been triggered. This will transfer the physics entity's new transform back into the game entity. */ void PhysicsProperty::OnMoveAfter() { if (this->IsEnabled() && this->physicsEntity->HasTransformChanged()) { Ptr<Message::UpdateTransform> msg = Message::UpdateTransform::Create(); msg->SetMatrix(this->GetPhysicsEntity()->GetTransform()); this->GetEntity()->SendSync(msg); GetEntity()->SetVector3(Attr::VelocityVector, this->physicsEntity->GetVelocity()); } } //------------------------------------------------------------------------------ /** */ bool PhysicsProperty::Accepts(Message::Msg* msg) { n_assert(msg != 0); if (msg->CheckId(Message::SetTransform::Id)) return true; return AbstractPhysicsProperty::Accepts(msg); } //------------------------------------------------------------------------------ /** */ void PhysicsProperty::HandleMessage(Message::Msg* msg) { n_assert(msg != 0); if (msg->CheckId(Message::SetTransform::Id) && this->IsEnabled()) { // set transform of physics entity Message::SetTransform* transformMsg = (Message::SetTransform*) msg; this->GetPhysicsEntity()->SetTransform(transformMsg->GetMatrix()); } // forward settransform msg upwards to set Attr::Transform directly in Transformable::Property AbstractPhysicsProperty::HandleMessage(msg); } //------------------------------------------------------------------------------ /** */ void PhysicsProperty::EnablePhysics() { n_assert(!this->IsEnabled()); if (GetEntity()->HasAttr(Attr::Physics)) { if (this->physicsEntity == 0) { // create and setup physics entity this->physicsEntity = CreatePhysicsEntity(); n_assert(this->physicsEntity != 0); this->physicsEntity->SetCompositeName(GetEntity()->GetString(Attr::Physics)); this->physicsEntity->SetUserData(GetEntity()->GetUniqueId()); } // attach physics entity to physics level this->physicsEntity->SetTransform(GetEntity()->GetMatrix44(Attr::Transform)); Physics::Level* physicsLevel = Physics::Server::Instance()->GetLevel(); n_assert(physicsLevel); physicsLevel->AttachEntity(this->physicsEntity); // call parent to do the real enable AbstractPhysicsProperty::EnablePhysics(); } } //------------------------------------------------------------------------------ /** */ Physics::Entity* PhysicsProperty::CreatePhysicsEntity() { return Physics::Entity::Create(); } //------------------------------------------------------------------------------ /** */ void PhysicsProperty::DisablePhysics() { n_assert(this->IsEnabled()); // release the physics entity Physics::Level* physicsLevel = Physics::Server::Instance()->GetLevel(); n_assert(physicsLevel); physicsLevel->RemoveEntity(this->GetPhysicsEntity()); // call parent AbstractPhysicsProperty::DisablePhysics(); } //------------------------------------------------------------------------------ /** */ void PhysicsProperty::OnDeactivate() { // call parent to cleanup AbstractPhysicsProperty::OnDeactivate(); // release physics entity if (this->physicsEntity != 0) { this->physicsEntity = 0; } } } // namespace Properties
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 175 ] ] ]
e9318793d6d0e66bcacc8fb439547b169d26f71d
5927f0908f05d3f58fe0adf4d5d20c27a4756fbe
/library/base/native_library.cpp
ceafbdb34ae94b0428aac8f932777700447c4461
[]
no_license
seasky013/x-framework
b5585505a184a7d00d229da8ab0f556ca0b4b883
575e29de5840ede157e0348987fa188b7205f54d
refs/heads/master
2016-09-16T09:41:26.994686
2011-09-16T06:16:22
2011-09-16T06:16:22
41,719,436
0
1
null
null
null
null
GB18030
C++
false
false
2,070
cpp
#include "native_library.h" #include "file_path.h" #include "file_util.h" #include "threading/thread_restrictions.h" #include "utf_string_conversions.h" namespace base { typedef HMODULE (WINAPI* LoadLibraryFunction)(const wchar_t* file_name); NativeLibrary LoadNativeLibraryHelper(const FilePath& library_path, LoadLibraryFunction load_library_api) { // LoadLibrary()会打开磁盘文件. ThreadRestrictions::AssertIOAllowed(); // 切换当前目录到库目录, 方式库依赖那个目录的其他DLLs. bool restore_directory = false; FilePath current_directory; if(GetCurrentDirectory(&current_directory)) { FilePath plugin_path = library_path.DirName(); if(!plugin_path.empty()) { SetCurrentDirectory(plugin_path); restore_directory = true; } } HMODULE module = (*load_library_api)(library_path.value().c_str()); if(restore_directory) { SetCurrentDirectory(current_directory); } return module; } NativeLibrary LoadNativeLibrary(const FilePath& library_path) { return LoadNativeLibraryHelper(library_path, LoadLibraryW); } NativeLibrary LoadNativeLibraryDynamically(const FilePath& library_path) { LoadLibraryFunction load_library; load_library = reinterpret_cast<LoadLibraryFunction>( GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW")); return LoadNativeLibraryHelper(library_path, load_library); } void UnloadNativeLibrary(NativeLibrary library) { FreeLibrary(library); } void* GetFunctionPointerFromNativeLibrary(NativeLibrary library, const char* name) { return GetProcAddress(library, name); } string16 GetNativeLibraryName(const string16& name) { return name + ASCIIToUTF16(".dll"); } } //namespace base
[ [ [ 1, 72 ] ] ]
74e48613c0cff2274c24c1b69c81ddf102d16d66
17083b919f058848c3eb038eae37effd1a5b0759
/SimpleGL/src/GL/GLTexture2D.cpp
0a20f03f02b6c1dc07850c74c05e80ee57b31628
[]
no_license
BackupTheBerlios/sgl
e1ce68dfc2daa011bdcf018ddce744698cc7bc5f
2ab6e770dfaf5268c1afa41a77c04ad7774a70ed
refs/heads/master
2021-01-21T12:39:59.048415
2011-10-28T16:14:29
2011-10-28T16:14:29
39,894,148
0
0
null
null
null
null
UTF-8
C++
false
false
10,686
cpp
#include "GL/GLCommon.h" #include "GL/GLTexture2D.h" namespace sgl { GLTexture2D::GLTexture2D(GLDevice* device, const Texture2D::DESC& desc) : GLTexture<Texture2D>(device, GL_TEXTURE_2D), format(desc.format), width(desc.width), height(desc.height), numSamples(0), numMipmaps(0) { // image settings GLenum glError; GLenum glUsage = BIND_GL_FORMAT_USAGE[format]; GLenum glPixelType = BIND_GL_FORMAT_PIXEL_TYPE[format]; GLenum glFormat = BIND_GL_FORMAT[format]; bool compressed = Texture::FORMAT_TRAITS[format].compressed; // save previous state & bind texture guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { throw gl_error("GLTexture2D<DeviceVersion>::GLTexture2D failed: "); } #endif // SGL_NO_STATUS_CHECK // copy image if (compressed) { glCompressedTexImage2D( glTarget, 0, glFormat, width, height, 0, Image::SizeOfData(format, width, height, 1), desc.data ); } else { glTexImage2D( glTarget, 0, glFormat, width, height, 0, glUsage, glPixelType, desc.data ); } #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { throw gl_error("GLTexture2D<DeviceVersion>::GLTexture2D failed: "); } #endif // SGL_NO_STATUS_CHECK } #ifndef SIMPLE_GL_ES GLTexture2D::GLTexture2D(GLDevice* device, const Texture2D::DESC_MS& desc) : GLTexture<Texture2D>(device, GL_TEXTURE_2D_MULTISAMPLE), format(desc.format), width(desc.width), height(desc.height), numSamples(desc.samples), numMipmaps(0) { // image settings GLenum glError; GLenum glFormat = BIND_GL_FORMAT[format]; // save previous state & bind texture guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { throw gl_error("GLTexture2D<DeviceVersion>::GLTexture2D failed: "); } #endif // SGL_NO_STATUS_CHECK // create image glTexImage2DMultisample( glTarget, numSamples, glFormat, width, height, GL_TRUE ); #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { throw gl_error("GLTexture2D<DeviceVersion>::GLTexture2D failed: "); } #endif // SGL_NO_STATUS_CHECK } #endif // !defined(SIMPLE_GL_ES) GLTexture2D::~GLTexture2D() { if (device->Valid()) { Unbind(); } } SGL_HRESULT GLTexture2D::SetSubImage( unsigned int mipmap, unsigned int offsetx, unsigned int offsety, unsigned int regionWidth, unsigned int regionHeight, const void* data ) { // image settings GLenum glError; GLenum glPixelType = BIND_GL_FORMAT_PIXEL_TYPE[format]; GLenum glFormat = BIND_GL_FORMAT[format]; bool compressed = Texture::FORMAT_TRAITS[format].compressed; // save previous state & bind texture guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::SetSubImage failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK // copy image if (compressed) { glCompressedTexSubImage2D( glTarget, mipmap, offsetx, offsety, regionWidth, regionHeight, glFormat, Image::SizeOfData(format, regionWidth, regionHeight, 1), data ); } else { glTexSubImage2D( glTarget, mipmap, offsetx, offsety, regionWidth, regionHeight, glFormat, glPixelType, data ); } #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::SetSubImage failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK // remember mipmaping numMipmaps = std::max(numMipmaps, mipmap); return SGL_OK; } #ifdef SIMPLE_GL_ES SGL_HRESULT GLTexture2D::GetImage( unsigned int /*mipmap*/, void* /*data*/ ) { return EUnsupported("GLTexture2D::GetImage failed. Unsupported in GLES."); } #else SGL_HRESULT GLTexture2D::GetImage( unsigned int mipmap, void* data ) { GLenum glError; GLenum glUsage = BIND_GL_FORMAT_USAGE[format]; GLenum glPixelType = BIND_GL_FORMAT_PIXEL_TYPE[format]; bool compressed = Texture::FORMAT_TRAITS[format].compressed; // save previous state & bind texture guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::GetImage failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK // copy image if (compressed) { glGetCompressedTexImage(glTarget, mipmap, data); } else { glGetTexImage(glTarget, mipmap, glUsage, glPixelType, data); } #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::GetImage failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK return SGL_OK; } #endif SGL_HRESULT GLTexture2D::GenerateMipmap() { guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); #ifndef SGL_NO_STATUS_CHECK GLenum glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::GenerateMipmap failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK #ifdef SIMPLE_GL_ES glGenerateMipmap(glTarget); #else if (glGenerateMipmapEXT) { glGenerateMipmapEXT(glTarget); } else { size_t dataSize = Image::SizeOfData(format, width, height, 1); void* data = malloc(dataSize); if (!data) { return EOutOfMemory("GLTexture2D::GenerateMipmap failed: out of memory"); } SGL_HRESULT result = GetImage(0, data); if (result != SGL_OK) { return result; } GLint gluError = gluBuild2DMipmaps( GL_TEXTURE_2D, BIND_GL_FORMAT[format], width, height, BIND_GL_FORMAT_USAGE[format], BIND_GL_FORMAT_PIXEL_TYPE[format], data ); #ifndef SGL_NO_STATUS_CHECK if ( gluError != GL_NO_ERROR ) { return CheckGLUError( "GLTexture2D::GenerateMipmap failed: ", gluError ); } #endif // SGL_NO_STATUS_CHECK } #endif #ifndef SGL_NO_STATUS_CHECK glError = glGetError(); if ( glError != GL_NO_ERROR ) { return CheckGLError( "GLTexture2D<DeviceVersion>::GenerateMipmap failed: ", glError ); } #endif // SGL_NO_STATUS_CHECK return SGL_OK; } SGL_HRESULT GLTexture2D::BindSamplerState(sgl::SamplerState* _samplerState) { samplerState.reset( static_cast<GLSamplerState*>(_samplerState) ); if (samplerState) { guarded_binding_ptr guardedTexture( new guarded_binding(device, this, 0) ); const SamplerState::DESC& desc = samplerState->Desc(); if (numSamples == 0) { glTexParameteri( glTarget, GL_TEXTURE_MIN_FILTER, BIND_TEXTURE_MIN_FILTER[ desc.filter[2] * 3 + desc.filter[0] ] ); glTexParameteri( glTarget, GL_TEXTURE_MAG_FILTER, BIND_TEXTURE_FILTER[ desc.filter[1] ] ); //glTexParameterf( glTarget, GL_TEXTURE_MIN_LOD, desc.minLod ); //glTexParameterf( glTarget, GL_TEXTURE_MAX_LOD, desc.maxLod ); //glTexParameterf( glTarget, GL_TEXTURE_LOD_BIAS, desc.lodBias ); } glTexParameteri( glTarget, GL_TEXTURE_WRAP_S, BIND_TEXTURE_CLAMP[ desc.wrapping[0] ] ); glTexParameteri( glTarget, GL_TEXTURE_WRAP_T, BIND_TEXTURE_CLAMP[ desc.wrapping[1] ] ); //glTexParameteri( glTarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, desc.maxAnisotropy); } return SGL_OK; } SGL_HRESULT GLTexture2D::Bind(unsigned int stage_) const { #ifndef SGL_NO_STATUS_CHECK if ( stage >= Device::NUM_TEXTURE_STAGES ) { return EInvalidCall("GLTexture2D<DeviceVersion>::Bind failed. Stage is too large."); } #endif stage = stage_; glActiveTexture(GL_TEXTURE0 + stage); glEnable(glTarget); glBindTexture(glTarget, glTexture); device->SetTexture(stage, this); return SGL_OK; } void GLTexture2D::Unbind() const { if ( stage >= 0 && device->CurrentTexture(stage) == this ) { glActiveTexture(GL_TEXTURE0 + stage); glBindTexture(glTarget, 0); glDisable(glTarget); device->SetTexture(stage, 0); stage = -1; } } } // namespace sgl
[ "devnull@localhost" ]
[ [ [ 1, 332 ] ] ]
08fae1fb504f5d46db3837245daac7070bf71ace
150926210848ebc2773f4683180b2e53e67232f1
/UFOHunt/OpenCVTest/AssemblyInfo.cpp
c3c84f39e17b67204a25db0dd2b303de9c09e78a
[]
no_license
wkx11/kuradevsandbox
429dccabf6b07847ed33ea07bb77a93d7c8004f0
21f09987fd7e22ba6bf2c4929ca4cbf872827b36
refs/heads/master
2021-01-02T09:33:52.967804
2010-12-12T04:06:19
2010-12-12T04:06:19
37,631,953
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,448
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 // [assembly:AssemblyTitleAttribute("OpenCVTest")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("OpenCVTest")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2010")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってリビジョンおよびビルド番号を // 既定値にすることができます: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ "sasraing@cdde4f24-bdbc-632a-de5c-276029d4cb88" ]
[ [ [ 1, 40 ] ] ]
22c3a1a78c4836a09b04116f45bb32736410e669
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/GameSDK/GameUILib/Source/tinyxmlerror.cpp
c377958be2c7d678c69dc1e785279bc731029230
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
UTF-8
C++
false
false
1,790
cpp
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //#include "StdAfx.h" #include "tinyxml.h" // The goal of the seperate error file is to make the first // step towards localization. tinyxml (currently) only supports // english error messages, but the could now be translated. // // It also cleans up the code a bit. // const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] = { "No error", "Error", "Failed to open file", "Memory allocation failed.", "Error parsing Element.", "Failed to read Element name", "Error reading Element value.", "Error reading Attributes.", "Error: empty tag.", "Error reading end tag.", "Error parsing Unknown.", "Error parsing Comment.", "Error parsing Declaration.", "Error document empty.", "Error null (0) or unexpected EOF found in input stream.", "Error parsing CDATA.", };
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 53 ] ] ]
f0382a4c1e4e7efd8d6de11829b2a4d385657242
744e9a2bf1d0aee245c42ee145392d1f6a6f65c9
/tags/last_qt3_support_release/gui/ttsearchframe.h
f551ea7153ee37b9d0752ca0c0523f61842ff013
[]
no_license
BackupTheBerlios/ttcut-svn
2b5d00c3c6d16aa118b4a58c7d0702cfcc0b051a
958032e74e8bb144a96b6eb7e1d63bc8ae762096
refs/heads/master
2020-04-22T12:08:57.640316
2009-02-08T16:14:00
2009-02-08T16:14:00
40,747,642
0
0
null
null
null
null
UTF-8
C++
false
false
3,154
h
/*----------------------------------------------------------------------------*/ /* COPYRIGHT: TriTime (c) 2003/2005 / www.tritime.org */ /*----------------------------------------------------------------------------*/ /* PROJEKT : TTCUT 2005 */ /* FILE : ttframesearch.h */ /*----------------------------------------------------------------------------*/ /* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 03/16/2005 */ /* MODIFIED: b. altendorf DATE: 06/22/2005 */ /* MODIFIED: DATE: */ /*----------------------------------------------------------------------------*/ // ---------------------------------------------------------------------------- // TTFRAMESEARCH // ---------------------------------------------------------------------------- /*----------------------------------------------------------------------------*/ /* This program is free software; you can redistribute it and/or modify it */ /* under the terms of the GNU General Public License as published by the Free */ /* Software Foundation; */ /* either version 2 of the License, or (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, but WITHOUT*/ /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */ /* FITNESS FOR A PARTICULAR PURPOSE. */ /* See the GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License along */ /* with this program; if not, write to the Free Software Foundation, */ /* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /*----------------------------------------------------------------------------*/ #ifndef TTFRAMESEARCH_H #define TTFRAMESEARCH_H #include <qstring.h> #include "ttcut.h" #include "ttprogressbar.h" #include "../avstream/ttavstream.h" #include "../mpeg2decoder/ttmpeg2decoder.h" class TTFrameSearch { public: TTFrameSearch( TTProgressBar* b_bar = NULL ); ~TTFrameSearch(); bool initFrameSearch( TTVideoStream* v_stream ); uint searchFrame( uint ref_frame_pos, uint start_frame_pos ); protected: bool initDecoder(); long compareFrames(); private: TTProgressBar* progress_bar; TTMpeg2Decoder* decoder; QString video_file_name; TTVideoHeaderList* header_list; TTVideoIndexList* index_list; uint current_frame; off64_t file_size; off64_t file_offset; uint8_t* ref_data; uint8_t* com_data; }; #endif //TTFRAMESEARCH_H
[ "tritime@7763a927-590e-0410-8f7f-dbc853b76eaa" ]
[ [ [ 1, 75 ] ] ]
497b790b31219c2e0010c6b7ba8b8ef176e930a3
937c59bea84dfe14cac07ed2e3a706ac765d965e
/Header Files/PictureEx.h
eba7e6891d2014fc74ce52a6552b1a76979de81c
[]
no_license
IDA-RE-things/dvsatucsd
1b73b21644ffa869a0b5dbd36ac1c0cbfa37bce0
dff552ac9c29bca8f5b20b46342fbb6887857915
refs/heads/master
2016-09-05T16:17:08.013350
2010-04-03T22:17:49
2010-04-03T22:17:49
40,741,625
0
0
null
null
null
null
UTF-8
C++
false
false
10,574
h
////////////////////////////////////////////////////////////////////// // PictureEx.cpp: implementation of the CPictureEx class. // // Picture displaying control with support for the following formats: // GIF (including animated GIF87a and GIF89a), 33, BMP, WMF, ICO, CUR // // Written by Oleg Bykov ([email protected]) // Copyright (c) 2001 // // To use CPictureEx, follow these steps: // - place a static control on your dialog (either a text or a bitmap) // - change its identifier to something else (e.g. IDC_MYPIC) // - associate a CStatic with it using ClassWizard // - in your dialog's header file replace CStatic with CPictureEx // (don't forget to #include "PictureEx.h" and add // PictureEx.h and PictureEx.cpp to your project) // - call one of the overloaded CPictureEx::Load() functions somewhere // (OnInitDialog is a good place to start) // - if the preceding Load() succeeded call Draw() // // You can also add the control by defining a member variable of type // CPictureEx, calling CPictureEx::Create (derived from CStatic), then // CPictureEx::Load and CPictureEx::Draw. // // By default, the control initializes its background to COLOR_3DFACE // (see CPictureEx::PrepareDC()). You can change the background by // calling CPictureEx::SetBkColor(COLORREF) after CPictureEx::Load(). // // I decided to leave in the class the functions to write separate frames from // animated GIF to disk. If you want to use them, uncomment #define GIF_TRACING // and an appropriate section in CPictureEx::Load(HGLOBAL, DWORD). These functions // won't be compiled and linked to your project unless you uncomment #define GIF_TRACING, // so you don't have to worry. // // Warning: this code hasn't been subject to a heavy testing, so // use it on your own risk. The author accepts no liability for the // possible damage caused by this code. // // Version 1.0 7 Aug 2001 // Initial release // // Version 1.1 6 Sept 2001 // ATL version of the class // // Version 1.2 14 Oct 2001 // - Fixed a problem with loading GIFs from resources // in MFC-version of the class for multi-modules apps. // Thanks to Ruben Avila-Carretero for finding this out. // // - Got rid of waitable timer in ThreadAnimation() // Now CPictureEx[Wnd] works in Win95 too. // Thanks to Alex Egiazarov and Wayne King for the idea. // // - Fixed a visual glitch of using SetBkColor. // Thanks to Kwangjin Lee for finding this out. // // Version 1.3 10 Nov 2001 // - Fixed a DC leak. One DC leaked per each UnLoad() // (forgot to put a ReleaseDC() in the end of // CPictureExWnd::PrepareDC() function). // // - Now it is possible to set a clipping rectangle using // CPictureEx[Wnd]::SetPaintRect(const LPRECT) function. // The LPRECT parameter tells the class what portion of // a picture should it display. If the clipping rect is // not set, the whole picture is shown. // Thanks to Fabrice Rodriguez for the idea. // // - Added support for Stop/Draw. Now you can Stop() an // animated GIF, then Draw() it again, it will continue // animation from the frame it was stopped on. You can // also know if a GIF is currently playing with the // IsPlaying() function. // // - Got rid of math.h and made m_bExitThread volatile. // Thanks to Piotr Sawicki for the suggestion. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_PICTUREEX_H__0EFE5DE0_7B68_4DB7_8B34_5DC634948438__INCLUDED_) #define AFX_PICTUREEX_H__0EFE5DE0_7B68_4DB7_8B34_5DC634948438__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <vector> //#define GIF_TRACING // uncomment it if you want detailed TRACEs class CPictureEx : public CStatic { public: struct TFrame // structure that keeps a single frame info { IPicture *m_pPicture; // pointer to the interface used for drawing SIZE m_frameSize; SIZE m_frameOffset; UINT m_nDelay; // delay (in 1/100s of a second) UINT m_nDisposal; // disposal method }; #pragma pack(1) // turn byte alignment on enum GIFBlockTypes { BLOCK_UNKNOWN, BLOCK_APPEXT, BLOCK_COMMEXT, BLOCK_CONTROLEXT, BLOCK_PLAINTEXT, BLOCK_IMAGE, BLOCK_TRAILER }; enum ControlExtValues // graphic control extension packed field values { GCX_PACKED_DISPOSAL, // disposal method GCX_PACKED_USERINPUT, GCX_PACKED_TRANSPCOLOR }; enum LSDPackedValues // logical screen descriptor packed field values { LSD_PACKED_GLOBALCT, LSD_PACKED_CRESOLUTION, LSD_PACKED_SORT, LSD_PACKED_GLOBALCTSIZE }; enum IDPackedValues // image descriptor packed field values { ID_PACKED_LOCALCT, ID_PACKED_INTERLACE, ID_PACKED_SORT, ID_PACKED_LOCALCTSIZE }; struct TGIFHeader // GIF header { char m_cSignature[3]; // Signature - Identifies the GIF Data Stream // This field contains the fixed value 'GIF' char m_cVersion[3]; // Version number. May be one of the following: // "87a" or "89a" }; struct TGIFLSDescriptor // Logical Screen Descriptor { WORD m_wWidth; // 2 bytes. Logical screen width WORD m_wHeight; // 2 bytes. Logical screen height unsigned char m_cPacked; // packed field unsigned char m_cBkIndex; // 1 byte. Background color index unsigned char m_cPixelAspect; // 1 byte. Pixel aspect ratio inline int GetPackedValue(enum LSDPackedValues Value); }; struct TGIFAppExtension // application extension block { unsigned char m_cExtIntroducer; // extension introducer (0x21) unsigned char m_cExtLabel; // app. extension label (0xFF) unsigned char m_cBlockSize; // fixed value of 11 char m_cAppIdentifier[8]; // application identifier char m_cAppAuth[3]; // application authentication code }; struct TGIFControlExt // graphic control extension block { unsigned char m_cExtIntroducer; // extension introducer (0x21) unsigned char m_cControlLabel; // control extension label (0xF9) unsigned char m_cBlockSize; // fixed value of 4 unsigned char m_cPacked; // packed field WORD m_wDelayTime; // delay time unsigned char m_cTColorIndex; // transparent color index unsigned char m_cBlockTerm; // block terminator (0x00) public: inline int GetPackedValue(enum ControlExtValues Value); }; struct TGIFCommentExt // comment extension block { unsigned char m_cExtIntroducer; // extension introducer (0x21) unsigned char m_cCommentLabel; // comment extension label (0xFE) }; struct TGIFPlainTextExt // plain text extension block { unsigned char m_cExtIntroducer; // extension introducer (0x21) unsigned char m_cPlainTextLabel; // text extension label (0x01) unsigned char m_cBlockSize; // fixed value of 12 WORD m_wLeftPos; // text grid left position WORD m_wTopPos; // text grid top position WORD m_wGridWidth; // text grid width WORD m_wGridHeight; // text grid height unsigned char m_cCellWidth; // character cell width unsigned char m_cCellHeight; // character cell height unsigned char m_cFgColor; // text foreground color index unsigned char m_cBkColor; // text background color index }; struct TGIFImageDescriptor // image descriptor block { unsigned char m_cImageSeparator; // image separator byte (0x2C) WORD m_wLeftPos; // image left position WORD m_wTopPos; // image top position WORD m_wWidth; // image width WORD m_wHeight; // image height unsigned char m_cPacked; // packed field inline int GetPackedValue(enum IDPackedValues Value); }; #pragma pack() // turn byte alignment off public: BOOL GetPaintRect(RECT *lpRect); BOOL SetPaintRect(const RECT *lpRect); CPictureEx(); virtual ~CPictureEx(); void Stop(); // stops animation void UnLoad(); // stops animation plus releases all resources BOOL IsGIF() const; BOOL IsPlaying() const; BOOL IsAnimatedGIF() const; SIZE GetSize() const; int GetFrameCount() const; COLORREF GetBkColor() const; void SetBkColor(COLORREF clr); // draws the picture (starts an animation thread if needed) // if an animation was previously stopped by Stop(), // continues it from the last displayed frame BOOL Draw(); // loads a picture from a file // i.e. Load(_T("mypic.gif")); BOOL Load(LPCTSTR szFileName); // loads a picture from a global memory block (allocated by GlobalAlloc) // Warning: this function DOES NOT free the global memory, pointed to by hGlobal BOOL Load(HGLOBAL hGlobal, DWORD dwSize); // loads a picture from a program resource // i.e. Load(MAKEINTRESOURCE(IDR_MYPIC),_T("GIFTYPE")); BOOL Load(LPCTSTR szResourceName,LPCTSTR szResourceType); BOOL CPictureEx::Scale(UINT Width, UINT Height); protected: #ifdef GIF_TRACING void EnumGIFBlocks(); void WriteDataOnDisk(CString szFileName, HGLOBAL hData, DWORD dwSize); #endif // GIF_TRACING RECT m_PaintRect; SIZE m_PictureSize; COLORREF m_clrBackground; UINT m_nCurrFrame; UINT m_nDataSize; UINT m_nCurrOffset; UINT m_nGlobalCTSize; BOOL m_bIsGIF; BOOL m_bIsPlaying; volatile BOOL m_bExitThread; BOOL m_bIsInitialized; HDC m_hMemDC; HDC m_hDispMemDC; HBITMAP m_hDispMemBM; HBITMAP m_hDispOldBM; HBITMAP m_hBitmap; HBITMAP m_hOldBitmap; HANDLE m_hThread; HANDLE m_hExitEvent; IPicture * m_pPicture; TGIFHeader * m_pGIFHeader; unsigned char * m_pRawData; TGIFLSDescriptor * m_pGIFLSDescriptor; std::vector<TFrame> m_arrFrames; void ThreadAnimation(); static UINT WINAPI _ThreadAnimation(LPVOID pParam); int GetNextBlockLen() const; BOOL SkipNextBlock(); BOOL SkipNextGraphicBlock(); BOOL PrepareDC(int nWidth, int nHeight); void ResetDataPointer(); enum GIFBlockTypes GetNextBlock() const; UINT GetSubBlocksLen(UINT nStartingOffset) const; HGLOBAL GetNextGraphicBlock(UINT *pBlockLen, UINT *pDelay, SIZE *pBlockSize, SIZE *pBlockOffset, UINT *pDisposal); // Generated message map functions //{{AFX_MSG(CPictureEx) afx_msg void OnDestroy(); afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #endif // !defined(AFX_PICTUREEX_H__0EFE5DE0_7B68_4DB7_8B34_5DC634948438__INCLUDED_)
[ [ [ 1, 307 ] ] ]
27c7d64e46e667f513c459cd20eff494738064c8
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/Learning OpenCV/Chapter 4 - HighGUI/Exercise_4_4.cpp
0e30efef6523a8ed07d4b83258ae495a8335e724
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,610
cpp
/////////////////////////////////////////////// // Date: 2009-10-17 // Author: Yishi Guo // Exercise: 4.4 // Page: 107 // Content: Capture, Frame, Trackbar /////////////////////////////////////////////// #include <cv.h> #include <highgui.h> #include <iostream.h> CvCapture* g_capture = NULL; IplImage* g_frame = NULL; int g_position_value = 0; int g_pause_value = 0; int g_now_frame = 0; int g_frame_count = 1; bool g_pause = false; // "Position" trackbar position // void position_callback( int pos ) { g_now_frame = pos * g_frame_count / 10; cvSetCaptureProperty( g_capture, CV_CAP_PROP_POS_FRAMES, g_now_frame ); if ( g_pause ) { g_frame = cvQueryFrame( g_capture ); cvShowImage( "Exercise 4-4", g_frame ); } } // "Pause" trackbar callback // void pause_callback( int pos ) { if ( pos ) { g_pause = true; } else { g_pause = false; } } // Set the "Position" trackbar position // void set_position( CvCapture* capture ) { ++g_now_frame; int pos = g_now_frame * 10 / g_frame_count; // For debug // cout << "Pos: " << pos << " Now: " << g_now_frame // << " Count: " << g_frame_count << endl; cvSetTrackbarPos( "Position", "Exercise 4-4", pos ); } int main( int argc, char** argv ) { if ( argc >= 2 ) { g_capture = cvCreateFileCapture( argv[1] ); // Get capture if ( !g_capture ) { return -1; } g_frame_count = (int)cvGetCaptureProperty( // Get frame count g_capture, CV_CAP_PROP_FRAME_COUNT ); cvNamedWindow( "Exercise 4-4", CV_WINDOW_AUTOSIZE ); cvCreateTrackbar( // Create "Position" trackbar "Position", "Exercise 4-4", &g_position_value, 10, position_callback ); cvCreateTrackbar( // Create "Pause" trackbar "Pause", "Exercise 4-4", &g_pause_value, 1, pause_callback ); char down_key; while ( 1 ) { if ( !g_pause ) { // If not pause g_frame = cvQueryFrame( g_capture ); set_position( g_capture ); } if ( !g_frame ) break; cvShowImage( "Exercise 4-4", g_frame ); down_key = cvWaitKey(33); if ( down_key == 27 ) { break; } else if ( down_key == ' ' ) { int pos = 0; if ( g_pause ) { g_pause = false; pos = 0; } else { g_pause = true; pos = 1; } cvSetTrackbarPos( "Pause", "Exercise 4-4", pos ); } } cvReleaseImage( &g_frame ); cvReleaseCapture( &g_capture ); cvDestroyWindow( "Exercise 4-4" ); return 0; } return -1; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 136 ] ] ]
29032eecbc3285d9379731960a91cb5a93651b39
2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4
/OUAN/OUAN/Src/Core/MainMenuState.cpp
eafb4e209dc2e3a49833347518801c9a9bf2683e
[]
no_license
juanjmostazo/once-upon-a-night
9651dc4dcebef80f0475e2e61865193ad61edaaa
f8d5d3a62952c45093a94c8b073cbb70f8146a53
refs/heads/master
2020-05-28T05:45:17.386664
2010-10-06T12:49:50
2010-10-06T12:49:50
38,101,059
1
1
null
null
null
null
UTF-8
C++
false
false
7,968
cpp
#include "OUAN_Precompiled.h" #include "MainMenuState.h" #include "../Application.h" #include "../Graphics/RenderSubsystem.h" #include "../GUI/GUISubsystem.h" #include "../GUI/GUIMainMenu.h" #include "../Utils/Utils.h" #include "GameStateManager.h" #include "GameRunningState.h" #include "GameOptionsState.h" #include "LevelLoadingState.h" #include "ExtrasState.h" #include "../Audio/AudioDefs.h" #include "../Audio/AudioSubsystem.h" using namespace OUAN; /// Default constructor MainMenuState::MainMenuState() :GameState() ,mTransitioningToLoading(false) ,mCurrentCloudFrame(0) ,mCurrentStarsFrame(0) ,mSkipFrame(false) { mMusicChannel=mClickChannel-1; } /// Destructor MainMenuState::~MainMenuState() { } /// init main menu's resources void MainMenuState::init(ApplicationPtr app) { GameState::init(app); mApp->mBackToMenu=false; //mApp->getGUISubsystem()->loadScheme("OUANLookSkin.scheme","OUANLook"); mGUI= BOOST_PTR_CAST(GUIMainMenu,mApp->getGUISubsystem()->createGUI(GUI_LAYOUT_MAINMENU)); mGUI->initGUI(shared_from_this()); initRects(); if (!mApp->getAudioSubsystem()->isLoaded("MUSIC")) mApp->getAudioSubsystem()->load("MUSIC",AUDIO_RESOURCES_GROUP_NAME); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); mApp->getAudioSubsystem()->pauseChannelGroup(SM_CHANNEL_MUSIC_GROUP,false); if (!mApp->getAudioSubsystem()->isMusicPlaying(mMusicChannel)) mApp->getAudioSubsystem()->playMusic("MUSIC",mMusicChannel,true); } void MainMenuState::initRects() { Utils::TTexturedRectangleDesc desc; desc.leftCorner=desc.bottomCorner=-1.0; desc.rightCorner=desc.topCorner=1.0; desc.renderQueue=Ogre::RENDER_QUEUE_BACKGROUND; desc.axisAlignedBox=Ogre::AxisAlignedBox::BOX_INFINITE; desc.materialName=MAINMENU_BG_MATERIAL_NAME; desc.materialGroup=MAINMENU_GROUP; desc.textureName=MAINMENU_BG_IMG; desc.sceneNodeName=MAINMENU_BG_SCREENNODE; Utils::createRectangle(desc,mScreen,mApp->getRenderSubsystem()); desc.leftCorner=desc.bottomCorner=-1.0; desc.rightCorner=desc.topCorner=1.0; desc.renderQueue=Ogre::RENDER_QUEUE_3; desc.axisAlignedBox=Ogre::AxisAlignedBox::BOX_INFINITE; desc.materialName=MAINMENU_STARS_MATERIAL_NAME; desc.materialGroup=MAINMENU_GROUP; desc.textureName=MAINMENU_STARS_IMG; desc.sceneNodeName=MAINMENU_STARS_SCREENNODE; desc.texAnimNumFrames=MAINMENU_STARS_FRAMENUM; desc.textureAnimation=true; desc.texAnimDuration=2.0; desc.alphaBlending=true; Utils::createRectangle(desc,mStars,mApp->getRenderSubsystem()); desc.leftCorner=desc.bottomCorner=-1.0; desc.rightCorner=desc.topCorner=1.0; desc.renderQueue=Ogre::RENDER_QUEUE_9; desc.axisAlignedBox=Ogre::AxisAlignedBox::BOX_INFINITE; desc.materialName=MAINMENU_LOGO_MATERIAL_NAME; desc.materialGroup=MAINMENU_GROUP; desc.textureName=MAINMENU_LOGO_IMG; desc.sceneNodeName=MAINMENU_LOGO_SCREENNODE; desc.textureAnimation=false; desc.alphaBlending=true; Utils::createRectangle(desc,mLogo,mApp->getRenderSubsystem()); desc.leftCorner=desc.bottomCorner=-1.0; desc.rightCorner=desc.topCorner=1.0; desc.renderQueue=Ogre::RENDER_QUEUE_MAX; desc.axisAlignedBox=Ogre::AxisAlignedBox::BOX_INFINITE; desc.materialName=MAINMENU_CLOUDS_MATERIAL_NAME; desc.materialGroup=MAINMENU_GROUP; desc.textureName=MAINMENU_CLOUDS_IMG; desc.sceneNodeName=MAINMENU_CLOUDS_SCREENNODE; desc.texAnimNumFrames=MAINMENU_CLOUDS_FRAMENUM; desc.textureAnimation=true; desc.texAnimDuration=0; Utils::createRectangle(desc,mClouds,mApp->getRenderSubsystem()); mClouds->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setCurrentFrame(0); mTransitioningToLoading=false; } void MainMenuState::destroyRects() { Utils::destroyRectangle(mScreen,mApp->getRenderSubsystem()); Utils::destroyRectangle(mStars,mApp->getRenderSubsystem()); Utils::destroyRectangle(mClouds,mApp->getRenderSubsystem()); Utils::destroyRectangle(mLogo,mApp->getRenderSubsystem()); } /// Clean up main menu's resources void MainMenuState::cleanUp() { GameState::cleanUp(); while(mApp->getAudioSubsystem()->isSfxPlaying(mClickChannel)); //Unsubscribe from events mGUI->destroy(); if (mMusicChannel!=-1) { mApp->getAudioSubsystem()->stopMusic(mMusicChannel); } mApp->getAudioSubsystem()->unload("MUSIC"); mApp->getAudioSubsystem()->unload("CLICK"); mApp->getGUISubsystem()->destroyGUI(); //mApp->getGUISubsystem()->unbindAllEvents(); destroyRects(); } /// pause state void MainMenuState::pause() { //mApp->getGUISubsystem()->hideGUI(); mGUI->destroy(); mApp->getGUISubsystem()->destroyGUI(); destroyRects(); } /// resume state void MainMenuState::resume() { GameState::resume(); //mApp->getGUISubsystem()->showGUI(); mGUI= BOOST_PTR_CAST(GUIMainMenu,mApp->getGUISubsystem()->createGUI(GUI_LAYOUT_MAINMENU)); mGUI->initGUI(shared_from_this()); if (!mApp->getAudioSubsystem()->isLoaded("MUSIC")) mApp->getAudioSubsystem()->load("MUSIC",AUDIO_RESOURCES_GROUP_NAME); if (!mApp->getAudioSubsystem()->isLoaded("CLICK")) mApp->getAudioSubsystem()->load("CLICK",AUDIO_RESOURCES_GROUP_NAME); if (!mApp->getAudioSubsystem()->isMusicPlaying(mMusicChannel)) mApp->getAudioSubsystem()->playMusic("MUSIC",mMusicChannel,true); initRects(); } /// process input events /// @param app the parent application void MainMenuState::handleEvents() { int pad; int key; if (mApp->isPressedJump(&pad,&key)) { mApp->cycleLanguage(); mGUI->setStrings(); } } /// Update game according to the current state /// @param app the parent app void MainMenuState::update(long elapsedTime) { GameState::update(elapsedTime); mApp->getAudioSubsystem()->update(elapsedTime*0.000001); Ogre::TextureUnitState* tex=mClouds->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0); if (tex && mClouds->isVisible()) { int currentFrame=tex->getCurrentFrame(); if (mTransitioningToLoading) { if (currentFrame-1==0) { gotoPlay(); } else if (!mSkipFrame) { tex->setCurrentFrame(currentFrame-1); } } else { if (currentFrame+1==tex->getNumFrames()) { mClouds->setVisible(false); } else if (!mSkipFrame) { tex->setCurrentFrame(currentFrame+1); } } } mSkipFrame=!mSkipFrame;//HACK TO KEEP THE ANIMATION RUNNING LONGER } void MainMenuState::gotoPlay() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); //TODO: Change to ProfileSelectState when it's implemented //GameStatePtr nextState(new GameRunningState()); //GameStatePtr nextState(new LevelLoadingState()); LevelLoadingStatePtr levelLoadingState(new LevelLoadingState()); levelLoadingState->setLevelFileName(LEVEL_2); mApp->getGameStateManager()->changeState(levelLoadingState,mApp); } void MainMenuState::gotoOptions() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); GameStatePtr nextState(new GameOptionsState()); //mApp->getGameStateManager()->changeState(nextState,mApp); mApp->getGameStateManager()->pushState(nextState,mApp); } void MainMenuState::gotoExtras() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); GameStatePtr nextState(new ExtrasState()); //mApp->getGameStateManager()->changeState(nextState,mApp); mApp->getGameStateManager()->pushState(nextState,mApp); } void MainMenuState::quit() { mApp->getAudioSubsystem()->playSound("CLICK",mClickChannel); mApp->mExitRequested=true; } void MainMenuState::startTransitionToLoading() { mTransitioningToLoading=true; mClouds->setVisible(true); mClouds->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setCurrentFrame(mClouds->getMaterial()->getTechnique(0)->getPass(0)->getTextureUnitState(0)->getNumFrames()-1); }
[ "ithiliel@1610d384-d83c-11de-a027-019ae363d039", "juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039", "wyern1@1610d384-d83c-11de-a027-019ae363d039" ]
[ [ [ 1, 35 ], [ 37, 38 ], [ 41, 128 ], [ 131, 131 ], [ 133, 134 ], [ 136, 136 ], [ 138, 138 ], [ 141, 143 ], [ 145, 160 ], [ 162, 179 ], [ 184, 184 ], [ 186, 188 ], [ 190, 193 ], [ 195, 229 ], [ 231, 231 ], [ 233, 237 ], [ 239, 239 ], [ 242, 248 ], [ 250, 256 ], [ 258, 269 ] ], [ [ 36, 36 ], [ 39, 40 ], [ 129, 130 ], [ 132, 132 ], [ 135, 135 ], [ 137, 137 ], [ 139, 140 ], [ 144, 144 ], [ 180, 183 ], [ 189, 189 ], [ 194, 194 ], [ 230, 230 ], [ 232, 232 ], [ 240, 241 ], [ 249, 249 ], [ 257, 257 ] ], [ [ 161, 161 ], [ 185, 185 ], [ 238, 238 ] ] ]
af5770389254c2e407f591d6bf20835cc070c10c
68bfdfc18f1345d1ff394b8115681110644d5794
/Examples/Example01/Model.h
6f654e8ae21bd1b362b59dce7c00b1bc2f4912b2
[]
no_license
y-gupta/glwar3
43afa1efe475d937ce0439464b165c745e1ec4b1
bea5135bd13f9791b276b66490db76d866696f9a
refs/heads/master
2021-05-28T12:20:41.532727
2010-12-09T07:52:12
2010-12-09T07:52:12
32,911,819
1
0
null
null
null
null
UTF-8
C++
false
false
2,319
h
#pragma once //+----------------------------------------------------------------------------- //| Included files //+----------------------------------------------------------------------------- #include "Misc.h" //+----------------------------------------------------------------------------- //| Pre-declared classes //+----------------------------------------------------------------------------- class MODEL_GEOSET; class MODEL_TEXTURE; //+----------------------------------------------------------------------------- //| Model info data structure //+----------------------------------------------------------------------------- struct MODEL_INFO_DATA { MODEL_INFO_DATA() { Version = MODEL_DEFAULT_VERSION; Name = "Name"; AnimationFile = ""; BlendTime = 150; } DWORD Version; std::string Name; std::string AnimationFile; EXTENT Extent; INT BlendTime; }; //+----------------------------------------------------------------------------- //| Model data structure //+----------------------------------------------------------------------------- struct MODEL_DATA { MODEL_DATA() { //Empty } MODEL_INFO_DATA Info; SIMPLE_CONTAINER<MODEL_TEXTURE*> TextureContainer; SIMPLE_CONTAINER<MODEL_GEOSET*> GeosetContainer; }; //+----------------------------------------------------------------------------- //| Model class //+----------------------------------------------------------------------------- class MODEL { public: CONSTRUCTOR MODEL(); DESTRUCTOR ~MODEL(); VOID Clear(); MODEL_DATA& Data(); VOID Render(INT TimeDifference); BOOL AddTexture(MODEL_TEXTURE* Texture); BOOL AddGeoset(MODEL_GEOSET* Geoset, BOOL Imported = FALSE); protected: MODEL_DATA ModelData; FLOAT BoundsRadius; VECTOR3 BoundsCenter; }; //+----------------------------------------------------------------------------- //| Global objects //+----------------------------------------------------------------------------- extern MODEL Model; //+----------------------------------------------------------------------------- //| Post-included files //+----------------------------------------------------------------------------- #include "Graphics.h" #include "ModelTexture.h" #include "ModelGeoset.h"
[ "sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83" ]
[ [ [ 1, 95 ] ] ]
2c66b5fd6fd2a22b675988e18adc1b775b8e39f8
0b66a94448cb545504692eafa3a32f435cdf92fa
/branches/kyr/cbear.berlios.de/windows/registry/hkey.hpp
874b4c368ed0d9ccacec25060f91f9ff7e82f355
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
7,649
hpp
#ifndef CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_HKEY_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_HKEY_HPP_INCLUDED #include <Winreg.h> #include <cbear.berlios.de/range/fill.hpp> #include <cbear.berlios.de/policy/main.hpp> #include <cbear.berlios.de/windows/base.hpp> #include <cbear.berlios.de/windows/lpstr.hpp> #include <cbear.berlios.de/windows/exception.hpp> #include <cbear.berlios.de/windows/select.hpp> #include <cbear.berlios.de/windows/security_attributes.hpp> #include <cbear.berlios.de/windows/registry/disposition.hpp> #include <cbear.berlios.de/windows/registry/sam.hpp> #include <cbear.berlios.de/windows/registry/options.hpp> #include <cbear.berlios.de/windows/registry/value.hpp> // RegCloseKey, ... #pragma comment(lib, "advapi32.lib") namespace cbear_berlios_de { namespace windows { namespace registry { class hkey: public policy::wrap<hkey, ::HKEY> { typedef policy::wrap<hkey, ::HKEY> wrap_type; public: BOOST_STATIC_ASSERT(sizeof(int)>=sizeof(internal_type)); enum enumeration_type { classes_root = reinterpret_cast<std::ptrdiff_t>(HKEY_CLASSES_ROOT), current_user = reinterpret_cast<std::ptrdiff_t>(HKEY_CURRENT_USER), local_machine = reinterpret_cast<std::ptrdiff_t>(HKEY_LOCAL_MACHINE), users = reinterpret_cast<std::ptrdiff_t>(HKEY_USERS), performance_data = reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_DATA), //performance_text = // reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_TEXT), //performance_nlstext = // reinterpret_cast<std::ptrdiff_t>(HKEY_PERFORMANCE_NLSTEXT), current_config = reinterpret_cast<std::ptrdiff_t>(HKEY_CURRENT_CONFIG), dyn_data = reinterpret_cast<std::ptrdiff_t>(HKEY_DYN_DATA), }; typedef wrap_type::internal_type internal_type; hkey() {} hkey(enumeration_type X): wrap_type(internal_type(X)) {} template<class Char> class create_options { public: basic_lpstr<const Char> class_; registry::options options; registry::sam sam; windows::security_attributes security_attributes; create_options() {} create_options( basic_lpstr<const Char> class_, registry::options options, registry::sam sam, windows::security_attributes security_attributes): class_(class_), options(options), sam(sam), security_attributes(security_attributes) { } }; class create_result; template<class Char> create_result create( basic_lpstr<const Char> SubKey, const create_options<Char> &Options) const { create_result Result; exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegCreateKeyEx)( //HKEY hKey, this->internal(), // LPCTSTR lpSubKey, SubKey.get(), //DWORD Reserved, 0, //LPTSTR lpClass, const_cast<Char *>(Options.class_.get()), //DWORD dwOptions, Options.options.internal(), //REGSAM samDesired, Options.sam.internal(), //LPSECURITY_ATTRIBUTES lpSecurityAttributes, Options.security_attributes.get(), //PHKEY phkResult, &Result.hkey.internal(), //LPDWORD lpdwDisposition, &Result.disposition.internal())); return Result; } // See // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/regconnectregistry.asp template<class Char> hkey connect(const basic_lpstr<const Char> &X) const { hkey Result; exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegConnectRegistry)( X.internal(), this->internal(), &Result.internal())); return Result; } // See // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/regopenkeyex.asp template<class Char> hkey open(const basic_lpstr<const Char> &SubKey, sam Sam) const { hkey Result; exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegOpenKeyEx)( this->internal(), SubKey.get(), 0, Sam.internal(), &Result.internal())); return Result; } template<class Char> void delete_(const basic_lpstr<const Char> &X) const { exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegDeleteKey)( this->internal(), X.get())); } void flush() const { exception::throw_if(::RegFlushKey(this->internal())); } void close() const { exception::throw_if(::RegCloseKey(this->internal())); } template<class Char> void query_value( basic_lpstr<Char const> const &Value, data<Char> &Data) { typedef data<Char> data_type; typedef typename data_type::properties_type properties_type; properties_type Properties = data_type::properties(Data); data_id_type Id = Properties.id; dword_t Size = Properties.size; exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegQueryValueEx)( this->internal(), Value.get(), 0, &Id.get(), 0, &Size)); switch(Id.get()) { case data_type::id_type::none: Data = data_type(); break; case data_type::id_type::dword: Data = data_type(dword_t()); break; case data_type::id_type::qword: Data = data_type(ulonglong_t()); break; case data_type::id_type::sz: Data = data_type(data_type::string_type(range::make_fill( Char(0), Size / sizeof(Char) - 1))); break; default: BOOST_ASSERT(false); } Properties = data_type::properties(Data); BOOST_ASSERT(Size == Properties.size); exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegQueryValueEx)( this->internal(), Value.get(), 0, &Id.get(), Properties.begin, &Size)); } /* // Client: Requires Windows Vista or Windows XP Pro x64 // Server: Requires Windows Server "Longhorn" or Windows Server 2003 SP1. template<class Char> void get_value( basic_lpstr<Char const> const &SubKey, basic_lpstr<Char const> const &Value, data<Char> &Data) { typedef data<Char> data_type; typedef typename data_type::properties_type properties_type; properties_type Properties = data_type::properties(Data); data_id_type Type = Properties.id; dword_t Size = Properties.size; exception::throw_if(CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, RegGetValue)( this->internal(), SubKey.get(), Value.get(), Properties.flags.c_in(), &Type.get(), Properties.begin, &Size)); } */ // See // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/regsetvalueex.asp template<class Char, class DataType> void set_value( const basic_lpstr<const Char> &ValueName, DataType &Data) const { typedef data<Char> data_type; typedef typename data_type::properties_type properties_type; properties_type Properties = data_type::properties(Data); exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegSetValueEx)( this->internal(), ValueName.get(), 0, Properties.id.get(), Properties.begin, Properties.size)); } template<class Char> void set_value(value<Char> &Value) const { this->set_value<Char>(Value.first, Value.second); } template<class Char> void set_value(data<Char> &Data) const { this->set_value(basic_lpstr<const Char>(), Data); } template<class Char> void delete_value(const basic_lpstr<const Char> &ValueName) { exception::throw_if( CBEAR_BERLIOS_DE_WINDOWS_FUNCTION(Char, ::RegDeleteValue)( this->internal(), ValueName.get())); } void delete_value() { this->delete_value(lpcstr_t()); } }; class hkey::create_result { public: hkey hkey; disposition disposition; }; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 285 ] ] ]
c8b16a87fee76938e97b67d8b4714ea7ce5a57b8
fad6f9883d4ad2686c196dc532a9ecb9199500ee
/NXP-LPC/CommTest/LogEx/LogData.h
333253764f523a79e659f9c2a3e4da68edcf1116
[]
no_license
aquarius20th/nxp-lpc
fe83d6a140d361a1737d950ff728c6ea9a16a1dd
4abfb804daf0ac9c59bd90d879256e7a3c1b2f30
refs/heads/master
2021-01-10T13:54:40.237682
2009-12-22T14:54:59
2009-12-22T14:54:59
48,420,260
0
0
null
null
null
null
GB18030
C++
false
false
1,895
h
#include <queue> #include "BDBWrapper.h" #include "SQLite.h" #include "boost/memory.hpp" const int MAX_LOG_STR_LINE = 1024; const int MAX_NAME_LEN = 128; const int MAX_STR_LEN = 256; const int WRITE_SQL_NUM = 100; const int WRITE_SQL_TIME = 8000; class CLogStr { public: CLogStr() { memset(&st,0,sizeof(SYSTEMTIME)); // szLogStr.Empty(); // szModuleName.Empty(); memset(szModuleName,0,sizeof(TCHAR)*MAX_NAME_LEN); memset(szLogStr,0,sizeof(TCHAR)*MAX_STR_LEN); nStrType = 0; } SYSTEMTIME st; int nStrType; TCHAR szModuleName[MAX_NAME_LEN]; TCHAR szLogStr[MAX_STR_LEN]; void BuildSQL( CString & szSQL ); }; class CLogDataMgr { friend UINT __stdcall MainTask (LPVOID lpParam); public: CLogDataMgr( ); ~CLogDataMgr( ); public: bool RegisterLog(TCHAR *szModuleName ); void UnregisterLog( TCHAR *szModuleName ); bool InitMgr( TCHAR*szFileName = NULL); void ExitMgr(); private: void GetExePathName(CString & strPathName,CString &szDirName,CString &strPlugInName); void Work( bool bForceWrite = false); protected: SQLite::Database m_db; //注册过的应该在此列表中定义 CStringArray m_arrModuleList; void FreeMem( ); CWinThread *m_pWorkTsk; HANDLE m_hWorkTsk; HANDLE m_hStopWorkEvent; HANDLE m_hDupWorkTaskHandle; DWORD m_dwWriteSQL; boost::memory::pool m_LogStrPool ; public: BOOL LogString( TCHAR * lpszModuleName, TCHAR * lpszTxt ,int nStrType); BOOL LogString( TCHAR * lpszModuleName,SYSTEMTIME st, TCHAR * lpszTxt ,int nStrType); int GetLogString(CLogStr *pBuff ); int GetLogStrCnt( ); private: CLogStr* Allocate(); BOOL Release (CLogStr *pBuff); void FreeBuff( ); std::deque <CLogStr *> m_arrBuffer; std::deque <CLogStr *> m_arrFreeBuffer; }; void WaitForThreadToTerminate(HANDLE hThread);
[ "lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2" ]
[ [ [ 1, 86 ] ] ]
e52bba1034b05c1a959bfc6f2fa7eb88d50e7c7c
3ec3b97044e4e6a87125470cfa7eef535f26e376
/cltatman-mountain_valley/code/Source/DustParticleComponent.cpp
9901f8e2c39b57524cef103d47d664e2de67b3ae
[]
no_license
strategist922/TINS-Is-not-speedhack-2010
6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af
718b9d037606f0dbd9eb6c0b0e021eeb38c011f9
refs/heads/master
2021-01-18T14:14:38.724957
2010-10-17T14:04:40
2010-10-17T14:04:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,280
cpp
#include <game/DustParticleComponent.hpp> #include <Component.h> #include <Game.hpp> DustParticleComponent::DustParticleComponent() : Component( "DustParticleComponent" ) { setup = false; angle = -2.3; speed = double( rand() % 400 ) / 100.0 + 0.5; entered = false; } void DustParticleComponent::update() { if( !setup ) { double startX,startY; if( rand() % 2 == 1 ) { double a = game.camera.x - 20, b = game.camera.x + game.width; startX = double( rand() % int( b - a ) ) + a; a = game.camera.y - 20; b = game.camera.y; startY = double( rand() % int( b - a ) ) + a; } else { double a = game.camera.x - 20, b = game.camera.x; startX = double( rand() % int( b - a ) ) + a; a = game.camera.y; b = game.camera.y + game.height; startY = double( rand() % int( b - a ) ) + a; } game.level.roster.get( parent ).x = startX; game.level.roster.get( parent ).y = startY; game.level.roster.get( parent ).z = double( rand() % 500 ) / 100.0 + 0.1; setup = true; } game.level.roster.get( parent ).x -= cos( angle ) * speed; game.level.roster.get( parent ).y -= sin( angle ) * speed; double parentX = game.level.roster.get( parent ).x, parentY = game.level.roster.get( parent ).y; if( !entered ) if( parentX > 0 && parentX < game.camera.x + game.width && parentY > 0 && parentY < game.camera.y + game.height ) entered = true; if( entered ) { if( parentX > ( game.camera.x + game.width ) ) game.level.roster.get( parent ).x -= game.width; else if( parentX < game.camera.x ) game.level.roster.get( parent ).x += game.width; if( parentY > ( game.camera.y + game.height ) ) game.level.roster.get( parent ).y -= game.height; else if( parentY < game.camera.y ) game.level.roster.get( parent ).y += game.height; } if( angle < -1.8 ) angle += double( rand() % 100 ) / 1500.0; if( angle > -2.3 ) angle -= double( rand() % 100 ) / 1500.0; if( speed < 5.0 ) speed += double( rand() % 100 ) / 3000.0; if( speed > 1.0 ) speed -= double( rand() % 100 ) / 3000.0; }
[ [ [ 1, 88 ] ] ]
0362df1b2257a30197c62e889d324e769fc37c58
f66e343bd16f5dd4c2652c2f8753efd90fb4e813
/ext/Blob.h
bad53fb1a27e8ac1e65815e94869643a1861af1e
[]
no_license
footprint4me/rcapdissector
7046307f9053fe515a9a0b5c6212a5f4d0e5c1c1
399a2da4229f8f371a8c3f4c88fa99ce1985a0eb
refs/heads/master
2021-01-14T10:28:15.490402
2010-11-07T17:47:42
2010-11-07T17:47:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,501
h
#pragma once #include "RubyAndShit.h" #include "rcapdissector.h" /** Ruby extension object that wraps the wireshark data_source, which is effectively a named blob where the blob contents are exposed as tvb's, which are roughly akin to the mbuf's in the BSD and Linux network stacks. For applications that need access to the raw packet, or (most likely) the reassembled payload of a number of TCP segments, this type comes in handy */ class Blob { public: static VALUE createClass(); /** Creates a new Blob object */ static VALUE createBlob(VALUE packet, data_source* ds); VALUE getRubyWrapper() const { return _self; } const data_source* getDataSource() const { return _ds; } private: Blob(void); virtual ~Blob(void); /*@ Methods implementing the Blob Ruby object methods */ static void free(void* p); static void mark(void* p); static VALUE alloc(VALUE klass); static VALUE initialize(VALUE self, VALUE packetObject); static VALUE init_copy(VALUE copy, VALUE orig); static VALUE name(VALUE self); static VALUE value(VALUE self); static VALUE length(VALUE self); /*@ Instance methods that actually perform the Blob-specific work */ void mark(); public: //Public to avoid duplicating the Ruby wrapper around the name string when adding to the hash VALUE getName(); private: VALUE getValue(); VALUE getLength(); VALUE _self; data_source* _ds; VALUE _rubyName; VALUE _rubyValue; VALUE _rubyLength; };
[ [ [ 1, 58 ] ] ]
701a2663ac39282cc3485c17cb7e133b096692bb
76ea17bc9bc52ae653bd203dd6716fd1e965a8c9
/libnge0.2/src/helper/win_private/main.cpp
394ee26e29517497a91001375bc1743fd49cd084
[]
no_license
eickegao/avgscript
1e78cc09b8c52e5ee9b3be48b81ef5b128fef269
75e75b8c5597b673855b91e6e1bd87c5c60b8c04
refs/heads/master
2016-09-08T00:32:29.508547
2009-01-12T08:40:08
2009-01-12T08:40:08
33,953,223
0
0
null
null
null
null
GB18030
C++
false
false
1,117
cpp
#include "CFileSystem_win.h" int main(int argc,char* argv[]) { CFileList * dir_files = new CFileList; CFileSystem::GetDirFiles(".",dir_files); printf("1 目录文件访问测试 共%d个目录或文件\n",dir_files->size()); for (int i =0 ;i<dir_files->size();i++) { if(!(*dir_files)[i]->IsDirectory()) printf("文件: %s\n",(*dir_files)[i]->m_filename.c_str()); else printf("目录: %s\n",(*dir_files)[i]->m_filename.c_str()); } //拷贝测试。 printf("2 文件拷贝测试\n"); printf("文件拷贝%s\n",CFileSystem::CopyFile("main.cpp","main.bak")==true?"成功":"失败"); printf("3 目录拷贝测试\n"); printf("目录拷贝1%s\n",CFileSystem::CopyDir( "Debug", "Debug1" )==true?"成功":"失败"); printf("目录拷贝2%s\n",CFileSystem::CopyDir( "Debug", "Debug2" )==true?"成功":"失败"); printf("4 目录删除测试,请按回车键继续....\n"); getchar(); printf("目录删除%s\n",CFileSystem::DeleteDir("Debug2" )==true?"成功":"失败"); printf("测试结束\n"); CFileSystem::Rename("main.bak","main.bak2"); //getchar(); return 1; }
[ "pspbter@7305fedb-903f-0410-a37f-9f94d3351015" ]
[ [ [ 1, 30 ] ] ]
99d72a0eeb9f37885da07ee15a9a58bce2f5886f
ed6f03c2780226a28113ba535d3e438ee5d70266
/src/printout.cpp
b402b376d8aec482b7bff8a8c56d1fe770d0909c
[]
no_license
snmsts/wxc
f06c0306d0ff55f0634e5a372b3a71f56325c647
19663c56e4ae2c79ccf647d687a9a1d42ca8cb61
refs/heads/master
2021-01-01T05:41:20.607789
2009-04-08T09:12:08
2009-04-08T09:12:08
170,876
4
1
null
null
null
null
UTF-8
C++
false
false
10,621
cpp
#include "wrapper.h" /*----------------------------------------------------------------------------- Special wxPrintout class that sends events. -----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- new event types -----------------------------------------------------------------------------*/ BEGIN_DECLARE_EVENT_TYPES() DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_BEGIN, 2000) DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_END, 2001 ) DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_BEGIN_DOC, 1002 ) DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_END_DOC, 1003 ) DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_PREPARE, 1004 ) DECLARE_LOCAL_EVENT_TYPE(wxEVT_PRINT_PAGE, 1005 ) END_DECLARE_EVENT_TYPES() DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_BEGIN ) DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_END ) DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_BEGIN_DOC ) DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_END_DOC ) DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_PREPARE ) DEFINE_LOCAL_EVENT_TYPE( wxEVT_PRINT_PAGE ) extern "C" { EWXWEXPORT(int,expEVT_PRINT_BEGIN)() { return wxEVT_PRINT_BEGIN; } //EWXWCONSTANTINT(EVT_PRINT_BEGIN,wxEVT_PRINT_BEGIN) EWXWEXPORT(int,expEVT_PRINT_BEGIN_DOC)() { return wxEVT_PRINT_BEGIN_DOC; } //EWXWCONSTANTINT(EVT_PRINT_BEGIN_DOC,wxEVT_PRINT_BEGIN_DOC) EWXWEXPORT(int,expEVT_PRINT_END)() { return wxEVT_PRINT_END; } //EWXWCONSTANTINT(EVT_PRINT_END,wxEVT_PRINT_END) EWXWEXPORT(int,expEVT_PRINT_END_DOC)() { return wxEVT_PRINT_END_DOC; } //EWXWCONSTANTINT(EVT_PRINT_END_DOC,wxEVT_PRINT_END_DOC) EWXWEXPORT(int,expEVT_PRINT_PREPARE)() { return wxEVT_PRINT_PREPARE; } //EWXWCONSTANTINT(EVT_PRINT_PREPARE,wxEVT_PRINT_PREPARE) EWXWEXPORT(int,expEVT_PRINT_PAGE)() { return wxEVT_PRINT_PAGE; } //EWXWCONSTANTINT(EVT_PRINT_PAGE,wxEVT_PRINT_PAGE) } /*----------------------------------------------------------------------------- Printout and events -----------------------------------------------------------------------------*/ class wxcPrintout : public wxPrintout { private: DECLARE_DYNAMIC_CLASS(wxcPrintout) protected: int m_startPage; int m_endPage; int m_fromPage; int m_toPage; wxEvtHandler* m_evtHandler; public: wxcPrintout() : wxPrintout() {}; wxcPrintout( const wxString& title ); ~wxcPrintout(); void SetPageLimits( int startPage, int endPage, int fromPage, int toPage ); wxEvtHandler* GetEvtHandler(); /* virtual members */ void GetPageInfo( int* startPage, int* endPage, int* fromPage, int* toPage ); bool OnBeginDocument( int startPage, int endPage ); void OnEndDocument(); void OnBeginPrinting(); void OnEndPrinting(); void OnPreparePrinting(); bool OnPrintPage( int page ); bool HasPage( int page ); }; IMPLEMENT_DYNAMIC_CLASS(wxcPrintout, wxPrintout) class wxcPrintEvent : public wxEvent { private: DECLARE_DYNAMIC_CLASS(wxcPrintEvent) private: wxcPrintout* m_printOut; int m_page; int m_lastPage; bool m_continue; public: wxcPrintEvent() : wxEvent() {}; wxcPrintEvent( const wxcPrintEvent& printEvent ); // copy constructor wxcPrintEvent( wxEventType evtType, int id, wxcPrintout* printOut, int page, int lastPage ); wxEvent* Clone() const { return new wxcPrintEvent(*this); } wxcPrintout* GetPrintout(); int GetPage(); int GetEndPage(); bool GetContinue(); void SetContinue( bool cont ); void SetPageLimits( int startPage, int endPage, int fromPage, int toPage ); }; IMPLEMENT_DYNAMIC_CLASS(wxcPrintEvent, wxEvent) /*----------------------------------------------------------------------------- Print events -----------------------------------------------------------------------------*/ wxcPrintEvent::wxcPrintEvent( wxEventType evtType, int id, wxcPrintout* printOut, int page, int lastPage ) : wxEvent( id, evtType ) { m_printOut = printOut; m_page = page; m_lastPage = lastPage; m_continue = true; } wxcPrintEvent::wxcPrintEvent( const wxcPrintEvent& printEvent ) : wxEvent( printEvent ) { m_printOut = printEvent.m_printOut; m_page = printEvent.m_page; m_lastPage = printEvent.m_lastPage; m_continue = printEvent.m_continue; } wxcPrintout* wxcPrintEvent::GetPrintout() { return m_printOut; } int wxcPrintEvent::GetPage() { return m_page; } int wxcPrintEvent::GetEndPage() { return m_lastPage; } bool wxcPrintEvent::GetContinue() { return m_continue; } void wxcPrintEvent::SetContinue( bool cont ) { m_continue = cont; } void wxcPrintEvent::SetPageLimits( int startPage, int endPage, int fromPage, int toPage ) { if (m_printOut) { m_printOut->SetPageLimits( startPage, endPage, fromPage, toPage ); } } /*----------------------------------------------------------------------------- Printout -----------------------------------------------------------------------------*/ wxcPrintout::wxcPrintout( const wxString& title ) : wxPrintout( title ) { m_startPage = 1; m_endPage = 32000; m_fromPage = 1; m_toPage = 1; m_evtHandler = new wxEvtHandler(); } wxcPrintout::~wxcPrintout() { if (m_evtHandler) delete m_evtHandler; } wxEvtHandler* wxcPrintout::GetEvtHandler() { return m_evtHandler; } void wxcPrintout::SetPageLimits( int startPage, int endPage, int fromPage, int toPage ) { m_startPage = startPage; m_endPage = endPage; m_fromPage = fromPage; m_toPage = toPage; } void wxcPrintout::GetPageInfo( int* startPage, int* endPage, int* fromPage, int* toPage ) { if (startPage) *startPage = m_startPage; if (endPage) *endPage = m_endPage; if (fromPage) *fromPage = m_fromPage; if (toPage) *toPage = m_toPage; } bool wxcPrintout::OnBeginDocument( int startPage, int endPage ) { bool cont = wxPrintout::OnBeginDocument( startPage, endPage ); if (cont) { wxcPrintEvent printEvent( wxEVT_PRINT_BEGIN_DOC, 0, this, startPage, endPage ); m_evtHandler->ProcessEvent( printEvent ); cont = printEvent.GetContinue(); } return cont; } void wxcPrintout::OnEndDocument() { wxcPrintEvent printEvent( wxEVT_PRINT_END_DOC, 0, this, 0, 0 ); m_evtHandler->ProcessEvent(printEvent); wxPrintout::OnEndDocument(); } void wxcPrintout::OnBeginPrinting() { wxcPrintEvent printEvent( wxEVT_PRINT_BEGIN, 0, this, 0, 0 ); wxPrintout::OnBeginPrinting(); m_evtHandler->ProcessEvent(printEvent); } void wxcPrintout::OnEndPrinting() { wxcPrintEvent printEvent( wxEVT_PRINT_END, 0, this, 0, 0 ); m_evtHandler->ProcessEvent(printEvent); wxPrintout::OnEndPrinting(); } void wxcPrintout::OnPreparePrinting() { wxcPrintEvent printEvent( wxEVT_PRINT_PREPARE, 0, this, 0, 0 ); wxPrintout::OnPreparePrinting(); m_evtHandler->ProcessEvent(printEvent); } bool wxcPrintout::OnPrintPage( int page ) { wxcPrintEvent printEvent( wxEVT_PRINT_PAGE, 0, this, page, page ); m_evtHandler->ProcessEvent(printEvent); return printEvent.GetContinue(); } bool wxcPrintout::HasPage( int page ) { return (page >= m_fromPage && page <= m_toPage); } /*----------------------------------------------------------------------------- Wrappers -----------------------------------------------------------------------------*/ extern "C" { EWXWEXPORT(wxPrintDialogData*,wxPrintDialog_GetPrintDialogData)(wxPrintDialog* self) { return &(self->GetPrintDialogData()); } EWXWEXPORT(wxcPrintout*,wxcPrintout_Create)(wxString* title) { return new wxcPrintout( *title ); } EWXWEXPORT(void,wxcPrintout_Delete)(wxcPrintout* self) { if (self) delete self; } EWXWEXPORT(void,wxcPrintout_SetPageLimits)(wxcPrintout* self,int startPage,int endPage,int fromPage,int toPage) { self->SetPageLimits( startPage, endPage, fromPage, toPage ); } EWXWEXPORT(wxEvtHandler*,wxcPrintout_GetEvtHandler)(wxcPrintout* self) { return self->GetEvtHandler(); } EWXWEXPORT(wxcPrintout*,wxcPrintEvent_GetPrintout)(wxcPrintEvent* self) { return self->GetPrintout(); } EWXWEXPORT(int,wxcPrintEvent_GetPage)(wxcPrintEvent* self) { return self->GetPage(); } EWXWEXPORT(int,wxcPrintEvent_GetEndPage)(wxcPrintEvent* self) { return self->GetEndPage(); } EWXWEXPORT(bool,wxcPrintEvent_GetContinue)(wxcPrintEvent* self) { return self->GetContinue(); } EWXWEXPORT(void,wxcPrintEvent_SetContinue)(wxcPrintEvent* self,bool cont) { self->SetContinue(cont); } EWXWEXPORT(void,wxcPrintEvent_SetPageLimits)(wxcPrintEvent* self,int startPage,int endPage,int fromPage,int toPage) { self->SetPageLimits(startPage, endPage, fromPage, toPage ); } /*----------------------------------------------------------------------------- Printout -----------------------------------------------------------------------------*/ EWXWEXPORT(wxString*,wxPrintout_GetTitle)(void* self) { wxString title = ((wxPrintout*)self)->GetTitle(); return new wxString(title); } EWXWEXPORT(void*,wxPrintout_GetDC)(void* self) { return (void*)((wxPrintout*)self)->GetDC(); } EWXWEXPORT(void,wxPrintout_SetDC)(void* self,wxDC* dc) { ((wxPrintout*)self)->SetDC(dc); } EWXWEXPORT(void,wxPrintout_SetPageSizePixels)(void* self,int w,int h) { ((wxPrintout*)self)->SetPageSizePixels(w, h); } EWXWEXPORT(void,wxPrintout_GetPageSizePixels)(void* self,int* w,int* h) { ((wxPrintout*)self)->GetPageSizePixels(w,h); } EWXWEXPORT(void,wxPrintout_SetPageSizeMM)(void* self,int w,int h) { ((wxPrintout*)self)->SetPageSizeMM(w, h); } EWXWEXPORT(void,wxPrintout_GetPageSizeMM)(void* self,int* w,int* h) { ((wxPrintout*)self)->GetPageSizeMM(w,h); } EWXWEXPORT(void,wxPrintout_SetPPIScreen)(void* self,int x,int y) { ((wxPrintout*)self)->SetPPIScreen(x, y); } EWXWEXPORT(void,wxPrintout_GetPPIScreen)(void* self,int* x,int* y) { ((wxPrintout*)self)->GetPPIScreen(x,y); } EWXWEXPORT(void,wxPrintout_SetPPIPrinter)(void* self,int x,int y) { ((wxPrintout*)self)->SetPPIPrinter(x, y); } EWXWEXPORT(void,wxPrintout_GetPPIPrinter)(void* self,int* x,int* y) { ((wxPrintout*)self)->GetPPIPrinter(x,y); } EWXWEXPORT(bool,wxPrintout_IsPreview)(wxPrintout* self) { return self->IsPreview(); } EWXWEXPORT(void,wxPrintout_SetIsPreview)(void* self,bool p) { ((wxPrintout*)self)->SetIsPreview(p); } }
[ [ [ 1, 404 ] ] ]
4c0af457b99ff5ad727c0376a6d6f8dd7bf0389c
110f8081090ba9591d295d617a55a674467d127e
/tests/DateTest.cpp
890a4a7bccd5e6d5cb64e17547849e728cbff20b
[]
no_license
rayfill/cpplib
617bcf04368a2db70aea8b9418a45d7fd187d8c2
bc37fbf0732141d0107dd93bcf5e0b31f0d078ca
refs/heads/master
2021-01-25T03:49:26.965162
2011-07-17T15:19:11
2011-07-17T15:19:11
783,979
1
0
null
null
null
null
UTF-8
C++
false
false
309
cpp
#include <cppunit/extensions/HelperMacros.h> #include <Date/Date.hpp> class DateTest : public CppUnit::TestFixture { private: CPPUNIT_TEST_SUITE(DateTest); CPPUNIT_TEST(); CPPUNIT_TEST_SUITE_END(); public: void setUp(){} void tearDown(){} }; CPPUNIT_TEST_SUITE_REGISTRATION( DateTest );
[ "bpokazakijr@287b3242-7fab-264f-8401-8509467ab285" ]
[ [ [ 1, 15 ] ] ]
648b24f82c51f0b2600b767c48679887951efaf5
71c8e50508c636ca36dfc42b0e5fffd5910e09fa
/Vertex.cpp
3d0e04b1506130261a888a7ef00c7a99389b4064
[]
no_license
NIA/D3DSkinning
ea6495b4cd792b8fe28e16c15a318bbe71cd5235
ede8f34154265075fae71bd496cd50b71653e0a2
refs/heads/master
2021-01-19T22:13:42.575728
2009-10-29T08:25:19
2009-10-29T08:25:19
344,934
1
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include "Vertex.h" const D3DFORMAT INDEX_FORMAT = D3DFMT_INDEX32; const D3DVERTEXELEMENT9 VERTEX_DECL_ARRAY[] = { {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, {0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0}, {0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, D3DDECL_END() };
[ [ [ 1, 11 ] ] ]
a78aad21c0ae5752d60fd03ce6a3c2c6f9163421
216ae2fd7cba505c3690eaae33f62882102bd14a
/utils/nxogre/include/NxOgreSharedPointer.h
8d2ee423db839511a09b72aace1b72c104ec80f2
[]
no_license
TimelineX/balyoz
c154d4de9129a8a366c1b8257169472dc02c5b19
5a0f2ee7402a827bbca210d7c7212a2eb698c109
refs/heads/master
2021-01-01T05:07:59.597755
2010-04-20T19:53:52
2010-04-20T19:53:52
56,454,260
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,291
h
/** File: NxOgreSharedPointer.h Created on: 15-Nov-08 Author: Robin Southern "betajaen" SVN: $Id$ © Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org This file is part of NxOgre. NxOgre is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NxOgre is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NxOgre. If not, see <http://www.gnu.org/licenses/>. */ #ifndef NXOGRE_SHAREDPOINTER_H #define NXOGRE_SHAREDPOINTER_H #include "NxOgreStable.h" #include "NxOgreMemory.h" namespace NxOgre_Namespace { /** \brief */ template<typename T> class NxOgrePublicClass SharedPointer { public: // Functions /** \brief SharedPointer<T> constructor with no pointer to T. */ SharedPointer(void) : mPtr(0), mReferences(0) { } /** \brief SharedPointer<T> copy constructor */ SharedPointer(const SharedPointer<T>& other) : mPtr(other.mPtr), mReferences(other.mReferences) { if (mReferences) (*mReferences)++; } /** \brief SharedPointer<T> constructor with a pointer to T */ explicit SharedPointer(T* ptr) : mPtr(ptr) { mReferences = (unsigned short*) NxOgre_Allocate(sizeof(unsigned short), Classes::_BufferReferenceCounter) (*mReferences) = 1; } /** \brief SharedPointer<T> destructor */ ~SharedPointer(void) { if (mReferences) { if (--(*mReferences) == 0) { NxOgre_Delete(mPtr); NxOgre_Unallocate(mReferences); mReferences = 0; mPtr = 0; } } } /** \brief SharedPointer<T> assignment operator */ SharedPointer<T>& operator=(const SharedPointer<T>& other) { if (mReferences) { if (--(*mReferences) == 0) { NxOgre_Delete(mPtr); NxOgre_Unallocate(mReferences); } } mPtr = other.mPtr; mReferences = other.mReferences; if (mReferences) (*mReferences)++; return *this; } /** \brief SharedPointer<T> -> operator */ T* operator->(void) const { return mPtr; } /** \brief SharedPointer<T> * operator */ T& operator*(void) const { return mPtr; } /** \brief SharedPointer<T> get operator */ inline T* get(void) const { return mPtr; } /** \brief Is the pointer that the SharedPointer represent actually NULL? */ bool isNullPtr(void) { return (mPtr == 0); } /** \brief Does the SharedPointer actually contain a pointer? */ bool isNull(void) { return (mReferences == 0); } protected: // Variables T* mPtr; unsigned short* mReferences; }; // class ClassName template <typename T1, typename T2> inline bool operator==(SharedPointer<T1> const& first, SharedPointer<T2> const& second) { return first.get() == second.get(); } } // namespace NxOgre_Namespace #endif
[ "umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b" ]
[ [ [ 1, 160 ] ] ]
833a2f18d66a7e50b4045e9b0089228a5976474c
1b3a26845c00ede008ea66d26f370c3542641f45
/pymfclib/PyMFC_CustomProtocol.h
bd0679a99dbf98451a43ca38cea2e294bd46316a
[]
no_license
atsuoishimoto/pymfc
26617fac259ed0ffd685a038b47702db0bdccd5f
1341ef3be6ca85ea1fa284689edbba1ac29c72cb
refs/heads/master
2021-01-01T05:50:51.613190
2010-12-29T07:38:01
2010-12-29T07:38:01
33,760,622
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,297
h
// PyMFC_CustomProtocol.h : CPyMFC_CustomProtocol の宣言 #pragma once #include "resource.h" // メイン シンボル #include "pymfclib_i.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "DCOM の完全サポートを含んでいない Windows Mobile プラットフォームのような Windows CE プラットフォームでは、単一スレッド COM オブジェクトは正しくサポートされていません。ATL が単一スレッド COM オブジェクトの作成をサポートすること、およびその単一スレッド COM オブジェクトの実装の使用を許可することを強制するには、_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA を定義してください。ご使用の rgs ファイルのスレッド モデルは 'Free' に設定されており、DCOM Windows CE 以外のプラットフォームでサポートされる唯一のスレッド モデルと設定されていました。" #endif // CPyMFC_CustomProtocol /* Based on `From Asynchronous Pluggable Protocol Handler for data: URLs' By Rama Krishna Vavilala(http://www.codeproject.com/KB/IP/DataProtocol.aspx). */ class ATL_NO_VTABLE CPyMFC_CustomProtocol: public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CPyMFC_CustomProtocol, &CLSID_PyMFC_CustomProtocol>, public IPyMFC_CustomProtocol, public IInternetProtocol { public: CPyMFC_CustomProtocol() { } static PyObject **mapfunc; BEGIN_COM_MAP(CPyMFC_CustomProtocol) COM_INTERFACE_ENTRY(IPyMFC_CustomProtocol) COM_INTERFACE_ENTRY(IInternetProtocol) COM_INTERFACE_ENTRY(IInternetProtocolRoot) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: // IInternetProtocol interface public: STDMETHOD(Start)( LPCWSTR szUrl, IInternetProtocolSink *pIProtSink, IInternetBindInfo *pIBindInfo, DWORD grfSTI, DWORD dwReserved); STDMETHOD(Continue)(PROTOCOLDATA *pStateInfo); STDMETHOD(Abort)(HRESULT hrReason,DWORD dwOptions); STDMETHOD(Terminate)(DWORD dwOptions); STDMETHOD(Suspend)(); STDMETHOD(Resume)(); STDMETHOD(Read)(void *pv,ULONG cb,ULONG *pcbRead); STDMETHOD(Seek)( LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition); STDMETHOD(LockRequest)(DWORD dwOptions); STDMETHOD(UnlockRequest)(); bool doCallback(LPCWSTR url); private: CComPtr<IInternetProtocolSink> m_spSink; CComPtr<IInternetBindInfo> m_spBindInfo; DWORD m_dwPos; CComBSTR m_mimetype; CAtlArray<BYTE> m_src; }; //OBJECT_ENTRY_AUTO(__uuidof(PyMFC_CustomProtocol), CPyMFC_CustomProtocol) class ATL_NO_VTABLE CPyMFC_CustomProtocolFactory : public CComClassFactory { public: STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj) { CComObject<CPyMFC_CustomProtocol> *cp; HRESULT hr = CComObject<CPyMFC_CustomProtocol>::CreateInstance(&cp); if (FAILED(hr )) { return hr; } hr = cp->QueryInterface(riid, ppvObj); if (FAILED(hr)) { delete cp; } return hr; } };
[ [ [ 1, 110 ] ] ]
34e534481f08139beaf0df202b2ea6f3f57feb9b
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/server/wscPsExchangeBuffer.cpp
3e98665f3263511cff8c88b487885b9659d9999d
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
2,414
cpp
#include "wscPsExchangeBuffer.h" #include <wcpp/lang/wscThrowable.h> #include <wcpp/net/wscDatagramPacket.h> #include <wcpp/wspr/wsuSingleLock.h> #include <wcpp/lang/wscArray.h> wscPsExchangeBuffer::wscPsExchangeBuffer(void) : m_count_packet_limit(1024) , m_packet_buffer_length(4096) { } wscPsExchangeBuffer::~wscPsExchangeBuffer(void) { } ws_result wscPsExchangeBuffer::AllocatePacket(wsiDatagramPacket ** ret) { ws_result rlt = InternalAllocatePacket(ret); if (rlt==WS_RLT_SUCCESS) return rlt; if ( InternalCountReadyPacket() < m_count_packet_limit ) { ws_int len = m_packet_buffer_length; ws_ptr<wsiByteArray> buf; rlt = NewObj<wscByteArray>( &buf , len ); return NewObj<wscDatagramPacket>( ret , buf , len ); } else { return WS_RLT_FAILED; } } ws_int wscPsExchangeBuffer::InternalCountReadyPacket(void) { wsuSingleLock lock( & m_mutex ); return static_cast<ws_int>( m_ready_list.size() ); } ws_result wscPsExchangeBuffer::InternalAllocatePacket(wsiDatagramPacket ** ret) { if (ret==WS_NULL) return WS_RLT_NULL_POINTER; WS_ASSERT( (*ret)==WS_NULL ); wsuSingleLock lock( & m_mutex ); if (m_free_list.size() <= 0) { return WS_RLT_ARRAY_INDEX_OUT_OF_BOUNDS; } else { (*ret) = m_free_list.front(); m_free_list.pop_front(); return WS_RLT_SUCCESS; } } ws_result wscPsExchangeBuffer::PushPacket(wsiDatagramPacket * packet) { if (packet==WS_NULL) return WS_RLT_NULL_POINTER; packet->AddRef(); wsuSingleLock lock( & m_mutex ); m_ready_list.push_back( packet ); return WS_RLT_SUCCESS; } ws_result wscPsExchangeBuffer::PopPacket(wsiDatagramPacket ** ret) { if (ret==WS_NULL) return WS_RLT_NULL_POINTER; WS_ASSERT( (*ret)==WS_NULL ); wsuSingleLock lock( & m_mutex ); if (m_ready_list.size() <= 0) { return WS_RLT_ARRAY_INDEX_OUT_OF_BOUNDS; } else { (*ret) = m_ready_list.front(); m_ready_list.pop_front(); return WS_RLT_SUCCESS; } } ws_result wscPsExchangeBuffer::RecyclePacket(wsiDatagramPacket * packet) { if (packet==WS_NULL) return WS_RLT_NULL_POINTER; packet->AddRef(); wsuSingleLock lock( & m_mutex ); m_free_list.push_back( packet ); return WS_RLT_SUCCESS; }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 98 ] ] ]
0e5867501e42793751a3ea00fb477f6659d0a198
af260b99d9f045ac4202745a3c7a65ac74a5e53c
/branches/engine/2.4/src/SeqWeight.cpp
b5983e58df04ca548ff5d9fc8945e11eb7fd04be
[]
no_license
BackupTheBerlios/snap-svn
560813feabcf5d01f25bc960d474f7e218373da0
a99b5c64384cc229e8628b22f3cf6a63a70ed46f
refs/heads/master
2021-01-22T09:43:37.862180
2008-02-17T15:50:06
2008-02-17T15:50:06
40,819,397
0
0
null
null
null
null
UTF-8
C++
false
false
5,715
cpp
#include "SeqWeight.h" #include "Sequence.h" #include "SequenceDB.h" #include "core/FixedStr.h" #include "persistance/TextReader.h" #include "persistance/StdInputStream.h" #include <string> #include <fstream> #include <iostream> #include <assert.h> double SeqWeightDB::PositionalWeight::getPositionWeight (int index) const { // // we can use find_if because I don't expect more than // 10 hot-spots in a sequence, and in this range // find_if performs better than binary_search Positions::const_iterator it = _positions.begin (); for (; it != _positions.end () ; ++it) { if (index < (*it)->_startIndex){ it = _positions.end (); break; } else if (index <= (*it)->_startIndex + (*it)->_length) break; } if (it == _positions.end ()) return _weight; else { return (*it)->_weight; } } // // // Format: // >SeqName1 Wgt1 // >SeqName2 Wgt2 // ... // // example: // // >YFL048C 0.991742546801741 // >YOL116W 0.991742546801741 struct WeightsReader { virtual ~WeightsReader () { } void read (const char* fname) { std::ifstream in (fname); if (! in.is_open()) { mmustfail ( FixedStrBuffer<4 * 1024> ("unable to open weight file %s", fname) ); } read (in); } void read (std::istream& in) { std::string name, s; while (true) { s.resize (0); name.resize (0); bool ok = true; while (ok && s.size()==0) { std::istream::sentry _ok(in); if (ok = _ok) in>>s;// skip empty lines; } if (!ok) break; // here we handle cases in which the ">" is/isn't separated from the name of the gene. if (s ==">") in>>name; else { assert(s[0]=='>'); name = s.substr(1); } readValue(in, Str (name)); } } virtual void readValue (std::istream& in, const Str&) = 0; }; /* AutoPtr <SeqWeightDB::Name2Weight> SeqWeightDB::readWgtFile (const char* wgtFileName) { // // we are not expected to deal with more than struct SeqWeightsReader : public WeightsReader, AutoPtr <Name2Weight> { SeqWeightsReader () { set (new Name2Weight (_default_db_size)); } virtual void readValue (std::ifstream& in, const Str& name) { double val; in>>val; get ()->add(new SeqWeightDB::Name2Weight::Node(Str (name), val)); } } reader; reader.read (wgtFileName); return reader.release(); } */ AutoPtr <SeqWeightDB::ID2Weight> SeqWeightDB::computeWeightIndex ( const Name2Weight& weights, const SequenceDB& db) { AutoPtr <ID2Weight> id2weight = new ID2Weight; Name2Weight::const_iterator it = weights.begin (); for (;it != weights.end () ; ++it) { Sequence* seq = db.getSequence(it->first); debug_mustbe (seq); if (seq) { PositionalWeight_var weight = it->second; (*id2weight) [seq->id ()] = weight; } } return id2weight; } // // Positional weights: // // // Format: // >SeqName1 Wgt1 = [index1a, index1b] {Tab} Wgt2 = [index2a, index2b] {Tab}... // ... // // example: // // >YFL048C 0.5 = [0, 100] 2.4 = [250, 300] 0.5 = [760, 900] // >YOL116W 0.5 =[0, 70] 0.67 = [560, 700] struct PosWeightsReader : public WeightsReader { PosWeightsReader () { _posweights = new SeqWeightDB::Name2Weight; _entries.reserve (10); } virtual void readValue (std::istream& sin, const Str& name) { double seqWeight; sin>>seqWeight; std::string buffer; std::getline (sin, buffer); readValue (buffer, name, seqWeight); } void readValue (const std::string& lineBuffer, const Str& name, double seqWeight) { Str buffer = Str (lineBuffer).trimmedSubstring(); _entries.clear (); while (!buffer.empty ()) { double w; int i1, i2; int count = sscanf (buffer.getChars (), "%lf = [%d, %d]", &w, &i1, &i2); Str::Index next = buffer.indexOf(']'); if ((next == Str::badIndex) || (count != 3) || (!(i1 <= i2) && (w>=0) && (w<=1) && (i1 >= 0))){ throw BaseException ( StrBuffer ( Str ("bad positional-weight format in "), name, Str (":\nUnexpected "), buffer ) ); } _entries.push_back(new SeqWeightDB::PositionalWeight::Entry (i1, i2-i1, seqWeight * w)); buffer = buffer.substring (next + 1); buffer = buffer.trimmedSubstring(); } _temp = name; SeqWeightDB::PositionalWeight_var posWeight ( new SeqWeightDB::PositionalWeight (seqWeight, _entries) ); _posweights->insert ( SeqWeightDB::Name2Weight::value_type (_temp, posWeight) ); } virtual void readValue (Persistance::TextReader& reader, const Str& name, double seqWeight) { _temp.setLength (0); reader.readln (_temp); } StrBuffer _temp; AutoPtr <SeqWeightDB::Name2Weight> _posweights; SeqWeightDB::PositionalWeight::Positions _entries; }; AutoPtr <SeqWeightDB::Name2Weight> SeqWeightDB::readWgtFile (const char* weightFileName) { PosWeightsReader reader; reader.read (weightFileName); return reader._posweights; } AutoPtr <SeqWeightDB::Name2Weight> SeqWeightDB::readWgtFile (std::istream& in) { PosWeightsReader reader; reader.read (in); return reader._posweights; }
[ "aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478" ]
[ [ [ 1, 226 ] ] ]
659dd4915e1af50c48b382f6351f21bd78883a0a
fd4f996b64c1994c5e6d8c8ff78a2549255aacb7
/ nicolinorochetaller --username adrianachelotti/trunk/tp3/Servidor/Arco.cpp
62d1c92d3e97849cbf47092a703335e3812bb1ff
[]
no_license
adrianachelotti/nicolinorochetaller
026f32476e41cdc5ac5c621c483d70af7b397fb0
d3215dfdfa70b6226b3616c78121f36606135a5f
refs/heads/master
2021-01-10T19:45:15.378823
2009-08-05T14:54:42
2009-08-05T14:54:42
32,193,619
0
0
null
null
null
null
UTF-8
C++
false
false
766
cpp
// Rectangulo.cpp: implementation of the Rectangulo class. // ////////////////////////////////////////////////////////////////////// #include "Arco.h" #include "Graficador.h" #include "Escenario.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Arco::Arco() { } Arco::~Arco() { } Rectangulo* Arco::getRepresentacionGrafica() { return this->representacionGrafica; } void Arco::setRepresentacionGrafica(Rectangulo* representacion) { this->representacionGrafica = representacion; } Punto Arco::getPosicion() { return this->getRepresentacionGrafica()->getPosicionVerticeInferiorIzquierdo(); }
[ "[email protected]@0b808588-0f27-11de-aab3-ff745001d230" ]
[ [ [ 1, 39 ] ] ]
68c9a56089ec83f0a19f6a29fc0ea017a1b2cda0
6c8c4728e608a4badd88de181910a294be56953a
/OgreAssetEditorModule/PropertyTableWidget.cpp
207ff68acd201173fe1d57b2a6b78e88831f5cb8
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
caocao/naali
29c544e121703221fe9c90b5c20b3480442875ef
67c5aa85fa357f7aae9869215f840af4b0e58897
refs/heads/master
2021-01-21T00:25:27.447991
2010-03-22T15:04:19
2010-03-22T15:04:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,494
cpp
// For conditions of distribution and use, see copyright notice in license.txt /** * @file PropertyTableWidget.cpp * @brief PropertyTableWidget inherits QTableWidget and add some custom drop-functionality. */ #include "StableHeaders.h" #include "PropertyTableWidget.h" #include <RexUUID.h> #include <QHeaderView> #include <QMimeData> #include <QDragEnterEvent> namespace Naali { PropertyTableWidget::PropertyTableWidget(QWidget *parent) : QTableWidget(parent) { InitWidget(); } PropertyTableWidget::PropertyTableWidget(int rows, int columns, QWidget *parent) : QTableWidget(rows, columns, parent) { InitWidget(); } PropertyTableWidget::~PropertyTableWidget() { } void PropertyTableWidget::dragMoveEvent(QDragMoveEvent *event) { if (event->mimeData()->hasFormat("application/vnd.inventory.item")) { QModelIndex index = indexAt(event->pos()); if (index.isValid()) { QTableWidgetItem * item = itemFromIndex(index); if (item && item->flags() & Qt::ItemIsDropEnabled) { event->accept(); return; } } } event->ignore(); } QStringList PropertyTableWidget::mimeTypes() const { QStringList types; types << "application/vnd.inventory.item"; return types; } bool PropertyTableWidget::dropMimeData(int row, int column, const QMimeData *data, Qt::DropAction action) { if (action == Qt::IgnoreAction) return true; if (!data->hasFormat("application/vnd.inventory.item")) return false; QByteArray encodedData = data->data("application/vnd.inventory.item"); QDataStream stream(&encodedData, QIODevice::ReadOnly); QString asset_id; bool valid = false; while(!stream.atEnd()) { QString mimedata, asset_type, item_id, name; stream >> mimedata; QStringList list = mimedata.split(";", QString::SkipEmptyParts); if (list.size() < 4) continue; asset_type = list.at(0); if (asset_type.toInt(&valid) != RexTypes::RexAT_Texture) continue; item_id = list.at(1); if (!RexUUID::IsValid(item_id.toStdString())) continue; name = list.at(2); asset_id = list.at(3); } if (!valid || !RexUUID::IsValid(asset_id.toStdString())) return false; QTableWidgetItem *item = this->item(row, column); if (item && item->flags() & Qt::ItemIsDropEnabled) item->setData(Qt::DisplayRole, asset_id); else return false; return true; } Qt::DropActions PropertyTableWidget::supportedDropActions() const { return Qt::CopyAction; } void PropertyTableWidget::InitWidget() { // Set up drop functionality. setAcceptDrops(true); setDragEnabled(false); setDragDropMode(QAbstractItemView::DropOnly); setAcceptDrops(true); setDropIndicatorShown(true); setDragDropOverwriteMode(true); // Set up headers and size. setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Type") << tr("Value")); verticalHeader()->setVisible(false); resizeColumnToContents(0); horizontalHeader()->setStretchLastSection(true); horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); setMouseTracking(true); } }
[ "Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3" ]
[ [ [ 1, 132 ] ] ]
3680e534a6a12e25b1ddd21d84460fe4862e021a
ce148b48b453a58d84664ec979eb64e4813a83c8
/Faeried/MainWidget.h
145bfc92ff16b281b36c7fae4a02bec16cc407ee
[]
no_license
theyoprst/Faeried
e8945f8cb21c317eeeb1b05f0d12b297b63621fe
d20bd990e7f91c8c03857d81e08b8f7f2dee3541
refs/heads/master
2020-04-09T16:04:47.472907
2011-02-21T16:38:02
2011-02-21T16:38:02
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
390
h
#pragma once #include <QtGui/QWidget.h> class FaerieAnimationsDelegate; // // Класс главного окна // class MainWidget : public QWidget { public: // // Конструктор // explicit MainWidget(FaerieAnimationsDelegate* animations); private: // // Событие выхода // virtual void closeEvent(QCloseEvent* event); };
[ [ [ 1, 27 ] ] ]
3598a785eb6f3378b950fe069dad1c4943993f51
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/App/SystemMonitorHandlerThread.cpp
54eea8e15896f892c0f2556a117a67ee28b73297
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,092
cpp
//-------------------------------------------------------------------------------- // // Copyright (c) 2000 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- #include "stdafx.h" #include <LockedSocket.h> #include <ReadLock.h> #include <WriteLock.h> #include <PlatformInfo.h> #include "SecuritySystem.h" #include "SystemMonitorHandlerThread.h" #include "MonitorSubSystem.h" #include "DBSubSystem.h" #include "DBTokens.h" #include "SSConfigMonitor.h" #include "SSConfigGeneral.h" #include "SSConfigBackup.h" #include "SSConfigGeneral.h" #include "SSConfigPerformance.h" #include "SecServTokenId.h" #include "SSQuickMail.h" #include "dongle.h" #define SECSERV_VERSION_STRING "071701" //-------------------------------------------------------------------------------- CSystemMonitorHandlerThread::CSystemMonitorHandlerThread(CMonitorSubSystem* pParent) : CSSThread(pParent) , m_bLoggedIn(false) { #ifdef _DEBUG m_bLoggedIn = true; #endif } //-------------------------------------------------------------------------------- CSystemMonitorHandlerThread::~CSystemMonitorHandlerThread() { if(::GetCurrentThreadId() != m_nThreadId) ::WaitForSingleObject(m_hThread, INFINITE); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::OnMessage(UINT nMsg, WPARAM hSocket, LPARAM lParam) { if(nMsg != CMonitorSubSystem::MSG_NEWCONNECTION) return; m_socket.Attach((SOCKET) hSocket); SetThreadBusy(true); CSSQuickMail* pMail = new CSSQuickMail; pMail->m_sSubject = "FYI: Control Connection Made"; CString sSockAddr; UINT nPort; m_socket.GetPeerName(sSockAddr, nPort); pMail->m_sMsg.Format("client %s port=%u\r\n", (LPCTSTR) sSockAddr, nPort); GetIO()->SendQuickMail(pMail); } //-------------------------------------------------------------------------------- bool CSystemMonitorHandlerThread::MainLoop() { CReadLock lock(GetStatePtr()); if(! IsThreadBusy()) return CheckState(); // m_pSocket wont be valid until MSG_NEWCONNECTION msg is received if(! m_socket.IsValid()) { SetThreadBusy(false); return CheckState(); } #ifndef _DEBUG CTime ctCurrent(CTime::GetCurrentTime()); if(m_ctLastActivity < ctCurrent - CTimeSpan(0, 0, 5, 0)) { CString sTemp("----* Session timed out *----\r\n"); m_socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK); SetThreadBusy(false); return CheckState(); } #endif CString sTemp; int nLen = 0; nLen = m_socket.Receive(sTemp.GetBuffer(1024), 1024, CSmallSocket::WAITFORDATA, 1000); // when there's no data (but no error) Receive will return len==-1 and err == WSAEWOULDBLOCK long nErr = ::WSAGetLastError(); if(nLen == -1 && nErr != WSAEWOULDBLOCK) { ::WSASetLastError(nErr); sTemp.ReleaseBuffer(0); SetThreadBusy(false); return CheckState(); } if(nLen < 1) nLen = 0; sTemp.ReleaseBuffer(nLen); if(nLen > 0) { #ifndef _DEBUG m_ctLastActivity = ctCurrent; #endif int nIndex = sTemp.FindOneOf("\r\n"); if(nIndex != -1) { sTemp.GetBufferSetLength(nIndex); sTemp.ReleaseBuffer(); m_sCurCmd += sTemp; if(! DoCommand()) SetThreadBusy(false); } else if(sTemp.GetLength() > 0) m_sCurCmd += sTemp; } return CheckState(); } //-------------------------------------------------------------------------------- bool CSystemMonitorHandlerThread::Init() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); return true; } //-------------------------------------------------------------------------------- bool CSystemMonitorHandlerThread::OnDeactivate() { m_sUser.Empty(); m_sPass.Empty(); m_bLoggedIn = false; m_socket.Close(); return true; } //-------------------------------------------------------------------------------- bool CSystemMonitorHandlerThread::OnActivate() { m_ctLastActivity = CTime::GetCurrentTime(); return true; } //-------------------------------------------------------------------------------- static LPCTSTR g_pCommands[] = {"load", "list", "pause", "continue", "exit", "revoke", "help", "serial", "user", "pass", "dongle", "config"}; enum { CMDLOAD, CMDLIST, CMDPAUSE, CMDCONT, CMDEXIT, CMDREVOKE, CMDHELP, CMDSERIAL, CMDUSER, CMDPASS, CMDDONGLE, CMDCONFIG, NUM_OF_CMDS }; //-------------------------------------------------------------------------------- bool CSystemMonitorHandlerThread::DoCommand() { ASSERT(NUM_OF_CMDS == sizeof(g_pCommands) / sizeof(LPCTSTR)); bool bRv = true; m_sCurCmd.MakeLower(); m_sCurCmd.TrimLeft(); m_sCurCmd.TrimRight(); TRY { CString sTemp(m_sCurCmd.Left(4)); if(sTemp == "hey") m_socket.Send("there\r\n\r\n", 6, CSmallSocket::WAITFORWOULDBLOCK); else { for(int i = 0; i < NUM_OF_CMDS; i++) { if(strncmp(sTemp, g_pCommands[i], 4) == 0) break; } if(i == CMDEXIT) { m_sCurCmd.Empty(); m_sUser.Empty(); m_sPass.Empty(); return false; } if(i == CMDUSER) { if(m_sCurCmd.GetLength() > 5) DoUser(m_sCurCmd.Mid(5)); m_sCurCmd.Empty(); return true; } if(i == CMDPASS) { if(m_sCurCmd.GetLength() > 5) DoPass(m_sCurCmd.Mid(5)); m_sCurCmd.Empty(); return true; } if(! m_bLoggedIn) { m_sCurCmd.Empty(); return true; } switch(i) { case CMDLOAD: if(m_sCurCmd.GetLength() > 5) DoLoad(m_sCurCmd.Mid(5)); else { CSSConfigGeneral config; DoLoad(config.m_sLicenseFileDefault); } break; case CMDLIST: DoList(); break; case CMDPAUSE: DoPause(); break; case CMDCONT: DoContinue(); break; case CMDREVOKE: DoRevoke(); break; case CMDHELP: { for(int i = 0; i < NUM_OF_CMDS; i++) { CString sTemp; sTemp.Format("%s\r\n", g_pCommands[i]); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } } break; case CMDSERIAL: { CString sTemp; for(int i = 0; CPlatformInfo::GetProcessorSerialNumber(sTemp, i); i++) { sTemp += "\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } } break; case CMDDONGLE: DoDongle(); break; case CMDCONFIG: DoConfigDump(); break; default: m_socket.Send("what?\r\n\r\n", 6, CSmallSocket::WAITFORWOULDBLOCK); break; } } } CATCH_ALL(e) { } END_CATCH_ALL m_sCurCmd.Empty(); return bRv; } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoUser(LPCTSTR pUser) { CSSConfigMonitor config; if(pUser == config.m_sUser) m_sUser = pUser; else m_sUser.Empty(); m_bLoggedIn = m_sUser == config.m_sUser && m_sPass == config.m_sPass; } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoPass(LPCTSTR pPass) { CSSConfigMonitor config; if(pPass == config.m_sPass) m_sPass = pPass; else m_sPass.Empty(); m_bLoggedIn = m_sUser == config.m_sUser && m_sPass == config.m_sPass; if(! m_bLoggedIn) { m_sUser.Empty(); m_sPass.Empty(); } } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoPause() { CString sTemp("This command does nothing - surprised?\r\n"); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); // GetSystem()->SetState(STATE_PAUSE); // GetSystem()->WaitForStateSync(); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoContinue() { CString sTemp("Is pause does nothing, what makes you think this command would?\r\n"); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); // GetSystem()->SetState(STATE_RUN); // GetSystem()->WaitForStateSync(); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoLoad(LPCTSTR pFilename) { CString sTemp(pFilename); if(! sTemp.IsEmpty()) GetSystem()->SetLicenseFilename(sTemp); if(GetDB()->LoadFromFile()) sTemp = "file loaded ok\r\n"; else sTemp = "error while loading file\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoList() { if(m_sCurCmd.Find("all") != -1) { DoListAll(); return; } CDBTokenInfoMap* pDB = GetDB()->GetTokenInfoMap(); CString sTemp; CReadLock lock(pDB, false); if(! lock.Lock(30000)) { sTemp = "can't lock the database right now (probably a lot of activity)\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); return; } sTemp = " Id Name In Use Count Max\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); for(POSITION pos = pDB->GetStartPosition(); pos != NULL; ) { DWORD nId; CDBTokenInfo* pInfo; pDB->GetNextAssoc(pos, nId, pInfo); if(! pInfo) continue; sTemp.Format("%4d %12s %6d %6d %6d\r\n", nId, pInfo->m_token.GetName(), pInfo->m_nInUse, pInfo->m_nCount, pInfo->m_nMax); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } if(GetSystem()->IsBackupServer()) sTemp.Format("%s%s\r\n", "Running as backup server", GetSystem()->IsServing() ? " currently serving" : ""); else sTemp.Format("Backup SecurityServer is %s\r\n", GetSystem()->IsBackupRunning() ? "running" : "not running"); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); #ifdef _DEBUG #pragma message("Don't forget to change the listed version for the next release!") #endif sTemp.Format("This server is version " SECSERV_VERSION_STRING "\r\n"); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoListAll() { CString sTemp; CReadLock lock(GetDB()->GetCertMasters(), false); if(! lock.Lock(10000)) { sTemp = "Can't lock the certificate database right now )\r\n"; m_socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK); return; } POSITION pos = GetDB()->GetCertMasters()->GetHeadPosition(); if(pos == NULL) { sTemp = "there are currently 0 connections\r\n"; m_socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK); return; } CReadLock lock2(GetDB()->GetTokenInfoMap(), false); if(! lock2.Lock(1000)) { sTemp = "Can't lock the token database right now\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); return; } sTemp = "IP Last Refresh Cert ID User Class Token Name\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); while(pos != NULL) { CCertificateMaster* pCert = (CCertificateMaster*) GetDB()->GetCertMasters()->GetNext(pos); if(! pCert) break; CReadLock lock(pCert, false); if(! lock.Lock(1000)) { sTemp = "Can't lock one of the certificates right now\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); continue; } POSITION pos = pCert->GetTokenMap()->GetStartPosition(); LPCTSTR pFormat = "%-15s %-20s %8ld %10ld %-16s\r\n"; if(pos == NULL) { sTemp.Format(pFormat, pCert->GetIP(), (LPCTSTR) pCert->GetLastRefresh().Format("%c"), pCert->GetId(), pCert->GetUserClass(), ""); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } else { while(pos != NULL) { CAccessToken* pTok; ULONG nId; pCert->GetTokenMap()->GetNextAssoc(pos, nId, pTok); if(pTok == NULL) break; sTemp.Format(pFormat, pCert->GetIP(), (LPCTSTR) pCert->GetLastRefresh().Format("%c"), pCert->GetId(), pCert->GetUserClass(), pTok->GetName()); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } } } } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoRevoke() { int nIndex = m_sCurCmd.ReverseFind(' '); if(nIndex == -1) return; if(nIndex == (m_sCurCmd.GetLength() - 1)) return; CString sTemp(m_sCurCmd.Mid(nIndex + 1)); if(sTemp == "all") { DoRevokeAll(); return; } if(sTemp.Find('.') != -1) { DoRevokeByIP(sTemp); return; } DWORD nId = (DWORD) atol(sTemp); if(! GetDB()->ReleaseCertificate(nId)) sTemp.Format("certificate %d not found\n\r", nId); else sTemp.Format("certificate %d revoked\r\n", nId); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoRevokeByIP(const CString& sIP) { CString sTemp; if(! GetDB()->ReleaseCertificate(sIP)) sTemp.Format("no certificates issued to %s\n\r", (LPCTSTR) sIP); else sTemp.Format("certificates issued to %s revoked\n\r", (LPCTSTR) sIP); m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoRevokeAll() { CString sTemp; if(! GetDB()->ReleaseAllCertificates()) sTemp = "certificates not found\n\r"; else sTemp = "all certificate revoked\r\n"; m_socket.Send(sTemp, sTemp.GetLength(), CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoDongle() { CDongle dongle; BYTE buf[128]; CString sTemp; if(dongle.GetDongleMemory(buf)) { for(int i = 0; i < 128; i++) { if(! isgraph(buf[i])) buf[i] = '.'; } buf[127] = 0; sTemp = buf; } else sTemp = "** Error reading dongle **"; sTemp += "\r\n"; m_socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK); } //-------------------------------------------------------------------------------- void CSystemMonitorHandlerThread::DoConfigDump() { CString sTemp("Configuration:\r\n"); if(! m_socket.Send(sTemp, CSmallSocket::WAITFORWOULDBLOCK)) return; CStringArray sArray; GetSystem()->GetSystemConfigStringMessage(sArray); for(int i = 0; i < sArray.GetSize(); i++) if(! m_socket.Send(sArray[i] + "\r\n", CSmallSocket::WAITFORWOULDBLOCK)) return; }
[ [ [ 1, 580 ] ] ]
f21c19ceb9be0c01d6921850373d6d40cca8c44b
1cc5720e245ca0d8083b0f12806a5c8b13b5cf98
/v1/ok/128/c.cpp
2dcba3cf8758f2a18a57144abaa2ae569d563da2
[]
no_license
Emerson21/uva-problems
399d82d93b563e3018921eaff12ca545415fd782
3079bdd1cd17087cf54b08c60e2d52dbd0118556
refs/heads/master
2021-01-18T09:12:23.069387
2010-12-15T00:38:34
2010-12-15T00:38:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
cpp
#include <iostream> #include <stdio.h> using namespace std; using namespace std; // Converte da base b para a base 10, eh isso? unsigned long long toBase10(const char *in, int b) { unsigned long long v = 0; while((*in)!='\0' && (*in)!='\n' && (*in)!='\r') { if((*in)>='0' && (*in)<='9') { v = v * b + ((*in)-'0'); } else if((*in)>='A' && (*in)<='F') { v = v * b + ((*in)-'A'+10); } in++; } return v; } char *ltoa(unsigned long long n, char *out, int rout) { int p = 0; char temp[50]; long long t; while(n > 0) { t = n % rout; if(t<10) temp[p] = '0' + t; else temp[p] = 65 + t - 10; p++; n /= rout; } if(p==0) temp[p++] = '0'; for(int i=0;i!=p;i++) { out[i] = temp[p-i-1]; } out[p] = '\0'; return out; } int main() { unsigned long long code = 0; int len = 0; char c; char l[200],lin[10000]; int i,j,k; while(true) { code = 0; gets(lin); if(lin[0]=='#') break; len = strlen(lin); for(i=0;i!=len;i++) { if(lin[i]=='\r' || lin[i]=='\n') break; code *= 256; code %= 34943; code += lin[i]; } code *= 256; code *= 256; // cout << "f1: " << code << endl; code %= 34943; // cout << "f2: " << code << endl; code = 34943 - code; code %= 34943; ltoa(code,l,16); len = strlen(l); if(len==4) printf("%c%c %c%c\n",l[0],l[1],l[2],l[3]); else if(len==3) printf("0%c %c%c\n",l[0],l[1],l[2]); else if(len==2) printf("00 %c%c\n",l[0],l[1]); else printf("00 0%c\n",l[0]); //cout << l << endl; } return 0; }
[ [ [ 1, 82 ] ] ]
27a53f731c14c091159199287e4a2887a7fc38be
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxSerialize/QxArchive.h
77a6a89be2b8b461edde3c3e6ebecd37844c7811
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
5,729
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _QX_ARCHIVE_H_ #define _QX_ARCHIVE_H_ #ifdef _MSC_VER #pragma once #endif #include <string> #include <iostream> #include <sstream> #include <fstream> #include <exception> #include <boost/archive/archive_exception.hpp> #include <boost/serialization/serialization.hpp> #include <boost/serialization/nvp.hpp> #include <QxTraits/archive_wide_traits.h> #include <QxTraits/get_class_name.h> #include <QxTraits/is_qx_registered.h> #include <QxCommon/QxConfig.h> #include <QxCommon/QxBool.h> #include <QxRegister/QxClass.h> #include <QxRegister/QxClassName.h> #include <QxSerialize/QxSerializeMacro.h> #include <QxSerialize/boost/QxSerializeInclude.h> #include <QxSerialize/QxBoostSerializeHelper/QxBoostSerializeRegisterHelperX.h> #define QX_STR_SERIALIZATION_ERROR "Serialization error : '%ERR%'" #define QX_STR_DESERIALIZATION_ERROR "Deserialization error : '%ERR%'" namespace qx { template <class T, class ArchiveInput = QX_DEFAULT_ARCHIVE_INPUT, class ArchiveOutput = QX_DEFAULT_ARCHIVE_OUTPUT> class QxArchive { public: static qx_bool toFile(const T & obj, const QString & sFileName, unsigned int flags = boost::archive::no_header); static qx_bool fromFile(T & obj, const QString & sFileName, unsigned int flags = boost::archive::no_header); static qx_bool toFileCompressed(const T & obj, const QString & sFileName, unsigned int flags = boost::archive::no_header, int iCompressionLevel = -1); static qx_bool fromFileCompressed(T & obj, const QString & sFileName, unsigned int flags = boost::archive::no_header); static QString toString(const T & obj, unsigned int flags = boost::archive::no_header); static qx_bool fromString(T & obj, const QString & sString, unsigned int flags = boost::archive::no_header); static qx_bool toNetwork(const T & obj, unsigned int flags = boost::archive::no_header); static qx_bool fromNetwork(T & obj, unsigned int flags = boost::archive::no_header); static qx_bool toNetworkCompressed(const T & obj, unsigned int flags = boost::archive::no_header); static qx_bool fromNetworkCompressed(T & obj, unsigned int flags = boost::archive::no_header); }; } // namespace qx #include "../../inl/QxSerialize/QxArchive.inl" namespace qx { namespace serialization { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, QX_DEFAULT_ARCHIVE_INPUT, QX_DEFAULT_ARCHIVE_OUTPUT) #if _QX_SERIALIZE_POLYMORPHIC namespace polymorphic_binary { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::polymorphic_binary_iarchive, boost::archive::polymorphic_binary_oarchive) } // namespace polymorphic_binary namespace polymorphic_text { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::polymorphic_text_iarchive, boost::archive::polymorphic_text_oarchive) } // namespace polymorphic_text namespace polymorphic_xml { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::polymorphic_xml_iarchive, boost::archive::polymorphic_xml_oarchive) } // namespace polymorphic_xml #endif // _QX_SERIALIZE_POLYMORPHIC #if _QX_SERIALIZE_BINARY namespace binary { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::binary_iarchive, boost::archive::binary_oarchive) } // namespace binary #endif // _QX_SERIALIZE_BINARY #if _QX_SERIALIZE_TEXT namespace text { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::text_iarchive, boost::archive::text_oarchive) } // namespace text #endif // _QX_SERIALIZE_TEXT #if _QX_SERIALIZE_XML namespace xml { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::xml_iarchive, boost::archive::xml_oarchive) } // namespace xml #endif // _QX_SERIALIZE_XML #if _QX_SERIALIZE_PORTABLE_BINARY namespace portable_binary { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, eos::portable_iarchive, eos::portable_oarchive) } // namespace portable_binary #endif // _QX_SERIALIZE_PORTABLE_BINARY namespace wide { #if _QX_SERIALIZE_WIDE_BINARY namespace binary { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::binary_wiarchive, boost::archive::binary_woarchive) } // namespace binary #endif // _QX_SERIALIZE_WIDE_BINARY #if _QX_SERIALIZE_WIDE_TEXT namespace text { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::text_wiarchive, boost::archive::text_woarchive) } // namespace text #endif // _QX_SERIALIZE_WIDE_TEXT #if _QX_SERIALIZE_WIDE_XML namespace xml { QX_ARCHIVE_NAMESPACE_FCT_IMPL(T, boost::archive::xml_wiarchive, boost::archive::xml_woarchive) } // namespace xml #endif // _QX_SERIALIZE_WIDE_XML } // namespace wide } // namespace serialization } // namespace qx #endif // _QX_ARCHIVE_H_
[ [ [ 1, 144 ] ] ]
4fc1d3e8cbeb78b952f9bb9e4eab0033cf795f02
5c4e36054f0752a610ad149dfd81e6f35ccb37a1
/libs/src2.75/BulletCollision/CollisionShapes/btConvexHullShape.cpp
fea2d31ecf071c9fc6538ff8ad9c56a08a6654c0
[]
no_license
Akira-Hayasaka/ofxBulletPhysics
4141dc7b6dff7e46b85317b0fe7d2e1f8896b2e4
5e45da80bce2ed8b1f12de9a220e0c1eafeb7951
refs/heads/master
2016-09-15T23:11:01.354626
2011-09-22T04:11:35
2011-09-22T04:11:35
1,152,090
6
0
null
null
null
null
UTF-8
C++
false
false
4,691
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "btConvexHullShape.h" #include "BulletCollision/CollisionShapes/btCollisionMargin.h" #include "LinearMath/btQuaternion.h" btConvexHullShape ::btConvexHullShape (const btScalar* points,int numPoints,int stride) : btPolyhedralConvexAabbCachingShape () { m_shapeType = CONVEX_HULL_SHAPE_PROXYTYPE; m_unscaledPoints.resize(numPoints); unsigned char* pointsAddress = (unsigned char*)points; for (int i=0;i<numPoints;i++) { btScalar* point = (btScalar*)pointsAddress; m_unscaledPoints[i] = btVector3(point[0], point[1], point[2]); pointsAddress += stride; } recalcLocalAabb(); } void btConvexHullShape::setLocalScaling(const btVector3& scaling) { m_localScaling = scaling; recalcLocalAabb(); } void btConvexHullShape::addPoint(const btVector3& point) { m_unscaledPoints.push_back(point); recalcLocalAabb(); } btVector3 btConvexHullShape::localGetSupportingVertexWithoutMargin(const btVector3& vec0)const { btVector3 supVec(btScalar(0.),btScalar(0.),btScalar(0.)); btScalar newDot,maxDot = btScalar(-BT_LARGE_FLOAT); btVector3 vec = vec0; btScalar lenSqr = vec.length2(); if (lenSqr < btScalar(0.0001)) { vec.setValue(1,0,0); } else { btScalar rlen = btScalar(1.) / btSqrt(lenSqr ); vec *= rlen; } for (int i=0;i<m_unscaledPoints.size();i++) { btVector3 vtx = m_unscaledPoints[i] * m_localScaling; newDot = vec.dot(vtx); if (newDot > maxDot) { maxDot = newDot; supVec = vtx; } } return supVec; } void btConvexHullShape::batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { btScalar newDot; //use 'w' component of supportVerticesOut? { for (int i=0;i<numVectors;i++) { supportVerticesOut[i][3] = btScalar(-BT_LARGE_FLOAT); } } for (int i=0;i<m_unscaledPoints.size();i++) { btVector3 vtx = getScaledPoint(i); for (int j=0;j<numVectors;j++) { const btVector3& vec = vectors[j]; newDot = vec.dot(vtx); if (newDot > supportVerticesOut[j][3]) { //WARNING: don't swap next lines, the w component would get overwritten! supportVerticesOut[j] = vtx; supportVerticesOut[j][3] = newDot; } } } } btVector3 btConvexHullShape::localGetSupportingVertex(const btVector3& vec)const { btVector3 supVertex = localGetSupportingVertexWithoutMargin(vec); if ( getMargin()!=btScalar(0.) ) { btVector3 vecnorm = vec; if (vecnorm .length2() < (SIMD_EPSILON*SIMD_EPSILON)) { vecnorm.setValue(btScalar(-1.),btScalar(-1.),btScalar(-1.)); } vecnorm.normalize(); supVertex+= getMargin() * vecnorm; } return supVertex; } //currently just for debugging (drawing), perhaps future support for algebraic continuous collision detection //Please note that you can debug-draw btConvexHullShape with the Raytracer Demo int btConvexHullShape::getNumVertices() const { return m_unscaledPoints.size(); } int btConvexHullShape::getNumEdges() const { return m_unscaledPoints.size(); } void btConvexHullShape::getEdge(int i,btVector3& pa,btVector3& pb) const { int index0 = i%m_unscaledPoints.size(); int index1 = (i+1)%m_unscaledPoints.size(); pa = getScaledPoint(index0); pb = getScaledPoint(index1); } void btConvexHullShape::getVertex(int i,btVector3& vtx) const { vtx = getScaledPoint(i); } int btConvexHullShape::getNumPlanes() const { return 0; } void btConvexHullShape::getPlane(btVector3& ,btVector3& ,int ) const { btAssert(0); } //not yet bool btConvexHullShape::isInside(const btVector3& ,btScalar ) const { btAssert(0); return false; }
[ [ [ 1, 188 ] ] ]
ad9f0646a8220405927810440e689cc0e871ccd3
cfb0fafddd1df76e22b1b4212ba9102693f100fa
/Kernel/USBRemover/MessageManager.h
4381103f1bbc04d3459757deedecbc3e391bf29e
[]
no_license
ExaByt3s/usbremover
ef8fecc6030d23f178c2cd50dbc5557e06c42322
13a6b6802a2f968d6cf923fd1821b03999292d5e
refs/heads/master
2020-04-11T14:48:34.107832
2011-04-09T07:51:39
2011-04-09T07:51:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,539
h
/* MessageManager.h Started: 12.08.2010 Author: Asha'man Email: [email protected] License: LGPL v3 <?> Message manager class: declarations */ #ifndef _H_MSGMGR #define _H_MSGMGR //API headers #include <windows.h> #include <dbt.h> #include "ApiWrapper.h" #include "WinAPIException.h" #include "IMessageListener.h" /* Description: This class is for registering and handling device arrival and removal notifications. It is designed in such way that it is possible to use both service status handles and window handles */ class MessageManager { private: bool pause; //paused or not HANDLE wndHandle; //receiver window handle HDEVNOTIFY notificationHandle; //device notification handle PDEV_BROADCAST_DEVICEINTERFACE messageFilter; //message filter for the devices; DelegateSet *listeners; //listeners void FireEvent(); //notifies all listeners abouth the changes void SetMessageFilter(); //setting message filter friend DWORD WINAPI InvokeOnInstallation(LPVOID parameters); //invocated on install event public: MessageManager(HANDLE hWnd, DWORD flags); //constructor ~MessageManager(); //destructor void AttachListener(IMessageListener &listener); //registering message listener void DetachListener(IMessageListener &listener); //unregistering message listener void Pause(); //pauses the manager's work void ProcessEvent(LPVOID messageData, DWORD messageCode); //processing messages by their code void Resume(); //resumes the manager's work }; #endif
[ "[email protected]@8417aba2-bd37-11de-8784-f7ad4773dbab" ]
[ [ [ 1, 51 ] ] ]
d759327591168e767e085d93bad69b3243a9fae5
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_events/messages/juce_MessageManager.h
075f6ef95dac6f35e0e65f22e791a903791baefe
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
12,673
h
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCE_MESSAGEMANAGER_JUCEHEADER__ #define __JUCE_MESSAGEMANAGER_JUCEHEADER__ #include "juce_CallbackMessage.h" class MessageManagerLock; class ThreadPoolJob; class ActionListener; class ActionBroadcaster; //============================================================================== /** See MessageManager::callFunctionOnMessageThread() for use of this function type */ typedef void* (MessageCallbackFunction) (void* userData); //============================================================================== /** Delivers Message objects to MessageListeners, and handles the event-dispatch loop. @see Message, MessageListener, MessageManagerLock, JUCEApplication */ class JUCE_API MessageManager { public: //============================================================================== /** Returns the global instance of the MessageManager. */ static MessageManager* getInstance(); /** Deletes the global MessageManager instance. Does nothing if no instance had been created. */ static void deleteInstance(); //============================================================================== /** Runs the event dispatch loop until a stop message is posted. This method is only intended to be run by the application's startup routine, as it blocks, and will only return after the stopDispatchLoop() method has been used. @see stopDispatchLoop */ void runDispatchLoop(); /** Sends a signal that the dispatch loop should terminate. After this is called, the runDispatchLoop() or runDispatchLoopUntil() methods will be interrupted and will return. @see runDispatchLoop */ void stopDispatchLoop(); /** Returns true if the stopDispatchLoop() method has been called. */ bool hasStopMessageBeenSent() const noexcept { return quitMessagePosted; } #if JUCE_MODAL_LOOPS_PERMITTED /** Synchronously dispatches messages until a given time has elapsed. Returns false if a quit message has been posted by a call to stopDispatchLoop(), otherwise returns true. */ bool runDispatchLoopUntil (int millisecondsToRunFor); #endif //============================================================================== /** Calls a function using the message-thread. This can be used by any thread to cause this function to be called-back by the message thread. If it's the message-thread that's calling this method, then the function will just be called; if another thread is calling, a message will be posted to the queue, and this method will block until that message is delivered, the function is called, and the result is returned. Be careful not to cause any deadlocks with this! It's easy to do - e.g. if the caller thread has a critical section locked, which an unrelated message callback then tries to lock before the message thread gets round to processing this callback. @param callback the function to call - its signature must be @code void* myCallbackFunction (void*) @endcode @param userData a user-defined pointer that will be passed to the function that gets called @returns the value that the callback function returns. @see MessageManagerLock */ void* callFunctionOnMessageThread (MessageCallbackFunction* callback, void* userData); /** Returns true if the caller-thread is the message thread. */ bool isThisTheMessageThread() const noexcept; /** Called to tell the manager that the current thread is the one that's running the dispatch loop. (Best to ignore this method unless you really know what you're doing..) @see getCurrentMessageThread */ void setCurrentThreadAsMessageThread(); /** Returns the ID of the current message thread, as set by setCurrentMessageThread(). (Best to ignore this method unless you really know what you're doing..) @see setCurrentMessageThread */ Thread::ThreadID getCurrentMessageThread() const noexcept { return messageThreadId; } /** Returns true if the caller thread has currenltly got the message manager locked. see the MessageManagerLock class for more info about this. This will be true if the caller is the message thread, because that automatically gains a lock while a message is being dispatched. */ bool currentThreadHasLockedMessageManager() const noexcept; //============================================================================== /** Sends a message to all other JUCE applications that are running. @param messageText the string that will be passed to the actionListenerCallback() method of the broadcast listeners in the other app. @see registerBroadcastListener, ActionListener */ static void broadcastMessage (const String& messageText); /** Registers a listener to get told about broadcast messages. The actionListenerCallback() callback's string parameter is the message passed into broadcastMessage(). @see broadcastMessage */ void registerBroadcastListener (ActionListener* listener); /** Deregisters a broadcast listener. */ void deregisterBroadcastListener (ActionListener* listener); //============================================================================== #ifndef DOXYGEN // Internal methods - do not use! void deliverMessage (Message*); void deliverBroadcastMessage (const String&); ~MessageManager() noexcept; #endif private: //============================================================================== MessageManager() noexcept; friend class MessageListener; friend class ChangeBroadcaster; friend class ActionBroadcaster; friend class CallbackMessage; static MessageManager* instance; SortedSet <const MessageListener*> messageListeners; ScopedPointer <ActionBroadcaster> broadcaster; friend class JUCEApplication; bool quitMessagePosted, quitMessageReceived; Thread::ThreadID messageThreadId; friend class MessageManagerLock; Thread::ThreadID volatile threadWithLock; CriticalSection lockingLock; void postMessageToQueue (Message* message); static bool postMessageToSystemQueue (Message*); static void* exitModalLoopCallback (void*); static void doPlatformSpecificInitialisation(); static void doPlatformSpecificShutdown(); static bool dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages); JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MessageManager); }; //============================================================================== /** Used to make sure that the calling thread has exclusive access to the message loop. Because it's not thread-safe to call any of the Component or other UI classes from threads other than the message thread, one of these objects can be used to lock the message loop and allow this to be done. The message thread will be suspended for the lifetime of the MessageManagerLock object, so create one on the stack like this: @code void MyThread::run() { someData = 1234; const MessageManagerLock mmLock; // the event loop will now be locked so it's safe to make a few calls.. myComponent->setBounds (newBounds); myComponent->repaint(); // ..the event loop will now be unlocked as the MessageManagerLock goes out of scope } @endcode Obviously be careful not to create one of these and leave it lying around, or your app will grind to a halt! Another caveat is that using this in conjunction with other CriticalSections can create lots of interesting ways of producing a deadlock! In particular, if your message thread calls stopThread() for a thread that uses these locks, you'll get an (occasional) deadlock.. @see MessageManager, MessageManager::currentThreadHasLockedMessageManager */ class JUCE_API MessageManagerLock { public: //============================================================================== /** Tries to acquire a lock on the message manager. The constructor attempts to gain a lock on the message loop, and the lock will be kept for the lifetime of this object. Optionally, you can pass a thread object here, and while waiting to obtain the lock, this method will keep checking whether the thread has been given the Thread::signalThreadShouldExit() signal. If this happens, then it will return without gaining the lock. If you pass a thread, you must check whether the lock was successful by calling lockWasGained(). If this is false, your thread is being told to die, so you should take evasive action. If you pass zero for the thread object, it will wait indefinitely for the lock - be careful when doing this, because it's very easy to deadlock if your message thread attempts to call stopThread() on a thread just as that thread attempts to get the message lock. If the calling thread already has the lock, nothing will be done, so it's safe and quick to use these locks recursively. E.g. @code void run() { ... while (! threadShouldExit()) { MessageManagerLock mml (Thread::getCurrentThread()); if (! mml.lockWasGained()) return; // another thread is trying to kill us! ..do some locked stuff here.. } ..and now the MM is now unlocked.. } @endcode */ MessageManagerLock (Thread* threadToCheckForExitSignal = 0); //============================================================================== /** This has the same behaviour as the other constructor, but takes a ThreadPoolJob instead of a thread. See the MessageManagerLock (Thread*) constructor for details on how this works. */ MessageManagerLock (ThreadPoolJob* jobToCheckForExitSignal); //============================================================================== /** Releases the current thread's lock on the message manager. Make sure this object is created and deleted by the same thread, otherwise there are no guarantees what will happen! */ ~MessageManagerLock() noexcept; //============================================================================== /** Returns true if the lock was successfully acquired. (See the constructor that takes a Thread for more info). */ bool lockWasGained() const noexcept { return locked; } private: class BlockingMessage; friend class ReferenceCountedObjectPtr<BlockingMessage>; ReferenceCountedObjectPtr<BlockingMessage> blockingMessage; bool locked; void init (Thread* thread, ThreadPoolJob* job); JUCE_DECLARE_NON_COPYABLE (MessageManagerLock); }; #endif // __JUCE_MESSAGEMANAGER_JUCEHEADER__
[ "ow3nskip" ]
[ [ [ 1, 313 ] ] ]
917fa39c20a9cb7bcae82516a3d21de65a3113a9
3449de09f841146a804930f2a51ccafbc4afa804
/C++/CodeJam/practice/OneFight.cpp
3ff259994a5f389cfddf743ed59f19ff3c2696a9
[]
no_license
davies/daviescode
0c244f4aebee1eb909ec3de0e4e77db3a5bbacee
bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd
refs/heads/master
2020-06-04T23:32:27.360979
2007-08-19T06:31:49
2007-08-19T06:31:49
32,641,672
1
1
null
null
null
null
UTF-8
C++
false
false
6,194
cpp
// BEGIN CUT HERE // PROBLEM STATEMENT // In some computer game, you are surrounded by monsters, and // you are to kill them all. Each monster has some number of // life points and damage points, and you also have some // number of damage points. Life points represent the amount // of life left in a monster. As long as a monster has one or // more life points, it remains alive. Damage points // represent the number of life points that are taken away // from an enemy by a single attack. At every turn, you are // attacked by each of the living monsters, and then you // attack exactly one of them (at the same turn). // // You are given a vector <int> life, the number of life // points that each monster starts out with, a vector <int> // damage, the number of damage points each monster has, and // an int yourDamage, the number of damage points you have. // The ith elements of life and damage represent the life // points and damage points for the ith monster. Return the // minimal number of life points you must start out with in // order to kill all the monsters. At the end of the fight, // you must have one or more life points remaining. // // DEFINITION // Class:OneFight // Method:monsterKilling // Parameters:vector <int>, vector <int>, int // Returns:int // Method signature:int monsterKilling(vector <int> life, // vector <int> damage, int yourDamage) // // // CONSTRAINTS // -life will have between 1 and 10 elements, inclusive. // -life and damage will have the same number of elements. // -All elements of life will be between 1 and 100, inclusive. // -All elements of damage will be between 0 and 100, // inclusive. // -yourDamage will be between 1 and 100, inclusive. // // // EXAMPLES // // 0) // {3} // {10} // 2 // // Returns: 21 // // You must hit the monster twice. You lose 20 life points in // the fight. Since you must have at least 1 life point // remaining, the answer is 21. // // 1) // {5,1} // {5,3} // 3 // // Returns: 19 // // If you kill the first monster and then the second one, you // will lose (3+5) + (3+5) + 3 = 19 life points. If you kill // the second monster and then first one, you will lose (3+5) // + 5 + 5 = 18 life points. You choose the latter option. // // 2) // {5,5,5,5,5,5,5,5,5,5} // {10,20,30,40,50,60,70,80,90,100} // 100 // // Returns: 2201 // // Kill all the monsters in reverse order from last to first. // // 3) // {6,34,21,79,31,5,8,23,9,100} // {1,65,95,32,48,9,3,13,100,4} // 4 // // Returns: 6554 // #line 84 "OneFight.cpp" // END CUT HERE #include <string> #include <iostream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <list> #include <set> #include <map> #include <cmath> #include <valarray> #include <numeric> #include <functional> #include <algorithm> using namespace std; typedef long long ll; typedef vector<int> VI; typedef vector< VI > VVI; typedef vector<char> VC; typedef vector<string> VS; typedef map<int,int> MII; typedef map<string,int> MSI; #define SZ(v) ((int)(v).size()) #define FOR(i,a,b) for(int i=(a);i<int(b);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() #define FOUND(v,p) (find(ALL(v),p)!=v.end()) #define SUM(v) accumulate(ALL(v),0) #define SE(i) (i)->second #define DV(v) REP(i,SZ(v)) cout << v[i] << " "; cout << endl typedef stringstream SS; typedef istringstream ISS; typedef ostringstream OSS; template<class U,class T> T cast(U x){T y; OSS a; a<<x; ISS b(a.str());b>>y;return y;} class OneFight { public: int monsterKilling(vector <int> _life, vector <int> _damage, int yourDamage) { int re=100000; int N=SZ(life); VI order(N); REP(i,N) order[i] = i; do{ int ex=0; int l=1; REP(i,N){ ex += (life[order[i]]+yourDamage-1)/yourDamage; l += ex * damage[order[i]]; } re = min(re,l); }while(next_permutation(ALL(order))); return re; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; int Arg3 = 21; verify_case(0, Arg3, monsterKilling(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {5,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {5,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; int Arg3 = 19; verify_case(1, Arg3, monsterKilling(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {5,5,5,5,5,5,5,5,5,5}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10,20,30,40,50,60,70,80,90,100}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 100; int Arg3 = 2201; verify_case(2, Arg3, monsterKilling(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {6,34,21,79,31,5,8,23,9,100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,65,95,32,48,9,3,13,100,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 4; int Arg3 = 6554; verify_case(3, Arg3, monsterKilling(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { OneFight ___test; ___test.run_test(-1); } // END CUT HERE
[ "davies.liu@32811f3b-991a-0410-9d68-c977761b5317" ]
[ [ [ 1, 167 ] ] ]
fe780a4c0ca1a3fc5ef37c652e8ede8046f39329
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
/src/enemies/spika.h
508479fd0d01db011bfe1bb1a13f126f0b78caf1
[]
no_license
renardchien/Eta-Chronicles
27ad4ffb68385ecaafae4f12b0db67c096f62ad1
d77d54184ec916baeb1ab7cc00ac44005d4f5624
refs/heads/master
2021-01-10T19:28:28.394781
2011-09-05T14:40:38
2011-09-05T14:40:38
1,914,623
1
2
null
null
null
null
UTF-8
C++
false
false
2,823
h
/*************************************************************************** * spika.h - headers for the corresponding cpp file * * Copyright (C) 2006 - 2009 Florian Richter ***************************************************************************/ /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SMC_SPIKA_H #define SMC_SPIKA_H #include "../enemies/enemy.h" namespace SMC { /* *** *** *** *** *** *** cSpika *** *** *** *** *** *** *** *** *** *** *** */ class cSpika : public cEnemy { /* Spika * Will wait for you and wheel you * if you can't run fast enough :D * * Colors : Orange, Green and Grey */ public: // constructor cSpika( float x, float y ); // create from stream cSpika( CEGUI::XMLAttributes &attributes ); // destructor virtual ~cSpika( void ); // init defaults void Init( void ); // copy virtual cSpika *Copy( void ); // create from stream virtual void Create_From_Stream( CEGUI::XMLAttributes &attributes ); // save to stream virtual void Save_To_Stream( ofstream &file ); // set color void Set_Color( DefaultColor col ); /* downgrade state ( if already weakest state : dies ) * force : usually dies or a complete downgrade */ virtual void DownGrade( bool force = 0 ); // dying animation update virtual void Update_Dying( void ); // update virtual void Update( void ); // if update is valid for the current state virtual bool Is_Update_Valid( void ); /* Validate the given collision object * returns 0 if not valid * returns 1 if an internal collision with this object is valid * returns 2 if the given object collides with this object (blocking) */ virtual Col_Valid_Type Validate_Collision( cSprite *obj ); // collision from player virtual void Handle_Collision_Player( cObjectCollision *collision ); // collision from an enemy virtual void Handle_Collision_Enemy( cObjectCollision *collision ); // collision with massive virtual void Handle_Collision_Massive( cObjectCollision *collision ); // collision from a box virtual void Handle_Collision_Box( ObjectDirection cdirection, GL_rect *r2 ); // Color DefaultColor m_color_type; // default speed float m_speed; // default detection size float m_detection_size; // counter for walking float m_walk_count; }; /* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */ } // namespace SMC #endif
[ [ [ 1, 98 ] ] ]
f9d6f5f9853929029bc9a27f79bf5c678806efb8
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/terrain/nterrain_main.cc
8e98e45a5d4da5a3e27349392d3870f4b6202055
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,546
cc
#define N_IMPLEMENTS nTerrainNode //------------------------------------------------------------------- // nterrain_main.cc // (C) 2000 A.Weissflog //------------------------------------------------------------------- #include "kernel/ntimeserver.h" #include "gfx/nscenegraph2.h" #include "terrain/nterrainnode.h" nNebulaScriptClass(nTerrainNode, "nvisnode"); std::vector<float> quadsquare::sin_lookup; std::vector<float> quadsquare::cos_lookup; nProfiler* nTerrainNode::p_update = 0; nProfiler* nTerrainNode::p_render = 0; //------------------------------------------------------------------- // nTerrainNode() // 23-Mar-00 floh created // 06-Oct-00 floh rewritten to ndynmeshnode // 17-Oct-00 floh rewritten again to ndynvertexbuffer //------------------------------------------------------------------- nTerrainNode::nTerrainNode() : ref_ibuf(this), dyn_vb(kernelServer,this), ref_gs(kernelServer,this), refSceneGraph(kernelServer,this), refFile(kernelServer, this) { this->ref_gs = "/sys/servers/gfx"; this->refSceneGraph = "/sys/servers/sgraph2"; this->refFile = "/sys/servers/file2"; this->map_dirty = false; this->first_run = false; this->detail = 100.0f; this->static_error = 8.0f; this->uv_scale = 1.0f; this->radius = 10.0f; this->quad_pool = NULL; this->free_quads = NULL; this->render_pass = 0; this->num_triangles = 0; this->stride4 = 0; this->cur_vertex = 0; this->cur_triangle = 0; this->cur_vb = NULL; this->coord = NULL; this->norm = NULL; n_memset(this->uv,0,sizeof(this->uv)); this->in_render = false; this->precull_nodes = 0; this->postcull_nodes = 0; // initialize root-corner-data int i; for (i=0; i<4; i++) { this->root_vertices[i].y = 0; } this->root_corner_data.parent = NULL; this->root_corner_data.square = NULL; this->root_corner_data.child_index = 0; this->root_corner_data.level = 15; this->root_corner_data.xorg = 0; this->root_corner_data.zorg = 0; for (i = 0; i < 4; i++) { this->root_corner_data.verts[i] = &(this->root_vertices[i]); } this->root_node = NULL; this->fp = NULL; this->num_tris = 0; } void nTerrainNode::Initialize() { if (this->GetClass()->GetRef() == 1) { // initialize the sincos lookup-table quadsquare::sin_lookup.resize(quadsquare::LOOKUP_ENTRIES+1); quadsquare::cos_lookup.resize(quadsquare::LOOKUP_ENTRIES+1); float a = 0.0f; float da = (2.0f*(nReal)N_PI)/float(quadsquare::LOOKUP_ENTRIES); for (int i = 0; i <= quadsquare::LOOKUP_ENTRIES; i++) { quadsquare::sin_lookup[i] = n_sin(a); quadsquare::cos_lookup[i] = n_cos(a); a += da; } // initialize profilers nTerrainNode::p_update = kernelServer->ts->NewProfiler("terr_update"); nTerrainNode::p_render = kernelServer->ts->NewProfiler("terr_render"); } nVisNode::Initialize(); } //------------------------------------------------------------------- // ~TerrainNode() // 23-Mar-00 floh created //------------------------------------------------------------------- nTerrainNode::~nTerrainNode() { if (this->root_node) this->root_node->Release(this); if (this->quad_pool) delete[] this->quad_pool; if (this->GetClass()->GetRef() == 1) { kernelServer->ts->ReleaseProfiler(nTerrainNode::p_update); kernelServer->ts->ReleaseProfiler(nTerrainNode::p_render); if (!quadsquare::sin_lookup.empty()) { quadsquare::sin_lookup.clear(); } if (!quadsquare::cos_lookup.empty()) { quadsquare::cos_lookup.clear(); } } } //------------------------------------------------------------------- // SetDetail() // 26-Mar-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetDetail(float d) { this->detail = d; } //------------------------------------------------------------------- // GetDetail() // 26-Mar-00 floh created //------------------------------------------------------------------- float nTerrainNode::GetDetail(void) { return this->detail; } //------------------------------------------------------------------- // SetStaticError() // 30-Mar-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetStaticError(float f) { this->static_error = f; this->map_dirty = true; } //------------------------------------------------------------------- // GetStaticError() // 30-Mar-00 floh created //------------------------------------------------------------------- float nTerrainNode::GetStaticError(void) { return this->static_error; } //------------------------------------------------------------------- // SetRadius() // 27-Mar-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetRadius(float r) { this->radius = r; this->vertex_radius = this->radius / float(1<<16); this->map_dirty = true; } //------------------------------------------------------------------- // GetRadius() // 27-Mar-00 floh created //------------------------------------------------------------------- float nTerrainNode::GetRadius(void) { return this->radius; } //------------------------------------------------------------------- // SetUvScale() // 27-Mar-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetUvScale(float s) { this->uv_scale = s; } //------------------------------------------------------------------- // GetUvScale() // 27-Mar-00 floh created //------------------------------------------------------------------- float nTerrainNode::GetUvScale(void) { return this->uv_scale; } //------------------------------------------------------------------- // SetHeightMap() // 27-Mar-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetHeightMap(const char *name) { this->image_path.Set(this->refFile.get(),name); this->tree_path.Clear(); this->map_dirty = true; } //------------------------------------------------------------------- // GetHeightMap() // 27-Mar-00 floh created //------------------------------------------------------------------- const char *nTerrainNode::GetHeightMap(void) { return this->image_path.GetPath(); } //------------------------------------------------------------------- // SetTreeFile() // 26-Apr-00 floh created //------------------------------------------------------------------- void nTerrainNode::SetTreeFile(const char *name) { this->tree_path.Set(this->refFile.get(),name); this->image_path.Clear(); this->map_dirty = true; } //------------------------------------------------------------------- // GetTreeFile() // 26-Apr-00 floh created //------------------------------------------------------------------- const char *nTerrainNode::GetTreeFile(void) { return this->tree_path.GetPath(); } //------------------------------------------------------------------- // GetNumNodes() // Get number of nodes in tree before // and after static culling (for statistics). // 27-Apr-00 floh created //------------------------------------------------------------------- void nTerrainNode::GetNumNodes(int& precull, int& postcull) { precull = this->precull_nodes; postcull = this->postcull_nodes; } //------------------------------------------------------------------- // Attach() // 26-Mar-00 floh created //------------------------------------------------------------------- bool nTerrainNode::Attach(nSceneGraph2* sceneGraph) { if (nVisNode::Attach(sceneGraph)) { sceneGraph->AttachVisualNode(this); return true; } return false; } //------------------------------------------------------------------- // Intersect() // Intersect line with terrain, return true if intersection // occurs and point of intersection. Line must already have been // translated into the terrains local coordinate system. // 20-Apr-00 floh created // 03-May-00 floh load map if not happened yet, because // intersection may happen at any time //------------------------------------------------------------------- bool nTerrainNode::Intersect(line3& l, float& ipos, triangle& itri) { // make sure everything is loaded... if (this->map_dirty) this->load_map(); // store line for visualization this->iline = l; // scale line into terrain's number range line3 l0(l.va()/this->vertex_radius, l.vb()/this->vertex_radius); // call the quadtree's intersect method ipos = 2.0f; // initialize with outside-bounds-value if (this->root_node->Intersect(this->root_corner_data,l0,ipos,itri)) { n_assert((ipos>=0.0f) && (ipos<=1.0f)); this->iposition = l.ipol(ipos); this->itriangle = itri; return true; } else { this->iposition.set(0.0f,0.0f,0.0f); return false; } } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 305 ] ] ]
177d8d6b2524b5cf0b9d74412b53b66084806679
c267e416aba473054330378d18bc3cd172bbad21
/MyEclipseKeyGen/MyEclipseKeyGenDlg.cpp
a15bc5b9c761a37ef5aa8b64cd2bdec9b8bed8ff
[]
no_license
chenwp/shuax
c3b7dea72708ee539664ac8db1d9885e87fefed7
b13bea0aae7e252650f4c8f5df1b2a716455ef80
refs/heads/master
2021-04-26T16:43:25.168306
2011-10-22T15:09:37
2011-10-22T15:09:37
45,179,472
2
0
null
null
null
null
GB18030
C++
false
false
4,370
cpp
// MyEclipseKeyGenDlg.cpp : implementation file // #include "stdafx.h" #include "MyEclipseKeyGen.h" #include "MyEclipseKeyGenDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static char LL[] = "Decompiling this copyrighted software is a violation of both your license agreement and the Digital Millenium Copyright Act of 1998 (http://www.loc.gov/copyright/legislation/dmca.pdf). Under section 1204 of the DMCA, penalties range up to a $500,000 fine or up to five years imprisonment for a first offense. Think about it; pay for a license, avoid prosecution, and feel better about yourself."; static int year=3; //年限1-3 static int license=20; //许可数0-999,0为不限制 static char type[]="YE3MP"; //YE3MB,YE3MP ///////////////////////////////////////////////////////////////////////////// // CMyEclipseKeyGenDlg dialog CMyEclipseKeyGenDlg::CMyEclipseKeyGenDlg(CWnd* pParent /*=NULL*/) : CDialog(CMyEclipseKeyGenDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMyEclipseKeyGenDlg) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMyEclipseKeyGenDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMyEclipseKeyGenDlg) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CMyEclipseKeyGenDlg, CDialog) //{{AFX_MSG_MAP(CMyEclipseKeyGenDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_EN_CHANGE(IDC_EDIT1, OnChangeEdit1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMyEclipseKeyGenDlg message handlers BOOL CMyEclipseKeyGenDlg::OnInitDialog() { CDialog::OnInitDialog(); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here GetDlgItem(IDC_EDIT1)->SetWindowText("http://www.shuax.com"); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CMyEclipseKeyGenDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } HCURSOR CMyEclipseKeyGenDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CMyEclipseKeyGenDlg::OnChangeEdit1() { char src[128]; int len=GetDlgItem(IDC_EDIT1)->GetWindowTextLength()+1; GetDlgItem(IDC_EDIT1)->GetWindowText(src, len); GetDlgItem(IDC_EDIT2)->SetWindowText(MyEclipseKeyGen(src)); } long CMyEclipseKeyGenDlg::decode(char *s) { long ret=0; for (int i=0;s[i]!=0;i++) ret = (31 * ret) + s[i]; return abs(ret); } char* CMyEclipseKeyGenDlg::change(char *s) { char j; int k=strlen(s); for (int i=0;i<k;i++) { j = s[i]; if ((j >= 48) && (j <= 57)) { j = (((j - 48) + 5) % 10) + 48; } else if ((j >= 65) && (j <= 90)) { j = (((j - 65) + 13) % 26) + 65; } else if ((j >= 97) && (j <= 122)) { j = (((j - 97) + 13) % 26) + 97; } s[i] = j; } return s; } char* CMyEclipseKeyGenDlg::MyEclipseKeyGen(char *userId) { SYSTEMTIME time; GetLocalTime(&time); time.wYear+=year; time.wDay-=1; char res[512]; wsprintf(res,"%c%s-300%03d-%02d%02d%02d0%s%s\0",userId[0],type,license,time.wYear-2000,time.wMonth,time.wDay,LL,userId); //printf(res); long suf=decode(res); wsprintf(res,"%c%s-300%03d-%02d%02d%02d0%d",userId[0],type,license,time.wYear-2000,time.wMonth,time.wDay,suf); return change(res); }
[ [ [ 1, 137 ] ] ]
8d7b8e0a393f8a02ad24dccf43dc61b403f45b01
6712f8313dd77ae820aaf400a5836a36af003075
/testJS.cpp
8df2392d8e2d6291c68d45da90112c7a5180b778
[]
no_license
AdamTT1/bdScript
d83c7c63c2c992e516dca118cfeb34af65955c14
5483f239935ec02ad082666021077cbc74d1790c
refs/heads/master
2021-12-02T22:57:35.846198
2010-08-08T22:32:02
2010-08-08T22:32:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,074
cpp
/* * Program testJS.cpp * * This program is simply a compilation test of the Netscape * Javascript interpreter source and build * * * Change History : * * $Log: testJS.cpp,v $ * Revision 1.20 2002-12-15 00:08:46 ericn * -removed debug msgs * * Revision 1.19 2002/11/30 18:52:57 ericn * -modified to queue jsval's instead of strings * * Revision 1.18 2002/11/30 16:28:32 ericn * -added MP3 support * * Revision 1.17 2002/11/30 05:29:21 ericn * -moved shutdown of disk cache * * Revision 1.16 2002/11/30 02:01:14 ericn * -rewrote as jsExec minus touch and sound * * Revision 1.15 2002/11/30 00:30:49 ericn * -removed curlCache and curlThread modules * * Revision 1.14 2002/10/31 02:03:17 ericn * -added curl thread startup/shutdown * * Revision 1.13 2002/10/27 17:38:40 ericn * -added hyperlink and process calls * * Revision 1.12 2002/10/26 14:13:54 ericn * -removed debug stmt * * Revision 1.11 2002/10/25 04:48:39 ericn * -limited Javascript memory to 1MB * * Revision 1.10 2002/10/25 03:07:16 ericn * -removed debug statements * * Revision 1.9 2002/10/25 02:20:05 ericn * -added child process initialization calls * * Revision 1.8 2002/10/24 13:16:21 ericn * -added MP3, relative URL support * * Revision 1.7 2002/10/20 16:30:11 ericn * -added URL support * * Revision 1.6 2002/10/18 01:18:13 ericn * -added text and screen clear support * * Revision 1.5 2002/10/13 15:52:07 ericn * -added ref to image module * * Revision 1.4 2002/09/29 17:35:55 ericn * -added curlFile class * * Revision 1.3 2002/09/28 17:05:07 ericn * -changed copyright tag * * Revision 1.2 2002/09/28 17:04:16 ericn * -changed #include references * * Revision 1.1.1.1 2002/09/28 16:50:46 ericn * -Initial import * * * Copyright Boundary Devices, Inc. 2002 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <sys/time.h> /* include the JS engine API header */ #include "js/jsstddef.h" #include "js/jsapi.h" #include "relativeURL.h" #include "jsHyperlink.h" #include "codeQueue.h" #include "jsTimer.h" #include "jsCurl.h" #include "jsImage.h" #include "jsGlobals.h" #include "jsScreen.h" #include "jsText.h" #include "jsAlphaMap.h" #include "jsTouch.h" #include "jsMP3.h" #include "jsVolume.h" #include "jsBarcode.h" #include "jsShell.h" #include "jsButton.h" #include "ccActiveURL.h" #include "ccDiskCache.h" #include "ccWorker.h" #include "urlFile.h" static JSBool global_resolve(JSContext *cx, JSObject *obj, jsval id, uintN flags, JSObject **objp) { if ((flags & JSRESOLVE_ASSIGNING) == 0) { JSBool resolved; if (!JS_ResolveStandardClass(cx, obj, id, &resolved)) return JS_FALSE; if (resolved) { *objp = obj; return JS_TRUE; } } return JS_TRUE; } static JSClass global_class = { "global", JSCLASS_NEW_RESOLVE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStandardClasses, (JSResolveOp) global_resolve, JS_ConvertStub, JS_FinalizeStub }; static JSBool Print(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { uintN i, n; JSString *str; for (i = n = 0; i < argc; i++) { str = JS_ValueToString(cx, argv[i]); if (!str) return JS_FALSE; fprintf(stdout, "%s%s", i ? " " : "", JS_GetStringBytes(str)); } n++; if (n) fputc('\n', stdout); return JS_TRUE; } static JSBool jsQueueCode( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_TRUE ; for( int arg = 0 ; arg < argc ; arg++ ) { if( !queueSource( obj, argv[arg], "queueCode" ) ) { fprintf( stderr, "error queuing code\n" ); *rval = JSVAL_FALSE ; } } return JS_TRUE; } static JSBool jsNanosleep( JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { if( ( 1 == argc ) && JSVAL_IS_NUMBER( argv[0] ) ) { double seconds ; JS_ValueToNumber( cx, argv[0], &seconds ); struct timespec tv ; tv.tv_sec = (unsigned)( floor( seconds ) ); tv.tv_nsec = (unsigned)( floor( fmod( seconds * 1000000000, 1000000000.0 ) ) ); // JS_ReportError( cx, "nanosleep %f : %u.%lu seconds\n", seconds, tv.tv_sec, tv.tv_nsec ); nanosleep( &tv, 0 ); *rval = JSVAL_TRUE ; } else { JS_ReportError( cx, "Usage : nanosleep( seconds )\n" ); *rval = JSVAL_FALSE ; } return JS_TRUE; } static JSFunctionSpec shell_functions[] = { {"print", Print, 0}, {"queueCode", jsQueueCode, 0}, {"nanosleep", jsNanosleep, 0}, {0} }; static void myError( JSContext *cx, const char *message, JSErrorReport *report) { fprintf( stderr, "Error %s\n", message ); fprintf( stderr, "file %s, line %u\n", report->filename, report->lineno ); } /* main function sets up global JS variables, including run time, * a context, and a global object, then initializes the JS run time, * and creates a context. */ int prMain(int argc, char **argv) { if( 2 == argc ) { // initialize the JS run time, and return result in rt JSRuntime * const rt = JS_NewRuntime(1L * 1024L * 1024L); if( rt ) { // create a context and associate it with the JS run time JSContext * const cx = JS_NewContext(rt, 8192); // if cx does not have a value, end the program here if( cx ) { execContext_ = cx ; // create the global object here JSObject *glob = JS_NewObject(cx, &global_class, NULL, NULL); if( 0 != glob ) { // initialize the built-in JS objects and the global object if( JS_InitStandardClasses(cx, glob) ) { if( JS_DefineFunctions( cx, glob, shell_functions) ) { initJSTimer( cx, glob ); initJSScreen( cx, glob ); initJSText( cx, glob ); initializeCodeQueue( cx, glob ); initJSCurl( cx, glob ); initJSImage( cx, glob ); initJSAlphaMap( cx, glob ); initJSHyperlink( cx, glob ); initJSVolume( cx, glob ); initJSMP3( cx, glob ); initJSBarcode( cx, glob ); initJSShell( cx, glob ); initJSButton( cx, glob ); getCurlCache(); urlFile_t f( argv[1] ); if( f.isOpen() ) { pushURL( argv[1] ); JSErrorReporter oldReporter = JS_SetErrorReporter( cx, myError ); JSScript *script= JS_CompileScript( cx, glob, (char const *)f.getData(), f.getSize(), argv[1], 1 ); if( script ) { jsval rval; JSBool exec ; { mutexLock_t lock( execMutex_ ); exec = JS_ExecuteScript( cx, glob, script, &rval ); JS_DestroyScript( cx, script ); } // limit if( exec ) { unsigned numEvents = 0 ; while( 1 ) { if( gotoCalled_ ) { break; } else { bool doGC = ( 0 == ( ++numEvents % 10 ) ); JSObject *scope ; if( dequeueByteCode( script, scope, 5000 ) ) { mutexLock_t lock( execMutex_ ); exec = JS_ExecuteScript( cx, scope, script, &rval ); if( !exec ) fprintf( stderr, "error executing code\n" ); JS_DestroyScript( cx, script ); } else doGC = true ; if( doGC ) { printf( "collectin' garbage\n" ); mutexLock_t lock( execMutex_ ); JS_GC( cx ); printf( "done\n" ); } } } } else fprintf( stderr, "exec error %s\n", argv[1] ); } else fprintf( stderr, "Error compiling script %s\n", argv[1] ); popURL(); } else fprintf( stderr, "Error opening url %s\n", argv[1] ); stopBarcodeThread(); shutdownCurlWorkers(); } else fprintf( stderr, "Error defining Javascript shell functions\n" ); } else fprintf( stderr, "Error creating Javascript builtins\n" ); } else fprintf( stderr, "Error allocating Javascript global\n" ); { mutexLock_t lock( execMutex_ ); JS_DestroyContext( cx ); } shutdownCCDiskCache(); } else fprintf( stderr, "Error initializing Javascript context\n" ); } else fprintf( stderr, "Error initializing Javascript runtime\n" ); } else fprintf( stderr, "Usage : testEvents url\n" ); return 0; } #include <prinit.h> int main( int argc, char *argv[] ) { int result = PR_Initialize( prMain, argc, argv, 0 ); if( gotoCalled_ ) { argv[1] = (char *)gotoURL_.c_str(); execv( argv[0], argv ); // start next } return result ; }
[ "ericn" ]
[ [ [ 1, 364 ] ] ]
fa186dcb91a0caa8c35c5b8b3b9389a38d3160dd
f246dc2a816ccd5acd0776a48c2c24cdb1f4178f
/libsrc/PigletLog.cpp
3d2cf637278dd57b465b2042eab3383ea514a696
[]
no_license
profcturner/pigletlib
3f2c4b1af000d73cf4a176a8463c16aaeefde99a
b2ccbb43270a5e8d3a0f8ae6bd3d3cb82a061fec
refs/heads/master
2021-07-24T07:23:10.577261
2007-08-26T22:36:47
2007-08-26T22:36:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,692
cpp
/** ** Piglet Productions ** ** FileName : PigletLog.cpp ** ** Implements : PigletLog ** ** Description ** ** A FrontDoor style log class ** ** ** Initial Coding : Colin Turner ** ** Date : Unknown ** ** ** Copyright applies on this file, and distribution may be limited. ** Copyright 1996-99 Colin Turner, distribution is limited */ /* ** Revision 1.10 ** ** Modified for compatibility with Watcom and other operating systems. ** (Colin Turner) ** */ #include <PigletLog.h> #if defined(__WATCOMC__) #include <PigletCore.h> #endif /****************************************************************************/ /* */ /* g_Log */ /* */ /****************************************************************************/ /****************************************************************************/ /* S E R V I C E F U N C T I O N S */ /****************************************************************************/ /****************************************************************************/ /* P U B L I C F U N C T I O N S */ /****************************************************************************/ void PigletLog::Printf(char *string, ...) { va_list ap; va_start(ap, string); VPrintf(0, string, ap); va_end(ap); } void PigletLog::Printf(char preline, char *string, ...) { char store=Preline; va_list ap; Preline=preline; va_start(ap, string); VPrintf(0, string, ap); va_end(ap); Preline=store; } void PigletLog::Debugf(int level, char *string, ...) { va_list ap; va_start(ap, string); VPrintf(level, string, ap); va_end(ap); } void PigletLog::Debugf(int level, char preline, char *string, ...) { char store=Preline; va_list ap; Preline=preline; va_start(ap, string); VPrintf(level, string, ap); va_end(ap); Preline=store; } void PigletLog::VPrintf(int level, char *string, va_list ap) { // This function calls both EchoPrintf and fprintf as required. register int loop,loop2; char buffer[10]; int logs=0, logf=0; // Storage space char sc; signed int sd; unsigned int su; char *ss; unsigned long int sul; signed long int sdl; logs=(log!=NULL && level<=DebugLevel); logf=((Flags & PigletLog_EchoPrint) && level<=EchoLevel); if(!logs && !logf) return; // Run through the basic string for(loop=0; string[loop]!=0; loop++){ switch (string[loop]){ case '%': // Dealing with a format command, look for a variable // Check for %% if(string[loop+1]=='%'){ if(logs) fprintf(log,"%%"); if(logf) EchoPrintf("%%"); } else{ // Scan to the next alphabetic or zero char for(loop2=loop+1; !IsSpecial(string[loop2]) && string[loop2]; loop2++); strncpy(buffer, string+loop, loop2-loop+2); switch (string[loop2]){ case 'l' : buffer[loop2-loop+2]=0; // great :-(, long variable loop2++; switch (string[loop2]){ case 'd' : case 'i' : // long signed decimal sdl = va_arg(ap, signed long); if(logs) fprintf(log, buffer, sdl); if(logf) EchoPrintf(buffer, sdl); break; case 'u' : // long unsigned integer sul = va_arg(ap, unsigned long); if(logs) fprintf(log, buffer, sul); if(logf) EchoPrintf(buffer, sul); break; case 'X' : case 'x' : // long hexadesimal sul = va_arg(ap, unsigned long); if(logs) fprintf(log, buffer, sul); if(logf) EchoPrintf(buffer, sul); break; } case '\0' : // Unexpected end of string! break; case 'c' : // character buffer[loop2-loop+1]=0; sc = va_arg(ap, char); if(logs) fprintf(log,buffer, sc); if(logf) EchoPrintf(buffer, sc); break; case 'd' : case 'i' : // signed decimal integer buffer[loop2-loop+1]=0; sd = va_arg(ap, signed); if(logs) fprintf(log,buffer, sd); if(logf) EchoPrintf(buffer, sd); break; case 's' : // string buffer[loop2-loop+1]=0; ss = va_arg(ap, char *); if(logs) fprintf(log,buffer, ss); if(logf) EchoPrintf(buffer, ss); break; case 'u' : // unsigned integer buffer[loop2-loop+1]=0; su = va_arg(ap, unsigned); if(logs) fprintf(log,buffer, su); if(logf) EchoPrintf(buffer, su); break; case 't' : // time in log format StartLine(level); break; //#ifdef g_RunDebug case 'm' : // coreleft, try to preserve formatting info as much as possible. buffer[loop2-loop+1]=0; strcpy(buffer+(strlen(buffer)-1), "lu"); #ifdef __WATCOMC__ if(logs) fprintf(log, buffer, _memavl()); if(logf) EchoPrintf(buffer, _memavl()); #else if(logs) fprintf(log, buffer, coreleft()); if(logf) EchoPrintf(buffer, coreleft()); #endif break; case 'z' : // stackleft, debug only, try to preserve formatting. buffer[loop2-loop+1]=0; strcpy(buffer+(strlen(buffer)-1), "lu"); if(logs) fprintf(log, buffer, stackavail()); if(logf) EchoPrintf(buffer, stackavail()); break; case 'X' : case 'x' : // Hexadecimal digits buffer[loop2-loop+1]=0; su = va_arg(ap, unsigned); if(logs) fprintf(log, buffer, su); if(logf) EchoPrintf(buffer, su); break; } } loop=loop2; break; case '\\': // Dealing with a special character // send next two chars strncpy(buffer, string+loop, 2); buffer[2]=0; if(logs) fprintf(log,"%s",buffer); if(logf) EchoPrintf("%s", buffer); break; default : // Bog standard char :-) */ if(logs) fprintf(log,"%c",string[loop]); if(logf) EchoPrintf("%c", string[loop]); break; } } if(Flags & PigletLog_FlushEvery) Flush(); } void PigletLog::Finish() { int EchoOn=(int) (Flags & PigletLog_EchoPrint); if(log){ if(EchoOn) Flags = Flags & ~PigletLog_EchoPrint; StartLine(0); fprintf(log, "%s Normal Termination\n", Name); StartLine(0); fprintf(log, "Execution time %.02f seconds\n", Extime()); fclose(log); if(EchoOn) Flags = Flags | PigletLog_EchoPrint; } } void PigletLog::Abnormal() { int EchoOn=(int) (Flags & PigletLog_EchoPrint); if(log){ if(EchoOn) Flags = Flags & ~PigletLog_EchoPrint; StartLine(0); fprintf(log, "%s Abnormal Termination\n", Name); StartLine(0); fprintf(log, "Execution time %.02f seconds\n", Extime()); fclose(log); if(EchoOn) Flags = Flags | PigletLog_EchoPrint; } } void PigletLog::Flush() { if(log) fflush(log); } /****************************************************************************/ /* P R I V A T E F U N C T I O N S */ /****************************************************************************/ void PigletLog::EchoPrintf(char *string, ...) { va_list ap; va_start(ap, string); if(Flags & PigletLog_EchoPrint) vprintf(string, ap); va_end(ap); } float PigletLog::Extime(void) { clock_t temp; float running; temp = clock(); running = temp/CLK_TCK; return((float) running); } // No check is made on validity of output file. This function places the // time (correctly formated for country codes) with the preline // character, to file. void PigletLog::StartLine(int level) { struct tm *local; time_t t; t = time(NULL); local = localtime(&t); if(log && level<=DebugLevel) fprintf(log,"%c %2u%s%02u%s%02u ", Preline, local->tm_hour, CoTSep, local->tm_min, CoTSep, local->tm_sec); if((Flags & PigletLog_EchoPrint) && (Flags & PigletLog_EchoTime) && level<=EchoLevel) EchoPrintf("%c %2u%s%02u%s%02u ", Preline, local->tm_hour, CoTSep, local->tm_min, CoTSep, local->tm_sec); } /****************************************************************************/ /* I M P L E M E N T A T I O N F U N C T I O N S */ /****************************************************************************/ /****************************************************************************/ /* P U B L I C F U N C T I O N S */ /****************************************************************************/ PigletLog::PigletLog() { Constructor("", "", "", 0); } PigletLog::PigletLog(FILE *fp, char *name, char *version, char *extra, long flags) { Constructor(name, version, extra, flags); Attach(fp); } PigletLog::PigletLog(char *filename, char *name, char *version, char *extra, long flags) { Constructor(name, version, extra, flags); SetFile(filename); Open(); } /****************************************************************************/ /* P R I V A T E F U N C T I O N S */ /****************************************************************************/ void PigletLog::Constructor(char *name, char *version, char *extra, long flags) { strcpy(Name, name); strcpy(Version, version); strcpy(Extra, extra); Flags=flags; Preline=0x20; DebugLevel=0; strcpy(CoDSep,"/"); strcpy(CoTSep,":"); GetCountry(); log=NULL; } void PigletLog::GetCountry(void) { // A function to grab country configuration struct COUNTRY space; struct COUNTRY * pointer = &space; #ifdef __WATCOMC__ PigletGetCountry(&space); #else pointer=country(0, pointer); #endif if(pointer!=NULL){ DateFormat=pointer->co_date; strcpy(CoDSep,pointer->co_dtsep); strcpy(CoTSep,pointer->co_tmsep); } } int PigletLog::Open() { log=_fsopen(Filename, "a", SH_DENYWR); if(!log) return(0); Start(); return(1); } void PigletLog::Start(void) { struct tm *local; time_t t; char stamp[20]; if(!log) return; t=time(NULL); local=localtime(&t); strftime(stamp,20," %a %d %b %y",local); fprintf(log, "\n----------%s, %s, Version %s; %s\n", stamp, Name, Version, Extra); } int PigletLog::IsSpecial(char test) { if(test=='c' || test=='d' || test=='i' || test=='s' || test=='f' || test=='u' || test=='t' || test=='x' || test=='X' || test=='l' || test=='m' || test=='z') return(1); return(0); }
[ [ [ 1, 406 ] ] ]
cc5fa67dbcf67b20a85ac5941a5062b1dd210ed6
2c428e38d9b50e8484fc56f62e3c9f3c083b39fa
/COMP 201/Lab4/Part2/account.cc
aba3a122a4f30af8b28b5243825777d4465da97d
[]
no_license
daveharris/uni-work
9b0a75ad13e6cf5bf6dad586945bb00e2b9ab737
669a96db775c809106c02e9e2973761a884b618f
refs/heads/master
2016-09-06T19:51:25.773023
2011-02-03T02:10:02
2011-02-03T02:10:02
1,252,689
1
0
null
null
null
null
UTF-8
C++
false
false
921
cc
#include "account.h" #include <iostream> #include <string> using namespace std; Account::Account(int id, char *n, int init){ idnumber = id; strncpy(name, n, 32); amount = init; transcount = 0; } Account::Account(){ idnumber = 0; name[0] = '\0'; amount = 0; transcount = 0; } void Account::credit(int x){ amount += x; ++ transcount; } void Account::debit(int x){ amount -= x; ++ transcount; } int Account::getid(){ return idnumber; } int Account::getbalance(){ return amount; } void Account::print(){ cout << "-----------------------------------------\n"; cout << "Account ID number : " << idnumber << '\n'; cout << "Account: Name is: " << name << '\n'; cout << "Account: Balance is $" << amount << '\n'; cout << "Account: Number of Transactions was " << transcount << '\n'; cout << "-----------------------------------------\n"; }
[ [ [ 1, 45 ] ] ]
235ccbe77f5dc2f382a70fc603edb2a0e4747d0d
61352a7371397524fe7dcfab838de40d502c3c9a
/client/Sources/View/Windows/MsgWindow.cpp
b8b204181ab5c23bbd6440dbca87bd01e9d1efdd
[]
no_license
ustronieteam/emmanuelle
fec6b6ccfa1a9a6029d8c3bb5ee2b9134fccd004
68d639091a781795d2e8ce95c3806ce6ae9f36f6
refs/heads/master
2021-01-21T13:04:29.965061
2009-01-28T04:07:01
2009-01-28T04:07:01
32,144,524
2
0
null
null
null
null
WINDOWS-1250
C++
false
false
4,151
cpp
#include "MsgWindow.h" MsgWindow::MsgWindow(Controller * controller, const std::string & name) : Window(controller, WIN_MSG) { // Inicjalizacja loggera. _logger = log4cxx::LoggerPtr(log4cxx::Logger::getLogger("MsgWindow")); _logger->setLevel(LOGLEVEL); _contactName = name; _talk = NULL; _showLast = true; std::string wname; wname.append(WIN_MSG); wname.append("("); wname.append(_contactName); wname.append(")"); this->SetName(wname); } void MsgWindow::Render(std::ostream & out) { boost::mutex::scoped_lock sl(_mxRender); out << HEADLINE << SIDE << "^ Rozmowa z ~" << this->_contactName << "\n" << SIDE << '\n'; _mxTalk->lock(); if ( _talk != NULL ) { if ( _talk->size() != 0 ) { int k = 0; for(std::list<MYMESSAGE>::iterator i = _talk->begin(); (i != _talk->end()) && ((k < MSG_MAX_SEE_MSG && _showLast) || !_showLast); ++i, ++k) { out << SIDE << (*i).sender << " [" << (*i).time << "]\n" << SIDE << (*i).content << '\n' << SIDE << '\n'; } } else { out << SIDE << MSG_INF_NO_MSG << '\n'; } } _mxTalk->unlock(); out << SIDE << '\n' << LINE; if ( ! this->GetMsg().empty() ) { out << SIDE << this->GetMsg() << '\n'; this->ClearMsg(); } out << PROMPT; } void MsgWindow::Command(std::string & cmd) { std::string mcmd; MYMESSAGE msg; msg.time = boost::posix_time::second_clock::local_time(); // Wyslanie wiadomosci. if ( !cmd.compare("snd") ) { // Pobranie całe linii wiadomosci. std::cin.getline(this->_singleMsg, MSG_MAX_MSG_LEN-1); // Komunikat o wysylaniu wiadomosci. std::cout << PROMPT << MSG_INF_SND_MSG; LOG4CXX_DEBUG(this->_logger, "Wysylanie wiadomosci... Adresat: " << _contactName.c_str() << " Tresc: " << _singleMsg); // !!! Wywolanie na kontrolerze. bool result = this->GetController()->SendMessageToClient(_singleMsg, _contactName.c_str()); LOG4CXX_DEBUG(this->_logger, "Rezultat wysylania wiadomosci: " << result); if ( result ) { msg.content = std::string(this->_singleMsg); msg.sender = this->GetController()->GetOwnName(); _mxTalk->lock(); _talk->push_front(msg); _mxTalk->unlock(); } // Jesli nie mozna bylo wyslac wiadomosci. else this->SetMsg(MSG_ER_SND_MSG); } // Przeslanie pliku. else if ( !cmd.compare("sfile") ) { // Pobranie nazwy pliku do wyslania. std::cin >> cmd; std::cout << PROMPT << MSG_INF_SND_FIL; LOG4CXX_DEBUG(this->_logger, "Zadanie wyslania pliku: Adresat: " << _contactName.c_str() << " Plik: " << cmd.c_str() ); std::ifstream file; file.open(cmd.c_str(), std::ios::in); // Udalo sie otworzyc plik. if ( file.is_open() ) { // Zamkniecie. file.close(); LOG4CXX_DEBUG(this->_logger, "Plik istnieje. Wysylanie..." ); // Wywolanie metody na kontrolerze... bool result = this->GetController()->SendFile(_contactName.c_str(), cmd.c_str()); LOG4CXX_DEBUG(this->_logger, "Zakonczenie wysylania. Rezultat: " << result ); msg.content = MSG_INF_FILE_SND1; msg.content.append(cmd.c_str()); if ( result ) msg.content.append(MSG_INF_FILE_SND2); else msg.content.append(MSG_ER_FILE_SND2); msg.sender = MSG_INF_FILE_SNDR; _mxTalk->lock(); _talk->push_front(msg); _mxTalk->unlock(); } // Nie udalo sie otworzyc pliku. else { LOG4CXX_DEBUG(this->_logger, "Nie znaleziono pliku: " << cmd.c_str() ); this->SetMsg(MSG_ER_SND_FIL); } } // Wyswietlenie wszystkich. else if ( !cmd.compare("all") ) { this->_showLast = false; this->SetMsg(MSG_INF_SHOW_A); } // Wyswietlenie ostatnich. else if ( !cmd.compare("last") ) { this->_showLast = true; this->SetMsg(MSG_INF_SHOW_L); } // Odswiezenie. else if ( !cmd.compare("r") ) { ; // Pusta operacja. } // Nieznana instrukcja. else this->SetMsg(ER_NO_COMMAND); } void MsgWindow::SetTalk(std::list<MYMESSAGE> * talk) { this->_talk = talk; } void MsgWindow::SetMutexTalk(boost::mutex * mxTalk) { this->_mxTalk = mxTalk; }
[ "w.grzeskowiak@c118a9a8-d993-11dd-9042-6d746b85d38b", "coutoPL@c118a9a8-d993-11dd-9042-6d746b85d38b" ]
[ [ [ 1, 7 ], [ 9, 114 ], [ 118, 120 ], [ 122, 177 ] ], [ [ 8, 8 ], [ 115, 117 ], [ 121, 121 ] ] ]
814105922e466f7c542c944d16ace93ce12ec3a4
823afcea9ac0705f6262ccffdff65d687822fe93
/RayTracing/Src/Triangle.cpp
204b6d83d2dc2eefbd96cc2b9972db4329cd8ec9
[]
no_license
shourav9884/raytracing99999
02b405759edf7eb5021496f87af8fa8157e972be
19c5e3a236dc1356f6b4ec38efcc05827acb9e04
refs/heads/master
2016-09-10T03:30:54.820034
2006-10-15T21:49:19
2006-10-15T21:49:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
147
cpp
#include "Triangle.h" Triangle::Triangle(void) { } void Triangle::checkIntersection( const Ray &aRay, IntersectionResult &aResult ) { }
[ "saulopessoa@34b68867-b01b-0410-ab61-0f167d00cb52" ]
[ [ [ 1, 9 ] ] ]
c5f3bbcb82e649ad5373f4bbca39d206bb7328a6
6f907ebd2c7dfa8887f8cbd068d989b2a59da161
/Simple3D_win32/S3DPoint.h
19cdb81e40aa1bae37a11a421708d37e0049a3e7
[ "MIT" ]
permissive
AVGP/Simple3D
cd53aa0fda912467e9df870474220ee0a680fda1
9832cb9b4e008ca0349585d96e14b41317691fd9
refs/heads/master
2021-01-19T08:46:20.767336
2010-09-27T11:14:15
2010-09-27T11:14:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
506
h
/** * Simple3D * Basic, cross-platform 3D-Engine * (c)2010 by M.Naumann * Licenced under GPL 2! */ #ifndef _S3DPoint_ #define _S3DPoint_ #include "global.h" #include "S3DPrimitive.h" class S3DPoint : public S3DPrimitive { public: double x; double y; double z; S3DPoint(); S3DPoint(double x,double y,double z); void move(double dx,double dy,double dz); void draw(S3DDevice *d,S3DSurface w,S3DContext g); void rotate(double rx,double ry,double rz) {}; double getZ(); }; #endif
[ [ [ 1, 28 ] ] ]
9b353988ded98640f0e185e58592c76e6a37b1f1
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/FLVGServer/Dog.h
c8281bf4653bae462e3455410bf771bd9c1a1e68
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
GB18030
C++
false
false
1,570
h
#ifndef DOG_H #define DOG_H #include "windows.h" #include "Md5.h" #include "Rc6.h" #include "time.h" enum CommandType{dog_attestation=1,dog_read,dog_write}; enum AuthType{rc6=1,md5}; typedef struct _DL_DLL_PARA { DWORD Command; //[in]命令码 LPVOID lpDogParam; //[in]指向DOG_PARA结构的指针 LPVOID lpAuthParam; //[in]指向AUTH_PARA结构的指针 }DL_DLL_PARA, * PDL_DLL_PARA; typedef struct _DOG_PARA { USHORT DogAddr; //[in]首地址 USHORT DogBytes; //[in]操作字节数 BYTE DogData[100];//[in][out]输入输出数据 }DOG_PARA, * PDOG_PARA; typedef struct _AUTH_PARA { DWORD Type; //[in]算法选择,目前只支持rc6 ,只能为1 DWORD Length; //[in]数据长度,对rc6算法,只能为16 PUCHAR pRandom; //[in]输入的16字节随机数指针 PUCHAR pReturnRandom;//[out]输出的加密数据指针 }AUTH_PARA, * PAUTH_PARA; typedef unsigned long ( * RC_DLDOG)(PDL_DLL_PARA pDLLParam); class CDog { public: CDog(); ~CDog(); BOOL Init(); BOOL WriteDog(int start,int len,char* content); BOOL ReadDog(int start,int len,char* result); void SetCommand(UINT nCommand); void SetRc6(BOOL use); BOOL IsRc6(); private: PDL_DLL_PARA m_pDllPara; PDOG_PARA m_pDogPara; PAUTH_PARA m_pAuthPara; RC_DLDOG RC_DLDog; int KeyLen; RC6_KEY RC6Key; //MD5 md5object; UCHAR sign[16]; int RandomLen; HRESULT hresult; unsigned char Random[16]; unsigned char DecryptRandom[16]; unsigned char ReturnRandom[16]; }; #endif
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 60 ] ] ]
79fcd01b53faa2a277dca9fa024212a8e5b43bc8
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Game/Object/GameScene/SkillPoint.cpp
612865439fc336aa95a69c62d66541a81789f7cd
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,214
cpp
/*******************************************************************************/ /** * @file SkillPoint.cpp. * * @brief スキルポイントクラスソース定義. * * @date 2008/12/15. * * @version 1.00. * * @author Ryosuke Ogawa. */ /*******************************************************************************/ #include "SkillPoint.h" #include "Player.h" #include <sstream> /*=========================================================================*/ /** * @brief コンストラクタ. * */ SkillPoint::SkillPoint(IGameDevice &device, ObjectManager &objectManager, Option &option, GameSceneState &gameSceneState, Player& player) : m_device(device), m_objectManager(objectManager), m_option(option), m_gameSceneState(gameSceneState), m_player(player), m_isTerminated(false) { } /*=========================================================================*/ /** * @brief デストラクタ. * */ SkillPoint::~SkillPoint() { } /*=========================================================================*/ /** * @brief 初期化処理. * */ void SkillPoint::Initialize() { switch( m_player.GetPlayerParameter().GetPlayerID()) { case(0): m_x = m_player.GetPuzzleScreen().GetBlockManager().GetField().GetPosition().x + 30.0f; m_y = m_player.GetPuzzleScreen().GetBlockManager().GetField().GetPosition().y + 500.0f; break; case(1): m_x = m_player.GetPuzzleScreen().GetBlockManager().GetField().GetPosition().x + 30.0f; m_y = m_player.GetPuzzleScreen().GetBlockManager().GetField().GetPosition().y + 500.0f; break; } } /*=========================================================================*/ /** * @brief 終了処理. * */ void SkillPoint::Terminate() { m_isTerminated = true; } /*=========================================================================*/ /** * @brief 終了しているかどうか. * * @return 終了フラグ. */ bool SkillPoint::IsTerminated() { return m_isTerminated; } /*=========================================================================*/ /** * @brief オブジェクトの描画処理. * */ void SkillPoint::RenderObject() { /** スキルポイント表示 */ m_player.GetPlayerParameter().GetSkillPoint(); SpriteDesc sd; TextDesc td; std::stringstream ss; sd.textureID = TEXTUREID_SBLOCK1; td.code = FONT_CODE_NORMAL; td.font = "MS ゴシック"; td.size = 15; for( int i = 0; i < 4; i++ ) { sd.rect = Rect(m_x + (i*60) ,m_y ,m_x+BLOCK_SIZE + (i*60) ,m_y+BLOCK_SIZE); m_device.GetGraphicDevice().Render( sd ); td.position = Vector2( m_x + (i * 60) + BLOCK_SIZE + 10.0f, m_y); ss.str(""); ss << (m_player.GetPlayerParameter().GetSkillPoint())[i]; td.string = ss.str(); m_device.GetGraphicDevice().Render( td ); sd.textureID ++; } } /*=========================================================================*/ /** * @brief オブジェクトの更新処理. * * @param[in] frameTimer 更新タイマ. */ void SkillPoint::UpdateObject(float frameTimer) { } /*===== EOF ===================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 125 ] ] ]
308c0e47fb380d8c5a70335303f78abd93698784
a3d70ef949478e1957e3a548d8db0fddb9efc125
/src/common/debug.cpp
f7f6e090e4938d624cd7e9d70b8db00039dae2c8
[]
no_license
SakuraSinojun/ling
fc58afea7c4dfe536cbafa93c0c6e3a7612e5281
46907e5548008d7216543bdd5b9cc058421f4eb8
refs/heads/master
2021-01-23T06:54:30.049039
2011-01-16T12:23:24
2011-01-16T12:23:24
32,323,103
0
0
null
null
null
null
GB18030
C++
false
false
4,169
cpp
#define _CRT_SECURE_NO_WARNINGS #include <windows.h> #include "debug.h" #ifdef __GAME_DEBUG_MESSAGE__ typedef struct memory_link { unsigned int size; int line; char file[MAX_PATH]; char func[100]; void * pointer; struct memory_link * prev; struct memory_link * next; }memory_link; static memory_link * link_head = NULL; static memory_link * link_tail = NULL; static memory_link * _find_link(void * ptr) { memory_link * temp = link_head; while(temp != NULL) { if(temp->pointer == ptr) { return temp; } temp = temp->next; } return NULL; } void __out_debug_(const char * string, ...) { char buffer[1024]; va_list arglist; if (NULL == string) { return; } va_start(arglist, string); vsprintf(buffer, string, arglist); va_end(arglist); (printf)(buffer); } void * malloc_debug( unsigned int num_bytes, const char * file, const int line, const char * function ) { memory_link * temp; void * result; if(num_bytes == 0) { __out_debug_("[%s]函数分配0字节空间!\n", function); return NULL; } result = (malloc)(num_bytes); if(result == NULL) { __out_debug_("内存分配失败!"); return NULL; } temp = (memory_link *)(malloc)(sizeof(memory_link)); temp->size = num_bytes; temp->line = line; strncpy(temp->file, file, MAX_PATH-1); strncpy(temp->func, function, 99); temp->file[MAX_PATH-1] = '\0'; temp->func[99] = '\0'; temp->prev = NULL; temp->next = NULL; temp->pointer = result; if(link_head == NULL) { link_head = temp; } else { link_tail->next = temp; temp->prev = link_tail; } link_tail = temp; __out_debug_("分配内存:文件[%s],行数[%d],大小[%u]\n", file, line, num_bytes); return result; } void free_debug(void * ptr) { memory_link * prev; memory_link * next; memory_link * temp; if(ptr == NULL) { __out_debug_("释放空指针!\n"); return; } temp = _find_link(ptr); if(temp == NULL) { __out_debug_("释放非法指针。\n"); return; } __out_debug_("释放内存:文件[%s],行数[%d],大小[%u]\n", temp->file, temp->line, temp->size); prev = temp->prev; next = temp->next; if(prev != NULL) { prev->next = next; }else{ link_head = next; } if(next != NULL) { next->prev = prev; }else{ link_tail = prev; } (free)(ptr); } void * operator new(size_t size, const char * file, const int line, const char * function) { return malloc_debug(size, file, line, function); } void operator delete(void * p) { free_debug(p); } void operator delete[] (void * p) { free_debug(p); } void operator delete(void * p,const char * file,const int line, const char * function) throw() { __out_debug_("内存分配失败!\n"); free_debug(p); } #endif
[ "SakuraSinojun@f09d58f5-735d-f1c9-472e-e8791f25bd30" ]
[ [ [ 1, 241 ] ] ]
4daa9074223f838807c958b95d9216cffc70d029
0033659a033b4afac9b93c0ac80b8918a5ff9779
/game/shared/so2/weapon_sg552.cpp
2803539e5a41404f180aa6e1d3531e01fea6b0d2
[]
no_license
jonnyboy0719/situation-outbreak-two
d03151dc7a12a97094fffadacf4a8f7ee6ec7729
50037e27e738ff78115faea84e235f865c61a68f
refs/heads/master
2021-01-10T09:59:39.214171
2011-01-11T01:15:33
2011-01-11T01:15:33
53,858,955
1
0
null
null
null
null
UTF-8
C++
false
false
2,342
cpp
#include "cbase.h" #include "weapon_sobase_machinegun.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #ifdef CLIENT_DLL #define CWeaponSG552 C_WeaponSG552 #endif class CWeaponSG552 : public CSOMachineGun { public: DECLARE_CLASS( CWeaponSG552, CSOMachineGun ); CWeaponSG552(); DECLARE_NETWORKCLASS(); DECLARE_PREDICTABLE(); void AddViewKick( void ); int GetMinBurst( void ) { return 1; } int GetMaxBurst( void ) { return 1; } float GetFireRate( void ) { return 0.086f; } // about 11.666 (repeating, of course) Hz Activity GetPrimaryAttackActivity( void ); virtual const Vector& GetBulletSpread( void ) { static Vector cone; cone = VECTOR_CONE_3DEGREES; return cone; } const WeaponProficiencyInfo_t *GetProficiencyValues(); // Add support for CS:S player animations const char *GetWeaponSuffix( void ) { return "SG552"; } // Weapon scope system virtual bool HasScope( void ) { return true; } // this weapon has a scope private: CWeaponSG552( const CWeaponSG552 & ); }; IMPLEMENT_NETWORKCLASS_ALIASED( WeaponSG552, DT_WeaponSG552 ) BEGIN_NETWORK_TABLE( CWeaponSG552, DT_WeaponSG552 ) END_NETWORK_TABLE() BEGIN_PREDICTION_DATA( CWeaponSG552 ) END_PREDICTION_DATA() LINK_ENTITY_TO_CLASS( weapon_sg552, CWeaponSG552 ); PRECACHE_WEAPON_REGISTER( weapon_sg552 ); CWeaponSG552::CWeaponSG552() { m_fMinRange1 = 0; // in inches; no minimum range m_fMaxRange1 = 15748; // in inches; about 400 meters } Activity CWeaponSG552::GetPrimaryAttackActivity( void ) { return ACT_VM_PRIMARYATTACK; } void CWeaponSG552::AddViewKick( void ) { CBasePlayer *pPlayer = ToBasePlayer( GetOwner() ); if ( !pPlayer ) return; #define EASY_DAMPEN 0.5f #define MAX_VERTICAL_KICK 5.0f // in degrees #define SLIDE_LIMIT 2.0f // in seconds DoMachineGunKick( pPlayer, EASY_DAMPEN, MAX_VERTICAL_KICK, m_fFireDuration, SLIDE_LIMIT ); } const WeaponProficiencyInfo_t *CWeaponSG552::GetProficiencyValues() { static WeaponProficiencyInfo_t proficiencyTable[] = { { 7.0, 0.75 }, { 5.00, 0.75 }, { 10.0/3.0, 0.75 }, { 5.0/3.0, 0.75 }, { 1.00, 1.0 }, }; COMPILE_TIME_ASSERT( ARRAYSIZE(proficiencyTable) == WEAPON_PROFICIENCY_PERFECT + 1); return proficiencyTable; }
[ "MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61" ]
[ [ [ 1, 97 ] ] ]
a2c5f50bc35081bc7a1d1fd6507663cb017e690d
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/rungun.h
5570d8f455507ccc034d0a5cb04f7bea53f2ddfe
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,302
h
/************************************************************************* Run and Gun / Slam Dunk *************************************************************************/ class rungun_state : public driver_device { public: rungun_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT16 * m_936_videoram; // UINT16 * m_paletteram; // currently this uses generic palette handling /* video-related */ tilemap_t *m_ttl_tilemap; tilemap_t *m_936_tilemap; UINT16 m_ttl_vram[0x1000]; int m_ttl_gfx_index; int m_sprite_colorbase; /* misc */ UINT16 m_sysreg[0x20]; int m_z80_control; int m_sound_status; /* devices */ device_t *m_maincpu; device_t *m_audiocpu; device_t *m_k054539_1; device_t *m_k054539_2; device_t *m_k053936; device_t *m_k055673; device_t *m_k053252; }; /*----------- defined in video/rungun.c -----------*/ extern void rng_sprite_callback(running_machine &machine, int *code, int *color, int *priority_mask); READ16_HANDLER( rng_ttl_ram_r ); WRITE16_HANDLER( rng_ttl_ram_w ); WRITE16_HANDLER( rng_936_videoram_w ); VIDEO_START( rng ); SCREEN_UPDATE( rng );
[ "Mike@localhost" ]
[ [ [ 1, 51 ] ] ]
71f1ce7c7814c83b18ce5ba1479796f1cc287d04
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SAMPLES/DSHOWFILTERS/mpeg4ip_mp4v2/src/atom_encv.cpp
2c31fa86d813387b725b35a8bdf9951b088c9015
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
2,478
cpp
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is MPEG4IP. * * The Initial Developer of the Original Code is Cisco Systems Inc. * Portions created by Cisco Systems Inc. are * Copyright (C) Cisco Systems Inc. 2001. All Rights Reserved. * * Contributor(s): * Dave Mackie [email protected] * Alix Marchandise-Franquet [email protected] */ #include "mp4common.h" MP4EncvAtom::MP4EncvAtom() : MP4Atom("encv") { AddReserved("reserved1", 6); /* 0 */ AddProperty( /* 1 */ new MP4Integer16Property("dataReferenceIndex")); AddReserved("reserved2", 16); /* 2 */ AddProperty( /* 3 */ new MP4Integer16Property("width")); AddProperty( /* 4 */ new MP4Integer16Property("height")); AddReserved("reserved3", 14); /* 5 */ MP4StringProperty* pProp = new MP4StringProperty("compressorName"); pProp->SetFixedLength(32); pProp->SetValue(""); AddProperty(pProp); /* 6 */ AddReserved("reserved4", 4); /* 7 */ ExpectChildAtom("esds", Required, OnlyOne); ExpectChildAtom("sinf", Required, OnlyOne); } void MP4EncvAtom::Generate() { MP4Atom::Generate(); ((MP4Integer16Property*)m_pProperties[1])->SetValue(1); // property reserved3 has non-zero fixed values static u_int8_t reserved3[14] = { 0x00, 0x48, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }; m_pProperties[5]->SetReadOnly(false); ((MP4BytesProperty*)m_pProperties[5])-> SetValue(reserved3, sizeof(reserved3)); m_pProperties[5]->SetReadOnly(true); // property reserved4 has non-zero fixed values static u_int8_t reserved4[4] = { 0x00, 0x18, 0xFF, 0xFF, }; m_pProperties[7]->SetReadOnly(false); ((MP4BytesProperty*)m_pProperties[7])-> SetValue(reserved4, sizeof(reserved4)); m_pProperties[7]->SetReadOnly(true); }
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 80 ] ] ]
ee2bb93f83b1f397950a6d8b2aebf4e1f6c8ec8b
77d70985fc66e39a7f5c518bdb0a5ebe0edf13dd
/labelimage.h
57b19bfd5639057031c8428a5a54a0f68d205ef0
[]
no_license
lefebvreariane/projet-image-imag
9b51c09563c8388147c75e1c4196e40f4f91af85
673618ffb9b074e826a322029ec78c6f51a5cdc3
refs/heads/master
2020-06-04T23:52:48.322289
2011-01-28T10:01:13
2011-01-28T10:01:13
33,365,133
0
0
null
null
null
null
UTF-8
C++
false
false
395
h
#ifndef LABELIMAGE_H #define LABELIMAGE_H #include <QtGui> #include <QWidget> #include <QLabel> class LabelImage : public QLabel { Q_OBJECT public: LabelImage(); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); int X0,Y0,X1,Y1; signals: void clic(); public slots: private: }; #endif // LABELIMAGE_H
[ "sauretq@2187a008-b734-0937-d5d4-3b54df4e424a" ]
[ [ [ 1, 27 ] ] ]
b0a27b6f1902cea0a2cd803eb525f50349680a13
e98d99816ad42028e5988ade802ffdf9846da166
/Mediotic/mediSurfaceCreationStrategy.h
3a63752c410f3302c6e5bc0c1bd58b029828b83e
[]
no_license
OpenEngineDK/extensions-MediPhysics
5e9b3a0d178db8e9a42ce7724ee35fdfee70ec64
94fdd25f90608ad3db6b3c6a30db1c1e4c490987
refs/heads/master
2016-09-14T04:26:29.607457
2008-10-14T12:14:53
2008-10-14T12:14:53
58,073,189
0
0
null
null
null
null
UTF-8
C++
false
false
280
h
#pragma once #include "mediParticle.h" #include "mediSurface.h" #include <vector> class mediSurfaceCreationStrategy { public: virtual ~mediSurfaceCreationStrategy() {} virtual void process(std::vector<mediParticle> & particles, mediSurface & surface) = 0; };
[ [ [ 1, 13 ] ] ]
8700ec08cecc113bf25093be8371ac86391f7e27
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Standard Gaming Platform/vsurface.h
b8c9112517d2d7a5aad121d7785acaa3453be013
[]
no_license
infernuslord/ja2
d5ac783931044e9b9311fc61629eb671f376d064
91f88d470e48e60ebfdb584c23cc9814f620ccee
refs/heads/master
2021-01-02T23:07:58.941216
2011-10-18T09:22:53
2011-10-18T09:22:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,206
h
#ifndef __VSURFACE_H #define __VSURFACE_H #include "types.h" #include "container.h" #include "himage.h" #include "vobject.h" /////////////////////////////////////////////////////////////////////////////////////////////////// // // Video Surface SGP Module // /////////////////////////////////////////////////////////////////////////////////////////////////// // // Defines for special video object handles given to blit function // #define PRIMARY_SURFACE 0xFFFFFFF0 #define BACKBUFFER 0xFFFFFFF1 #define FRAME_BUFFER 0xFFFFFFF2 #define MOUSE_BUFFER 0xFFFFFFF3 // // Defines for blitting // #define VS_BLT_COLORFILL 0x000000020 #define VS_BLT_USECOLORKEY 0x000000002 #define VS_BLT_USEDESTCOLORKEY 0x000000200 #define VS_BLT_FAST 0x000000004 #define VS_BLT_CLIPPED 0x000000008 #define VS_BLT_SRCREGION 0x000000010 #define VS_BLT_DESTREGION 0x000000080 #define VS_BLT_SRCSUBRECT 0x000000040 #define VS_BLT_COLORFILLRECT 0x000000100 #define VS_BLT_MIRROR_Y 0x000001000 // // Effects structure for specialized blitting // typedef struct { COLORVAL ColorFill; // Used for fill effect SGPRect SrcRect; // Given SRC subrect instead of srcregion SGPRect FillRect; // Given SRC subrect instead of srcregion UINT16 DestRegion; // Given a DEST region for dest positions within the VO } blt_vs_fx; // // Video Surface Flags // Used to describe the memory usage of a video Surface // #define VSURFACE_DEFAULT_MEM_USAGE 0x00000001 // Default mem usage is same as DD, try video and then try system. Will usually work #define VSURFACE_VIDEO_MEM_USAGE 0x00000002 // Will force surface into video memory and will fail if it can't #define VSURFACE_SYSTEM_MEM_USAGE 0x00000004 // Will force surface into system memory and will fail if it can't #define VSURFACE_RESERVED_SURFACE 0x00000100 // Reserved for special purposes, like a primary surface // // Video Surface creation flags // Used in the VSurface_DESC structure to describe creation flags // #define VSURFACE_CREATE_DEFAULT 0x00000020 // Creates and empty Surface of given width, height and BPP #define VSURFACE_CREATE_FROMFILE 0x00000040 // Creates a video Surface from a file ( using HIMAGE ) #define VSURFACE_CREATE_FROMJPC 0x00010000 // replace file extension : sti -> jpc.7z #define VSURFACE_CREATE_FROMPNG 0x00020000 // replace file extension : sti -> png #define VSURFACE_CREATE_FROMJPC_FALLBACK 0x00100000 // replace file extension : sti -> jpc.7z, fall back to sti when it doesn't exist #define VSURFACE_CREATE_FROMPNG_FALLBACK 0x00200000 // replace file extension : sti -> png, fall back to sti when it doesn't exist // // The following structure is used to define a region of the video Surface // These regions are stored via a HLIST // typedef struct { SGPRect RegionCoords; // Rectangle describing coordinates of region SGPPoint Origin; // Origin used for hot spots, etc UINT8 ubHitMask; // Byte flags for hit detection } VSURFACE_REGION; // // This structure is a video Surface. Contains a HLIST of regions // typedef struct { UINT16 usHeight; // Height of Video Surface UINT16 usWidth; // Width of Video Surface UINT8 ubBitDepth; // BPP ALWAYS 16! PTR pSurfaceData; // A void pointer, but for this implementation, is really a lpDirectDrawSurface; PTR pSurfaceData1; // Direct Draw One Interface PTR pSavedSurfaceData1; // A void pointer, but for this implementation, is really a lpDirectDrawSurface; // pSavedSurfaceData is used to hold all video memory Surfaces so that they my be restored PTR pSavedSurfaceData; // A void pointer, but for this implementation, is really a lpDirectDrawSurface; // pSavedSurfaceData is used to hold all video memory Surfaces so that they my be restored UINT32 fFlags; // Used to describe memory usage, etc PTR pPalette; // A void pointer, but for this implementation a DDPalette UINT16 *p16BPPPalette; // A 16BPP palette used for 8->16 blits COLORVAL TransparentColor; // Defaults to 0,0,0 PTR pClipper; // A void pointer encapsolated as a clipper Surface HLIST RegionList; // A List of regions within the video Surface } SGPVSurface, *HVSURFACE; // // This structure describes the creation parameters for a Video Surface // typedef struct { UINT32 fCreateFlags; // Specifies creation flags like from file or not SGPFILENAME ImageFile; // Filename of image data to use UINT16 usWidth; // Width, ignored if given from file UINT16 usHeight; // Height, ignored if given from file UINT8 ubBitDepth; // BPP, ignored if given from file } VSURFACE_DESC; namespace SurfaceData { typedef unsigned long tID; BYTE* SetApplicationData(BYTE* data); void ReleaseApplicationData(BYTE* data); tID GetSurfaceID(BYTE* data); }; /////////////////////////////////////////////////////////////////////////////////////////////////// // // Video Surface Manager Functions // /////////////////////////////////////////////////////////////////////////////////////////////////// /* #ifdef __cplusplus extern "C" { #endif */ extern INT32 giMemUsedInSurfaces; // Creates a list to contain video Surfaces BOOLEAN InitializeVideoSurfaceManager( ); // Deletes any video Surface placed into list BOOLEAN ShutdownVideoSurfaceManager( ); // Restores all video Surfaces in list BOOLEAN RestoreVideoSurfaces( ); // Creates and adds a video Surface to list #ifdef SGP_VIDEO_DEBUGGING void DumpVSurfaceInfoIntoFile( const STR8 filename, BOOLEAN fAppend ); extern BOOLEAN _AddAndRecordVSurface( VSURFACE_DESC *VSurfaceDesc, UINT32 *uiIndex, UINT32 uiLineNum, const STR8 pSourceFile ); #define AddVideoSurface( a, b ) _AddAndRecordVSurface( a, b, __LINE__, __FILE__ ) #else #define AddVideoSurface( a, b ) AddStandardVideoSurface( a, b ) #endif BOOLEAN AddStandardVideoSurface( VSURFACE_DESC *VSurfaceDesc, UINT32 *uiIndex ); // Returns a HVSurface for the specified index BOOLEAN GetVideoSurface( HVSURFACE *hVSurface, UINT32 uiIndex ); BYTE *LockVideoSurface( UINT32 uiVSurface, UINT32 *uiPitch ); void UnLockVideoSurface( UINT32 uiVSurface ); // Blits a video Surface to another video Surface BOOLEAN BltVideoSurface(UINT32 uiDestVSurface, UINT32 uiSrcVSurface, UINT16 usRegionIndex, INT32 iDestX, INT32 iDestY, UINT32 fBltFlags, blt_vs_fx *pBltFx ); BOOLEAN ColorFillVideoSurfaceArea(UINT32 uiDestVSurface, INT32 iDestX1, INT32 iDestY1, INT32 iDestX2, INT32 iDestY2, UINT16 Color16BPP); BOOLEAN ImageFillVideoSurfaceArea(UINT32 uiDestVSurface, INT32 iDestX1, INT32 iDestY1, INT32 iDestX2, INT32 iDestY2, HVOBJECT BkgrndImg, UINT16 Index, INT16 Ox, INT16 Oy); // This function sets the global video Surfaces for primary and backbuffer BOOLEAN SetPrimaryVideoSurfaces( ); // Sets transparency BOOLEAN SetVideoSurfaceTransparency( UINT32 uiIndex, COLORVAL TransColor ); // Adds a video Surface region BOOLEAN AddVideoSurfaceRegion( UINT32 uiIndex, VSURFACE_REGION *pNewRegion ); // Gets width, hight, bpp information BOOLEAN GetVideoSurfaceDescription( UINT32 uiIndex, UINT16 *usWidth, UINT16 *usHeight, UINT8 *ubBitDepth ); /////////////////////////////////////////////////////////////////////////////////////////////////// // // Video Surface manipulation functions // /////////////////////////////////////////////////////////////////////////////////////////////////// // Darkens a rectangular area on a surface for menus etc. BOOLEAN PixelateVideoSurfaceRect( UINT32 uiDestVSurface, INT32 X1, INT32 Y1, INT32 X2, INT32 Y2); // Created from a VSurface_DESC structure. Can be from a file via HIMAGE or empty. HVSURFACE CreateVideoSurface( VSURFACE_DESC *VSurfaceDesc ); // Gets the RGB palette entry values BOOLEAN GetVSurfacePaletteEntries( HVSURFACE hVSurface, SGPPaletteEntry *pPalette ); BOOLEAN RestoreVideoSurface( HVSURFACE hVSurface ); // Returns a flat pointer for direct manipulation of data BYTE *LockVideoSurfaceBuffer( HVSURFACE hVSurface, UINT32 *pPitch ); // Must be called after Locking buffer call above void UnLockVideoSurfaceBuffer( HVSURFACE hVSurface ); // Set data from HIMAGE. BOOLEAN SetVideoSurfaceDataFromHImage( HVSURFACE hVSurface, HIMAGE hImage, UINT16 usX, UINT16 usY, SGPRect *pSrcRect ); // Sets Transparency color into HVSurface and the underlying DD surface BOOLEAN SetVideoSurfaceTransparencyColor( HVSURFACE hVSurface, COLORVAL TransColor ); // Sets HVSurface palette, creates if nessessary. Also sets 16BPP palette BOOLEAN SetVideoSurfacePalette( HVSURFACE hVSurface, SGPPaletteEntry *pSrcPalette ); // Used if it's in video memory, will re-load backup copy //BOOLEAN RestoreVideoSurface( HVSurface hVSurface ); // Deletes all data, including palettes, regions, DD Surfaces BOOLEAN DeleteVideoSurface( HVSURFACE hVSurface ); BOOLEAN DeleteVideoSurfaceFromIndex( UINT32 uiIndex ); /////////////////////////////////////////////////////////////////////////////////////////////////// // // Region manipulation functions // /////////////////////////////////////////////////////////////////////////////////////////////////// // Regions will allow creation of sections within the Surface to manipulate quickly and cleanly // An example would be a cursor tileset BOOLEAN AddVSurfaceRegion( HVSURFACE hVSurface, VSURFACE_REGION *pNewRegion ); BOOLEAN AddVSurfaceRegionAtIndex( HVSURFACE hVSurface, UINT16 usIndex, VSURFACE_REGION *pNewRegion ); BOOLEAN AddVSurfaceRegions( HVSURFACE hVSurface, VSURFACE_REGION **ppNewRegions, UINT16 uiNumRegions ); BOOLEAN RemoveVSurfaceRegion( HVSURFACE hVSurface, UINT16 usIndex ); BOOLEAN ClearAllVSurfaceRegions( HVSURFACE hVSurface ); BOOLEAN GetVSurfaceRegion( HVSURFACE hVSurface, UINT16 usIndex, VSURFACE_REGION *aRegion ); BOOLEAN GetNumRegions( HVSURFACE hVSurface , UINT32 *puiNumRegions ); BOOLEAN ReplaceVSurfaceRegion( HVSURFACE hVSurface , UINT16 usIndex, VSURFACE_REGION *aRegion ); BOOLEAN DeleteVideoSurfaceFromIndex( UINT32 uiIndex ); /////////////////////////////////////////////////////////////////////////////////////////////////// // // Clipper manipulation functions // /////////////////////////////////////////////////////////////////////////////////////////////////// BOOLEAN SetClipList( HVSURFACE hVSurface, SGPRect *RegionData, UINT16 usNumRegions ); ///////////////////////////////////////////////////////////////////////////////////////////////////// // // Blt Functions // /////////////////////////////////////////////////////////////////////////////////////////////////// // These blitting functions more-or less encapsolate all of the functionality of DirectDraw // Blitting, giving an API layer for portability. BOOLEAN BltVideoSurfaceToVideoSurface( HVSURFACE hDestVSurface, HVSURFACE hSrcVSurface, UINT16 usIndex, INT32 iDestX, INT32 iDestY, INT32 fBltFlags, blt_vs_fx *pBltFx ); HVSURFACE GetPrimaryVideoSurface( ); HVSURFACE GetBackBufferVideoSurface( ); BOOLEAN ShadowVideoSurfaceRect( UINT32 uiDestVSurface, INT32 X1, INT32 Y1, INT32 X2, INT32 Y2); BOOLEAN ShadowVideoSurfaceImage( UINT32 uiDestVSurface, HVOBJECT hImageHandle, INT32 iPosX, INT32 iPosY); // If the Dest Rect and the source rect are not the same size, the source surface will be either //enlraged or shunk. BOOLEAN BltStretchVideoSurface(UINT32 uiDestVSurface, UINT32 uiSrcVSurface, INT32 iDestX, INT32 iDestY, UINT32 fBltFlags, SGPRect *SrcRect, SGPRect *DestRect ); BOOLEAN MakeVSurfaceFromVObject(UINT32 uiVObject, UINT16 usSubIndex, UINT32 *puiVSurface); BOOLEAN ShadowVideoSurfaceRectUsingLowPercentTable( UINT32 uiDestVSurface, INT32 X1, INT32 Y1, INT32 X2, INT32 Y2); /* #ifdef __cplusplus } #endif */ #endif
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 289 ] ] ]
23e04423bedd3e42197d65ea464ddb6db6c5f164
814b49df11675ac3664ac0198048961b5306e1c5
/Code/Engine/Graphics/include/MultipleRenderTarget.h
6e71af86da09088034225c87c7acfea8af73c849
[]
no_license
Atridas/biogame
f6cb24d0c0b208316990e5bb0b52ef3fb8e83042
3b8e95b215da4d51ab856b4701c12e077cbd2587
refs/heads/master
2021-01-13T00:55:50.502395
2011-10-31T12:58:53
2011-10-31T12:58:53
43,897,729
0
0
null
null
null
null
UTF-8
C++
false
false
958
h
#pragma once #ifndef __MULTIPLE_RENDER_TARGET_H__ #define __MULTIPLE_RENDER_TARGET_H__ #include "RenderTarget.h" class CXMLTreeNode; class CTextureRenderTarget; class CRenderManager; class CMultipleRenderTarget : public CRenderTarget { public: CMultipleRenderTarget() {}; virtual ~CMultipleRenderTarget() {Done();}; bool Init(const string& _szName); virtual void Activate(CRenderManager* l_pRM); virtual void Deactivate(CRenderManager* l_pRM); bool AddTextureRenderTarget(CTextureRenderTarget* _pTextureRenderTarget, int _iIndex); virtual int GetWidth (); virtual int GetHeight(); protected: virtual void Release(); struct SIndexedTextureRenderTarget { CTextureRenderTarget* m_pTextureRenderTarget; int m_iIndex; SIndexedTextureRenderTarget() : m_pTextureRenderTarget(0), m_iIndex(0) {}; }; vector<SIndexedTextureRenderTarget> m_vTextureRenderTargets; }; #endif
[ "sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485", "Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485" ]
[ [ [ 1, 20 ], [ 22, 42 ] ], [ [ 21, 21 ] ] ]
1a9884e8203f1ad79691221db5755a3e69a87757
43c8fd003f99a2764bcb39290520c1e9108afc99
/touchscreen/app/StdAfx.cpp
55ffb9e8415724531efb1967b78019fb2d199a41
[]
no_license
undees/esc
0f09ffa05f37a588da4f8a0f284607a9e7334763
eef0ebee8159ab45323e86de6c6b5444c62e1a71
refs/heads/master
2016-08-05T08:27:29.511129
2010-06-08T00:45:46
2010-06-08T00:45:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
// stdafx.cpp : source file that includes just the standard includes // waveform.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 6 ] ] ]
b508f621e82389470f8a99a53a42d952020c1be8
82cceba079939c15aa1fc3086c2a6c87e71f96d5
/ACM5/chemistry.h
32a4e8baa046ee62e69a99e05f715e5fba144604
[]
no_license
ahnt/ACM5
7844df3359d9b3bcae63745c465f13f09045264e
0cce2226d70930df0f3186ed53e9d32edafef36b
refs/heads/master
2016-09-01T23:09:01.446157
2011-11-11T15:27:15
2011-11-11T15:27:15
2,606,523
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
h
#ifndef _T_CHEMISTRY_H_ #include "globals.h" #include <stdint.h> struct t_pcr{ int16_t A,B; int8_t wo_A,wo_B; }; class t_chemistry{ public: int32_t compound[highest_compound+1]; unsigned char compound_content[highest_compound+1][4]; //double n[mx+1][my+1][highest_compound+1]; double xp[highest_compound+1]; double yp[highest_compound+1]; double np[highest_compound+1]; //short q_aff[0x1000000]; t_pcr *q_pcr; t_chemistry(); ~t_chemistry(); void setup(void); int is_valid_compound(int32_t to_test); double affinity(int32_t a, int32_t b); unsigned char contains_site(int32_t A, int32_t B); unsigned char split(int32_t O1,int32_t O2,int32_t O3,int32_t O4,int32_t &O5,int32_t &O6); void show_str_compound(int32_t i); unsigned char delta_e(int32_t O1,int32_t O2,int32_t O3,int32_t O4); unsigned char length(int32_t O); double c(double x, double y,int32_t comp); void show_concentrations(void); unsigned char quick_split(int A, int B, int wo_A, int wo_B, int &AP, int &BP); int inttolinked(int v); }; #define _T_CHEMISTRY_H_ #endif
[ [ [ 1, 38 ] ] ]
2318210ba4109cd81e3bc0893039321fc8c8bd81
4561a0f9a0de6a9b75202e1c05a4bd6ba7adabcf
/ustring.h
51da01ca943525230b402b6b22f566710794ac2c
[ "MIT" ]
permissive
embarkmobile/ustl-symbian
3a2471a0487ae8d834f44a69debdb4e093215ce0
6d108f5683677d1d6b57705ac08cf1a4f5a37204
refs/heads/master
2020-04-23T15:37:30.148583
2010-12-10T15:35:16
2010-12-10T15:35:16
898,964
1
0
null
null
null
null
UTF-8
C++
false
false
15,314
h
// This file is part of the ustl library, an STL implementation. // // Copyright (C) 2005 by Mike Sharov <[email protected]> // Portions copyright (c) Penrillian, Smartphone Software Innovators <http://www.penrillian.com> // // This file is free software, distributed under the MIT License. // // ustring.h // #ifndef USTRING_H_1249CB7A098A9010763AAC6D37B133CF #define USTRING_H_1249CB7A098A9010763AAC6D37B133CF #include "memblock.h" #include "utf8.h" #include <stdarg.h> // for va_list, va_start, and va_end (in string::format) #ifdef __SYMBIAN32__ #include "SymbianStringSupport.h" #endif namespace ustl { /// \class string ustring.h ustl.h /// \ingroup Sequences /// /// \brief STL basic_string&lt;char&gt; equivalent. /// /// An STL container for text string manipulation. /// Differences from C++ standard: /// - string is a class, not a template. Wide characters are assumed to be /// encoded with utf8 at all times except when rendering or editing, /// where you would use a utf8 iterator. /// - format member function - you can, of course use an \ref ostringstream, /// which also have format functions, but most of the time this way /// is more convenient. Because uSTL does not implement locales, /// format is the only way to create localized strings. /// - const char* cast operator. It is much clearer to use this than having /// to type .c_str() every time. /// - length returns the number of _characters_, not bytes. /// This function is O(N), so use wisely. /// class string : public memblock { public: typedef char value_type; typedef value_type* pointer; typedef const value_type* const_pointer; typedef wchar_t wvalue_type; typedef wvalue_type* wpointer; typedef const wvalue_type* const_wpointer; typedef pointer iterator; typedef const_pointer const_iterator; typedef value_type& reference; typedef value_type const_reference; typedef ::ustl::reverse_iterator<iterator> reverse_iterator; typedef ::ustl::reverse_iterator<const_iterator> const_reverse_iterator; typedef utf8in_iterator<const_iterator> utf8_iterator; public: static const uoff_t npos = static_cast<uoff_t>(-1); ///< Value that means the end of string. static const value_type c_Terminator = 0; ///< String terminator static const size_type size_Terminator = sizeof(c_Terminator); ///< Most systems terminate strings with '\\0' static const char empty_string [size_Terminator]; ///< An empty string. public: string (void); string (const string& s); inline string (const string& s, uoff_t o, size_type n); inline explicit string (const cmemlink& l); string (const_pointer s); inline string (const_pointer s, size_type len); inline string (const_pointer s1, const_pointer s2); explicit string (size_type n, value_type c = c_Terminator); inline pointer data (void) { return (string::pointer (memblock::data())); } inline const_pointer c_str (void) const { return (string::const_pointer (memblock::cdata())); } inline size_type max_size (void) const { size_type s (memblock::max_size()); return (s - !!s); } inline size_type capacity (void) const { size_type c (memblock::capacity()); return (c - !!c); } void resize (size_type n); inline void clear (void) { resize (0); } inline const_iterator begin (void) const { return (const_iterator (memblock::begin())); } inline iterator begin (void) { return (iterator (memblock::begin())); } inline const_iterator end (void) const { return (const_iterator (memblock::end())); } inline iterator end (void) { return (iterator (memblock::end())); } inline const_reverse_iterator rbegin (void) const { return (const_reverse_iterator (end())); } inline reverse_iterator rbegin (void) { return (reverse_iterator (end())); } inline const_reverse_iterator rend (void) const { return (const_reverse_iterator (begin())); } inline reverse_iterator rend (void) { return (reverse_iterator (begin())); } inline utf8_iterator utf8_begin (void) const { return (utf8_iterator (begin())); } inline utf8_iterator utf8_end (void) const { return (utf8_iterator (end())); } inline const_reference at (uoff_t pos) const { assert (pos <= size() && begin()); return (begin()[pos]); } inline reference at (uoff_t pos) { assert (pos <= size() && begin()); return (begin()[pos]); } inline const_iterator iat (uoff_t pos) const { return (begin() + min (pos, size())); } inline iterator iat (uoff_t pos) { return (begin() + min (pos, size())); } inline size_type utf_length (void) const { return (distance (utf8_begin(), utf8_end())); } inline size_type length (void) const { return size(); } inline void append (const_iterator i1, const_iterator i2) { append (i1, distance (i1, i2)); } void append (const_pointer s, size_type len); void append (const_pointer s); void append (size_type n, const_reference c); inline void append (size_type n, wvalue_type c) { insert (size(), c, n); } inline void append (const_wpointer s1, const_wpointer s2) { insert (size(), s1, s2); } inline void append (const_wpointer s) { const_wpointer se (s); for (;se&&*se;++se) ; append (s, se); } inline void append (const string& s) { append (s.begin(), s.end()); } inline void append (const string& s, uoff_t o, size_type n) { append (s.iat(o), s.iat(o+n)); } inline void assign (const_iterator i1, const_iterator i2) { assign (i1, distance (i1, i2)); } void assign (const_pointer s, size_type len); void assign (const_pointer s); inline void assign (const_wpointer s1, const_wpointer s2) { clear(); append (s1, s2); } inline void assign (const_wpointer s1) { clear(); append (s1); } inline void assign (const string& s) { assign (s.begin(), s.end()); } inline void assign (const string& s, uoff_t o, size_type n) { assign (s.iat(o), s.iat(o+n)); } size_type copyto (pointer p, size_type n, const_iterator start = NULL) const; inline int compare (const string& s) const { return (compare (begin(), end(), s.begin(), s.end())); } inline int compare (const_pointer s) const { return (compare (begin(), end(), s, s + strlen(s))); } static int compare (const_iterator first1, const_iterator last1, const_iterator first2, const_iterator last2); inline operator const value_type* (void) const; inline operator value_type* (void); inline const string& operator= (const string& s) { assign (s.begin(), s.end()); return (*this); } inline const string& operator= (const_reference c) { assign (&c, 1); return (*this); } inline const string& operator= (const_pointer s) { assign (s); return (*this); } inline const string& operator= (const_wpointer s) { assign (s); return (*this); } inline const string& operator+= (const string& s) { append (s.begin(), s.size()); return (*this); } inline const string& operator+= (const_reference c) { append (1, c); return (*this); } inline const string& operator+= (const_pointer s) { append (s); return (*this); } inline const string& operator+= (wvalue_type c) { append (1, c); return (*this); } inline const string& operator+= (const_wpointer s) { append (s); return (*this); } inline string operator+ (const string& s) const; inline bool operator== (const string& s) const { return (memblock::operator== (s)); } bool operator== (const_pointer s) const; inline bool operator== (const_reference c) const { return (size() == 1 && c == at(0)); } inline bool operator!= (const string& s) const { return (!operator== (s)); } inline bool operator!= (const_pointer s) const { return (!operator== (s)); } inline bool operator!= (const_reference c) const { return (!operator== (c)); } inline bool operator< (const string& s) const { return (0 > compare (s)); } inline bool operator< (const_pointer s) const { return (0 > compare (s)); } inline bool operator< (const_reference c) const { return (0 > compare (begin(), end(), &c, &c + 1)); } inline bool operator> (const_pointer s) const { return (0 < compare (s)); } void insert (const uoff_t ip, wvalue_type c, size_type n = 1); void insert (const uoff_t ip, const_wpointer first, const_wpointer last, const size_type n = 1); iterator insert (iterator start, const_reference c, size_type n = 1); iterator insert (iterator start, const_pointer s, size_type n = 1); iterator insert (iterator start, const_pointer first, const_iterator last, size_type n = 1); inline void insert (uoff_t ip, const_pointer s, size_type nlen) { insert (iat(ip), s, s + nlen); } inline void insert (uoff_t ip, size_type n, value_type c) { insert (iat(ip), c, n); } inline void insert (uoff_t ip, const string& s, uoff_t sp, size_type slen) { insert (iat(ip), s.iat(sp), s.iat(sp + slen)); } iterator erase (iterator start, size_type size = 1); void erase (uoff_t start, size_type size = 1); inline iterator erase (iterator first, const_iterator last) { return (erase (first, size_type(distance(first,last)))); } OVERLOAD_POINTER_AND_SIZE_T_V2(erase, iterator) inline void push_back (const_reference c) { append (1, c); } inline void push_back (wvalue_type c) { append (1, c); } inline void pop_back (void) { resize (size() - 1); } void replace (iterator first, iterator last, const_pointer s); void replace (iterator first, iterator last, const_pointer i1, const_pointer i2, size_type n = 1); inline void replace (iterator first, iterator last, const string& s) { replace (first, last, s.begin(), s.end()); } inline void replace (iterator first, iterator last, const_pointer s, size_type slen) { replace (first, last, s, s + slen); } inline void replace (iterator first, iterator last, size_type n, value_type c) { replace (first, last, &c, &c + 1, n); } inline void replace (uoff_t rp, size_type n, const string& s) { replace (iat(rp), iat(rp + n), s); } inline void replace (uoff_t rp, size_type n, const string& s, uoff_t sp, size_type slen) { replace (iat(rp), iat(rp + n), s.iat(sp), s.iat(sp + slen)); } inline void replace (uoff_t rp, size_type n, const_pointer s, size_type slen) { replace (iat(rp), iat(rp + n), s, s + slen); } inline void replace (uoff_t rp, size_type n, const_pointer s) { replace (iat(rp), iat(rp + n), string(s)); } inline void replace (uoff_t rp, size_type n, size_type count, value_type c) { replace (iat(rp), iat(rp + n), count, c); } inline string substr (uoff_t o, size_type n) const { return (string (*this, o, n)); } inline string substr (uoff_t o) const { return (string (*this, o, length() - o)); } uoff_t find (const_reference c, uoff_t pos = 0) const; uoff_t find (const string& s, uoff_t pos = 0) const; uoff_t rfind (const_reference c, uoff_t pos = npos) const; uoff_t rfind (const string& s, uoff_t pos = npos) const; uoff_t find_first_of (const string& s, uoff_t pos = 0) const; uoff_t find_first_of (char c, uoff_t pos = 0) const; uoff_t find_first_not_of (const string& s, uoff_t pos = 0) const; uoff_t find_last_of (const string& s, uoff_t pos = npos) const; uoff_t find_last_not_of (const string& s, uoff_t pos = npos) const; int vformat (const char* fmt, va_list args); int format (const char* fmt, ...) __attribute__((__format__(__printf__, 2, 3))); void read (istream&); void write (ostream& os) const; size_t stream_size (void) const; static hashvalue_t hash (const char* f1, const char* l1); #ifdef __SYMBIAN32__ string( const TDesC& aDes ); void append( const TDesC& aDes ); inline void assign (const TDesC& aDes ) { clear(); append (aDes); } inline const string& operator= (const TDesC& aDes ) { assign (aDes); return (*this); } SymbianString DesL(); SymbianString8 Des8L(); #endif private: DLL_LOCAL iterator utf8_iat (uoff_t i); protected: inline virtual size_type minimumFreeCapacity (void) const { return (size_Terminator); } }; //---------------------------------------------------------------------- /// Assigns itself the value of string \p s inline string::string (const cmemlink& s) : memblock () { assign (const_iterator (s.begin()), s.size()); } /// Assigns itself a [o,o+n) substring of \p s. inline string::string (const string& s, uoff_t o, size_type n) : memblock() { assign (s, o, n); } /// Copies the value of \p s of length \p len into itself. inline string::string (const_pointer s, size_type len) : memblock () { assign (s, len); } /// Copies into itself the string data between \p s1 and \p s2 inline string::string (const_pointer s1, const_pointer s2) : memblock () { assert (s1 <= s2 && "Negative ranges result in memory allocation errors."); assign (s1, s2); } /// Returns the pointer to the first character. inline string::operator const string::value_type* (void) const { assert ((!end() || *end() == c_Terminator) && "This string is linked to data that is not 0-terminated. This may cause serious security problems. Please assign the data instead of linking."); return (begin()); } /// Returns the pointer to the first character. inline string::operator string::value_type* (void) { assert ((end() && *end() == c_Terminator) && "This string is linked to data that is not 0-terminated. This may cause serious security problems. Please assign the data instead of linking."); return (begin()); } /// Concatenates itself with \p s inline string string::operator+ (const string& s) const { string result (*this); result += s; return (result); } //---------------------------------------------------------------------- // Operators needed to avoid comparing pointer to pointer #define PTR_STRING_CMP(op, impl) \ inline bool op (const char* s1, const string& s2) { return impl; } PTR_STRING_CMP (operator==, (s2 == s1)) PTR_STRING_CMP (operator!=, (s2 != s1)) PTR_STRING_CMP (operator<, (s2 > s1)) PTR_STRING_CMP (operator>, (s2 < s1)) // KLUDGE - Symbian seems to think these are already defined... #ifndef __SYMBIAN32__ PTR_STRING_CMP (operator<=, (s2 >= s1)) PTR_STRING_CMP (operator>=, (s2 <= s1)) #endif #undef PTR_STRING_CMP //---------------------------------------------------------------------- template <typename T> inline hashvalue_t hash_value (const T& v) { return (string::hash (v.begin(), v.end())); } template <> inline hashvalue_t hash_value (const string::const_pointer& v) { return (string::hash (v, v + strlen(v))); } template <> inline hashvalue_t hash_value (const string::pointer& v) { return (string::hash (v, v + strlen(v))); } //---------------------------------------------------------------------- } // namespace ustl // Specialization for stream alignment ALIGNOF (ustl::string, alignof (string::value_type())) #endif
[ [ [ 1, 288 ] ] ]
aa2bc2f8576e918106660897293d509683cdd53e
f8b364974573f652d7916c3a830e1d8773751277
/emulator/win32/win32_memory.cpp
3fc77e6033af85307ba0d051338cdbe786090544
[]
no_license
lemmore22/pspe4all
7a234aece25340c99f49eac280780e08e4f8ef49
77ad0acf0fcb7eda137fdfcb1e93a36428badfd0
refs/heads/master
2021-01-10T08:39:45.222505
2009-08-02T11:58:07
2009-08-02T11:58:07
55,047,469
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,336
cpp
/* * memory.cpp * * Created on: 15 nov. 2008 * Author: hli */ /* * specific.h * * Created on: 2 nov. 2008 * Author: hli */ #include "emulator/memory.h" void *psp::memory = 0; int psp::memory_exception = 0; #include <windows.h> static HANDLE psp_memory_handle; static bool mapped_buffer(unsigned int address, unsigned int times, unsigned int offset, unsigned int size) { void *buffer = ::MapViewOfFileEx ( psp_memory_handle, FILE_MAP_READ|FILE_MAP_WRITE, 0, offset, size, (LPVOID)(reinterpret_cast< unsigned int >(psp::memory) + address) ); if (!buffer) { return false; } for (unsigned int i = 1; i < times; ++i) { address += size; void *p = ::MapViewOfFileEx ( psp_memory_handle, FILE_MAP_READ, 0, offset, size, (LPVOID)(reinterpret_cast< unsigned int >(psp::memory) + address) ); if (!p) { return false; } } return true; } static bool unused_buffer(unsigned int start, unsigned int end) { start = (start + 0xFFFF)&~0xFFFF; void *buffer = ::VirtualAlloc ( (LPVOID)(reinterpret_cast< unsigned int >(psp::memory) + start), end - start, MEM_RESERVE, PAGE_NOACCESS ); if (buffer == 0) { return false; } return true; } void *psp::reserve_memory() { psp_memory_handle = ::CreateFileMapping ( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, SRAM_SIZE + VRAM_SIZE + MRAM_SIZE, 0 ); if (psp_memory_handle == INVALID_HANDLE_VALUE) { return 0; } psp::memory = ::VirtualAlloc ( (void *)0, VMEM_SIZE, MEM_RESERVE, PAGE_NOACCESS ); if (!psp::memory) { return 0; } ::VirtualFree(psp::memory, 0, MEM_RELEASE); // 0×00010000 0×00004000 (16 KiB) Scratchpad // 0×04000000 0×00200000 (2 MiB) Lower video ram // 0×04200000 0×00200000 (2 MiB) Upper video ram (SLIM only) // 0×08000000 0×02000000 (32 MiB) Lower main ram // 0×0A000000 0×02000000 (32 MiB) Upper main ram (SLIM only) if ( true && unused_buffer(0x00000000, 0x00010000) && mapped_buffer(0x00010000, 1, MRAM_SIZE + VRAM_SIZE, SRAM_SIZE) && unused_buffer(0x00014000, 0x04000000) && mapped_buffer(0x04000000, 1, MRAM_SIZE, VRAM_SIZE) && unused_buffer(0x04400000, 0x08000000) && mapped_buffer(0x08000000, 1, 0, MRAM_SIZE) && unused_buffer(0x0C000000, 0x10000000) ) { return psp::memory; } return 0; } void psp::release_memory() { if (psp::memory) { ::UnmapViewOfFile(psp::memory); } if (psp_memory_handle != INVALID_HANDLE_VALUE) { ::CloseHandle(psp_memory_handle); } } int psp::exception_handler(unsigned int dwCode, void *pExceptionPointers) { EXCEPTION_POINTERS *ep = (EXCEPTION_POINTERS *)pExceptionPointers; EXCEPTION_RECORD *pExceptionRecord = ep->ExceptionRecord; psp::memory_exception = 0; if (dwCode != EXCEPTION_ACCESS_VIOLATION) return EXCEPTION_CONTINUE_SEARCH; unsigned int address = (unsigned int)pExceptionRecord->ExceptionInformation[1] - (unsigned int)psp::memory; if (address < 0x00010000) { psp::memory_exception = -1; return EXCEPTION_EXECUTE_HANDLER; } else if (address < 0x00014000) { psp::memory_exception = 3; return EXCEPTION_CONTINUE_EXECUTION; } else if (address < 0x04000000) { psp::memory_exception = -1; return EXCEPTION_EXECUTE_HANDLER; } else if (address < 0x04400000) { psp::memory_exception = 2; return EXCEPTION_CONTINUE_EXECUTION; } else if (address < 0x08010000) { psp::memory_exception = -1; return EXCEPTION_EXECUTE_HANDLER; } else if (address < 0x0C000000) { psp::memory_exception = 1; return EXCEPTION_CONTINUE_EXECUTION; } else { psp::memory_exception = -1; return EXCEPTION_EXECUTE_HANDLER; } return EXCEPTION_CONTINUE_SEARCH; }
[ [ [ 1, 203 ] ] ]
73ccdcfb72fab3fd52bb04d9f16e174e987ed4c3
17dd108341e7b9fdc20d5b9c9e8118f9d5901b1a
/Main.cpp
6876ceadc5c8b4e69d40cf7d76061d12e97f7708
[]
no_license
mattsan/MessagingSample
1ff8087b8d6744d1914c13210dd35f0d7a91c58d
727c02315b113c576e9aac6f675b544ea6e18db6
refs/heads/master
2016-09-06T00:36:35.836723
2009-05-18T11:51:52
2009-05-18T11:51:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
729
cpp
#include "ConcreteMessages.h" #include "Processor.h" #include "Factory.h" #include <iostream> #include <string> int main(int, char*[]) { Processor processor(std::cout); Creators creators; creators.insert(Creators::value_type("Foo", Foo::create)); creators.insert(Creators::value_type("Bar", Bar::create)); creators.insert(Creators::value_type("Baz", Baz::create)); std::string id; while(std::cin >> id) { Creators::const_iterator i = creators.find(id); if(i != creators.end()) { Message* message = i->second(); std::cin >> *message; message->dispatch(processor); delete message; } else { std::cout << "UNKNOWN ID : " << id << "\n"; } } return 0; }
[ [ [ 1, 36 ] ] ]
926f8add42f1bad95c9b3bf022e5b85b95ffa799
48c6de8cb63cf11147049ce07b2bd7e020d0d12b
/gcc/opencollada/include/COLLADAStreamWriter/include/COLLADASWLibraryGeometries.h
797448db734d9cf8cd65b00d3bf06c933313aff8
[]
no_license
ngbinh/libBlenderWindows
73effaa1aab8d9d1745908f5528ded88eca21ce3
23fbaaaad973603509b23f789a903959f6ebb560
refs/heads/master
2020-06-08T00:41:55.437544
2011-03-25T05:13:25
2011-03-25T05:13:25
1,516,625
1
1
null
null
null
null
UTF-8
C++
false
false
3,482
h
/* Copyright (c) 2008-2009 NetAllied Systems GmbH This file is part of COLLADAStreamWriter. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADASTREAMWRITER_LIBRARY_GEOMETRY_H__ #define __COLLADASTREAMWRITER_LIBRARY_GEOMETRY_H__ #include "COLLADASWPrerequisites.h" #include "COLLADASWLibrary.h" #include "COLLADASWInputList.h" namespace COLLADASW { /** Class to simply the creation of @a \<library_geometries\> and @a \<geometry\>'s*/ class LibraryGeometries : public Library { public: static const String GEOMETRY_ID_PRAEFIX ; static const String POSITIONS_SOURCE_ID_SUFFIX; static const String INTANGENT_SOURCE_ID_SUFFIX; static const String OUTTANGENT_SOURCE_ID_SUFFIX; static const String INTERPOLATION_SOURCE_ID_SUFFIX; static const String NORMALS_SOURCE_ID_SUFFIX; static const String TEXCOORDS_SOURCE_ID_SUFFIX; static const String COLORS_SOURCE_ID_SUFFIX; static const String TEXTANGENT_SOURCE_ID_SUFFIX; static const String TEXBINORMAL_SOURCE_ID_SUFFIX; static const String ARRAY_ID_SUFFIX; static const String VERTICES_ID_SUFFIX; static const String TANGENT_ID_SUFFIX; static const String BINORMAL_ID_SUFFIX; private: TagCloser mCurrentGeometryCloser; //!< Used to close the current geometry TagCloser mCurrentMeshOrSplineCloser; //!< Used to close the current mesh TagCloser mCurrentExtraCloser; //!< Used to close the current extra public: /** Constructor @param streamWriter The stream the @a \<library_geometries\> and @a \<geometry\>'s should be written to. */ LibraryGeometries ( StreamWriter* streamWriter ); virtual ~LibraryGeometries() {} protected: /** Writes the opening @a \<geometry\> and @a \<mesh\> tags and, if necessary the opening @a \<library_geometry\> tag. closeMesh() must be use to close the opened tags. @param geoId The id of the geometry @param geoName The Name of the geometry*/ void openMesh ( const String& geoId, const String& geoName = EMPTY_STRING ); /** Writes the opening @a \<geometry\> and @a \<spline\> tags and, if necessary the opening @a \<library_geometry\> tag. closeMesh() must be use to close the opened tags. @param closed Indicates if the spline si closed or open @param geoName The Name of the geometry*/ void openSpline ( bool closed, const String & geoId, const String & geoName ); /** Closes the tag opened by openMesh()*/ void closeMesh(); /** Closes the tag opened by openSpline()*/ void closeSpline(); /** Writes the opening @a \<mesh\> tag and, if necessary the opening @a \<library_geometry\> tag. closeGeometry() must be use to close the opened tags. @param id The id of the geometry. @param name The name of the geometry.*/ void openGeometry ( const String& id, const String& name = EMPTY_STRING ); /** Closes the tag open by openGeometry()*/ void closeGeometry(); /** Returns the suffix string of the given type semantic. */ static String getSuffixBySemantic ( Semantics type ); }; } //namespace COLLADASW #endif //__COLLADASTREAMWRITER_LIBRARY_GEOMETRY_H__
[ [ [ 1, 92 ] ] ]
5cc6b25677fe4cc13c0b5f2b87a38e23d44339aa
85d62b70a294dd0ef0ad4819afcc0103d50bed2c
/src/moaicore/MOAISim.cpp
8695773beb415a744fc5e1651b2e8bb55495b939
[]
no_license
doches/moai-beta
786e219cd47cb60214b2270868ca08cabc2f34e4
ef0e495e963cf14615fe3dcb384ec0e5dec89b5b
refs/heads/master
2021-01-15T22:52:20.503799
2011-11-24T02:51:16
2011-11-24T02:51:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,099
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAIActionMgr.h> #include <moaicore/MOAIDebugLines.h> #include <moaicore/MOAIGfxDevice.h> #include <moaicore/MOAIInputMgr.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAINodeMgr.h> #include <moaicore/MOAIProp2D.h> #include <moaicore/MOAISim.h> #include <moaicore/MOAITexture.h> #include <moaicore/MOAIUrlMgr.h> #include <aku/AKU.h> #if defined(_WIN32) #include <Psapi.h> #elif defined(__APPLE__) //&& defined(TARGET_IPHONE_SIMULATOR) // Not sure if using mach API is disallowed in the app store. :/ #include <mach/mach.h> #endif //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name clearLoopFlags @text Uses the mask provided to clear the loop flags. @opt number mask Default value is 0xffffffff. @out nil */ int MOAISim::_clearLoopFlags ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLoopFlags &= ~state.GetValue < u32 >( 1, 0xffffffff ); return 0; } //----------------------------------------------------------------// /** @name clearRenderStack @text Clears the render stack. @out nil */ int MOAISim::_clearRenderStack ( lua_State* L ) { MOAILuaState state ( L ); MOAISim& device = MOAISim::Get (); device.Clear (); return 0; } //----------------------------------------------------------------// /** @name enterFullscreenMode @text Enters fullscreen mode on the device if possible. @out nil */ int MOAISim::_enterFullscreenMode ( lua_State* L ) { MOAILuaState state ( L ); AKUEnterFullscreenModeFunc enterFullscreenMode = AKUGetFunc_EnterFullscreenMode (); if ( enterFullscreenMode ) { enterFullscreenMode (); } return 0; } //----------------------------------------------------------------// /** @name exitFullscreenMode @text Exits fullscreen mode on the device if possible. @out nil */ int MOAISim::_exitFullscreenMode ( lua_State* L ) { MOAILuaState state ( L ); AKUEnterFullscreenModeFunc exitFullscreenMode = AKUGetFunc_ExitFullscreenMode (); if ( exitFullscreenMode ) { exitFullscreenMode (); } return 0; } //----------------------------------------------------------------// /** @name forceGarbageCollection @text Runs the garbage collector repeatedly until no more MOAIObjects can be collected. @out nil */ int MOAISim::_forceGarbageCollection ( lua_State* L ) { UNUSED ( L ); MOAINodeMgr::Get ().Update (); MOAILuaRuntime::Get ().ForceGarbageCollection (); return 0; } //----------------------------------------------------------------// /** @name framesToTime @text Converts the number of frames to time passed in seconds. @in number frames The number of frames. @out number time The equivilant number of seconds for the specified number of frames. */ int MOAISim::_framesToTime ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float frames = state.GetValue < float >( 1, 0.0f ); MOAISim& device = MOAISim::Get (); lua_pushnumber ( state, frames * device.mStep ); return 1; } //----------------------------------------------------------------// /** @name getDeviceSize @text Gets the dimensions of the device screen as two return values (width, height). @out number width The width of the device screen. @out number height The height of the device screen. */ int MOAISim::_getDeviceSize ( lua_State* L ) { MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get (); lua_pushnumber ( L, gfxDevice.GetWidth ()); lua_pushnumber ( L, gfxDevice.GetHeight ()); return 2; } //----------------------------------------------------------------// /** @name getDeviceTime @text Gets the raw device clock. This is a replacement for Lua's os.time (). @out number time The device clock time in seconds. */ int MOAISim::_getDeviceTime ( lua_State* L ) { lua_pushnumber ( L, USDeviceTime::GetTimeInSeconds ()); return 1; } //----------------------------------------------------------------// /** @name getElapsedFrames @text Gets the number of frames elapsed since the application was started. @out number frames The number of elapsed frames. */ int MOAISim::_getElapsedFrames ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushnumber ( L, device.mSimTime / device.mStep ); return 1; } //----------------------------------------------------------------// /** @name getElapsedTime @text Gets the number of seconds elapsed since the application was started. @out number time The number of elapsed seconds. */ int MOAISim::_getElapsedTime ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mSimTime ); return 1; } //----------------------------------------------------------------// /** @name getLoopFlags @text Returns the current loop flags. @out number mask */ int MOAISim::_getLoopFlags ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().mLoopFlags ); return 1; } //----------------------------------------------------------------// /** @name getLuaObjectCount @text Gets the total number of objects in memory that inherit MOAILuaObject. Count includes objects that are not bound to the Lua runtime. @out number count */ int MOAISim::_getLuaObjectCount ( lua_State* L ) { lua_pushnumber ( L, MOAILuaRuntime::Get ().GetObjectCount ()); return 1; } //----------------------------------------------------------------// /** @name getMemoryUsage @text Get the current amount of memory used by MOAI and its subsystems. This will attempt to return reasonable estimates where exact values cannot be obtained. Some fields represent informational fields (i.e. are not double counted in the total, but present to assist debugging) and may be only available on certain platforms (e.g. Windows, etc). These fields begin with a '_' character. @out table usage The breakdown of each subsystem's memory usage, in bytes. There is also a "total" field that contains the summed value. */ int MOAISim::_getMemoryUsage ( lua_State* L ) { float divisor = 1.0f; if( lua_type(L, 1) == LUA_TSTRING ) { cc8* str = lua_tostring(L, 1); if( str[0] == 'k' || str[0] == 'K' ) divisor = 1024.0f; else if( str[0] == 'm' || str[0] == 'M' ) divisor = 1024.0f * 1024.0f; else if( str[0] == 'b' || str[0] == 'B' ) divisor = 1.0f; } size_t total = 0; lua_newtable(L); size_t count; count = MOAILuaRuntime::Get().GetMemoryUsage (); lua_pushnumber(L, count / divisor); lua_setfield(L, -2, "lua"); total += count; // This is informational only (i.e. don't double count with the previous field). // It doesn't actually seem to represent the real usage of lua, but maybe // someone is interested. lua_pushnumber ( L, lua_gc ( L, LUA_GCCOUNTB, 0 ) / divisor ); lua_setfield ( L, -2, "_luagc_count" ); count = MOAIGfxDevice::Get ().GetTextureMemoryUsage (); lua_pushnumber ( L, count / divisor ); lua_setfield ( L, -2, "texture" ); total += count; #if defined(_WIN32) PROCESS_MEMORY_COUNTERS pmc; // Print the process identifier. if ( GetProcessMemoryInfo( GetCurrentProcess(), &pmc, sizeof(pmc)) ) { lua_pushnumber(L, pmc.PagefileUsage / divisor); lua_setfield(L, -2, "_sys_vs"); lua_pushnumber(L, pmc.WorkingSetSize / divisor); lua_setfield(L, -2, "_sys_rss"); } #elif defined(__APPLE__) //&& defined(TARGET_IPHONE_SIMULATOR) // Tricky undocumented mach polling of memory struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; kern_return_t kr = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&t_info), &t_info_count); // Most likely cause for failure: |task| is a zombie. if( kr == KERN_SUCCESS ) { lua_pushnumber(L, t_info.virtual_size / divisor); lua_setfield(L, -2, "_sys_vs"); lua_pushnumber(L, t_info.resident_size / divisor); lua_setfield(L, -2, "_sys_rss"); } #endif lua_pushnumber(L, total / divisor); lua_setfield(L, -2, "total"); return 1; } //----------------------------------------------------------------// /** @name getPerformance @text Returns an estimated frames per second based on measurements taken at every render. @out number fps Estimated frames per second. */ int MOAISim::_getPerformance ( lua_State* L ) { MOAISim& device = MOAISim::Get (); lua_pushnumber ( L, device.mFrameRate ); return 1; } //----------------------------------------------------------------// /** @name getStep @text Gets the amount of time (in seconds) that it takes for one frame to pass. @out number size The size of the frame; the time it takes for one frame to pass. */ int MOAISim::_getStep ( lua_State* L ) { lua_pushnumber ( L, MOAISim::Get ().GetStep ()); return 1; } //----------------------------------------------------------------// /** @name openWindow @text Opens a new window for the application to render on. This must be called before any rendering can be done, and it must only be called once. @in string title The title of the window. @in number width The width of the window in pixels. @in number height The height of the window in pixels. @out nil */ int MOAISim::_openWindow ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "SNN" )) return 0; cc8* title = lua_tostring ( state, 1 ); u32 width = state.GetValue < u32 >( 2, 320 ); u32 height = state.GetValue < u32 >( 3, 480 ); MOAIGfxDevice::Get ().SetSize ( width, height ); AKUOpenWindowFunc openWindow = AKUGetFunc_OpenWindow (); if ( openWindow ) { openWindow ( title, width, height ); } return 0; } //----------------------------------------------------------------// /** @name pauseTimer @text Pauses or unpauses the device timer, preventing any visual updates (rendering) while paused. @in boolean pause Whether the device timer should be paused. @out nil */ int MOAISim::_pauseTimer ( lua_State* L ) { MOAILuaState state ( L ); bool pause = state.GetValue < bool >( 1, true ); if ( pause ) { MOAISim::Get ().PauseMOAI (); } else { MOAISim::Get ().ResumeMOAI (); } return 0; } //----------------------------------------------------------------// /** @name popRenderPass @text Pops the rendering prim off the stack. @out nil */ int MOAISim::_popRenderPass ( lua_State* L ) { UNUSED ( L ); MOAISim& device = MOAISim::Get (); device.PopRenderPass (); return 0; } //----------------------------------------------------------------// /** @name pushRenderPass @text Pushes the specified prim onto the render stack. @in MOAIProp2D prop The viewport of the render prim. @out nil */ int MOAISim::_pushRenderPass ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "U" )) return 0; MOAIProp2D* prop = state.GetLuaObject < MOAIProp2D >( 1 ); if ( !prop ) return 0; MOAISim& device = MOAISim::Get (); device.PushRenderPass ( prop ); return 0; } //----------------------------------------------------------------// /** @name reportHistogram @text Generates a histogram of active MOAIObjects. @out nil */ int MOAISim::_reportHistogram ( lua_State* L ) { MOAILuaState state ( L ); MOAILuaRuntime::Get ().ReportHistogram ( MOAILogMgr::Get ().GetFile ()); return 0; } //----------------------------------------------------------------// /** @name reportLeaks @text Analyze the currently allocated MOAI objects and create a textual report of where they were declared, and what Lua references (if any) can be found. NOTE: This is incredibly slow, so only use to debug leaking memory issues. This will also trigger a full garbage collection before performing the required report. (Equivalent of collectgarbage("collect").) @in bool clearAfter If true, it will reset the allocation tables (without freeing the underlying objects). This allows this method to be called after a known operation and get only those allocations created since the last call to this function. @out nil */ int MOAISim::_reportLeaks ( lua_State* L ) { MOAILuaState state ( L ); bool clearAfter = state.GetValue < bool >( 1, false ); MOAILuaRuntime& luaRuntime = MOAILuaRuntime::Get (); luaRuntime.ReportLeaksFormatted ( MOAILogMgr::Get ().GetFile ()); if ( clearAfter ) { luaRuntime.ResetLeakTracking (); } return 0; } //----------------------------------------------------------------// /** @name setBoostThreshold @text Sets the boost threshold, a scalar applied to step. If the gap between simulation time and device time is greater than the step size multiplied by the boost threshold and MOAISim.SIM_LOOP_ALLOW_BOOST is set in the loop flags, then the simulation is updated once with a large, variable step to make up the entire gap. @opt number boostThreshold Default value is DEFAULT_BOOST_THRESHOLD. @out nil */ int MOAISim::_setBoostThreshold ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mBoostThreshold = state.GetValue < double >( 1, DEFAULT_BOOST_THRESHOLD ); return 0; } //----------------------------------------------------------------// /** @name setCpuBudget @text Sets the amount of time (given in simulation steps) to allow for updating the simulation. @in number budget Default value is DEFAULT_CPU_BUDGET. @out nil */ int MOAISim::_setCpuBudget ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mCpuBudget = state.GetValue < u32 >( 1, DEFAULT_CPU_BUDGET ); return 0; } //----------------------------------------------------------------// /** @name setHistogramEnabled @text Enable tracking of every MOAILuaObject so that an object count histogram may be generated. @opt bool enable Default value is false. @out nil */ int MOAISim::_setHistogramEnabled ( lua_State* L ) { MOAILuaState state ( L ); MOAILuaRuntime::Get ().EnableHistogram ( state.GetValue < bool >( 1, false )); return 0; } //----------------------------------------------------------------// /** @name setLeakTrackingEnabled @text Enable extra memory book-keeping measures that allow all MOAI objects to be tracked back to their point of allocation (in Lua). Use together with MOAISim.reportLeaks() to determine exactly where your memory usage is being created. NOTE: This is very expensive in terms of both CPU and the extra memory associated with the stack info book-keeping. Use only when tracking down leaks. @opt bool enable Default value is false. @out nil */ int MOAISim::_setLeakTrackingEnabled ( lua_State* L ) { MOAILuaState state ( L ); MOAILuaRuntime::Get ().EnableLeakTracking ( state.GetValue < bool >( 1, false )); return 0; } //----------------------------------------------------------------// /** @name setLongDelayThreshold @text Sets the long delay threshold. If the sim step falls behind the given threshold, the deficit will be dropped: sim will neither spin nor boost to catch up. @opt number longDelayThreshold Default value is DEFAULT_LONG_DELAY_THRESHOLD. @out nil */ int MOAISim::_setLongDelayThreshold ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLongDelayThreshold = state.GetValue < double >( 1, DEFAULT_LONG_DELAY_THRESHOLD ); return 0; } //----------------------------------------------------------------// /** @name setLoopFlags @text Fine tune behavior of the simulation loop. MOAISim.SIM_LOOP_ALLOW_SPIN will allow the simulation step to run multiple times per update to try and catch up with device time, but will abort if processing the simulation exceeds the configfured step time. MOAISim.SIM_LOOP_ALLOW_BOOST will permit a *variable* update step if simulation time falls too far behind device time (based on the boost threshold). Be warned: this can wreak havok with physics and stepwise animation or game AI. Three presets are provided: MOAISim.LOOP_FLAGS_DEFAULT, MOAISim.LOOP_FLAGS_FIXED, and MOAISim.LOOP_FLAGS_MULTISTEP. @opt number flags Mask or a combination of MOAISim.SIM_LOOP_FORCE_STEP, MOAISim.SIM_LOOP_ALLOW_BOOST, MOAISim.SIM_LOOP_ALLOW_SPIN, MOAISim.SIM_LOOP_NO_DEFICIT, MOAISim.SIM_LOOP_NO_SURPLUS, MOAISim.SIM_LOOP_RESET_CLOCK. Default value is 0. @out nil */ int MOAISim::_setLoopFlags ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mLoopFlags |= state.GetValue < u32 >( 1, 0 ); return 0; } //----------------------------------------------------------------// /** @name setLuaAllocLogEnabled @text Toggles log messages from Lua allocator. @opt boolean enable Default value is 'false.' @out nil */ int MOAISim::_setLuaAllocLogEnabled ( lua_State* L ) { MOAILuaState state ( L ); MOAILuaRuntime::Get ().SetAllocLogEnabled ( state.GetValue < bool >( 1, false )); return 0; } //----------------------------------------------------------------// /** @name setStep @text Sets the size of each simulation step (in seconds). @in number step The step size. Default value is 1 / DEFAULT_STEPS_PER_SECOND. @out nil */ int MOAISim::_setStep ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().SetStep ( state.GetValue < double >( 1, 1.0 / ( double )DEFAULT_STEPS_PER_SECOND )); return 0; } //----------------------------------------------------------------// /** @name setStepMultiplier @text Runs the simulation multiple times per step (but with a fixed step size). This is used to speed up the simulation without providing a larger step size (which could destabilize physics simulation). @in number count Default value is DEFAULT_STEP_MULTIPLIER. @out nil */ int MOAISim::_setStepMultiplier ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mStepMultiplier = state.GetValue < u32 >( 1, DEFAULT_STEP_MULTIPLIER ); return 0; } //----------------------------------------------------------------// /** @name setTimerError @text Sets the tolerance for timer error. This is a multiplier of step. Timer error tolerance is step * timerError. @in number timerError Default value is 0.0. @out nil */ int MOAISim::_setTimerError ( lua_State* L ) { MOAILuaState state ( L ); MOAISim::Get ().mTimerError = state.GetValue < double >( 1, 0.0 ); return 0; } //----------------------------------------------------------------// /** @name timeToFrames @text Converts the number of time passed in seconds to frames. @in number time The number of seconds. @out number frames The equivilant number of frames for the specified number of seconds. */ int MOAISim::_timeToFrames ( lua_State* L ) { MOAILuaState state ( L ); if ( !state.CheckParams ( 1, "N" )) return 0; float time = state.GetValue < float >( 1, 0.0f ); MOAISim& device = MOAISim::Get (); lua_pushnumber ( state, time / device.mStep ); return 1; } //================================================================// // MOAISim //================================================================// //----------------------------------------------------------------// void MOAISim::Clear () { while ( this->mRenderPasses.Count ()) { this->PopRenderPass (); } } //----------------------------------------------------------------// MOAISim::MOAISim () : mLoopState ( START ), mStep ( 1.0 / ( double )DEFAULT_STEPS_PER_SECOND ), mSimTime ( 0.0 ), mRealTime ( 0.0 ), mFrameTime ( 0.0 ), mRenderCounter ( 0 ), mFrameRate ( 0.0f ), mFrameRateIdx ( 0 ), mLoopFlags ( LOOP_FLAGS_DEFAULT ), mBoostThreshold ( DEFAULT_BOOST_THRESHOLD ), mLongDelayThreshold ( DEFAULT_LONG_DELAY_THRESHOLD ), mCpuBudget ( DEFAULT_CPU_BUDGET ), mStepMultiplier ( DEFAULT_STEP_MULTIPLIER ), mTimerError ( 0.0 ) { RTTI_SINGLE ( MOAIGlobalEventSource ) for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { this->mFrameRateBuffer [ i ] = 0.0f; } this->mFrameTime = USDeviceTime::GetTimeInSeconds (); } //----------------------------------------------------------------// MOAISim::~MOAISim () { this->Clear (); } //----------------------------------------------------------------// double MOAISim::MeasureFrameRate () { double frameTime = USDeviceTime::GetTimeInSeconds (); double delay = frameTime - this->mFrameTime; this->mFrameTime = frameTime; if ( delay > 0.0 ) { float sample = ( float )( 1.0 / delay ); this->mFrameRateBuffer [ this->mFrameRateIdx++ ] = sample; this->mFrameRateIdx %= FPS_BUFFER_SIZE; sample = 0.0f; for ( u32 i = 0; i < FPS_BUFFER_SIZE; ++i ) { sample += this->mFrameRateBuffer [ i ]; } this->mFrameRate = sample / ( float )FPS_BUFFER_SIZE; } return delay; } //----------------------------------------------------------------// void MOAISim::OnGlobalsFinalize () { this->SendFinalizeEvent (); } //----------------------------------------------------------------// void MOAISim::OnGlobalsRestore () { } //----------------------------------------------------------------// void MOAISim::OnGlobalsRetire () { } //----------------------------------------------------------------// void MOAISim::PauseMOAI () { this->mLoopState = PAUSED; } //----------------------------------------------------------------// void MOAISim::PopRenderPass () { if ( this->mRenderPasses.Count ()) { MOAIProp2D* prop = this->mRenderPasses.Back (); this->mRenderPasses.PopBack (); this->LuaRelease ( *prop ); } } //----------------------------------------------------------------// void MOAISim::PushRenderPass ( MOAIProp2D* prop ) { if ( prop ) { if ( !this->mRenderPasses.Contains ( prop )) { this->LuaRetain ( *prop ); this->mRenderPasses.PushBack ( prop ); } } } //----------------------------------------------------------------// void MOAISim::RegisterLuaClass ( MOAILuaState& state ) { state.SetField ( -1, "EVENT_FINALIZE", ( u32 )EVENT_FINALIZE ); state.SetField ( -1, "SIM_LOOP_FORCE_STEP", ( u32 )SIM_LOOP_FORCE_STEP ); state.SetField ( -1, "SIM_LOOP_ALLOW_BOOST", ( u32 )SIM_LOOP_ALLOW_BOOST ); state.SetField ( -1, "SIM_LOOP_ALLOW_SPIN", ( u32 )SIM_LOOP_ALLOW_SPIN ); state.SetField ( -1, "SIM_LOOP_NO_DEFICIT", ( u32 )SIM_LOOP_NO_DEFICIT ); state.SetField ( -1, "SIM_LOOP_NO_SURPLUS", ( u32 )SIM_LOOP_NO_SURPLUS ); state.SetField ( -1, "SIM_LOOP_RESET_CLOCK", ( u32 )SIM_LOOP_RESET_CLOCK ); state.SetField ( -1, "LOOP_FLAGS_DEFAULT", ( u32 )LOOP_FLAGS_DEFAULT ); state.SetField ( -1, "LOOP_FLAGS_FIXED", ( u32 )LOOP_FLAGS_FIXED ); state.SetField ( -1, "LOOP_FLAGS_MULTISTEP", ( u32 )LOOP_FLAGS_MULTISTEP ); state.SetField ( -1, "DEFAULT_STEPS_PER_SECOND", ( u32 )DEFAULT_STEPS_PER_SECOND ); state.SetField ( -1, "DEFAULT_BOOST_THRESHOLD", ( u32 )DEFAULT_BOOST_THRESHOLD ); state.SetField ( -1, "DEFAULT_LONG_DELAY_THRESHOLD", ( u32 )DEFAULT_LONG_DELAY_THRESHOLD ); state.SetField ( -1, "DEFAULT_CPU_BUDGET", ( u32 )DEFAULT_CPU_BUDGET ); state.SetField ( -1, "DEFAULT_STEP_MULTIPLIER", ( u32 )DEFAULT_STEP_MULTIPLIER ); luaL_Reg regTable [] = { { "clearLoopFlags", _clearLoopFlags }, { "clearRenderStack", _clearRenderStack }, { "enterFullscreenMode", _enterFullscreenMode }, { "exitFullscreenMode", _exitFullscreenMode }, { "forceGarbageCollection", _forceGarbageCollection }, { "framesToTime", _framesToTime }, { "getDeviceSize", _getDeviceSize }, { "getDeviceTime", _getDeviceTime }, { "getElapsedFrames", _getElapsedFrames }, { "getElapsedTime", _getElapsedTime }, { "getLoopFlags", _getLoopFlags }, { "getLuaObjectCount", _getLuaObjectCount }, { "getMemoryUsage", _getMemoryUsage }, { "getPerformance", _getPerformance }, { "getStep", _getStep }, { "openWindow", _openWindow }, { "pauseTimer", _pauseTimer }, { "popRenderPass", _popRenderPass }, { "pushRenderPass", _pushRenderPass }, { "reportHistogram", _reportHistogram }, { "reportLeaks", _reportLeaks }, { "setBoostThreshold", _setBoostThreshold }, { "setCpuBudget", _setCpuBudget}, { "setHistogramEnabled", _setHistogramEnabled }, { "setLeakTrackingEnabled", _setLeakTrackingEnabled }, { "setListener", &MOAIGlobalEventSource::_setListener < MOAISim > }, { "setLongDelayThreshold", _setLongDelayThreshold }, { "setLoopFlags", _setLoopFlags }, { "setLuaAllocLogEnabled", _setLuaAllocLogEnabled }, { "setStep", _setStep }, { "setStepMultiplier", _setStepMultiplier }, { "setTimerError", _setTimerError }, { "timeToFrames", _timeToFrames }, { NULL, NULL } }; luaL_register( state, 0, regTable ); } //----------------------------------------------------------------// void MOAISim::RegisterLuaFuncs ( MOAILuaState& state ) { UNUSED ( state ); } //----------------------------------------------------------------// void MOAISim::Render () { this->mRenderCounter++; MOAIGfxDevice::Get ().BeginDrawing (); RenderPassIt passIt = this->mRenderPasses.Head (); for ( ; passIt; passIt = passIt->Next ()) { MOAIProp2D* renderPass = passIt->Data (); MOAIGfxDevice::Get ().BeginLayer (); renderPass->Draw (); } MOAIGfxDevice::Get ().Flush (); } //----------------------------------------------------------------// void MOAISim::ResumeMOAI() { if ( this->mLoopState == PAUSED ) { this->mLoopState = START; } } //----------------------------------------------------------------// void MOAISim::RunFile ( cc8* filename ) { if ( !USFileSys::CheckFileExists ( filename )) return; int status; MOAILuaStateHandle state = MOAILuaRuntime::Get ().State (); status = luaL_loadfile ( state, filename ); if ( state.PrintErrors ( USLog::CONSOLE, status )) return; state.DebugCall ( 0, 0 ); } //----------------------------------------------------------------// void MOAISim::RunString ( cc8* script ) { int status; MOAILuaStateHandle state = MOAILuaRuntime::Get ().State (); status = luaL_loadstring ( state, script ); if ( state.PrintErrors ( USLog::CONSOLE, status )) return; state.DebugCall ( 0, 0 ); } //----------------------------------------------------------------// void MOAISim::SendFinalizeEvent () { MOAILuaStateHandle state = MOAILuaRuntime::Get ().State (); if ( this->PushListener ( EVENT_FINALIZE, state )) { state.DebugCall ( 0, 0 ); } } //----------------------------------------------------------------// void MOAISim::SetStep ( double step ) { if ( this->mStep != step ) { this->mStep = step; AKUSetSimStepFunc setSimStep = AKUGetFunc_SetSimStep (); if ( setSimStep ) { setSimStep ( step ); } } } //----------------------------------------------------------------// double MOAISim::StepSim ( double step, u32 multiplier ) { double time = USDeviceTime::GetTimeInSeconds (); for ( u32 s = 0; s < multiplier; ++s ) { MOAIDebugLines::Get ().Reset (); MOAIInputMgr::Get ().Update (); MOAIActionMgr::Get ().Update (( float )step ); MOAINodeMgr::Get ().Update (); } this->mSimTime += step * ( double )multiplier; return USDeviceTime::GetTimeInSeconds () - time; } //----------------------------------------------------------------// void MOAISim::Update () { double interval = this->MeasureFrameRate (); // try to account for timer error if ( this->mTimerError != 0.0 ) { double steps = interval / this->mStep; double integer = floor ( steps ); double decimal = steps - integer; if ( decimal <= this->mTimerError ) { interval = this->mStep * integer; } else if ( decimal >= ( 1.0 - this->mTimerError )) { interval = this->mStep * ( integer + 1.0 ); } } // actual device time elapsed since starting or restarting the sim this->mRealTime += interval; // bail if we're paused if ( this->mLoopState == PAUSED ) { return; } // the reset clock flag warps the sim time ahead to match real time just once, then autoclears // this means there will be no time deficit or attempted catch-up // if spinning is not allowed, also clear prevent any time deficit if ( this->mLoopFlags & SIM_LOOP_RESET_CLOCK ) { this->mLoopState = START; this->mLoopFlags &= ~SIM_LOOP_RESET_CLOCK; } // 'budget' will be used to measure the actual CPU time each sim step takes to proces // initialize budget to limit time spent updating when the sim has fallen behind realtime // this prevents a scenario where the sim falls behind but loops forever when attempting to catch up due to // the update itself taking too long and increading the gap between real and target time double budget = this->mStep * this->mCpuBudget; // reset sim time on start if ( this->mLoopState == START ) { this->mRealTime = this->mSimTime; this->mLoopState = RUNNING; // perform an empty step to initialize the sim // subtract the elapsed CPU time from the budget budget -= this->StepSim ( 0.0, 1 ); } // 'gap' is the time left to make up between sim time and real time // i.e. the time deficit double gap = this->mRealTime - this->mSimTime; // long delay lets us ignore gaps bigger than a certain threshold if (( this->mLoopFlags & SIM_LOOP_LONG_DELAY ) && ( gap > ( this->mStep * this->mLongDelayThreshold ))) { budget -= this->StepSim ( gap, 1 ); gap = 0.0f; this->mRealTime = this->mSimTime; } // boost mode allows the sim to perform a large, variable-sized step to // make up the entire time deficit - but only if the sim has fallen behind // by a certain threshold (given in number of frames) // we only boost if we've fallen behind the number of steps given by boost threshold if (( this->mLoopFlags & SIM_LOOP_ALLOW_BOOST ) && ( gap > ( this->mStep * this->mBoostThreshold ))) { budget -= this->StepSim ( gap, 1 ); gap = 0.0f; } else { // we didn't boost, so process steps normally... // perform a single step only if the time deficit is greater than step time // in other words, at least one interval of step time has elapsed in real time // so we need to catch up if (( this->mLoopFlags & SIM_LOOP_FORCE_STEP ) || (( this->mStep <= gap ) && ( budget > 0.0 ))) { budget -= this->StepSim ( this->mStep, this->mStepMultiplier ); gap -= this->mStep * ( double )this->mStepMultiplier; } // spin mode allows us to attempt to close the time deficit by using our // budget to run additional sim steps // of course, if the sim takes an excessively long time to process // we may never catch up... if ( this->mLoopFlags & SIM_LOOP_ALLOW_SPIN ) { while (( this->mStep <= gap ) && ( budget > 0.0 )) { budget -= this->StepSim ( this->mStep, this->mStepMultiplier ); gap -= this->mStep * ( double )this->mStepMultiplier; } } } // if real time is more than a step ahead of sim time (for whatever reason), wait up if (( this->mLoopFlags & SIM_LOOP_NO_DEFICIT ) && (( this->mRealTime - this->mSimTime ) >= this->mStep )) { this->mRealTime = this->mSimTime; } // if real time is behind sim time (for whatever reason), catch up if (( this->mLoopFlags & SIM_LOOP_NO_SURPLUS ) && ( this->mRealTime < this->mSimTime )) { this->mRealTime = this->mSimTime; } // these stay out of the sim step for now MOAIUrlMgr::Get ().Process (); this->mDataIOThread.Publish (); }
[ [ [ 1, 4 ], [ 6, 6 ], [ 8, 12 ], [ 15, 16 ], [ 24, 27 ], [ 41, 48 ], [ 50, 64 ], [ 66, 82 ], [ 84, 92 ], [ 108, 116 ], [ 118, 136 ], [ 138, 138 ], [ 141, 144 ], [ 157, 165 ], [ 167, 177 ], [ 179, 181 ], [ 314, 324 ], [ 326, 331 ], [ 333, 350 ], [ 352, 354 ], [ 356, 357 ], [ 359, 386 ], [ 388, 398 ], [ 459, 459 ], [ 463, 463 ], [ 600, 608 ], [ 610, 616 ], [ 618, 633 ], [ 648, 648 ], [ 650, 650 ], [ 656, 663 ], [ 701, 703 ], [ 705, 712 ], [ 714, 721 ], [ 723, 728 ], [ 730, 730 ], [ 750, 750 ], [ 752, 754 ], [ 756, 757 ], [ 759, 760 ], [ 766, 769 ], [ 783, 789 ], [ 795, 797 ], [ 802, 804 ], [ 807, 809 ], [ 811, 815 ], [ 818, 826 ], [ 828, 829 ], [ 831, 838 ], [ 840, 841 ], [ 843, 846 ], [ 886, 887 ], [ 931, 931 ], [ 960, 960 ], [ 995, 996 ] ], [ [ 5, 5 ], [ 287, 289 ], [ 291, 301 ], [ 638, 638 ], [ 640, 641 ], [ 651, 653 ], [ 664, 664 ], [ 666, 666 ], [ 670, 683 ], [ 686, 687 ], [ 764, 764 ], [ 888, 888 ] ], [ [ 7, 7 ], [ 13, 14 ], [ 18, 18 ], [ 20, 21 ], [ 28, 40 ], [ 49, 49 ], [ 65, 65 ], [ 83, 83 ], [ 93, 107 ], [ 117, 117 ], [ 137, 137 ], [ 139, 140 ], [ 145, 156 ], [ 166, 166 ], [ 178, 178 ], [ 182, 204 ], [ 236, 236 ], [ 244, 245 ], [ 247, 249 ], [ 290, 290 ], [ 302, 313 ], [ 325, 325 ], [ 332, 332 ], [ 351, 351 ], [ 355, 355 ], [ 358, 358 ], [ 387, 387 ], [ 399, 410 ], [ 426, 426 ], [ 430, 438 ], [ 442, 458 ], [ 460, 462 ], [ 464, 464 ], [ 467, 469 ], [ 473, 599 ], [ 609, 609 ], [ 634, 637 ], [ 639, 639 ], [ 642, 642 ], [ 644, 647 ], [ 649, 649 ], [ 654, 655 ], [ 665, 665 ], [ 667, 669 ], [ 684, 685 ], [ 688, 700 ], [ 704, 704 ], [ 713, 713 ], [ 722, 722 ], [ 729, 729 ], [ 731, 749 ], [ 751, 751 ], [ 755, 755 ], [ 758, 758 ], [ 761, 762 ], [ 765, 765 ], [ 770, 770 ], [ 772, 782 ], [ 790, 794 ], [ 798, 801 ], [ 805, 806 ], [ 810, 810 ], [ 816, 817 ], [ 827, 827 ], [ 830, 830 ], [ 839, 839 ], [ 842, 842 ], [ 847, 874 ], [ 880, 885 ], [ 889, 930 ], [ 932, 933 ], [ 935, 937 ], [ 940, 959 ], [ 961, 969 ], [ 971, 994 ] ], [ [ 17, 17 ], [ 19, 19 ], [ 22, 23 ], [ 205, 235 ], [ 237, 243 ], [ 246, 246 ], [ 250, 286 ], [ 411, 425 ], [ 427, 429 ], [ 439, 441 ], [ 763, 763 ], [ 771, 771 ] ], [ [ 465, 466 ], [ 470, 472 ], [ 643, 643 ], [ 875, 879 ], [ 934, 934 ], [ 938, 939 ], [ 970, 970 ] ], [ [ 617, 617 ] ] ]
c67e3406f0f703df7d520dad6a1c8c8b47c2a6a9
c63c4fed502fd4cbf82acc7901ba0d72b0338bdb
/Create/Task/WallFollowerTask.cpp
cff9e0097c35f26efffe9248f4051df4f490479a
[]
no_license
seeyousystems/core
7436a38fb09ea08f5d29cf8db2490c92f48d9267
baddc89a366ad769a1a9c9a59c14f28291b81971
refs/heads/master
2020-05-17T19:11:57.814200
2011-05-06T04:00:59
2011-05-06T04:00:59
1,517,217
1
4
null
null
null
null
UTF-8
C++
false
false
3,117
cpp
/* * WallFollowerTask.cpp * * =========================================================================== * * Copyright 2008-2009 Daniel Kruesi (Dan Krusi) and David Grob * * This file is part of the emms framework. * * The emms framework is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The emms framework is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. * */ #include "WallFollowerTask.h" #include "../Navigation/Navigation.h" #include "../Navigation/SystemOfWeightsNavigation.h" #include "../Navigation/Weight/WallFollowerWeight.h" #include "../Navigation/Weight/FullSpeedWeight.h" #include "../Navigation/Weight/ControllerSpeedWeight.h" #include "../Navigation/Weight/OrientationWeight.h" #include "../Navigation/Weight/CollisionAvoidanceWeight.h" #include "../Navigation/Weight/AccelerationFilterWeight.h" #include "../Navigation/Weight/JoystickWeight.h" #include "../Map/StructureMap.h" #include "../Controller/EmssController.h" #include "../Library/Debug.h" WallFollowerTask::WallFollowerTask(Create *create, int speed, TaskPriority priority) : Task("WallFollowerTask", create, create->intSetting("Task_DefaultInterval"), priority) { startPosition = Vector2D(0,0); } WallFollowerTask::~WallFollowerTask() { } void WallFollowerTask::preProcess() { if( create->navigation->name == "SystemOfWeightsNavigation"){ navigation = (SystemOfWeightsNavigation*) create->navigation; navigation->deleteAllWeights(); navigation->addWeight(new FullSpeedWeight(create)); navigation->addWeight(new WallFollowerWeight(create)); navigation->addWeight(new JoystickWeight(create)); navigation->addWeight(new CollisionAvoidanceWeight(create, CollisionAvoidanceWeight::AvoidanceDirectionLeft)); navigation->addWeight(new AccelerationFilterWeight(create)); navigation->addWeight(new ControllerSpeedWeight(create)); } else { Debug::warning("This navigation module is not supported"); this->status = Interrupted; } } void WallFollowerTask::process() { Vector2D wheelSpeed = navigation->getWheelSpeed(0,0); create->controller->setWheelSpeed((short)wheelSpeed.x(), (short)wheelSpeed.y()); // Is Task finished if (create->structureMap->isFinish() == true){ this->status = Finished; //navigation->deleteAllWeights(); Debug::print("[WallFollowerTask] WallFollower Task Finished"); } } void WallFollowerTask::postProcess() { create->controller->setWheelSpeed(0, 0); } QString WallFollowerTask::description() { return QString("Task:\tWallFollower"); }
[ [ [ 1, 90 ] ] ]
31ca52e0f8788ac736b7e51a06b813de28f3578c
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/DirectInputInit.cpp
4a7f2c6a5bcaa34e9bd8262af0d830dbd9a19596
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
2,569
cpp
#include "DirectInput.h" CDirectInput* CDirectInput::Singleton = NULL; CDirectInput::CDirectInput(void) { m_pDIObject = NULL; m_pDIKeyboard = NULL; void(::memset(&m_bKeyDown, NULL, sizeof(m_bKeyDown))); m_pDIMouse = NULL; void(::memset(&m_MouseState, NULL, sizeof(m_MouseState))); void(::memset(&m_MousePosition, NULL, sizeof(m_MousePosition))); m_HResult = NULL; m_HWnd = NULL; m_HResult = NULL; m_ClickOnce = false; } CDirectInput* CDirectInput::GetInstance(HINSTANCE hInst, HWND hWnd) { if(Singleton == NULL) { Singleton = new CDirectInput(); Singleton->m_HInst = hInst; Singleton->m_HWnd = hWnd; Singleton->Init(); return Singleton; } else return Singleton; } CDirectInput* CDirectInput::GetInstance(void) { return Singleton; } void CDirectInput::Init() { // Create the Direct Input Object // m_HResult = DirectInput8Create(m_HInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDIObject, NULL); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Create Input Device", "DirectInput8Create() Failed", MB_OK | MB_ICONERROR); } // Initialize Mouse // m_HResult = m_pDIObject->CreateDevice(GUID_SysMouse, &m_pDIMouse, NULL); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Create Mouse Device", "CreateDevice() Failed", MB_OK | MB_ICONERROR); } // Set up Mouse // m_HResult = m_pDIMouse->SetCooperativeLevel(m_HWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Set Mouse Cooperative Level", "SetCooperativeLevel() Failed", MB_OK | MB_ICONERROR); } // 2 Button Mouse // m_HResult = m_pDIMouse->SetDataFormat(&c_dfDIMouse2); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Set Mouse Data Format", "SetDataFormat() Failed", MB_OK | MB_ICONERROR); } // Initialize Keyboard // m_HResult = m_pDIObject->CreateDevice(GUID_SysKeyboard, &m_pDIKeyboard, NULL); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Create Keyboard Device", "CreateDevice() Failed", MB_OK | MB_ICONERROR); } // Set up Keyboard // m_pDIKeyboard->SetCooperativeLevel(m_HWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Set Keyboard Cooperative Level", "SetCooperativeLevel() Failed", MB_OK | MB_ICONERROR); } m_pDIKeyboard->SetDataFormat(&c_dfDIKeyboard); if(m_HResult != S_OK) { ::MessageBoxA(m_HWnd, "Failed to Set Keyboard Data Format", "SetDataFormat() Failed", MB_OK | MB_ICONERROR); } }
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 82 ] ] ]
b3897895bf40f5bcd29fa6f8ca56972645413a4b
971b000b9e6c4bf91d28f3723923a678520f5bcf
/OO_Widged/demo/textedit.cpp
ca2605cdb38638b0981122a05475024b0b5fc1d4
[]
no_license
google-code-export/fop-miniscribus
14ce53d21893ce1821386a94d42485ee0465121f
966a9ca7097268c18e690aa0ea4b24b308475af9
refs/heads/master
2020-12-24T17:08:51.551987
2011-09-02T07:55:05
2011-09-02T07:55:05
32,133,292
2
0
null
null
null
null
UTF-8
C++
false
false
24,578
cpp
/**************************************************************************** ** ** Copyright (C) 2004-2008 Trolltech ASA. All rights reserved. ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License versions 2.0 or 3.0 as published by the Free Software ** Foundation and appearing in the files LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Alternatively you may (at ** your option) use any later version of the GNU General Public ** License if such license has been publicly approved by Trolltech ASA ** (or its successors, if any) and the KDE Free Qt Foundation. In ** addition, as a special exception, Trolltech gives you certain ** additional rights. These rights are described in the Trolltech GPL ** Exception version 1.2, which can be found at ** http://www.trolltech.com/products/qt/gplexception/ and in the file ** GPL_EXCEPTION.txt in this package. ** ** Please review the following information to ensure GNU General ** Public Licensing requirements will be met: ** http://trolltech.com/products/qt/licenses/licensing/opensource/. If ** you are unsure which license is appropriate for your use, please ** review the following information: ** http://trolltech.com/products/qt/licenses/licensing/licensingoverview ** or contact the sales department at [email protected]. ** ** In addition, as a special exception, Trolltech, as the sole ** copyright holder for Qt Designer, grants users of the Qt/Eclipse ** Integration plug-in the right for the Qt/Eclipse Integration to ** link to functionality provided by Qt Designer and its related ** libraries. ** ** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, ** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE. Trolltech reserves all rights not expressly ** granted herein. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include "textedit.h" #include <QAction> #include <QApplication> #include <QClipboard> #include <QColorDialog> #include <QComboBox> #include <QFontComboBox> #include <QFile> #include <QFileDialog> #include <QFileInfo> #include <QFontDatabase> #include <QMenu> #include <QMenuBar> #include <QPrintDialog> #include <QPrinter> #include <QTextCodec> #include <QTextEdit> #include <QToolBar> #include <QTextCursor> #include <QTextList> #include <QtDebug> #include <QCloseEvent> #include <QMessageBox> #include <QPrintPreviewDialog> ////// #include "OOReader.h" static inline QString FileFilterHaving() { QString filter; filter = ""; ///////filter += QString( "FOP file" ) + " (*.fop *.fop.gz *.fo *.fo.gz *.xml);;"; /////filter+= QString( "MiniScribus binary stream file" ) + " (*.page);;"; //////filter+= QString( "OpenOffice 1.1 file format" ) + " (*.sxw *.stw);;"; filter+= QString( "OpenOffice 2.4 file format OASIS " ) + " (*.odt *.ott);;"; filter+= QString( "XHTML file format" ) + " (*.htm *.html);;"; //////filter += ")"; return filter; } #ifdef Q_WS_MAC const QString rsrcPath = ":/images/mac"; #else const QString rsrcPath = ":/images/win"; #endif TextEdit::TextEdit(QWidget *parent) : QMainWindow(parent) { setupFileActions(); setupEditActions(); setupTextActions(); { QMenu *helpMenu = new QMenu(tr("Help"), this); menuBar()->addMenu(helpMenu); helpMenu->addAction(tr("About"), this, SLOT(about())); helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); } textEdit = new QTextEdit(this); connect(textEdit, SIGNAL(currentCharFormatChanged(const QTextCharFormat &)), this, SLOT(currentCharFormatChanged(const QTextCharFormat &))); connect(textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChanged())); setCentralWidget(textEdit); textEdit->setFocus(); setCurrentFileName(QString()); fontChanged(textEdit->font()); colorChanged(textEdit->textColor()); alignmentChanged(textEdit->alignment()); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), actionSave, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool))); connect(textEdit->document(), SIGNAL(undoAvailable(bool)), actionUndo, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(redoAvailable(bool)), actionRedo, SLOT(setEnabled(bool))); setWindowModified(textEdit->document()->isModified()); actionSave->setEnabled(textEdit->document()->isModified()); actionUndo->setEnabled(textEdit->document()->isUndoAvailable()); actionRedo->setEnabled(textEdit->document()->isRedoAvailable()); connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo())); connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo())); actionCut->setEnabled(false); actionCopy->setEnabled(false); connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut())); connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy())); connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste())); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); statusbar = new QStatusBar(this); statusbar->setObjectName(QString::fromUtf8("statusbar")); setStatusBar(statusbar); //// 4.41 = 263169 ///////qDebug() << "### QT_VERSION " << QT_VERSION; QString initialFile; const QStringList args = QCoreApplication::arguments(); if (args.count() == 2) initialFile = args.at(1); if (!load(initialFile)) fileNew(); } void TextEdit::closeEvent(QCloseEvent *e) { if (maybeSave()) e->accept(); else e->ignore(); } void TextEdit::setupFileActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("File Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("&File"), this); menuBar()->addMenu(menu); QAction *a; a = new QAction(QIcon(rsrcPath + "/filenew.png"), tr("&New"), this); a->setShortcut(QKeySequence::New); connect(a, SIGNAL(triggered()), this, SLOT(fileNew())); tb->addAction(a); menu->addAction(a); a = new QAction(QIcon(rsrcPath + "/fileopen.png"), tr("&Open..."), this); a->setShortcut(QKeySequence::Open); connect(a, SIGNAL(triggered()), this, SLOT(fileOpen())); tb->addAction(a); menu->addAction(a); menu->addSeparator(); actionSave = a = new QAction(QIcon(rsrcPath + "/filesave.png"), tr("&Save"), this); a->setShortcut(QKeySequence::Save); connect(a, SIGNAL(triggered()), this, SLOT(fileSave())); a->setEnabled(false); tb->addAction(a); menu->addAction(a); a = new QAction(tr("Save &As..."), this); connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs())); menu->addAction(a); menu->addSeparator(); a = new QAction(QIcon(rsrcPath + "/fileprint.png"), tr("&Print..."), this); a->setShortcut(QKeySequence::Print); connect(a, SIGNAL(triggered()), this, SLOT(filePrint())); tb->addAction(a); menu->addAction(a); a = new QAction(QIcon(rsrcPath + "/fileprint.png"), tr("Print Preview..."), this); connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview())); menu->addAction(a); a = new QAction(QIcon(rsrcPath + "/exportpdf.png"), tr("&Export PDF..."), this); a->setShortcut(Qt::CTRL + Qt::Key_D); connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf())); tb->addAction(a); menu->addAction(a); menu->addSeparator(); a = new QAction(tr("&Quit"), this); a->setShortcut(Qt::CTRL + Qt::Key_Q); connect(a, SIGNAL(triggered()), this, SLOT(close())); menu->addAction(a); } void TextEdit::setupEditActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("Edit Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("&Edit"), this); menuBar()->addMenu(menu); QAction *a; a = actionUndo = new QAction(QIcon(rsrcPath + "/editundo.png"), tr("&Undo"), this); a->setShortcut(QKeySequence::Undo); tb->addAction(a); menu->addAction(a); a = actionRedo = new QAction(QIcon(rsrcPath + "/editredo.png"), tr("&Redo"), this); a->setShortcut(QKeySequence::Redo); tb->addAction(a); menu->addAction(a); menu->addSeparator(); a = actionCut = new QAction(QIcon(rsrcPath + "/editcut.png"), tr("Cu&t"), this); a->setShortcut(QKeySequence::Cut); tb->addAction(a); menu->addAction(a); a = actionCopy = new QAction(QIcon(rsrcPath + "/editcopy.png"), tr("&Copy"), this); a->setShortcut(QKeySequence::Copy); tb->addAction(a); menu->addAction(a); a = actionPaste = new QAction(QIcon(rsrcPath + "/editpaste.png"), tr("&Paste"), this); a->setShortcut(QKeySequence::Paste); tb->addAction(a); menu->addAction(a); actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty()); } void TextEdit::setupTextActions() { QToolBar *tb = new QToolBar(this); tb->setWindowTitle(tr("Format Actions")); addToolBar(tb); QMenu *menu = new QMenu(tr("F&ormat"), this); menuBar()->addMenu(menu); actionTextBold = new QAction(QIcon(rsrcPath + "/textbold.png"), tr("&Bold"), this); actionTextBold->setShortcut(Qt::CTRL + Qt::Key_B); QFont bold; bold.setBold(true); actionTextBold->setFont(bold); connect(actionTextBold, SIGNAL(triggered()), this, SLOT(textBold())); tb->addAction(actionTextBold); menu->addAction(actionTextBold); actionTextBold->setCheckable(true); actionTextItalic = new QAction(QIcon(rsrcPath + "/textitalic.png"), tr("&Italic"), this); actionTextItalic->setShortcut(Qt::CTRL + Qt::Key_I); QFont italic; italic.setItalic(true); actionTextItalic->setFont(italic); connect(actionTextItalic, SIGNAL(triggered()), this, SLOT(textItalic())); tb->addAction(actionTextItalic); menu->addAction(actionTextItalic); actionTextItalic->setCheckable(true); actionTextUnderline = new QAction(QIcon(rsrcPath + "/textunder.png"), tr("&Underline"), this); actionTextUnderline->setShortcut(Qt::CTRL + Qt::Key_U); QFont underline; underline.setUnderline(true); actionTextUnderline->setFont(underline); connect(actionTextUnderline, SIGNAL(triggered()), this, SLOT(textUnderline())); tb->addAction(actionTextUnderline); menu->addAction(actionTextUnderline); actionTextUnderline->setCheckable(true); menu->addSeparator(); QActionGroup *grp = new QActionGroup(this); connect(grp, SIGNAL(triggered(QAction *)), this, SLOT(textAlign(QAction *))); actionAlignLeft = new QAction(QIcon(rsrcPath + "/textleft.png"), tr("&Left"), grp); actionAlignLeft->setShortcut(Qt::CTRL + Qt::Key_L); actionAlignLeft->setCheckable(true); actionAlignCenter = new QAction(QIcon(rsrcPath + "/textcenter.png"), tr("C&enter"), grp); actionAlignCenter->setShortcut(Qt::CTRL + Qt::Key_E); actionAlignCenter->setCheckable(true); actionAlignRight = new QAction(QIcon(rsrcPath + "/textright.png"), tr("&Right"), grp); actionAlignRight->setShortcut(Qt::CTRL + Qt::Key_R); actionAlignRight->setCheckable(true); actionAlignJustify = new QAction(QIcon(rsrcPath + "/textjustify.png"), tr("&Justify"), grp); actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J); actionAlignJustify->setCheckable(true); tb->addActions(grp->actions()); menu->addActions(grp->actions()); menu->addSeparator(); QPixmap pix(16, 16); pix.fill(Qt::black); actionTextColor = new QAction(pix, tr("&Color..."), this); connect(actionTextColor, SIGNAL(triggered()), this, SLOT(textColor())); tb->addAction(actionTextColor); menu->addAction(actionTextColor); tb = new QToolBar(this); tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea); tb->setWindowTitle(tr("Format Actions")); addToolBarBreak(Qt::TopToolBarArea); addToolBar(tb); comboStyle = new QComboBox(tb); tb->addWidget(comboStyle); comboStyle->addItem("Standard"); comboStyle->addItem("Bullet List (Disc)"); comboStyle->addItem("Bullet List (Circle)"); comboStyle->addItem("Bullet List (Square)"); comboStyle->addItem("Ordered List (Decimal)"); comboStyle->addItem("Ordered List (Alpha lower)"); comboStyle->addItem("Ordered List (Alpha upper)"); connect(comboStyle, SIGNAL(activated(int)), this, SLOT(textStyle(int))); comboFont = new QFontComboBox(tb); tb->addWidget(comboFont); connect(comboFont, SIGNAL(activated(const QString &)), this, SLOT(textFamily(const QString &))); comboSize = new QComboBox(tb); comboSize->setObjectName("comboSize"); tb->addWidget(comboSize); comboSize->setEditable(true); QFontDatabase db; foreach(int size, db.standardSizes()) comboSize->addItem(QString::number(size)); connect(comboSize, SIGNAL(activated(const QString &)), this, SLOT(textSize(const QString &))); comboSize->setCurrentIndex(comboSize->findText(QString::number(QApplication::font() .pointSize()))); } void TextEdit::drawDoc() { /* remote image is loading after ..... */ if (Ooo) { textEdit->setDocument ( Ooo->document()->clone() ); delete Ooo; } if (force) { force->quit(); } } void TextEdit::onRead( int now ,int tot ) { //////qDebug() << "### reading line -> " << now << " t." << tot; } bool TextEdit::load(const QString &f) { QFileInfo fi(f); const QString ext = fi.completeSuffix().toLower(); if (!fi.exists()) { return false; } if ( ext == "odt" || ext == "ott" ) { force = new PushDoc(this); Ooo = new OOReader(f); Ooo->moveToThread(force); connect(force, SIGNAL(started()),Ooo,SLOT(read())); connect(Ooo, SIGNAL(ready()), this, SLOT(drawDoc())); connect(Ooo, SIGNAL(statusRead(int,int)), this, SLOT(onRead(int,int))); force->start(); setCurrentFileName(f); return true; } else { QFile file(f); if (!file.open(QFile::ReadOnly)) return false; QByteArray data = file.readAll(); QTextCodec *codec = Qt::codecForHtml(data); QString str = codec->toUnicode(data); if (Qt::mightBeRichText(str)) { textEdit->setHtml(str); } else { str = QString::fromLocal8Bit(data); textEdit->setPlainText(str); } setCurrentFileName(f); return true; } } bool TextEdit::maybeSave() { if (!textEdit->document()->isModified()) return true; if (fileName.startsWith(QLatin1String(":/"))) return true; QMessageBox::StandardButton ret; ret = QMessageBox::warning(this, tr("Application"), tr("The document has been modified.\n" "Do you want to save your changes?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); if (ret == QMessageBox::Save) return fileSave(); else if (ret == QMessageBox::Cancel) return false; return true; } void TextEdit::setCurrentFileName(const QString &fileName) { this->fileName = fileName; textEdit->document()->setModified(false); QString shownName; if (fileName.isEmpty()) shownName = "untitled.txt"; else shownName = QFileInfo(fileName).fileName(); setWindowTitle(QString("%1[*] OASIS Open Document Format for Office Applications").arg(shownName)); setWindowModified(false); } void TextEdit::fileNew() { if (maybeSave()) { textEdit->clear(); setCurrentFileName(QString()); } } void TextEdit::fileOpen() { QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."), QString(setter.value("LastDir").toString()), FileFilterHaving() ); if (!fn.isEmpty()) { QFileInfo fi(fn); setter.setValue("LastDir",fi.absolutePath() +"/"); load(fn); } } bool TextEdit::fileSave() { if (fileName.isEmpty()) return fileSaveAs(); bool canodt = false; #if QT_VERSION >= 0x040500 canodt = true; #endif const QString ext = QFileInfo(fileName).completeSuffix().toLower(); if (ext == "odt" && canodt) { #if QT_VERSION >= 0x040500 QTextDocumentWriter writer(fileName); return writer.write(textEdit->document()); #endif return false; } else { QFile file(fileName); if (!file.open(QFile::WriteOnly)) return false; QTextStream ts(&file); ts.setCodec(QTextCodec::codecForName("UTF-8")); ts << textEdit->document()->toHtml("UTF-8"); textEdit->document()->setModified(false); } return true; } bool TextEdit::fileSaveAs() { QString support; #if QT_VERSION >= 0x040500 support = tr("ODF files (*.odt);;HTML-Files (*.htm *.html);;All Files (*)"); #else support = tr("HTML-Files (*.htm *.html);;All Files (*)"); #endif QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(),support); if (fn.isEmpty()) return false; setCurrentFileName(fn); return fileSave(); } void TextEdit::filePrint() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, this); if (textEdit->textCursor().hasSelection()) dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) { textEdit->print(&printer); } delete dlg; #endif } void TextEdit::filePrintPreview() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintPreviewDialog preview(&printer, this); preview.setWindowFlags ( Qt::Window ); connect(&preview, SIGNAL(paintRequested(QPrinter *)), SLOT(printPreview(QPrinter *))); preview.exec(); #endif } void TextEdit::printPreview(QPrinter *printer) { #ifndef QT_NO_PRINTER textEdit->print(printer); #endif } void TextEdit::filePrintPdf() { #ifndef QT_NO_PRINTER //! [0] QString fileName = QFileDialog::getSaveFileName(this, "Export PDF", QString(), "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".pdf"); QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); textEdit->document()->print(&printer); } //! [0] #endif } void TextEdit::textBold() { QTextCharFormat fmt; fmt.setFontWeight(actionTextBold->isChecked() ? QFont::Bold : QFont::Normal); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textUnderline() { QTextCharFormat fmt; fmt.setFontUnderline(actionTextUnderline->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textItalic() { QTextCharFormat fmt; fmt.setFontItalic(actionTextItalic->isChecked()); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textFamily(const QString &f) { QTextCharFormat fmt; fmt.setFontFamily(f); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textSize(const QString &p) { QTextCharFormat fmt; fmt.setFontPointSize(p.toFloat()); mergeFormatOnWordOrSelection(fmt); } void TextEdit::textStyle(int styleIndex) { QTextCursor cursor = textEdit->textCursor(); if (styleIndex != 0) { QTextListFormat::Style style = QTextListFormat::ListDisc; switch (styleIndex) { default: case 1: style = QTextListFormat::ListDisc; break; case 2: style = QTextListFormat::ListCircle; break; case 3: style = QTextListFormat::ListSquare; break; case 4: style = QTextListFormat::ListDecimal; break; case 5: style = QTextListFormat::ListLowerAlpha; break; case 6: style = QTextListFormat::ListUpperAlpha; break; } cursor.beginEditBlock(); QTextBlockFormat blockFmt = cursor.blockFormat(); QTextListFormat listFmt; if (cursor.currentList()) { listFmt = cursor.currentList()->format(); } else { listFmt.setIndent(blockFmt.indent() + 1); blockFmt.setIndent(0); cursor.setBlockFormat(blockFmt); } listFmt.setStyle(style); cursor.createList(listFmt); cursor.endEditBlock(); } else { // #### QTextBlockFormat bfmt; bfmt.setObjectIndex(-1); cursor.mergeBlockFormat(bfmt); } } void TextEdit::textColor() { QColor col = QColorDialog::getColor(textEdit->textColor(), this); if (!col.isValid()) return; QTextCharFormat fmt; fmt.setForeground(col); mergeFormatOnWordOrSelection(fmt); colorChanged(col); } void TextEdit::textAlign(QAction *a) { if (a == actionAlignLeft) textEdit->setAlignment(Qt::AlignLeft); else if (a == actionAlignCenter) textEdit->setAlignment(Qt::AlignHCenter); else if (a == actionAlignRight) textEdit->setAlignment(Qt::AlignRight); else if (a == actionAlignJustify) textEdit->setAlignment(Qt::AlignJustify); } void TextEdit::currentCharFormatChanged(const QTextCharFormat &format) { fontChanged(format.font()); colorChanged(format.foreground().color()); } void TextEdit::cursorPositionChanged() { alignmentChanged(textEdit->alignment()); } void TextEdit::clipboardDataChanged() { actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty()); } void TextEdit::about() { QMessageBox::about(this, tr("About"), tr("This example demonstrates Qt's " "rich text editing facilities in action, providing an example " "document for you to experiment with.")); } void TextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format) { QTextCursor cursor = textEdit->textCursor(); if (!cursor.hasSelection()) cursor.select(QTextCursor::WordUnderCursor); cursor.mergeCharFormat(format); textEdit->mergeCurrentCharFormat(format); } void TextEdit::fontChanged(const QFont &f) { comboFont->setCurrentIndex(comboFont->findText(QFontInfo(f).family())); comboSize->setCurrentIndex(comboSize->findText(QString::number(f.pointSize()))); actionTextBold->setChecked(f.bold()); actionTextItalic->setChecked(f.italic()); actionTextUnderline->setChecked(f.underline()); } void TextEdit::colorChanged(const QColor &c) { QPixmap pix(16, 16); pix.fill(c); actionTextColor->setIcon(pix); } void TextEdit::alignmentChanged(Qt::Alignment a) { if (a & Qt::AlignLeft) { actionAlignLeft->setChecked(true); } else if (a & Qt::AlignHCenter) { actionAlignCenter->setChecked(true); } else if (a & Qt::AlignRight) { actionAlignRight->setChecked(true); } else if (a & Qt::AlignJustify) { actionAlignJustify->setChecked(true); } }
[ "ppkciz@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 772 ] ] ]
ee2b97ed3480ed574697eac55ee6a71fefc7eebd
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/deprecated/DOM_DocumentType.cpp
ae63b651f02420f02ad957116aa59750be45d6a6
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
2,588
cpp
/* * Copyright 1999-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOM_DocumentType.cpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #include "DOM_DocumentType.hpp" #include "DocumentTypeImpl.hpp" #include "DOM_NamedNodeMap.hpp" #include <assert.h> XERCES_CPP_NAMESPACE_BEGIN DOM_DocumentType::DOM_DocumentType() : DOM_Node(null) { }; DOM_DocumentType::DOM_DocumentType(int nullPointer) : DOM_Node(null) { //Note: the assert below has no effect in release build //needs to revisit later assert(nullPointer == 0); }; DOM_DocumentType::DOM_DocumentType(const DOM_DocumentType & other) : DOM_Node(other) { }; DOM_DocumentType::DOM_DocumentType(DocumentTypeImpl *impl) : DOM_Node(impl) { }; DOM_DocumentType::~DOM_DocumentType() { }; DOM_DocumentType & DOM_DocumentType::operator = (const DOM_DocumentType & other) { return (DOM_DocumentType &) DOM_Node::operator = (other); }; DOM_DocumentType & DOM_DocumentType::operator = (const DOM_NullPtr *other) { return (DOM_DocumentType &) DOM_Node::operator = (other); }; DOMString DOM_DocumentType::getName() const { return ((DocumentTypeImpl *)fImpl)->getName().clone(); }; DOM_NamedNodeMap DOM_DocumentType::getEntities() const { return DOM_NamedNodeMap(((DocumentTypeImpl *)fImpl)->getEntities()); }; DOM_NamedNodeMap DOM_DocumentType::getNotations() const { return DOM_NamedNodeMap(((DocumentTypeImpl *)fImpl)->getNotations()); }; //Introduced in DOM Level 2 DOMString DOM_DocumentType::getPublicId() const { return ((DocumentTypeImpl *)fImpl)->getPublicId().clone(); } DOMString DOM_DocumentType::getSystemId() const { return ((DocumentTypeImpl *)fImpl)->getSystemId().clone(); } DOMString DOM_DocumentType::getInternalSubset() const { return ((DocumentTypeImpl *)fImpl)->getInternalSubset().clone(); } XERCES_CPP_NAMESPACE_END
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 113 ] ] ]
9fbecd2564ed83a76178218dfb1bd8a80f9bb8e8
6da3740464cfcc95b095d769974876eb8faf716d
/raytrace/Camera.h
93f6b236af78c07a2c1ca897c4f2c8fab3f7f34e
[]
no_license
thorlund/rendering
8e46b9f11e6c88eb105dfaf9b35ce3c8ca9588f7
648633722d7685f4a2c939595e96d79d34cba344
refs/heads/master
2021-01-24T06:12:27.825294
2011-09-28T09:01:13
2011-09-28T09:01:13
2,473,863
0
0
null
null
null
null
UTF-8
C++
false
false
4,349
h
// 02562 Rendering Framework // Written by Jeppe Revall Frisvad, 2011 // Copyright (c) DTU Informatics 2011 #ifndef CAMERA_H #define CAMERA_H #include <iostream> #include "my_glut.h" #include <optix_world.h> const float NEAR_PLANE = 1.0e-3f; const float FAR_PLANE = 1.0e5f; class Camera { public: Camera(const optix::float3& eye_point = optix::make_float3(0.0f, 0.0f, 0.0f), const optix::float3& lookat_point = optix::make_float3(0.0f, 0.0f, -1.0f), const optix::float3& up_vector = optix::make_float3(0.0f, 1.0f, 0.0f), float focal_distance = 1.0f) { set(eye_point, lookat_point, up_vector, focal_distance); } void set(const optix::float3& eye_point, const optix::float3& lookat_point, const optix::float3& up_vector, float focal_distance) { eye = eye_point; lookat = lookat_point; up = up_vector; focal_dist = focal_distance; float film_width = 1; // Compute image plane normal and basis (ip_normal, ip_xaxis, ip_yaxis) // // Hint: The OptiX math library has a function normalize(v) which returns // the vector v normalized and a function cross(v, w) which returns // the cross product of the vectors v and w. //validate that the cross is done correctly ip_normal = optix::normalize(optix::make_float3(eye.x-lookat.x,eye.y-lookat.y,eye.z-lookat.z)); ip_xaxis = optix::normalize(optix::cross(ip_normal,up)); ip_yaxis = optix::normalize(up); // Compute the field of view in degrees (using the pinhole camera model) // // Hints: (a) Assume that the height and the width of the film is 1. // (b) The inverse tangent function is called atan(x). // (c) The OptiX math library has a constant for 1/pi called M_1_PIf. // (d) The following constant is the field of view that you should // get with the default scene. fov = 360*M_1_PIf*atan(film_width/2*(focal_dist));//53.13f; //fov = 53.13f; std::cout << fov << std::endl; } /// Get direction of viewing ray from image coords. optix::float3 get_ray_dir(const optix::float2& coords) const { // Given view plane coordinates, compute the normalized ray direction // by a change of basis optix::float3 VRP = ip_normal* focal_dist; optix::float3 PRPw = VRP + eye.x*ip_xaxis + eye.y*ip_yaxis + eye.z*ip_normal; optix::float3 pw = VRP + coords.x+eye.x + coords.y+eye.y + eye.z; optix::float3 dirvector = pw - PRPw; optix::float3 ray = PRPw + dirvector; return optix::normalize(ray); } /// Return position of camera. const optix::float3& get_position() const { return eye; } /// Return camera line of sight const optix::float3& get_line_of_sight() const { return ip_normal; } /// Return the ray corresponding to a set of image coords optix::Ray get_ray(const optix::float2& coords) const { // Use the function get_ray_dir(...) to construct a ray starting at // the eye and going through the position in the image plane given // by the image plane coordinates received as argument. // // Hint: You can set the ray type to 0 as the framework currently // does not use different ray types. return optix::Ray(eye,get_ray_dir(coords),0,0); } float get_fov() const { return fov; } float get_focal_dist() const { return focal_dist; } void set_focal_dist(float focal_distance) { set(eye, lookat, up, focal_distance); } // OpenGL void glSetPerspective(unsigned int width, unsigned int height) const { GLdouble aspect = width/static_cast<float>(height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fov, aspect, focal_dist*NEAR_PLANE, FAR_PLANE); glMatrixMode(GL_MODELVIEW); } void glSetCamera() const { gluLookAt(eye.x, eye.y, eye.z, lookat.x, lookat.y, lookat.z, up.x, up.y, up.z); } private: optix::float3 eye, lookat, up; float focal_dist; float fov; // Basis of camera coordinate system (ip - image plane). // The normal is the viewing direction. optix::float3 ip_normal; optix::float3 ip_xaxis; optix::float3 ip_yaxis; }; #endif
[ [ [ 1, 127 ] ] ]
d7b830746e9ff73c0134a2ce178038db236c546b
1033609e705e0b432f8a0760d32befa92c2b9cb5
/trunk/svn.cpp
faa9b082f273babb1a9bfe693cdbe3fdd990526f
[]
no_license
BackupTheBerlios/cb-svn-svn
5b89c2c5445cf7a51575cf08c0eaaf832074b266
6b512f58bbb56fbc186ca26d5c934e1fe83173af
refs/heads/master
2020-04-02T00:14:00.063607
2005-10-26T13:52:08
2005-10-26T13:52:08
40,614,579
0
0
null
null
null
null
UTF-8
C++
false
false
73,063
cpp
/* * This file is part of the Code::Blocks SVN Plugin * Copyright (C) 2005 Thomas Denk * * This program is licensed under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * $HeadURL$ * $Id$ */ #include <wx/wx.h> #include <wx/xrc/xmlres.h> #include <wx/fs_zip.h> #include "svn.h" #include <manager.h> #include <sdk_events.h> #include <editormanager.h> #include <cbproject.h> #include <pipedprocess.h> #include "dialogs.h" #include "toolrunner.h" #ifdef __WIN32__ const bool filenames_are_unix = false; #else const bool filenames_are_unix = true; #endif extern const wxEventType EVT_WX_SUCKS; BEGIN_EVENT_TABLE(SubversionPlugin, cbPlugin) EVT_MENU(ID_MENU_PREFS, SubversionPlugin::Preferences) EVT_MENU(ID_MENU_IMPORT, SubversionPlugin::Import) EVT_MENU(ID_MENU_CHECKOUT, SubversionPlugin::Checkout) EVT_MENU(ID_MENU_USER, SubversionPlugin::SetUser) EVT_MENU(ID_MENU_COMMIT, SubversionPlugin::Commit) EVT_MENU(ID_MENU_UPDATE, SubversionPlugin::Update) EVT_MENU(ID_MENU_UP_P, SubversionPlugin::Update) EVT_MENU(ID_MENU_UP_C, SubversionPlugin::Update) EVT_MENU(ID_MENU_UP_B, SubversionPlugin::Update) EVT_MENU(ID_MENU_UP_REV, SubversionPlugin::Update) EVT_MENU(ID_MENU_D_H, SubversionPlugin::Diff) EVT_MENU(ID_MENU_D_P, SubversionPlugin::Diff) EVT_MENU(ID_MENU_D_C, SubversionPlugin::Diff) EVT_MENU(ID_MENU_D_B, SubversionPlugin::Diff) EVT_MENU(ID_MENU_D_REV, SubversionPlugin::Diff) EVT_MENU(ID_MENU_PATCH, SubversionPlugin::Patch) EVT_MENU(ID_MENU_RESTORE, SubversionPlugin::Update) EVT_MENU(ID_MENU_REVERT, SubversionPlugin::Revert) EVT_MENU(ID_MENU_BRANCH, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_SWITCH, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_MERGE, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_CREATE, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_RELOCATE, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_TSVN_PATCH, SubversionPlugin::OnFatTortoiseFunctionality) EVT_MENU(ID_MENU_CVS_BRANCH, SubversionPlugin::OnFatTortoiseCVSFunctionality) EVT_MENU(ID_MENU_CVS_TAG, SubversionPlugin::OnFatTortoiseCVSFunctionality) EVT_MENU(ID_MENU_CVS_MERGE, SubversionPlugin::OnFatTortoiseCVSFunctionality) EVT_MENU(ID_MENU_CVS_PATCH, SubversionPlugin::OnFatTortoiseCVSFunctionality) EVT_MENU(ID_MENU_CVS_UPDATE, SubversionPlugin::CVSUpdate) EVT_MENU(ID_MENU_CVS_UPDATE_R, SubversionPlugin::CVSUpdate) EVT_MENU(ID_MENU_CVS_UPDATE_D, SubversionPlugin::CVSUpdate) EVT_MENU(ID_MENU_CVS_COMMIT, SubversionPlugin::Commit) EVT_MENU(ID_MENU_CVS_LOGIN, SubversionPlugin::CVSLogin) EVT_MENU(ID_MENU_RESOLVETOOL, SubversionPlugin::EditConflicts) EVT_MENU(ID_MENU_RESOLVED, SubversionPlugin::Resolved) EVT_MENU(ID_MENU_RELEASE, SubversionPlugin::Release) EVT_MENU(ID_MENU_ADD, SubversionPlugin::Add) EVT_MENU(ID_MENU_DELETE, SubversionPlugin::Delete) EVT_MENU(ID_MENU_PROP_IGNORE, SubversionPlugin::PropIgnore) EVT_MENU(ID_MENU_PROP_MIME, SubversionPlugin::PropMime) EVT_MENU(ID_MENU_PROP_EXECUTABLE, SubversionPlugin::PropExec) EVT_MENU(ID_MENU_PROP_NEEDSLOCK, SubversionPlugin::PropNeedsLock) EVT_MENU(ID_MENU_PROP_EXTERNALS, SubversionPlugin::PropExt) EVT_MENU(ID_MENU_LOCK, SubversionPlugin::Lock) EVT_MENU(ID_MENU_UNLOCK, SubversionPlugin::Lock) EVT_MENU(ID_MENU_KW_DATE, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_REVISION, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_AUTHOR, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_HEAD, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_ID, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_SETALL, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_KW_CLEARALL, SubversionPlugin::PropKeywords) EVT_MENU(ID_MENU_PROP_NEW, SubversionPlugin::EditProperty) EVT_TIMER(ID_BLIP, SubversionPlugin::OnTimer) EVT_TIMER(ID_FORCEKILL, SubversionPlugin::ForceKill) SCREW_THIS_MACRO_ABUSE(TRANSACTION_SUCCESS, SubversionPlugin::TransactionSuccess) SCREW_THIS_MACRO_ABUSE(TRANSACTION_FAILURE, SubversionPlugin::TransactionFailure) SCREW_THIS_MACRO_ABUSE(RUN_AGAIN, SubversionPlugin::ReRun) SCREW_THIS_MACRO_ABUSE(RUN_NEXT_IN_QUEUE, SubversionPlugin::ReRun) END_EVENT_TABLE() cbPlugin* GetPlugin() { return new SubversionPlugin; } SubversionPlugin::SubversionPlugin() : cascade_menu(true), auto_add(true), auto_add_only_project(true), auto_delete(false), force_clean(false), require_comments(true), prefill_comments(true), avoid_out_of_date(true), no_ask_revertable(true), never_ask(false), warn_revert(true), full_status_on_startup(false), no_props(false), show_resolved(false), prompt_reload(false), up_after_co(true), svn_ssh(true), cvs_rsh(true), verbose(true), clearTimer(this, ID_BLIP), killTimer(this, ID_FORCEKILL) { wxFileSystem::AddHandler(new wxZipFSHandler); wxXmlResource::Get()->InitAllHandlers(); wxXmlResource::Get()->Load(ConfigManager::Get()->Read("data_path", wxEmptyString) + "/svn.zip#zip:*.xrc"); m_PluginInfo.name = "svn"; m_PluginInfo.title = "Subversion"; { wxString rev("$Revision$"); // let svn:keywords fill in the revision number wxString date("$Date$"); rev.Replace("$", ""); // but make it a bit prettier wxRegEx reg("(\\(.*\\))", wxRE_ICASE); if(reg.Matches(date)) date = reg.GetMatch(date, 1); m_PluginInfo.version = "0.4 " + rev + date; } wxString repo("$HeadURL$"); repo = repo.Mid(repo.Index(' ')+1).BeforeLast('/') + "/"; m_PluginInfo.description = "code::blocks revision control using subversion\n\n" "Subversion is an advanced revision control system intended to replace CVS.\n\n" "If you develop under Windows, do not forget to get TortoiseSVN as well.\n\n" "References:\nhttp://subversion.tigris.org\nhttp://tortoisesvn.tigris.org\n\n" "Subversion access to the cb-svn project is available at:\n" + repo; m_PluginInfo.author = "Thomas Denk"; m_PluginInfo.authorEmail = "[email protected]"; m_PluginInfo.authorWebsite = "http://cb-svn.berlios.de"; m_PluginInfo.thanksTo = wxEmptyString; m_PluginInfo.license = "This program is licensed under the terms of the\n\n" "GNU General Public License Version 2, June 1991\n" "http://www.gnu.org/copyleft/gpl.htm\n\n"; m_PluginInfo.hasConfigure = true; } void SubversionPlugin::OnAttach() { Log::Instance(); // avoid lazy creation ReadConfig(); svn = new SVNRunner(svnbinary); svn->RunBlind(""); // get svn into the file cache asynchronously, as we'll need it soon /* For some reason, if you do not start Tortoise from cmd, then it won't work. I have no idea why, and neither * have the guys developing Tortoise. There is no good reason why it should not work, really. * It is apparently not specifically my code, though. It rather seems to be that wxExecute is broken somehow, * since Tortoise does work fine if you use *anything* except wxExecute() to call it * - including popen(), CreateProcess(), execv(), and system(). * On the other hand, Tortoise does not even run using the original "exec" sample from wxWindows, which we may assume does * implement wxExecute() "correctly". * I would use popen() as the much better alternative (not only does it work, it also reduces code size by 20kB!), * but could not live with a DOS window constantly popping up under Windows. */ tortoise = tortoiseproc.IsEmpty() ? 0 : new TortoiseRunner("cmd /C " + tortoiseproc); cvs = cvsbinary.IsEmpty() ? 0 : new CVSRunner(cvsbinary); tortoisecvs = tortoiseact.IsEmpty() ? 0 : new TortoiseCVSRunner("cmd /C " + tortoiseact); binutils = new ToolRunner(); if(!plink.IsEmpty()) { if(svn_ssh) svn->SetPlink(plink); if(cvs_rsh) cvs->SetPlink(plink); } if(!extdiff.IsEmpty()) { #ifdef __WIN32__ const char* shell = "cmd /C "; #else const char* shell = "bash "; #endif if(extdiff.Contains(".tcl")) diff3 = new DiffRunner("tclsh " + extdiff); else diff3 = extdiff.IsEmpty() ? 0 : new DiffRunner(shell + extdiff); } } void SubversionPlugin::OnRelease(bool appShutDown) { WriteConfig(); Manager::Get()->GetAppWindow()->SetStatusText("Waiting for in-progress transactions to finish..."); Log::Instance()->fg(); if(svn && svn->Running()) svn->Finish(); if(cvs && cvs->Running()) cvs->Finish(); Manager::Get()->GetAppWindow()->SetStatusText(""); TempFile::Cleanup(); } void SubversionPlugin::OnTimer(wxTimerEvent& event) { TempFile::CleanupCheck(); if (Log::lastLogTime < wxGetLocalTime() - 180) { Log::Instance()->Reduce(); clearTimer.Start(360000); } else clearTimer.Start(120000); } void SubversionPlugin::BuildModuleMenu(const ModuleType type, wxMenu* menu, const wxString& arg) { wxMenu* cmenu; if (!menu || !m_IsAttached || type != mtProjectManager) return; menu->AppendSeparator(); if(svn->Running()) // this may be more user-friendly than wxEnableTopLevelWindows(false) { menu->Append(ID_MENU, "Revision Control"); menu->Enable(ID_MENU, false); return; } if(cascade_menu) cmenu = new wxMenu; else cmenu = menu; if (arg.IsEmpty()) { BuildMgrMenu(cmenu); if(menu != cmenu) menu->Append( ID_MENU, "Subversion", cmenu ); return; } wxString selected(GetSelection()); if(!DirUnderVersionControl(selected) && !DirUnderCVS(selected)) { cmenu->Append( ID_MENU_IMPORT, "Import Project (currently unversioned)" ); if(menu != cmenu) menu->Append( ID_MENU, "Subversion", cmenu ); return; } if(cvs && DirUnderCVS(selected)) { Build_CVS_ModuleMenu(cmenu, arg); if (tortoisecvs && IsProject(arg)) { cmenu->AppendSeparator(); cmenu->Append( ID_MENU_CVS_BRANCH, "Branch..." ); cmenu->Append( ID_MENU_CVS_TAG, "Tag..." ); cmenu->Append( ID_MENU_CVS_MERGE, "Merge..." ); cmenu->Append( ID_MENU_CVS_PATCH, "Create patch..." ); } if(menu != cmenu) menu->Append( ID_MENU, "[cvs]", cmenu ); return; } svn->Status(selected); if (IsProject(arg)) BuildProjectMenu(cmenu, arg, selected); else BuildFileMenu(cmenu, arg, selected); if(menu != cmenu) menu->Append( ID_MENU, "Subversion", cmenu ); } void SubversionPlugin::Build_CVS_ModuleMenu(wxMenu* menu, const wxString& arg) { assert(cvs); menu->Append( ID_MENU_CVS_COMMIT, "Commit" ); menu->AppendSeparator(); menu->Append( ID_MENU_CVS_UPDATE, "Update" ); menu->Append( ID_MENU_CVS_UPDATE_R, "Update to revision..." ); menu->Append( ID_MENU_CVS_UPDATE_D, "Update to date..." ); if (!IsProject(arg)) { menu->AppendSeparator(); menu->Append( ID_MENU_PATCH, "Create patch..." ); } else { if(has_tar_or_zip) { menu->AppendSeparator(); menu->Append( ID_MENU_RELEASE, "Export a Release"); } menu->AppendSeparator(); menu->Append( ID_MENU_CVS_LOGIN, "Login" ); } } void SubversionPlugin::BuildMgrMenu(wxMenu* menu) { menu->Append( ID_MENU_CHECKOUT, "Checkout...", "Instantiate a working copy that you can safely modify. This requires a revision controlled project." ); if(!tortoiseproc.IsEmpty()) { menu->AppendSeparator(); menu->Append( ID_MENU_CREATE, "Create repository..." ); } menu->AppendSeparator(); menu->Append( ID_MENU_PREFS, "Preferences..." ); } void SubversionPlugin::BuildFileMenu(wxMenu* menu, wxString name, wxString target) { char status = 0; char pstatus = 0; bool locked = false; int n = svn->std_out.GetCount(); for(int i = 0; i < n; ++i) { if(svn->std_out[i].Mid(7) == target ) { status = (svn->std_out[i])[(size_t)0]; pstatus = (svn->std_out[i])[(size_t)1]; locked = ((svn->std_out[i])[(size_t)5] == 'K'); break; } } if(status == '?') { menu->Append( ID_MENU_ADD, "Add (currently not versioned)" ); return; } if(status == '!') { menu->Append( ID_MENU_RESTORE, "Restore (file is missing)" ); menu->AppendSeparator(); menu->Append( ID_MENU_DELETE, "Remove from version control" ); return; } if(status == 'M' || status == 'A' || status == 'D' || pstatus == 'M') { menu->Append( ID_MENU_COMMIT, "Commit", "Copy your local modifications to a new revision in the repository" ); menu->AppendSeparator(); } if(status == 'C' && (tortoise || diff3)) { menu->Append( ID_MENU_RESOLVETOOL, "Edit file conflicts"); menu->Append( ID_MENU_RESOLVED, "Resolved!"); menu->AppendSeparator(); } if(pstatus == 'C' && status != 'C') // do not allow to resolve properties if files are in conflict! { menu->Append( ID_MENU_RESOLVEPROP, "Resolve property conflicts"); menu->AppendSeparator(); } AppendCommonMenus(menu, target, false, locked); menu->AppendSeparator(); wxMenu *sub = new wxMenu; sub->Append( ID_MENU_D_H, "HEAD" ); sub->Append( ID_MENU_D_P, "PREV" ); sub->Append( ID_MENU_D_C, "COMMITTED" ); sub->Append( ID_MENU_D_B, "BASE" ); sub->Append( ID_MENU_D_REV, "Revision..." ); menu->Append( ID_MENU, "DIFF against...", sub ); if(status == 'M' || status == 'A' || status == 'D' || pstatus == 'M') { menu->AppendSeparator(); menu->Append(ID_MENU_REVERT, "Revert"); } menu->AppendSeparator(); menu->Append( ID_MENU_DELETE, "Delete", "Remove from project, delete, and schedule for deletion from repository. Can be reverted." ); } void SubversionPlugin::BuildProjectMenu(wxMenu* menu, wxString name, wxString target) { int fm = 0; int fa = 0; int fd = 0; int pm = 0; int cf = 0; int ms = 0; int lk = 0; int n = svn->std_out.GetCount(); for(int i = 0; i < n; ++i) { if((svn->std_out[i])[(size_t)0] == 'M' ) ++fm; if((svn->std_out[i])[(size_t)1] == 'M' ) ++pm; if((svn->std_out[i])[(size_t)0] == 'A' ) ++fa; if((svn->std_out[i])[(size_t)0] == 'D' ) ++fd; if((svn->std_out[i])[(size_t)0] == 'C' || (svn->std_out[i])[(size_t)1] == 'C') ++cf; if((svn->std_out[i])[(size_t)0] == '!') ++ms; if((svn->std_out[i])[(size_t)5] == 'K') ++lk; } if(cf) { if(tortoise || diff3) { wxString comstr("Edit conflicts ("); comstr << cf << " file" << (cf == 1 ? "" : "s") << ")"; menu->Append( ID_MENU_RESOLVETOOL, comstr ); menu->Append( ID_MENU_RESOLVED, "Resolved!"); menu->AppendSeparator(); } menu->Append( ID_MENU_REVERT, "Revert..." ); menu->AppendSeparator(); } else if(fm || pm || fa || fd) { wxString comstr("Commit ("); if(fm) comstr << fm << " file" << (fm == 1 ? "" : "s"); if(pm) comstr << (fm ? ", " : "") << pm << (pm == 1 ? " property" : " properties"); if(fm || pm) comstr << " modified"; if(fa) comstr << (comstr.IsEmpty() ? "" : ", ") << fa << " file" << (fa == 1 ? "" : "s") << " added"; if(fd) comstr << (comstr.IsEmpty() ? "" : ", ") << fd << " file" << (fd == 1 ? "" : "s") << " deleted"; if(ms) comstr << (comstr.IsEmpty() ? "" : ", ") << ms << " file" << (ms == 1 ? "" : "s") << " missing"; if(lk) comstr << (comstr.IsEmpty() ? "" : ", ") << lk << " lock" << (lk == 1 ? "" : "s") << " held"; comstr << ")"; menu->Append( ID_MENU_COMMIT, comstr ); menu->AppendSeparator(); menu->Append( ID_MENU_REVERT, "Revert..." ); menu->AppendSeparator(); } AppendCommonMenus(menu, target, true, false); if(! tortoiseproc.IsEmpty()) { menu->AppendSeparator(); menu->Append( ID_MENU_BRANCH, "Branch..." ); menu->Append( ID_MENU_SWITCH, "Switch..." ); menu->Append( ID_MENU_MERGE, "Merge..." ); menu->Append( ID_MENU_RELOCATE, "Relocate..." ); } menu->AppendSeparator(); menu->Append( ID_MENU_USER, "Set User...", "Set (or change) username and password for the next transaction."); } void SubversionPlugin::AppendCommonMenus(wxMenu *menu, wxString target, bool isProject, bool isLocked) { menu->Append( ID_MENU_UPDATE, "Update (HEAD)", "Update (overwrite) your local copy with a file from the repository" ); wxMenu *sub = new wxMenu; sub->Append( ID_MENU_UP_P, "PREV" ); sub->Append( ID_MENU_UP_C, "COMMITTED" ); sub->Append( ID_MENU_UP_B, "BASE" ); sub->Append( ID_MENU_UP_REV, "Revision..." ); menu->Append( ID_MENU, "Update to...", sub ); if(!fileProperties.empty()) { IdToStringHash::iterator it; for( it = fileProperties.begin(); it != fileProperties.end(); ++it ) // remove all the old rubbish Disconnect(it->first); // from the event tables fileProperties.clear(); } if(no_props) return; wxArrayString props = svn->GetPropertyList(target); bool has_ignore = false; bool has_keywords = false; bool has_exec = false; bool has_mime = false; bool has_externals = false; bool has_needslock = false; int n = props.GetCount(); for(int i = 0; i < n; ++i) { has_ignore |= (props[i] == "svn:ignore"); has_keywords |= (props[i] == "svn:keywords"); has_exec |= (props[i] == "svn:executable"); has_mime |= (props[i] == "svn:mime-type"); has_externals |= (props[i] == "svn:externals"); has_needslock |= (props[i] == "svn:needs-lock"); } menu->AppendSeparator(); wxMenu* keywords = new wxMenu; wxMenu* svnprops = new wxMenu; if(isProject) { keywords->Append( ID_MENU_KW_SETALL, "Set all" ); keywords->Append( ID_MENU_KW_CLEARALL, "Clear all" ); svnprops->Append( ID_MENU, "Global->svn:keywords", keywords ); } else { keywords->Append( ID_MENU_KW_DATE, "Date", "", wxITEM_CHECK ); keywords->Append( ID_MENU_KW_REVISION, "Revision", "", wxITEM_CHECK ); keywords->Append( ID_MENU_KW_AUTHOR, "Author", "", wxITEM_CHECK ); keywords->Append( ID_MENU_KW_HEAD, "HeadURL", "", wxITEM_CHECK ); keywords->Append( ID_MENU_KW_ID, "Id", "", wxITEM_CHECK ); svnprops->Append( ID_MENU, "keywords", keywords ); } if(isProject) { svnprops->Append( ID_MENU_PROP_IGNORE, has_ignore ? "svn:ignore" : "svn:ignore [none]" ); svnprops->Append( ID_MENU_PROP_EXTERNALS, has_externals ? "svn:externals" : "svn:externals [none]" ); } else { wxFileName fn(target); fn.MakeRelativeTo(GetSelectionsProject()); wxString f = fn.GetPath().IsEmpty() ? "Global->" : fn.GetPath()+"->"; svnprops->Append( ID_MENU_PROP_EXECUTABLE, "executable", "", wxITEM_CHECK ); svnprops->Append( ID_MENU_PROP_NEEDSLOCK, "needs lock", "", wxITEM_CHECK ); svnprops->Append( ID_MENU_PROP_MIME, has_mime ? "mime-type" : "mime-type [default]" ); svnprops->Check(ID_MENU_PROP_EXECUTABLE, has_exec); svnprops->Check(ID_MENU_PROP_NEEDSLOCK, has_needslock); svnprops->AppendSeparator(); svnprops->Append( ID_MENU_PROP_IGNORE, has_ignore ? f+"svn:ignore" : f+"svn:ignore [none]" ); svnprops->Append( ID_MENU_PROP_EXTERNALS, has_externals ? f+"svn:externals" : f+"svn:externals [none]" ); } if(has_keywords) { wxString kw = svn->PropGet(target, "svn:keywords"); keywords->Check(ID_MENU_KW_DATE, kw.Contains("Date")); keywords->Check(ID_MENU_KW_REVISION, kw.Contains("Revision")); keywords->Check(ID_MENU_KW_AUTHOR, kw.Contains("Author")); keywords->Check(ID_MENU_KW_HEAD, kw.Contains("HeadURL")); keywords->Check(ID_MENU_KW_ID, kw.Contains("Id")); } wxMenu* propsub = new wxMenu; propsub->Append( ID_MENU, "svn", svnprops ); propsub->Append( ID_MENU_PROP_NEW, "New Property"); props.Remove("svn:ignore"); props.Remove("svn:keywords"); props.Remove("svn:executable"); props.Remove("svn:mime-type"); props.Remove("svn:externals"); if(props.Count()) { propsub->AppendSeparator(); unsigned int tid ; for(unsigned int i = 0; i < props.Count(); ++i) { tid = wxNewId(); propsub->Append(tid, props[i]); fileProperties[tid] = props[i]; Connect(tid, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) &SubversionPlugin::EditProperty); } } menu->Append( ID_MENU, "Properties...", propsub); menu->AppendSeparator(); if(isLocked) { menu->Append(ID_MENU_UNLOCK, "Release Lock"); menu->AppendSeparator(); } else if(has_needslock) { menu->Append(ID_MENU_LOCK, "Acquire Lock"); menu->AppendSeparator(); } if(has_tar_or_zip && isProject) { menu->Append( ID_MENU_RELEASE, "Export a Release"); menu->AppendSeparator(); } menu->Append( isProject ? ID_MENU_TSVN_PATCH : ID_MENU_PATCH, "Create Patch"); } void SubversionPlugin::Update(wxCommandEvent& event) { wxString revision("HEAD"); wxString selected(GetSelection()); switch(event.GetId()) { case ID_MENU_UPDATE: break; case ID_MENU_UP_P: revision = "PREV"; break; case ID_MENU_UP_C: revision = "COMMITTED"; break; case ID_MENU_UP_B: revision = "BASE"; break; case ID_MENU_UP_REV: { wxTextEntryDialog d(NULL, "Please enter:\n" "- a revision number,\n" "- a revision keyword (HEAD, COMMITTED, PREV, BASE),\n" "- a revision date, time, or date-time in curly braces.\n\n" "Examples of valid revision dates are:\n" "{2002-02-17} {15:30} {2002-02-17 15:30} {20020217T1530}", "Update to revision..."); d.ShowModal(); revision = d.GetValue(); if(revision == wxEmptyString) return; } break; } DisableCheckExternals(); svn->Update(selected, revision); } void SubversionPlugin::CVSUpdate(wxCommandEvent& event) { wxString revision; wxString date; wxString selected(GetSelection()); if(event.GetId() == ID_MENU_CVS_UPDATE_R) { wxTextEntryDialog d(NULL, "Please enter a revision tag:", "Update to revision..."); d.ShowModal(); revision = d.GetValue(); if(revision == wxEmptyString) return; } if(event.GetId() == ID_MENU_CVS_UPDATE_D) { wxTextEntryDialog d(NULL, "Please enter a revision date.\n" "meta dates such as 'yesterday' or 'last week' are allowed.", "Update to date..."); d.ShowModal(); date = d.GetValue(); if(date == wxEmptyString) return; } cvs->Update(selected, revision, date); } void SubversionPlugin::ReloadEditors(const wxArrayString& filenames) { if(prompt_reload && wxMessageDialog(Manager::Get()->GetAppWindow(), "Do you want to replace the editor's out-of-date versions with their respective updated versions?", "Reload editor", wxYES_NO).ShowModal() == wxID_NO) return; EditorManager *em = Manager::Get()->GetEditorManager(); assert(em); for(unsigned int i = 0; i < filenames.Count(); ++i) if(cbEditor *e = em->GetBuiltinEditor(filenames[i])) { //Log::Instance()->Add("reloading " + filenames[i]); e->Reload(); } } void SubversionPlugin::ReOpenEditor(const wxString& filename) { EditorManager *em = Manager::Get()->GetEditorManager(); assert(em); if(cbEditor *e = em->GetBuiltinEditor(filename)) { e->Close(); em->Open(filename); } } void SubversionPlugin::Diff(wxCommandEvent& event) { wxString revision("HEAD"); wxString selected(GetSelection()); switch(event.GetId()) { case ID_MENU_D_P: revision = "PREV"; break; case ID_MENU_D_C: revision = "COMMITTED"; break; case ID_MENU_D_B: revision = "BASE"; break; case ID_MENU_D_REV: { wxTextEntryDialog d(NULL, "Please enter:\n" "- a revision number,\n" "- a revision keyword (HEAD, COMMITTED, PREV, BASE),\n" "- a revision date, time, or date-time in curly braces.\n\n" "Examples of valid revision dates are:\n" "{2002-02-17} {15:30} {2002-02-17 15:30} {20020217T1530}", "Compare to revision..."); d.ShowModal(); revision = d.GetValue(); if(revision == wxEmptyString) return; } break; } svn->ExportToTemp(selected, revision, "diff"); } void SubversionPlugin::Patch(wxCommandEvent& event) { wxString selected(GetSelection()); wxString fn((selected.IsEmpty() ? "patchfile" : selected) + ".patch"); patchFileName = wxFileSelector("Save patch file as...", "", fn, "*.patch", "patch files (*.patch)|*.patch|text files (*.txt)|*.txt|all files (*.*)|*.*", wxSAVE); if(!patchFileName.IsEmpty()) if(DirUnderCVS(selected)) cvs->Diff(selected); else svn->Diff(selected, "HEAD"); } void SubversionPlugin::Release(wxCommandEvent& event) { assert(has_tar_or_zip); wxString selected(GetSelection()); wxString types; if(!tarbin.IsEmpty()) { if(!bzip2bin.IsEmpty()) types << "|bzip compressed tar (*.tar.bz2)|*.tar.bz2"; types << "|gzip compressed tar (*.tar.gz)|*.tar.gz"; types << "|tar file (*.tar)|*.tar"; } if(!zipbin.IsEmpty()) types << "|zip compressed file (*.zip)|*.zip"; types = types.Mid(1); patchFileName = wxFileSelector("Export release as...", "", "", "*.tar.bz2", types, wxSAVE); if(patchFileName.IsEmpty()) return; wxString tempDir = TempFile::TempFolder() + "cbsvn-" << wxGetLocalTime(); // de-moronize wxFileSelector if(patchFileName.Contains(".bz2") && !patchFileName.Contains(".tar.")) patchFileName.Replace(".bz2", ".tar.bz2"); if(patchFileName.Contains(".gz") && !patchFileName.Contains(".tar.")) patchFileName.Replace(".gz", ".tar.gz"); wxTextEntryDialog d(NULL, "Please enter the desired revision to export from:\n", "Export a Release", "HEAD"); d.ShowModal(); wxString rev = d.GetValue(); if(rev.IsEmpty()) return; if(DirUnderCVS(selected)) { wxString repo; wxString module; if(TamperWithCVS(repo, module)) { tempDir = wxString("cbsvn-") << wxGetLocalTime(); cvs->Export(repo, module, tempDir, TempFile::TempFolder(), rev); } else { Log::Instance()->Red("Could not successfully tamper with CVS. Unable to determine repository."); } return; } svn->Export(selected, tempDir, rev, "release"); } void SubversionPlugin::Lock(wxCommandEvent& event) { wxString selected(GetSelection()); if(wxFileName::DirExists(selected)) return; // no locking of directories if(event.GetId() == ID_MENU_LOCK) svn->Lock(selected); else svn->UnLock(selected); } void SubversionPlugin::Commit(wxCommandEvent& event) { wxString selected(GetSelection()); if(DirUnderCVS(selected)) { wxArrayString files; CommitDialog d(Manager::Get()->GetAppWindow(), files, require_comments); d.Centre(); if(d.ShowModal() == wxID_OK) cvs->Commit(selected, d.comment); return; } svn->Status(selected); wxArrayString files; wxArrayString toAdd; wxArrayString missing = ExtractFilesWithStatus('?'); if(auto_add) files = wxArrayString(); else files = missing; CommitDialog d(Manager::Get()->GetAppWindow(), files, require_comments); if(prefill_comments) { wxArrayString modified = ExtractFilesWithStatus('M'); wxString prefill; for(unsigned int i = 0; i < modified.Count(); ++i) { modified[i] = wxFileName(modified[i]).GetFullName(); prefill << modified[i] << " : \n"; } d.SetComment(prefill); } d.Centre(); if(d.ShowModal() == wxID_OK) { if(auto_delete) { missing = ExtractFilesWithStatus('!'); wxString concat; for(unsigned int i = 0; i < missing.Count(); ++i) concat << " \"" << missing[i] << "\" "; concat = concat.Mid(2, concat.Length()-4); if(!concat.IsEmpty()) svn->Delete(concat); } if(auto_add) { if(auto_add_only_project) { ProjectsArray* array = Manager::Get()->GetProjectManager()->GetProjects(); if (array) { unsigned int n = array->GetCount(); for (unsigned int k = 0; k < missing.Count(); ++k) for (unsigned int i = 0; i < n; ++i) { cbProject* proj = array->Item(i); if (proj && proj->GetFileByFilename(missing[k], false, filenames_are_unix)) { toAdd.Add(missing[k]); break; } } } } else toAdd = missing; } else toAdd = d.finalList; wxString concat; for(unsigned int i = 0; i < toAdd.Count(); ++i) // better call svn with 637 paramters than run svn 637 times... concat << " \"" << toAdd[i] << "\" "; concat = concat.Mid(2, concat.Length()-4); // svn->Add() wraps in double quotes already if(!concat.IsEmpty()) svn->Add(concat); DisableCheckExternals(); svn->Commit(selected, d.comment, avoid_out_of_date); } } void SubversionPlugin::Checkout(wxCommandEvent& event) { CheckoutDialog d(Manager::Get()->GetAppWindow(), repoHistory, repoHistoryCVS, defaultCheckoutDir); d.Centre(); if(d.ShowModal() == wxID_OK) { if(d.use_cvs_instead) { if(!d.cvs_pass.IsEmpty()) cvs->Login(d.cvs_proto, d.cvs_repo, d.cvs_user, d.cvs_pass); if(d.cvs_workingdir.IsEmpty()) d.cvs_workingdir = GetCheckoutDir(); repoHistoryCVS.Add(d.cvs_repo); cvs->Checkout(d.cvs_proto, d.cvs_repo, d.cvs_module, d.cvs_workingdir, d.cvs_user, d.cvs_revision); request_autoopen = d.cvs_auto_open; return; } if(!d.username.IsEmpty()) svn->SetPassword(d.username, d.password); if(d.checkoutDir.IsEmpty()) d.checkoutDir = GetCheckoutDir(); request_autoopen = d.autoOpen; svn->Checkout(d.repoURL, d.checkoutDir, (d.revision.IsEmpty() ? wxString("HEAD") : d.revision), d.noExternals ); repoHistory.Add(d.repoURL); } } void SubversionPlugin::AutoOpenProjects(const wxString& rootdir, bool recursive, bool others) { ProjectManager *pmgr = Manager::Get()->GetProjectManager(); wxArrayString dirs; wxString f; dirs.Add(rootdir); if(recursive) { f = wxFindFirstFile(rootdir + "/", wxDIR); while ( !f.IsEmpty() ) { dirs.Add(f); f = wxFindNextFile(); } } for(unsigned int i = 0; i < dirs.Count(); ++i) { f = wxFindFirstFile(dirs[i] + "/*.cbp"); while ( !f.IsEmpty() ) { if(verbose) Log::Instance()->Add("opening " + f); pmgr->LoadProject(f); f = wxFindNextFile(); } if(others) { f = wxFindFirstFile(dirs[i] + "/*.dev"); while ( !f.IsEmpty() ) { if(verbose) Log::Instance()->Add("importing " + f); pmgr->LoadProject(f); f = wxFindNextFile(); } f = wxFindFirstFile(dirs[i] + "/*.dsp"); while ( !f.IsEmpty() ) { if(verbose) Log::Instance()->Add("importing " + f); pmgr->LoadProject(f); f = wxFindNextFile(); } } } } void SubversionPlugin::Import(wxCommandEvent& event) { ImportDialog d(Manager::Get()->GetAppWindow(), repoHistory, GetSelectionsProject(), require_comments); d.Centre(); if(d.ShowModal() == wxID_OK) { if(!d.username.IsEmpty()) svn->SetPassword(d.username, d.password); wxString target(defaultCheckoutDir + "/" +DirName(d.importDir)); request_autoopen = true; repoHistory.Add(d.repoURL); cbProject *p = GetCBProject(); if(p) { ProjectManager *pmgr = Manager::Get()->GetProjectManager(); pmgr->CloseProject(p); } svn->Import(d.repoURL, d.importDir, d.comment); svn->Checkout(d.repoURL, target, "HEAD"); if(!d.keywords.IsEmpty()) svn->PropSet(target, "svn:keywords", d.keywords, true); if(!d.ignore.IsEmpty()) svn->PropSet(target, "svn:ignore", d.ignore, true); if(!d.externals.IsEmpty()) svn->PropSet(target, "svn:externals", d.externals, true); if(!d.copy.IsEmpty()) svn->PropSet(target, "copyright", d.copy, true); if(!d.home.IsEmpty()) svn->PropSet(target, "home", d.home, true); if(!d.docs.IsEmpty()) svn->PropSet(target, "documentation", d.docs, true); if(!d.contact.IsEmpty()) svn->PropSet(target, "contact", d.contact, true); if(!d.arch.IsEmpty()) svn->PropSet(target, "architecture", d.arch, true); } } void SubversionPlugin::SetUser(wxCommandEvent& event) { PasswordDialog p(Manager::Get()->GetAppWindow()); p.Centre(); if(p.ShowModal() == wxID_OK) { svn->SetPassword(p.username, p.password); svn->Status(GetSelection(), true); } } void SubversionPlugin::CVSLogin(wxCommandEvent& event) { PasswordDialog p(Manager::Get()->GetAppWindow()); p.Centre(); if(p.ShowModal() == wxID_OK) { //cvs->Login(p.username, p.password); } } void SubversionPlugin::Revert(wxCommandEvent& event) { wxString target(GetSelection()); svn->Status(target); wxArrayString mods; wxArrayString files; int n = svn->std_out.Count(); for(int i = 0; i < n; ++i) { if(svn->std_out[i][(size_t)0] == '?') continue; wxString f(LocalPath(svn->std_out[i].Mid(7))); if(f.StartsWith("..")) f = "[project]"; wxString s; if(svn->std_out[i][(size_t)0] == '!') s << "missing"; if(svn->std_out[i][(size_t)0] == 'D') s << "deleted"; if(svn->std_out[i][(size_t)0] == 'A') s << (s.Length()? ", " : "") << "added"; if(svn->std_out[i][(size_t)0] == 'M') s << (s.Length()? ", " : "") << "modified"; if(svn->std_out[i][(size_t)0] == 'C') s << (s.Length()? ", " : "") << "modified and in conflict"; if(svn->std_out[i][(size_t)1] == 'M') s << (s.Length()? ", " : "") << "has property changes"; s = f + " (" + s + ")"; if(svn->std_out[i].Length()) { mods.Add(s); files.Add(svn->std_out[i].Mid(7)); } } if(::wxDirExists(target)) // seems like we have a project folder here { RevertDialog d(Manager::Get()->GetAppWindow(), mods, files); d.Centre(); if(d.ShowModal() == wxID_OK) { wxString toRevert; for(unsigned int i = 0; i < d.finalList.Count(); i++) toRevert << " \"" + d.finalList[i] + "\" "; DisableCheckExternals(); svn->Revert(toRevert.Mid(2, toRevert.Length()-4)); } } else { wxString localMods; if(warn_revert && ParseStatusOutputForFile(target) == 'M') localMods = "\nWARNING:\n\nThis file has local modifications which you will lose if you revert it.\n\n\n"; if(never_ask || wxMessageDialog(Manager::Get()->GetAppWindow(), localMods + "Do you want to revert the file " + target + "?", (localMods.IsEmpty() ? "Revert" : "Revert over Modifications"), wxYES_NO).ShowModal() == wxID_YES) { DisableCheckExternals(); svn->Revert(target); } } } char SubversionPlugin::ParseStatusOutputForFile(const wxString& what) { int n = svn->std_out.Count(); for(int i = 0; i < n; ++i) { if(svn->std_out[i].Contains(what)) { return (svn->std_out[i])[(size_t)0]; } } return 0; } /* * We have to discriminate between lines like * U somefile.h * UU anotherfile.cpp * and * Update failed (details follow) * * Luckily, svn status codes are *never* lowercase, so we can use "std_out[i])[(size_t)1] < 'a'" as a condition * A regex would certainly do even better, but a regex is 30-40 times slower, too. * We don't know in advance how many files there are in a transaction, it could very easily be 200 (or 5000?) * I'd rather avoid running wxRegex.Matches() 200 times in a loop unless I have to. */ void SubversionPlugin::ExtractFilesWithStatus(const char what, wxArrayString& ret, unsigned int pos) { wxString t; for(unsigned int i = 0; i < svn->std_out.GetCount(); ++i) if( (svn->std_out[i])[(size_t)pos] == what && (svn->std_out[i])[(size_t)1] < 'a') ret.Add(svn->std_out[i].Mid(5).Strip(wxString::both)); } wxArrayString SubversionPlugin::ExtractFilesWithStatus(const char what, unsigned int pos) { wxArrayString ret; ExtractFilesWithStatus(what, ret, pos); return ret; } void SubversionPlugin::Preferences(wxCommandEvent& event) { PreferencesDialog d(Manager::Get()->GetAppWindow()); d.Centre(); XRCCTRL(d, "svn binary path", wxTextCtrl)->SetValue(wxFileName(svnbinary).GetFullPath()); XRCCTRL(d, "cvs binary path", wxTextCtrl)->SetValue(wxFileName(cvsbinary).GetFullPath()); XRCCTRL(d, "std checkout", wxTextCtrl)->SetValue(defaultCheckoutDir); XRCCTRL(d, "auto add", wxCheckBox)->SetValue(auto_add); XRCCTRL(d, "autoadd only project", wxCheckBox)->SetValue(auto_add_only_project); XRCCTRL(d, "auto remove missing", wxCheckBox)->SetValue(auto_delete); XRCCTRL(d, "auto merge", wxCheckBox)->SetValue(avoid_out_of_date); XRCCTRL(d, "no emtpy comments", wxCheckBox)->SetValue(require_comments); XRCCTRL(d, "prefill comments", wxCheckBox)->SetValue(prefill_comments); XRCCTRL(d, "forceclean", wxCheckBox)->SetValue(force_clean); XRCCTRL(d, "no confirm revertable", wxCheckBox)->SetValue(no_ask_revertable); XRCCTRL(d, "warn revert", wxCheckBox)->SetValue(warn_revert); XRCCTRL(d, "never ask", wxCheckBox)->SetValue(never_ask); XRCCTRL(d, "full status", wxCheckBox)->SetValue(full_status_on_startup); XRCCTRL(d, "no props", wxCheckBox)->SetValue(no_props); XRCCTRL(d, "show resolved", wxCheckBox)->SetValue(show_resolved); XRCCTRL(d, "cascade", wxCheckBox)->SetValue(cascade_menu); XRCCTRL(d, "prompt reload", wxCheckBox)->SetValue(prompt_reload); XRCCTRL(d, "up after co", wxCheckBox)->SetValue(up_after_co); XRCCTRL(d, "svn_ssh", wxCheckBox)->SetValue(svn_ssh); XRCCTRL(d, "cvs_rsh", wxCheckBox)->SetValue(cvs_rsh); if(plink.IsEmpty()) { XRCCTRL(d, "svn_ssh", wxCheckBox)->Enable(false); XRCCTRL(d, "cvs_rsh", wxCheckBox)->Enable(false); } d.RadioToggle(event); if(d.ShowModal() == wxID_OK) { svnbinary = XRCCTRL(d, "svn binary path", wxTextCtrl)->GetValue(); cvsbinary = XRCCTRL(d, "cvs binary path", wxTextCtrl)->GetValue(); defaultCheckoutDir = XRCCTRL(d, "std checkout", wxTextCtrl)->GetValue(); if(!svnbinary.IsEmpty()) if(!svn) svn = new SVNRunner(svnbinary); if(!cvsbinary.IsEmpty()) if(!cvs) cvs = new CVSRunner(cvsbinary); svn->SetExecutable(svnbinary); cvs->SetExecutable(cvsbinary); auto_add = XRCCTRL(d, "auto add", wxCheckBox)->GetValue(); auto_add_only_project = XRCCTRL(d, "autoadd only project", wxCheckBox)->GetValue(); auto_delete = XRCCTRL(d, "auto remove missing", wxCheckBox)->GetValue(); avoid_out_of_date = XRCCTRL(d, "auto merge", wxCheckBox)->GetValue(); require_comments = XRCCTRL(d, "no emtpy comments", wxCheckBox)->GetValue(); prefill_comments = XRCCTRL(d, "prefill comments", wxCheckBox)->GetValue(); force_clean = XRCCTRL(d, "forceclean", wxCheckBox)->GetValue(); no_ask_revertable = XRCCTRL(d, "no confirm revertable", wxCheckBox)->GetValue(); warn_revert = XRCCTRL(d, "warn revert", wxCheckBox)->GetValue(); never_ask = XRCCTRL(d, "never ask", wxCheckBox)->GetValue(); full_status_on_startup = XRCCTRL(d, "full status", wxCheckBox)->GetValue(); no_props = XRCCTRL(d, "no props", wxCheckBox)->GetValue(); show_resolved = XRCCTRL(d, "show resolved", wxCheckBox)->GetValue(); cascade_menu = XRCCTRL(d, "cascade", wxCheckBox)->GetValue(); prompt_reload = XRCCTRL(d, "prompt reload", wxCheckBox)->GetValue(); up_after_co = XRCCTRL(d, "up after co", wxCheckBox)->GetValue(); svn_ssh = XRCCTRL(d, "svn_ssh", wxCheckBox)->GetValue(); cvs_rsh = XRCCTRL(d, "cvs_rsh", wxCheckBox)->GetValue(); if(!plink.IsEmpty()) { svn->SetPlink(svn_ssh ? plink : ""); cvs->SetPlink(cvs_rsh ? plink : ""); } WriteConfig(); } } void SubversionPlugin::ReadConfig() { wxConfigBase* c = ConfigManager::Get(); svnbinary = c->Read("/svn/svnbinary"); cvsbinary = c->Read("/svn/cvsbinary"); tarbin = c->Read("/svn/tarbinary"); bzip2bin = c->Read("/svn/bzip2binary"); zipbin = c->Read("/svn/zipbinary"); defaultCheckoutDir = c->Read("/svn/defaultCheckoutDir"); c->Read("/svn/auto_add", &auto_add); c->Read("/svn/auto_add_only_project", &auto_add_only_project); c->Read("/svn/auto_delete", &auto_delete); c->Read("/svn/avoid_out_of_date", &avoid_out_of_date); c->Read("/svn/require_comments", &require_comments); c->Read("/svn/prefill_comments", &prefill_comments); c->Read("/svn/force_clean", &force_clean); c->Read("/svn/no_ask_revertable", &no_ask_revertable); c->Read("/svn/warn_revert", &warn_revert); c->Read("/svn/never_ask", &never_ask); c->Read("/svn/full_status_on_startup", &full_status_on_startup); c->Read("/svn/no_props", &no_props); c->Read("/svn/show_resolved", &show_resolved); c->Read("/svn/cascade_menu", &cascade_menu); c->Read("/svn/prompt_reload", &prompt_reload); c->Read("/svn/up_after_co", &up_after_co); c->Read("/svn/svn_ssh", &svn_ssh); c->Read("/svn/cvs_rsh", &cvs_rsh); c->Read("/svn/verbose", &verbose); TamperWithWindowsRegistry(); SearchBinaries(); { wxString ht("/svn/repoHist"); wxString val; for(unsigned int i = 0; i < 16; ++i) { wxString h = ht; val = c->Read(h<<i); if(!val.IsEmpty()) repoHistory.Add(val); } } { wxString ht("/svn/repoHistCVS"); wxString val; for(unsigned int i = 0; i < 16; ++i) { wxString h = ht; val = c->Read(h<<i); if(!val.IsEmpty()) repoHistoryCVS.Add(val); } } } void SubversionPlugin::WriteConfig() { wxConfigBase* c = ConfigManager::Get(); c->Write("/svn/svnbinary", svnbinary); c->Write("/svn/cvsbinary", cvsbinary); c->Write("/svn/tarbinary", tarbin); c->Write("/svn/bzip2binary", bzip2bin); c->Write("/svn/zipbinary", zipbin); c->Write("/svn/defaultCheckoutDir", defaultCheckoutDir); c->Write("/svn/auto_add", auto_add); c->Write("/svn/auto_add_only_project", auto_add_only_project); c->Write("/svn/auto_delete", auto_delete); c->Write("/svn/avoid_out_of_date", avoid_out_of_date); c->Write("/svn/require_comments", require_comments); c->Write("/svn/prefill_comments", prefill_comments); c->Write("/svn/force_clean", force_clean); c->Write("/svn/no_ask_revertable", no_ask_revertable); c->Write("/svn/warn_revert", warn_revert); c->Write("/svn/never_ask", never_ask); c->Write("/svn/full_status_on_startup", full_status_on_startup); c->Write("/svn/no_props", no_props); c->Write("/svn/show_resolved", show_resolved); c->Write("/svn/cascade_menu", cascade_menu); c->Write("/svn/prompt_reload", prompt_reload); c->Write("/svn/up_after_co", up_after_co); c->Write("/svn/svn_ssh", svn_ssh); c->Write("/svn/cvs_rsh", cvs_rsh); c->Write("/svn/verbose", verbose); { unsigned int count = repoHistory.Count() < 16 ? repoHistory.Count() : 16; wxString ht("/svn/repoHist"); for(unsigned int i = 0; i < count; ++i) { wxString h = ht; c->Write(h<<i, repoHistory[i]); } } { unsigned int count = repoHistoryCVS.Count() < 16 ? repoHistoryCVS.Count() : 16; wxString ht("/svn/repoHistCVS"); for(unsigned int i = 0; i < count; ++i) { wxString h = ht; c->Write(h<<i, repoHistoryCVS[i]); } } } void SubversionPlugin::Add(wxCommandEvent& event) { svn->Add(GetSelection()); } void SubversionPlugin::Delete(wxCommandEvent& event) { wxString selected(GetSelection()); if(never_ask) svn->Force(); if(never_ask || no_ask_revertable || wxMessageDialog(Manager::Get()->GetAppWindow(), "Issue a 'svn delete' on the file " + selected + "?\n\nThis will not only delete the from disk, but also remove it from revision control.", "Delete File", wxYES_NO).ShowModal() == wxID_YES) { svn->Delete(selected); if(!svn->std_err.Count()) { wxTreeCtrl* tree = Manager::Get()->GetProjectManager()->GetTree(); FileTreeData* ftd = (FileTreeData*) tree->GetItemData(tree->GetSelection()); cbProject *p = ftd->GetProject(); p->RemoveFile(ftd->GetFileIndex()); Manager::Get()->GetProjectManager()->RebuildTree(); } else { Log::Instance()->Add("Warning: delete failed."); svn->DumpErrors(); } } } void SubversionPlugin::PropIgnore(wxCommandEvent& event) { wxString target(GetSelection()); if(!::wxDirExists(target)) // svn:ignore only valid on directories target = wxFileName(target).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR); wxString value = svn->PropGet(target, "svn:ignore"); IgnoreEditorDialog d(Manager::Get()->GetAppWindow(), target, value, target); d.Centre(); wxString localPath = LocalPath(target); d.SetTitle("svn:ignore" + (localPath.IsEmpty() ? "" : " on " + localPath)); if(d.ShowModal() == wxID_OK) { svn->PropSet(target, "svn:ignore", d.value, false); } } void SubversionPlugin::PropMime(wxCommandEvent& event) { wxString target = GetSelection(); wxString mime = svn->PropGet(target, "svn:mime-type"); wxTextEntryDialog d(Manager::Get()->GetAppWindow(), "Please provide a mime-type for the file " + LocalPath(target) + "\n or leave empty to use the default type.\n\n" "Note that a mime type outside text/* will effectively disable all merging capabilities.", "svn:mime-type on " + LocalPath(target), mime); if(d.ShowModal() == wxID_OK) { mime = d.GetValue(); if(mime.IsEmpty()) svn->PropDel(target, "svn:mime-type"); else svn->PropSet(target, "svn:mime-type", mime, false); } } void SubversionPlugin::PropExec(wxCommandEvent& event) { if(event.IsChecked()) svn->PropDel(GetSelection(), "svn:executable"); else svn->PropSet(GetSelection(), "svn:executable", "", false); } void SubversionPlugin::PropNeedsLock(wxCommandEvent& event) { if(event.IsChecked()) svn->PropDel(GetSelection(), "svn:needs-lock"); else svn->PropSet(GetSelection(), "svn:needs-lock", "", false); } void SubversionPlugin::PropExt(wxCommandEvent& event) { //FIXME: svn:externals deserves its own dialog wxString file(GetSelection()); if(!::wxDirExists(file)) file = wxFileName(file).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR); wxString value(svn->PropGet(file, "svn:externals")); PropertyEditorDialog d(Manager::Get()->GetAppWindow(), "svn:externals", value); d.Centre(); wxString loc = LocalPath(file); loc = loc == "" ? "[top dir]" : loc; d.SetTitle("Property editor: " + loc); if(d.ShowModal() == wxID_OK) { svn->PropSet(file, d.name, d.value, false); } else if(d.del && ( never_ask || no_ask_revertable || wxMessageDialog(Manager::Get()->GetAppWindow(), "Remove the property " + d.name + " from " + file + " ?", "Delete Property", wxYES_NO).ShowModal() == wxID_YES)) { svn->PropDel(file, d.name); } } void SubversionPlugin::PropKeywords(wxCommandEvent& event) { wxString item; switch(event.GetId()) { case ID_MENU_KW_DATE: item << "Date"; break; case ID_MENU_KW_REVISION: item << "Revision"; break; case ID_MENU_KW_AUTHOR: item << "Author"; break; case ID_MENU_KW_HEAD: item << "HeadURL"; break; case ID_MENU_KW_ID: item << "Id"; break; case ID_MENU_KW_SETALL: svn->PropSet(GetSelection(), "svn:keywords", "Date Revision Author HeadURL Id", true); return; case ID_MENU_KW_CLEARALL: svn->PropSet(GetSelection(), "svn:keywords", "", true); return; } wxString kw = svn->PropGet(GetSelection(), "svn:keywords"); if(kw.Contains(item)) kw.Replace(item, ""); else kw << " " << item; kw.Replace("\n", " ", true); // this is probably unneeded, but better do it anyway just in case kw.Replace(" ", " ", true); kw.Trim(false); svn->PropSet(GetSelection(), "svn:keywords", kw, true); } void SubversionPlugin::EditConflicts(wxCommandEvent& event) { assert(tortoise || diff3); svn->Status(svn->GetTarget()); wxArrayString conflicting; ExtractFilesWithStatus('C', conflicting); for(unsigned int i = 0; i < conflicting.Count(); ++i) DoResolve(conflicting[i]); } void SubversionPlugin::OnFatTortoiseCVSFunctionality(wxCommandEvent& event) { assert(tortoisecvs); wxString p(GetSelection()); switch(event.GetId()) { case ID_MENU_CVS_BRANCH: tortoisecvs->Branch(p); break; case ID_MENU_CVS_TAG: tortoisecvs->Tag(p); break; case ID_MENU_CVS_MERGE: tortoisecvs->Merge(p); break; case ID_MENU_CVS_PATCH: tortoisecvs->Patch(p); break; }; } void SubversionPlugin::OnFatTortoiseFunctionality(wxCommandEvent& event) { assert(tortoise); wxString p(GetSelection()); switch(event.GetId()) { case ID_MENU_BRANCH: tortoise->Branch(p); break; case ID_MENU_SWITCH: tortoise->Switch(p); break; case ID_MENU_MERGE: tortoise->Merge(p); break; case ID_MENU_CREATE: { wxString d(::wxDirSelector("Please point to the location where the new repository will be created.")); if(!d.IsEmpty()) tortoise->Create(d); } break; case ID_MENU_RELOCATE: tortoise->Relocate(p); break; case ID_MENU_TSVN_PATCH: tortoise->Patch(p); break; }; } void SubversionPlugin::EditProperty(wxCommandEvent& event) { wxString name; wxString value; wxString file(GetSelection()); if(event.GetId() == ID_MENU_PROP_NEW) { name = "NewPropertyName"; } else { name = fileProperties[event.GetId()]; value = svn->PropGet(file, name); } PropertyEditorDialog d(Manager::Get()->GetAppWindow(), name, value); d.Centre(); wxString loc = LocalPath(file); loc = loc == "" ? "[top dir]" : loc; d.SetTitle("Property editor: " + loc); if(d.ShowModal() == wxID_OK) { svn->PropSet(file, d.name, d.value, false); } else if(d.del && ( never_ask || no_ask_revertable || wxMessageDialog(Manager::Get()->GetAppWindow(), "Remove the property " + d.name + " from " + file + " ?", "Delete Property", wxYES_NO).ShowModal() == wxID_YES)) { svn->PropDel(file, d.name); } } void SubversionPlugin::TransactionSuccess(wxCommandEvent& event) { wxString cmd(event.GetString()); if(event.GetExtraLong() == ToolRunner::SVN) { wxArrayString conflicting; ExtractFilesWithStatus('C', conflicting); if(conflicting.Count()) { svn->EmptyQueue(); // Although the command was successful, files in conflict are still a failure, so break here if(tortoise) { for(unsigned int i = 0; i < conflicting.Count(); ++i) DoResolve(conflicting[i]); } if(verbose) Log::Instance()->Blue("Transaction was successful, but conflicts remain."); return; } } wxString lastCommand(svn->LastCommand()); if(lastCommand.Contains(" commit ")) // cannot rely on cmd here due to RemoteStatusHandler { if(up_after_co) { wxArrayString changed; for(unsigned int i = 0; i < svn->std_out.Count(); ++i) if(svn->std_out[i].Contains("Adding") || svn->std_out[i].Contains("Sending")) changed.Add(svn->std_out[i].Mid(12).Strip(wxString::both)); ReloadEditors(changed); } } if(cmd.Contains("lock")) { ReOpenEditor(svn->GetTarget()); // this may be a bug in svn? IMO, the transaction should fail on an existing lock if(svn->blob.Contains("is already locked by")) if(wxMessageDialog(Manager::Get()->GetAppWindow(), "The resource is alredy locked by another user.\n\n" "You can 'break' the existing lock and acquire your own lock on the resource if you wish to do so.\n\n" "However, locking is a mechanism that should not be handled carelessly.\n" "Before you think about breaking a lock, it is STRONGLY recommended that you communicate with the user currently holding that lock.\n\n" "Do you want to break the lock at the risk of possibly breaking more than just a lock?", "Resource locked", wxYES_NO | wxNO_DEFAULT |wxICON_EXCLAMATION).ShowModal() == wxID_YES) { svn->AddToLastCommand(" --force"); svn->RunAgain(); return; } else { Log::Instance()->Blue("Aborted."); return; } } if(cmd.IsSameAs("checkout")) { ToolRunner *tool = (event.GetExtraLong() == ToolRunner::SVN) ? (ToolRunner *) svn : (ToolRunner *) cvs; if(request_autoopen) AutoOpenProjects(tool->GetTarget(), true, true); } if(cmd.IsSameAs("info")) { wxString s; int n = svn->std_out.Count(); for(int i = 0; i < n; ++i) s << svn->std_out[i] << "\n"; Log::Instance()->Add(s); } if(cmd.IsSameAs("diff")) { if(svn->out.IsEmpty()) Log::Instance()->Add("No differences, skipping output file generation."); else if(!patchFileName.IsEmpty()) { wxFile f(patchFileName, wxFile::write); f.Write(svn->out); patchFileName.Empty(); } } if(cmd.IsSameAs("export:diff")) { wxString dest = svn->GetTarget(); wxString src = dest.BeforeFirst('*'); dest = dest.AfterFirst('*'); if(tortoise) tortoise->Diff(src, dest); else if(diff3) diff3->Diff(src, dest); } if(cmd.IsSameAs("export:release")) { ToolRunner *tool = (event.GetExtraLong() == ToolRunner::SVN) ? (ToolRunner *) svn : (ToolRunner *) cvs; wxString dest = tool->GetTarget().AfterFirst('*'); if(!patchFileName.IsEmpty()) { wxString tarpath(wxFileName(patchFileName).GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR)); // must not Q()! wxString tarfile(binutils->Q(wxFileName(patchFileName).GetFullName())); wxString cmd; if(patchFileName.Contains(".tar")) { binutils->SetExecutable(tarbin); cmd = "--remove-files "; } else if(patchFileName.Contains(".zip")) { binutils->SetExecutable(zipbin); cmd = "-r -m -q -9"; binutils->Run(cmd + binutils->Q(patchFileName) + ".", dest); // must not Q()! patchFileName.Empty(); return; } if(patchFileName.Contains(".tar.gz")) cmd << "-zcf"; else if(patchFileName.Contains(".tar.bz2")) cmd << "--use-compress-program" << binutils->Q(bzip2bin) << "-cf"; else if(patchFileName.Contains(".tar")) cmd << "-cf"; //Log::Instance()->Add(tarpath); //Log::Instance()->Add(cmd + tarfile + "-C" + binutils->Q(dest) + "."); binutils->Run(cmd + tarfile + "-C" + binutils->Q(dest) + ".", tarpath); patchFileName.Empty(); } } // Know nothing, assume the best :) if(svn->IsIdle()) Log::Instance()->Blue("All transactions finished."); if(cmd.IsSameAs("checkout") || cmd.IsSameAs("update") || cmd.IsSameAs("revert")) ResetCheckExternals(); svn->RunQueue(); } void SubversionPlugin::TransactionFailure(wxCommandEvent& event) { wxString cmd(event.GetString()); if(event.GetExtraLong() == ToolRunner::SVN) { // svn:run 'svn cleanup' to remove locks (type 'svn help cleanup' for details) if(svn->blob.Contains("svn cleanup")) { svn->QueueAgain(); svn->InsertFirst(); svn->Run("cleanup" + svn->Q(svn->GetTarget())); return; } // svn: Out of date: 'main.cpp' in transaction '43-1' if(avoid_out_of_date && svn->blob.Contains("Out of date")) { svn->QueueAgain(); svn->InsertFirst(); svn->Update(svn->GetTarget()); return; } // svn: Server doesn't support the lock command // svn: Unknown command 'lock' if(svn->blob.Contains("Unknown command 'lock'")) { Log::Instance()->Red("Locking is a feature only available in newer versions of subversion.\n" "You need at least version 1.2.0 both on the server and on the client side."); } } if(event.GetExtraLong() == ToolRunner::CVS) { /* * Now tell me that CVS does not suck... * CVS exits with error if diff finds differences in files. * Seriously, what do you expect if the user runs "diff"? */ if(cmd.IsSameAs("CVS-diff")) { if(cvs->out.IsEmpty()) Log::Instance()->Add("No differences, skipping output file generation."); else if(!patchFileName.IsEmpty()) { wxFile f(patchFileName, wxFile::write); f.Write(cvs->out); patchFileName.Empty(); } if(verbose && cvs->IsIdle()) Log::Instance()->Blue("All transactions finished."); return; } NotImplemented("Error handler for CVS."); } // We were not able to handle whatever errors occurred Log::Instance()->Red("Transaction failed."); svn->EmptyQueue(); } void SubversionPlugin::ReRun(wxCommandEvent& event) { int id = event.GetId(); assert(id == RUN_AGAIN || id == RUN_NEXT_IN_QUEUE); if(id = RUN_AGAIN) svn->RunAgain(); else svn->RunQueue(); } void SubversionPlugin::DoResolve(const wxString& conflicting) { if(tortoise) tortoise->ConflictEditor(conflicting); else if(diff3) { /* * tkdiff.tcl does not understand the -m switch that is mandatory for all others. * Luckily, it has a much easier way to handle conflict files */ if(diff3->Type() == ToolRunner::TKDIFF) { diff3->Merge(conflicting); } else { wxString target(conflicting); wxString mine(target + ".mine"); wxString theirs; wxString f = wxFindFirstFile( target+ ".r*"); while ( !f.IsEmpty() ) // we're only interested in the last one { theirs = f; f = wxFindNextFile(); } diff3->Merge(mine, theirs, target); } } } void SubversionPlugin::Resolved(wxCommandEvent& event) { wxString target(GetSelection()); if(never_ask || (show_resolved == false) || (wxMessageDialog(Manager::Get()->GetAppWindow(), "Do you want to issue a 'svn resolved' command?\n\n" "This command does NOT resolve any conflicts, instead it tells the revision control system that you have been " "manually editing the conflicting to resolve all conflicts.\n\n" "Undoing the effects of a false 'resolved' command is not impossible, but it is painful. Be sure about what you do.", "Resolved", wxYES_NO | wxICON_EXCLAMATION).ShowModal() == wxID_YES)) svn->Resolved(target); } /*----------------------------------------------------------------------------------------------------------------- * * DO NOT LOOK ANY FURTHER. BEYOND THIS POINT, THINGS ARE REALLY EVIL. YOU HAVE BEEN WARNED. * */ #ifdef __WIN32__ #include <shlobj.h> #include <wx/msw/registry.h> #ifndef CSIDL_PROGRAM_FILES #define CSIDL_PROGRAM_FILES 0x0026 #endif #endif wxString SubversionPlugin::GetCheckoutDir() { wxFileName home; home.AssignHomeDir(); return home.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + "checkout"; } void SubversionPlugin::SearchBinaries() { #ifdef __WIN32__ if(!wxFile::Exists(svnbinary)) svnbinary = NastyFind("svn.exe"); if(!wxFile::Exists(cvsbinary)) cvsbinary = NastyFind("cvs.exe"); if(!wxFile::Exists(tarbin)) tarbin = NastyFind("tar.exe"); if(!wxFile::Exists(bzip2bin)) bzip2bin = NastyFind("bzip2.exe"); if(!wxFile::Exists(zipbin)) zipbin = NastyFind("zip.exe"); has_tar_or_zip = !(tarbin.IsEmpty() && zipbin.IsEmpty()); if(!wxFile::Exists(plink)) plink = NastyFind("TortoisePlink.exe"); if(!wxFile::Exists(plink)) plink = NastyFind("Plink.exe"); plink.Replace("\\", "/"); #else if(!wxFile::Exists(svnbinary)) svnbinary = NastyFind("svn"); if(!wxFile::Exists(cvsbinary)) cvsbinary = NastyFind("cvs"); if(!wxFile::Exists(tarbin)) tarbin = NastyFind("tar"); if(!wxFile::Exists(bzip2bin)) bzip2bin = NastyFind("bzip2"); if(!wxFile::Exists(zipbin)) zipbin = NastyFind("zip"); has_tar_or_zip = !(tarbin.IsEmpty() && zipbin.IsEmpty()); extdiff = NastyFind("kdiff3"); if(extdiff.IsEmpty()) extdiff = NastyFind("tkdiff.tcl"); if(!wxFile::Exists(plink)) plink = NastyFind("ssh"); #endif #ifdef SCO long* ptr = 0; *ptr = 1L; #endif WriteConfig(); } void SubversionPlugin::TamperWithWindowsRegistry() { #ifdef __WIN32__ wxRegKey* rKey; wxString bin; rKey = new wxRegKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\TortoiseSVN"); if( rKey->Exists() ) { rKey->QueryValue("ProcPath", bin); if(wxFile::Exists(bin)) tortoiseproc = bin; } delete rKey; rKey = new wxRegKey("HKEY_CURRENT_USER\\Software\\TortoiseSVN\\History\\repoURLS"); if( rKey->Exists() ) { long index; wxString val; wxString result; if(rKey->GetFirstValue(val, index)) do { if(rKey->QueryValue(val, result)) repoHistory.Add(result); } while ( rKey->GetNextValue(val, index) ); } delete rKey; if(tortoiseproc.IsEmpty()) { if(verbose) Log::Instance()->Add("No working installation of TortoiseSVN was found. Although TortoiseSVN is not strictly necessary to use this plugin,\n" "it offers valuable additional functionality and is highly recommended.\n" "TortoiseSVN is available under http://tortoisesvn.tigris.org\n"); rKey = new wxRegKey("HKEY_CURRENT_USER\\Software\\KDiff3"); if( rKey->Exists() ) { rKey->QueryValue("", bin); bin << "\\kdiff3.exe"; if(wxFile::Exists(bin)) { extdiff = bin; if(verbose) Log::Instance()->Add("KDiff3 detected."); } } delete rKey; if(extdiff.IsEmpty()) { rKey = new wxRegKey("HKEY_CURRENT_USER\\Software\\Thingamahoochie\\WinMerge"); if( rKey->Exists() ) { rKey->QueryValue("Executable", bin); if(wxFile::Exists(bin)) { extdiff = bin; if(verbose) Log::Instance()->Add("WinMerge detected."); } } delete rKey; } } rKey = new wxRegKey("HKEY_LOCAL_MACHINE\\SOFTWARE\\TortoiseCVS"); if( rKey->Exists() ) { rKey->QueryValue("RootDir", bin); bin << "TortoiseAct.exe"; if(wxFile::Exists(bin)) tortoiseact = bin; } delete rKey; if(verbose) { if(!tortoiseproc.IsEmpty()) Log::Instance()->Add("TortoiseSVN detected."); if(repoHistory.Count()) Log::Instance()->Add("Successfully imported TortoiseSVN history from registry."); if(!tortoiseact.IsEmpty()) Log::Instance()->Add("TortoiseCVS detected."); clearTimer.Start(12000); Log::lastLogTime = 0; Log::Instance()->fg(); } #endif } wxString SubversionPlugin::NastyFind(const wxString& name) { // NOTE : This hideous beast could maybe be implemented more elegantly using wxPathList #ifdef __WIN32__ wxArrayString prefix; wxArrayString location; TCHAR szPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, 0, szPath); prefix.Add(szPath); prefix.Add("C:"); prefix.Add("D:"); prefix.Add("C:\\Program Files"); prefix.Add("C:\\Programme"); prefix.Add("C:\\Programa"); prefix.Add("C:\\Programmes"); prefix.Add("C:\\Apps"); prefix.Add("C:\\Tools"); prefix.Add("E:"); location.Add(""); location.Add("\\subversion\\bin"); location.Add("\\TortoiseSVN\\bin"); location.Add("\\TortoiseMerge\\bin"); location.Add("\\subversion"); location.Add("\\TortoiseSVN"); location.Add("\\TortoiseMerge"); location.Add("\\svn\\bin"); location.Add("\\svn"); location.Add("\\bin"); location.Add("\\cvs"); location.Add("\\TortoiseCVS"); location.Add("\\mingw\\bin"); location.Add("\\cygwin\\bin"); int lc = location.GetCount(); // I never trust these are really inline, are they...? int pc = prefix.GetCount(); for(int i = 0; i < lc; i++) { for(int j = 0; j < pc; j++) { wxString loc = prefix[j] + location[i] + "\\" + name; if(wxFile::Exists(loc)) return loc; } } // In the case of svn, we assume that if we have not found it, then it is (hopefully) in PATH. // Tortoise, if not found, is assumed "missing". // Hopefully anyone installing a plugin to run svn has enough sense to install svn as well. if(name.IsSameAs("svn.exe")) { Log::Instance()->Add("The svn executable could not be found in any of the 'usual' locations.\n" "Please do note that svn is essential for the operation of this plugin.\n" "As this is the only thing that makes sense, I will assume that svn is accessible via the %PATH% environment variable.\n" "You can set the path to the svn executable in the preferences dialog.\n"); return(name); } #endif #ifdef __linux__ wxArrayString location; location.Add("/usr/bin"); // this is probably it, anyway location.Add("/usr/local/bin"); location.Add("/usr/share/bin"); location.Add("/bin"); location.Add("/opt/bin"); location.Add("/usr/sbin"); // uhh... hopefully not, but who knows... location.Add("/sbin"); // everything is possible for(int i = 0; i < location.GetCount(); i++) { wxString loc = location[i] + "/" + name; if(wxFile::Exists(loc)) return loc; } // similar to above - if we can't find svn, we will assume (hope) it is in $PATH and just call "svn" // - if the user actually works with svn at all, this should be the case if(name.IsSameAs("svn")) { Log::Instance()->Add("The svn executable could not be found in any of the 'usual' locations.\n" "Please do note that svn is essential for the operation of this plugin.\n" "As this is the only thing that makes sense, I will assume that svn is accessible via the $PATH environment variable.\n" "You can set the path to the svn executable in the preferences dialog.\n"); return(name); } #endif return wxEmptyString; }
[ "thomasdenk@96b225bb-4cfa-0310-88f5-88b948d20ad7" ]
[ [ [ 1, 2313 ] ] ]
dde2c8522c4c8f5849df22972e56d1ba4d09f1a3
14bc620a0365e83444dad45611381c7f6bcd052b
/ITUEngine/Utils/Log.cpp
69e314bf8b11cf3cc200530447a8ae718683d06a
[]
no_license
jumoel/itu-gameengine
a5750bfdf391ae64407217bfc1df8b2a3db551c7
062dd47bc1be0f39a0add8615e81361bcaa2bd4c
refs/heads/master
2020-05-03T20:39:31.307460
2011-12-19T10:54:10
2011-12-19T10:54:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
374
cpp
#include <Utils/Log.hpp> #include <stdio.h> Log::Log(char* filename) { m_stream.open(filename); } Log::~Log() { m_stream.close(); } void Log::Write(const char* logline, ...) { va_list argList; char cbuffer[1024]; va_start(argList, logline); vsnprintf_s(cbuffer, 1024, logline, argList); va_end(argList); m_stream << cbuffer << std::endl; }
[ [ [ 1, 23 ] ] ]
44d02cf0b933bb2327e93dedcf38fac5fb35981c
f9d55548d2d1044dc344bb9685393f6e820d44df
/src/bullet/btGjkEpa2.cpp
d242e8cef1082c8b6d0e04b42f29e8c6964f85b1
[]
no_license
schweikm/3DJoust
5709bed8e6ad5299faef576d4d754e8f15004fdb
d662b9379cd1afc8204535254343df42ff438b9d
refs/heads/master
2020-12-24T05:24:09.774415
2011-10-08T03:47:29
2011-10-08T03:47:29
61,953,068
0
0
null
null
null
null
UTF-8
C++
false
false
25,032
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2008 Erwin Coumans http://continuousphysics.com/Bullet/ This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* GJK-EPA collision solver by Nathanael Presson, 2008 */ #include "btConvexInternalShape.h" #include "btSphereShape.h" #include "btGjkEpa2.h" #if defined(DEBUG) || defined (_DEBUG) #include <stdio.h> //for debug printf #ifdef __SPU__ #include <spu_printf.h> #define printf spu_printf #endif //__SPU__ #endif namespace gjkepa2_impl { // Config /* GJK */ #define GJK_MAX_ITERATIONS 128 #define GJK_ACCURARY ((btScalar)0.0001) #define GJK_MIN_DISTANCE ((btScalar)0.0001) #define GJK_DUPLICATED_EPS ((btScalar)0.0001) #define GJK_SIMPLEX2_EPS ((btScalar)0.0) #define GJK_SIMPLEX3_EPS ((btScalar)0.0) #define GJK_SIMPLEX4_EPS ((btScalar)0.0) /* EPA */ #define EPA_MAX_VERTICES 64 #define EPA_MAX_FACES (EPA_MAX_VERTICES*2) #define EPA_MAX_ITERATIONS 255 #define EPA_ACCURACY ((btScalar)0.0001) #define EPA_FALLBACK (10*EPA_ACCURACY) #define EPA_PLANE_EPS ((btScalar)0.00001) #define EPA_INSIDE_EPS ((btScalar)0.01) // Shorthands typedef unsigned int U; typedef unsigned char U1; // MinkowskiDiff struct MinkowskiDiff { const btConvexShape* m_shapes[2]; btMatrix3x3 m_toshape1; btTransform m_toshape0; btVector3 (btConvexShape::*Ls)(const btVector3&) const; void EnableMargin(bool enable) { if(enable) Ls=&btConvexShape::localGetSupportVertexNonVirtual; else Ls=&btConvexShape::localGetSupportVertexWithoutMarginNonVirtual; } inline btVector3 Support0(const btVector3& d) const { return(((m_shapes[0])->*(Ls))(d)); } inline btVector3 Support1(const btVector3& d) const { return(m_toshape0*((m_shapes[1])->*(Ls))(m_toshape1*d)); } inline btVector3 Support(const btVector3& d) const { return(Support0(d)-Support1(-d)); } btVector3 Support(const btVector3& d,U index) const { if(index) return(Support1(d)); else return(Support0(d)); } }; typedef MinkowskiDiff tShape; // GJK struct GJK { /* Types */ struct sSV { btVector3 d,w; }; struct sSimplex { sSV* c[4]; btScalar p[4]; U rank; }; struct eStatus { enum _ { Valid, Inside, Failed };}; /* Fields */ tShape m_shape; btVector3 m_ray; btScalar m_distance; sSimplex m_simplices[2]; sSV m_store[4]; sSV* m_free[4]; U m_nfree; U m_current; sSimplex* m_simplex; eStatus::_ m_status; /* Methods */ GJK() { Initialize(); } void Initialize() { m_ray = btVector3(0,0,0); m_nfree = 0; m_status = eStatus::Failed; m_current = 0; m_distance = 0; } eStatus::_ Evaluate(const tShape& shapearg,const btVector3& guess) { U iterations=0; btScalar sqdist=0; btScalar alpha=0; btVector3 lastw[4]; U clastw=0; /* Initialize solver */ m_free[0] = &m_store[0]; m_free[1] = &m_store[1]; m_free[2] = &m_store[2]; m_free[3] = &m_store[3]; m_nfree = 4; m_current = 0; m_status = eStatus::Valid; m_shape = shapearg; m_distance = 0; /* Initialize simplex */ m_simplices[0].rank = 0; m_ray = guess; const btScalar sqrl= m_ray.length2(); appendvertice(m_simplices[0],sqrl>0?-m_ray:btVector3(1,0,0)); m_simplices[0].p[0] = 1; m_ray = m_simplices[0].c[0]->w; sqdist = sqrl; lastw[0] = lastw[1] = lastw[2] = lastw[3] = m_ray; /* Loop */ do { const U next=1-m_current; sSimplex& cs=m_simplices[m_current]; sSimplex& ns=m_simplices[next]; /* Check zero */ const btScalar rl=m_ray.length(); if(rl<GJK_MIN_DISTANCE) {/* Touching or inside */ m_status=eStatus::Inside; break; } /* Append new vertice in -'v' direction */ appendvertice(cs,-m_ray); const btVector3& w=cs.c[cs.rank-1]->w; bool found=false; for(U i=0;i<4;++i) { if((w-lastw[i]).length2()<GJK_DUPLICATED_EPS) { found=true;break; } } if(found) {/* Return old simplex */ removevertice(m_simplices[m_current]); break; } else {/* Update lastw */ lastw[clastw=(clastw+1)&3]=w; } /* Check for termination */ const btScalar omega=dot(m_ray,w)/rl; alpha=btMax(omega,alpha); if(((rl-alpha)-(GJK_ACCURARY*rl))<=0) {/* Return old simplex */ removevertice(m_simplices[m_current]); break; } /* Reduce simplex */ btScalar weights[4]; U mask=0; switch(cs.rank) { case 2: sqdist=projectorigin( cs.c[0]->w, cs.c[1]->w, weights,mask);break; case 3: sqdist=projectorigin( cs.c[0]->w, cs.c[1]->w, cs.c[2]->w, weights,mask);break; case 4: sqdist=projectorigin( cs.c[0]->w, cs.c[1]->w, cs.c[2]->w, cs.c[3]->w, weights,mask);break; } if(sqdist>=0) {/* Valid */ ns.rank = 0; m_ray = btVector3(0,0,0); m_current = next; for(U i=0,ni=cs.rank;i<ni;++i) { if(mask&(1<<i)) { ns.c[ns.rank] = cs.c[i]; ns.p[ns.rank++] = weights[i]; m_ray += cs.c[i]->w*weights[i]; } else { m_free[m_nfree++] = cs.c[i]; } } if(mask==15) m_status=eStatus::Inside; } else {/* Return old simplex */ removevertice(m_simplices[m_current]); break; } m_status=((++iterations)<GJK_MAX_ITERATIONS)?m_status:eStatus::Failed; } while(m_status==eStatus::Valid); m_simplex=&m_simplices[m_current]; switch(m_status) { case eStatus::Valid: m_distance=m_ray.length();break; case eStatus::Inside: m_distance=0;break; } return(m_status); } bool EncloseOrigin() { switch(m_simplex->rank) { case 1: { for(U i=0;i<3;++i) { btVector3 axis=btVector3(0,0,0); axis[i]=1; appendvertice(*m_simplex, axis); if(EncloseOrigin()) return(true); removevertice(*m_simplex); appendvertice(*m_simplex,-axis); if(EncloseOrigin()) return(true); removevertice(*m_simplex); } } break; case 2: { const btVector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w; for(U i=0;i<3;++i) { btVector3 axis=btVector3(0,0,0); axis[i]=1; const btVector3 p=cross(d,axis); if(p.length2()>0) { appendvertice(*m_simplex, p); if(EncloseOrigin()) return(true); removevertice(*m_simplex); appendvertice(*m_simplex,-p); if(EncloseOrigin()) return(true); removevertice(*m_simplex); } } } break; case 3: { const btVector3 n=cross(m_simplex->c[1]->w-m_simplex->c[0]->w, m_simplex->c[2]->w-m_simplex->c[0]->w); if(n.length2()>0) { appendvertice(*m_simplex,n); if(EncloseOrigin()) return(true); removevertice(*m_simplex); appendvertice(*m_simplex,-n); if(EncloseOrigin()) return(true); removevertice(*m_simplex); } } break; case 4: { if(btFabs(det( m_simplex->c[0]->w-m_simplex->c[3]->w, m_simplex->c[1]->w-m_simplex->c[3]->w, m_simplex->c[2]->w-m_simplex->c[3]->w))>0) return(true); } break; } return(false); } /* Internals */ void getsupport(const btVector3& d,sSV& sv) const { sv.d = d/d.length(); sv.w = m_shape.Support(sv.d); } void removevertice(sSimplex& simplex) { m_free[m_nfree++]=simplex.c[--simplex.rank]; } void appendvertice(sSimplex& simplex,const btVector3& v) { simplex.p[simplex.rank]=0; simplex.c[simplex.rank]=m_free[--m_nfree]; getsupport(v,*simplex.c[simplex.rank++]); } static btScalar det(const btVector3& a,const btVector3& b,const btVector3& c) { return( a.y()*b.z()*c.x()+a.z()*b.x()*c.y()- a.x()*b.z()*c.y()-a.y()*b.x()*c.z()+ a.x()*b.y()*c.z()-a.z()*b.y()*c.x()); } static btScalar projectorigin( const btVector3& a, const btVector3& b, btScalar* w,U& m) { const btVector3 d=b-a; const btScalar l=d.length2(); if(l>GJK_SIMPLEX2_EPS) { const btScalar t(l>0?-dot(a,d)/l:0); if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length2()); } else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length2()); } else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length2()); } } return(-1); } static btScalar projectorigin( const btVector3& a, const btVector3& b, const btVector3& c, btScalar* w,U& m) { static const U imd3[]={1,2,0}; const btVector3* vt[]={&a,&b,&c}; const btVector3 dl[]={a-b,b-c,c-a}; const btVector3 n=cross(dl[0],dl[1]); const btScalar l=n.length2(); if(l>GJK_SIMPLEX3_EPS) { btScalar mindist=-1; btScalar subw[2]; U subm; for(U i=0;i<3;++i) { if(dot(*vt[i],cross(dl[i],n))>0) { const U j=imd3[i]; const btScalar subd(projectorigin(*vt[i],*vt[j],subw,subm)); if((mindist<0)||(subd<mindist)) { mindist = subd; m = static_cast<U>(((subm&1)?1<<i:0)+((subm&2)?1<<j:0)); w[i] = subw[0]; w[j] = subw[1]; w[imd3[j]] = 0; } } } if(mindist<0) { const btScalar d=dot(a,n); const btScalar s=btSqrt(l); const btVector3 p=n*(d/l); mindist = p.length2(); m = 7; w[0] = (cross(dl[1],b-p)).length()/s; w[1] = (cross(dl[2],c-p)).length()/s; w[2] = 1-(w[0]+w[1]); } return(mindist); } return(-1); } static btScalar projectorigin( const btVector3& a, const btVector3& b, const btVector3& c, const btVector3& d, btScalar* w,U& m) { static const U imd3[]={1,2,0}; const btVector3* vt[]={&a,&b,&c,&d}; const btVector3 dl[]={a-d,b-d,c-d}; const btScalar vl=det(dl[0],dl[1],dl[2]); const bool ng=(vl*dot(a,cross(b-c,a-b)))<=0; if(ng&&(btFabs(vl)>GJK_SIMPLEX4_EPS)) { btScalar mindist=-1; btScalar subw[3]; U subm; for(U i=0;i<3;++i) { const U j=imd3[i]; const btScalar s=vl*dot(d,cross(dl[i],dl[j])); if(s>0) { const btScalar subd=projectorigin(*vt[i],*vt[j],d,subw,subm); if((mindist<0)||(subd<mindist)) { mindist = subd; m = static_cast<U>((subm&1?1<<i:0)+ (subm&2?1<<j:0)+ (subm&4?8:0)); w[i] = subw[0]; w[j] = subw[1]; w[imd3[j]] = 0; w[3] = subw[2]; } } } if(mindist<0) { mindist = 0; m = 15; w[0] = det(c,b,d)/vl; w[1] = det(a,c,d)/vl; w[2] = det(b,a,d)/vl; w[3] = 1-(w[0]+w[1]+w[2]); } return(mindist); } return(-1); } }; // EPA struct EPA { /* Types */ typedef GJK::sSV sSV; struct sFace { btVector3 n; btScalar d; btScalar p; sSV* c[3]; sFace* f[3]; sFace* l[2]; U1 e[3]; U1 pass; }; struct sList { sFace* root; U count; sList() : root(0),count(0) {} }; struct sHorizon { sFace* cf; sFace* ff; U nf; sHorizon() : cf(0),ff(0),nf(0) {} }; struct eStatus { enum _ { Valid, Touching, Degenerated, NonConvex, InvalidHull, OutOfFaces, OutOfVertices, AccuraryReached, FallBack, Failed };}; /* Fields */ eStatus::_ m_status; GJK::sSimplex m_result; btVector3 m_normal; btScalar m_depth; sSV m_sv_store[EPA_MAX_VERTICES]; sFace m_fc_store[EPA_MAX_FACES]; U m_nextsv; sList m_hull; sList m_stock; /* Methods */ EPA() { Initialize(); } static inline void bind(sFace* fa,U ea,sFace* fb,U eb) { fa->e[ea]=(U1)eb;fa->f[ea]=fb; fb->e[eb]=(U1)ea;fb->f[eb]=fa; } static inline void append(sList& list,sFace* face) { face->l[0] = 0; face->l[1] = list.root; if(list.root) list.root->l[0]=face; list.root = face; ++list.count; } static inline void remove(sList& list,sFace* face) { if(face->l[1]) face->l[1]->l[0]=face->l[0]; if(face->l[0]) face->l[0]->l[1]=face->l[1]; if(face==list.root) list.root=face->l[1]; --list.count; } void Initialize() { m_status = eStatus::Failed; m_normal = btVector3(0,0,0); m_depth = 0; m_nextsv = 0; for(U i=0;i<EPA_MAX_FACES;++i) { append(m_stock,&m_fc_store[EPA_MAX_FACES-i-1]); } } eStatus::_ Evaluate(GJK& gjk,const btVector3& guess) { GJK::sSimplex& simplex=*gjk.m_simplex; if((simplex.rank>1)&&gjk.EncloseOrigin()) { /* Clean up */ while(m_hull.root) { sFace* f = m_hull.root; remove(m_hull,f); append(m_stock,f); } m_status = eStatus::Valid; m_nextsv = 0; /* Orient simplex */ if(gjk.det( simplex.c[0]->w-simplex.c[3]->w, simplex.c[1]->w-simplex.c[3]->w, simplex.c[2]->w-simplex.c[3]->w)<0) { btSwap(simplex.c[0],simplex.c[1]); btSwap(simplex.p[0],simplex.p[1]); } /* Build initial hull */ sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true), newface(simplex.c[1],simplex.c[0],simplex.c[3],true), newface(simplex.c[2],simplex.c[1],simplex.c[3],true), newface(simplex.c[0],simplex.c[2],simplex.c[3],true)}; if(m_hull.count==4) { sFace* best=findbest(); sFace outer=*best; U pass=0; U iterations=0; bind(tetra[0],0,tetra[1],0); bind(tetra[0],1,tetra[2],0); bind(tetra[0],2,tetra[3],0); bind(tetra[1],1,tetra[3],2); bind(tetra[1],2,tetra[2],1); bind(tetra[2],2,tetra[3],1); m_status=eStatus::Valid; for(;iterations<EPA_MAX_ITERATIONS;++iterations) { if(m_nextsv<EPA_MAX_VERTICES) { sHorizon horizon; sSV* w=&m_sv_store[m_nextsv++]; bool valid=true; best->pass = (U1)(++pass); gjk.getsupport(best->n,*w); const btScalar wdist=dot(best->n,w->w)-best->d; if(wdist>EPA_ACCURACY) { for(U j=0;(j<3)&&valid;++j) { valid&=expand( pass,w, best->f[j],best->e[j], horizon); } if(valid&&(horizon.nf>=3)) { bind(horizon.cf,1,horizon.ff,2); remove(m_hull,best); append(m_stock,best); best=findbest(); if(best->p>=outer.p) outer=*best; } else { m_status=eStatus::InvalidHull;break; } } else { m_status=eStatus::AccuraryReached;break; } } else { m_status=eStatus::OutOfVertices;break; } } const btVector3 projection=outer.n*outer.d; m_normal = outer.n; m_depth = outer.d; m_result.rank = 3; m_result.c[0] = outer.c[0]; m_result.c[1] = outer.c[1]; m_result.c[2] = outer.c[2]; m_result.p[0] = cross( outer.c[1]->w-projection, outer.c[2]->w-projection).length(); m_result.p[1] = cross( outer.c[2]->w-projection, outer.c[0]->w-projection).length(); m_result.p[2] = cross( outer.c[0]->w-projection, outer.c[1]->w-projection).length(); const btScalar sum=m_result.p[0]+m_result.p[1]+m_result.p[2]; m_result.p[0] /= sum; m_result.p[1] /= sum; m_result.p[2] /= sum; return(m_status); } } /* Fallback */ m_status = eStatus::FallBack; m_normal = -guess; const btScalar nl=m_normal.length(); if(nl>0) m_normal = m_normal/nl; else m_normal = btVector3(1,0,0); m_depth = 0; m_result.rank=1; m_result.c[0]=simplex.c[0]; m_result.p[0]=1; return(m_status); } sFace* newface(sSV* a,sSV* b,sSV* c,bool forced) { if(m_stock.root) { sFace* face=m_stock.root; remove(m_stock,face); append(m_hull,face); face->pass = 0; face->c[0] = a; face->c[1] = b; face->c[2] = c; face->n = cross(b->w-a->w,c->w-a->w); const btScalar l=face->n.length(); const bool v=l>EPA_ACCURACY; face->p = btMin(btMin( dot(a->w,cross(face->n,a->w-b->w)), dot(b->w,cross(face->n,b->w-c->w))), dot(c->w,cross(face->n,c->w-a->w))) / (v?l:1); face->p = face->p>=-EPA_INSIDE_EPS?0:face->p; if(v) { face->d = dot(a->w,face->n)/l; face->n /= l; if(forced||(face->d>=-EPA_PLANE_EPS)) { return(face); } else m_status=eStatus::NonConvex; } else m_status=eStatus::Degenerated; remove(m_hull,face); append(m_stock,face); return(0); } m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces; return(0); } sFace* findbest() { sFace* minf=m_hull.root; btScalar mind=minf->d*minf->d; btScalar maxp=minf->p; for(sFace* f=minf->l[1];f;f=f->l[1]) { const btScalar sqd=f->d*f->d; if((f->p>=maxp)&&(sqd<mind)) { minf=f; mind=sqd; maxp=f->p; } } return(minf); } bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon) { static const U i1m3[]={1,2,0}; static const U i2m3[]={2,0,1}; if(f->pass!=pass) { const U e1=i1m3[e]; if((dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS) { sFace* nf=newface(f->c[e1],f->c[e],w,false); if(nf) { bind(nf,0,f,e); if(horizon.cf) bind(horizon.cf,1,nf,2); else horizon.ff=nf; horizon.cf=nf; ++horizon.nf; return(true); } } else { const U e2=i2m3[e]; f->pass = (U1)pass; if( expand(pass,w,f->f[e1],f->e[e1],horizon)&& expand(pass,w,f->f[e2],f->e[e2],horizon)) { remove(m_hull,f); append(m_stock,f); return(true); } } } return(false); } }; // static void Initialize( const btConvexShape* shape0,const btTransform& wtrs0, const btConvexShape* shape1,const btTransform& wtrs1, btGjkEpaSolver2::sResults& results, tShape& shape, bool withmargins) { /* Results */ results.witnesses[0] = results.witnesses[1] = btVector3(0,0,0); results.status = btGjkEpaSolver2::sResults::Separated; /* Shape */ shape.m_shapes[0] = shape0; shape.m_shapes[1] = shape1; shape.m_toshape1 = wtrs1.getBasis().transposeTimes(wtrs0.getBasis()); shape.m_toshape0 = wtrs0.inverseTimes(wtrs1); shape.EnableMargin(withmargins); } } // // Api // using namespace gjkepa2_impl; // int btGjkEpaSolver2::StackSizeRequirement() { return(sizeof(GJK)+sizeof(EPA)); } // bool btGjkEpaSolver2::Distance( const btConvexShape* shape0, const btTransform& wtrs0, const btConvexShape* shape1, const btTransform& wtrs1, const btVector3& guess, sResults& results) { tShape shape; Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false); GJK gjk; GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess); if(gjk_status==GJK::eStatus::Valid) { btVector3 w0=btVector3(0,0,0); btVector3 w1=btVector3(0,0,0); for(U i=0;i<gjk.m_simplex->rank;++i) { const btScalar p=gjk.m_simplex->p[i]; w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p; w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p; } results.witnesses[0] = wtrs0*w0; results.witnesses[1] = wtrs0*w1; results.normal = w0-w1; results.distance = results.normal.length(); results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1; return(true); } else { results.status = gjk_status==GJK::eStatus::Inside? sResults::Penetrating : sResults::GJK_Failed ; return(false); } } // bool btGjkEpaSolver2::Penetration( const btConvexShape* shape0, const btTransform& wtrs0, const btConvexShape* shape1, const btTransform& wtrs1, const btVector3& guess, sResults& results, bool usemargins) { tShape shape; Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,usemargins); GJK gjk; GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess); switch(gjk_status) { case GJK::eStatus::Inside: { EPA epa; EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess); if(epa_status!=EPA::eStatus::Failed) { btVector3 w0=btVector3(0,0,0); for(U i=0;i<epa.m_result.rank;++i) { w0+=shape.Support(epa.m_result.c[i]->d,0)*epa.m_result.p[i]; } results.status = sResults::Penetrating; results.witnesses[0] = wtrs0*w0; results.witnesses[1] = wtrs0*(w0-epa.m_normal*epa.m_depth); results.normal = -epa.m_normal; results.distance = -epa.m_depth; return(true); } else results.status=sResults::EPA_Failed; } break; case GJK::eStatus::Failed: results.status=sResults::GJK_Failed; break; } return(false); } // btScalar btGjkEpaSolver2::SignedDistance(const btVector3& position, btScalar margin, const btConvexShape* shape0, const btTransform& wtrs0, sResults& results) { tShape shape; btSphereShape shape1(margin); btTransform wtrs1(btQuaternion(0,0,0,1),position); Initialize(shape0,wtrs0,&shape1,wtrs1,results,shape,false); GJK gjk; GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,btVector3(1,1,1)); if(gjk_status==GJK::eStatus::Valid) { btVector3 w0=btVector3(0,0,0); btVector3 w1=btVector3(0,0,0); for(U i=0;i<gjk.m_simplex->rank;++i) { const btScalar p=gjk.m_simplex->p[i]; w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p; w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p; } results.witnesses[0] = wtrs0*w0; results.witnesses[1] = wtrs0*w1; const btVector3 delta= results.witnesses[1]- results.witnesses[0]; const btScalar margin= shape0->getMarginNonVirtual()+ shape1.getMarginNonVirtual(); const btScalar length= delta.length(); results.normal = delta/length; results.witnesses[0] += results.normal*margin; return(length-margin); } else { if(gjk_status==GJK::eStatus::Inside) { if(Penetration(shape0,wtrs0,&shape1,wtrs1,gjk.m_ray,results)) { const btVector3 delta= results.witnesses[0]- results.witnesses[1]; const btScalar length= delta.length(); if (length >= SIMD_EPSILON) results.normal = delta/length; return(-length); } } } return(SIMD_INFINITY); } // bool btGjkEpaSolver2::SignedDistance(const btConvexShape* shape0, const btTransform& wtrs0, const btConvexShape* shape1, const btTransform& wtrs1, const btVector3& guess, sResults& results) { if(!Distance(shape0,wtrs0,shape1,wtrs1,guess,results)) return(Penetration(shape0,wtrs0,shape1,wtrs1,guess,results,false)); else return(true); } /* Symbols cleanup */ #undef GJK_MAX_ITERATIONS #undef GJK_ACCURARY #undef GJK_MIN_DISTANCE #undef GJK_DUPLICATED_EPS #undef GJK_SIMPLEX2_EPS #undef GJK_SIMPLEX3_EPS #undef GJK_SIMPLEX4_EPS #undef EPA_MAX_VERTICES #undef EPA_MAX_FACES #undef EPA_MAX_ITERATIONS #undef EPA_ACCURACY #undef EPA_FALLBACK #undef EPA_PLANE_EPS #undef EPA_INSIDE_EPS
[ [ [ 1, 943 ] ] ]
6ce1c64aff08a32754be54521bfc1be88914fc10
2e5bc0ec41f772109b48082961b791ce8ef13e37
/classes/SingleCount.h
383058075939f16445fd2bc7f7e0415c5961c269
[]
no_license
Chefslayer/Translator
41fde25e143218c4cdd4cb9cf4889dadf31848d7
7ecf27cbc0dffedb4cf9b624cb50d6aab979443f
refs/heads/master
2016-09-05T14:18:12.645917
2009-07-31T17:01:38
2009-07-31T17:01:38
190,734
1
0
null
null
null
null
UTF-8
C++
false
false
1,383
h
/** * @file * @author Gruppe 2 * @version 1.0 * * @section DESCRIPTION * * The SingleCount class holds and counts the occurrence of single-words. */ #ifndef __SINGLECOUNT_H__ #define __SINGLECOUNT_H__ #include "../includes/constants.h" #include <vector> using namespace std; /** * The SingleCount class holds and counts the occurrence of single-words. */ class SingleCount { private: /// counts and holds the occurrences of a word(-code) vector<unsigned int> wordcounts; public: /** * Constructor inits the wordcounts vector size */ inline SingleCount() { vector<unsigned int> wordcounts(VECTOR_INIT_SIZE, 0); } /** * inserts and/or increments the count of a single-word. * * \param word word to insert */ inline void insert(unsigned int word) { if (word >= wordcounts.size()) { wordcounts.resize(wordcounts.size() + VECTOR_RESIZE); } wordcounts[word]++; } /** * gets the count of occurrence of a word. * * \param word the word to get the count for. * \return count of occurrence of the given word. */ inline unsigned int getFreq(unsigned int word) { return wordcounts[word]; } /** * gets the count of inserted words. * * \return count of inserted words = size of the wordcounts-map. */ inline unsigned int getSize() { return wordcounts.size(); } }; #endif
[ [ [ 1, 10 ], [ 15, 15 ], [ 17, 20 ], [ 27, 29 ], [ 34, 39 ], [ 48, 54 ], [ 59, 64 ] ], [ [ 11, 14 ], [ 21, 23 ], [ 25, 25 ], [ 33, 33 ], [ 40, 40 ], [ 47, 47 ], [ 55, 58 ], [ 65, 70 ] ], [ [ 16, 16 ], [ 26, 26 ], [ 30, 32 ], [ 41, 46 ] ], [ [ 24, 24 ] ] ]
a49d466ca2f4f192e50bda8dc3a6adb4feaac4fa
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/tiles_generic.cpp
fc023c0b70a43ce9fc2921364008b1a74f3ad3de
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
86,854
cpp
/*================================================================================================ Generic Tile Rendering Module - Uses the Colour-Depth Independent Image Transfer Method Supports 8 x 8, 16 x 16 and 32 x 32 with or without masking and with full flipping. The functions fully support varying colour-depths and palette offsets as well as all the usual variables. Call GenericTilesInit() in the driver Init function to store the drivers screen size for clipping. This function also calls BurnTransferInit(). Call GenericTilesExit() in the driver Exit function to clear the screen size variables. Again, this function also calls BurnTransferExit(). Otherwise, use the Transfer code as usual. ================================================================================================*/ #if defined (_XBOX) #include <xtl.h> #else #include "ssnes-typedefs.h" #endif #include "tiles_generic.h" unsigned char* pTileData; int nScreenWidth, nScreenHeight; int GenericTilesInit() { int nRet; if (BurnDrvGetFlags() & BDF_ORIENTATION_VERTICAL) BurnDrvGetVisibleSize(&nScreenHeight, &nScreenWidth); else BurnDrvGetVisibleSize(&nScreenWidth, &nScreenHeight); nRet = BurnTransferInit(); return nRet; } int GenericTilesExit() { nScreenWidth = nScreenHeight = 0; BurnTransferExit(); return 0; } /*================================================================================================ Graphics Decoding ================================================================================================*/ #define READBIT(src, bitnum) (src[bitnum / 8] & (0x80 >> (bitnum % 8))) void GfxDecode(int num, int numPlanes, int xSize, int ySize, int planeoffsets[], int xoffsets[], int yoffsets[], int modulo, unsigned char *pSrc, unsigned char *pDest) { int c; for (c = 0; c < num; c++) { int plane, x, y; uint8_t *dp = pDest + (c * xSize * ySize); XMemSet(dp, 0, xSize * ySize); for (plane = 0; plane < numPlanes; plane++) { int planebit = 1 << (numPlanes - 1 - plane); int planeoffs = (c * modulo) + planeoffsets[plane]; for (y = 0; y < ySize; y++) { int yoffs = planeoffs + yoffsets[y]; dp = pDest + (c * xSize * ySize) + (y * xSize); for (x = 0; x < xSize; x++) { int _bitnum = yoffs + xoffsets[x]; if (READBIT(pSrc, _bitnum)) dp[x] |= planebit; } } } } } //================================================================================================ #define PLOTPIXEL(x) pPixel[x] = nPalette | pTileData[x]; #define PLOTPIXEL_FLIPX(x, a) pPixel[x] = nPalette | pTileData[a]; #define PLOTPIXEL_MASK(x, mc) if (pTileData[x] != mc) {pPixel[x] = nPalette | pTileData[x];} #define PLOTPIXEL_MASK_FLIPX(x, a, mc) if (pTileData[a] != mc) {pPixel[x] = nPalette | pTileData[a] ;} #define CLIPPIXEL(x, sx, mx, a) if ((sx + x) >= 0 && (sx + x) < mx) { a; }; /*================================================================================================ 8 x 8 Functions ================================================================================================*/ void Render8x8Tile(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth ) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { PLOTPIXEL(0); PLOTPIXEL(1); PLOTPIXEL(2); PLOTPIXEL(3); PLOTPIXEL(4); PLOTPIXEL(5); PLOTPIXEL(6); PLOTPIXEL(7); } } void Render8x8Tile_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL(0)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL(1)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL(2)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL(3)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL(4)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL(5)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL(6)); CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL(7)); } } void Render8x8Tile_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { PLOTPIXEL_FLIPX(7, 0); PLOTPIXEL_FLIPX(6, 1); PLOTPIXEL_FLIPX(5, 2); PLOTPIXEL_FLIPX(4, 3); PLOTPIXEL_FLIPX(3, 4); PLOTPIXEL_FLIPX(2, 5); PLOTPIXEL_FLIPX(1, 6); PLOTPIXEL_FLIPX(0, 7); } } void Render8x8Tile_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_FLIPX(7, 0)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_FLIPX(6, 1)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_FLIPX(5, 2)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_FLIPX(4, 3)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_FLIPX(3, 4)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_FLIPX(2, 5)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_FLIPX(1, 6)); CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_FLIPX(0, 7)); } } void Render8x8Tile_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { PLOTPIXEL(0); PLOTPIXEL(1); PLOTPIXEL(2); PLOTPIXEL(3); PLOTPIXEL(4); PLOTPIXEL(5); PLOTPIXEL(6); PLOTPIXEL(7); } } void Render8x8Tile_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL(0)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL(1)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL(2)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL(3)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL(4)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL(5)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL(6)); CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL(7)); } } void Render8x8Tile_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { PLOTPIXEL_FLIPX(7, 0); PLOTPIXEL_FLIPX(6, 1); PLOTPIXEL_FLIPX(5, 2); PLOTPIXEL_FLIPX(4, 3); PLOTPIXEL_FLIPX(3, 4); PLOTPIXEL_FLIPX(2, 5); PLOTPIXEL_FLIPX(1, 6); PLOTPIXEL_FLIPX(0, 7); } } void Render8x8Tile_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_FLIPX(7, 0)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_FLIPX(6, 1)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_FLIPX(5, 2)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_FLIPX(4, 3)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_FLIPX(3, 4)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_FLIPX(2, 5)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_FLIPX(1, 6)); CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_FLIPX(0, 7)); } } /*================================================================================================ 8 x 8 Functions with Masking ================================================================================================*/ void Render8x8Tile_Mask(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { PLOTPIXEL_MASK(0, nMaskColour); PLOTPIXEL_MASK(1, nMaskColour); PLOTPIXEL_MASK(2, nMaskColour); PLOTPIXEL_MASK(3, nMaskColour); PLOTPIXEL_MASK(4, nMaskColour); PLOTPIXEL_MASK(5, nMaskColour); PLOTPIXEL_MASK(6, nMaskColour); PLOTPIXEL_MASK(7, nMaskColour); } } void Render8x8Tile_Mask_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_MASK(0, nMaskColour)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_MASK(1, nMaskColour)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_MASK(2, nMaskColour)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_MASK(3, nMaskColour)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_MASK(4, nMaskColour)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_MASK(5, nMaskColour)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_MASK(6, nMaskColour)); CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_MASK(7, nMaskColour)); } } void Render8x8Tile_Mask_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { PLOTPIXEL_MASK_FLIPX(7, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(6, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(5, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(4, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(3, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(2, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX(1, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX(0, 7, nMaskColour); } } void Render8x8Tile_Mask_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 8; y++, pPixel += nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(7, 0, nMaskColour)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(6, 1, nMaskColour)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(5, 2, nMaskColour)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(4, 3, nMaskColour)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(3, 4, nMaskColour)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(2, 5, nMaskColour)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(1, 6, nMaskColour)); CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(0, 7, nMaskColour)); } } void Render8x8Tile_Mask_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { PLOTPIXEL_MASK(0, nMaskColour); PLOTPIXEL_MASK(1, nMaskColour); PLOTPIXEL_MASK(2, nMaskColour); PLOTPIXEL_MASK(3, nMaskColour); PLOTPIXEL_MASK(4, nMaskColour); PLOTPIXEL_MASK(5, nMaskColour); PLOTPIXEL_MASK(6, nMaskColour); PLOTPIXEL_MASK(7, nMaskColour); } } void Render8x8Tile_Mask_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_MASK(0, nMaskColour)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_MASK(1, nMaskColour)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_MASK(2, nMaskColour)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_MASK(3, nMaskColour)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_MASK(4, nMaskColour)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_MASK(5, nMaskColour)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_MASK(6, nMaskColour)); CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_MASK(7, nMaskColour)); } } void Render8x8Tile_Mask_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { PLOTPIXEL_MASK_FLIPX(7, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(6, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(5, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(4, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(3, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(2, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX(1, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX(0, 7, nMaskColour); } } void Render8x8Tile_Mask_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 6); unsigned short* pPixel = pDestDraw + ((StartY + 7) * nScreenWidth) + StartX; for (int y = 7; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 8) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(7, 0, nMaskColour)); CLIPPIXEL(6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(6, 1, nMaskColour)); CLIPPIXEL(5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(5, 2, nMaskColour)); CLIPPIXEL(4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(4, 3, nMaskColour)); CLIPPIXEL(3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(3, 4, nMaskColour)); CLIPPIXEL(2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(2, 5, nMaskColour)); CLIPPIXEL(1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(1, 6, nMaskColour)); CLIPPIXEL(0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(0, 7, nMaskColour)); } } /*================================================================================================ 16 x 16 Functions ================================================================================================*/ void Render16x16Tile(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { PLOTPIXEL( 0); PLOTPIXEL( 1); PLOTPIXEL( 2); PLOTPIXEL( 3); PLOTPIXEL( 4); PLOTPIXEL( 5); PLOTPIXEL( 6); PLOTPIXEL( 7); PLOTPIXEL( 8); PLOTPIXEL( 9); PLOTPIXEL(10); PLOTPIXEL(11); PLOTPIXEL(12); PLOTPIXEL(13); PLOTPIXEL(14); PLOTPIXEL(15); } } void Render16x16Tile_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL( 0)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL( 1)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL( 2)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL( 3)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL( 4)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL( 5)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL( 6)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL( 7)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL( 8)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL( 9)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL(10)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL(11)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL(12)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL(13)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL(14)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL(15)); } } void Render16x16Tile_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { PLOTPIXEL_FLIPX(15, 0); PLOTPIXEL_FLIPX(14, 1); PLOTPIXEL_FLIPX(13, 2); PLOTPIXEL_FLIPX(12, 3); PLOTPIXEL_FLIPX(11, 4); PLOTPIXEL_FLIPX(10, 5); PLOTPIXEL_FLIPX( 9, 6); PLOTPIXEL_FLIPX( 8, 7); PLOTPIXEL_FLIPX( 7, 8); PLOTPIXEL_FLIPX( 6, 9); PLOTPIXEL_FLIPX( 5, 10); PLOTPIXEL_FLIPX( 4, 11); PLOTPIXEL_FLIPX( 3, 12); PLOTPIXEL_FLIPX( 2, 13); PLOTPIXEL_FLIPX( 1, 14); PLOTPIXEL_FLIPX( 0, 15); } } void Render16x16Tile_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_FLIPX(15, 0)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_FLIPX(14, 1)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_FLIPX(13, 2)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_FLIPX(12, 3)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_FLIPX(11, 4)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_FLIPX(10, 5)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 9, 6)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 8, 7)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 7, 8)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 6, 9)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 5, 10)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 4, 11)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 3, 12)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 2, 13)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 1, 14)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 0, 15)); } } void Render16x16Tile_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { PLOTPIXEL( 0); PLOTPIXEL( 1); PLOTPIXEL( 2); PLOTPIXEL( 3); PLOTPIXEL( 4); PLOTPIXEL( 5); PLOTPIXEL( 6); PLOTPIXEL( 7); PLOTPIXEL( 8); PLOTPIXEL( 9); PLOTPIXEL(10); PLOTPIXEL(11); PLOTPIXEL(12); PLOTPIXEL(13); PLOTPIXEL(14); PLOTPIXEL(15); } } void Render16x16Tile_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL( 0)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL( 1)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL( 2)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL( 3)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL( 4)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL( 5)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL( 6)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL( 7)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL( 8)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL( 9)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL(10)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL(11)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL(12)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL(13)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL(14)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL(15)); } } void Render16x16Tile_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { PLOTPIXEL_FLIPX(15, 0); PLOTPIXEL_FLIPX(14, 1); PLOTPIXEL_FLIPX(13, 2); PLOTPIXEL_FLIPX(12, 3); PLOTPIXEL_FLIPX(11, 4); PLOTPIXEL_FLIPX(10, 5); PLOTPIXEL_FLIPX( 9, 6); PLOTPIXEL_FLIPX( 8, 7); PLOTPIXEL_FLIPX( 7, 8); PLOTPIXEL_FLIPX( 6, 9); PLOTPIXEL_FLIPX( 5, 10); PLOTPIXEL_FLIPX( 4, 11); PLOTPIXEL_FLIPX( 3, 12); PLOTPIXEL_FLIPX( 2, 13); PLOTPIXEL_FLIPX( 1, 14); PLOTPIXEL_FLIPX( 0, 15); } } void Render16x16Tile_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_FLIPX(15, 0)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_FLIPX(14, 1)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_FLIPX(13, 2)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_FLIPX(12, 3)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_FLIPX(11, 4)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_FLIPX(10, 5)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 9, 6)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 8, 7)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 7, 8)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 6, 9)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 5, 10)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 4, 11)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 3, 12)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 2, 13)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 1, 14)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 0, 15)); } } /*================================================================================================ 16 x 16 Functions with Masking ================================================================================================*/ void Render16x16Tile_Mask(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { PLOTPIXEL_MASK( 0, nMaskColour); PLOTPIXEL_MASK( 1, nMaskColour); PLOTPIXEL_MASK( 2, nMaskColour); PLOTPIXEL_MASK( 3, nMaskColour); PLOTPIXEL_MASK( 4, nMaskColour); PLOTPIXEL_MASK( 5, nMaskColour); PLOTPIXEL_MASK( 6, nMaskColour); PLOTPIXEL_MASK( 7, nMaskColour); PLOTPIXEL_MASK( 8, nMaskColour); PLOTPIXEL_MASK( 9, nMaskColour); PLOTPIXEL_MASK(10, nMaskColour); PLOTPIXEL_MASK(11, nMaskColour); PLOTPIXEL_MASK(12, nMaskColour); PLOTPIXEL_MASK(13, nMaskColour); PLOTPIXEL_MASK(14, nMaskColour); PLOTPIXEL_MASK(15, nMaskColour); } } void Render16x16Tile_Mask_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK( 0, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK( 1, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK( 2, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK( 3, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK( 4, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK( 5, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK( 6, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK( 7, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK( 8, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK( 9, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK(10, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK(11, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK(12, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK(13, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK(14, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK(15, nMaskColour)); } } void Render16x16Tile_Mask_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { PLOTPIXEL_MASK_FLIPX(15, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(14, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(13, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(12, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(11, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(10, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX( 9, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX( 8, 7, nMaskColour); PLOTPIXEL_MASK_FLIPX( 7, 8, nMaskColour); PLOTPIXEL_MASK_FLIPX( 6, 9, nMaskColour); PLOTPIXEL_MASK_FLIPX( 5, 10, nMaskColour); PLOTPIXEL_MASK_FLIPX( 4, 11, nMaskColour); PLOTPIXEL_MASK_FLIPX( 3, 12, nMaskColour); PLOTPIXEL_MASK_FLIPX( 2, 13, nMaskColour); PLOTPIXEL_MASK_FLIPX( 1, 14, nMaskColour); PLOTPIXEL_MASK_FLIPX( 0, 15, nMaskColour); } } void Render16x16Tile_Mask_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 16; y++, pPixel += nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(15, 0, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(14, 1, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(13, 2, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(12, 3, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(11, 4, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(10, 5, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 9, 6, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 8, 7, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 7, 8, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 6, 9, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 5, 10, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 4, 11, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 3, 12, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 2, 13, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 1, 14, nMaskColour)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 0, 15, nMaskColour)); } } void Render16x16Tile_Mask_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { PLOTPIXEL_MASK( 0, nMaskColour); PLOTPIXEL_MASK( 1, nMaskColour); PLOTPIXEL_MASK( 2, nMaskColour); PLOTPIXEL_MASK( 3, nMaskColour); PLOTPIXEL_MASK( 4, nMaskColour); PLOTPIXEL_MASK( 5, nMaskColour); PLOTPIXEL_MASK( 6, nMaskColour); PLOTPIXEL_MASK( 7, nMaskColour); PLOTPIXEL_MASK( 8, nMaskColour); PLOTPIXEL_MASK( 9, nMaskColour); PLOTPIXEL_MASK(10, nMaskColour); PLOTPIXEL_MASK(11, nMaskColour); PLOTPIXEL_MASK(12, nMaskColour); PLOTPIXEL_MASK(13, nMaskColour); PLOTPIXEL_MASK(14, nMaskColour); PLOTPIXEL_MASK(15, nMaskColour); } } void Render16x16Tile_Mask_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK( 0, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK( 1, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK( 2, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK( 3, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK( 4, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK( 5, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK( 6, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK( 7, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK( 8, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK( 9, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK(10, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK(11, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK(12, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK(13, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK(14, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK(15, nMaskColour)); } } void Render16x16Tile_Mask_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { PLOTPIXEL_MASK_FLIPX(15, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(14, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(13, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(12, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(11, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(10, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX( 9, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX( 8, 7, nMaskColour); PLOTPIXEL_MASK_FLIPX( 7, 8, nMaskColour); PLOTPIXEL_MASK_FLIPX( 6, 9, nMaskColour); PLOTPIXEL_MASK_FLIPX( 5, 10, nMaskColour); PLOTPIXEL_MASK_FLIPX( 4, 11, nMaskColour); PLOTPIXEL_MASK_FLIPX( 3, 12, nMaskColour); PLOTPIXEL_MASK_FLIPX( 2, 13, nMaskColour); PLOTPIXEL_MASK_FLIPX( 1, 14, nMaskColour); PLOTPIXEL_MASK_FLIPX( 0, 15, nMaskColour); } } void Render16x16Tile_Mask_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 8); unsigned short* pPixel = pDestDraw + ((StartY + 15) * nScreenWidth) + StartX; for (int y = 15; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 16) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(15, 0, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(14, 1, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(13, 2, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(12, 3, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(11, 4, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(10, 5, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 9, 6, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 8, 7, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 7, 8, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 6, 9, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 5, 10, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 4, 11, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 3, 12, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 2, 13, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 1, 14, nMaskColour)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 0, 15, nMaskColour)); } } /*================================================================================================ 32 x 32 Functions ================================================================================================*/ void Render32x32Tile(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { PLOTPIXEL( 0); PLOTPIXEL( 1); PLOTPIXEL( 2); PLOTPIXEL( 3); PLOTPIXEL( 4); PLOTPIXEL( 5); PLOTPIXEL( 6); PLOTPIXEL( 7); PLOTPIXEL( 8); PLOTPIXEL( 9); PLOTPIXEL(10); PLOTPIXEL(11); PLOTPIXEL(12); PLOTPIXEL(13); PLOTPIXEL(14); PLOTPIXEL(15); PLOTPIXEL(16); PLOTPIXEL(17); PLOTPIXEL(18); PLOTPIXEL(19); PLOTPIXEL(20); PLOTPIXEL(21); PLOTPIXEL(22); PLOTPIXEL(23); PLOTPIXEL(24); PLOTPIXEL(25); PLOTPIXEL(26); PLOTPIXEL(27); PLOTPIXEL(28); PLOTPIXEL(29); PLOTPIXEL(30); PLOTPIXEL(31); } } void Render32x32Tile_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL( 0)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL( 1)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL( 2)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL( 3)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL( 4)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL( 5)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL( 6)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL( 7)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL( 8)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL( 9)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL(10)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL(11)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL(12)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL(13)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL(14)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL(15)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL(16)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL(17)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL(18)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL(19)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL(20)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL(21)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL(22)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL(23)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL(24)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL(25)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL(26)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL(27)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL(28)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL(29)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL(30)); CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL(31)); } } void Render32x32Tile_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { PLOTPIXEL_FLIPX(31, 0); PLOTPIXEL_FLIPX(30, 1); PLOTPIXEL_FLIPX(29, 2); PLOTPIXEL_FLIPX(28, 3); PLOTPIXEL_FLIPX(27, 4); PLOTPIXEL_FLIPX(26, 5); PLOTPIXEL_FLIPX(25, 6); PLOTPIXEL_FLIPX(24, 7); PLOTPIXEL_FLIPX(23, 8); PLOTPIXEL_FLIPX(22, 9); PLOTPIXEL_FLIPX(21, 10); PLOTPIXEL_FLIPX(20, 11); PLOTPIXEL_FLIPX(19, 12); PLOTPIXEL_FLIPX(18, 13); PLOTPIXEL_FLIPX(17, 14); PLOTPIXEL_FLIPX(16, 15); PLOTPIXEL_FLIPX(15, 16); PLOTPIXEL_FLIPX(14, 17); PLOTPIXEL_FLIPX(13, 18); PLOTPIXEL_FLIPX(12, 19); PLOTPIXEL_FLIPX(11, 20); PLOTPIXEL_FLIPX(10, 21); PLOTPIXEL_FLIPX( 9, 22); PLOTPIXEL_FLIPX( 8, 23); PLOTPIXEL_FLIPX( 7, 24); PLOTPIXEL_FLIPX( 6, 25); PLOTPIXEL_FLIPX( 5, 26); PLOTPIXEL_FLIPX( 4, 27); PLOTPIXEL_FLIPX( 3, 28); PLOTPIXEL_FLIPX( 2, 29); PLOTPIXEL_FLIPX( 1, 30); PLOTPIXEL_FLIPX( 0, 31); } } void Render32x32Tile_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_FLIPX(31, 0)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_FLIPX(30, 1)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_FLIPX(29, 2)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_FLIPX(28, 3)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_FLIPX(27, 4)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_FLIPX(26, 5)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_FLIPX(25, 6)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_FLIPX(24, 7)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_FLIPX(23, 8)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_FLIPX(22, 9)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_FLIPX(21, 10)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_FLIPX(20, 11)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_FLIPX(19, 12)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_FLIPX(18, 13)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_FLIPX(17, 14)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_FLIPX(16, 15)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_FLIPX(15, 16)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_FLIPX(14, 17)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_FLIPX(13, 18)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_FLIPX(12, 19)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_FLIPX(11, 20)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_FLIPX(10, 21)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 9, 22)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 8, 23)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 7, 24)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 6, 25)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 5, 26)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 4, 27)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 3, 28)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 2, 29)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 1, 30)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 0, 31)); } } void Render32x32Tile_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { PLOTPIXEL( 0); PLOTPIXEL( 1); PLOTPIXEL( 2); PLOTPIXEL( 3); PLOTPIXEL( 4); PLOTPIXEL( 5); PLOTPIXEL( 6); PLOTPIXEL( 7); PLOTPIXEL( 8); PLOTPIXEL( 9); PLOTPIXEL(10); PLOTPIXEL(11); PLOTPIXEL(12); PLOTPIXEL(13); PLOTPIXEL(14); PLOTPIXEL(15); PLOTPIXEL(16); PLOTPIXEL(17); PLOTPIXEL(18); PLOTPIXEL(19); PLOTPIXEL(20); PLOTPIXEL(21); PLOTPIXEL(22); PLOTPIXEL(23); PLOTPIXEL(24); PLOTPIXEL(25); PLOTPIXEL(26); PLOTPIXEL(27); PLOTPIXEL(28); PLOTPIXEL(29); PLOTPIXEL(30); PLOTPIXEL(31); } } void Render32x32Tile_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) { continue; } CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL( 0)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL( 1)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL( 2)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL( 3)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL( 4)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL( 5)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL( 6)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL( 7)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL( 8)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL( 9)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL(10)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL(11)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL(12)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL(13)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL(14)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL(15)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL(16)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL(17)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL(18)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL(19)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL(20)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL(21)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL(22)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL(23)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL(24)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL(25)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL(26)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL(27)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL(28)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL(29)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL(30)); CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL(31)); } } void Render32x32Tile_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { PLOTPIXEL_FLIPX(31, 0); PLOTPIXEL_FLIPX(30, 1); PLOTPIXEL_FLIPX(29, 2); PLOTPIXEL_FLIPX(28, 3); PLOTPIXEL_FLIPX(27, 4); PLOTPIXEL_FLIPX(26, 5); PLOTPIXEL_FLIPX(25, 6); PLOTPIXEL_FLIPX(24, 7); PLOTPIXEL_FLIPX(23, 8); PLOTPIXEL_FLIPX(22, 9); PLOTPIXEL_FLIPX(21, 10); PLOTPIXEL_FLIPX(20, 11); PLOTPIXEL_FLIPX(19, 12); PLOTPIXEL_FLIPX(18, 13); PLOTPIXEL_FLIPX(17, 14); PLOTPIXEL_FLIPX(16, 15); PLOTPIXEL_FLIPX(15, 16); PLOTPIXEL_FLIPX(14, 17); PLOTPIXEL_FLIPX(13, 18); PLOTPIXEL_FLIPX(12, 19); PLOTPIXEL_FLIPX(11, 20); PLOTPIXEL_FLIPX(10, 21); PLOTPIXEL_FLIPX( 9, 22); PLOTPIXEL_FLIPX( 8, 23); PLOTPIXEL_FLIPX( 7, 24); PLOTPIXEL_FLIPX( 6, 25); PLOTPIXEL_FLIPX( 5, 26); PLOTPIXEL_FLIPX( 4, 27); PLOTPIXEL_FLIPX( 3, 28); PLOTPIXEL_FLIPX( 2, 29); PLOTPIXEL_FLIPX( 1, 30); PLOTPIXEL_FLIPX( 0, 31); } } void Render32x32Tile_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_FLIPX(31, 0)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_FLIPX(30, 1)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_FLIPX(29, 2)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_FLIPX(28, 3)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_FLIPX(27, 4)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_FLIPX(26, 5)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_FLIPX(25, 6)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_FLIPX(24, 7)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_FLIPX(23, 8)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_FLIPX(22, 9)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_FLIPX(21, 10)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_FLIPX(20, 11)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_FLIPX(19, 12)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_FLIPX(18, 13)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_FLIPX(17, 14)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_FLIPX(16, 15)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_FLIPX(15, 16)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_FLIPX(14, 17)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_FLIPX(13, 18)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_FLIPX(12, 19)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_FLIPX(11, 20)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_FLIPX(10, 21)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 9, 22)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 8, 23)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 7, 24)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 6, 25)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 5, 26)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 4, 27)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 3, 28)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 2, 29)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 1, 30)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_FLIPX( 0, 31)); } } /*================================================================================================ 32 x 32 Functions with Masking ================================================================================================*/ void Render32x32Tile_Mask(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { PLOTPIXEL_MASK( 0, nMaskColour); PLOTPIXEL_MASK( 1, nMaskColour); PLOTPIXEL_MASK( 2, nMaskColour); PLOTPIXEL_MASK( 3, nMaskColour); PLOTPIXEL_MASK( 4, nMaskColour); PLOTPIXEL_MASK( 5, nMaskColour); PLOTPIXEL_MASK( 6, nMaskColour); PLOTPIXEL_MASK( 7, nMaskColour); PLOTPIXEL_MASK( 8, nMaskColour); PLOTPIXEL_MASK( 9, nMaskColour); PLOTPIXEL_MASK(10, nMaskColour); PLOTPIXEL_MASK(11, nMaskColour); PLOTPIXEL_MASK(12, nMaskColour); PLOTPIXEL_MASK(13, nMaskColour); PLOTPIXEL_MASK(14, nMaskColour); PLOTPIXEL_MASK(15, nMaskColour); PLOTPIXEL_MASK(16, nMaskColour); PLOTPIXEL_MASK(17, nMaskColour); PLOTPIXEL_MASK(18, nMaskColour); PLOTPIXEL_MASK(19, nMaskColour); PLOTPIXEL_MASK(20, nMaskColour); PLOTPIXEL_MASK(21, nMaskColour); PLOTPIXEL_MASK(22, nMaskColour); PLOTPIXEL_MASK(23, nMaskColour); PLOTPIXEL_MASK(24, nMaskColour); PLOTPIXEL_MASK(25, nMaskColour); PLOTPIXEL_MASK(26, nMaskColour); PLOTPIXEL_MASK(27, nMaskColour); PLOTPIXEL_MASK(28, nMaskColour); PLOTPIXEL_MASK(29, nMaskColour); PLOTPIXEL_MASK(30, nMaskColour); PLOTPIXEL_MASK(31, nMaskColour); } } void Render32x32Tile_Mask_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK( 0, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK( 1, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK( 2, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK( 3, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK( 4, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK( 5, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK( 6, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK( 7, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK( 8, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK( 9, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK(10, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK(11, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK(12, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK(13, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK(14, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK(15, nMaskColour)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_MASK(16, nMaskColour)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_MASK(17, nMaskColour)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_MASK(18, nMaskColour)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_MASK(19, nMaskColour)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_MASK(20, nMaskColour)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_MASK(21, nMaskColour)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_MASK(22, nMaskColour)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_MASK(23, nMaskColour)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_MASK(24, nMaskColour)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_MASK(25, nMaskColour)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_MASK(26, nMaskColour)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_MASK(27, nMaskColour)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_MASK(28, nMaskColour)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_MASK(29, nMaskColour)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_MASK(30, nMaskColour)); CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_MASK(31, nMaskColour)); } } void Render32x32Tile_Mask_FlipX(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { PLOTPIXEL_MASK_FLIPX(31, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(30, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(29, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(28, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(27, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(26, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX(25, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX(24, 7, nMaskColour); PLOTPIXEL_MASK_FLIPX(23, 8, nMaskColour); PLOTPIXEL_MASK_FLIPX(22, 9, nMaskColour); PLOTPIXEL_MASK_FLIPX(21, 10, nMaskColour); PLOTPIXEL_MASK_FLIPX(20, 11, nMaskColour); PLOTPIXEL_MASK_FLIPX(19, 12, nMaskColour); PLOTPIXEL_MASK_FLIPX(18, 13, nMaskColour); PLOTPIXEL_MASK_FLIPX(17, 14, nMaskColour); PLOTPIXEL_MASK_FLIPX(16, 15, nMaskColour); PLOTPIXEL_MASK_FLIPX(15, 16, nMaskColour); PLOTPIXEL_MASK_FLIPX(14, 17, nMaskColour); PLOTPIXEL_MASK_FLIPX(13, 18, nMaskColour); PLOTPIXEL_MASK_FLIPX(12, 19, nMaskColour); PLOTPIXEL_MASK_FLIPX(11, 20, nMaskColour); PLOTPIXEL_MASK_FLIPX(10, 21, nMaskColour); PLOTPIXEL_MASK_FLIPX( 9, 22, nMaskColour); PLOTPIXEL_MASK_FLIPX( 8, 23, nMaskColour); PLOTPIXEL_MASK_FLIPX( 7, 24, nMaskColour); PLOTPIXEL_MASK_FLIPX( 6, 25, nMaskColour); PLOTPIXEL_MASK_FLIPX( 5, 26, nMaskColour); PLOTPIXEL_MASK_FLIPX( 4, 27, nMaskColour); PLOTPIXEL_MASK_FLIPX( 3, 28, nMaskColour); PLOTPIXEL_MASK_FLIPX( 2, 29, nMaskColour); PLOTPIXEL_MASK_FLIPX( 1, 30, nMaskColour); PLOTPIXEL_MASK_FLIPX( 0, 31, nMaskColour); } } void Render32x32Tile_Mask_FlipX_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < 32; y++, pPixel += nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(31, 0, nMaskColour)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(30, 1, nMaskColour)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(29, 2, nMaskColour)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(28, 3, nMaskColour)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(27, 4, nMaskColour)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(26, 5, nMaskColour)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(25, 6, nMaskColour)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(24, 7, nMaskColour)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(23, 8, nMaskColour)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(22, 9, nMaskColour)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(21, 10, nMaskColour)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(20, 11, nMaskColour)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(19, 12, nMaskColour)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(18, 13, nMaskColour)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(17, 14, nMaskColour)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(16, 15, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(15, 16, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(14, 17, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(13, 18, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(12, 19, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(11, 20, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(10, 21, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 9, 22, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 8, 23, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 7, 24, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 6, 25, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 5, 26, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 4, 27, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 3, 28, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 2, 29, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 1, 30, nMaskColour)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 0, 31, nMaskColour)); } } void Render32x32Tile_Mask_FlipY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { PLOTPIXEL_MASK( 0, nMaskColour); PLOTPIXEL_MASK( 1, nMaskColour); PLOTPIXEL_MASK( 2, nMaskColour); PLOTPIXEL_MASK( 3, nMaskColour); PLOTPIXEL_MASK( 4, nMaskColour); PLOTPIXEL_MASK( 5, nMaskColour); PLOTPIXEL_MASK( 6, nMaskColour); PLOTPIXEL_MASK( 7, nMaskColour); PLOTPIXEL_MASK( 8, nMaskColour); PLOTPIXEL_MASK( 9, nMaskColour); PLOTPIXEL_MASK(10, nMaskColour); PLOTPIXEL_MASK(11, nMaskColour); PLOTPIXEL_MASK(12, nMaskColour); PLOTPIXEL_MASK(13, nMaskColour); PLOTPIXEL_MASK(14, nMaskColour); PLOTPIXEL_MASK(15, nMaskColour); PLOTPIXEL_MASK(16, nMaskColour); PLOTPIXEL_MASK(17, nMaskColour); PLOTPIXEL_MASK(18, nMaskColour); PLOTPIXEL_MASK(19, nMaskColour); PLOTPIXEL_MASK(20, nMaskColour); PLOTPIXEL_MASK(21, nMaskColour); PLOTPIXEL_MASK(22, nMaskColour); PLOTPIXEL_MASK(23, nMaskColour); PLOTPIXEL_MASK(24, nMaskColour); PLOTPIXEL_MASK(25, nMaskColour); PLOTPIXEL_MASK(26, nMaskColour); PLOTPIXEL_MASK(27, nMaskColour); PLOTPIXEL_MASK(28, nMaskColour); PLOTPIXEL_MASK(29, nMaskColour); PLOTPIXEL_MASK(30, nMaskColour); PLOTPIXEL_MASK(31, nMaskColour); } } void Render32x32Tile_Mask_FlipY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK( 0, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK( 1, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK( 2, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK( 3, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK( 4, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK( 5, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK( 6, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK( 7, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK( 8, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK( 9, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK(10, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK(11, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK(12, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK(13, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK(14, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK(15, nMaskColour)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_MASK(16, nMaskColour)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_MASK(17, nMaskColour)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_MASK(18, nMaskColour)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_MASK(19, nMaskColour)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_MASK(20, nMaskColour)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_MASK(21, nMaskColour)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_MASK(22, nMaskColour)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_MASK(23, nMaskColour)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_MASK(24, nMaskColour)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_MASK(25, nMaskColour)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_MASK(26, nMaskColour)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_MASK(27, nMaskColour)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_MASK(28, nMaskColour)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_MASK(29, nMaskColour)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_MASK(30, nMaskColour)); CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_MASK(31, nMaskColour)); } } void Render32x32Tile_Mask_FlipXY(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { PLOTPIXEL_MASK_FLIPX(31, 0, nMaskColour); PLOTPIXEL_MASK_FLIPX(30, 1, nMaskColour); PLOTPIXEL_MASK_FLIPX(29, 2, nMaskColour); PLOTPIXEL_MASK_FLIPX(28, 3, nMaskColour); PLOTPIXEL_MASK_FLIPX(27, 4, nMaskColour); PLOTPIXEL_MASK_FLIPX(26, 5, nMaskColour); PLOTPIXEL_MASK_FLIPX(25, 6, nMaskColour); PLOTPIXEL_MASK_FLIPX(24, 7, nMaskColour); PLOTPIXEL_MASK_FLIPX(23, 8, nMaskColour); PLOTPIXEL_MASK_FLIPX(22, 9, nMaskColour); PLOTPIXEL_MASK_FLIPX(21, 10, nMaskColour); PLOTPIXEL_MASK_FLIPX(20, 11, nMaskColour); PLOTPIXEL_MASK_FLIPX(19, 12, nMaskColour); PLOTPIXEL_MASK_FLIPX(18, 13, nMaskColour); PLOTPIXEL_MASK_FLIPX(17, 14, nMaskColour); PLOTPIXEL_MASK_FLIPX(16, 15, nMaskColour); PLOTPIXEL_MASK_FLIPX(15, 16, nMaskColour); PLOTPIXEL_MASK_FLIPX(14, 17, nMaskColour); PLOTPIXEL_MASK_FLIPX(13, 18, nMaskColour); PLOTPIXEL_MASK_FLIPX(12, 19, nMaskColour); PLOTPIXEL_MASK_FLIPX(11, 20, nMaskColour); PLOTPIXEL_MASK_FLIPX(10, 21, nMaskColour); PLOTPIXEL_MASK_FLIPX( 9, 22, nMaskColour); PLOTPIXEL_MASK_FLIPX( 8, 23, nMaskColour); PLOTPIXEL_MASK_FLIPX( 7, 24, nMaskColour); PLOTPIXEL_MASK_FLIPX( 6, 25, nMaskColour); PLOTPIXEL_MASK_FLIPX( 5, 26, nMaskColour); PLOTPIXEL_MASK_FLIPX( 4, 27, nMaskColour); PLOTPIXEL_MASK_FLIPX( 3, 28, nMaskColour); PLOTPIXEL_MASK_FLIPX( 2, 29, nMaskColour); PLOTPIXEL_MASK_FLIPX( 1, 30, nMaskColour); PLOTPIXEL_MASK_FLIPX( 0, 31, nMaskColour); } } void Render32x32Tile_Mask_FlipXY_Clip(unsigned short* pDestDraw, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber << 10); unsigned short* pPixel = pDestDraw + ((StartY + 31) * nScreenWidth) + StartX; for (int y = 31; y >= 0; y--, pPixel -= nScreenWidth, pTileData += 32) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; CLIPPIXEL(31, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(31, 0, nMaskColour)); CLIPPIXEL(30, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(30, 1, nMaskColour)); CLIPPIXEL(29, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(29, 2, nMaskColour)); CLIPPIXEL(28, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(28, 3, nMaskColour)); CLIPPIXEL(27, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(27, 4, nMaskColour)); CLIPPIXEL(26, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(26, 5, nMaskColour)); CLIPPIXEL(25, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(25, 6, nMaskColour)); CLIPPIXEL(24, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(24, 7, nMaskColour)); CLIPPIXEL(23, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(23, 8, nMaskColour)); CLIPPIXEL(22, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(22, 9, nMaskColour)); CLIPPIXEL(21, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(21, 10, nMaskColour)); CLIPPIXEL(20, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(20, 11, nMaskColour)); CLIPPIXEL(19, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(19, 12, nMaskColour)); CLIPPIXEL(18, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(18, 13, nMaskColour)); CLIPPIXEL(17, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(17, 14, nMaskColour)); CLIPPIXEL(16, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(16, 15, nMaskColour)); CLIPPIXEL(15, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(15, 16, nMaskColour)); CLIPPIXEL(14, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(14, 17, nMaskColour)); CLIPPIXEL(13, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(13, 18, nMaskColour)); CLIPPIXEL(12, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(12, 19, nMaskColour)); CLIPPIXEL(11, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(11, 20, nMaskColour)); CLIPPIXEL(10, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(10, 21, nMaskColour)); CLIPPIXEL( 9, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 9, 22, nMaskColour)); CLIPPIXEL( 8, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 8, 23, nMaskColour)); CLIPPIXEL( 7, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 7, 24, nMaskColour)); CLIPPIXEL( 6, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 6, 25, nMaskColour)); CLIPPIXEL( 5, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 5, 26, nMaskColour)); CLIPPIXEL( 4, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 4, 27, nMaskColour)); CLIPPIXEL( 3, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 3, 28, nMaskColour)); CLIPPIXEL( 2, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 2, 29, nMaskColour)); CLIPPIXEL( 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 1, 30, nMaskColour)); CLIPPIXEL( 0, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX( 0, 31, nMaskColour)); } } /*================================================================================================ Custom Height and Width Functions ================================================================================================*/ void RenderCustomTile(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth ) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL(x); } } void RenderCustomTile_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(x, StartX, nScreenWidth, PLOTPIXEL(x)); } } void RenderCustomTile_FlipX(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_FLIPX(nWidth - x - 1, x); } } void RenderCustomTile_FlipX_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(nWidth - x - 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX(nWidth - x - 1, x)); } } void RenderCustomTile_FlipY(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL(x); } } void RenderCustomTile_FlipY_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(x, StartX, nScreenWidth, PLOTPIXEL(x)); } } void RenderCustomTile_FlipXY(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_FLIPX(nWidth - x - 1, x); } } void RenderCustomTile_FlipXY_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(nWidth - x - 1, StartX, nScreenWidth, PLOTPIXEL_FLIPX(nWidth - x - 1, x)); } } /*================================================================================================ Custom Height and Width Functions with Masking ================================================================================================*/ void RenderCustomTile_Mask(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_MASK(x, nMaskColour); } } void RenderCustomTile_Mask_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(x, StartX, nScreenWidth, PLOTPIXEL_MASK(x, nMaskColour)); } } void RenderCustomTile_Mask_FlipX(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_MASK_FLIPX(nWidth - x - 1, x, nMaskColour); } } void RenderCustomTile_Mask_FlipX_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + (StartY * nScreenWidth) + StartX; for (int y = 0; y < nHeight; y++, pPixel += nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(nWidth - x - 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(nWidth - x - 1, x, nMaskColour)); } } void RenderCustomTile_Mask_FlipY(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_MASK(x, nMaskColour); } } void RenderCustomTile_Mask_FlipY_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(x, StartX, nScreenWidth, PLOTPIXEL_MASK(x, nMaskColour)); } } void RenderCustomTile_Mask_FlipXY(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { for (int x = 0; x < nWidth; x++) PLOTPIXEL_MASK_FLIPX(nWidth - x - 1, x, nMaskColour); } } void RenderCustomTile_Mask_FlipXY_Clip(unsigned short* pDestDraw, int nWidth, int nHeight, int nTileNumber, int StartX, int StartY, int nTilePalette, int nColourDepth, int nMaskColour, int nPaletteOffset, unsigned char *pTile) { uint32_t nPalette = (nTilePalette << nColourDepth) | nPaletteOffset; pTileData = pTile + (nTileNumber * nWidth * nHeight); unsigned short* pPixel = pDestDraw + ((StartY + nHeight - 1) * nScreenWidth) + StartX; for (int y = nHeight - 1; y >= 0; y--, pPixel -= nScreenWidth, pTileData += nHeight) { if ((StartY + y) < 0 || (StartY + y) >= nScreenHeight) continue; for (int x = 0; x < nWidth; x++) CLIPPIXEL(nWidth - x - 1, StartX, nScreenWidth, PLOTPIXEL_MASK_FLIPX(nWidth - x - 1, x, nMaskColour)); } } #undef PLOTPIXEL #undef PLOTPIXEL_FLIPX #undef PLOTPIXEL_MASK #undef CLIPPIXEL /*================================================================================================ Zoomed Tile Functions ================================================================================================*/ void RenderZoomedTile(unsigned short *dest, unsigned char *gfx, int code, int color, int t, int sx, int sy, int fx, int fy, int width, int height, int zoomx, int zoomy) { int h = ((zoomy << 4) + 0x8000) >> 16; int w = ((zoomx << 4) + 0x8000) >> 16; if (!h || !w || sx + w < 0 || sy + h < 0 || sx >= nScreenWidth || sy >= nScreenHeight) return; if (fy) fy = (height-1)*width; if (fx) fy |= (width-1); int hz = (height << 12) / h; int wz = (width << 12) / w; int starty = 0, startx = 0, endy = h, endx = w; if (sy < 0) starty = 0 - sy; if (sx < 0) startx = 0 - sx; if (sy + h >= nScreenHeight) endy -= (h + sy) - nScreenHeight; if (sx + w >= nScreenWidth ) endx -= (w + sx) - nScreenWidth; unsigned char *src = gfx + (code * width * height); unsigned short *dst = dest + (sy + starty) * nScreenWidth + sx; for (int y = starty; y < endy; y++) { int zy = ((y * hz) >> 12) * width; for (int x = startx; x < endx; x++) { int pxl = src[(zy + ((x * wz) >> 12)) ^ fy]; if (pxl != t) dst[x] = pxl | color; } dst += nScreenWidth; } } /*================================================================================================ Tile with Transparency Table Functions ================================================================================================*/ void RenderTileTranstab(unsigned short *dest, unsigned char *gfx, int code, int color, int trans_col, int sx, int sy, int flipx, int flipy, int width, int height, unsigned char *tab) { int flip = 0; if (flipy) flip |= (height - 1) * width; if (flipx) flip |= width - 1; gfx += code * width * height; for (int y = 0; y < height; y++, sy++) { if (sy < 0 || sy >= nScreenHeight) continue; for (int x = 0; x < width; x++, sx++) { if (sx < 0 || sx >= nScreenWidth) continue; int pxl = gfx[((y * width) + x) ^ flip] | color; if (tab[pxl] == trans_col) continue; dest[sy * nScreenWidth + sx] = pxl; } sx -= width; } }
[ [ [ 1, 1962 ] ] ]
95ee279e89c307c792b07dd9a802c133e624a2e6
0d5c8865066a588602d621f3ea1657f9abb14768
/dgate.cpp
4da0ffc9c7cfe0bfa6d6e6e3ea9ed61bf39be7c9
[]
no_license
peerct/Conquest-DICOM-Server
301e6460c87b8a8d5d95f0057af95e8357dd4e7c
909978a7c8e5838ec8eb61d333e3a3fdd637ef60
refs/heads/master
2021-01-18T05:03:42.221986
2009-06-15T14:00:15
2009-06-15T14:00:15
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
522,690
cpp
/* MvH 19980327: Disable logfile for speed and save disk MvH 19980327: -! Enables logging to Personal pacs console; RunServer works; -p breaks MvH 19980327: All printf's to systemdebug MvH 19980320: Integrated dumppacs code here for convenience MvH 19980320: Fixed -p option; SaveToDisk returns filename, printed in stats MvH 19980320: Documented and added print of usage MvH 19980404: Added test options, SQL config option and command line specified console pipe/udp MvH 19980409: added FileCompressMode option; use local save to disk code instead of pdu member MvH+LJZ 19980409: Return on failed GenerateFileName in SaveToDisk MvH 19980409: Cleaned up nki private compression code and allow >15 bit differences MvH 19980410: Added run length encoding for equal pixels to compressor; fix 3-byte case MvH 19980415: Cleaned up the messages; -! does not enable debug; do not enable accessupdates (use aroute) MvH 19980618: Some work on manual and database layout listing MvH 19980621: Added -z option: zap patient MvH 19980624: Comm test also produces systemdebug and long text output; added \n to some output MvH 19980625: SaveDicomDataObject in loadddo.cpp supports NKI compression MvH 19980704: Added some test code for counting disk space and renaming device for patient MvH 19980705: Added CACHE devices in free store check; added FindPhysicalDevice (searches for file) MvH 19980709: Added archiving options: -as, -au, -ab, -ac, -ad MvH 19981217: Temporary use PDU.Save... code for testing DICOM objects (does not compress) MvH 19981218: Temp use Pdu.Load as well (no compression) MvH 19981228: Disabled ljz's code until it has been completed ljz 19990108: Reenabled ljz's code: Replace uncompressed by compressed pixeldata VR in SaveToDisk (it seemed to work anyway...) MvH 19990109: Removed some commented out code; added comments for alternative load and save routines Added Regen of specified device MvH 19990110: Added n, for MAGn, as parameter in -as and -ab archiving options (default all) exit(1) on failure MvH 19990111: Fixed exit code on -ar option MvH 19990117: If the filename is *.dcm (depends on FileNameSyntax) use uncompressed chapter 10 format ljz 19990317: Added NKI-private stuff MvH 19990628: Temporary enabled debug in -!nnnn option MvH 19990630: Added MIRROR option; disabled debug in -!nnnn option MvH 19990707: Fixed MIRROR option; added MIRROR message; added check on FindPhysicalDevice result ljz 19990817: Added ability to spawn ExportConverters at the end of SaveToDisk MvH 19990827: Optimized read of slices: cache a DB to pass to GetFileName (10% faster) ljz 19991117: Added parameter FileCompressMode to in nki_private_compress call mvh 20000318: Added private command object 9999, 0300 = print to console Added private command object 9999, 0400 = force C-Echo to be 'silent' (no log) Display C-Move Destination; print time info about threads ljz 20000323: Serious fix: MainThread 'hangs' when several associations occur simultaneously, caused by compiler-optimisation. Solution: DriverApp.Lock should be 'volatile'. mvh 20000329: On request by ljz: designed crash of server if silent VR receives 'DEAD' ljz 20000501: Compare dicom modality with UPPER-case ini-file setting (ExportConverters) ljz 20000221: Initialize TroubleLogFile and UserLogFile; log C-STORE and C-MOVE ljz 20000703: Logging of trouble now starts with '***' mvh 20000703: Exclude archival messages from trouble log; removed force dcm code mvh 20001104: Added WINAPI to thread routines mvh 20001105: Replaced malloc by new where a mix could occur (vr->data) Made compilable for MSC and BC and WC using some #ifdefs Changed order of verification and store; better localized new/delete DDO more mvh 20001106: Run-time load odbcinst routine for BC and WC, use spawn... i/s/o _spawn... mvh 20001106: Use delete [] operation for vr->Data mvh 20010328: Added -av: verify mirror disk mvh 20010415: Added DeleteSeries, DeleteStudy and DeleteImage routines and -f options mvh 20010416: Added -f options: -feFile = enter MAGN file into DB, -fdFile = delete file from DB -faFile = add (also makes copy) file into server, -f?=ask UID of file, -fu = generate UID, -fcNEWPATID,file = modify patient ID of image file (moves file!) NOTE: -fc is irreversible in the sense that if a portion of a study/series is changed and changed back it winds up as a different study/series. This occurs because the UIDs must be changed for each image modification. This problem does not occur when a whole series or study is changed mvh 20010417: Simplified code to change uids to allow easy extension to referenced SOPs Check after load on common UIDs to avoid accepting dropped non-dicom files NOTE: ChangeUIDinDDO should also change sequences and referenced SOPs (0008,1155) mvh 20010418: Fix in above change mvh 20010418: Changed names of database fields in UIDMODS - did not work on msaccess mvh 20010419: Added -fk option: copy image file to other patient ID (as -fc but no delete) Added version number 1.3.9 to command line help mvh 20010429: Added -fz option: zap file from server and database mvh 20010430: Some work on read ahead thread: note that thread must not use any pointer copy! mvh 20010502: Made read ahead thread working; fixed thread counter; fix odbc option: strings too short mvh 20020506: Fixed handle leak in read ahead thread mvh 20020507: Fixed memory leak in read ahead thread; kbhit() test #ifdef DO_LEAK_DETECTION mvh 20010509: Added RenameDevice is -ae option ljz 20010730: Replaced parameter argv[0] of ExportConverters to proper value mvh 20010829: Added ExportStationName as export filter; default Export... value set to "*" Made export comparisons case insensitive; added special 'forward to AE' ExportConverter Version to 1.3.10 mvh 20010831: Added extended syntax for exportconverters with %f=filename, %m=modality, %s=stationname, %b=file base name, %p=file path; Also allows 'copy %f destination', but for windows NT only (uses cmd.exe) Added ExportFilter option that uses an SQL statement to filter. mvh 20010901: Added a simple queue to process exportconverters asynchroniously mvh 20010901: Create a queue for each converter; queue mirror copy requests mvh 20010902: Added %o = SOP; %n = newline; added the following hard coded converters: append "text" to file; write "text" to file; copy file to file; copy file to dir ljz 20010904: Re-entered change of 20010730 ljz 20010905: Fix: After 'SaveToDisk', do not free pDDO mvh 20011109: Fix: made ExportConverter stuff case insensitive Note: empty filter tests for empty contents - this is not the same as '*' Released 1.3.10 mvh 20011110: Note: in release 1.3.10, the " to " in e.g., write "%f%n" to file must be lowercase mvh 20011115: Made " to" case insensitive; Added *** before some error messages for better logging Removed cache db: would hang the server if SQL has gone down and up. Now use one DB per thread which is passed to the read ahead thread = fast too! ljz 20011207: Added extra errormessage when creation of datasource fails mvh 20020109: Disabled this code for watcom or borland (instead of run-time loading an address) mvh 20020314: Implemented ignore of C-CANCEL request for ADAC NM (was error before) Blocked out SQLInstallerError call; does not compile on clinical MS4.2 mvh 20020413: Added some notes about thread safety and db's: The serverchild is not thread safe when reading and writing is done on the same association. mvh 20020415: Added -atDEVICE option: sanity check of images on disk; version to 1.3.11 mvh 20020416: Made UID generator configurable through UIDPrefix in dicom.ini; made time print unsigned mvh 20020422: Sleazy fix of ModifyPatID: time(null) created same UID: now wait 1 s per changed file mvh 20020426: Generate filename no longer gives an error: is done at higher level mvh 20020428: Only serious error messages use *** in message mvh 20020428: Added FAILSAFE_STORAGE: tries to save incoming files even when DB errors occur mvh 20020429: Put SaveToDisk in myUnknownStorage: pass DB failures to caller Disabled FAILSAFE_STORAGE: any storage failures should now be detected by client mvh 20020508: Do not rewrite image not on MAG but it is not an error (warning is generated earlier) mvh 20020520: Added -gSERVER,DATE option: grab images on date from remote server mvh 20020521: fix displaying junk filename when rewriting image not on MAG ljz 20020522: Fix in SetStringVR: strings must be padded with a space mvh 20020529: -i and -r now have mode parameter (0=normal and default, 1=simple, e.g., for DBASEIII) ljz 20020531: In 'QualifyOn', support case-sensitive call to 'GetACRNema', but make AE-Title uppercase after retrieving IP and port. ljz 20020613: Better handling of Compression ON/OFF in 'SaveToDisk' Fixed crash in DeleteImageFile (twice free of VR->Data) mvh 20020613: compress to specified mode, check (de)compress result, decompresses data before forward; added 'export compressed to AE' export; -fa has optional ,NEWPATID syntax; mvh 20020802: Simplified rmdir code and allow multiple subdirectories in rmdir and mkdir code Version to 1.3.12 (unreleased) mvh 20020804: Use PATHSEPCHAR where possible mvh 20020807: Changed SaveToDisk order: only make patientdir when DB save succeeded mvh 20020812: Added skeleton of printer support mvh 20020816: Added color imagebox; Save incoming print DDO as file mvh 20020819: UIDs of imageboxes end on rows.cols.position for easy print handling mvh 20020819: Fix in delete unexistent mirror files for changepatientUID Extract pixel data from sequence in ImageBox; added sleep(10) in -fk option mvh 20020819: Added better UID generation (but gets close to 64 chars) mvh 20020821: Fix printer UID generation; display page orientation and film #; shorter info mvh 20021016: Added (indexed) patid to exportfilter query and getfilename for speed; The option tests for rev5 db or higher; increase 64 strings to 66; Note: the GrabImagesFromServer option does not yet pass patid to the query (i.e., will be slow with non-odbc driver) mvh 20021017: Control NeedPack from here; added -c option: set UID counter at startup Removed Sleep from anonimize options; do not re-create UIDMODS mvh 20021018: Pass NoKill through GenerateFilename for interactive DGATE mvh 20021028: Fix query on study in PatientStudyOnlyQuery (did an image query) mvh 20021105: Revamped read-ahead thread logic to try fix rare crash where ratd->DDOOutPtr became NULL mvh 20021115: Use Generic style retrieve classes with NKIqrsop code instead of older qrsop code Advantages: read ahead thread used, and allows print of error messages from C-MOVE Required changes such that ratd->pcdo can be NULL. mvh 20021121: Disabled read-ahead thread for time being mvh 20021212: Also loop ServerApp.Server(Port) in threaded mode server mvh 20021213: Re-entered fix by Hanne Kooy: compressed forwarding had extra ; mvh 20021213: Re-enabled use of generic query classes with read-ahead thread; but made read-ahead thread configurable with "EnableReadAheadThread" Made grab query faster by including date - note grab is independent of FixPhilips mvh 20021215: Found read-ahead thread problem reported by Aaron Cann - missing Sleep in wait for slices mvh 20021223: Version to 1.4.1 pre-release; added in dgatefn forbidden filename chars suggest by Thomas Buerer mvh 20030113: Removed loop ServerApp.Server(Port): gave endless loop error messages ljz 20030120: Added cleanup-code when DO_LEAK_DETECTION is defined for easy leak checking mvh+ljz 20030205: Fix bug found by Frank-Andre Siebert: read ahead thread crashed when ID or SOP is missing Also fix 2 other potential missing VR problems mvh 20030228: Fixed bug reported by Jeff Bacbcock: series retrieve from E-film crashed (patid not passed) ljz 20030424: Version to 1.3.12 Changed calls to obsolete PDU.Write(&DDO) In 'SaveToDisk' the call to PDU.SaveDICOMDataObject now has parameterDICOM_CHAPTER_10_EXPLICIT (which in writes IMPLICIT files iff not compressed) ljz 20030606: Fixed incremental counter when creating UIDs or generating filenames Fix: QueryRetrieveLevel is mandatory for a QueryResponse mvh 20030625: Fix NGET of BasicPrinterSOPClass ljz 20030625: Fix in above fix mvh 20030627: Adapted for MSC4.2; Finally really fix NGET of BasicPrinterSOPClass (wrong UID used) mvh 20030629: Added -nd, -nc, -jd and -jc options: (de)compress NKI; (de)compress JPEG (used OFFIS executables) mvh 20030630: Started on compression for dropped, incoming, transmitted; NKI vr 0x9999,0x700=custom compression Added 'forward compressed as xx to ...' mvh 20030701: QualifyOn now also has compression parameter mvh 20030703: Moved compression code to nkiqrsop; dgate -j-xx and -j*xx = test compression options Removed "forward compressed to" because "forward compressed as .. to" is better. Note that FileCompressMode is now obsolete. KNOWN BUG: JPEG compressed images may be rewritten as V2 (when written originally as NKI) which are then not correctly read. mvh 20030704: Made that FileCompressMode parameter still works even though is obsolete Moved faulty delete DDO after SOPUnknownStorage.Read mvh 20030705: Added check of Tranfer Syntax next to extension for save type; ProcessDDO takes **DDO mvh 20030706: Use dgate.dic; Attach VRType to PDU's for implicit little endian support; small fix in dump code mvh 20030709: Printer support fix; version to 1.4.2; added SendUpperCaseAE parameter (default 0) ljz 20030730: Force ImplicitLittleEndian, ExplicitLittleEndian and ExplicitBigEndian objects that must be stored in Chapter10 format, to ImplicitLittleEndian. mvh 20030815: Version to 1.4.3 mvh 20030905: Allow longer filenames mvh 20030910: Added check on rights to write (trouble) log file and printer_files in MAG0 mvh 20030921: Allow write to any MIRROR if MAG is full; added -ff# option: delete until # MB free mvh 20030922: Added StorageFailedErrorCode (default 0x110 = 272 decimal = failed processing) Added ExportCallingAE and ExportCalledAE export filters (also %u=SCU, %c=calledAE in converter) mvh 20040401: Version to 1.4.4; pass status pointer to compress routines mvh 20040402: Delete DDOptr when SaveToDisk cannot write but does not give an error Added "Cannot rewrite jpeg/rle image in v2 format" check Use system DSN for ODBC (easier login) mvh 20040406: Always use EXPLICIT syntax for jpeg, fix v2 always use DUMP mvh 20040426: Version to 1.4.4a mvh 20040520: Version to 1.4.4b mvh 20040523: Added patient ID to speed GetFileName for single slice move ljz 20040602: Fix: 'forward compressed as' always failed mvh 20040528: Set NeedPack (controls DbaseIII indexing) for regen, archive, maintenance; Version to 1.4.4c mvh 20040528: Added built-in maintenance commands through silent VR in ECHO; pass patid in DeleteImageFile mvh 20040530: extract (DBF only) to database like XDicomImages in same directory; Version to 1.4.5 mvh 20040601: Added deletestudy, deleteseries and packdbf maintenance commands mvh 20040605: packdbf maintenance command sets NeedPack to 3: forces pack mvh 20040606: fix rewrite to not MAG (JUKEBOX) was NOT ignored mvh 20040607: Merged fix ljz 20040602; do not allow rename and delete with empty name mvh 20040610: Added maintenance server tasks for archival and regeneration mvh 20040612: Added indexdbf maintenance server task mvh 20040614: dgate command line maintenance options use NeedPack=5: non-threaded index generation Added -am option: move (all) device data; to move selected data use -amMAG0.Archiving,MAG1 mvh 20040624: Version to 1.4.5a mvh 20040626: Pass study and series UID to getfilename; version to 1.4.5b; Fixed leak of pats array mvh 20040713: Version to 1.4.6 mvh 20040805: Fix in C-MOVE for single file (fix from ljz); version to 1.4.6b ljz 20040909: Increased length of ExportFilter (was 64, now 510) mvh 20041020: Added mergeseries(file) and mergestudy(file) maintenance commands, silenttext to 1024 mvh 20041101: Added deletesopfromdb maintenance command; version to 1.4.7 mvh 20041103: called, e.g., AE~nj overrides IncomingCompression to nj mvh 20041108: Added $c test compression mode (alt-drop files with $c as patient ID tests compression modes) mvh 20041109: Added $tSERVER test compressed forward; some fixes in forward compressed to (server name read wrong) $s tests all filename syntaxes mvh 20041112: Added $rN N times repeated entry test, and $tN which enters image N time each on its own thread mvh 20041128: Added -^file: log to file (timestamped) instead of to server console; -#file: same with debug mvh 20041129: Added silent commands debuglog_on and log_on to set logging to UDP or file Added silent command read_amap to re-read acrnema.map without restarting the server mvh 20050102: Small modifications to allow compile through total.cxx mvh 20050107: Added code to hold and retry queued forwards and mirror copies when failed: After failed export/copy, start storing entries in file ExportFailuresN (CopyFailures) if a new export/copy is requested >1 minute after last failed one, try again if queue is empty, >100 seconds after last fail, try export/copy stored ones processing queued entries has priority over processing stored entries mvh 20050107: Version to 1.4.8; modifications for linux compile mvh 20050108: Added server PORT# to fail files, so that multiple servers on different ports do not share files mvh 20050109: Added configurable TCPIPTimeOut, FailHoldOff, RetryDelay and QueueSize mvh 20050109: Adapted thread code for linux; still need to implement WaitForSingleObject mvh 20050111: Added ctype.h (for mingw) mvh 20050118: Linux: crudely implemented WaitForSingleObject; detach pthreads to avoid leaks; crudely implemented export converter apps mvh 20050119: Added grabimagesfromserver, regendir and makespace server commands dgate -- sends server commands to other running server; adapted manual mvh 20050121: Small updates to manual mvh 20050124: Replaced BackGroundExec with simpler system() for Linux; added query server command, e.g., dgate "--query:DICOMpatients|patientid,patientname,patientsex|patientsex='F'|%s %s %s|t.t" Added read_ini: server command to reread dicom.ini; changes most config except: TCPPort (busy), UseBuiltInDecompressor (cached) and FileNameSyntax (cached) mvh 20050130: added get_param, get_freestore, get_amap, get_sqldef that respond through echo-response also: get_sop, get_transfer, get_application, get_localae, get_remoteae, get_dic, forward added: dump_header (to file), convert_to_gif (to file); adapted query (to file) where file="cgi" for stdout in cgi/mime mode, file="" to send to stdout as is most GUI commands can now pass PatientID|SOPInstanceUID instead of filename of dicom object added put_amap, write_amap, put_sop, put_transfer, put_application, put_localae, put_remoteae, put_param. Note: get/put_param work through disk (read_ini activates), get/put_amap through memory (write_amap writes to disk), get/put_sop etc read from memory and write to mem and disk. mvh 20050204: Added delete_param, delete_amap and fix cgi output (double \n) mvh 20050204 most GUI commands can now pass PatientID|?*:SOPInstanceUID; added delete sop etc commands More fixes in cgi data passing VR vr() is mostly wrong; use VR *vr=new VR() mvh 20050205: Allow up to 16 output fields in query:, repeat queried fields over all 16 outputs Added counters for server status; start on display_status server command mvh 20050206: More work at display_status, renamed testtable to xtesttable: default not opened Access ObjectFile and DeviceName through query instead of with GetFileName up to 3 x faster!! Also fixes potential leak in read ahead thread: pats, series and studies not always freed Allow up to 32 cgi query outputs, tidied dump layout, start on web interface (put dgate and ini in cgi-bin) mvh 20050207: Added query2 option: limits number of output rows as asked; gui command not counted as association Some more work for web interface mvh 20050210: Adapted web interface queries such that they run on sql server mvh 20050212: Removed need for thread local storage; automatically adapt dgate extension in cgi scripts depending in OS mvh 20050213: Added more parameters to server configuration web page mvh 20050214: Added update button to server config (updateconfig page to be implemented) ljz 20050215: Fix in LoadForGUI: Drag 'n' drop of files in the server did not work anymore Fixed dgate crash in case of failure in 'recompress()' (pDDO=NULL when OFFIS failes) mvh merged mvh 20050327: Added rudimentary gz unzip support for dropped files (uses 7za.exe) mvh 20050401: Start on Modality WorkList Support mvh 20050404: List End/Start sequence db types (only supported for worklist) mvh 20050411: Fix incorrect space after filename and device in C-MOVE internal query mvh 20050414: Added addrecord server command: for now only option to enter worklist entries mvh 20050603: Fix servercommand query(2) for empty where part mvh 20050825: Fix web interface queries for sql server (were OK for dbase) mvh 20050826: More work on web interface and added worklist there; deleterecord command mvh 20050827: Fixes in addrecord and query commands, editworklist,saveworklist,deleteworklist mvh 20050829: More fixes in web interface, disable caching for most/all? of it mvh 20050831: Allow command line length of up to 4096, allow edit all worklist database fields mvh 20050901: Removed invalid cache-control: cache; added WorkListMode:0= off, 1=optional, 2=compulsory mvh 20050902: Read db config for worklist edit page in web interface; use generic webpages for db edit Added HL7Tag in DumpDD mvh 20050903: Added 'simple' loadhl7: server task implementation and HL7->DICOM translation Also addimagefile will enter HL7 files into the server, i.e., drag and drop works Fix some web queries for sql server with denormalized tables mvh 20050904: Some more tweaks to hl7 code; max query formats to 48; max format to 8192 mvh 20050905: Auto split HL7 subfields and repeats without using a list mvh 20050907: Merged change by Hans-Peter Hellemann: fixes extension problem for linux web interface for some browsers mvh 20050908: Protect convert_to_gif when file not found mvh 20051121: Recompute SQLResultLength because it does not work in PostGres BindField mvh 20051123: put in #ifdef POSTGRES mvh 20051208: put in #if 0 (fixed in odbci.cpp); start on virtual server: will grab images from other server as needed in read-ahead thread: when in db but not on disk; for now use rat also for single image access to avoid code duplication mvh 20051209: Start on virtual query: image (!) query is passed to other server, results populate db mvh 20051210: Added "vX" incomingcompression (stores dbf but not image; forwarding disabled) Added virtual queries on all queries and moves: now works as transparant file cache Added VirtualServerFor0..9 configuration entries: server merges own data with these AE's Added CacheVirtualData control; if set data not deleted after use (db kept for now) mvh 20051211: Fix: override query level in virtual query mvh 20051212: Store virtual server # in device; saved on query, used when retrieving, stripped when storing mvh 20051214: Use different sleep lenghts under linux - not all sleep(0); small fix in virtual server mvh 20051215: Implemented a linux version of Sleep using nanosleep mvh 20051217: Use new VR::ReAlloc method to replace data in VR; added quit: command mvh 20051218: Use ReplaceVR instead of Push in anonymize etc; also changes in sequences Version to 1.4.10; show version and exe date in startup log Do not start mirror copy queue unless it is needed; show some thread startup info Added -b = NOTHREAD: run server as single process, useful for debugging and profiling Fixed doc of --regendir: command mvh 20051219: Fixed several small leaks - as tested with Linux malloc_stats mvh 20051222: Started on bypass server for virtual query - not functional yet (cleanup required) Removed debugVR logic: errors should now list DCO mvh 20051228: Fix virtual device logic for VirtualServerFor0; Cleanup vr's and duplicates when bypassing server for virtual query, seems functional mvh 20051229: NonDestructiveDumpDICOMObject now also list sequences; DebugLevel>0 lists DCO, >1 lists query DDO; fixed leaks in virtual query and some others mvh 20051230: Added --debuglevel: command, small fix in NonDestructiveDumpDICOMObject mvh 20060103: Small fix in virtual query; disabled virtual query for worklist; debuglevel 3 shows some query results mvh 20060123: Added patient/study/seriesfinder (server parameter ignored for now, later for virtual servers etc) mvh 20060125: Added serieslister (server parameter ignored for now, later for virtual servers etc) mvh 20060128: Renamed to imagelister, added serieslister mvh 20060131: Sort filenames from imagelister on ImageNumber (0020,0013) mvh 20060226: Version to 1.4.11 mvh 20060228: Small fix in isxdigit thanks to ljz mvh 20060311: Use ReplaceVR in virtual query - level was sent twice (thanks David Lang) Added WEBReadOnly flag mvh 20060317: Support calledae and callingae in filenamesyntax - for virtualquery called is always MYACRNEMA mvh 20060324: Strip group 2 from outgoing c-stores if not compression "as" or "is" mvh 20060328: Improved forwarder, always propose Verification and use IsAbstractSyntaxAccepted(iUID) to test if host accepts image mvh 20060402: Fix hang condition when a file failed to read in the read-ahead thread mvh 20060402: Do not remove transfer syntax prior to dcmdjpeg/dcmcjpeg (here in test recompress only) mvh 20060405: Tried fix for multiple moves on same assoc (thanks Andrej Savelov) mvh 20060405: Added message when IOD fails to read mvh 20060603: Fix crash when started as dgate -v: empty statbuf mvh 20060607: Finally fixed multiple moves on same assoc (thanks Andrej Savelov and Fred Röhner) mvh 20060618: Renamed dfilecopy and define ODBC_ADD_SYS_DSN if needed mvh 20060619: Set version to 1.4.12alpha1 mvh 20060621: Added clonedb: command; transfer FULL db from other server to this one using virtualquery mvh 20060628: AddToDatabase has JustAdd parameter: skip one unnecessary query mvh 20060701: Speeded filter string handling mvh 20060702: Pass DB to GenerateFilename to avoid zillions of db open and closes mvh 20060704: Print number of records found in all queries mvh 20060708: Set version to 1.4.12alpha mvh 20061126: Moved servertask temporary files to MAG0/printer_files; protected query: and query2 against empty input mvh 20061126: Experimental forwarding on same association: close unused association after 5 seconds Clean collected sopclasses after one hour of inactivity Note 1: there is a problem with AReleaseRQ: do not use in this task Note 2: maximal 20 forwarders have a remaining association mvh 20061127: Added ForwardAssociationLevel (PATIENT, SERIES, STUDY, IMAGE, SOPCLASS; default STUDY), ForwardAssociationRefreshDelay (default 3600 s), and ForwardAssociationCloseDelay (default 5 s) Limit maximum number of ExportConverters to MAXExportConverters=20 (for static arrays used in forwarders) Forwarders keep association open as long as UID at ForwardAssociationLevel does not change. Show filename in forward log; document where fixkodak should operate for virtual queries mvh 20061128: Added ForwardAssociationLevel GLOBAL: use association until timout or incompatible Close ForwardAssociation after send when ForwardAssociationLevel is IMAGE mvh 20061129: VirtualServerForN may be "server,FIXKODAK" to clean queries (add 0) and their response (remove 0) Hardcoded filters for exportconverters (modality, called, calling, station) can now match e.g., RT* mvh 20061130: Pass series and study in virtualserver outgoing c-move mvh 20061213: Fixed nasty bug in query2 and TestFilter: Query without bindfield overwrites previous bound strings! Maybe was problem causing crash on linux with query2: and problem with option -g reportedly stopping incorrectly mvh 20061219: Version to 1.4.12 mvh 20061231: Added ForwardAssociationRelease to allow testing reconnect problem (default 0 = just hangup) mvh 20070103: FixKodak blocks *xxxx wildcard virtual queries on date (not allowed in Kodak) mvh 20070103: Version to 1.4.12b; start on ImportConverters e.g., <set 0008,1040 to "%V0008,0080"> mvh 20070104: ImportConverters %QP %QS %QE %QW; <destroy> <delete xxxx,yyyy> <save to filename> Added %% and %i to Export and Import converters mvh 20070105: <set 0008,1040 if "...">, <setifempty 0008,1040 to "...">, <setifempty 0008,1040 if "..."> Import/export converters only report when syntax OK and report when action is void Added %Vxxxx,yyyy to export converters and %d(date/time) to import and export converters An import/export converter can thus be used to extensively log incoming images Added import converters: <stop>, <if "string">, <ifempty "string">, <nop> (also export) Added general purpose variables x, y, z (read as %x, %y, %z) to import converters Definition of number of ImportConverters now unnecessary. Note: importconverter and exportconverter strings may be changed run-time in dicom.ini mvh 20070105: Some fixes in dgate --archiving options manual; fixed dgate --restoremagflags: mvh 20070107: Fix web access broken by change in odbci for dbaseIII; query must now always include spaces around = mvh 20070113: Do not store NKI compressed data in v2 format: decompress and give error message Recompress to NKI format now enables StripGroup2; Tested with $c server debug command mvh 20070117: Allow multiple rules per Export or ImportConverter separated by ; and zero or more spaces <nop> statement prints itself on console: useful for logging anything that follows mvh 20070117: Now maintain multiple connections per ExportConverter line (max 20x20 forwards) Added <stop>, <silentstop>, <if> and <ifempty> to ExportConverters; but they only affect single rule (while these would cross over to the subsequent rules in ImportConverters) mvh 20070122: Now also show free space on mirror devices mvh 20070123: Fixed TestFilter for patientid with ' mvh 20070125: Removed <if> and added <ifnotempty>, <ifequal>, <ifnotequal>, <ifmatch>, <ifnotmatch>, <ifnumequal>, <ifnumnotequal>, <ifnumgreater>, <ifnumless> as im/exportconverters Added %xxx[first,last] substring operator; and protect it against overrange <ifxxx> no longer crosses over importconverters; added {} block for im/exportconverters E.g.: ifequal "%V0008,0020[0,3]", "2004"; { forward to CONQUESTSRV3; forward to CONQUESTSRV4; } nop test Note: 1) all (also ifxxxx) statements end with ; 2) statements may begin with { or }; 3) extra spaces only allowed after ;{} and single space after , mvh 20070127: Fix {} in exportconverters. Release 1.4.12b to fix more or less critical odbci error mvh 20070131: Fix in TestFilter (quotes double); Version to 1.4.12c mvh 20070201: Added <storage MAGn> import converter: sets device to store this (new) image to (default MAG0) Fixed importconverters stop and destroy: did not break current line mvh 20070204: Added extra format starting with # to ImageFileLister: e.g. #%s:%s prints MAG0:filename mvh 20070206: Added create database: dgate -esapw name user password mvh 20070207: Fix query string bug on applyworklist found by capolan1 mvh 20070207: dgate -e name root <blank> works for mysql: root is used as admin and login Also implemented dgate -esapw name sa sapw where sapw may be empty mvh 20070210: Added CheckDuplicates to UpdateOrAddToTable; added @ in imagefilelister: replace \ by / Start on ocx based viewer integrated in cgi interface; used dicom over http: Small change in gif export; added * as separator in query/2 mvh 20070211: Added WebScriptAddress (default http://server/cgi-bin/dgate), WebMAG0Address (defaults http://server/mag0) and WebServerFor (default 127.0.0.1). Fix in cgi query parser: now loads dsize and size correctly Version to 1.4.12d mvh 20070212: Added WebCodeBase, show version in status_display, added config of which dicom server the web server connects to, added [webdefaults] section, added iconsize parameter mvh 20070213: Added : as format in imagefilelister: use to list pat:sopuid Fixed sorting problem by using adapted imagefilelister for seriesviewer Fixed default for WebCodebase; Version to 1.4.12e; Use correct case of sql table names in cgi interface: required by mysql on linux Unsolved: n3 does not always decompress correctly in dview.pas see p20401977:i47, changed default to n4 mvh 20070215: Fixed logging and added *** Association rejected message when association is rejected mvh 20070304: Added <defer> exportconverter: retry later as if connection unavailable mvh 20070305: Note: n3 problem fixed in dview.pas, version to 1.4.13alpha Allow merging of up to 1000 UIDs: set SilentText to 64000 and *uids[1000] (thanks mp) Allow named pipes for log_on and debuglog_on mvh 20070307: Work on extending extract: allow e.g. SQlite -> dbaseIII bcb 20070308: Made changes for big endian and Apple's DARWIN mvh 20070314: Fisished extract: allow e.g. SQlite -> dbaseIII in directory MAGO dbase mvh 20070315: Merged DARWIN stuff; Set TCPIPTimeOut for PDU that moves images mvh 20070316: Display defer import converter; Clumsily added <compression> import converter and improved <storage> import converter; Made <storage> thread safe Failed recompress() no longer reason to fail drag and drop; add convert_to_bmp Use | instead of , to separate patientid from file in addimagefile: Distributed , code to each of the server commands to make it more , safe Note: it is NOT a good idea to use a , in a flexible filenamesyntax Added level & window to convert_to_gif and convert_to_bmp; longer log lines for dump VR mvh 20070317: <prefetch> using new prefetch_queue, mayprocess and into_queue_unique, <preforward>, <preget> mvh 20070324: preget now <preretrieve> and avoids looping by checking orgmessageid!=0xfbad I.e., data collected by <preretrieve> does not go through import/exportconverters Added delayed exportconverters <forward patient>, <forward study>, <forward series> with optional compression Removed "forward compressed to" (without as section) as is never used Version to 1.4.13beta; delay to 10 minutes mvh 20070326: Fixed leak in <forward patient> etc. preretrieve also checking orgmoveae mvh 20070330: Change by Mark Pearson: read dicom.ini from same dir as exe in unix mode; merged more Darwin stuff Also taken over bcb's fix for the finder: studymodality was asked at patient level Also put in a more ENxxxx as command and messageid ljz 20070404: Added CommaInFilenameWorkAround() mvh 20070407: Use reentrant ctime_r when available; moved static SOPPatientRootQuery etc to stack to fix reentrancy problem: concurrent outgoing c-move of CT and MRI on different associations would share PDU causing sopclass not accepted on one. Also seems to reduce linux crash problems on multiple inbound (4 or more) C-stores. Also moved CreateBasicFilmSessionRequest etc to fix potential reentrance problem for printing. mvh 20070410: Merged CommaInFilenameWorkAround() mvh 20070413: "extract:" will just create dbase III clone of full patient DB; added "prefetch" server command mvh 20070415: Added Prefetcher option to dicom.ini: is set will aggresively preread queried patient or studies mvh 20070416: Prefetcher prints more information; use windows calls in windows for faster preread mvh 20070705: extract: uses DT_DBASEIIINOINDEX to disable indexing and packing when extracting from e.g. sqlite to dbaseiii Note: extract: non dbaseIII goes to MAG0\dbase, dbaseIII goes to DataSource mvh 20070706: Added <between "9", "17"> (9:00 to 16:59) or <between "17", "9"> (17:00 to 08:59) import/exportconverter mvh 20070709: Fixed print of clone db done mvh 20070720: Fixed problem where waiting "forward ... to " task caused high CPU load mvh 20070901: Added dgate --checklargestmalloc: mvh 20071027: Added ForwardCollectDelay for delayed forwarding (default 600 sec) mvh 20071030: Fill in called and calling AE for SaveToDisk for e.g., dropped files etc Fix %u and %c in Export and ImportConverters: called and calling AE Log flow control Export and ImportConverters only in debug mode Added retrying to delayed forwards or prefetches mvh 20071102: SetDicomErrorHandler: orderly shutdown of server on serious DICOM library errors Fixed a bug in ForwardAssociationLevel: last UID was lost when reading INI file to szTemp Added MaximumExportRetries and MaximumDelayedFetchForwardRetries (default=0 is no maximum) mvh 20071103: Version to 1.4.13; defer resets queue fails -> keeps on retrying mvh 20071104: Use local as AE for imagelister in web page instead of CONQUESTSRV1 Enable remote servers (use AE instead of 'local') in finder and lister commands Fix crash when dgate -- option gets empty filename: now lists to stdout mvh 20071114: Put --checklargestmalloc: in dgate -? mvh 20071118: Adapted for 64 bits (use SQLLEN for BindField) mvh 20071120: Fixed KodakFixer for empty patient ID (crashed on 64 bits only) Added [modality xx] and [date yyyymmdd-yyyymmdd] clauses to export [patient|study|series] to AE mvh 20071121: Added %V*GGGG,EEEE: search VR in any sequence; version to 1.4.13a Added [now -ddd+ddd] and [age -ddd+ddd] clauses to export [patient|study|series] to AE No retry on remote dicom error in forward xxx to: would retry zero records response Use study date for data, age and now clauses mvh 20071123: Made forward command case insensitive; added forward image; added get [patient|study|series|image] from AE The latter option makes preretrieve obsolete mvh 20071124: Added [sop xxx] clause to [forward|get] Reorganized exportconverter code: all converters now do % substitution; reduced code duplication Added reading of sequence items like in %V/300c,0060.0/0008,1155 or %V/300c,0060/0008,1155 Real life example (must all be one one line, max 512 characters): ifnotequal "%m", "RTPLAN"; stop; nop "tests modality = RTPLAN"; ifnotequal "%V*300a,00b2[0,1]", "A2"; stop; nop "test machine name = A2" forward to XVI_A2; nop "forwards the current recieved RTPLAN"; get study modality CT from NKIPACS; nop "collects associated CT"; get study modality RTSTRUCT sop %V/300c,0060.0/0008,1155 from NKIPACS; nop "collects associated RTSTRUCT"; forward study modality CT imagetype *AXIAL* to XVI_A2; nop "forwards associated CT"; forward study modality CT series %V(/300c,0060/0008,1155)/3006,0010/3006,0012/3006,0014/0020,000e forward study modality RTSTRUCT sop %V/300c,0060.0/0008,1155 to XVI_A2; nop "forwards associated RTSTUCT"; mvh 20071125: Fixed syntax for %V/gggg,eeee.i/*gggg,eeee (search all groups under a specified one) mvh 20071126: Start on StorageCommitment mvh 20080103: Switched to ms7 compiler; fixed forward and get date, modality, sop filters: would not supress the UIDs mvh 20080107: Fixed malformed web viewer header: worked for IE but not for other browsers Check presence of dicom.sql in web pages that need it Deal with spaces in patient IDs in web pages mvh 20080126: Check presence of dgate.dic when starting server mvh 20080129: Fix KodakFixer: wrote one byte outside VR data (pr) mvh 20080129: Added [imagetype xxxx] clause to [forward|get] (pr) mvh 20080130: Small fix in above mvh 20080205: Added experimental PadAEWithZeros flag; version to 1.4.14alpha mvh 20080210: Added experimental IgnoreOutOfMemoryErrors; Added "delete [patient|study|series|image] [date yyyymmdd-yyyymmdd] [now -ddd+ddd] [age -ddd+ddd] [modality mm] [sop xxxx] [imagetype xxxx]" export converter mvh 20080221: Added [seriesdesc xxxxx] filter and "process [patient|study|series|image] [by command]" mvh 20080222: Small fix in imagetype filter code; process by clause not part of unique check mvh 20080302: Fixed case of DICOM table names mvh 20080316: Added dgate --deletestudies:date(range) and dgate --movepatient/study/studies/series mvh 20080318: Added [series xxxx] and [study xxxxx] filters; work on web page --deleteseries/study and --moveseries/study allow patid:uid as parameter Web interface can now push and delete on series and study level, but delete is disabled in readonly web interface Version to 1.4.14beta mvh 20080319: Delete in browsers fixed?; added %v(desc)desc: search VR in given sop of same patient Example: %V(/300c,0060/0008,1155)/3006,0010/3006,0012/3006,0014/0020,000e Gives referenced CT series UID in referenced structure set from forwarded RTPLAN mvh 20080321: Fixes in browser; added graphic web setting; may be gif or bmp for now; Fix %V for non-existing items mvh 20080322: Added dgate --anonymize that uses general scripting mvh 20080323: Small fix in (local) for DcmMove: overwrote destination mvh+pr 20080404: Fixes in series and study filter (rethink naming) pr added value* match for in match() routine mvh 20080618: Added extra logging in IARQ() mvh 20080620: Only show extra logging in IARQ when assoc rejected mvh 20080816: IARQ shows which sops are accepted; and differentiates no sop from connection terminated mvh 20080817: Small layout fixes; <process with> import converter; show PDU length in log Check saving of file succeeded (thanks Jeff Bellamy and Alberto Smulders) mvh 20080819: Added experimental DT_MSTR: multi-value entry, e.g. query on 'PET' matches 'PET\CT' map 20080819: added --get_ini_param (same as get_param) and get_ini_num to list parameter by index map 20080819: Added get_ini to list all parameters in DICOM.INI mvh 20080819: Added code by map but kept original get_param for old web cgi client compatibility Version to 1.4.14 mvh 20080820: Solaris 10 fixes, and general UNIX fixes (map): configfiles may not be in current dir mvh 20080821: Default of ForwardAssociationRelease to 1; added sleep export converter mvh 20080823: Added study UID search to PatientStudyFinder; fixed DcmMove: would call local when remote adressed Added rudimentary query/move web pages mvh 20080825: query/move looks better; added "thumbs" column to local series lister; config patched to readonly added background color and display of icon (to be placed in WebCodeBase) mvh 20080826: One more fix in DcmMove, still called wrong server sometimes Do not use 0xfbad as message ID for DcmMove from web page; webreadonly defaults to true CGI viewer configurable: seriesviewer, seriesviewer2, noviewer, aiviewer mvh 20080827: Added slice number and repeat output data in ImagefileLister and SeriesUIDLister for more flexible formatting Added flexviewer: reads code from dicom.ini in web server directory mvh 20080831: Translate yyyy and yyyymm to date range in finder; further only accept valid date and date ranges Added dgate --get_amaps: lists all non wildcard entries from acrnema.map Fixed handling of patient ID with spaces in ImageFileLister mode : All undefined cgi modes can come from the cgi dicom.ini; added special and cgi script variables Lines can start with -- to start dgate, with # as comment, any other passed as HTML Added source parameter: flex pages can be read from script file Added serversideviewer: requires javascript only, nothing to install mvh 20080901: Fixed some leaks in printing and --commands; fixed --get_ini: formatting mvh 20080902: Added header option for web scripts; added some CGI environment variables */ #define VERSION "1.4.14" //#define DO_LEAK_DETECTION 1 //#define DO_VIOLATION_DETECTION 1 //#define FAILSAFE_STORAGE // max ExportConverters lines AND max forwards per line #define MAXExportConverters 20 # include "dgate.hpp" # include "nkiqrsop.hpp" # include <time.h> #ifdef WIN32 # include <io.h> # include <process.h> # include <conio.h> #else # include <unistd.h> # include <pthread.h> #ifndef DARWIN # include <malloc.h> #endif //DARWIN #endif # include <stdio.h> # include <ctype.h> # include <fcntl.h> # include <sys/stat.h> #ifdef WIN32 #if !defined(__BORLANDC__) && !defined(__WATCOMC__) # include <odbcinst.h> #endif #if defined(DO_LEAK_DETECTION) || defined(DO_VIOLATION_DETECTION) # include <crtdbg.h> #endif #endif #ifndef ODBC_ADD_SYS_DSN #define ODBC_ADD_SYS_DSN 4 // add a system DSN #endif BOOL NoThread=FALSE; // debug non-threaded #ifndef UNIX // Win32... # include <process.h> # define THREAD_RETURN_FALSE FALSE # define THREAD_RETURN_TRUE TRUE typedef BOOL ThreadRoutineType; typedef int ThreadRoutineArgType; #else // UNIX... # include <pthread.h> # include <unistd.h> # include <stdlib.h> # include <string.h> # include <signal.h> # include <sys/types.h> # include <sys/stat.h> //# include <fstream.h> # include "npipe.hpp" # define THREAD_RETURN_FALSE ((void *)NULL) # define THREAD_RETURN_TRUE ((void *)1) //# define closesocket(s) close(s) # define CloseHandle(h) void Sleep(int h) { struct timespec t; if (NoThread) return; t.tv_sec =(h/1000); t.tv_nsec=(h%1000)*1000000; nanosleep(&t, NULL); } # define eof(h) FALSE typedef void * ThreadRoutineType; typedef void * ThreadRoutineArgType; #endif // This file compiles into two different "modes". The first (DEBUG_MODE) defined will // compile into a Windows NT console application. Just run this exactly like // any other NT console app (it provides everything the service does). The second // mode (DEBUG_MODE undefined) is the service. #define DEBUG_MODE // IPC Block is a block of data which is passed from parent to child with the socket# #define IPCBlockMagic 0xafaced0a typedef struct _IPCBlock { #ifdef UNIX int Magic; #endif int Socketfd; } IPCBlock; BOOL RunServer = TRUE; // reset for regen etc char RootConfig[64] = "sscscp"; // main entry in ini file #ifndef UNIX char ConfigFile[512] = ".\\dicom.ini"; // name ini file char DicomDict[64] = ".\\dgate.dic"; // name dicomdictionary file #else char ConfigFile[512] = "dicom.ini"; char DicomDict[64] = "dgate.dic"; #endif #ifndef UNIX // for routing IODs char AutoRoutePipe[128] = "\\\\.\\pipe\\AutoRoutePipe"; char AutoRouteExec[128] = "aroute.exe"; #else char AutoRoutePipe[128] = "/tmp/AutoRoutePipe"; char AutoRouteExec[128] = "aroute"; #endif extern Array < ACRNemaAddress * > ACRNemaAddressArray; // for -a listing int DebugLevel = 0; // increased after error RTC VRType(TRUE); // VR translation table extern int FileCompressMode; extern unsigned int gl_iFileCounter; int ThreadCount = 0; // Counts total number of associations int EnableReadAheadThread=1; // to enable/disable read ahead thread int WorkListMode = 0; // use worklist to update incoming data char DroppedFileCompression[16]; // compression of dropped files char IncomingCompression[16]; // compression of incoming images char TransmitCompression[16]; // compression of transmitted images char DefaultNKITransmitCompression[16]; // default compression of transmitted images using NKI C-MOVE char ArchiveCompression[16]; // compression of images to be archived int StorageFailedErrorCode = 0x110; // returned when C-STORE fails (default failed processing) int FailHoldOff = 60; // holdoff in seconds aftre last export/copy failure int RetryDelay = 100; // delay in seconds aftre last export/copy failure for retry int QueueSize = 128; // number of entries in export/copy queue (2k per entry in memory) int ForwardCollectDelay = 600; // delay for forward patient to etc .... char VirtualServerFor[11][48]; // AE's of servers providing data for this one (cache function) + parameters int CacheVirtualData=1; // if set, keep (cache) passed through data // counters for status display int StartTime; // when dgate is started int TotalTime=0; // total run time in s int LoadTime=0; // total time loading int ProcessTime=0; // total time processing (downsize) int SaveTime=0; // total time saving int ImagesSent=0; // how many images were sent int ImagesReceived=0; // idem recieved int ImagesSaved=0; // idem saved int ImagesForwarded=0; // idem forwarded int ImagesExported=0; // executable as export converted int ImagesCopied=0; // copy as export converter int IncomingAssociations=0; // accepted incoming associations (start thread) int EchoRequest=0; // c-echo requests int C_Find_PatientRoot=0; int C_Move_PatientRootNKI=0; int C_Move_PatientRoot=0; int C_Find_StudyRoot=0; int C_Move_StudyRootNKI=0; int C_Move_StudyRoot=0; int C_Find_PatientStudyOnly=0; int C_Find_ModalityWorkList=0; int C_Move_PatientStudyOnlyNKI=0; int C_Move_PatientStudyOnly=0; int UnknownRequest=0; int CreateBasicFilmSession=0; // printer actions int DeleteBasicFilmSession=0; int ActionBasicFilmSession=0; int SetBasicFilmSession=0; int CreateBasicFilmBox=0; int ActionBasicFilmBox=0; int SetBasicFilmBox=0; int DeleteBasicFilmBox=0; int SetBasicGrayScaleImageBox=0; int SetBasicColorImageBox=0; int GuiRequest=0; // server command requests from GUI int ImagesToGifFromGui=0; int ImagesToDicomFromGui=0; int ExtractFromGui=0; int QueryFromGui=0; int DeleteImageFromGui=0; int DeletePatientFromGui=0; int DeleteStudyFromGui=0; int DeleteStudiesFromGui=0; int DeleteSeriesFromGui=0; int MovePatientFromGui=0; int MoveStudyFromGui=0; int MoveStudiesFromGui=0; int MoveSeriesFromGui=0; int AddedFileFromGui=0; int DumpHeaderFromGui=0; int ForwardFromGui=0; int GrabFromGui=0; extern int DatabaseOpen; // database activity extern int DatabaseClose; extern int DatabaseQuery; extern int DatabaseAddRecord; extern int DatabaseDeleteRecord; extern int DatabaseNextRecord; extern int DatabaseCreateTable; extern int DatabaseUpdateRecords; extern int QueryTime; extern int SkippedCachedUpdates; // entering into database levels extern int UpdateDatabase; extern int AddedDatabase; extern int NKIPrivateCompress; // compression activity extern int NKIPrivateDecompress; extern int DownSizeImage; extern int DecompressJpeg; extern int CompressJpeg; extern int DecompressedRLE; extern int RecompressTime; #ifndef ctime_r #define ctime_r(a, b) ctime(a) #endif #ifndef localtime_r #define localtime_r(a, b) memcpy(b, localtime(a), sizeof(struct tm)) #endif /* error handling for out of memory and such */ static void MyDcmError(int error, char *message, int count) { char buffer[300]; char szRootSC[64]; strcpy(buffer, "***"); sprintf(buffer+3, message, count); strcat(buffer, "\n"); OperatorConsole.printf(buffer); if (GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) { GetPrivateProfileString(szRootSC, "IgnoreOutOfMemoryErrors", "0", buffer, 64, ConfigFile); if (atoi(buffer)) return; } OperatorConsole.printf("***A fatal error occurred (out of memory) - closing server\n"); exit(1); } void StatusDisplay(FILE *f) { char TimeString[80], buf[64]; time_t T=StartTime; Database DB; int i; strcpy(TimeString, ctime_r(&T, buf)); TimeString[strlen(TimeString)-1] = '\0'; fprintf(f, "DICOM server '%s' (version %s, port %s) was started on %s\n", MYACRNEMA, VERSION, Port, TimeString); fprintf(f, "Run time (s) total %d, query %d, load %d, save %d, compress %d, process %d\n", TotalTime, QueryTime/1000, LoadTime, SaveTime, RecompressTime, ProcessTime); fprintf(f, "Associations=%d; Images sent=%d, recieved=%d, forwarded=%d\n", IncomingAssociations, ImagesSent, ImagesReceived, ImagesForwarded); fprintf(f, "Images printed=%d, in color=%d\n", SetBasicGrayScaleImageBox+SetBasicColorImageBox, SetBasicColorImageBox); fprintf(f, "Activity: Echo:%d, Find:%d, Move:%d, Unknown:%d\n", EchoRequest, C_Find_PatientRoot+C_Find_StudyRoot+C_Find_PatientStudyOnly+C_Find_ModalityWorkList, C_Move_PatientRootNKI+C_Move_PatientRoot+C_Move_StudyRootNKI+C_Move_StudyRoot+C_Move_PatientStudyOnlyNKI+C_Move_PatientStudyOnly, UnknownRequest); fprintf(f, "Images (de)compressed: NKI %d, JPEG %d, RLE %d, Downsize %d\n", NKIPrivateCompress+NKIPrivateDecompress, DecompressJpeg+CompressJpeg, DecompressedRLE, DownSizeImage); for (i=0; i<MAGDevices; i++) fprintf (f, "Space on MAG%d : %d MByte\n", i, CheckFreeStoreOnMAGDevice(i)); for (i=0; i<CACHEDevices; i++) fprintf (f, "Space on CACHE%d: %d MByte\n", i, CheckFreeStoreOnCACHEDevice(i)); if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { for (i=0; i<10; i++) if (DB.dbase_handles[i]) fprintf(f, "Database %s has %d records\n", DB.dbase_handles[i]->filename, DB.dbase_handles[i]->reccount); }; }; // Dump an association request for the status display static BOOL AbstractSyntaxEnabled(CheckedPDU_Service &p, AbstractSyntax &AbsSyntax) { UINT Index; if ( ! p.SOPUIDListCount ) return ( TRUE ); Index = 0; while ( Index < p.SOPUIDListCount ) { if ( UID ( p.SOPUIDList [ Index ] ) == AbsSyntax.AbstractSyntaxName) return ( TRUE ); ++Index; } return ( FALSE ); } void IARQ (AAssociateRQ &ARQ, BOOL showall) { char s[128]; SystemDebug.printf("A-ASSOCIATE-RQ Packet Dump\n"); memset(s, 0, 64); memcpy(s, ARQ.CallingApTitle, 16); OperatorConsole.printf("\tCalling Application Title : \"%s\"\n", s); memset(s, 0, 64); memcpy(s, ARQ.CalledApTitle, 16); OperatorConsole.printf("\tCalled Application Title : \"%s\"\n", s); memset(s, 0, 64); memcpy(s, ARQ.AppContext.ApplicationContextName.GetBuffer(1), ARQ.AppContext.ApplicationContextName.GetSize() ); OperatorConsole.printf("\tApplication Context : \"%s\", PDU length: %d\n", s, ARQ.UserInfo.GetMax()); SystemDebug.printf("\tNumber of Proposed Presentation Contexts: %d\n", ARQ.PresContexts.GetSize()); int Index = 0; while (Index < ARQ.PresContexts.GetSize() ) { PresentationContext PC; PC = ARQ.PresContexts.Get(Index); PC.TrnSyntax.ClearType = FALSE; memset(s, 0, 64); memcpy(s, PC.AbsSyntax.AbstractSyntaxName.GetBuffer(1), PC.AbsSyntax.AbstractSyntaxName.GetSize()%64 ); OperatorConsole.printf("\tPresentation Context %d \"%s\" %d\n", Index, s, AbstractSyntaxEnabled(*(CheckedPDU_Service*)(&ARQ), PC.AbsSyntax)); ++Index; if (showall) { int IndexTrn = 0; while ( IndexTrn < PC.TrnSyntax.GetSize()) { UID uid; TransferSyntax TrnSyntax = PC.TrnSyntax.Get(IndexTrn); memset(s, 0, 64); memcpy(s, TrnSyntax.TransferSyntaxName.GetBuffer(1), TrnSyntax.TransferSyntaxName.GetSize()%64 ); uid = TrnSyntax.TransferSyntaxName; OperatorConsole.printf("\t\tTransfer Syntax %d \"%s\" %d\n", IndexTrn, s, ((CheckedPDU_Service*)&ARQ)->CanYouHandleTransferSyntax(TrnSyntax)); IndexTrn++; } } } } // Help routines to allow dumping of logs after an error occurs // Test if character is alphanumerical BOOL IsAlpha(BYTE c) { if((c >= ' ')&&(c <= 125)) return ( TRUE ); if(!c) return ( TRUE ); return ( FALSE ); } // Test if all of string is alphanumerical BOOL IsDataAlpha(UINT Size, BYTE *data) { if(Size > 16) Size = 16; if(!Size) return ( FALSE ); --Size; while(Size) { if(!IsAlpha(data[Size])) return ( FALSE ); --Size; } return ( TRUE ); } static void TranslateText(char* pSrc, char* pDest, int iSize) { int i; /* Translate CR, LF and FF to escape sequences */ for (i=0; i<iSize; i++) switch (*pSrc) { case '\\': *pDest++ = *pSrc; *pDest++ = *pSrc++; break; case '\n': *pDest++ = '\\'; *pDest++ = 'n'; pSrc++; break; case '\r': *pDest++ = '\\'; *pDest++ = 'r'; pSrc++; break; case '\f': *pDest++ = '\\'; *pDest++ = 'f'; pSrc++; break; default: *pDest++ = *pSrc++; break; } *pDest = 0; } // Print data from a single dicom object BOOL PrintUDATA(UINT Size, void *data, UINT16 TypeCode, char *dest) { UINT Index = 0; unsigned char *c; UINT16 tint16; UINT32 tint32; BYTE *b; LE_UINT16 *w; char Str[512]; LE_UINT32 *l32 = (LE_UINT32*)data; LE_UINT16 *l16 = (LE_UINT16*)data; LE_INT32 *s32 = (LE_INT32*)data; LE_INT16 *s16 = (LE_INT16*)data; if(!data) { if ( TypeCode == 'SQ' ) { sprintf(dest, "Sequence Item"); return ( TRUE ); } sprintf(dest, "(empty)"); return ( TRUE ); } if ( ! TypeCode || TypeCode == 'UN' ) { switch ( Size ) { case 2: tint16 = (*((UINT16 *) data)); sprintf(dest, "(%d|%x)", (UINT) tint16, (UINT) tint16); break; case 4: tint32 = (*((UINT32 *) data)); sprintf(dest, "[%d|%x]", (UINT) tint32, (UINT) tint32); break; default: if(IsDataAlpha(Size, (BYTE*) data)) { if(Size > 256) Size = 256; TranslateText((char*)data, Str, Size); sprintf(dest, "\"%s\"", Str); break; } Index = 0; while(Index < Size) { if(Index >= 16) break; c = (unsigned char*)data; c += Index; if (isprint(*c)) sprintf(dest, "%2.2x(%c)", *c, *c); else sprintf(dest, "%2.2x", *c); ++Index; } } } else { switch ( TypeCode ) { case 'AE': case 'AS': case 'CS': case 'DA': case 'DS': case 'DT': case 'IS': case 'LO': case 'LT': case 'PN': case 'SH': case 'ST': case 'TM': case 'UI': if(Size > 256) Size = 256; TranslateText((char*)data, Str, Size); sprintf(dest, "\"%s\" ", Str); break; case 'FL': case 'FD': break; case 'AT': Index = 0; while ( Index < Size ) { UINT16 Grp, Elm; Grp = (*l16);++l16; Elm = (*l16);++l16; sprintf(dest, "(%4.4x, %4.4x) ", Grp, Elm); Index += 4; } break; case 'OB': b = (BYTE*)data; while ( Index < Size ) { if ( Index > 10 ) break; sprintf(dest, "%2.2x ", *b); ++b; ++Index; } break; case 'OW': w = (LE_UINT16*)data; while(Index < Size ) { if ( Index > 20 ) break; sprintf(dest, "%4.4x ", (UINT16)(*w)); ++w; ++Index; ++Index; } break; case 'UL': while ( Index < Size ) { if ( Index > 40 ) break; sprintf(dest, "%ld ", (UINT32)(*l32)); ++l32; Index += 4; } break; case 'US': while ( Index < Size ) { if ( Index > 20 ) break; sprintf(dest, "%d ", (UINT32)(*l16)); ++l16; Index += 2; } break; case 'SL': while ( Index < Size ) { if ( Index > 40 ) break; sprintf(dest, "%ld ", (UINT32)(*s32)); ++s32; Index += 4; } break; case 'SS': while ( Index < Size ) { if ( Index > 20 ) break; sprintf(dest, "%d ", (UINT32)(*s16)); ++s16; Index += 2; } break; } } return ( TRUE ); } // Print a single dicom object BOOL DumpVR(VR *vr, FILE *f, int iDepth) { INT Index; UINT16 TypeCode; char b[256]; char s[256]; char d[256]; if (DebugLevel<1 && f==NULL) return ( TRUE ); if (vr->Element==0) return TRUE; for (Index=0; Index<iDepth; Index++) b[Index]='>'; b[iDepth]=0; s[0] = '\0'; TypeCode = 0; TypeCode = VRType.RunTimeClass(vr->Group, vr->Element, s); PrintUDATA ( vr->Length, vr->Data, TypeCode, d ); if (f) { if(TypeCode) fprintf(f, "%s%4.4x,%4.4x %6d %c%c %-20.20s %s\n", b, vr->Group, vr->Element, vr->Length, TypeCode>>8, TypeCode&0x00ff, s, d); else fprintf(f, "%s%4.4x,%4.4x %6d UN %-20.20s %s\n", b, vr->Group, vr->Element, vr->Length, "", d); } else { if(TypeCode) SystemDebug.printf("%s%4.4x,%4.4x %6d %c%c %-20.20s %s\n", b, vr->Group, vr->Element, vr->Length, TypeCode>>8, TypeCode&0x00ff, s, d); else SystemDebug.printf("%s%4.4x,%4.4x %6d UN %-20.20s %s\n", b, vr->Group, vr->Element, vr->Length, "", d); } return(TRUE); } // Print a composite dicom object + sequences BOOL NonDestructiveDumpDICOMObject( DICOMObject *DO, FILE *f = NULL, int iDepth=0) { DICOMObject DO2; VR *vr; int Index, i; if(DebugLevel<1 && f==NULL) return ( TRUE ); while(vr=DO->Pop()) { DumpVR(vr, f, iDepth); if ( vr->SQObjectArray ) { Array < DICOMDataObject * > *ADDO = (Array<DICOMDataObject*>*) vr->SQObjectArray; Index = 0; while ( Index < ADDO->GetSize() ) { NonDestructiveDumpDICOMObject(ADDO->Get(Index), f, iDepth+1); ++Index; if (Index == ADDO->GetSize()) break; for (i=0; i<iDepth+1; i++) if (f) fprintf(f, "-"); else SystemDebug.printf("-"); if (f) fprintf(f, "\n"); else SystemDebug.printf("\n"); } } DO2.Push(vr); } DO->Reset(); while(vr=DO2.Pop()) { DO->Push(vr); } return ( TRUE ); } // Check code from dumppacs pasted here for convenience // List status of mag devices (free space) BOOL PrintFreeSpace() { int Index; OperatorConsole.printf("** MAG DEVICE CHECK\n"); OperatorConsole.printf("\n"); Index = 0; while ( Index < MAGDevices ) { OperatorConsole.printf ( "Free space on MAG Device %d := %d MByte\n", Index, CheckFreeStoreOnMAGDevice(Index)); ++Index; } Index = 0; while ( Index < MIRRORDevices ) { OperatorConsole.printf ( "Free space on MIRROR Device %d := %d MByte\n", Index, CheckFreeStoreOnMIRRORDevice(Index)); ++Index; } Index = 0; while ( Index < CACHEDevices ) { OperatorConsole.printf ( "Free space on CACHE Device %d := %d MByte\n", Index, CheckFreeStoreOnCACHEDevice(Index)); ++Index; } return ( TRUE ); } // Print Out A-MAP data struct (used for outgoing C-MOVES) BOOL PrintAMap() { UINT Index = 0; OperatorConsole.printf( "** AE / IP-PORT Map dump\n"); OperatorConsole.printf("\n"); while ( Index < ACRNemaAddressArray.GetSize() ) { ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(Index); OperatorConsole.printf("%-17s %-30s %-10s %-16s\n", AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress); ++Index; } return ( TRUE ); } // Help routine for listing SQL database configuation; sql field type string char * SQLTypeSymName( int SQLType) { switch ( SQLType ) { case SQL_C_CHAR: return("SQL_C_CHAR"); case SQL_C_DATE: return("SQL_C_DATE"); default: return("--bad--"); } return("--bad--"); } // Help routine for listing SQL database configuration; dicom object type string char * DICOMTypeSymName( int DICOMType) { switch ( DICOMType ) { case DT_STR: return("DT_STR"); case DT_MSTR: return("DT_MSTR"); case DT_DATE: return("DT_DATE (DA)"); case DT_UINT16: return("DT_UINT16 (US)"); case DT_UINT32: return("DT_UINT32 (UL)"); case DT_UI: return("DT_UI (UI)"); case DT_STARTSEQUENCE: return("Start sequence"); case DT_ENDSEQUENCE: return("End sequence"); default: return ("--bad--"); } return("--bad--"); } // Help routine for listing SQL database configuration; list one table BOOL DumpDD ( DBENTRY *DBE) { UINT Index = 0; while ( DBE[Index].Group ) { OperatorConsole.printf("0x%4.4x,0x%4.4x %10s %4d %10s %14s %10s\n", DBE[Index].Group, DBE[Index].Element, DBE[Index].SQLColumn, DBE[Index].SQLLength, SQLTypeSymName(DBE[Index].SQLType), DICOMTypeSymName(DBE[Index].DICOMType), DBE[Index].HL7Tag); ++Index; } return ( TRUE ); } // List full SQL database configuration BOOL PrintKFactorFile() { UINT Index = 0; OperatorConsole.printf( "** Database Description dump\n"); OperatorConsole.printf("\n"); OperatorConsole.printf ("--Patient Database: %s\n", PatientTableName); DumpDD(PatientDB); OperatorConsole.printf ("--Study Database: %s\n", StudyTableName); DumpDD(StudyDB); OperatorConsole.printf ("--Series Database: %s\n", SeriesTableName); DumpDD(SeriesDB); OperatorConsole.printf ("--Image Database: %s\n", ImageTableName); DumpDD(ImageDB); OperatorConsole.printf ("--WorkList Database: %s\n", WorkListTableName); DumpDD(WorkListDB); return ( TRUE ); } // Delete everything of selected patient, optionally DB only BOOL DeletePatient(char *PID, BOOL KeepImages) { VR *vr = new VR(0x0010, 0x0020, strlen(PID), (void*)PID, (BOOL) FALSE ); DICOMDataObject DDO; if (PID==NULL || *PID==0) return FALSE; if (!KeepImages) OperatorConsole.printf("Deleting patient: %s\n", PID); else OperatorConsole.printf("Deleting database entries for patient: %s\n", PID); DDO.Push(vr); RemoveFromPACS(&DDO, KeepImages); return ( TRUE ); } // Delete study BOOL DeleteStudy(char *ID, BOOL KeepImages) { VR *vr; DICOMDataObject DDO; if (ID==NULL || *ID==0) return FALSE; char *p = strchr(ID, ':'); if (p==0) { vr = new VR(0x0020, 0x000d, strlen(ID), (void*)ID, (BOOL) FALSE ); DDO.Push(vr); } else { *p=0; vr = new VR(0x0020, 0x000d, strlen(p+1), (void*)(p+1), (BOOL) FALSE ); DDO.Push(vr); vr = new VR(0x0010, 0x0020, strlen(ID), (void*)ID, (BOOL) FALSE ); } if (!KeepImages) OperatorConsole.printf("Deleting study: %s\n", ID); else OperatorConsole.printf("Deleting database entries for study: %s\n", ID); RemoveFromPACS(&DDO, KeepImages); return ( TRUE ); } // Delete studies on date (wildcards or range allowed) BOOL DeleteStudies(char *date, BOOL KeepImages) { VR *vr = new VR(0x0008, 0x0020, strlen(date), (void*)date, (BOOL) FALSE ); DICOMDataObject DDO; if (date==NULL || *date==0) return FALSE; if (!KeepImages) OperatorConsole.printf("Deleting studies on date: %s\n", date); else OperatorConsole.printf("Deleting database entries for studies on date: %s\n", date); DDO.Push(vr); RemoveFromPACS(&DDO, KeepImages); return ( TRUE ); } // Delete series BOOL DeleteSeries(char *ID, BOOL KeepImages) { VR *vr; DICOMDataObject DDO; if (ID==NULL || *ID==0) return FALSE; char *p = strchr(ID, ':'); if (p==0) { vr = new VR(0x0020, 0x000e, strlen(ID), (void*)ID, (BOOL) FALSE ); DDO.Push(vr); } else { *p=0; vr = new VR(0x0020, 0x000e, strlen(p+1), (void*)(p+1), (BOOL) FALSE ); DDO.Push(vr); vr = new VR(0x0010, 0x0020, strlen(ID), (void*)ID, (BOOL) FALSE ); } if (!KeepImages) OperatorConsole.printf("Deleting series: %s\n", ID); else OperatorConsole.printf("Deleting database entries for series: %s\n", ID); DDO.Push(vr); RemoveFromPACS(&DDO, KeepImages); return ( TRUE ); } // Delete image BOOL DeleteImage(char *ID, BOOL KeepImages) { VR *vr = new VR(0x0008, 0x0018, strlen(ID), (void*)ID, (BOOL) FALSE ); DICOMDataObject DDO; if (ID==NULL || *ID==0) return FALSE; if (!KeepImages) OperatorConsole.printf("Deleting image: %s\n", ID); else OperatorConsole.printf("Deleting database entry for image: %s\n", ID); DDO.Push(vr); RemoveFromPACS(&DDO, KeepImages); return ( TRUE ); } // Compute size of a file static int DFileSize(char *Path) { FILE *f; int res; f = fopen(Path, "rb"); if (f==NULL) return 0; fseek(f, 0, SEEK_END); res = ftell(f); /* ask position */ fclose(f); return res; } // Test file exists static BOOL DFileExists(char *Path) { FILE *f; int res; f = fopen(Path, "rb"); if (f==NULL) return FALSE; fclose(f); return TRUE; } // Load DICOM object for GUI given with filename or patientID|sopInstanceUID DICOMDataObject *LoadForGUI(char *filename) { char FullFilename[1024], Filename[1024]; char Device[32]; char *sop, *pat; PDU_Service PDU; DICOMDataObject DDO; VR *vr; PDU.AttachRTC(&VRType); sop = strchr(filename, '|'); if (!sop) sop = strchr(filename, '?'); if (!sop) sop = strchr(filename, '*'); if (!sop) sop = strchr(filename, ':'); if (sop && (sop[1] != '\\')) { *sop++= 0; pat = filename; vr = new VR(0x0008, 0x0018, strlen(sop), (void*)sop, FALSE ); if(!GetFileName(vr, Filename, Device, TRUE, pat)) { delete vr; return NULL; // not in database ? } if (!FindPhysicalDevice(Device, FullFilename, Filename)) { OperatorConsole.printf("***GUI could not find file:%s\n", Filename); delete vr; return NULL; } strcat(FullFilename, Filename); delete vr; // leak return PDU.LoadDICOMDataObject(FullFilename); } else { char *p = strrchr(filename, '.'); // rudimentary gz support if (p && stricmp(p, ".gz")==0) { char line[1000]; char *q = strrchr(filename, PATHSEPCHAR); if (!q) q = filename; DICOMDataObject *D; sprintf(line, "7za e -y \"%s\"", filename); system(line); *p = 0; D = PDU.LoadDICOMDataObject(q+1); unlink(q+1); *p = '.'; return D; } return PDU.LoadDICOMDataObject(filename); } } // Delete image from database, where only filename is given BOOL DeleteImageFile(char *filename, BOOL KeepImages) { DICOMDataObject *pDDO; VR *vrSOPInstanceUID, *vrPat; DICOMDataObject DDO; VR *pVR; pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[DeleteImageFile] %s -FAILED: Error on Load\n", filename); return ( FALSE ); } if (!pDDO->GetVR(0x0010, 0x0020) || !pDDO->GetVR(0x0020, 0x000d) || !pDDO->GetVR(0x0020, 0x000e) || !pDDO->GetVR(0x0008, 0x0018)) { OperatorConsole.printf("***[DeleteImageFile] %s -FAILED: file does not contain correct UIDs\n", filename); delete pDDO; return ( FALSE ); } pVR = pDDO->GetVR(0x0008, 0x0018); vrSOPInstanceUID = new VR(0x0008, 0x0018, pVR->Length, pVR->Data, (BOOL) FALSE ); DDO.Push(vrSOPInstanceUID); pVR = pDDO->GetVR(0x0010, 0x0020); vrPat = new VR(0x0010, 0x0020, pVR->Length, pVR->Data, (BOOL) FALSE ); DDO.Push(vrPat); OperatorConsole.printf("Deleting database entry for image: %s\n", filename); RemoveFromPACS(&DDO, KeepImages); delete pDDO; return ( TRUE ); } // Ask image UID BOOL GetImageFileUID(char *filename, char *UID) { DICOMDataObject* pDDO; VR *vrSOPInstanceUID; pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[GetImageFileUID] %s -FAILED: Error on Load\n", filename); return ( FALSE ); } if (!pDDO->GetVR(0x0010, 0x0020) || !pDDO->GetVR(0x0020, 0x000d) || !pDDO->GetVR(0x0020, 0x000e) || !pDDO->GetVR(0x0008, 0x0018)) { OperatorConsole.printf("***[GetImageFileUID] %s -FAILED: file does not contain correct UIDs\n", filename); return ( FALSE ); } vrSOPInstanceUID = pDDO->GetVR(0x0008, 0x0018); memset(UID, 0, 255); memcpy(UID, vrSOPInstanceUID->Data, vrSOPInstanceUID->Length); delete pDDO; return ( TRUE ); } // Change UID of given DDO static BOOL ChangeUIDinDDO(DICOMDataObject *pDDO, int group, int element, char *name) { char s[255], NewUID[255]; VR *vr; int len; vr = pDDO->GetVR(group, element); if (!vr) return ( FALSE); memset(s, 0, 255); memcpy(s, vr->Data, vr->Length); if (!ChangeUID(s, name, NewUID)) { OperatorConsole.printf("***[ModifyImageFile] FAILED to change %s\n", name); return ( FALSE ); } len = strlen(NewUID); if (len&1) len++; vr->ReAlloc(len); memcpy(vr->Data, NewUID, len); return ( TRUE ); } // Change any VR of given DDO static BOOL ChangeVRinDDO(DICOMDataObject *pDDO, int group, int element, char *text) { char s[255]; VR *vr; int len; vr = pDDO->GetVR(group, element); if (!vr) { vr = new VR(group, element, 10, TRUE); } memset(s, 0, 255); memcpy(s, vr->Data, vr->Length); len = strlen(text); if (len&1) len++; vr->ReAlloc(len); memcpy(vr->Data, text, len); // pDDO->Push(vr); pDDO->ReplaceVR(vr); // also works in sequences return ( TRUE ); } // Change patient ID of pDDO in memory BOOL ModifyPATIDofDDO(DICOMDataObject *pDDO, char *NewPATID) { int len; PDU_Service PDU; DICOMDataObject DDO; Database DB; char s[255]; BOOL ok; VR *vr; PDU.AttachRTC(&VRType); if (NewPATID==NULL || *NewPATID==0) { OperatorConsole.printf("***[ModifyPATIDofDDO] Empty patient ID not allowed\n"); return ( FALSE ); } if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***[ModifyPATIDofDDO] Error Connecting to SQL\n"); return ( FALSE ); } // Just to make sure the table exists // DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64), MODType varchar(32), NewUID varchar(64)" ); // check image in memory if(!pDDO) { OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: No image passed\n"); return ( FALSE ); } if (!pDDO->GetVR(0x0010, 0x0020) || !pDDO->GetVR(0x0020, 0x000d) || !pDDO->GetVR(0x0020, 0x000e) || !pDDO->GetVR(0x0008, 0x0018)) { OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: image does not contain correct UIDs\n"); return ( FALSE ); } ok = ChangeUIDinDDO(pDDO, 0x0020, 0x000d, "StudyUID"); ok &= ChangeUIDinDDO(pDDO, 0x0020, 0x000e, "SeriesUID"); ok &= ChangeUIDinDDO(pDDO, 0x0008, 0x0018, "SOPInstanceUID"); if (!ok) { OperatorConsole.printf("***[ModifyPATIDofDDO] -FAILED: could not change all UIDs\n"); return ( FALSE ); } // change patient ID vr = pDDO->GetVR(0x0010, 0x0020); memset(s, 0, 255); memcpy(s, vr->Data, vr->Length); len = strlen(NewPATID); if (len&1) len++; vr->ReAlloc(len); memcpy(vr->Data, NewPATID, len); OperatorConsole.printf("Modified patient ID to: %s\n", NewPATID); return ( TRUE ); } // Merge (SeriesUID or StudyUID {given in type}) of pDDO in memory BOOL MergeUIDofDDO(DICOMDataObject *pDDO, char *type) { int len; PDU_Service PDU; DICOMDataObject DDO; Database DB; char s[255]; BOOL ok; VR *vr; PDU.AttachRTC(&VRType); if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***[MergeUIDofDDO] Error Connecting to SQL\n"); return ( FALSE ); } // check image in memory if(!pDDO) { OperatorConsole.printf("***[MergeUIDofDDO] -FAILED: No image passed\n"); return ( FALSE ); } if (!pDDO->GetVR(0x0010, 0x0020) || !pDDO->GetVR(0x0020, 0x000d) || !pDDO->GetVR(0x0020, 0x000e) || !pDDO->GetVR(0x0008, 0x0018)) { OperatorConsole.printf("***[MergeUIDofDDO -FAILED: image does not contain correct UIDs\n"); return ( FALSE ); } ok = TRUE; if (strcmp(type, "StudyUID")==0) ok &= ChangeUIDinDDO(pDDO, 0x0020, 0x000d, "StudyUID"); ok = ChangeUIDinDDO(pDDO, 0x0020, 0x000e, "SeriesUID"); ok &= ChangeUIDinDDO(pDDO, 0x0008, 0x0018, "SOPInstanceUID"); if (!ok) { OperatorConsole.printf("***[MergeUIDofDDO] -FAILED: could not change all UIDs\n"); return ( FALSE ); } return ( TRUE ); } // forward references BOOL SaveToDisk(Database &DB, DICOMDataObject *DDOPtr, char *Filename, BOOL NoKill, unsigned char *calling=NULL, unsigned char *called=NULL, int Syntax=0, BOOL nopreget=FALSE); void TestCompress(char *filename, char *modes); void TestForward(char *filename, char *mode, char *server); void TestSyntax(char *filename, int syntax); void TestThreadedSave(char *filename); void ProcessHL7Data(char *data); // Add image file to server (also copies file!); optional changes patient ID before entering file BOOL AddImageFile(char *filename, char *NewPatid) { DICOMDataObject* pDDO; int len, i; VR *vrSOPInstanceUID; DICOMDataObject DDO; Database DB; char rFilename[1024]; BOOL rc; if (NewPatid) { if (NewPatid[0]=='$' && NewPatid[1]=='c') { TestCompress(filename, "unasn1n2n3n4j1j2j3j4j5j6k1k2k4k8"); return TRUE; } if (NewPatid[0]=='$' && NewPatid[1]=='t') { TestForward(filename, "un", NewPatid+2); TestForward(filename, "as", NewPatid+2); TestForward(filename, "n1", NewPatid+2); TestForward(filename, "n2", NewPatid+2); TestForward(filename, "n3", NewPatid+2); TestForward(filename, "n4", NewPatid+2); TestForward(filename, "j1", NewPatid+2); TestForward(filename, "j2", NewPatid+2); TestForward(filename, "j3", NewPatid+2); TestForward(filename, "j4", NewPatid+2); TestForward(filename, "j5", NewPatid+2); TestForward(filename, "j6", NewPatid+2); TestForward(filename, "k1", NewPatid+2); TestForward(filename, "k2", NewPatid+2); TestForward(filename, "k4", NewPatid+2); TestForward(filename, "k8", NewPatid+2); return TRUE; } if (NewPatid[0]=='$' && NewPatid[1]=='s') { TestSyntax(filename, 1); TestSyntax(filename, 2); TestSyntax(filename, 3); TestSyntax(filename, 4); TestSyntax(filename, 5); TestSyntax(filename, 6); TestSyntax(filename, 7); TestSyntax(filename, 8); TestSyntax(filename, 9); TestSyntax(filename, 10); return TRUE; } if (NewPatid[0]=='$' && NewPatid[1]=='r') { for (i=0; i<atoi(NewPatid+2); i++) TestSyntax(filename, 0); return TRUE; } if (NewPatid[0]=='$' && NewPatid[1]=='t') { for (i=0; i<atoi(NewPatid+2); i++) TestThreadedSave(filename); return TRUE; } } // rudimentary hl7 support if (strlen(filename)>4 && stricmp(filename+strlen(filename)-4, ".hl7")==0) { int len = DFileSize(filename); if (len) { char *p=(char*) malloc(len+1); FILE *f; f = fopen(filename, "rb"); fread(p, 1, len, f); p[len]=0; fclose(f); ProcessHL7Data(p); free(p); OperatorConsole.printf("[AddImageFile] loaded HL7 file: %s\n", filename); return TRUE; } else { OperatorConsole.printf("*** [AddImageFile] could not open HL7 file: %s\n", filename); return FALSE; } } if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error Connecting to SQL\n"); return ( FALSE ); } pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[AddImageFile] %s -FAILED: Error on Load\n", filename); return ( FALSE ); } if (NewPatid) { if (!ModifyPATIDofDDO(pDDO, NewPatid)) { OperatorConsole.printf("***[AddImageFile] Error changing patient ID for file: %s\n", filename); delete pDDO; return FALSE; } } if (!pDDO->GetVR(0x0010, 0x0020) || !pDDO->GetVR(0x0020, 0x000d) || !pDDO->GetVR(0x0020, 0x000e) || !pDDO->GetVR(0x0008, 0x0018)) { OperatorConsole.printf("***[AddImageFile] %s -FAILED: file does not contain correct UIDs\n", filename); delete pDDO; return ( FALSE ); } // recompress dropped files rc = recompress(&pDDO, DroppedFileCompression, "", DroppedFileCompression[0]=='n' || DroppedFileCompression[0]=='N'); rc = TRUE; // failed compression leaves original object if ((rc == FALSE) || (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"dropped", (unsigned char *)"dropped"))) { OperatorConsole.printf("***[AddImageFile] Error entering object into server: %s\n", filename); if (pDDO) delete pDDO; return FALSE; } OperatorConsole.printf("Added file: %s\n", rFilename); return ( TRUE ); } // Make a new UID for external use (prefix configurable via UIDPrefix in dicom.ini) extern int UIDPostfix; static char UIDPrefix[65] = "1.2.826.0.1.3680043.2.135.1066.6"; // default value static BOOL dgLoadRoot = TRUE; BOOL GenUID(char *oString) { if (dgLoadRoot) { char szRootSC[64]; if (GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) { if (GetPrivateProfileString(szRootSC, "UIDPrefix", "1.2.826.0.1.3680043.2.135.1066", UIDPrefix, 64, ConfigFile)) strcat(UIDPrefix, ".6"); } dgLoadRoot = FALSE; } #ifdef WIN32 sprintf(oString, "%s.%u.%d.%u", UIDPrefix, time(NULL), GetTickCount()%1000, (UIDPostfix++)%100); #else sprintf(oString, "%s.%u.%u", UIDPrefix, time(NULL), (UIDPostfix++)%10000); #endif return ( TRUE ); } int CallImportConverterN(DICOMDataObject *DDO, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called, char *Storage); // Change patient ID of image file BOOL ModifyPATIDofImageFile(char *filename, char *NewPATID, BOOL DelFile, char *script) { DICOMDataObject* pDDO; int sIndex, Index, len; DICOMDataObject DDO; Database DB; char rFilename[1024], s[255]; char MirrorFile[1024], Device[255], Physical[1024]; BOOL ok; VR *vr; int devlen, mirrordevlen; if (NewPATID==NULL || *NewPATID==0) { OperatorConsole.printf("***[ModifyPATIDofImageFile] Empty patient ID not allowed\n"); return ( FALSE ); } // try to locate the mirror file because that one has to change too MirrorFile[0] = 0; Index = 0; while ( Index < MAGDevices ) { sprintf(Device, "MAG%d", Index); GetPhysicalDevice(Device, Physical); devlen = strlen(Physical); if (memicmp(Physical, filename, strlen(Physical))==0) { sprintf(Device, "MIRROR%d", Index); if (GetPhysicalDevice(Device, MirrorFile)) { mirrordevlen = strlen(MirrorFile); strcat(MirrorFile, filename + strlen(Physical)); } break; } ++Index; if (Index == MAGDevices) { OperatorConsole.printf("***File to modify is not on a MAG device\n"); return ( FALSE ); } } // remove image file from database if (DelFile) if (!DeleteImageFile(filename, TRUE)) { OperatorConsole.printf("***Could not remove image file from database\n"); return ( FALSE ); } if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error Connecting to SQL\n"); return ( FALSE ); } // Just to make sure the table exists // DB.CreateTable ( "UIDMODS", "MODTime int, OldUID varchar(64), MODType varchar(32), NewUID varchar(64)" ); // load image into memory pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[ModifyPATIDofImageFile] %s -FAILED: Error on Load\n", filename); return ( FALSE ); } // change patient ID of object file in memory if (!ModifyPATIDofDDO(pDDO, NewPATID)) { delete pDDO; return FALSE; } if (script) CallImportConverterN(pDDO, -1, NULL, NULL, NULL, NULL, NULL, NULL, script); // add the image in memory to the server, also makes a copy of the image if (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"modpatid", (unsigned char *)"modpatid")) { delete pDDO; OperatorConsole.printf("***Error entering object into server: %s\n", filename); return ( FALSE ); } OperatorConsole.printf("Modified image: %s\n", rFilename); if (!DelFile) { return ( TRUE ); } // delete the original image since it would show up with original PATID after regen if (stricmp(filename, rFilename)) { unlink(filename); OperatorConsole.printf("Deleting file: %s\n", filename); } // delete the mirror image since it would show up with original PATID after regen if (strlen(MirrorFile)) if (stricmp(MirrorFile, rFilename)) { unlink(MirrorFile); OperatorConsole.printf("Deleting mirror file: %s\n", MirrorFile); } // remove the source directory and any required subdirectories (just fails quietly if directory not yet empty) strcpy(s, filename); for (sIndex = strlen(s)-1; sIndex>=devlen; sIndex--) if (s[sIndex]==PATHSEPCHAR) { s[sIndex]='\0'; rmdir(s); } // remove the mirror source directory and any required subdirectories (just fails quietly if directory not yet empty) strcpy(s, MirrorFile); for (sIndex = strlen(s)-1; sIndex>=mirrordevlen; sIndex--) if (s[sIndex]==PATHSEPCHAR) { s[sIndex]='\0'; rmdir(s); } return ( TRUE ); } // Merge SeriesUID or StudyUID (passed in type) of image file BOOL MergeUIDofImageFile(char *filename, BOOL DelFile, char *type) { DICOMDataObject* pDDO; int sIndex, Index, len; DICOMDataObject DDO; Database DB; char rFilename[1024], s[255]; char MirrorFile[1024], Device[255], Physical[1024]; BOOL ok; VR *vr; int devlen, mirrordevlen; // try to locate the mirror file because that one has to change too MirrorFile[0] = 0; Index = 0; while ( Index < MAGDevices ) { sprintf(Device, "MAG%d", Index); GetPhysicalDevice(Device, Physical); devlen = strlen(Physical); if (memicmp(Physical, filename, strlen(Physical))==0) { sprintf(Device, "MIRROR%d", Index); if (GetPhysicalDevice(Device, MirrorFile)) { mirrordevlen = strlen(MirrorFile); strcat(MirrorFile, filename + strlen(Physical)); } break; } ++Index; if (Index == MAGDevices) { OperatorConsole.printf("***File to merge is not on a MAG device\n"); return ( FALSE ); } } // remove image file from database if (DelFile) if (!DeleteImageFile(filename, TRUE)) { OperatorConsole.printf("***Could not remove image file from database\n"); return ( FALSE ); } if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error Connecting to SQL\n"); return ( FALSE ); } // load image into memory pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[MergeUIDofImageFile] %s -FAILED: Error on Load\n", filename); return ( FALSE ); } // change patient ID of object file in memory if (!MergeUIDofDDO(pDDO, type)) { delete pDDO; return FALSE; } // add the image in memory to the server, also makes a copy of the image if (!SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"merging", (unsigned char *)"merging")) { delete pDDO; OperatorConsole.printf("***Error entering object into server: %s\n", filename); return ( FALSE ); } OperatorConsole.printf("Merged image: %s\n", rFilename); if (!DelFile) return ( TRUE ); // delete the original image since it would show up with original series UID after regen if (stricmp(filename, rFilename)) { unlink(filename); OperatorConsole.printf("Deleting file: %s\n", filename); } // delete the mirror image since it would show up with original series UID after regen if (strlen(MirrorFile)) if (stricmp(MirrorFile, rFilename)) { unlink(MirrorFile); OperatorConsole.printf("Deleting mirror file: %s\n", MirrorFile); } // remove the source directory and any required subdirectories (just fails quietly if directory not yet empty) strcpy(s, filename); for (sIndex = strlen(s)-1; sIndex>=devlen; sIndex--) if (s[sIndex]==PATHSEPCHAR) { s[sIndex]='\0'; rmdir(s); } // remove the mirror source directory and any required subdirectories (just fails quietly if directory not yet empty) strcpy(s, MirrorFile); for (sIndex = strlen(s)-1; sIndex>=mirrordevlen; sIndex--) if (s[sIndex]==PATHSEPCHAR) { s[sIndex]='\0'; rmdir(s); } return ( TRUE ); } // Help routine for spawning a process on WIN32 or UNIX #ifndef UNIX // Win32... BOOL BackgroundExec( char *ProcessBinary, // name of executable char *Args) // arguments { PROCESS_INFORMATION PINFO; STARTUPINFO SINFO; SECURITY_ATTRIBUTES SA; HANDLE hMap; char CommandLine[1024]; memset((void*)&SINFO, 0, sizeof(STARTUPINFO)); SINFO.cb = sizeof(STARTUPINFO); SA.nLength = sizeof (SECURITY_ATTRIBUTES); SA.lpSecurityDescriptor = NULL; SA.bInheritHandle = TRUE; sprintf(CommandLine, "%s %s", ProcessBinary, Args); if(!CreateProcess(ProcessBinary, CommandLine, NULL, NULL, TRUE, DETACHED_PROCESS, NULL, NULL, &SINFO, &PINFO)) { OperatorConsole.printf("***Failed to create process: %d\n", GetLastError()); } else { CloseHandle(PINFO.hThread); CloseHandle(PINFO.hProcess); } return ( TRUE ); } #else // UNIX... BOOL BackgroundExec( char *theExecName, char *theArg) { // fork and exec a new process... (just replicate 1 thread...) pid_t aPID = fork(); if(aPID == 0) { // this is the child process... // lose controlling tty setsid(); // close all open files, except standard I/O // (could close those also, and attach them to /dev/console) // like: // fd = open("/dev/console", 1); // if(fd != 1) // { // dup2(fd, 1); // close(fd); // fd = 1; // } // dup2(1, 2); int anIndex; int anOpenFileMax; for(anIndex = 3, anOpenFileMax = sysconf(_SC_OPEN_MAX); anIndex < anOpenFileMax; ++anIndex) { close(anIndex); } // reset signals for(anIndex = 1; anIndex <= SIGUSR2; ++anIndex) { (void)signal(anIndex, SIG_DFL); } // do the exec() if(execlp(theExecName, theExecName, theArg, NULL)) { SystemDebug.printf( "DriverApp::ServerChildInit(): failed to execlp(%s)\n", theExecName); //_exit(255); } } return ( TRUE ); } #endif //////////////////////////////////////////////////////////////////////// // copy a file (possibly opening as shared file) static BOOL DFileCopy2(char *source, char *target, int smode) { BOOL err_status = TRUE; /* Error status */ char *copybuffer; /* The copy buffer */ int inhandle, outhandle; /* Handle of input, output files */ unsigned bufsize; /* Size of copy buffer */ unsigned bytes; /* Actual transferred bytes */ /* Open input file for read-only. parser error if operation fails. */ if (!smode) inhandle = open( source, O_RDONLY | O_BINARY, S_IREAD); else inhandle = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD); if( inhandle == -1) return FALSE; /* Ok, open output file. Parser error on permission failure: */ outhandle = open( target, O_CREAT | O_TRUNC | O_BINARY | O_RDWR, 0666); if( outhandle == -1) { close(inhandle); return FALSE; } /* get a large buffer */ bufsize = 0xF000; copybuffer = (char *)malloc(bufsize); if (copybuffer == NULL) { close(inhandle); close(outhandle); return FALSE; } while( !eof(inhandle) && err_status) { bytes= (unsigned)read( inhandle, copybuffer, bufsize); #ifndef WIN32 if (bytes == 0) break; #endif if (bytes == (unsigned) -1) { err_status= FALSE; break; } if (bytes != (unsigned)write(outhandle, copybuffer, bytes)) { err_status= FALSE; break; } } free(copybuffer); close(outhandle); close(inhandle); /* Clean up mess in case of error : */ if(err_status != TRUE) unlink(target); return err_status; } // Special RunTime-Classing Storage mechanism. Used for "Generic" // Unknown outgoing C-Store requests from the Query / Retrieve Engine // Defined here because needed in forward code class RunTimeClassStorage : public StandardStorage { UID MyUID; public: // is not used anymore and would not be thread safe (db's may not be shared) // Database DB; BOOL uGetUID(UID &uid) { return ( GetUID(uid) ); }; inline BOOL Read ( PDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *DDO ) { return ( StandardStorage :: Read ( PDU, DCO, DDO ) ); }; inline BOOL Write ( PDU_Service *PDU, DICOMDataObject *DDO) { return ( StandardStorage :: Write ( PDU, DDO ) ); }; BOOL GetUID(UID &); BOOL SetUID(UID &); BOOL SetUID(VR *); BOOL SetUID(DICOMDataObject *); }; // This routine is used as a filter for export converter. // It works by combining a given filter string with a query // for a given SOP, and returning TRUE if a record is found. // maxname is used to truncate fieldnames to fit with the DB spec. // limitations: PatientID, SeriesInstanceUID and StudyInstanceUID // cannot be queried. All other DB fields can be queried. int TestFilter(char *query, char *sop, int maxname, char *patid=NULL) { Database aDB; char Tables[512], QueryString[512], Dum[256]; int result, instring=0, inword=0, i, L, Index; char *p; SQLLEN sdword; if (*query) sprintf(Tables, "%s, %s, %s, %s", ImageTableName, SeriesTableName, StudyTableName, PatientTableName); else sprintf(Tables, "%s", ImageTableName); if(!aDB.Open(DataSource, UserName, Password, DataHost)) { OperatorConsole.printf("***Filter: Unable to open database %s as user %s on %s\n", DataSource, UserName, DataHost); return 0; } // truncate the identifiers in the query to 10 characters // this is our default maximum field name length for the DB L = strlen(query); for (i=0; i<L; i++) { if (instring) { if (query[i]=='\'') { instring = 0; } continue; } else if (inword) { if (query[i]==' ') { inword = 0; } else { inword++; if (inword>maxname) query[i] = ' '; } } else { if (query[i]=='\'') { instring = 1; } else if (isalpha(query[i])) { inword = 1; } } } if (*query) sprintf(QueryString, "(%s) and " "DICOMImages.SopInstanc = '%s' and " "DICOMStudies.PatientID = DICOMPatients.PatientID and " "DICOMImages.SeriesInst = DICOMSeries.SeriesInst and " "DICOMSeries.StudyInsta = DICOMStudies.StudyInsta", query, sop); else sprintf(QueryString, "DICOMImages.SopInstanc = '%s'", sop); // include patid (indexed) for speed; test for rev5 or higher of the database if (patid) { Index = 1; while (ImageDB[Index].Element) { if (ImageDB[Index].Group==0x0010 && ImageDB[Index].Element==0x0020) { char newpatid[128]; strcpy(newpatid, patid); DICOM2SQLQuery(newpatid); sprintf(QueryString+strlen(QueryString), " AND DICOMImages.ImagePat = %s", newpatid); break; } Index++; } } if (!aDB.Query(Tables, "DICOMImages.ObjectFile", QueryString, NULL)) { OperatorConsole.printf("***Filter: Unable to query for image record\n"); aDB.Close(); return 0; } aDB.BindField (1, SQL_C_CHAR, Dum, 255, &sdword); result = aDB.NextRecord(); aDB.Close(); return result; } /* The following function is called at the end of 'SaveToDisk' or through a queue that is filled from SaveToDisk. After the arrival and storage of each DicomObject, several executables may be invoked, to perform further processing. */ #ifdef WIN32 #include "shellapi.h" #endif // forward references static int htoin(char *value, int len); static int isxdig(char ch); BOOL prefetch_queue(char *operation, char *patientid, char *server, char *studyuid, char *seriesuid, char *compress, char *modality, char *date, char *sop, char *imagetype, char *seriesdesc); void reset_queue_fails(int N); static BOOL match(char *source, char *target) { if (strlen(target)==1 && target[0]=='*') return TRUE; char Source[512]; strcpy(Source, source); while (strlen(Source)>0 && Source[strlen(Source)-1]==' ') Source[strlen(Source)-1] = 0; if (strlen(target)> 1 && target[strlen(target)-1]=='*') { if (memicmp(Source, target, strlen(target)-1)) return FALSE; } else if (strlen(target)> 1 && target[0]=='*') { if (memicmp(Source+strlen(Source)-strlen(target)+1, target+1, strlen(target)-1)) return FALSE; } else if (stricmp(Source, target)) return FALSE; return TRUE; } // Search a composite dicom object: // desc=gggg,eeee plain element // desc=*gggg,eeee search in all sequences // desc=/*gggg,eeee idem // desc=/gggg,eeee.i.. search specified in sequence, ith element (recursive) // desc=/gggg,eeee.. idem, first element // e.g. /gggg,eeee.0/gggg,eeee/*gggg,eeee: to search specified sequences // // desc=(desc1)desc2 search desc1 in DICOM object which sop is specified in (desc1), patient ID taken from 0010,0020 // e.g. %V(/300c,0060.0/0008,1155)/gggg,eeee.0/gggg,eeee // // returns length of parsed desc string int SearchDICOMObject(DICOMObject *DDO, char *desc, char *result) { DICOMObject DDO2; VR *vr; int Index, i, g, e, len; char *p; BOOL seq=FALSE, wild=FALSE; *result=0; i =0; if (desc[i]=='(') { i++; char r[300]; DICOMObject *pDDO; SearchDICOMObject(DDO, "0010,0020", r); strcat(r, ":"); i += SearchDICOMObject(DDO, desc+i, r+strlen(r)); if (desc[i]==')') i++; //else OperatorConsole.printf("***Syntax error in %V(desc)desc statement %s at %d\n", desc, i); pDDO = LoadForGUI(r); i += SearchDICOMObject(pDDO, desc+i, result); delete pDDO; return i; } if (desc[i]=='/') i++, seq=TRUE; if (desc[i]=='*') i++, seq=FALSE, wild=TRUE; if (!isxdig(desc[i])) return i; g = htoin(desc+i, 4); e = htoin(desc+i+5, 4); i +=9; // get plain element if (!seq && !wild) { if (!DDO) return i; vr = DDO->GetVR(g, e); if (vr) { strncpy(result, (char*)vr->Data, vr->Length); result[vr->Length] = 0; len = vr->Length - 1; while(len>0) { if (result[len] == ' ') result[len] = 0; else break; len--; } } return i; } // get specified sequence element (only 0..9 supported for now) else if (seq) { int j=0; if (desc[i]=='.') { Index = atoi(desc+i+1); i+=2; } else Index = 0; vr = NULL; if (DDO) vr = DDO->GetVR(g, e); if (vr) { if ( vr->SQObjectArray ) { Array < DICOMDataObject * > *ADDO = (Array<DICOMDataObject*>*) vr->SQObjectArray; j = SearchDICOMObject(ADDO->Get(Index), desc+i, result); } else { strncpy(result, (char*)vr->Data, vr->Length); result[vr->Length] = 0; len = vr->Length - 1; while(len>0) { if (result[len] == ' ') result[len] = 0; else break; len--; } } } else { // ignore rest of desc char dum[1024]; j = SearchDICOMObject(DDO, desc+i, dum); } return i+j; } // wild: search all sequences if (!DDO) return i; while(vr=DDO->Pop()) { if (*result==0) { if ( vr->SQObjectArray ) { Array < DICOMDataObject * > *ADDO = (Array<DICOMDataObject*>*) vr->SQObjectArray; Index = 0; while ( Index < ADDO->GetSize() ) { SearchDICOMObject(ADDO->Get(Index), desc, result); if (*result) break; ++Index; } } else if (vr->Group==g && vr->Element==e) { strncpy(result, (char*)vr->Data, vr->Length); result[vr->Length] = 0; len = vr->Length - 1; while(len>0) { if (result[len] == ' ') result[len] = 0; else break; len--; } } } DDO2.Push(vr); } DDO->Reset(); while(vr=DDO2.Pop()) { DDO->Push(vr); } return i; } // operates asynchronously on images AFTER it they are stored in the database // return TRUE if it worthwile to retry (connection or write failed) // For general scripting use: // CallExportConverterN(FileName, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, script) BOOL CallExportConverterN(char *pszFileName, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called, ExtendedPDU_Service *PDU, char *ForwardLastUID) { char szRootSC[64]; char szEntry[32]; char szTemp[66]; int i, rc, MaxLength, part, skipping; char szExecName[512], szNext[512]; char szExecModality[66]; char szExecStationName[66]; char szExecFilter[512]; char ExportCalledAE[18], ExportCallingAE[18], Called[18], Calling[18]; BOOL StripGroup2; DICOMDataObject *DDO = NULL; ExtendedPDU_Service PDU2; PDU2.AttachRTC(&VRType); if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return FALSE; /* filter using modality, stationname, calling and called */ if (pszModality) { sprintf(szEntry, "ExportModality%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", szExecModality, 64, ConfigFile)) return FALSE; if (!match(pszModality, szExecModality)) return FALSE; } if (pszStationName) { sprintf(szEntry, "ExportStationName%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", szExecStationName, 64, ConfigFile)) return FALSE; if (!match(pszStationName, szExecStationName)) return FALSE; } if (calling) { sprintf(szEntry, "ExportCallingAE%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", ExportCallingAE, 18, ConfigFile)) return FALSE; if (!match(calling, ExportCallingAE)) return FALSE; } if (called) { sprintf(szEntry, "ExportCalledAE%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", ExportCalledAE, 18, ConfigFile)) return FALSE; if (!match(called, ExportCalledAE)) return FALSE; } /* apply database filter */ if (called && calling) { sprintf(szEntry, "ExportFilter%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", szExecFilter, 510, ConfigFile)) return FALSE; if (szExecFilter[0]!='*') { if (!GetPrivateProfileString(szRootSC, "TruncateFieldNames", "255", szTemp, 32, ConfigFile)) return FALSE; MaxLength = atoi(szTemp); if (!TestFilter(szExecFilter, pszSop, MaxLength, patid)) return FALSE; } } /* get the export converter name: empty is none */ if (called && calling) { sprintf(szEntry, "ExportConverter%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "", szExecName, 512, ConfigFile)) return FALSE; if (szExecName[0]==0) return FALSE; } else strcpy(szExecName, ForwardLastUID); rc = 1; // status for if statement and stop part = 0; skipping = 0; while(1) { szNext[0] = 0; if (skipping || rc==4) // {} block being skipped { if (szExecName[0]=='{') skipping++, rc=0; else if (szExecName[0]=='}') skipping--, rc=0; } // remove {} for all export converters (not only those with a %) i = 0; if (szExecName[0] == '{') {i++; while(szExecName[i]==' ')i++; memmove(szExecName, szExecName+i, strlen(szExecName+i)+1); } else if (szExecName[0] == '}') {i++; while(szExecName[i]==' ')i++; memmove(szExecName, szExecName+i, strlen(szExecName+i)+1); } // find ; not in string: splits export commands int instring=0; int L = strlen(szExecName); for (int k=0; k<L; k++) { if (szExecName[k]=='"') instring = !instring; if (szExecName[k]==';' && instring==0) { szExecName[k] = 0; // split command while (szExecName[k+1]==' ') k++; // skip spaces after ; strcpy(szNext, szExecName+k+1); // remaining for next break; } } if (skipping) // {} block being skipped { SystemDebug.printf("Exportconverter%d.%d skipped\n", N, part); } else if (szExecName[0]==0) // leftover of { or } { } else if (rc==4) // ifxxxx statement causes a skip { rc = 0; SystemDebug.printf("Exportconverter%d.%d not executed because of previous statement\n", N, part); } /* for all export converters: first substitute % variables */ else { char line[1000]; if (strchr(szExecName, '%')) { int i=0, l, L, len; char *p; VR *pVR; char vr[256]; /* substitute %x variables and remove possible { and } at begin of statement */ line[0] = 0; L = strlen(szExecName); while (i<L) { if (i==0 && szExecName[i] == '{') {i++; while(szExecName[i]==' ')i++;} else if (i==0 && szExecName[i] == '}') {i++; while(szExecName[i]==' ')i++;} else if (szExecName[i] == '%') { char *ps = line + strlen(line); switch(tolower(szExecName[i+1])) { case 'f': strcat(line, pszFileName); // %f=filename break; case 'm': if (pszModality) strcat(line, pszModality); // %m=modality else { char result[256]; if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); SearchDICOMObject(DDO, "0008,0060", result); strcat(line, result); } break; case 's': if (pszStationName) strcat(line, pszStationName); // %s=stationname else { char result[256]; if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); SearchDICOMObject(DDO, "0008,1100", result); strcat(line, result); } break; case 'o': if (pszSop) strcat(line, pszSop); // %o=object instance else { char result[256]; if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); SearchDICOMObject(DDO, "0008,0018", result); strcat(line, result); } break; case 'i': if (patid) strcat(line, patid); // %i=patient ID else { char result[256]; if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); SearchDICOMObject(DDO, "0010,0020", result); strcat(line, result); } break; case 'u': Calling[0]=0; if (calling) strcpy(Calling, calling); while (strlen(Calling)>0 && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0; strcat(line, Calling); // %u=SCU break; case 'c': Called[0]=0; if (called) strcpy(Called, called); while (strlen(Called)>0 && Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0; strcat(line, Called); // %c=calledAE = scp break; case 'd': time_t TimeOfDay; // %d=date and time char TimeString[128], buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; strcat(line, TimeString); break; case 'b': p = strrchr(pszFileName, PATHSEPCHAR); if (p) // %b=file base name { strcat(line, p+1); p = strrchr(line, '.'); if (p) *p=0; } break; case 'p': strcat(line, pszFileName); // %p=file path p = strrchr(line, PATHSEPCHAR); if (p) *p=0; break; case 'n': strcat(line, "\n"); // %n=newline break; case '%': strcat(line, "%"); // %%=% break; case 'v': // %Vxxxx,yyyy=any vr (group and element must have 4 digits) char result[256]; // %V*xxxx,yyyy=any vr in any sequence if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); i += SearchDICOMObject(DDO, szExecName+i+2, result); strcat(line, result); break; // case 'q': not (yet) supported for export converters - probably no need } i += 2; // get substring of variable if (szExecName[i]=='[') { int a=0, b=-1; sscanf(szExecName+i, "[%d,%d]", &a, &b); for (;i<L;i++) if (szExecName[i-1]==']') break; if (a>strlen(ps)) a=strlen(ps); if (b>strlen(ps)) b=strlen(ps); if (b>=a) {memmove(ps, ps+a, b-a+1); ps[b-a+1]=0;} } } else { l = strlen(line); line[l] = szExecName[i++]; line[l+1] = 0; } } // if (DDO) delete DDO; } else strcpy(line, szExecName); /* converter: direct forward of received object */ if (memicmp(line, "forward to", 10)==0 || memicmp(line, "forward compressed", 18)==0 ) { char host[64], port[64], compress[64], Level[64], Temp[66]; char *p; RunTimeClassStorage RTCStorage; UID AppUID ("1.2.840.10008.3.1.1.1"); UID iUID, uid; VR *vr; int offset = 11, level; // fallback if none passed: forces one association per image if (!PDU) PDU = &PDU2; // preprocess the forwarder string if (memicmp(line, "forward compressed as ", 22)==0) offset = 28; // xx to where xx = 'is', 'un', 'n0'..'n4', or 'j0'..'j6' if(!GetACRNema(line+offset, (char *)host, (char *)port, (char *)compress)) { strcpy(host, line+offset); p = strchr(host, ':'); if (p) { *p=0; strcpy(port, p+1); } else strcpy(port, "5678"); } /// offer transfer syntax (compression) from forward string if (offset==28) { compress[0] = line[22]; compress[1] = line[23]; compress[2] = 0; } OperatorConsole.printf("ExportConverter%d.%d: forward %s to %s\n", N, part, pszFileName, line+offset); // load and check the data if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); if (!DDO) { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to load DICOM object %s\n", N, part, pszFileName); return FALSE; } // get UID at selected ForwardAssociationLevel into szTemp vr = NULL; level = 0; GetPrivateProfileString(szRootSC, "ForwardAssociationLevel", "STUDY", Level, 64, ConfigFile); if (strncmp(Level, "PATIENT", 7)==0) level=1; else if (strncmp(Level, "STUDY", 5)==0) level=2; else if (strncmp(Level, "SERIES", 6)==0) level=3; else if (strncmp(Level, "IMAGE", 5)==0) level=4; else if (strncmp(Level, "SOPCLASS",8)==0) level=5, PDU[part].ClearAbstractSyntaxs(); else if (strncmp(Level, "GLOBAL", 6)==0) level=6; szTemp[0] = 0; if (level==1) vr = DDO->GetVR(0x0010, 0x0020); if (level==2) vr = DDO->GetVR(0x0020, 0x000d); if (level==3) vr = DDO->GetVR(0x0020, 0x000e); if (level==4) vr = DDO->GetVR(0x0008, 0x0018); if (level==5) vr = DDO->GetVR(0x0008, 0x0016); if (vr) memcpy(szTemp, vr->Data, vr->Length); // get sopclass (to check whether it is accepted at the current connection) vr = DDO -> GetVR(0x0008, 0x0016); if (!vr) { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed because SopClass is missing in %s\n", N, part, pszFileName); delete DDO; return FALSE; } // does the existing link accept images of this type - if not then hang up to force a reconnect // also hang up when UID at ForwardAssociationLevel changes to start a new association if (PDU[part].Link.Connected) { SetUID ( iUID, vr ); if (!PDU[part].IsAbstractSyntaxAccepted(iUID) || strcmp(ForwardLastUID+part*66, szTemp)!=0 ) { //OperatorConsole.printf("!!! ExportConverter%d.%d: attempt to reconnect %s \n", N, part, szTemp); GetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile); if (atoi(Temp)) PDU[part].Close(); else PDU[part].Link.Close(); } } // for new check of UID at ForwardAssociationLevel strcpy(ForwardLastUID+part*66, szTemp); // (re)connect if (!PDU[part].Link.Connected) { PDU[part].AttachRTC(&VRType); PDU[part].SetRequestedCompressionType(compress); PDU[part].SetApplicationContext ( AppUID ); PDU[part].SetLocalAddress ( MYACRNEMA ); PDU[part].SetRemoteAddress ( (unsigned char *)(line+offset) ); PDU[part].SetTimeOut(TCPIPTimeOut); vr = DDO -> GetVR(0x0008, 0x0016); SetUID ( iUID, vr ); PDU[part].AddAbstractSyntax ( iUID ); // adds type of this image to presentation contexts uid.Set("1.2.840.10008.1.1"); // This one should always accept: verification PDU[part].AddAbstractSyntax(uid); // assures connect will not return FALSE because image is not accepted if (!PDU[part].Connect((unsigned char *)&host, (unsigned char *)&port)) { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to connect to host %s\n", N, part, line+offset); delete DDO; return TRUE; // may be good idea to retry later } } vr = DDO -> GetVR(0x0008, 0x0016); SetUID ( iUID, vr ); if (!PDU[part].IsAbstractSyntaxAccepted(iUID)) { OperatorConsole.printf("*** ExportConverter%d.%d: DICOM server %s does not accept type of forwarded image\n", N, part, line+offset); PDU[part].Close(); delete DDO; return FALSE; } // recompress data to be forwarded here according to accepted compression mode; strip group 2 unless "as" or "is" p = PDU[part].GetAcceptedCompressionType(iUID); StripGroup2 = memicmp(p, "as", 2)!=0 && memicmp(p, "is", 2)!=0; recompress(&DDO, p, "", StripGroup2); RTCStorage.SetUID(iUID); if (!RTCStorage.Write(PDU+part, DDO)) { OperatorConsole.printf("*** ExportConverter%d.%d: Forward failed to send DICOM image to %s\n", N, part, line+offset); PDU[part].Close(); delete DDO; return FALSE; // NOT a good idea to retry later } ImagesForwarded++; if (level==4) { GetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", Temp, 64, ConfigFile); if (atoi(Temp)) PDU[part].Close(); else PDU[part].Link.Close(); } delete DDO; // write was destructive DDO = NULL; } /* converter: write "string" to file - uses text file, use %n for newline */ else if (memicmp(line, "write \"", 7)==0) { char string[256]; char *file; FILE *f; char *p; strcpy(string, line+7); p = strstr(string, "\" to "); if (!p) p = strstr(string, "\" TO "); if (p) { *p=0; OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line); file = p+5; f = fopen(file, "wt"); if (f) { fputs(string, f); fclose(f); } else OperatorConsole.printf("*** Exportconverter%d.%d: Failed to write to file %s\n", N, part, file); } } /* converter: append "string" to file - uses text file, use %n for newline */ else if (memicmp(line, "append \"", 8)==0) { char string[256]; char *file; FILE *f; char *p; strcpy(string, line+8); p = strstr(string, "\" to "); if (!p) p = strstr(string, "\" TO "); if (p) { *p=0; OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line); file = p+5; f = fopen(file, "at"); if (f) { fputs(string, f); fclose(f); } else OperatorConsole.printf("*** Exportconverter%d.%d: Failed to append to file %s\n", N, part, file); } } /* converter: copy file to file; copy file to directory */ else if (memicmp(line, "copy ", 5)==0) { char string[1024]; char *file; struct stat statbuf; char *p; strcpy(string, line+5); p = strstr(string, " to "); if (!p) p = strstr(string, " TO "); if (p) { *p=0; OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line); file = p+4; /* if the destination a directory then append the source filename to it */ stat(file, &statbuf); if (statbuf.st_mode & S_IFDIR) { p = strrchr(pszFileName, PATHSEPCHAR); if (p) { if (file[strlen(file)-1]==PATHSEPCHAR) file[strlen(file)-1]=0; strcat(file, p); } } if (!DFileCopy2(string, file, 0)) OperatorConsole.printf("*** Exportconverter%d.%d: Failed to copy %s to %s\n", N, part, string, file); else ImagesCopied++; } } /* converter: ifnotempty "string" (only execute next converter if string not empty) */ else if (memicmp(line, "ifnotempty \"", 12)==0) { char string[1024]; char *p; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); int len = strlen(string); if (len==0) rc = 4; } } /* converter: ifempty "string" (only execute next converter if string empty) */ else if (memicmp(line, "ifempty \"", 9)==0) { char string[1024]; char *p; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); int len = strlen(string); if (len!=0) rc = 4; } } /* converter: ifequal "string1","string2" (only execute next converter if string1 equals string2) */ else if (memicmp(line, "ifequal \"", 9)==0) { char string[1024]; char *p, *string2; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); int cmp = strcmp(string, string2); if (cmp!=0) rc = 4; } } } /* converter: ifnotequal "string1","string2" (only execute next converter if string1 not equals string2) */ else if (memicmp(line, "ifnotequal \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); int cmp = strcmp(string, string2); if (cmp==0) rc = 4; } } } /* converter: ifmatch "string1","string2" (only execute next converter if string1 matches string2 - case insensitive) */ else if (memicmp(line, "ifmatch \"", 9)==0) { char string[1024]; char *p, *string2; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (!match(string, string2)) rc = 4; } } } /* converter: ifnotmatch "string1","string2" (only execute next converter if string1 not matches string2 - case insensitive) */ else if (memicmp(line, "ifnotmatch \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (match(string, string2)) rc = 4; } } } /* converter: ifnumequal "string1","string2" (only execute next converter if string1 num equals string2 - integer) */ else if (memicmp(line, "ifnumequal \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)!=atoi(string2)) rc = 4; } } } /* converter: ifnumnotequal "string1","string2" (only execute next converter if string1 num not equals string2 - integer) */ else if (memicmp(line, "ifnumnotequal \"", 15)==0) { char string[1024]; char *p, *string2; strcpy(string, line+15); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)==atoi(string2)) rc = 4; } } } /* converter: ifnumgreater "string1","string2" (only execute next converter if string1 num greater than string2 num - integer) */ else if (memicmp(line, "ifnumgreater \"", 14)==0) { char string[1024]; char *p, *string2; strcpy(string, line+14); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)<=atoi(string2)) rc = 4; } } } /* converter: ifnumless "string1","string2" (only execute next converter if string1 num less than string2 num - integer) */ else if (memicmp(line, "ifnumless \"", 11)==0) { char string[1024]; char *p, *string2; strcpy(string, line+11); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)>=atoi(string2)) rc = 4; } } } /* converter: between "string1","string2" (execute next converter on time in hours: between "9", "17"; defer) */ else if (memicmp(line, "between \"", 9)==0) { char string[1024]; char *p, *string2; int h1, h2, h; struct tm tmbuf; time_t t = time(NULL); localtime_r(&t, &tmbuf); h = tmbuf.tm_hour; strcpy(string, line+9); h1 = atoi(string); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; h2 = atoi(string2); SystemDebug.printf("Exportconverter%d.%d executes: %s\n", N, part, line); if (h2>=h1 && (h <h1 || h>=h2)) rc = 4; // between "9", "17": skip if h<9 or h>=17 if (h2< h1 && (h <h1 && h>=h2)) rc = 4; // between "17", "9": skip if h<=17 and h>=9 } } } /* converter: prefetch */ else if (memicmp(line, "prefetch", 8)==0) { if (prefetch_queue("prefetch", patid, "", "", "", "", "", "", "", "", "")) OperatorConsole.printf("Exportconverter%d.%d: queued prefetch %s\n", N, part, patid); } /* converter: delayed "[forward|get] [patient|study|series|image] [compressed as xx] [date yyyymmdd-yyyymmdd] [now -ddd+ddd] [age -ddd+ddd] [modality mm] [sop xxxx] [imagetype xxxx] [seriesdesc xxxx] [to/from AE]" and: delayed "delete [patient|study|series|image] [date yyyymmdd-yyyymmdd] [now -ddd+ddd] [age -ddd+ddd] [modality mm] [sop xxxx] [imagetype xxxx] [seriesdesc xxxx]" and: delayed "process [patient|study|series|image] [by command]" Will process data only from the current patient, but filters 'now, age, modality, sop, imagetype, seriesdesc' will read from other studies and series */ else if (memicmp(line, "forward patient ", 16)==0 || memicmp(line, "forward study ", 14)==0 || memicmp(line, "forward series ", 15)==0 || memicmp(line, "forward image ", 14)==0 || memicmp(line, "get patient ", 12)==0 || memicmp(line, "get study ", 10)==0 || memicmp(line, "get series ", 11)==0 || memicmp(line, "get image ", 10)==0 || memicmp(line, "delete patient ", 15)==0 || memicmp(line, "delete study ", 13)==0 || memicmp(line, "delete series ", 14)==0 || memicmp(line, "delete image ", 13)==0 || memicmp(line, "process patient ", 16)==0 || memicmp(line, "process study ", 14)==0 || memicmp(line, "process series ", 15)==0 || memicmp(line, "process image ", 14)==0) { char *level = strchr(line, ' ')+1; char *compress="", *dest="", *date="", *modality="", *sop="", *imagetype="", *seriesdesc=""; char studyuid[65], seriesuid[65], vr[200], dat[200]; VR *pVR; int len; studyuid[0]=0; seriesuid[0]=0; if (!DDO) DDO = PDU2.LoadDICOMDataObject(pszFileName); char *p=level; p = strchr(p, ' '); while(p) { *p=0; p++; if (memicmp(p, "compressed as ", 14)==0) { compress = p+14; p = strchr(p+14, ' '); } else if (memicmp(p, "to ", 3)==0) { dest = p+3; p = strchr(p+3, ' '); } else if (memicmp(p, "by ", 3)==0) { dest = p+3; p = strchr(p+3, ' '); } else if (memicmp(p, "from ", 5)==0) { dest = p+5; p = strchr(p+5, ' '); } else if (memicmp(p, "date ", 5)==0) // date yyyymmdd or yyyymmdd-yyyymmdd { date = p+5; p = strchr(p+5, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "now ", 4)==0) // now -365+365: within one year from now (+/- compulsory) { struct tm tmbuf1, tmbuf2; char *q; int from=0, to=0; from=atoi(p+4); q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q); time_t t1 = time(NULL)+24*3600*from; time_t t2 = time(NULL)+24*3600*to; localtime_r(&t1, &tmbuf1); localtime_r(&t2, &tmbuf2); sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday); date = dat; p = strchr(p+4, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "age ", 4)==0) // age -365+365: within one year from series date (+/- compulsory) { struct tm tmbuf1, tmbuf2; char *q; int from=0, to=0; from=atoi(p+4); q = strchr(p+5, '+'); if (!q) q = strchr(p+5, '-'); if (q) to=atoi(q); SearchDICOMObject(DDO, "0008,0020", dat); memset(&tmbuf1, 0, sizeof(tmbuf1)); sscanf(dat, "%04d%02d%02d", &tmbuf1.tm_year, &tmbuf1.tm_mon, &tmbuf1.tm_mday); tmbuf1.tm_year -= 1900; time_t t = mktime(&tmbuf1); time_t t1 = t+24*3600*from; time_t t2 = t+24*3600*to; localtime_r(&t1, &tmbuf1); localtime_r(&t2, &tmbuf2); sprintf(dat, "%04d%02d%02d-%04d%02d%02d", tmbuf1.tm_year+1900, tmbuf1.tm_mon, tmbuf1.tm_mday, tmbuf2.tm_year+1900, tmbuf2.tm_mon, tmbuf2.tm_mday); date = dat; p = strchr(p+4, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "modality ", 9)==0) { modality = p+9; p = strchr(p+9, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "sop ", 4)==0) { sop = p+4; p = strchr(p+4, ' '); level = "selection"; // causes that no UID is passed to query except the given SOP } else if (memicmp(p, "imagetype ", 10)==0) { imagetype = p+10; p = strchr(p+10, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "seriesdesc ", 11)==0) { seriesdesc = p+11; p = strchr(p+11, ' '); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "series ", 7)==0) { char *a=p+7; p = strchr(p+7, ' '); *p=0; strcpy(seriesuid, a); level = "selection"; // causes that no UID is passed to query } else if (memicmp(p, "study ", 6)==0) { char *a=p+6; p = strchr(p+6, ' '); *p=0; strcpy(studyuid, a); level = "selection"; // causes that no UID is passed to query } } if (DDO) { pVR = DDO->GetVR(0x0020, 0x000d); if (pVR && (memicmp(level, "stu", 3)==0 || memicmp(level, "ser", 3)==0) || memicmp(level, "ima", 3)==0) { strncpy(vr, (char*)pVR->Data, pVR->Length); vr[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (vr[len] == ' ') vr[len] = 0; else break; len--; } strcpy(studyuid, vr); } pVR = DDO->GetVR(0x0020, 0x000e); if (pVR && (memicmp(level, "ser", 3)==0 || memicmp(level, "ima", 3)==0)) { strncpy(vr, (char*)pVR->Data, pVR->Length); vr[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (vr[len] == ' ') vr[len] = 0; else break; len--; } strcpy(seriesuid, vr); } pVR = DDO->GetVR(0x0008, 0x0018); if (pVR && memicmp(level, "ima", 3)==0) { strncpy(vr, (char*)pVR->Data, pVR->Length); vr[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (vr[len] == ' ') vr[len] = 0; else break; len--; } sop = vr; } } line[11]=0; if (sop) level = "single object"; if (prefetch_queue(line, patid, dest, studyuid, seriesuid, compress, modality, date, sop, imagetype, seriesdesc)) OperatorConsole.printf("Exportconverter%d.%d: queued %s - (%s %s %s of %s) to %s\n", N, part, line, level, modality, date, patid, dest); } /* converter: preretrieve */ else if (memicmp(line, "preretrieve ", 12)==0) { if (prefetch_queue("preretrieve", patid, line+12, "", "", "", "", "", "", "", "")) OperatorConsole.printf("Exportconverter%d.%d: queued preretrieve of patient %s from %s\n", N, part, patid, line+12); } /* converter: nop with % item */ else if (memicmp(line, "nop", 3)==0) { OperatorConsole.printf("Exportconverter%d.%d: %s\n", N, part, line); } else if (memicmp(line, "stop", 4)==0) { SystemDebug.printf("Exportconverter%d.%d: stop\n", N, part); rc = 3; } else if (memicmp(line, "silentstop", 10)==0) { rc = 3; } else if (memicmp(line, "defer", 5)==0) { SystemDebug.printf("Exportconverter%d.%d: defer\n", N, part); reset_queue_fails(N); if (DDO) delete DDO; return TRUE; // retry later } /* converter: prefetch */ else if (memicmp(line, "prefetch", 8)==0) { if (prefetch_queue("prefetch", patid, "", "", "", "", "", "", "", "", "")) OperatorConsole.printf("Exportconverter%d.%d: queued prefetch %s\n", N, part, patid); } /* default: execute the command */ else if (strchr(szExecName, '%')) { OperatorConsole.printf("Exportconverter%d.%d executes: %s\n", N, part, line); #ifdef WIN32 WinExec(line, SW_MINIMIZE); #else // char *s=strchr(line, ' '); // *s=0; // BackgroundExec(line, s+1); system(line); #endif ImagesExported++; } /* for backwards compatibility: execute executable with single parameter */ else #ifdef WIN32 { int r = spawnlpe(_P_WAIT, szExecName, szExecName, /* argv[0] */ pszFileName, /* argv[1] */ NULL, /* Allways NULL */ NULL); /* Environment */ if (r == -1) OperatorConsole.printf("***Exportconverter%d: Spawning '%s' failed (argv=%s)\n", N, szExecName, pszFileName); ImagesExported++; } #else // BackgroundExec(szExecName, pszFileName); { char line[1000]; sprintf(line, "%s %s", szExecName, pszFileName); system(line); ImagesExported++; } #endif } // process next command if (szNext[0]==0) break; strcpy(szExecName, szNext); part++; if (rc==3) break; } if (DDO) delete DDO; return FALSE; } void CallExportConverters(char *pszFileName, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called) { char szRootSC[64]; char szEntry[32]; char szTemp[32]; int i, iNbConverters; if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return; if (!GetPrivateProfileString(szRootSC, "ExportConverters", "0", szTemp, 128, ConfigFile)) return; iNbConverters = atoi(szTemp); if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters; /* Loop over all converters */ for(i=0; i<iNbConverters; i++) CallExportConverterN(pszFileName, i, pszModality, pszStationName, pszSop, patid, calling, called, NULL, NULL); } // forward reference void SetStringVR(VR **vr, int g, int e, char *String); static void NewTempFile(char *name, char *ext); // external reference from nkiqrsop.cxx void SaveDICOMDataObject(char *Filename, DICOMDataObject* pDDO); static VR *VariableVRs[3] = {NULL, NULL, NULL}; // variables x, y, z // operates synchronously on image BEFORE it is stored in the database // For general scripting use: // CallImportConverterN(DDO, -1, NULL, NULL, NULL, NULL, NULL, NULL, script); int CallImportConverterN(DICOMDataObject *DDO, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called, char *Storage) { char szRootSC[64]; char szEntry[32]; char szTemp[66]; int i, MaxLength; char szExecName[512], szNext[512]; char szExecModality[66]; char szExecStationName[66]; char szExecFilter[512]; char ImportCalledAE[18], ImportCallingAE[18], Called[18], Calling[18]; int rc, part, skipping; if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return FALSE; /* filter using modality, stationname, calling and called */ if (pszModality) { sprintf(szEntry, "ImportModality%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", szExecModality, 64, ConfigFile)) return FALSE; if (!match(pszModality, szExecModality)) return FALSE; } if (pszStationName) { sprintf(szEntry, "ImportStationName%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", szExecStationName, 64, ConfigFile)) return FALSE; if (!match(pszStationName, szExecStationName)) return FALSE; } if (calling) { sprintf(szEntry, "ImportCallingAE%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", ImportCallingAE, 18, ConfigFile)) return FALSE; if (!match(calling, ImportCallingAE)) return FALSE; } if (called) { sprintf(szEntry, "ImportCalledAE%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "*", ImportCalledAE, 18, ConfigFile)) return FALSE; if (!match(called, ImportCalledAE)) return FALSE; } /* get the import converter name */ if (called && calling) { sprintf(szEntry, "ImportConverter%d", N); if (!GetPrivateProfileString(szRootSC, szEntry, "silentstop", szExecName, 512, ConfigFile)) return FALSE; } else { strcpy(szExecName, Storage); } /* only import converters using %x syntax are allowed */ rc = 1; // status for if statement, destroy and stop part = 0; skipping = 0; while(1) { char line[1000], vr[256]; int i=0, l, L, len; unsigned int g, e; char *p; VR *pVR, *newVR; DICOMDataObject DDO2; Array < DICOMDataObject * > ADDO; char level; szNext[0] = 0; if (skipping || rc==4) // {} block being skipped { if (szExecName[0]=='{') skipping++, rc=0; else if (szExecName[0]=='}') skipping--, rc=0; } // find ; not in string: splits import commands int instring=0; L = strlen(szExecName); for (int k=0; k<L; k++) { if (szExecName[k]=='"') instring = !instring; if (szExecName[k]==';' && instring==0) { szExecName[k] = 0; // split command while (szExecName[k+1]==' ') k++; // skip spaces after ; strcpy(szNext, szExecName+k+1); // remaining for next break; } } /* substitute %x variables and remove possible { and } at begin of statement */ line[0] = 0; L = strlen(szExecName); while (i<L) { if (i==0 && szExecName[i] == '{') {i++; while(szExecName[i]==' ')i++;} else if (i==0 && szExecName[i] == '}') {i++; while(szExecName[i]==' ')i++;} else if (szExecName[i] == '%') { char *ps = line + strlen(line); switch(tolower(szExecName[i+1])) { case 'm': if (pszModality) strcat(line, pszModality); // %m=modality else { char result[256]; SearchDICOMObject(DDO, "0008,0060", result); strcat(line, result); } break; case 's': if (pszStationName) strcat(line, pszStationName);// %s=stationname else { char result[256]; SearchDICOMObject(DDO, "0008,1110", result); strcat(line, result); } break; case 'o': if (pszSop) strcat(line, pszSop); // %o=object instance else { char result[256]; SearchDICOMObject(DDO, "0008,0018", result); strcat(line, result); } break; case 'i': if (patid) strcat(line, patid); // %i=patient ID else { char result[256]; SearchDICOMObject(DDO, "0010,0020", result); strcat(line, result); } break; case 'u': Calling[0]=0; if (calling) strcpy(Calling, calling); while (strlen(Calling)>0 && Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0; strcat(line, Calling); // %u=SCU break; case 'c': Called[0]=0; if (called) strcpy(Called, called); while (strlen(Called)>0 && Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0; strcat(line, Called); // %c=calledAE = scp break; case 'd': time_t TimeOfDay; // %d=date and time char TimeString[128], buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; strcat(line, TimeString); break; case 'n': strcat(line, "\n"); // %n=newline break; case '%': strcat(line, "%"); // %%=% break; case 'x': // %x, %y, %z are general purpose variables case 'y': case 'z': pVR = VariableVRs[tolower(szExecName[i+1])-'x']; if (!pVR) pVR = new VR; VariableVRs[tolower(szExecName[i+1])-'x'] = pVR; strncpy(vr, (char*)pVR->Data, pVR->Length); vr[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (vr[len] == ' ') vr[len] = 0; else break; len--; } strcat(line, vr); break; case 'v': // %Vxxxx,yyyy=any vr (group and element must have 4 digits) char result[256]; // %V*xxxx,yyyy=any vr in any sequence i += SearchDICOMObject(DDO, szExecName+i+2, result); strcat(line, result); break; case 'q': level = szExecName[i+2]; // %QXxxxx,yyyy=from db (group and element must have 4 digits) g = htoin(szExecName+i+3, 4); e = htoin(szExecName+i+8, 4); switch(level) { case 'p': case 'P': // %QPxxxx,yyyy=query from patient db on patid SetStringVR(&pVR, 0x0008, 0x0052, "PATIENT"); DDO2.Push(pVR); pVR = DDO->GetVR(0x0010, 0x0020); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); SetStringVR(&pVR, g, e, ""); DDO2.Push(pVR); QueryOnPatient (&DDO2, &ADDO); } break; case 's': case 'S': // %QSxxxx,yyyy=from study db on patid and study uid SetStringVR(&pVR, 0x0008, 0x0052, "STUDY"); DDO2.Push(pVR); pVR = DDO->GetVR(0x0010, 0x0020); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); pVR = DDO->GetVR(0x0020, 0x000d); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); SetStringVR(&pVR, g, e, ""); DDO2.Push(pVR); QueryOnStudy (&DDO2, &ADDO); } } break; case 'e': case 'E': // %QExxxx,yyyy=from series db on patid, study and series uid SetStringVR(&pVR, 0x0008, 0x0052, "SERIES"); DDO2.Push(pVR); pVR = DDO->GetVR(0x0010, 0x0020); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); pVR = DDO->GetVR(0x0020, 0x000d); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); pVR = DDO->GetVR(0x0020, 0x000e); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); SetStringVR(&pVR, g, e, ""); DDO2.Push(pVR); QueryOnSeries (&DDO2, &ADDO); } } } break; case 'w': case 'W': // %QWxxxx,yyyy=from worklist db on accession number SetStringVR(&pVR, 0x0008, 0x0052, "MODALITYWORKLIST"); DDO2.Push(pVR); pVR = DDO->GetVR(0x0008, 0x0050); if (pVR && pVR->Length) { newVR = new VR(pVR->Group, pVR->Element, pVR->Length, (BOOL) TRUE); memcpy(newVR->Data, pVR->Data, pVR->Length); DDO2.Push(newVR); SetStringVR(&pVR, g, e, ""); DDO2.Push(pVR); QueryOnModalityWorkList (&DDO2, &ADDO); } break; default: break; } if (ADDO.GetSize()>0) pVR = ADDO.Get(0)->GetVR(g, e); else pVR = NULL; if (pVR) { strncpy(vr, (char*)pVR->Data, pVR->Length); vr[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (vr[len] == ' ') vr[len] = 0; else break; len--; } strcat(line, vr); } for (int j=0; j<ADDO.GetSize(); j++) { while(pVR=ADDO.Get(j)->Pop()) delete pVR; } i+=10; break; } i += 2; // get substring of variable if (szExecName[i]=='[') { int a=0, b=-1; sscanf(szExecName+i, "[%d,%d]", &a, &b); for (;i<L;i++) if (szExecName[i-1]==']') break; if (a>strlen(ps)) a=strlen(ps); if (b>strlen(ps)) b=strlen(ps); if (b>=a) {memmove(ps, ps+a, b-a+1); ps[b-a+1]=0;} } } else { l = strlen(line); line[l] = szExecName[i++]; line[l+1] = 0; } } if (skipping) // {} block being skipped { SystemDebug.printf("Importconverter%d.%d skipped\n", N, part); } else if (rc==4) // ifxxxx statement causes a skip { rc = 0; SystemDebug.printf("Importconverter%d.%d not executed because of previous statement\n", N, part); } /* converter: write "string" to file - uses text file, use %n for newline */ else if (memicmp(line, "write \"", 7)==0) { char string[256]; char *file; FILE *f; strcpy(string, line+7); p = strstr(string, "\" to "); if (!p) p = strstr(string, "\" TO "); if (p) { *p=0; OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); file = p+5; f = fopen(file, "wt"); if (f) { fputs(string, f); fclose(f); } else OperatorConsole.printf("*** Importconverter%d.%d: Failed to write to file %s\n", N, part, file); } } /* converter: append "string" to file - uses text file, use %n for newline */ else if (memicmp(line, "append \"", 8)==0) { char string[256]; char *file; FILE *f; strcpy(string, line+8); p = strstr(string, "\" to "); if (!p) p = strstr(string, "\" TO "); if (p) { *p=0; OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); file = p+5; f = fopen(file, "at"); if (f) { fputs(string, f); fclose(f); } else OperatorConsole.printf("*** Importconverter%d.%d: Failed to append to file %s\n", N, part, file); } } /* converter: set xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: set xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: set x to "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: set y if "items like %Vxxxx,yyyy or %QP0010,0030" */ else if (memicmp(line, "set ", 4)==0) { char string[1024]; char *file; int offset=13; if (strchr("xyzXYZ", line[4])) { g=e=0; offset = 5; } else { g = htoin(line+4, 4); e = htoin(line+9, 4); } if (memicmp(line+offset, " to \"", 4)==0 || memicmp(line+offset, " if \"", 4)==0) { strcpy(string, line+offset+5); p = strrchr(string, '"'); if (p) { *p=0; int len = strlen(string); VR *vr; if (len&1) { len++; strcat(string, " "); } if (memicmp(line+offset, " to \"", 4)==0 || len>0) // if does not set when len==0 { if (g==0 && e==0) { vr = VariableVRs[tolower(line[4])-'x']; if (!vr) vr = new VR; VariableVRs[tolower(line[4])-'x'] = vr; } else vr = DDO->GetVR(g, e); if(!vr) { vr = new VR(g, e, len, (BOOL)TRUE); DDO->Push(vr); } else vr->ReAlloc(len); memcpy(vr->Data, string, len); OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); } else SystemDebug.printf("Importconverter%d.%d executes void: %s\n", N, part, line); } } } /* converter: setifempty xxxx,yyyy to "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: setifempty xxxx,yyyy if "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: setifempty x to "items like %Vxxxx,yyyy or %QP0010,0030" */ /* converter: setifempty y if "items like %Vxxxx,yyyy or %QP0010,0030" */ else if (memicmp(line, "setifempty ", 11)==0) { char string[1024]; char *file; int offset=20; if (strchr("xyzXYZ", line[11])) { g=e=0; offset = 12; } else { g = htoin(line+11, 4); e = htoin(line+16, 4); } if (memicmp(line+offset, " to \"", 4)==0 || memicmp(line+offset, " if \"", 4)==0) { strcpy(string, line+offset+5); p = strrchr(string, '"'); if (p) { VR *vr; *p=0; int len = strlen(string); if (len&1) { len++; strcat(string, " "); } if (memicmp(line+offset, " if \"", 4)==0 || len>0) // if does not set when len==0 { if (g==0 && e==0) { vr = VariableVRs[tolower(line[11])-'x']; if (!vr) vr = new VR; VariableVRs[tolower(line[11])-'x'] = vr; } else vr = DDO->GetVR(g, e); if(!vr) { vr = new VR(g, e, len, (BOOL)TRUE); memcpy(vr->Data, string, len); DDO->Push(vr); OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); } else if (vr->Length==0) { vr->ReAlloc(len); memcpy(vr->Data, string, len); OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); } else SystemDebug.printf("Importconverter%d.%d executes void: %s\n", N, part, line); } else SystemDebug.printf("Importconverter%d.%d executes void: %s\n", N, part, line); } } } /* converter: delete xxxx,yyyy */ else if (memicmp(line, "delete ", 7)==0) { g = htoin(line+7, 4); e = htoin(line+12, 4); pVR = DDO->GetVR(g, e); if (pVR) { DDO->DeleteVR(pVR); OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); } else SystemDebug.printf("Importconverter%d.%d executes void: %s\n", N, part, line); } /* converter: save to filename (filename can be generated using all % tricks) */ else if (memicmp(line, "save to ", 8)==0) { char *file = line+8; OperatorConsole.printf("Importconverter%d.%d executes: %s\n", N, part, line); DICOMDataObject *pDDO = MakeCopy(DDO); SaveDICOMDataObject(file, pDDO); delete pDDO; } /* converter: process with (command line can be generated using all % tricks, tempfile appended) */ else if (memicmp(line, "process with ", 13)==0) { char cline[512]; char tempfile[512]; DICOMDataObject *DO2; PDU_Service PDU; PDU.AttachRTC(&VRType); NewTempFile(tempfile, ".dcm"); strcpy(cline, line+13); if (cline[strlen(cline)-1]!=' ') strcat(cline, " "); strcat(cline, tempfile); OperatorConsole.printf("Importconverter%d.%d executes: process with %s\n", N, part, cline); SaveDICOMDataObject(tempfile, DDO); DDO->Reset(); system(cline); DO2 = PDU.LoadDICOMDataObject(tempfile); while ( pVR = DO2->Pop() ) { DDO->Push(pVR); } delete DO2; } /* converter: destroy (will prevent the image from being stored in the database) */ else if (memicmp(line, "destroy", 7)==0 && calling && called) { OperatorConsole.printf("Importconverter%d.%d: destroyed received image\n", N, part); rc = 2; } /* converter: storage (sets preferred device for storing image, e.g, STORAGE MAG1) */ /* disabled for general scripting */ else if (memicmp(line, "storage ", 8)==0 && called && calling) { OperatorConsole.printf("Importconverter%d.%d: sets preferred storage to %s\n", N, part, line+8); strcpy(Storage, line+8); } /* converter: compression (sets preferred compression for storing image, e.g, COMPRESSION un) */ else if (memicmp(line, "compression ", 12)==0) { OperatorConsole.printf("Importconverter%d.%d: compression to %s\n", N, part, line+12); recompress(&DDO, line+12, "", line[12]=='n' || line[12]=='N'); } /* converter: prefetch */ else if (memicmp(line, "prefetch", 8)==0) { if (prefetch_queue("prefetch", patid, "", "", "", "", "", "", "", "", "")) OperatorConsole.printf("Importconverter%d.%d: queued prefetch %s\n", N, part, patid); } /* converter: preretrieve */ else if (memicmp(line, "preretrieve ", 12)==0) { if (prefetch_queue("preretrieve", patid, line+12, "", "", "", "", "", "", "", "")) OperatorConsole.printf("Importconverter%d.%d: queued preretrieve of patient %s from %s\n", N, part, patid, line+12); } /* converter: stop and silentstop (will prevent further converters from running for this image) */ else if (memicmp(line, "stop", 4)==0) { SystemDebug.printf("Importconverter%d.%d: stop\n", N, part); rc = 3; } else if (memicmp(line, "silentstop", 10)==0) { rc = 3; } /* converter: if "string" (only execute next converter if string not empty) */ else if (memicmp(line, "ifnotempty \"", 12)==0) { char string[1024]; char *p; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); int len = strlen(string); if (len==0) rc = 4; } } /* converter: ifempty "string" (only execute next converter if string empty) */ else if (memicmp(line, "ifempty \"", 9)==0) { char string[1024]; char *p; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); int len = strlen(string); if (len!=0) rc = 4; } } /* converter: ifequal "string1","string2" (only execute next converter if string1 equals string2) */ else if (memicmp(line, "ifequal \"", 9)==0) { char string[1024]; char *p, *string2; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); int cmp = strcmp(string, string2); if (cmp!=0) rc = 4; } } } /* converter: ifnotequal "string1","string2" (only execute next converter if string1 not equals string2) */ else if (memicmp(line, "ifnotequal \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); int cmp = strcmp(string, string2); if (cmp==0) rc = 4; } } } /* converter: ifmatch "string1","string2" (only execute next converter if string1 matches string2 - case insensitive) */ else if (memicmp(line, "ifmatch \"", 9)==0) { char string[1024]; char *p, *string2; strcpy(string, line+9); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (!match(string, string2)) rc = 4; } } } /* converter: ifnotmatch "string1","string2" (only execute next converter if string1 not matches string2 - case insensitive) */ else if (memicmp(line, "ifnotmatch \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (match(string, string2)) rc = 4; } } } /* converter: ifnumequal "string1","string2" (only execute next converter if string1 num equals string2 - integer) */ else if (memicmp(line, "ifnumequal \"", 12)==0) { char string[1024]; char *p, *string2; strcpy(string, line+12); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)!=atoi(string2)) rc = 4; } } } /* converter: ifnumnotequal "string1","string2" (only execute next converter if string1 num not equals string2 - integer) */ else if (memicmp(line, "ifnumnotequal \"", 15)==0) { char string[1024]; char *p, *string2; strcpy(string, line+15); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)==atoi(string2)) rc = 4; } } } /* converter: ifnumgreater "string1","string2" (only execute next converter if string1 num greater than string2 num - integer) */ else if (memicmp(line, "ifnumgreater \"", 14)==0) { char string[1024]; char *p, *string2; strcpy(string, line+14); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)<=atoi(string2)) rc = 4; } } } /* converter: ifnumless "string1","string2" (only execute next converter if string1 num less than string2 num - integer) */ else if (memicmp(line, "ifnumless \"", 11)==0) { char string[1024]; char *p, *string2; strcpy(string, line+11); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (atoi(string)>=atoi(string2)) rc = 4; } } } /* converter: between "string1","string2" (execute next converter on time in hours: between "9", "17"; defer) */ else if (memicmp(line, "between \"", 9)==0) { char string[1024]; char *p, *string2; int h1, h2, h; struct tm tmbuf; time_t t = time(NULL); localtime_r(&t, &tmbuf); h = tmbuf.tm_hour; strcpy(string, line+9); h1 = atoi(string); p = strrchr(string, '"'); if (p) { *p=0; p = strstr(string, "\",\""); if (!p) p = strstr(string, "\", \""); if (p) { string2 = strchr(p+1, '"')+1; *p=0; h2 = atoi(string2); SystemDebug.printf("Importconverter%d.%d executes: %s\n", N, part, line); if (h2>=h1 && (h <h1 || h>=h2)) rc = 4; // between "9", "17": skip if h<9 or h>=17 if (h2< h1 && (h <h1 && h>=h2)) rc = 4; // between "17", "9": skip if h<=17 and h>=9 } } } /* converter: nop (no operation) */ else if (memicmp(line, "nop", 3)==0) { OperatorConsole.printf("Importconverter%d.%d: %s\n", N, part, line); } // process next command if (szNext[0]==0) break; strcpy(szExecName, szNext); part++; if (rc==3 || rc==2) break; // stop destroy } return rc; } BOOL CallImportConverters(DICOMDataObject *DDO, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called, char *Storage) { char szRootSC[64]; char szEntry[32]; char szTemp[32]; int i, iNbConverters; int rc; if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return FALSE; if (!GetPrivateProfileString(szRootSC, "ImportConverters", "99", szTemp, 128, ConfigFile)) return FALSE; iNbConverters = atoi(szTemp); /* Loop over all converters */ rc = 0; for(i=0; i<iNbConverters; i++) { //if (rc==4) // ifxxxx statement causes a skip //{ rc = 0; // OperatorConsole.printf("Importconverter%d not executed because of previous statement\n", i); //} //else rc = CallImportConverterN(DDO, i, pszModality, pszStationName, pszSop, patid, calling, called, Storage); if (rc==3 || rc==2) break; // stop destroy } // the status of the last one is returned: FALSE means destroy command (status 2) was executed return !(rc==2); } ////////////////////////////////////////////////////////////////////////////////// /* This code is a simple thread safe queue with its own processing thread */ ////////////////////////////////////////////////////////////////////////////////// #ifndef WIN32 #define EnterCriticalSection(a) pthread_mutex_lock(a) #define LeaveCriticalSection(a) pthread_mutex_unlock(a) #define CRITICAL_SECTION pthread_mutex_t #define InitializeCriticalSection(a) pthread_mutex_init(a, NULL); #define mkdir(a) mkdir(a, 0777) #endif struct conquest_queue { int top; int bottom; int num; int entrysize; char *data; #ifdef WIN32 HANDLE threadhandle; #else pthread_t threadhandle; #endif CRITICAL_SECTION critical; int delay; BOOL (*process) (char *, ExtendedPDU_Service *PDU, char *); BOOL (*mayprocess)(char *, ExtendedPDU_Service *PDU, char *); int fails; // counts failures time_t lastfailtime; // set on failure, cleared on success int maxfails; // if set and exceeded stop retrying char failfile[512]; // file to store failed entries in ExtendedPDU_Service *PDU; // to allow keeping association open time_t opentime; // set on success int pdu_refreshdelay; // clear accepted syntaxes after .. s (use long time) int pdu_closedelay; // close unused pdu after .. s (use short time) int pdu_release; // if set, release pdu else just drop link char *ForwardLastUID; // remember last uid of link (hang up?) } q1; extern int NumIndexing; // from odbci.cpp: is -1 on startup, >0 during DBF indexing static BOOL WINAPI processthread(struct conquest_queue *q) { char *data = (char *)malloc(q->entrysize); while (1) { while (1) { EnterCriticalSection(&q->critical); if (q->top!=q->bottom) { memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize); // it is possible to delay processing of queue through this function if (q->mayprocess) { if (!q->mayprocess(data, q->PDU, q->ForwardLastUID)) { LeaveCriticalSection(&q->critical); Sleep(q->delay); continue; } } q->bottom = (q->bottom+1)%q->num; LeaveCriticalSection(&q->critical); // only try to process if last failure was more than FailHoldOff seconds ago if (time(NULL)-q->lastfailtime > FailHoldOff) { if (q->process(data, q->PDU, q->ForwardLastUID)) { q->lastfailtime = time(NULL); // failed q->fails++; // store failures if (q->failfile[0]) { FILE *f = fopen(q->failfile, "ab"); if (f) { fwrite(data, q->entrysize, 1, f); fclose(f); OperatorConsole.printf("*** Queue: holding processing of file %s\n", data); } } } else { q->lastfailtime= 0; // remember that last process was a success q->opentime = time(NULL); // PDU must be open by now q->fails = 0; } } else { // store failures (actually these were not even tried) if (q->failfile[0]) { FILE *f = fopen(q->failfile, "ab"); if (f) { fwrite(data, q->entrysize, 1, f); fclose(f); OperatorConsole.printf("*** Queue: holding processing of file %s\n", data); } } } break; // this break avoids delays when the queue is not empty } LeaveCriticalSection(&q->critical); Sleep(q->delay); // Retry logic: RetryDelay s after last failure retry to process the data // This condition would also be at startup: therefore wait until DB completely indexed if (time(NULL)-q->lastfailtime>RetryDelay && q->failfile[0] && NumIndexing==0) { int rec=0, done=0, count=0; FILE *f = fopen(q->failfile, "r+b"); if (f) { while(1) { fseek(f, rec * q->entrysize, SEEK_SET); if (fread(data, 1, q->entrysize, f)!=q->entrysize) // if eof -> done { done=1; break; } if (data[0]) // filled entry ? { OperatorConsole.printf("Queue: retrying processing of file %s\n", data); if (q->process(data, q->PDU, q->ForwardLastUID)) { q->lastfailtime = time(NULL); // failed again q->fails++; if (q->maxfails && (q->fails>q->maxfails)) { OperatorConsole.printf("*** Queue: %d retries exceeds set maximum of %d - giving up\n", q->fails, q->maxfails); q->lastfailtime = 0; q->fails = 0; done = 1; } break; // retry later } else { q->lastfailtime = 0; q->opentime = time(NULL); // PDU must be open by now q->fails = 0; data[0]=0; // mark data as processed fseek(f, rec * q->entrysize, SEEK_SET); fwrite(data, 1, 1, f); count++; // every 10 files make time to process.. if(count>10) break; // ..queue entries that are freshly created } } rec++; // next entry in file } fclose(f); if (done) unlink(q->failfile); // delete file when not needed anymore } } for(int i=0; i<MAXExportConverters; i++) { if (q->PDU && (time(NULL)-q->opentime > q->pdu_closedelay)) // close unused association after 5 seconds { if (q->PDU[i].Link.Connected) //q->PDU[i].Close(); just hangup without AReleaseRQ: otherwise server sometimes fails to reconnect if (q->pdu_release) q->PDU[i].Close(); else q->PDU[i].Link.Close(); } if (q->PDU && (time(NULL)-q->opentime > q->pdu_refreshdelay)) // clean collected sopclasses after one hour of inactivity { if (!q->PDU[i].Link.Connected) q->PDU[i].ClearAbstractSyntaxs(); q->opentime = time(NULL); } } } } free(data); return TRUE; } struct conquest_queue *new_queue(int num, int size, int delay, BOOL (*process)(char *, ExtendedPDU_Service *PDU, char *), ExtendedPDU_Service *PDU, int maxfails) { struct conquest_queue *result; unsigned long ThreadID; result = new conquest_queue; result->top = 0; result->bottom = 0; result->num = num; result->entrysize = size; result->delay = delay; result->process = process; result->mayprocess = NULL; result->data = (char *)malloc(num * size); result->fails = 0; result->maxfails = maxfails; result->lastfailtime = 0; result->failfile[0] = 0; result->PDU = PDU; result->opentime = 0; result->pdu_refreshdelay = 3600; result->pdu_closedelay = 5; result->pdu_release = 0; result->ForwardLastUID = NULL; InitializeCriticalSection(&result->critical); /* Note: since the queue is thread safe it is possible to start more than one thread to service it */ #ifdef WIN32 result->threadhandle = CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) processthread, result, 0, &ThreadID); #else pthread_create(&result->threadhandle, NULL, (void*(*)(void*))processthread, (void *)result); pthread_detach(result->threadhandle); #endif return result; }; void into_queue(struct conquest_queue *q, char *in) { while (1) { EnterCriticalSection(&q->critical); if ((q->top+1)%q->num != q->bottom) { memcpy(q->data + q->top * q->entrysize, in, q->entrysize); q->top = (q->top+1)%q->num; LeaveCriticalSection(&q->critical); return; } LeaveCriticalSection(&q->critical); Sleep(q->delay); } } // enters entry into queue if first numunique characters are not there. // note: will discard entry when no space in queue // intended for prefetching stuff: use a large queue BOOL into_queue_unique(struct conquest_queue *q, char *in, int numunique) { int i; EnterCriticalSection(&q->critical); // no space! if ((q->top+1)%q->num == q->bottom) { LeaveCriticalSection(&q->critical); return FALSE; } // search for identical items for (i=q->bottom; i!=(q->top+1)%q->num; i = (i+1)%q->num) { if (memcmp(q->data + i * q->entrysize, in, numunique)==0) { LeaveCriticalSection(&q->critical); return FALSE; } } // enter new item memcpy(q->data + q->top * q->entrysize, in, q->entrysize); q->top = (q->top+1)%q->num; LeaveCriticalSection(&q->critical); return TRUE; } ////////////////////////////////////////////////////////////////////////////////// // This code starts a thread for each defined export converter ////////////////////////////////////////////////////////////////////////////////// static struct conquest_queue **eqN = NULL; static ExtendedPDU_Service ForwardPDU[MAXExportConverters][MAXExportConverters]; // max 20*20 with remaining association BOOL exportprocessN(char *data, ExtendedPDU_Service *PDU, char *t) { return CallExportConverterN(data, data[1024+18+18+66], data+1024, data+1024+18, data+1024+18+18, data+1024+18+18+66+4, data+1024+18+18+66+4+66, data+1024+18+18+66+4+66+18, PDU, t); } void reset_queue_fails(int N) { eqN[N]->fails = 0; } void export_queueN(struct conquest_queue **q, char *pszFileName, int N, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called) { char data[1536]; if (!*q) { char szRootSC[64], szTemp[32]; *q = new_queue(QueueSize, 1536, 100, exportprocessN, N>=MAXExportConverters ? NULL : ForwardPDU[N], 0); sprintf((*q)->failfile, "ExportFailures%s_%d", Port, N); (*q)->ForwardLastUID = (char *) malloc(MAXExportConverters * 66); memset((*q)->ForwardLastUID, 0, MAXExportConverters * 66); GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile); GetPrivateProfileString(szRootSC, "ForwardAssociationRefreshDelay", "3600", szTemp, 128, ConfigFile); (*q)->pdu_refreshdelay = atoi(szTemp); GetPrivateProfileString(szRootSC, "ForwardAssociationCloseDelay", "5", szTemp, 128, ConfigFile); (*q)->pdu_closedelay = atoi(szTemp); GetPrivateProfileString(szRootSC, "ForwardAssociationRelease", "1", szTemp, 128, ConfigFile); (*q)->pdu_release = atoi(szTemp); GetPrivateProfileString(szRootSC, "MaximumExportRetries", "0", szTemp, 128, ConfigFile); (*q)->maxfails = atoi(szTemp); } if (pszFileName==NULL) return; memset(data, 0, 1536); strcpy(data, pszFileName); strcpy(data+1024, pszModality); strcpy(data+1024+18, pszStationName); strcpy(data+1024+18+18, pszSop); data[1024+18+18+66] = N; strcpy(data+1024+18+18+66+4, patid); if(calling) strcpy(data+1024+18+18+66+4+66, calling); if(called) strcpy(data+1024+18+18+66+4+66+18, called); into_queue(*q, data); }; // This routine queues all export converter requests. Use instead of CallExportConverters void QueueExportConverters(char *pszFileName, char *pszModality, char *pszStationName, char *pszSop, char *patid, char *calling, char *called) { char szRootSC[64]; char szEntry[32]; char szTemp[32]; int i, iNbConverters; if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return; if (!GetPrivateProfileString(szRootSC, "ExportConverters", "0", szTemp, 128, ConfigFile)) return; iNbConverters = atoi(szTemp); if (!iNbConverters) return; if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters; if (!eqN) { eqN = (struct conquest_queue **)malloc(iNbConverters * sizeof(struct conquest_queue *)); memset(eqN, 0, iNbConverters * sizeof(struct conquest_queue *)); }; /* Loop over all converters */ for(i=0; i<iNbConverters; i++) { export_queueN(&eqN[i], pszFileName, i, pszModality, pszStationName, pszSop, patid, calling, called); } } ////////////////////////////////////////////////////////////////////////////////// // This code is a queue for filecopy requests; it is used to speed mirror copying ////////////////////////////////////////////////////////////////////////////////// // return TRUE if it worthwile to retry (copy failed) BOOL copyprocess(char *data, ExtendedPDU_Service *PDU, char *dum) { if (DFileCopy2(data, data+1024, 0)) { OperatorConsole.printf("Mirror copy: %s\n", data+1024); return FALSE; } else { OperatorConsole.printf("***Writing mirror copy failed: %s\n", data+1024); return TRUE; } } void mirrorcopy_queue(char *pszFileName, char *pszDestination) { char data[2048]; static struct conquest_queue *q = NULL; if (!q) { q = new_queue(QueueSize, 2048, 100, copyprocess, NULL, 0); sprintf(q->failfile, "CopyFailures%s", Port); } if (pszFileName==NULL) return; strcpy(data, pszFileName); strcpy(data+1024, pszDestination); into_queue(q, data); }; ////////////////////////////////////////////////////////////////////////////////// // This code is a queue for prefetch and preforward requests ////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // read all files of a patient (to populate cache) use windows call for windows version BOOL TestFile(char *FullFilename, char *status); static int DFileRead(char *source, int MaxRead) { BOOL err_status = TRUE; /* Error status */ char *copybuffer; /* The copy buffer */ unsigned bufsize; /* Size of copy buffer */ unsigned long bytes, totbytes; /* Actual transferred bytes */ #ifdef WIN32 HANDLE handle = CreateFile(source, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if( handle == NULL) return FALSE; #else /* Open input file for read-only. parser error if operation fails. */ int inhandle = sopen( source, O_RDONLY | O_BINARY, SH_DENYNO, S_IREAD); if( inhandle == -1) return FALSE; #endif /* get a large buffer */ bufsize = 0x4000; copybuffer = (char *)malloc(bufsize); if (copybuffer == NULL) { #ifdef WIN32 CloseHandle(handle); #else close(inhandle); #endif return -1; } totbytes=0; while( /*!eof(inhandle) && */err_status) { #ifdef WIN32 ReadFile(handle, copybuffer, bufsize, &bytes, NULL); #else bytes= (unsigned)read( inhandle, copybuffer, bufsize); #endif //#ifndef WIN32 if (bytes == 0) break; //#endif if (bytes == (unsigned) -1) { err_status= FALSE; break; } totbytes += (bytes+512)>>10; if (MaxRead && totbytes>(MaxRead>>10)) break; } free(copybuffer); #ifdef WIN32 CloseHandle(handle); #else close(inhandle); #endif return totbytes; } char LastPrefetch[65] = ""; BOOL MakeSafeString (char *in, char *string ); BOOL PrefetchPatientData (char *PatientID, int MaxRead) { Database aDB; char Tables[512], DeviceName[512], ObjectFile[1024], FileNameFrom[1024]; char QueryString[512], PatientIDValue[512], PhysicalFrom[1024]; SQLLEN SQLResultLength; BOOL Status=TRUE; char error[256]; if (strcmp(PatientID, LastPrefetch)==0) return TRUE; OperatorConsole.printf("Prefetching patient %s\n", PatientID); sprintf(Tables, "%s", ImageTableName); if(!aDB.Open(DataSource, UserName, Password, DataHost)) { OperatorConsole.printf("***Unable to open database %s as user %s on %s\n", DataSource, UserName, DataHost); return FALSE; } MakeSafeString(PatientID, PatientIDValue); sprintf(QueryString, "DICOMImages.ImagePat = %s", PatientIDValue); if (!aDB.Query(Tables, "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL)) { OperatorConsole.printf("***Unable to query for image records for prefetch\n"); aDB.Close(); return FALSE; } aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength); aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength); while (aDB.NextRecord()) { if (!FindPhysicalDevice(DeviceName, PhysicalFrom, ObjectFile)) continue; strcpy(FileNameFrom, PhysicalFrom); strcat(FileNameFrom, ObjectFile); SystemDebug.printf("Prefetching file: %s\n", FileNameFrom); if (MaxRead<0) { if (!TestFile(FileNameFrom, error)) { OperatorConsole.printf("***Prefetch read failed for file: %s (%s)\n", FileNameFrom, error); Status = FALSE; } } else { if (DFileRead(FileNameFrom, MaxRead)<0) { OperatorConsole.printf("***Prefetch read failed for file: %s\n", FileNameFrom); Status = FALSE; } } } aDB.Close(); strcpy(LastPrefetch, PatientID); return Status; } // move patient from this to other server: returns TRUE is meaningful to retry static BOOL DcmMove(char *patid, char* pszSourceAE, char* pszDestinationAE, char *studyuid, char *seriesuid, char *compress, char *modality, char *date, char *sop, char *imagetype, char *seriesdesc, int id) { PDU_Service PDU; DICOMCommandObject DCO; DICOMCommandObject DCOR; DICOMDataObject DDO; DICOMDataObject DDOR; UID uid; VR *vr; LE_UINT16 command, datasettype, messageid, priority; BYTE SOP[64]; BYTE AppTitle[64], host[64], port[64], compr[64]; BOOL rc = FALSE; if (strcmp(pszSourceAE, "(local)")==0) pszSourceAE = (char *)MYACRNEMA; PDU.ClearAbstractSyntaxs(); PDU.SetLocalAddress((unsigned char*)MYACRNEMA); PDU.SetRemoteAddress((unsigned char*)pszSourceAE); uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU.SetApplicationContext(uid); uid.Set("1.2.840.10008.5.1.4.1.2.1.2"); // patientrootmove PDU.AddAbstractSyntax(uid); if (strcmp(pszSourceAE, (char *)MYACRNEMA)==0) { if(!PDU.Connect((BYTE *)"127.0.0.1", Port)) { OperatorConsole.printf("***forward xxxx to: local server not working\n"); return FALSE; // self not working: no retry } messageid = id; } else { if(!GetACRNema(pszSourceAE, (char *)host, (char *)port, (char *)compr)) { OperatorConsole.printf("***preretrieve: AE not found: %s\n", pszSourceAE); return FALSE; // wrong address no retry } if(!PDU.Connect(host, port)) { OperatorConsole.printf("***preretrieve: could not connect to AE: %s\n", pszSourceAE); return TRUE; // remote not working: retry } messageid = id; // special to indicate move to itself - no import/exportconverters } sprintf((char*) SOP, "1.2.840.10008.5.1.4.1.2.1.2"); vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); command = EN0021; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); priority = 0; vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE); DCO.Push(vr); datasettype = EN0102; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE); DCO.Push(vr); memset((char*)AppTitle, ' ', 20); memcpy((void*)AppTitle, pszDestinationAE, strlen(pszDestinationAE)); vr = new VR(0x0000, 0x0600, 16, (void*)&AppTitle[0], FALSE); DCO.Push(vr); if (*sop) SetStringVR(&vr, 0x0008, 0x0052, "IMAGE"); else if (*modality) SetStringVR(&vr, 0x0008, 0x0052, "SERIES"); else if (*date) SetStringVR(&vr, 0x0008, 0x0052, "SERIES"); else if (*seriesuid) SetStringVR(&vr, 0x0008, 0x0052, "SERIES"); else if (*studyuid) SetStringVR(&vr, 0x0008, 0x0052, "STUDY"); else SetStringVR(&vr, 0x0008, 0x0052, "PATIENT"); DDO.Push(vr); if (*patid) { SetStringVR(&vr, 0x0010, 0x0020, patid); DDO.Push(vr); } if (*studyuid) { vr = new VR(0x0020, 0x000d, strlen(studyuid), (void*)studyuid, FALSE ); DDO.Push(vr); } if (*seriesuid) { vr = new VR(0x0020, 0x000e, strlen(seriesuid), (void*)seriesuid, FALSE ); DDO.Push(vr); } if (*sop) { vr = new VR(0x0008, 0x0018, strlen(sop), (void*)sop, FALSE ); DDO.Push(vr); } if (*modality) { SetStringVR(&vr, 0x0008, 0x0060, modality); DDO.Push(vr); } if (*date) { SetStringVR(&vr, 0x0008, 0x0020, date); DDO.Push(vr); } if (*imagetype) { vr = new VR(0x0008, 0x0008, strlen(imagetype), (void*)imagetype, FALSE ); DDO.Push(vr); } if (*seriesdesc) { vr = new VR(0x0008, 0x103e, strlen(seriesdesc), (void*)imagetype, FALSE ); DDO.Push(vr); } if (*compress) { SetStringVR(&vr, 0x9999, 0x0700, compress); DCO.Push(vr); } uid.Set(SOP); PDU.Write(&DCO, uid); PDU.Write(&DDO, uid); while(TRUE) { if(!PDU.Read(&DCOR)) { OperatorConsole.printf("***preretrieve/forward xxx to: association lost\n"); return TRUE; // associate lost: may retry } if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8021) { OperatorConsole.printf("***preretrieve/forward xxx to: invalid C-move response\n"); rc = FALSE; goto EXIT; // not a C-MOVE-RSP ? no retry } if(DCOR.GetUINT16(0x0000, 0x0800)!=0x0101) { PDU.Read(&DDOR);// ignore the data set DDOR.Reset(); } if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000) { rc = FALSE; goto EXIT; // completed OK, no retry } else if (DCOR.GetUINT16(0x0000, 0x0900)==0xff00) { // continuing no problem DCOR.Reset(); continue; } else { OperatorConsole.printf("***preretrieve/forward xxx to: remote DICOM error\n"); rc = FALSE; // remote DICOM error: NO retry FOR NOW goto EXIT; } DCOR.Reset(); } EXIT: PDU.Close(); return rc; } // delete patient data from this server: always returns FALSE static BOOL DcmDelete(char *patid, char *studyuid, char *seriesuid, char *modality, char *date, char *sop, char *imagetype) { DICOMDataObject DDO; VR *vr; if (*patid) { SetStringVR(&vr, 0x0010, 0x0020, patid); DDO.Push(vr); } if (*studyuid) { vr = new VR(0x0020, 0x000d, strlen(studyuid), (void*)studyuid, FALSE ); DDO.Push(vr); } if (*seriesuid) { vr = new VR(0x0020, 0x000e, strlen(seriesuid), (void*)seriesuid, FALSE ); DDO.Push(vr); } if (*sop) { vr = new VR(0x0008, 0x0018, strlen(sop), (void*)sop, FALSE ); DDO.Push(vr); } if (*modality) { SetStringVR(&vr, 0x0008, 0x0060, modality); DDO.Push(vr); } if (*date) { SetStringVR(&vr, 0x0008, 0x0020, date); DDO.Push(vr); } if (*imagetype) { vr = new VR(0x0008, 0x0008, strlen(imagetype), (void*)imagetype, FALSE ); DDO.Push(vr); } RemoveFromPACS(&DDO, FALSE); return FALSE; } // runs in the thread BOOL prefetchprocess(char *data, ExtendedPDU_Service *PDU, char *dum) { if (memicmp(data+65, "prefetch", 8)==0) PrefetchPatientData(data, 0); if (memicmp(data+65, "forward ", 8)==0) return DcmMove (data, (char *)MYACRNEMA, data+82, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 5); if (memicmp(data+65, "preretrieve", 11)==0) return DcmMove (data, data+82, (char *)MYACRNEMA, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 0xfbad); if (memicmp(data+65, "get ", 4)==0) return DcmMove (data, data+82, (char *)MYACRNEMA, data+100, data+165, data+230, data+256, data+276, data+300, data+366, data+500, 0xfbad); if (memicmp(data+65, "delete ", 7)==0) return DcmDelete(data, data+100, data+165, data+256, data+276, data+300, data+366); if (memicmp(data+65, "process ", 8)==0) #ifdef WIN32 WinExec(data+230, SW_MINIMIZE); #else system(data+230); #endif return FALSE; } // blocks the thread so as not to prefetch too often BOOL mayprefetchprocess(char *data, ExtendedPDU_Service *PDU, char *dum) { if ((*(unsigned int*)(data+596)) + ForwardCollectDelay > time(NULL)) return FALSE; // hold until e.g. 10 minutes past return TRUE; } // enter prefetch or preforward request into queue BOOL prefetch_queue(char *operation, char *patientid, char *server, char *studyuid, char *seriesuid, char *compress, char *modality, char *date, char *sop, char *imagetype, char *seriesdesc) { char data[600]; static struct conquest_queue *q = NULL; if (!q) { char szRootSC[64], szTemp[32]; q = new_queue(QueueSize, 600, 100, prefetchprocess, NULL, 0); q->mayprocess = mayprefetchprocess; sprintf(q->failfile, "DelayedFetchForwardFailures%s", Port); GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile); GetPrivateProfileString(szRootSC, "MaximumDelayedFetchForwardRetries", "0", szTemp, 128, ConfigFile); q->maxfails = atoi(szTemp); } memset(data, 0, 600); strncpy(data, patientid, 64); strncpy(data+65, operation, 16); *(unsigned int*)(data+596) = time(NULL); if (memicmp(data+65, "process ", 8)==0) { strncpy(data+100, studyuid, 64); strncpy(data+165, seriesuid, 64); strncpy(data+230, server, 360); return into_queue_unique(q, data, 230); } else { strncpy(data+82, server, 17); strncpy(data+100, studyuid, 64); strncpy(data+165, seriesuid, 64); strncpy(data+230, compress, 25); strncpy(data+256, modality, 19); strncpy(data+276, date, 23); strncpy(data+300, sop, 64); strncpy(data+366, imagetype, 128); strncpy(data+500, seriesdesc,64); return into_queue_unique(q, data, 596); } }; ////////////////////////////////////////////////////////////////////////////////// // This queue is intended to prefetch (in disk cache) patient data // likely to be requested soon in the time that the server is inactive // Enter P+patientID or S+studyUID to be read using into_queue or enter // empty item to abort current prefetch ////////////////////////////////////////////////////////////////////////////////// static BOOL WINAPI prefetcherthread(struct conquest_queue *q) { char data[66], curitem[65]; Database aDB; char DeviceName[512], ObjectFile[1024], FileNameFrom[1024]; char QueryString[512], QueryValue[512], PhysicalFrom[1024]; SQLLEN SQLResultLength; BOOL Status=TRUE; BOOL qact = FALSE; int count, kb; time_t TimeOfDay; curitem[0]=0; while (1) { while (1) { EnterCriticalSection(&q->critical); if (q->top!=q->bottom) { memcpy(data, q->data + q->bottom * q->entrysize, q->entrysize); q->bottom = (q->bottom+1)%q->num; LeaveCriticalSection(&q->critical); if (data[0]==0 && qact) // abort current prefetch { int skipped = 0; while (aDB.NextRecord()) skipped++; OperatorConsole.printf("Aborted prefetch after reading %d images (%d MB) in %d s, %d images skipped\n", count, (kb+512)>>10, time(NULL) - TimeOfDay, skipped); qact = FALSE; curitem[0]=0; aDB.Close(); break; }; if (data[0]==0) break; // ignore abort when not active if (strcmp(curitem, data+1)==0) break; // already prefetched if (!qact) if(!aDB.Open(DataSource, UserName, Password, DataHost)) { OperatorConsole.printf("***Unable to open database for prefetch\n"); break; }; MakeSafeString(data+1, QueryValue); TimeOfDay = time(NULL); kb = 0; count = 0; if (data[0]=='P') { OperatorConsole.printf("Prefetching patient %s\n", data+1); sprintf(QueryString, "DICOMImages.ImagePat = %s", QueryValue); if (!aDB.Query("DICOMImages", "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL)) { OperatorConsole.printf("***Unable to query for image records for prefetch\n"); break; }; } else { OperatorConsole.printf("Prefetching study %s\n", data+1); sprintf(QueryString, "DICOMSeries.StudyInsta = %s and DICOMSeries.SeriesInst = DICOMImages.SeriesInst", QueryValue); if (!aDB.Query("DICOMSeries, DICOMImages", "DICOMImages.DeviceName, DICOMImages.ObjectFile", QueryString, NULL)) { OperatorConsole.printf("***Unable to query on study for image records for prefetch\n"); break; }; }; aDB.BindField (1, SQL_C_CHAR, DeviceName, 255, &SQLResultLength); aDB.BindField (2, SQL_C_CHAR, ObjectFile, 255, &SQLResultLength); qact = TRUE; strcpy(curitem, data+1); // do not break: delay a bit } else if (qact) { LeaveCriticalSection(&q->critical); if (aDB.NextRecord()) { if (!FindPhysicalDevice(DeviceName, PhysicalFrom, ObjectFile)) break; strcpy(FileNameFrom, PhysicalFrom); strcat(FileNameFrom, ObjectFile); SystemDebug.printf("Prefetching file: %s\n", FileNameFrom); kb += DFileRead(FileNameFrom, 0); count++; break; } else { qact = FALSE; aDB.Close(); OperatorConsole.printf("Prefetch done: read %d images (%d MB) in %d s\n", count, (kb+512)>>10, time(NULL) - TimeOfDay); } } else LeaveCriticalSection(&q->critical); Sleep(q->delay); } } DeleteCriticalSection(&q->critical); return TRUE; } struct conquest_queue *prefetcherqueue; struct conquest_queue *new_prefetcherqueue(void) { struct conquest_queue *result; unsigned long ThreadID; int num=1000, size = 66; result = new conquest_queue; result->top = 0; result->bottom = 0; result->num = num; result->entrysize = size; result->delay = 10; result->process = NULL; result->mayprocess = NULL; result->data = (char *)malloc(num * size); result->fails = 0; result->lastfailtime = 0; result->failfile[0] = 0; result->PDU = NULL; result->opentime = 0; result->pdu_refreshdelay = 3600; result->pdu_closedelay = 5; result->pdu_release = 0; result->ForwardLastUID = NULL; InitializeCriticalSection(&result->critical); #ifdef WIN32 result->threadhandle = CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) prefetcherthread, result, 0, &ThreadID); #else pthread_create(&result->threadhandle, NULL, (void*(*)(void*))prefetcherthread, (void *)result); pthread_detach(result->threadhandle); #endif return result; }; // Control prefetcher from queries or moves static int prefetchermode=0; BOOL prefetcher(struct DICOMDataObject *DDO, BOOL move) { VR *pVR = NULL; char id[66]; int len; if (!prefetchermode) return FALSE; if (!prefetcherqueue) prefetcherqueue = new_prefetcherqueue(); if (!DDO) return FALSE; memset(id, 0, 66); if (move) { pVR = DDO->GetVR(0x0008, 0x0018); if (pVR && pVR->Length) return FALSE; // do not abort on single sop move into_queue(prefetcherqueue, id); // abort on all other moves return FALSE; } pVR = DDO->GetVR(0x0010, 0x0020); // get patientid if (!pVR) id[0] = 0; else { id[0] = 'P'; strncpy(id+1, (char*)pVR->Data, pVR->Length); id[pVR->Length+1] = 0; len = pVR->Length - 1; while(len>0) { if (id[len+1] == ' ') id[len+1] = 0; else break; len--; } } // no patient id or wildcard provided: try study if (id[0]==0 || id[1]==0 || strchr(id, '*')!=NULL) { pVR = DDO->GetVR(0x0020, 0x000d); if (!(pVR && pVR->Length)) return FALSE; // no study: do not affect prefetch id[0]='S'; // prefetch on study (for e.g. kpacs) strncpy(id+1, (char*)pVR->Data, pVR->Length); id[pVR->Length+1] = 0; } // any other query will start prefetch of patient or study into_queue(prefetcherqueue, id); return TRUE; }; ////////////////////////////////////////////////////////////////////////////////// // This code is for worklist processing ////////////////////////////////////////////////////////////////////////////////// // will replace all items in object with worklist fields (if filled) for AccessionNumber // returns TRUE if replacement was succesfull: AccessionNumber was found or no entries to replace // Note: since PatientId and StudyInstanceUID may be changed by this operation, this operation // cannot be done after the original images were entered into the server. I will need to consider // generating new SOP and Series UID's in this case BOOL ApplyWorklist(DICOMDataObject *DDOPtr, Database *DB) { DBENTRY *DBE; int Index, I; char Fields[1024]; char QueryString[256]; VR *vr; char *Data[100]; SQLLEN SQLResultLength[100]; if (!WorkListDB[0].Element) // no worklist DB return FALSE; DBE = WorkListDB; Fields[0]=0; vr = DDOPtr->GetVR(DBE[0].Group, DBE[0].Element); // query string for AccessionNumber if (vr) { strcpy(QueryString, DBE[0].SQLColumn); // strcat(QueryString, DBE[0].SQLColumn); strcat(QueryString, " = '"); QueryString[strlen(QueryString) + vr->Length]=0; memcpy(QueryString+strlen(QueryString), vr->Data, vr->Length); if (QueryString[strlen(QueryString)-1]==' ') QueryString[strlen(QueryString)-1]=0; strcat(QueryString, "'"); // strcat(QueryString, " and PatientID = '"); // patient ID cannnot be used: may be the same in image as in worklist ! // vr = DDOPtr->GetVR(0x0010, 0x0020); // memcpy(QueryString+strlen(QueryString), vr->Data, vr->Length); // if (QueryString[strlen(QueryString)-1]==' ') QueryString[strlen(QueryString)-1]=0; // strcat(QueryString, "'"); } else return FALSE; if (vr->Length==0) return FALSE; // accessionnumber not filled in Index = 1; // do not read AccessionNumber from db I = 0; while ( TRUE ) { if(!DBE[Index].Element) break; // end of fields vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element); if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE) { // field is real and present in image strcat(Fields, DBE[Index].SQLColumn); strcat(Fields, ","); ++I; } ++Index; } Fields[strlen(Fields)-1]=0; // remove trailing , if (I==0) return TRUE; // nothing to do // no db access if (!DB->Query(WorkListTableName, Fields, QueryString, NULL)) return FALSE; Index = 1; // do not read AccessionNumber from db I = 0; while ( TRUE ) { if(!DBE[Index].Element) break; // end of fields vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element); if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE) { // field is real and present in image Data[I] = (char *)malloc(256); // data area for db read DB->BindField (I+1, SQL_C_CHAR, Data[I], 255, SQLResultLength+I); Data[I][0]=0; ++I; } ++Index; } if (!DB->NextRecord()) // no record found ? return FALSE; Index = 1; // do not read AccessionNumber from db I = 0; while ( TRUE ) { if(!DBE[Index].Element) break; vr = DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element); if (vr && DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE) { // field is real and present in image #if 0 // mvh 20051208 SQLResultLength[I] = strlen(Data[I]); #endif if (SQLResultLength[I]) // only replace if db field contains data { if (SQLResultLength[I] & 1) // make length even { if (DBE[Index].DICOMType==DT_UI) Data[I][SQLResultLength[I]++] = 0; // uid else Data[I][SQLResultLength[I]++] = ' '; // text } Data[I][SQLResultLength[I]] = 0; vr->ReAlloc(SQLResultLength[I]); memcpy(vr->Data, (void*)Data[I], SQLResultLength[I]); } free(Data[I]); ++I; } ++Index; } return TRUE; // success } // Save a dicom composite data object to disk and update database; returns filename // Warning: Filename must point to an array of 1024 characters that is filled BOOL NewDeleteSopFromDB(char *pat, char *study, char *series, char *sop, Database &aDB); BOOL SaveToDisk(Database &DB, DICOMDataObject *DDOPtr, char *Filename, BOOL NoKill, unsigned char *calling, unsigned char *called, int Syntax, BOOL nopreget) { FILE *fp; DICOMDataObject DDO; PDU_Service PDU; Debug AutoRoute; char s[1024]; char rRoot[1024], rFilename[1024], MirrorFilename[1024]; char Device[256], MirrorDevice[256], Device2[256]; char SOPInstanceUID[256]; int len, UseChapter10, sIndex, devlen, has_dcm_extension=0; VR* pVR; char szModality[66]; char szStationName[66]; char szSop[66], szSeries[66], szStudy[66]; char patid[66]; BOOL bForcedImplicit = FALSE; char *p; char Storage[64]; PDU.AttachRTC(&VRType); if (WorkListMode==1) // optionally update information from worklist db ApplyWorklist(DDOPtr, &DB); else if (WorkListMode==2) // compulsory update information from worklist db { if (!ApplyWorklist(DDOPtr, &DB)) { OperatorConsole.printf("***[WorkListMode 2] Worklist entry (AccessionNumber) not found; object not saved\n"); return FALSE; } } FixImage(DDOPtr); // Make sure the required DICOM UID's are there + fix patient ID if enabled /* PDU.SaveDICOMDataObject destroys the contents of DDOPtr. We need to know the modality in order to decide whether ExportConverters or ImportConverters should be called. Get the modality here... */ pVR = DDOPtr->GetVR(0x0008, 0x0060); if (!pVR) szModality[0] = 0; else { strncpy(szModality, (char*)pVR->Data, pVR->Length); szModality[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (szModality[len] == ' ') szModality[len] = 0; else break; len--; } } /* same for the StationName */ pVR = DDOPtr->GetVR(0x0008, 0x1010); if (!pVR) szStationName[0] = 0; else { strncpy(szStationName, (char*)pVR->Data, pVR->Length); szStationName[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (szStationName[len] == ' ') szStationName[len] = 0; else break; len--; } } /* same for the Sop */ pVR = DDOPtr->GetVR(0x0008, 0x0018); if (!pVR) szSop[0] = 0; else { strncpy(szSop, (char*)pVR->Data, pVR->Length); szSop[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (szSop[len] == ' ') szSop[len] = 0; else break; len--; } } /* same for the Series */ pVR = DDOPtr->GetVR(0x0020, 0x000e); if (!pVR) szSeries[0] = 0; else { strncpy(szSeries, (char*)pVR->Data, pVR->Length); szSeries[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (szSeries[len] == ' ') szSeries[len] = 0; else break; len--; } } /* same for the Study */ pVR = DDOPtr->GetVR(0x0020, 0x000d); if (!pVR) szStudy[0] = 0; else { strncpy(szStudy, (char*)pVR->Data, pVR->Length); szStudy[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (szStudy[len] == ' ') szStudy[len] = 0; else break; len--; } } /* same for the patid */ pVR = DDOPtr->GetVR(0x0010, 0x0020); if (!pVR) patid[0] = 0; else { strncpy(patid, (char*)pVR->Data, pVR->Length); patid[pVR->Length] = 0; len = pVR->Length - 1; while(len>0) { if (patid[len] == ' ') patid[len] = 0; else break; len--; } } Storage[0]=0; if (!nopreget) if (!CallImportConverters(DDOPtr, szModality, szStationName, szSop, patid, (char *)calling, (char *)called, Storage)) { // the import converter destroyed the image: silently cancel store Filename[0]=0; delete DDOPtr; return TRUE; } // make a filename for the new object; note: rRoot (patient directory part of rFilename) is not used any longer *rRoot=1; if (!GenerateFileName(DDOPtr, Device, rRoot, rFilename, NoKill, Syntax, (char *)called, (char *)calling, &DB)) { //OperatorConsole.printf("***Failed to create filename for DICOM object (is it a slice ?)\n"); #ifdef FAILSAFE_STORAGE strcpy(rFilename, "failsafe_storage\\"); GenUID(rFilename + strlen(rFilename)); strcat(rFilename, ".v2"); OperatorConsole.printf("***There was a DB problem, failsafe storage created following filename: %s\n", rFilename); #else return FALSE; //!!!!!!!!! added mvh+ljz 19980409 #endif } // newly written image (not rewritten image): use selection preferred storage if enough space if (*rRoot) { if (Storage[0]) { int PreferredDevice = atoi(Storage+3); if(CheckFreeStoreOnMAGDevice(PreferredDevice) > 30) sprintf(Device, "MAG%d", PreferredDevice); } } // If MAG is full, may write to MIRROR, but database will say MAG if (memicmp(Device, "MIRROR", 6)==0) sprintf(Device2, "MAG%d", atoi(Device+6)); else strcpy(Device2, Device); // fix 20040606 (was sprintf(Device2, "MAG%d", atoi(Device+3));) // do not rewrite image not on MAG but it is not an error (warning is generated earlier) if (memicmp(Device2, "MAG", 3)!=0) { Filename[0]=0; delete DDOPtr; // 20040402 return TRUE; } // When written replace virtual MAG device, i.e. MAG0.1 (for VirtualServerFor1) with real one: MAG0 p = strchr(Device2, '.'); if (p && p[1]>='0' && p[1]<='9') *p = 0; // try to enter object into database (object is not saved when this fails) if(!SaveToDataBase(DB, DDOPtr, rFilename, Device2, *rRoot)) { OperatorConsole.printf("***Error saving to SQL: %s\n", rFilename); #ifndef FAILSAFE_STORAGE return FALSE; #endif } // Make the patient directory (and any required subdirectories), that might not be there GetPhysicalDevice(Device, Filename); devlen = strlen(Filename); strcat(Filename, rFilename); for (sIndex = devlen; sIndex<=strlen(Filename); sIndex++) if (Filename[sIndex]==PATHSEPCHAR) { strcpy(s, Filename); s[sIndex]='\0'; mkdir(s); } // Find a mirror device if it exists (will not do this if MIRROR is being written because MAG if full) if (memicmp(Device, "MAG", 3)==0) { sprintf(MirrorDevice, "MIRROR%d", atoi(Device+3)); if (!GetPhysicalDevice(MirrorDevice, MirrorFilename)) MirrorDevice[0]=0; } else MirrorDevice[0]=0; // Make the mirror patient directory (and any required subdirectories), that might not be there if (MirrorDevice[0]) { devlen = strlen(MirrorFilename); strcat(MirrorFilename, rFilename); for (sIndex = devlen; sIndex<strlen(MirrorFilename); sIndex++) if (MirrorFilename[sIndex]==PATHSEPCHAR) { strcpy(s, MirrorFilename); s[sIndex]='\0'; mkdir(s); } } // UIDs must be zero padded (not with a space) VR *vrSOPInstanceUID = DDOPtr->GetVR(0x0008, 0x0018); if(vrSOPInstanceUID) { memset((void*)SOPInstanceUID, 0, 128); memcpy((void*)SOPInstanceUID, vrSOPInstanceUID->Data, vrSOPInstanceUID->Length); // Fix a bad encoding engine on a remote side.. if(vrSOPInstanceUID->Length) if(SOPInstanceUID[vrSOPInstanceUID->Length-1]==' ') SOPInstanceUID[vrSOPInstanceUID->Length-1] = '\0'; } else SOPInstanceUID[0] = '\0'; // check the filename to determine format; this avoids format change on rewrite len = strlen(rFilename); if (len>4) has_dcm_extension = (stricmp(rFilename+len-4, ".dcm")==0); /* Type of save depends on file name extension is .dcm (UseChapter10) and on the transfer syntax (not ImplicitLittleEndian, not ExplicitLittleEndian and not ExplicitBigEndian) */ pVR = DDOPtr->GetVR(0x0002, 0x0010); // TransferSyntaxUID if (pVR && pVR->Data) { strncpy(s, (char*)pVR->Data, pVR->Length); s[pVR->Length] = 0; if ((strcmp(s, "1.2.840.10008.1.2") != 0) && (strcmp(s, "1.2.840.10008.1.2.1") != 0) && (strcmp(s, "1.2.840.10008.1.2.2") != 0)) { if (!has_dcm_extension) { OperatorConsole.printf("SaveToDisk: cannot rewrite jpeg/rle image in v2 format: %s\n", Filename); Filename[0]=0; delete DDOPtr; return TRUE; } UseChapter10 = has_dcm_extension; } else { UseChapter10 = has_dcm_extension; //bForcedImplicit = TRUE; // 20040406 } } else UseChapter10 = has_dcm_extension; // is it nki compressed and attempt to store as .dcm --> decompress ? if (DDOPtr->GetVR(0x7fdf, 0x0010)!=NULL && DDOPtr->GetVR(0x7fe0, 0x0010)==NULL && has_dcm_extension) { OperatorConsole.printf("SaveToDisk: *** warning: cannot write NKI compressed in dcm format, decompressing: %s\n", Filename); DecompressNKI(DDOPtr); } int t = time(NULL); if (!UseChapter10) PDU.SaveDICOMDataObject(Filename, ACRNEMA_VR_DUMP, DDOPtr); else if (bForcedImplicit) PDU.SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_IMPLICIT, DDOPtr); else // OR (tested OK) chapter 10 format (does not compress) code in filepdu.cxx (dicom.lib) PDU.SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, DDOPtr); SaveTime += time(NULL)-t; // 20080817: check file was actually written, if not report error and delete database entry if (!DFileExists(Filename)) { OperatorConsole.printf("***Error writing file: %s\n", Filename); NewDeleteSopFromDB(patid, szStudy, szSeries, szSop, DB); return FALSE; } if (MirrorDevice[0]) { #if DONTQUEUEMIRRORCOPY if (DFileCopy2(Filename, MirrorFilename, 0)) OperatorConsole.printf("Mirror copy: %s\n", MirrorFilename); else OperatorConsole.printf("***Writing mirror copy failed: %s\n", MirrorFilename); #else mirrorcopy_queue(Filename, MirrorFilename); #endif } // notify the autorouter that a dicom object has landed if ( Edition != E_PERSONAL ) { if(SOPInstanceUID[0]!='\0') AutoRoute.printf("%s", SOPInstanceUID); } // notify additional executables that a dicom object has landed if (!nopreget) #if DONTQUEUEEXPORTCONVERTERS CallExportConverters(Filename, szModality, szStationName, szSop, patid, (char *)calling, (char *)called, NULL, NULL); #else QueueExportConverters(Filename, szModality, szStationName, szSop, patid, (char *)calling, (char *)called); #endif delete DDOPtr; return ( TRUE ); } // some help for the simple user BOOL PrintOptions () { fprintf(stderr, "\n"); fprintf(stderr, "DGATE: UCDMC/NKI DICOM server thread and PACS utility application %s\n", VERSION); fprintf(stderr, "\n"); fprintf(stderr, "Usage:\n"); fprintf(stderr, "(1) DGATE <-!#|-v|-u#|-^#> Report as in dicom.ini|stdout|UDP|File(#=port)\n"); fprintf(stderr, " [-p#|-b] Set listen port|run in non-theaded debug mode\n"); fprintf(stderr, " [-i|-r|-arDEVICE] Init|Init/regenerate DB|Regen single device\n"); fprintf(stderr, " [-d|-m|-k] List (-d) devices (-m) AE map (-k) DICOM.SQL\n"); fprintf(stderr, " [-t|-o] Test console|Test database\n"); fprintf(stderr, " [-sOpts|-es d u p] Create ODBC data source, database (WIN32 only)\n"); fprintf(stderr, " [-nd|-nc#|-jd|-jc#] NKI de-/compress#|JPEG de-/compress# FILE\n"); fprintf(stderr, " [-as#,N|-amFROM,TO] Select#KB to archive of MAGN|move device data\n"); fprintf(stderr, " [-au|-aeFROM,TO] Undo select for archiving|rename device\n"); fprintf(stderr, " [-av|-atDEVICE] Verify mirror disk|Test read files for DEVICE\n"); fprintf(stderr, " [-abJUKEBOX1.2,N] Make cacheset to burn JUKEBOX1,CD2 from MAGN\n"); fprintf(stderr, " [-acJUKEBOX1.2] Verify JUKEBOX1,CD2 against cacheset\n"); fprintf(stderr, " [-adJUKEBOX1.2] Verify and delete cacheset for JUKEBOX1, CD2\n"); fprintf(stderr, " [-f<p|t|s|i>ID] Delete DB for Patient, sTudy, Series, Image\n"); fprintf(stderr, " [-f<e|d|z>file] Enter/Delete DB of file, Zap server file\n"); fprintf(stderr, " [-faFILE<,ID>] Add file to server<optionally change PATID>\n"); fprintf(stderr, " [-zID] Delete (zap) patient\n"); fprintf(stderr, " [-frDEVICE,DIR] Regen single directory DIR on DEVICE\n"); fprintf(stderr, " [-f<c|k>PATID,file] Change/Kopy PATID of file (irreversible/once)\n"); fprintf(stderr, " [-f?file|-fu|-c#] get UID of file|Make new UID|UID helper(0..99)\n"); fprintf(stderr, " [-ff#] Delete old patients until #MB free\n"); fprintf(stderr, " [-gSERVER,DATE] grab images from SERVER of date not on here\n"); fprintf(stderr, " Otherwise: run as threaded server, port=1111\n"); fprintf(stderr, "\n"); fprintf(stderr, "(2) DGATE FileMapping Run server child; shared memory has socket#\n"); fprintf(stderr, "\n"); fprintf(stderr, "(3) DGATE --command:arguments Send command to running server in other process\n"); fprintf(stderr, " (works directly - use with care)\n"); fprintf(stderr, "Delete options:\n"); fprintf(stderr, " --deleteimagefile:file Delete given image file from server\n" ); fprintf(stderr, " --deletepatient:patid Delete given patient from server\n" ); fprintf(stderr, " --deletestudy:patid:studyuid Delete given study from server\n" ); fprintf(stderr, " --deletestudies:date(range) Delete studies from server on date\n" ); fprintf(stderr, " --deleteseries:patid:seriesuid Delete given series from server\n" ); fprintf(stderr, " --deleteimagefromdb:file Delete given file from db only\n" ); fprintf(stderr, " --deletesopfromdb:pat,study,series,sop Delete specified image from db only\n" ); fprintf(stderr, "\n"); fprintf(stderr, "DICOM move options:\n"); fprintf(stderr, " --movepatient:source,dest,patid Move patient, source e.g. (local)\n" ); fprintf(stderr, " --movestudy:source,dest,patid:studyuid Move study, patid: optional\n" ); fprintf(stderr, " --movestudies:source,dest,date(range) Move studies on date\n" ); fprintf(stderr, " --moveseries:source,dest,patid:seruid Move series patid: optional\n" ); fprintf(stderr, "\n"); fprintf(stderr, "Dbase without ODBC options:\n"); fprintf(stderr, " --packdbf: Pack dbase databases and recreate memory index\n" ); fprintf(stderr, " --indexdbf: Re-create memory index for dbase database\n" ); fprintf(stderr, "\n"); fprintf(stderr, "Modification of dicom objects:\n"); fprintf(stderr, " --modifypatid:file,patid Change patid of given file\n" ); fprintf(stderr, " --anonymize:file,patid Anonymize given file\n" ); fprintf(stderr, " --mergestudy:uid,uid,.. Start merging studies with given studyuids\n" ); fprintf(stderr, " --mergestudyfile:file Use to process all files to merge\n" ); fprintf(stderr, " --mergeseries:uid,uid,.. Start merging series with given seriesuids\n" ); fprintf(stderr, " --mergeseriesfile:file Use to process all files to merge\n" ); fprintf(stderr, "\n"); fprintf(stderr, "Maintenance options:\n"); fprintf(stderr, " --initializetables: Clear and create database\n" ); fprintf(stderr, " --initializetables:1 Clear and create database without indices\n" ); fprintf(stderr, " --initializetables:2 Clear and create worklist database\n" ); fprintf(stderr, " --regen: Re-generate entire database\n" ); fprintf(stderr, " --regendevice:device Re-generate database for single device\n" ); fprintf(stderr, " --regendir:device,dir Re-generate database for single directory\n" ); fprintf(stderr, " --regenfile:file Re-enter given file in database\n" ); fprintf(stderr, " --addimagefile:file,patid Copy file into server, optionally with new patid\n" ); fprintf(stderr, " --testcompress:file Test: enter file in server with many compressions\n" ); fprintf(stderr, " --debuglog_on:file/port Start debug logging\n" ); fprintf(stderr, " --log_on:file/port/pipe Start normal logging\n" ); fprintf(stderr, " --debuglevel:# Set debug logging level\n" ); fprintf(stderr, " --makespace:# Delete old patients to make #MB space\n" ); fprintf(stderr, " --get_freestore:dev,fmt Report free #Mb on device\n" ); fprintf(stderr, " --get_param:name,fmt Read any parameter from DICOM.INI\n" ); fprintf(stderr, " --get_ini_param:name,fmt Read any parameter from DICOM.INI\n" ); fprintf(stderr, " --get_ini_num:index,fmt List any entry from DICOM.INI\n" ); fprintf(stderr, " --get_ini:fmt List all entries from DICOM.INI\n" ); fprintf(stderr, " --put_param:name,value Write any parameter to DICOM.INI\n" ); fprintf(stderr, " --delete_param:name Delete any parameter from DICOM.INI\n" ); fprintf(stderr, " --read_ini: Re-read all parameters from DICOM.INI\n" ); fprintf(stderr, " --get_amap:index,fmt List any entry from ACRNEMA.MAP\n" ); fprintf(stderr, " --get_amaps:fmt List all entries from ACRNEMA.MAP\n" ); fprintf(stderr, " --put_amap:i,AE,ip,p#,cmp Write entry in memory for ACRNEMA.MAP\n" ); fprintf(stderr, " --delete_amap:index Delete entry in memory for ACRNEMA.MAP\n" ); fprintf(stderr, " --write_amap: Write ACRNEMA.MAP from memory to disk\n" ); fprintf(stderr, " --read_amap: Re-read ACRNEMA.MAP from disk to memory\n" ); fprintf(stderr, " --get_sop:index,fmt List any accepted service class UID\n" ); fprintf(stderr, " --put_sop:index,UID,name Write/add accepted service class UID\n" ); fprintf(stderr, " --delete_sop:index Delete accepted service class UID\n" ); fprintf(stderr, " --get_transfer:index,fmt List any accepted transfer syntax\n" ); fprintf(stderr, " --put_transfer:in,UID,nam Write/add accepted transfer syntax\n" ); fprintf(stderr, " --delete_transfer:index Delete accepted transfer syntax\n" ); fprintf(stderr, " --get_application:idx,fmt List any accepted application UID\n" ); fprintf(stderr, " --put_application:i,U,n Write/add accepted application UID\n" ); fprintf(stderr, " --delete_application:inde Delete accepted application UID\n" ); fprintf(stderr, " --get_localae:index,fmt List any accepted local AE title\n" ); fprintf(stderr, " --put_localae:in,AE,name Write/add accepted local AE title\n" ); fprintf(stderr, " --delete_localae:index Delete accepted local AE title\n" ); fprintf(stderr, " --get_remoteae:index,fmt List any accepted remote AE title\n" ); fprintf(stderr, " --put_remoteae:in,AE,name Write/add accepted remote AE title\n" ); fprintf(stderr, " --delete_remoteae:index Delete accepted remote AE title\n" ); fprintf(stderr, " --get_dic:index,fmt List any dicom dictionary item\n" ); fprintf(stderr, " --get_sqldef:level,in,fmt List any database field definition\n" ); fprintf(stderr, " --dump_header:filein,fileout Create header dump of file\n" ); fprintf(stderr, " --forward:file,mode,server Send file with compr. mode to server\n"); fprintf(stderr, " --convert_to_gif:file,size,out,l/w Downsize and convert to mono GIF\n"); fprintf(stderr, " --convert_to_bmp:file,size,out,l/w Downsize and convert to color BMP\n"); fprintf(stderr, " --convert_to_dicom:file,size,comp Downsize/compress DICOM for cgi\n"); fprintf(stderr, " --query:table|fields|where|fmt|file Arbitrary query output to file\n" ); fprintf(stderr, " --query2:tab|fld|whe|fmt|max|file Same but limit output rows to max\n" ); fprintf(stderr, " --patientfinder:srv|str|fmt|file List patients on server\n" ); fprintf(stderr, " --studyfinder:srv|str|fmt|file List studies on server\n" ); fprintf(stderr, " --seriesfinder:srv|str|fmt|file List series on server\n" ); fprintf(stderr, " --serieslister:srv|pat|stu|fmt|file List series in a study\n" ); fprintf(stderr, " --imagelister:srv|pat|ser|fmt|file List files in a series\n" ); fprintf(stderr, " --extract:PatientID = 'id' Extract all dbase tables to X..\n" ); fprintf(stderr, " --extract: Extract patient dbase table to XA..\n" ); fprintf(stderr, " --addrecord:table|flds|values Append record, values must be in ''\n" ); fprintf(stderr, " --deleterecord:table,where Delete record from table\n" ); fprintf(stderr, " --grabimagesfromserver:AE,date Update this server from other\n" ); fprintf(stderr, " --display_status:file Display server status\n" ); fprintf(stderr, " --loadhl7:file Load HL7 data into worklist\n" ); fprintf(stderr, " --clonedb:AE Clone db from server for testing\n" ); fprintf(stderr, " --prefetch:patientid prefetch all images for improved speed\n" ); fprintf(stderr, " --checklargestmalloc: Estimates DICOM object size limit\n" ); fprintf(stderr, " --quit: Stop the server\n" ); fprintf(stderr, "\n"); fprintf(stderr, "Archival options:\n"); fprintf(stderr, " --renamedevice:from,to Rename device in database\n" ); fprintf(stderr, " --verifymirrordisk:device Verify mirror disk for selected device\n" ); fprintf(stderr, " --testimages:device Test read all images on device\n" ); fprintf(stderr, " --movedatatodevice:to,from Move data from one device to another\n" ); fprintf(stderr, " --selectlruforarchival:kb,device Step 1 for archival: to device.Archival\n" ); fprintf(stderr, " --preparebunchforburning:to,from Step 2 for archival: moves to cache\n" ); fprintf(stderr, " --deletebunchafterburning:deviceto Step 3 for archival: deletes from cache\n" ); fprintf(stderr, " --comparebunchafterburning:deviceto Part step 3 - compare jukebox to cache\n" ); fprintf(stderr, " --restoremagflags: Undo archival sofar\n" ); return ( TRUE ); } // external references BOOL SelectLRUForArchival(char *Device, int KB); BOOL PrepareBunchForBurning(char *DeviceFrom, char *DeviceTo); BOOL MoveDataToDevice(char *DeviceFrom, char *DeviceTo); BOOL RestoreMAGFlags(); BOOL CompareBunchAfterBurning(char *DeviceTo); BOOL DeleteBunchAfterBurning(char *DeviceTo); BOOL VerifyMirrorDisk(char *DeviceFrom); BOOL RenameDevice(char *DeviceFrom, char *DeviceTo); BOOL TestImages(char *DeviceFrom); BOOL PanicKillOff(int MAGThreshHold); // forward references BOOL GrabImagesFromServer(BYTE *calledae, char *studydate, char *destination); static BOOL SendServerCommand(char *NKIcommand1, char *NKIcommand2, int con, char *buf=NULL, BOOL html=TRUE); #if defined(__BORLANDC__) || defined(__WATCOMC__) typedef BOOL (__stdcall *_SQLConfigDataSource)(HWND hwndParent, WORD fRequest, LPCSTR lpszDriver, LPCSTR lpszAttributes); _SQLConfigDataSource __SQLConfigDataSource; #define SQLConfigDataSource __SQLConfigDataSource #define ODBC_ADD_DSN 1 // Add data source #endif // Main routine for parsing the command line; return FALSE when not running // as server or a socket # when running as server thread int ParseArgs (int argc, char *argv[]) { UINT Valid; int valid_argc, mode=0; int Socketfd = 0; BOOL bUIDPostfixSet = FALSE; Valid = 2; ConfigMicroPACS(); UserLog.On(UserLogFile); UserLog.AddTimeStamps(TRUE); TroubleLog.On(TroubleLogFile); TroubleLog.AddTimeStamps(TRUE); valid_argc = 1; while ( valid_argc < argc ) { #ifndef UNIX // Win32... if ((argv[valid_argc][0]=='-')||(argv[valid_argc][1]=='/')) #else // UNIX.. if(argv[valid_argc][0]=='-') #endif { switch ( argv[valid_argc][1] ) { case 'v': // verbose mode case 'V': SystemDebug.On(); OperatorConsole.On(); break; case 'b': // debug mode case 'B': SystemDebug.On(); OperatorConsole.On(); NoThread=TRUE; break; case 'c': // set UID counter case 'C': UIDPostfix = atoi(argv[valid_argc]+2); bUIDPostfixSet = TRUE; break; case 'u': case 'U': // be verbose to specified pipe/udp if(argv[valid_argc][2] == PATHSEPCHAR) { OperatorConsole.OnMsgPipe(argv[valid_argc]+2); SystemDebug.OnMsgPipe(argv[valid_argc]+2); } else { OperatorConsole.OnUDP(OCPipeName, argv[valid_argc]+2); SystemDebug.OnUDP(OCPipeName, argv[valid_argc]+2); } break; case '!': // be verbose to pipe/udp specified in DICOM.INI (no debug) if(OCPipeName[0] == PATHSEPCHAR) { OperatorConsole.OnMsgPipe(OCPipeName); } else { if (argv[valid_argc][2]>='0' && argv[valid_argc][2]<='9') { OperatorConsole.OnUDP(OCPipeName, argv[valid_argc]+2); #if 0 SystemDebug.OnUDP(OCPipeName, argv[valid_argc]+2); #endif } else OperatorConsole.OnUDP(OCPipeName, "1111"); } break; case '^': // be verbose to passed file with timestamps (no debug) OperatorConsole.On(argv[valid_argc]+2); OperatorConsole.AddTimeStamps(1); break; case '#': // be verbose to passed file with timestamps (with debug) OperatorConsole.On(argv[valid_argc]+2); OperatorConsole.AddTimeStamps(1); SystemDebug.On(argv[valid_argc]+2); SystemDebug.AddTimeStamps(1); break; case 'p': // override dicom.ini port# case 'P': strcpy((char*)Port, argv[valid_argc]+2); ++Valid; break; // fall through was not intended ! case 'r': // init and regenerate database case 'R': RunServer = FALSE; NeedPack = 2; SystemDebug.printf("Regen Database\n"); if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit(1); } OperatorConsole.printf("Step 1: Re-intialize SQL Tables\n"); mode = atoi(argv[valid_argc]+2); InitializeTables (mode); OperatorConsole.printf("Step 2: Load / Add DICOM Object files\n"); Regen(); OperatorConsole.printf("Regeneration Complete\n"); return ( FALSE ); case 'd': // List magnetic device status case 'D': RunServer = FALSE; NeedPack = FALSE; SystemDebug.Off(); PrintFreeSpace(); return ( FALSE ); case 'm': // list map of outgoing AE's case 'M': RunServer = FALSE; NeedPack = FALSE; if(!InitACRNemaAddressArray()) { OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP); exit(1); } PrintAMap(); return ( FALSE ); case 'k': // list K factor file (DICOM.SQL) case 'K': RunServer = FALSE; NeedPack = FALSE; if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit (1); } PrintKFactorFile(); return ( FALSE ); case 't': // test (TCP/IP) console connnection case 'T': { char lt[] = "This is a very long text output for testing -- "; RunServer = FALSE; NeedPack = FALSE; OperatorConsole.printf("This output is generated by the dicom server application\n"); OperatorConsole.printf("If you can read this, the console communication is OK\n"); SystemDebug.printf("This is systemdebug output; can you read this ?\n"); SystemDebug.printf("%s%s%s%s%s%s\n", lt, lt, lt, lt, lt, lt); OperatorConsole.printf(" ---------- Succesful end of test -----------\n"); return ( FALSE ); } case 'o': // test ODBC database connnection case 'O': { Database aDB; int i; RunServer = FALSE; NeedPack = FALSE; for (i=1; i<=10; i++) { OperatorConsole.printf("Attempting to open database; test #%d of 10\n", i); if(!aDB.Open(DataSource, UserName, Password, DataHost)) { OperatorConsole.printf("***Unable to open database %s as user %s on %s\n", DataSource, UserName, DataHost); exit (1); } OperatorConsole.printf("Creating test table\n"); aDB.CreateTable ( "xtesttable", "Name varchar(254), AccessTime int" ); OperatorConsole.printf("Adding a record\n"); aDB.AddRecord("xtesttable", "Name", "'Testvalue'"); OperatorConsole.printf("Dropping test table\n"); aDB.DeleteTable ( "xtesttable" ); OperatorConsole.printf("Closing database\n"); aDB.Close(); } OperatorConsole.printf(" ---------- Succesful end of test -----------\n"); return ( FALSE ); } case 'a': // Archival code case 'A': // Archival code { RunServer = FALSE; NeedPack = 5; OperatorConsole.printf(" ---------- Start archival operation -----------\n"); // Select a number of KB to archive from device MAGn (default MAG0) if (argv[valid_argc][2] == 's' || argv[valid_argc][2] == 'S') { char MAG[256]; char *p; p = strchr(argv[valid_argc]+3,','); if (p) sprintf(MAG, "MAG%d", atoi(p+1)); else strcpy(MAG, "MAG?"); if (!SelectLRUForArchival(MAG, atoi(argv[valid_argc]+3))) exit(1); } // Create cache set for burning for JUKEBOXn.n from MAGn (default MAG0) else if (argv[valid_argc][2] == 'b' || argv[valid_argc][2] == 'B') { char MAG[256], Device[256]; char *p; strcpy(Device, argv[valid_argc]+3); p = strchr(Device,','); if (p) { sprintf(MAG, "MAG%d", atoi(p+1)); *p = 0; } else strcpy(MAG, "MAG?"); if (!PrepareBunchForBurning(MAG, Device)) exit(1); } // Move (all) data from device1 to device2 else if (argv[valid_argc][2] == 'm' || argv[valid_argc][2] == 'M') { char Device1[256]; char *p; strcpy(Device1, argv[valid_argc]+3); p = strchr(Device1,','); if (p) { *p = 0; if (!MoveDataToDevice(Device1, p+1)) exit(1); } else exit(1); } // Undo any archiving that was not completed else if (argv[valid_argc][2] == 'u' || argv[valid_argc][2] == 'U') { if (!RestoreMAGFlags()) exit(1); } // Verify CD in jukebox against its cache set else if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C') { if (!CompareBunchAfterBurning(argv[valid_argc]+3)) exit(1); } // Verify MAG device against its mirror device else if (argv[valid_argc][2] == 'v' || argv[valid_argc][2] == 'V') { if (!VerifyMirrorDisk(argv[valid_argc]+3)) exit(1); } // Test read slices on device else if (argv[valid_argc][2] == 't' || argv[valid_argc][2] == 'T') { if (!TestImages(argv[valid_argc]+3)) exit(1); } // Delete cache set for burned CD else if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D') { if (!DeleteBunchAfterBurning(argv[valid_argc]+3)) exit(1); } // Regen a single device (for database maintenance) else if (argv[valid_argc][2] == 'r' || argv[valid_argc][2] == 'R') { if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit(1); } OperatorConsole.printf("Regen single device: %s\n", argv[valid_argc]+3); if (!Regen(argv[valid_argc]+3, FALSE)) exit(1); OperatorConsole.printf("Regeneration Complete\n"); } // rEname device name else if (argv[valid_argc][2] == 'e' || argv[valid_argc][2] == 'E') { char DeviceFrom[256]; char *p; strcpy(DeviceFrom, argv[valid_argc]+3); p = strchr(DeviceFrom,','); if (p) { *p = 0; if (!RenameDevice(DeviceFrom, p+1)) exit(1); } else { OperatorConsole.printf("option requires two device names\n"); exit(1); } } else { OperatorConsole.printf("Unknown archiving option\n"); exit(1); } OperatorConsole.printf(" ---------- End of archival operation -----------\n"); return ( FALSE ); } #ifdef WIN32 case 's': case 'S': // Create ODBC data source { char Options[1512], Driver[512]; int i, len; #if defined(__BORLANDC__) || defined(__WATCOMC__) HINSTANCE hODBCInst = LoadLibrary("odbccp32.dll"); __SQLConfigDataSource= (_SQLConfigDataSource)GetProcAddress(hODBCInst, "SQLConfigDataSource"); #endif strcpy(Driver, "Microsoft dBase Driver (*.dbf)"); strcpy(Options, "DSN=ConQuestPacs;" "Description=ConQuest DICOM server data source;" "Fil=dBase III;" "DriverID=21;" "Deleted=1;" "DefaultDir=C:\\quirt"); for (i=2; i<strlen(argv[valid_argc]); i++) { if (argv[valid_argc][i] == ';') { memcpy(Driver, argv[valid_argc]+2, i-2); Driver[i-2]=0; strcpy(Options, argv[valid_argc]+i+1); Options[strlen(Options)+1] = 0; break; } } OperatorConsole.printf("Creating data source\n"); OperatorConsole.printf("Driver = %s\n", Driver); OperatorConsole.printf("Options = %s\n", Options); len = strlen(Options); for (i=0; i<len; i++) if (Options[i] == ';') Options[i] = 0; RunServer = FALSE; NeedPack = FALSE; if ( !SQLConfigDataSource(NULL, ODBC_ADD_SYS_DSN, Driver, Options) ) // if ( !SQLConfigDataSource(NULL, ODBC_ADD_DSN, Driver, Options) ) { char szMsg[256] = "(No details)"; char szTmp[280]; DWORD dwErrorCode; OperatorConsole.printf("***Datasource configuration FAILED\n"); #if !defined(__BORLANDC__) && !defined(__WATCOMC__) && 0 SQLInstallerError(1, &dwErrorCode, szMsg, sizeof(szMsg) - 1, NULL); sprintf(szTmp, "***%s (ec=%d)\n", szMsg, dwErrorCode); OperatorConsole.printf(szTmp); #endif exit(1); } else OperatorConsole.printf("Datasource configuration succesful\n"); OperatorConsole.printf(" ----------------------------------\n"); return ( FALSE ); } #endif case 'e': // create database case 'E': { Database DB; DebugLevel=4; if (strcmp(argv[valid_argc+2], "root")==0 || strcmp(argv[valid_argc+2], "sa")==0) { if (DB.Open ( DataSource, argv[valid_argc+2], argv[valid_argc]+2, DataHost)) if (DB.CreateDatabase(argv[valid_argc+1], argv[valid_argc+2], argv[valid_argc]+2)) OperatorConsole.printf("succesfully created database\n"); } else { if (DB.Open ( DataSource, "sa", argv[valid_argc]+2, DataHost)) if (DB.CreateDatabase(argv[valid_argc+1], argv[valid_argc+2], argv[valid_argc+3])) OperatorConsole.printf("succesfully created database and login\n"); } OperatorConsole.printf(" ----------------------------------\n"); exit(0); } case 'i': // initialize database case 'I': RunServer = FALSE; NeedPack = FALSE; OperatorConsole.printf("Initializing Tables\n"); if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit(1); } mode = atoi(argv[valid_argc]+2); InitializeTables (mode); return ( FALSE ); case 'z': // delete (zap) patient case 'Z': RunServer = FALSE; NeedPack = 5; if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit (1); } if (!DeletePatient(argv[valid_argc]+2, FALSE)) exit(1); return ( FALSE ); case 'g': // grab data from server case 'G': { char *p; RunServer = FALSE; NeedPack = 5; if(!InitACRNemaAddressArray()) { OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP); exit(1); } if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit (1); } p = strchr(argv[valid_argc]+2,','); if (p) { *p=0; if (!GrabImagesFromServer((unsigned char *)argv[valid_argc]+2, p+1, (char *)MYACRNEMA)) exit(1); } else { if (!GrabImagesFromServer((unsigned char *)argv[valid_argc]+2, "*", (char *)MYACRNEMA)) exit(1); } return ( FALSE ); } case 'f': // Database fix options case 'F': RunServer = FALSE; NeedPack = 5; if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Could not load kfactor file: %s\n", KFACTORFILE); exit (1); } if (argv[valid_argc][2] == 'p' || argv[valid_argc][2] == 'P') { if (!DeletePatient(argv[valid_argc]+3, TRUE)) exit(1); } if (argv[valid_argc][2] == 'f' || argv[valid_argc][2] == 'F') { if (LargestFreeMAG()>atoi(argv[valid_argc]+3)) exit(0); if (!PanicKillOff(atoi(argv[valid_argc]+3))) exit(1); } else if (argv[valid_argc][2] == 't' || argv[valid_argc][2] == 'T') { if (!DeleteStudy(argv[valid_argc]+3, TRUE)) exit(1); } else if (argv[valid_argc][2] == 's' || argv[valid_argc][2] == 'S') { if (!DeleteSeries(argv[valid_argc]+3, TRUE)) exit(1); } else if (argv[valid_argc][2] == 'i' || argv[valid_argc][2] == 'I') { if (!DeleteImage(argv[valid_argc]+3, TRUE)) exit(1); } else if (argv[valid_argc][2] == 'r' || argv[valid_argc][2] == 'R') { char par[256]; char *p; strcpy(par, argv[valid_argc]+3); p = strchr(par,','); if (p) { *p=0; if (!Regen(par, FALSE, p+1)) exit(1); } else if (!Regen("MAG0", FALSE, par)) exit(1); } else if (argv[valid_argc][2] == 'e' || argv[valid_argc][2] == 'E') { if (!RegenFile(argv[valid_argc]+3)) exit(1); } else if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D') { if (!DeleteImageFile(argv[valid_argc]+3, TRUE)) exit(1); } else if (argv[valid_argc][2] == 'z' || argv[valid_argc][2] == 'Z') { if (!DeleteImageFile(argv[valid_argc]+3, FALSE)) exit(1); } else if (argv[valid_argc][2] == 'a' || argv[valid_argc][2] == 'A') { char par[1024]; char *p; strcpy(par, argv[valid_argc]+3); p = strchr(par,','); if (bUIDPostfixSet) gl_iFileCounter = UIDPostfix; else gl_iFileCounter = ComputeCRC(par, strlen(par)); if (p) { *p=0; if (!AddImageFile(par, p+1)) exit(1); } else { if (!AddImageFile(par, NULL)) exit(1); } } else if (argv[valid_argc][2] == '?') { char UID[256]; if (!GetImageFileUID(argv[valid_argc]+3, UID)) exit(1); printf("%s\n", UID); } else if (argv[valid_argc][2] == 'u' || argv[valid_argc][2] == 'U') { char UID[256]; if (!GenUID(UID)) exit(1); printf("%s\n", UID); } else if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C') { char par[256]; char *p; strcpy(par, argv[valid_argc]+3); p = strchr(par,','); if (p) { *p=0; if (!ModifyPATIDofImageFile(p+1, par, TRUE, NULL)) exit(1); } } else if (argv[valid_argc][2] == 'k' || argv[valid_argc][2] == 'K') { char par[256]; char *p; strcpy(par, argv[valid_argc]+3); p = strchr(par,','); if (p) { *p=0; if (!ModifyPATIDofImageFile(p+1, par, FALSE, NULL)) exit(1); } } return ( FALSE ); case 'n': // NKI compression options case 'N': RunServer = FALSE; NeedPack = FALSE; if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D') { int dum; if (!DecompressImageFile(argv[valid_argc]+3, &dum)) exit(1); } if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C') { int dum; if (!CompressNKIImageFile(argv[valid_argc]+4, argv[valid_argc][3]-'0', &dum)) exit(1); } return ( FALSE ); case 'j': // JPEG compression options case 'J': RunServer = FALSE; NeedPack = FALSE; if (argv[valid_argc][2] == 'd' || argv[valid_argc][2] == 'D') { int dum; if (!DecompressImageFile(argv[valid_argc]+3, &dum)) exit(1); } if (argv[valid_argc][2] == 'c' || argv[valid_argc][2] == 'C') { int dum; if (!CompressJPEGImageFile(argv[valid_argc]+4, argv[valid_argc][3], &dum)) exit(1); } if (argv[valid_argc][2] == '*') // test recompressFile { char mode[4]; mode[0] = argv[valid_argc][3]; mode[1] = argv[valid_argc][4]; mode[2] = 0; if (!recompressFile(argv[valid_argc]+5, mode)) exit(1); } if (argv[valid_argc][2] == '-') // test recompress { PDU_Service PDU; VR *pVR; PDU.AttachRTC(&VRType); DICOMDataObject *pDDO; pDDO = PDU.LoadDICOMDataObject(argv[valid_argc]+5); char mode[4]; mode[0] = argv[valid_argc][3]; mode[1] = argv[valid_argc][4]; mode[2] = 0; if (!recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N')) exit(1); // mvh 20040602: why is this deleted at all? // pVR = pDDO->GetVR(0x0002, 0x0010); // if (pVR) pDDO->DeleteVR(pVR); PDU.SaveDICOMDataObject(argv[valid_argc]+5, ACRNEMA_VR_DUMP, pDDO); delete pDDO; } return ( FALSE ); case '-': // Server command SendServerCommand("Server command sent using DGATE -- option", argv[valid_argc]+2, 0, NULL, FALSE); exit(1); default: // provide some help RunServer = FALSE; NeedPack = FALSE; PrintOptions(); return (FALSE); } } else { FILE *logFile; // This is a simple way to get a socket#; but why make it simple if it can be done complex ? // Socketfd = (void*)atoi(argv[valid_argc]); // Open some channel (UDP/pipe) for statistics when running as server child (from .ini file) if(OCPipeName[0] == PATHSEPCHAR) { OperatorConsole.OnMsgPipe(OCPipeName); } else { OperatorConsole.OnUDP(OCPipeName, "1111"); } // WIN32: get the socket# through shared memory #ifndef UNIX HANDLE hMap; IPCBlock *IPCBlockPtrInstance; hMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, argv[valid_argc]); if(!hMap) { OperatorConsole.printf("***Child: Unable to OpenFileMapping : %d (%s)\n", GetLastError(), argv[valid_argc]); exit(0); } IPCBlockPtrInstance = (IPCBlock*)MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0,0, sizeof(IPCBlock)); if(!IPCBlockPtrInstance) { OperatorConsole.printf("***Child: Unable to MapViewOfFile : %d\n", GetLastError()); } Socketfd = IPCBlockPtrInstance->Socketfd; UnmapViewOfFile(IPCBlockPtrInstance); CloseHandle(hMap); // UNIX: get the socket# from a small file or pipe #else #if 0 IPCBlock aIPCBlock; ifstream aStream(argv[valid_argc], ios::in | ios::nocreate); if(aStream.good()) { aStream.read((unsigned char *)&aIPCBlock, sizeof(aIPCBlock)); } if(!aStream.good() || aStream.gcount() != sizeof(aIPCBlock) || aIPCBlock.Magic != IPCBlockMagic) { // magic # assures safety -- // we don't try unlink("/"), for example OperatorConsole.printf("***Child: Unable to read file %s\n", argv[valid_argc]); } else { unlink(argv[valid_argc]); } Socketfd = aIPCBlock.Socketfd; #endif #endif } ++valid_argc; } /* check access for logging and saving images */ if (1) { FILE *f; char Filename[1024]; int i; f = fopen(TroubleLogFile, "at"); if (f) fclose(f); if (!f) OperatorConsole.printf("*** Not enough rights to write to logfiles\n"); memset(Filename, 0, 1024); GetPhysicalDevice("MAG0", Filename); strcat(Filename, "printer_files"); mkdir(Filename); i = strlen(Filename); Filename[i] = PATHSEPCHAR; Filename[i+1] = 0; strcat(Filename, "accesstest.log"); f = fopen(Filename, "at"); if (f) fclose(f); if (!f) OperatorConsole.printf("*** Not enough rights to write in MAG0\n"); } // prepare to run as a child server thread if(!LoadKFactorFile((char*)KFACTORFILE)) { OperatorConsole.printf("***Error loading kfactor file:%s\n", KFACTORFILE); return ( FALSE ); } if(!InitACRNemaAddressArray()) { OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP); return ( FALSE ); } if(!atoi((char*)Port)) return ( Socketfd ); if(Valid > 1) // always TRUE !!!!! return ( Socketfd ); return ( Socketfd ); } /* BOOL SetString(VR *vr, char *s, int Max) { memset((void*)s, 0, Max); if(vr) if(vr->Data) { memcpy((void*)s, vr->Data, vr->Length%Max); return ( TRUE ); } return ( FALSE ); } */ class DriverApp { public: virtual BOOL ServerChild ( int ) = 0; public: BOOL ServerChildThread ( int ); BOOL Server ( BYTE * ); int ChildSocketfd; volatile int Lock; DriverApp () { Lock = 0; }; }; // Query / Retrieve Engine class MyPatientRootQuery : public PatientRootQuery { public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); int RecordsFound; }; class MyStudyRootQuery : public StudyRootQuery { public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); int RecordsFound; }; class MyPatientStudyOnlyQuery : public PatientStudyOnlyQuery { public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); int RecordsFound; }; class MyModalityWorkListQuery : public ModalityWorkListQuery { public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); int RecordsFound; }; class MyPatientRootRetrieve : public PatientRootRetrieve { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyPatientRootRetrieveNKI : public PatientRootRetrieveNKI { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyPatientRootRetrieveGeneric : public PatientRootRetrieveGeneric { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyStudyRootRetrieve : public StudyRootRetrieve { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyStudyRootRetrieveNKI : public StudyRootRetrieveNKI { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyStudyRootRetrieveGeneric : public StudyRootRetrieveGeneric { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyPatientStudyOnlyRetrieve : public PatientStudyOnlyRetrieve { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyPatientStudyOnlyRetrieveNKI : public PatientStudyOnlyRetrieveNKI { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; class MyPatientStudyOnlyRetrieveGeneric : public PatientStudyOnlyRetrieveGeneric { RunTimeClassStorage RTCStorage; public: BOOL SearchOn (DICOMDataObject *, Array < DICOMDataObject *> *); BOOL CallBack (DICOMCommandObject *, DICOMDataObject *); BOOL RetrieveOn ( DICOMDataObject *, DICOMDataObject **, StandardStorage **, DICOMCommandObject *, Array < DICOMDataObject *> *, void *); BOOL QualifyOn ( BYTE *, BYTE *, BYTE *, BYTE *, BYTE * ); }; // This class handles storage; used to allow error messages to be sent back to the caller class MyUnknownStorage : public UnknownStorage { public: Database *DB; // must be set by caller (needs one per thread) BOOL nopreget; // must be set by caller (derived from messageid) // called for each incoming DDO UINT16 CheckObject(DICOMDataObject *DDO, PDU_Service *PDU) { char Filename[1024]; char Called[20], Calling[20]; char *Compression; if (!DB) return 0; // no db set: processing done by caller (failsafe_storage) #ifdef DEBUG_MODE //OperatorConsole.printf("C-Store (RTC class)\n"); #endif ImagesReceived++; // If the called AE looks like SERVER~j2, then the last 2 characters override IncomingCompression strcpy(Called, (char *)(((AAssociateAC *)PDU)->CalledApTitle)); while (Called[strlen(Called)-1]==' ') Called[strlen(Called)-1] = 0; strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle)); while (Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0; Compression = strchr(Called, '~'); if (!Compression) Compression = IncomingCompression; else Compression++; // Recompress (e.g., leave as is or decompress) incoming files recompress(&DDO, Compression, "", Compression[0]=='n' || Compression[0]=='N'); // Virtual compression: save in database, not on disk if (Compression[0]=='v' || Compression[0]=='V') { char rRoot[1024], rFilename[1024]; char Device[256]; FixImage(DDO); // Make sure the required DICOM UID's are there + fix patient ID if enabled *rRoot=1; if (!GenerateFileName(DDO, Device, rRoot, rFilename, TRUE, 0, Called, Calling, DB)) { OperatorConsole.printf("**** Virtual storage filename problem - %s\n", rFilename); } if(!SaveToDataBase(*DB, DDO, rFilename, Device, *rRoot)) { OperatorConsole.printf("**** Virtual storage db problem - %s\n", rFilename); } OperatorConsole.printf("Virtual file: %s\n", rFilename); delete DDO; ImagesSaved++; return 0; } // NOTE: NOT THREAD SAFE - IF ONE THREAD HANDLES READS AND WRITES THIS OPERATION CAN FAIL DUE TO DB SHARING: if(!SaveToDisk(*DB, DDO, Filename, FALSE, ((AAssociateAC *)PDU)->CallingApTitle, ((AAssociateAC *)PDU)->CalledApTitle, 0, nopreget)) { delete DDO; return StorageFailedErrorCode; // Processing failed } else { #ifdef DEBUG_MODE if(strlen(Filename)) OperatorConsole.printf("Written file: %s\n", Filename); #endif ImagesSaved++; return 0; } } }; class StorageApp : public DriverApp { // MyUnknownStorage SOPUnknownStorage; //Verification SOPVerification; //MyPatientRootQuery SOPPatientRootQuery; //MyPatientRootRetrieve SOPPatientRootRetrieve; //MyPatientRootRetrieveNKI SOPPatientRootRetrieveNKI; //MyPatientRootRetrieveGeneric SOPPatientRootRetrieveGeneric; //MyStudyRootQuery SOPStudyRootQuery; //MyStudyRootRetrieve SOPStudyRootRetrieve; //MyStudyRootRetrieveNKI SOPStudyRootRetrieveNKI; //MyStudyRootRetrieveGeneric SOPStudyRootRetrieveGeneric; //MyPatientStudyOnlyQuery SOPPatientStudyOnlyQuery; //MyPatientStudyOnlyRetrieve SOPPatientStudyOnlyRetrieve; //MyPatientStudyOnlyRetrieveNKI SOPPatientStudyOnlyRetrieveNKI; //MyPatientStudyOnlyRetrieveGeneric SOPPatientStudyOnlyRetrieveGeneric; //MyModalityWorkListQuery SOPModalityWorkListQuery; public: BOOL ServerChild ( int ); void FailSafeStorage(CheckedPDU_Service *PDU); BOOL PrinterSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *PrintData[]); BOOL StorageCommitmentSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject **CommitData); }; // from dbsql.cpp BOOL UpdateOrAddToTable( Database &DB, DBENTRY *DCMGateDB, char *TableName, DICOMDataObject *DDOPtr, char *ObjectFile, char *DeviceName, char *Patid, char *Modality, BOOL *Added, BOOL JustAdd, BOOL CheckDuplicates); void KodakFixer(DICOMDataObject *DDOPtr, BOOL tokodak) { VR *vr = DDOPtr->GetVR(0x0010, 0x0020); char patid[11]; int Length; if (!vr) return; if (!vr->Data) return; if (!vr->Length) return; if (vr->Length>8) return; memset(patid, 0, 10); memcpy(patid, (char *)(vr->Data), vr->Length); patid[vr->Length]=0; if (patid[vr->Length-1]==' ') patid[vr->Length-1] = 0; if (!tokodak && strlen(patid)==8 && patid[0] == '0' && atoi(patid)>1000000 ) { vr->ReAlloc(8); patid[8] = ' '; memcpy(vr->Data, patid + 1, 8); SystemDebug.printf("Fixed patient ID from kodak, now %s\n", patid+1); } if (tokodak && strlen(patid)==7 && patid[0] != '0' && atoi(patid)>1000000 ) { vr->ReAlloc(8); ((char *)(vr->Data))[0]='0'; memcpy(((char *)(vr->Data))+1, patid, 7); //sprintf((char *)(vr->Data), "0%s", patid); SystemDebug.printf("Fixed patient ID to kodak, now 0%s\n", patid); } } // virtual query: pass query (extended) through to other server and populate db with results (no images) int VirtualQuery(DICOMDataObject *DDO, char *Level, int N, Array < DICOMDataObject *> *pADDO) { char AE[48]; strcpy(AE, VirtualServerFor[N]); if (*AE==0) return FALSE; char *param = strchr(AE, ','); if (param) *param++ = 0; unsigned char ip[64], port[64], compress[64], SOP[66]; char rRoot[1024], rFilename[1024], ID[66]; VR *vr; UID uid; DICOMCommandObject DCO, DCOR; DICOMDataObject DDOR; LE_UINT16 command, datasettype, messageid, priority; BOOL quit; Database DB; char Device[256]; DICOMDataObject *DDOPtr, *DDOPtr2; DBENTRY *DBE; int Index, level, count=0; level=0; if (strncmp(Level, "PATIENT", 7)==0) level=1; else if (strncmp(Level, "STUDY", 5)==0) level=2; else if (strncmp(Level, "SERIES", 6)==0) level=3; else if (strncmp(Level, "IMAGE", 5)==0) level=4; PDU_Service PDU; PDU.AttachRTC(&VRType); if(!GetACRNema(AE, (char *)ip, (char *)port, (char *)compress)) return 0; // 20070103 if (param) if (stricmp(param, "FixKodak")==0) // disallow wildcard date queries { BOOL flag; vr = DDO->GetVR(0x0010, 0x0030); // birthdate flag = (vr && vr->Length>0 && *(char *)vr->Data == '*'); vr = DDO->GetVR(0x0008, 0x0020); // study date flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*'); vr = DDO->GetVR(0x0008, 0x0021); // series date flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*'); vr = DDO->GetVR(0x0008, 0x0022); // acq date flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*'); vr = DDO->GetVR(0x0008, 0x0023); // img date flag = flag || (vr && vr->Length>0 && *(char *)vr->Data == '*'); if (flag) { OperatorConsole.printf("Virtual query - blocked wildcard date query to %s\n", AE); return 0; } } // Start setting up connection for C-FIND PDU.ClearAbstractSyntaxs(); PDU.SetLocalAddress(MYACRNEMA); PDU.SetRemoteAddress((unsigned char *)AE); uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU.SetApplicationContext(uid); if (level==1) uid.Set("1.2.840.10008.5.1.4.1.2.1.1"); // PatientRootQuery else uid.Set("1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery PDU.AddAbstractSyntax(uid); PDU.SetTimeOut(TCPIPTimeOut); // Make the association for the FIND on port/ip if(!PDU.Connect(ip, port)) { OperatorConsole.printf("*** Virtual query - failed to connect for C-FIND to %s\n", AE); return ( 0 ); } // Start a Patient/StudyRootQuery if (level==1) strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.1.1"); // PatientRootQuery else strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); command = EN0020; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); priority = 0; // MEDIUM vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE); DCO.Push(vr); datasettype = EN0102; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); messageid = EN0003; vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE); DCO.Push(vr); DDOPtr = MakeCopy(DDO); DDOPtr2 = MakeCopy(DDO); // Use passed data object and Level for query SetStringVR(&vr, 0x0008, 0x0052, Level); DDOPtr->ReplaceVR(vr); // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID if (param) if (stricmp(param, "FixKodak")==0) KodakFixer(DDOPtr, TRUE); ///////// virtual queries not via database (experimental - complicated cleanup of pADDO required) if (pADDO && 1) { MyPatientRootQuery mq; MyStudyRootQuery sq; int s=pADDO->GetSize(); // forward query if (level==1) mq.Write(&PDU, DDOPtr, pADDO); else sq.Write(&PDU, DDOPtr, pADDO); PDU.Close(); // anything recieved ? if (pADDO->GetSize() != s) { DBENTRY *dum; int el[1000], gr[1000], count, i, j, count2; BOOL us[1000]; DICOMDataObject DO2; if (DebugLevel>=3) { SystemDebug.printf("Virtual query: first response from %s (total %d records)\n", AE, pADDO->GetSize() - s); NonDestructiveDumpDICOMObject(pADDO->Get(s)); } // build list of valid response vr's: those in query AND in our database at correct level // Our database model is used because the virtual server mimics ours with data from elsewhere count=0; while (vr = DDOPtr2->Pop()) { if (level==0) { if (VerifyIsInDBE(vr, WorkListDB, dum)) { us[count ] = FALSE; el[count ] = vr->Element; gr[count++] = vr->Group; delete vr; continue; } } if (level>=1) { if (VerifyIsInDBE(vr, PatientDB, dum)) { us[count ] = FALSE; el[count ] = vr->Element; gr[count++] = vr->Group; delete vr; continue; } } if (level>=2) { if (VerifyIsInDBE(vr, StudyDB, dum)) { us[count ] = FALSE; el[count ] = vr->Element; gr[count++] = vr->Group; delete vr; continue; } } if (level>=3) { if (VerifyIsInDBE(vr, SeriesDB, dum)) { us[count ] = FALSE; el[count ] = vr->Element; gr[count++] = vr->Group; delete vr; continue; } } if (level>=4) { if (VerifyIsInDBE(vr, ImageDB, dum)) { us[count ] = FALSE; el[count ] = vr->Element; gr[count++] = vr->Group; delete vr; continue; } } delete vr; } count2=0; // counts valid fields during first record OperatorConsole.printf("Virtualquery: processing response from server: %s\n", AE); for (i=s; i<pADDO->GetSize(); i++) { if (i==s+1 && count2==count) // after one record: all fields were valid break; if (i==s+1 && count2!=count) OperatorConsole.printf("Virtualquery: cleaning response from server: %s %d %d\n", AE, count2, count); while(vr=pADDO->Get(i)->Pop()) { for (j=0; j<count; j++) { if (0x0052==vr->Element && 0x0008==vr->Group) { delete vr; break; // auto generated - no need to copy } if (0x0000==vr->Element) { delete vr; break; // auto generated - no need to copy } if (el[j]==vr->Element && gr[j]==vr->Group) { // copy valid fields DO2.Push(vr); us[j] = TRUE; count2++; break; } if (j==count-1) { count2=-10000; // superfluous fields: cleanup always required delete vr; } } } for (j=0; j<count; j++) // insert empties for missing fields { if (!us[j]) { vr = new VR(gr[j], el[j], 0, FALSE); DO2.Push(vr); } else us[j]=FALSE; } pADDO->Get(i)->Reset(); while(vr=DO2.Pop()) pADDO->Get(i)->Push(vr); DO2.Reset(); } // Here fixkodak fiximage should operate stripping 0 to e.g., 09901234 patient ID for (i=s; i<pADDO->GetSize(); i++) if (param) if (stricmp(param, "FixKodak")==0) KodakFixer(pADDO->Get(i), FALSE); } else while (vr = DDOPtr2->Pop()) delete vr; delete DDOPtr2; delete DDOPtr; return pADDO->GetSize() - s; } ////////////////////////////////// Index = 0; DBE = PatientDB; if (level==1) while ( TRUE ) // patient query { if(!DBE[Index].Element) break; if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; } SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, ""); DDOPtr->Push(vr); ++Index; } Index = 0; DBE = StudyDB; if (level>=2) while ( TRUE ) // study, series and image query { if(!DBE[Index].Element) break; if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; } SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, ""); DDOPtr->Push(vr); ++Index; } Index = 0; DBE = SeriesDB; if (level>=3) while ( TRUE ) // series and image query { if(!DBE[Index].Element) break; if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; } SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, ""); DDOPtr->Push(vr); ++Index; } Index = 0; DBE = ImageDB; if (level>=4) while ( TRUE ) // image query { if(!DBE[Index].Element) break; if (DDOPtr->GetVR(DBE[Index].Group, DBE[Index].Element)) {++Index; continue; } SetStringVR(&vr, DBE[Index].Group, DBE[Index].Element, ""); DDOPtr->Push(vr); ++Index; } // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID if (param) if (stricmp(param, "FixKodak")==0) KodakFixer(DDOPtr, TRUE); // Write query command object and data object PDU.Write(&DCO, uid); PDU.Write(DDOPtr, uid); DB.Open ( DataSource, UserName, Password, DataHost ); // Get response quit = 0; while(!quit) { if(!PDU.Read(&DCOR)) { OperatorConsole.printf("*** Virtual query - association lost in C-FIND to %s\n", AE); break; } // is this a C-Find-RSP ? if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8020) { OperatorConsole.printf("*** Virtual query - wrong response for C-FIND to %s\n", AE); break; } // is there a data set? if(DCOR.GetUINT16(0x0000, 0x0800)==0x0101) { OperatorConsole.printf("Virtual query from %s - finished\n", AE); break; } // no success if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000) { OperatorConsole.printf("*** Virtual query - C-FIND failed to %s\n", AE); break; } // read response data if(!PDU.Read(&DDOR)) { OperatorConsole.printf("*** Virtual query - C-FIND failed to %s\n", AE); break; } while(vr = DCOR.Pop()) delete vr; // enter new results in database memset((void*)ID, 0, 65); vr = DDOR.GetVR(0x0010, 0x0020); if(vr) strncpy(ID, (char*) vr->Data, vr->Length); if (vr->Length) if (ID[vr->Length-1]==' ') ID[vr->Length-1]=0; if (level>=4) // full db add { FixImage(&DDOR); // Make sure the required DICOM UID's are there + fix patient ID if enabled *rRoot=1; *rFilename=0; if (!GenerateFileName(&DDOR, Device, rRoot, rFilename, TRUE, 0, (char *)MYACRNEMA, (char *)AE, &DB)) OperatorConsole.printf("**** Virtual query (%s) filename problem - %s\n", AE, rFilename); if (*rRoot) // keeps set if image is not on server { if (strchr(Device, '.')==NULL) sprintf(Device+strlen(Device), ".%d", N); // set virtual device # (keep lowest) if(!SaveToDataBase(DB, &DDOR, rFilename, Device, TRUE)) OperatorConsole.printf("**** Virtual query db problem - %s\n", rFilename); else { OperatorConsole.printf("Virtual query (%s) added - %s\n", AE, rFilename); count++; } } } else // partial db add { BOOL AddedImage, AddedStudy, AddedSeries, AddedPatient, AddedWorkList; if (level>=3) UpdateOrAddToTable(DB, SeriesDB, SeriesTableName, &DDOR, "", NULL, ID, NULL, &AddedSeries, FALSE, FALSE); if (level>=2) UpdateOrAddToTable(DB, StudyDB, StudyTableName, &DDOR, "", NULL, ID, NULL, &AddedStudy, FALSE, TRUE); if (level>=1) UpdateOrAddToTable(DB, PatientDB,PatientTableName,&DDOR, "", NULL, ID, NULL, &AddedPatient, FALSE, FALSE); if (level==0) UpdateOrAddToTable(DB, WorkListDB, WorkListTableName,&DDOR, "", NULL, ID, NULL, &AddedWorkList, FALSE, FALSE); OperatorConsole.printf("Virtual query (%s) added db at level - %s\n", AE, Level); count++; } while(vr = DDOR.Pop()) delete vr; } while (vr = DDOPtr2->Pop()) delete vr; while (vr = DDOPtr->Pop()) delete vr; delete DDOPtr2; delete DDOPtr; PDU.Close(); return count; } // sort functions used by RemoveQueryDuplicates static int SortPatient(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; vr1 = ddo1->GetVR(0x0010, 0x0020); vr2 = ddo2->GetVR(0x0010, 0x0020); if (vr1==NULL || vr2==NULL) return 0; if (vr1->Length < vr2->Length) return -1; if (vr1->Length > vr2->Length) return 1; return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length); } static int SortStudy(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; vr1 = ddo1->GetVR(0x0020, 0x000d); vr2 = ddo2->GetVR(0x0020, 0x000d); if (vr1==NULL || vr2==NULL) return 0; if (vr1->Length < vr2->Length) return -1; if (vr1->Length > vr2->Length) return 1; return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length); } static int SortSeries(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; vr1 = ddo1->GetVR(0x0020, 0x000e); vr2 = ddo2->GetVR(0x0020, 0x000e); if (vr1==NULL || vr2==NULL) return 0; if (vr1->Length < vr2->Length) return -1; if (vr1->Length > vr2->Length) return 1; return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length); } static int SortImages(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; vr1 = ddo1->GetVR(0x0008, 0x0018); vr2 = ddo2->GetVR(0x0008, 0x0018); if (vr1==NULL || vr2==NULL) return 0; if (vr1->Length < vr2->Length) return -1; if (vr1->Length > vr2->Length) return 1; return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length); } static int SortAccession(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; vr1 = ddo1->GetVR(0x0008, 0x0050); vr2 = ddo2->GetVR(0x0008, 0x0050); if (vr1==NULL || vr2==NULL) return 0; if (vr1->Length < vr2->Length) return -1; if (vr1->Length > vr2->Length) return 1; return memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length); } static int SortImageNumber(const void* pElem1, const void* pElem2) { VR *vr1, *vr2; DICOMDataObject *ddo1= *(DICOMDataObject **) pElem1; DICOMDataObject *ddo2= *(DICOMDataObject **) pElem2; char t1[68], t2[68]; vr1 = ddo1->GetVR(0x0020, 0x0013); vr2 = ddo2->GetVR(0x0020, 0x0013); if (vr1==NULL || vr2==NULL) return 0; strncpy(t1, (char *)vr1->Data, vr1->Length); t1[vr1->Length]=0; strncpy(t2, (char *)vr2->Data, vr2->Length); t2[vr2->Length]=0; if (atoi(t1) < atoi(t2)) return -1; else if (atoi(t1) > atoi(t2)) return 1; else return 0; } // Remove duplicate entries from a query response - on selected Level void RemoveQueryDuplicates(char *Level, Array < DICOMDataObject * > *ADDO) { DICOMDataObject **addo = (DICOMDataObject **)malloc(ADDO->GetSize() * sizeof(DICOMDataObject *)); int i, j, g, e; VR *vr1, *vr2; for (i=0; i<ADDO->GetSize(); i++) addo[i] = ADDO->Get(i); // sort on primary key if (strncmp(Level, "PATIENT", 7)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortPatient), g=0x0010, e=0x0020; else if (strncmp(Level, "STUDY", 5)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortStudy), g=0x0020, e=0x000d; else if (strncmp(Level, "SERIES", 6)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortSeries), g=0x0020, e=0x000e; else if (strncmp(Level, "IMAGE", 5)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortImages), g=0x0008, e=0x0018; else if (strncmp(Level, "WORKLIST",8)==0) qsort(addo, ADDO->GetSize(), sizeof(DICOMDataObject *), SortAccession),g=0x0008, e=0x0050; else { free(addo); return; } j = ADDO->GetSize(); while(ADDO->GetSize()) ADDO->RemoveAt(0); // remove duplicates of primary key for (i=0; i<j; i++) { if (i>0) { vr1 = addo[i-1]->GetVR(g, e); vr2 = addo[i ]->GetVR(g, e); if (vr1 && vr2 && vr1->Length==vr2->Length) if (memicmp((char *)vr1->Data, (char *)vr2->Data, vr1->Length)==0) { ADDO->Get(ADDO->GetSize()-1) = addo[i]; delete addo[i-1]; continue; } } ADDO->Add(addo[i]); } SystemDebug.printf("Virtualquery: removed %d duplicates out of %d entries\n", j-ADDO->GetSize(), j); free(addo); } // Patient, study or series finder (server functional); search string starts with = means exact BOOL PatientStudyFinder(char *server, char *str, char *fmt, FILE *f, char *level) { DICOMDataObject DDO; VR *vr; char tmp[256]; char outp[7][256]; BOOL local=stricmp(server, (char *)MYACRNEMA)==0; Array < DICOMDataObject * > ADDO; int i, j; // search ID SetStringVR(&vr, 0x0008, 0x0052, level); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0010, ""); DDO.Push(vr); if (str[0] == '=') sprintf(tmp, "%s", str+1); else sprintf(tmp, "*%s*", str); SetStringVR(&vr, 0x0010, 0x0020, tmp); DDO.Push(vr); if (level[0]=='S') { SetStringVR(&vr, 0x0008, 0x0020, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000d, ""); DDO.Push(vr); if (level[1]=='E') { SetStringVR(&vr, 0x0008, 0x0031, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, ""); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0060, ""); DDO.Push(vr); } else { SetStringVR(&vr, 0x0008, 0x0061, ""); DDO.Push(vr); } } if (strcmp(server, "local")==0) { if (level[0]=='P') QueryOnPatient (&DDO, &ADDO); if (level[0]=='S' && level[1]=='T') QueryOnStudy (&DDO, &ADDO); if (level[0]=='S' && level[1]=='E') QueryOnSeries (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, level, 10, &ADDO); } DDO.Reset(); // search name SetStringVR(&vr, 0x0008, 0x0052, level); DDO.Push(vr); if (str[0] == '=') sprintf(tmp, "%s", str+1); else sprintf(tmp, "*%s*", str); SetStringVR(&vr, 0x0010, 0x0010, tmp); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0020, ""); DDO.Push(vr); if (level[0]=='S') { SetStringVR(&vr, 0x0008, 0x0020, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000d, ""); DDO.Push(vr); if (level[1]=='E') { SetStringVR(&vr, 0x0008, 0x0031, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, ""); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0060, ""); DDO.Push(vr); } else { SetStringVR(&vr, 0x0008, 0x0061, ""); DDO.Push(vr); } } if (strcmp(server, "local")==0) { if (level[0]=='P') QueryOnPatient (&DDO, &ADDO); if (level[0]=='S' && level[1]=='T') QueryOnStudy (&DDO, &ADDO); if (level[0]=='S' && level[1]=='E') QueryOnSeries (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, level, 10, &ADDO); } DDO.Reset(); // search study date (=passed as is), only yyyy, yyyymm, yyyymmdd or data range queries if (level[0]=='S' && str[0]!='=') { SetStringVR(&vr, 0x0008, 0x0052, level); DDO.Push(vr); if (str[0] == '=') sprintf(tmp, "%s", str+1); else { if (strlen(str)==4 && atoi(str)>1900 && atoi(str)<2200) sprintf(tmp, "%s0101-%s1231", str, str); else if (strlen(str)==6 && atoi(str)>190000 && atoi(str)<220000) sprintf(tmp, "%s01-%s31", str, str); else if (strlen(str)==8 && atoi(str)>19000000 && atoi(str)<22000000) sprintf(tmp, "%s", str); else if (strlen(str)==9 && atoi(str)>19000000 && atoi(str)<22000000 && str[8]=='-') sprintf(tmp, "%s", str); else if (strlen(str)==9 && atoi(str+1)>19000000 && atoi(str+1)<22000000 && str[0]=='-') sprintf(tmp, "%s", str); else if (strlen(str)==17 && atoi(str)>19000000 && atoi(str)<22000000 && str[8]=='-' && atoi(str+9)>19000000 && atoi(str+9)<22000000) sprintf(tmp, "%s", str); else sprintf(tmp, "invalid"); } SetStringVR(&vr, 0x0008, 0x0020, tmp); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0010, ""); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0020, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000d, ""); DDO.Push(vr); if (level[1]=='E') { SetStringVR(&vr, 0x0008, 0x0031, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, ""); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0060, ""); DDO.Push(vr); } else { SetStringVR(&vr, 0x0008, 0x0061, ""); DDO.Push(vr); } if (strcmp(tmp, "invalid")!=0) { if (strcmp(server, "local")==0) { if (level[1]=='T') QueryOnStudy (&DDO, &ADDO); if (level[1]=='E') QueryOnSeries (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, level, 10, &ADDO); } } DDO.Reset(); } // search study UID (as is) for series level (exact only) if (level[0]=='S' && level[1]=='E' && str[0] == '=' && strlen(str)>15) { SetStringVR(&vr, 0x0008, 0x0052, level); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0020, ""); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0010, ""); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0020, ""); DDO.Push(vr); if (str[0] == '=') sprintf(tmp, "%s", str+1); else sprintf(tmp, "%s", str); SetStringVR(&vr, 0x0020, 0x000d, tmp); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0031, ""); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, ""); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0060, ""); DDO.Push(vr); if (strcmp(server, "local")==0) { QueryOnSeries (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, level, 10, &ADDO); } DDO.Reset(); } RemoveQueryDuplicates(level, &ADDO); for (i=0; i<ADDO.GetSize(); i++) { j = 0; while(vr=ADDO.Get(i)->Pop()) { if (0x0052==vr->Element && 0x0008==vr->Group) { delete vr; continue; } if (0x0000==vr->Element) { delete vr; continue; } if (j<7) { memcpy(outp[j], vr->Data, vr->Length); if (outp[j][vr->Length-1]==' ') outp[j++][vr->Length-1]=0; else outp[j++][vr->Length]=0; } delete vr; } if (level[0]=='P') fprintf(f, fmt, outp[0], outp[1], outp[0], outp[1], outp[0], outp[1], outp[0], outp[1], outp[0], outp[1]); else if (level[1]=='T') fprintf(f, fmt, outp[0], outp[1], outp[2], outp[3], outp[4], outp[0], outp[1], outp[2], outp[3], outp[4], outp[0], outp[1], outp[2], outp[3], outp[4], outp[0], outp[1], outp[2], outp[3], outp[4], outp[0], outp[1], outp[2], outp[3], outp[4]); else if (level[1]=='E') fprintf(f, fmt, outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6], outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6], outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6], outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6], outp[0], outp[1], outp[2], outp[3], outp[4], outp[5], outp[6]); } return TRUE; } // Image lister: get filenames, url's or pat:uid identifier of all objects in one series BOOL ImageFileLister(char *server, char *pat, char *series, char *fmt, FILE *f) { DICOMDataObject DDO; VR *vr; char Device[256], Filename[512], FullFilename[512], Sop[66]; BOOL local=stricmp(server, (char *)MYACRNEMA)==0; Array < DICOMDataObject * > ADDO; int i, j; DICOMDataObject **addo; // search ID SetStringVR(&vr, 0x0008, 0x0052, "IMAGE"); DDO.Push(vr); if (pat) { SetStringVR(&vr, 0x0010, 0x0020, pat); DDO.Push(vr); } if (series) { SetStringVR(&vr, 0x0020, 0x000e, series); DDO.Push(vr); } SetStringVR(&vr, 0x9999, 0x0800, ""); // filename DDO.Push(vr); SetStringVR(&vr, 0x9999, 0x0801, ""); // device DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x0013, ""); // slice number DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0018, ""); // uid DDO.Push(vr); if (strcmp(server, "local")==0) { QueryOnImage (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, "IMAGE", 10, &ADDO); } // sort on image number addo = (DICOMDataObject **)malloc(ADDO.GetSize() * sizeof(DICOMDataObject *)); for (i=0; i<ADDO.GetSize(); i++) addo[i] = ADDO.Get(i); qsort(addo, ADDO.GetSize(), sizeof(DICOMDataObject *), SortImageNumber); j = ADDO.GetSize(); while(ADDO.GetSize()) ADDO.RemoveAt(0); for (i=0; i<j; i++) ADDO.Add(addo[i]); free(addo); // locate files for (i=0; i<ADDO.GetSize(); i++) { Filename[0] = 0; Device[0] = 0; vr = ADDO.Get(i)->GetVR(0x9999, 0x0800); if (vr) { memcpy(Filename, vr->Data, vr->Length); if (Filename[vr->Length-1]==' ') Filename[vr->Length-1] = 0; else Filename[vr->Length] = 0; } vr = ADDO.Get(i)->GetVR(0x9999, 0x0801); if (vr) { memcpy(Device, vr->Data, vr->Length); if (Device[vr->Length-1]==' ') Device[vr->Length-1] = 0; else Device[vr->Length] = 0; } vr = ADDO.Get(i)->GetVR(0x0008, 0x0018); if (vr) { memcpy(Sop, vr->Data, vr->Length); if (Sop[vr->Length-1]==' ') Sop[vr->Length-1] = 0; else Sop[vr->Length] = 0; } if (FindPhysicalDevice(Device, FullFilename, Filename)) { if (i==ADDO.GetSize()-1 && fmt[strlen(fmt)-1]=='*') fmt[strlen(fmt)-1]=0; strcat(FullFilename, Filename); if (fmt[0]=='#') fprintf(f, fmt+1, Device, Filename, i, Device, Filename, i, Device, Filename, i ); else if (fmt[0]=='@') { for (j=0; j<strlen(Filename); j++) if (Filename[j]=='\\') Filename[j]='/'; fprintf(f, fmt+1, Device, Filename, i, Device, Filename, i, Device, Filename, i ); } else if (fmt[0]==':') { char out[100]; int outlen=0; for (j=0; j<strlen(pat); j++) { if (pat[j]==' ') { out[outlen++] = '%'; out[outlen++] = '2'; out[outlen++] = '0'; } else out[outlen++] = pat[j]; } out[outlen++]=0; fprintf(f, fmt+1, out, Sop, i, out, Sop, i, out, Sop, i); } else fprintf(f, fmt, FullFilename, i, FullFilename, i, FullFilename, i); } while(vr=ADDO.Get(i)->Pop()) delete vr; } return TRUE; } // Series lister: get all series of one (or all) study BOOL SeriesUIDLister(char *server, char *pat, char *study, char *fmt, FILE *f) { DICOMDataObject DDO; VR *vr; char UID[256]; BOOL local=stricmp(server, (char *)MYACRNEMA)==0; Array < DICOMDataObject * > ADDO; int i; // search ID SetStringVR(&vr, 0x0008, 0x0052, "SERIES"); DDO.Push(vr); if (pat) { SetStringVR(&vr, 0x0010, 0x0020, pat); DDO.Push(vr); } if (study) { SetStringVR(&vr, 0x0020, 0x000d, study); DDO.Push(vr); } SetStringVR(&vr, 0x0020, 0x000e, ""); DDO.Push(vr); if (strcmp(server, "local")==0) { QueryOnSeries (&DDO, &ADDO); } else { strncpy(VirtualServerFor[10], server, 16); VirtualServerFor[10][16]=0; VirtualQuery(&DDO, "SERIES", 10, &ADDO); } for (i=0; i<ADDO.GetSize(); i++) { UID[0] = 0; vr = ADDO.Get(i)->GetVR(0x0020, 0x000e); if (vr) { memcpy(UID, vr->Data, vr->Length); if (UID[vr->Length-1]==' ') UID[vr->Length-1] = 0; else UID[vr->Length] = 0; fprintf(f, fmt, UID, i, UID, i, UID, i); } while(vr=ADDO.Get(i)->Pop()) delete vr; } return TRUE; } // Implementation: Query BOOL MyPatientRootQuery :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { char Level [ 10 ]; int sources=0, count1, count2; BOOL st; SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10); strcpy(QueryRetrieveLevel, Level); OperatorConsole.printf("(PatientRootQuery) search level: %s\n", Level); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) sources += VirtualQuery(DDOPtr, Level, i, ADDO)!=0; count1 = ADDO->GetSize(); prefetcher(DDOPtr, FALSE); if(!strncmp(Level, "PATIENT", 7)) st = ( QueryOnPatient (DDOPtr, ADDO)); else if(!strncmp(Level, "STUDY", 5)) st = ( QueryOnStudy (DDOPtr, ADDO)); else if(!strncmp(Level, "SERIES", 6)) st = ( QueryOnSeries (DDOPtr, ADDO)); else if(!strncmp(Level, "IMAGE", 5)) st = ( QueryOnImage (DDOPtr, ADDO)); else st = FALSE; count2 = ADDO->GetSize()-count1; sources += count2!=0; if (sources>1) // more than one source; data can be duplicated RemoveQueryDuplicates(Level, ADDO); RecordsFound = ADDO->GetSize(); return st; } BOOL MyStudyRootQuery :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { char Level [ 10 ]; int sources=0, count1, count2; BOOL st; SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10); strcpy(QueryRetrieveLevel, Level); OperatorConsole.printf("(StudyRootQuery) search level: %s\n", Level); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) sources += VirtualQuery(DDOPtr, Level, i, ADDO)!=0; count1 = ADDO->GetSize(); prefetcher(DDOPtr, FALSE); if(!strncmp(Level, "STUDY", 5)) st = ( QueryOnStudy (DDOPtr, ADDO)); else if(!strncmp(Level, "SERIES", 6)) st = ( QueryOnSeries (DDOPtr, ADDO)); else if(!strncmp(Level, "IMAGE", 5)) st = ( QueryOnImage (DDOPtr, ADDO)); else st = FALSE; count2 = ADDO->GetSize()-count1; sources += count2!=0; if (sources>1) RemoveQueryDuplicates(Level, ADDO); if (DebugLevel>=3 && ADDO->GetSize()!=0) { SystemDebug.printf("First record of cleaned response:\n"); NonDestructiveDumpDICOMObject(ADDO->Get(0)); } RecordsFound = ADDO->GetSize(); return st; } BOOL MyPatientStudyOnlyQuery :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { char Level [ 10 ]; int sources=0, count1, count2; BOOL st; SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10); strcpy(QueryRetrieveLevel, Level); OperatorConsole.printf("(PatientStudyOnlyQuery) search level: %s\n", Level); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) sources += VirtualQuery(DDOPtr, Level, i, ADDO)!=0; count1 = ADDO->GetSize(); prefetcher(DDOPtr, FALSE); if(!strncmp(Level, "PATIENT", 7)) st = ( QueryOnPatient (DDOPtr, ADDO)); else if(!strncmp(Level, "STUDY", 5)) st = ( QueryOnStudy (DDOPtr, ADDO)); else st = FALSE; count2 = ADDO->GetSize()-count1; sources += count2!=0; if (sources>1) RemoveQueryDuplicates(Level, ADDO); if (DebugLevel>=3 && ADDO->GetSize()!=0) { SystemDebug.printf("First record of cleaned response:\n"); NonDestructiveDumpDICOMObject(ADDO->Get(0)); } RecordsFound = ADDO->GetSize(); return st; } BOOL MyModalityWorkListQuery :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { char Level [ 10 ]; int sources=0, count1, count2; BOOL st; SetString(DDOPtr->GetVR(0x0008, 0x0052), Level, 10); strcpy(QueryRetrieveLevel, Level); OperatorConsole.printf("(ModalityWorkListQuery) search level: %s\n", Level); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); // for (int i=0; i<10; i++) // sources += VirtualQuery(DDOPtr, Level, i, ADDO)!=0; count1 = ADDO->GetSize(); // prefetcher(DDOPtr, FALSE); st = ( QueryOnModalityWorkList (DDOPtr, ADDO)); count2 = ADDO->GetSize()-count1; sources += count2!=0; if (sources>1) RemoveQueryDuplicates(Level, ADDO); if (DebugLevel>=3 && ADDO->GetSize()!=0) { SystemDebug.printf("First record of cleaned response:\n"); NonDestructiveDumpDICOMObject(ADDO->Get(0)); } RecordsFound = ADDO->GetSize(); return st; } BOOL MyPatientRootQuery :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyStudyRootQuery :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientStudyOnlyQuery :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyModalityWorkListQuery :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientRootRetrieve :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientRootRetrieve :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientRootRetrieveNKI :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientRootRetrieveNKI :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientRootRetrieveGeneric :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientRootRetrieveGeneric :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyStudyRootRetrieve :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyStudyRootRetrieve :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyStudyRootRetrieveNKI :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyStudyRootRetrieveNKI :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyStudyRootRetrieveGeneric :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyStudyRootRetrieveGeneric :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientStudyOnlyRetrieve :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientStudyOnlyRetrieve :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientStudyOnlyRetrieveNKI :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientStudyOnlyRetrieveNKI :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientStudyOnlyRetrieveGeneric :: SearchOn ( DICOMDataObject *DDOPtr, Array < DICOMDataObject * > *ADDO) { VR *vr; // char Level [ 10 ]; prefetcher(DDOPtr, TRUE); SystemDebug.printf("MyPatientStudyOnlyRetrieveGeneric :: SearchOn\n"); if (DebugLevel>=2) NonDestructiveDumpDICOMObject(DDOPtr); for (int i=0; i<10; i++) VirtualQuery(DDOPtr, "IMAGE", i, NULL); if(!DDOPtr->GetVR(0x0008, 0x0018)) { vr = new VR ( 0x0008, 0x0018, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0008, 0x0016)) { vr = new VR ( 0x0008, 0x0016, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000d)) { vr = new VR ( 0x0020, 0x000d, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x0020, 0x000e)) { vr = new VR ( 0x0020, 0x000e, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0800)) { vr = new VR ( 0x9999, 0x0800, 0, FALSE ); DDOPtr->Push(vr); } if(!DDOPtr->GetVR(0x9999, 0x0801)) { vr = new VR ( 0x9999, 0x0801, 0, FALSE ); DDOPtr->Push(vr); } QueryOnImage(DDOPtr, ADDO); if(!ADDO->GetSize()) return(FALSE); OperatorConsole.printf("Number of Images to send: %d\n", ADDO->GetSize()); return(TRUE); } BOOL MyPatientRootRetrieve :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientRootRetrieveNKI :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientRootRetrieveGeneric :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyStudyRootRetrieve :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyStudyRootRetrieveNKI :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyStudyRootRetrieveGeneric :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientStudyOnlyRetrieve :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientStudyOnlyRetrieveNKI :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } BOOL MyPatientStudyOnlyRetrieveGeneric :: CallBack ( DICOMCommandObject *DCOPtr, DICOMDataObject *DDOPtr) { return ( TRUE ); } /* Read ahead implementation */ struct ReadAheadThreadData { char *SOPs; char *Studies; char *Series; char *ObjectFiles; char *Devices; char *pats; int NumToRead; DICOMDataObject **DDOOutPtr; Database *DB; int iVrSizeLimit; #ifdef WIN32 HANDLE Handle; #else pthread_t Handle; #endif DICOMCommandObject *pDCO; char *Filenames; volatile BOOL Busy; volatile BOOL ForceEnd; volatile BOOL TimeOut; char *FullFilenames; int filesmissing; int numreadahead; }; #ifdef WIN32 #define NULLHANDLE NULL #else #define NULLHANDLE 0 #endif // Move any missing slices from the AE to here BOOL VirtualServer(struct ReadAheadThreadData *ratd, int N) { char AE[48]; strcpy(AE, VirtualServerFor[N]); if (*AE==0) return FALSE; char *param = strchr(AE, ','); if (param) *param++ = 0; unsigned char ip[64], port[64], compress[64]; VR *vr; char SOP[66]; DICOMCommandObject DCO, DCOR2; DICOMDataObject DDO, DDOR2; LE_UINT16 command, datasettype, messageid=3, priority, tempid; UID uid; int quit, i, ims=0; PDU_Service PDU2; char *pats, *series, *studies, *sops, *p; OperatorConsole.printf("Virtual server - collecting %d missing objects from %s\n", ratd->filesmissing, AE); PDU2.AttachRTC(&VRType); if(!GetACRNema(AE, (char *)ip, (char *)port, (char *)compress)) return FALSE; PDU2.ClearAbstractSyntaxs(); PDU2.SetLocalAddress(MYACRNEMA); PDU2.SetRemoteAddress((unsigned char *)AE); uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU2.SetApplicationContext(uid); uid.Set("1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootRetrieve (C-Move SOP) PDU2.AddAbstractSyntax(uid); PDU2.SetTimeOut(TCPIPTimeOut); // Make association for MOVE on port/ip if(!PDU2.Connect(ip, port)) { PDU2.Close(); OperatorConsole.printf("*** Virtual server - failed to connect %s (%s %s) for C-MOVE\n", AE, ip, port); return(FALSE); } // collect move requests together if possible (same patients) in pats and sops; else set pats to NULL pats=NULL; studies=NULL; series=NULL; sops = (char *)malloc(66*ratd->NumToRead); sops[0]=0; for (i=0; i<ratd->NumToRead; i++) { if (*(ratd->FullFilenames+i*1024)) continue; // present if (!pats) pats = strdup(ratd->pats +i*66); if (!studies) studies = strdup(ratd->Studies+i*66); if (!series) series = strdup(ratd->Series +i*66); else if (strcmp(pats, ratd->pats +i*66) || strcmp(studies, ratd->Studies+i*66) || strcmp(series, ratd->Series +i*66)) { free(pats); pats = NULL; free(studies); studies = NULL; free(series); series = NULL; break; } strcat(sops, ratd->SOPs+i*66); strcat(sops, "\\"); } sops[strlen(sops)-1]=0; if (!pats) free(sops); // perform one or more c-move requests for (i=0; i<ratd->NumToRead; i++) { if (*(ratd->FullFilenames+i*1024)) continue; // present p = strchr(ratd->Devices+i*32, '.'); if (p && atoi(p+1)!=N) continue; // not on this server DCO.Reset(); DDO.Reset(); // move missing file to this server strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootMove (C-Move SOP) vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); command = EN0021; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); priority = 0; // MEDIUM vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE); DCO.Push(vr); datasettype = EN0102; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); messageid++; #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian tempid = messageid; #else //Big Endian like Apple power pc tempid = SwitchEndian((UINT16) messageid); #endif //Big Endian vr = new VR (0x0000, 0x0110, 0x0002, &tempid, FALSE); DCO.Push(vr); vr = new VR(0x0000, 0x0600, 16, (void*)MYACRNEMA, FALSE); DCO.Push(vr); // Data object. Query level is image; ask for patient ID and SopInstanceUID SetStringVR(&vr, 0x0008, 0x0052, "IMAGE"); DDO.Push(vr); if (pats) // one request { SetStringVR(&vr, 0x0010, 0x0020, pats); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0018, sops); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000d, studies); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, series); DDO.Push(vr); } else // many requests { SetStringVR(&vr, 0x0010, 0x0020, ratd->pats+i*66); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0018, ratd->SOPs+i*66); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000d, ratd->Studies+i*66); DDO.Push(vr); SetStringVR(&vr, 0x0020, 0x000e, ratd->Series+i*66); DDO.Push(vr); } // Here fixkodak fiximage should operate adding 0 to e.g., 9901234 patient ID if (param) if (stricmp(param, "FixKodak")==0) KodakFixer(&DDO, TRUE); // Write command object and data object PDU2.Write(&DCO, uid); PDU2.Write(&DDO, uid); // Get response quit = 0; while(!quit) { if(!PDU2.Read(&DCOR2)) { OperatorConsole.printf("*** Virtual server - C-MOVE association lost to %s\n", AE); quit=1; } if(DCOR2.GetUINT16(0x0000, 0x0100)!=0x8021) { OperatorConsole.printf("*** Virtual server - C-MOVE got a wrong response from %s\n", AE); quit=1; } // ignore the data set if(DCOR2.GetUINT16(0x0000, 0x0800)!=0x0101) { PDU2.Read(&DDOR2); DDOR2.Reset(); } if(DCOR2.GetUINT16(0x0000, 0x0900)==0x0000) // success ? { if (pats) OperatorConsole.printf("Virtual server - Grabbed %d images for %s from %s\n", ims, pats, AE); else OperatorConsole.printf("Virtual server - Grabbed %s from %s\n", ratd->SOPs+i*66, AE); quit=1; } else if (DCOR2.GetUINT16(0x0000, 0x0900)==0xff00) // continuing no problem { ims++; } else { UINT16 RemoteError = DCOR2.GetUINT16(0x0000, 0x0900); OperatorConsole.printf("*** Virtual server - remote C-MOVE DICOM Error code %x (%d) from %s\n", RemoteError, RemoteError, AE); quit=1; } DCOR2.Reset(); } if(pats) // one request { free(pats); free(sops); free(series); free(studies); break; } } PDU2.Close(); ratd->filesmissing -= ims; // how many are left ? return (ratd->filesmissing==0); // all missing images retrieved? -> OK } static BOOL WINAPI ReadAheadThread(struct ReadAheadThreadData *ratd) { DICOMDataObject *DDOMask; char FullFilename[1024]; char Filename[1024]; char Device[256]; PDU_Service PDU, PDU2; int len, UseChapter10=0, i, j; DICOMDataObject *DDOOut; // char *pats, *sops; ratd->filesmissing=0; PDU.AttachRTC(&VRType); // Check if all files are there and generate their full filenames ratd->FullFilenames = (char *)malloc(ratd->NumToRead * 1024); for (i=0; i<ratd->NumToRead; i++) { strcpy(Filename, ratd->ObjectFiles + i * 256); strcpy(Device, ratd->Devices + i * 32); if (!FindPhysicalDevice(Device, ratd->FullFilenames+i*1024, Filename)) { *(ratd->FullFilenames+i*1024)=0; ratd->filesmissing++; } else strcat(ratd->FullFilenames+i*1024, Filename); } // virtual server: grab images in db but not on disk from other server; send them and then delete again if (ratd->filesmissing>0) { for (int i=0; i<10; i++) if (VirtualServer(ratd, i)) break; } for (i=0; i<ratd->NumToRead; i++) { if (*(ratd->FullFilenames+i*1024)==0) // retry; may have been collected by virtual server { strcpy(Filename, ratd->ObjectFiles + i * 256); strcpy(Device, ratd->Devices + i * 32); if (!FindPhysicalDevice(Device, FullFilename, Filename)) { OperatorConsole.printf("***Could not find file:%s\n", Filename); free(ratd->FullFilenames); // mvh 20060401: fix hang condition when a read ahead failed ratd->Busy = FALSE; ratd->TimeOut = TRUE; return FALSE; } strcat(FullFilename, Filename); } else strcpy(FullFilename, ratd->FullFilenames + i*1024); len = strlen(FullFilename); if (len>4) UseChapter10 = (stricmp(FullFilename+len-4, ".dcm")==0); if (ratd->ForceEnd) goto TimeOut; int t = time(NULL); if (!UseChapter10) DDOOut = LoadImplicitLittleEndianFile(FullFilename, ratd->iVrSizeLimit); else DDOOut = PDU.LoadDICOMDataObject(FullFilename); LoadTime += time(NULL)-t; if (!DDOOut) // mvh 20060401: fix hang condition when a read ahead failed { OperatorConsole.printf("***Could not read file:%s\n", Filename); ratd->Busy = FALSE; ratd->TimeOut = TRUE; return FALSE; } if (!CacheVirtualData) { if (*(ratd->FullFilenames+i*1024)==0) // if virtual server retrieved data unlink(FullFilename); // delete data if not caching } if (ratd->ForceEnd) { delete DDOOut; goto TimeOut; } t = time(NULL); ProcessDDO(&DDOOut, ratd->pDCO); ProcessTime += time(NULL)-t; strcpy(ratd->Filenames + i*1024, FullFilename); ratd->DDOOutPtr[i] = DDOOut; // Make the thread wait when it is further than numreadahead slices ahead - self timeout is disabled j = 0; while (i>=ratd->numreadahead && ratd->DDOOutPtr[i-ratd->numreadahead]) { if (ratd->ForceEnd) goto TimeOut; Sleep(1); //printf("."); //if (j++ > 5000) goto TimeOut; } } ratd->Busy = FALSE; free(ratd->FullFilenames); return TRUE; // Happens when the client hangs up the TCP/IP connection (signalled by ForceEnd) TimeOut: ratd->TimeOut = TRUE; ratd->Busy = FALSE; free(ratd->FullFilenames); return TRUE; } BOOL RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, RunTimeClassStorage &RTCStorage, DICOMCommandObject *pDCO = NULL, Array < DICOMDataObject *> *pADDO = NULL, void *ExtraBytes = NULL) { VR *vr; char FullFilename[1024]; char Filename[1024]; char Device[256]; PDU_Service PDU; DICOMDataObject *pDDO; int len, UseChapter10=0, i, j; VR* pVR; unsigned int iVrSizeLimit; unsigned long ThreadID; struct ReadAheadThreadData *ratd; PDU.AttachRTC(&VRType); ratd = (struct ReadAheadThreadData *)ExtraBytes; // assume read will fail unless proven otherwise *DDOOutPtr = NULL; // This line will disable the read ahead thread if (!EnableReadAheadThread || NoThread) pADDO = NULL; // mvh 20060401: fix hang condition when a read ahead failed if (ratd->TimeOut) return FALSE; // start read ahead thread when first slice of more than (one:normal, zero:virtual server) is requested if (pADDO && pADDO->Get(0)==DDOMask && pADDO->GetSize() > 0) { VR *vr; iVrSizeLimit = 0xffffffff; if (pDCO) { pVR = pDCO->GetVR(0x9999, 0x0100); if (pVR) iVrSizeLimit = (unsigned int)(*((unsigned int*)pVR->Data)); } // wait for thread to end from possible previous move on same association while (ratd->Busy) { Sleep(10); printf("."); } // free memory of thread if not already done so if (ratd->Devices) { if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL; for (i=0; i<ratd->NumToRead; i++) if (ratd->DDOOutPtr[i]) delete ratd->DDOOutPtr[i]; free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL; free(ratd->Filenames); ratd->Filenames = NULL; free(ratd->ObjectFiles);ratd->ObjectFiles = NULL; free(ratd->Devices); ratd->Devices = NULL; free(ratd->SOPs); ratd->SOPs = NULL; free(ratd->Series); ratd->Series = NULL; free(ratd->Studies); ratd->Studies = NULL; free(ratd->pats); ratd->pats = NULL; CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE; } // initialize thread data ratd->Busy = TRUE; ratd->TimeOut = FALSE; if (pDCO) ratd->pDCO = (DICOMCommandObject *)MakeCopy((DICOMDataObject *)pDCO); ratd->numreadahead = EnableReadAheadThread<2 ? 5 : EnableReadAheadThread; ratd->NumToRead = pADDO->GetSize(); ratd->SOPs = (char *) malloc(ratd->NumToRead * 66); ratd->Series = (char *) malloc(ratd->NumToRead * 66); ratd->Studies= (char *) malloc(ratd->NumToRead * 66); ratd->pats = (char *) malloc(ratd->NumToRead * 66); ratd->ObjectFiles = (char *) malloc(ratd->NumToRead * 256); ratd->Devices = (char *) malloc(ratd->NumToRead * 32); memset(ratd->SOPs, 0, ratd->NumToRead * 66); memset(ratd->Series, 0, ratd->NumToRead * 66); memset(ratd->Studies, 0, ratd->NumToRead * 66); memset(ratd->pats, 0, ratd->NumToRead * 66); memset(ratd->ObjectFiles, 0, ratd->NumToRead * 256); memset(ratd->Devices, 0, ratd->NumToRead * 32); for (i=0; i<ratd->NumToRead; i++) { vr = pADDO->Get(i)->GetVR(0x9999, 0x0800); if (vr) { memcpy(ratd->ObjectFiles+i*256, vr->Data, vr->Length); if ((ratd->ObjectFiles+i*256)[vr->Length-1]==' ') (ratd->ObjectFiles+i*256)[vr->Length-1] = 0; } vr = pADDO->Get(i)->GetVR(0x9999, 0x0801); if (vr) { memcpy(ratd->Devices+i*32, vr->Data, vr->Length); if ((ratd->Devices+i*32)[vr->Length-1]==' ') (ratd->Devices+i*32)[vr->Length-1] = 0; } vr = pADDO->Get(i)->GetVR(0x0008, 0x0018); if (vr) memcpy(ratd->SOPs+i*66, vr->Data, vr->Length); vr = pADDO->Get(i)->GetVR(0x0020, 0x000d); if (vr) memcpy(ratd->Studies+i*66, vr->Data, vr->Length); vr = pADDO->Get(i)->GetVR(0x0020, 0x000e); if (vr) memcpy(ratd->Series+i*66, vr->Data, vr->Length); vr = pADDO->Get(i)->GetVR(0x0010, 0x0020); if (vr) { memcpy(ratd->pats+i*66, vr->Data, vr->Length); if ((ratd->pats+i*66)[vr->Length-1]==' ') (ratd->pats+i*66)[vr->Length-1] = 0; } } ratd->iVrSizeLimit = iVrSizeLimit; ratd->DDOOutPtr = (DICOMDataObject **) malloc(ratd->NumToRead * sizeof(DICOMDataObject *)); memset(ratd->DDOOutPtr, 0, ratd->NumToRead * sizeof(DICOMDataObject *)); ratd->Filenames = (char *) malloc(ratd->NumToRead * 1024); memset(ratd->Filenames, 0, ratd->NumToRead * 1024); // start the thread #ifdef WIN32 ratd->Handle = CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) ReadAheadThread, ratd, 0, &ThreadID); #else pthread_create(&ratd->Handle, NULL, (void*(*)(void*))ReadAheadThread, (void *)ratd); pthread_detach(ratd->Handle); #endif } // Get an item from the read ahead thread if it is running if (pADDO && ratd->Handle!=NULLHANDLE && !ratd->TimeOut) { j = 0; while (!ratd->TimeOut) { for (i=0; i<ratd->NumToRead; i++) { if (pADDO->Get(i)==DDOMask && ratd->DDOOutPtr[i]) { *DDOOutPtr = ratd->DDOOutPtr[i]; strcpy(Filename, ratd->Filenames + i*1024); ratd->DDOOutPtr[i] = NULL; // if it is the last item wait for the thread to end and free the memory if (i==ratd->NumToRead-1) { while (1) { ratd->ForceEnd = TRUE; #ifdef WIN32 if (WaitForSingleObject(ratd->Handle, 10) != WAIT_TIMEOUT) break; if (j++ > 200) break; #else while(ratd->Busy) Sleep(10); if (j++ > 200) break; #endif } if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL; free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL; free(ratd->Filenames); ratd->Filenames = NULL; free(ratd->SOPs); ratd->SOPs = NULL; free(ratd->Series); ratd->Series = NULL; free(ratd->Studies); ratd->Studies = NULL; free(ratd->pats); ratd->pats = NULL; free(ratd->ObjectFiles); ratd->ObjectFiles = NULL; free(ratd->Devices); ratd->Devices = NULL; CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE; } goto further; } } Sleep(1); // 20021215: fixes bug reported by Aaron Cann - 100% load } // mvh 20060401: fix hang condition when a read ahead failed if (ratd->TimeOut) { if (ratd->Devices) { if (ratd->pDCO) delete ratd->pDCO; ratd->pDCO = NULL; for (i=0; i<ratd->NumToRead; i++) if (ratd->DDOOutPtr[i]) delete ratd->DDOOutPtr[i]; free(ratd->DDOOutPtr); ratd->DDOOutPtr = NULL; free(ratd->Filenames); ratd->Filenames = NULL; free(ratd->ObjectFiles);ratd->ObjectFiles = NULL; free(ratd->Devices); ratd->Devices = NULL; free(ratd->SOPs); ratd->SOPs = NULL; free(ratd->Series); ratd->Series = NULL; free(ratd->Studies); ratd->Studies = NULL; free(ratd->pats); ratd->pats = NULL; CloseHandle(ratd->Handle); ratd->Handle = NULLHANDLE; } return FALSE; } further: if(*DDOOutPtr) { OperatorConsole.printf("Sending file : %s\n", Filename); // note subtle difference in message! RTCStorage.SetUID(DDOMask->GetVR(0x0008, 0x00016)); (*SStorage) = &RTCStorage; ImagesSent++; SystemDebug.printf("Image Loaded from Read Ahead Thread, returning TRUE\n"); return ( TRUE ); } } // use normal read code used when only one slice is requested char pat[66]; /* get the patient ID */ pat[0]=0; vr = DDOMask->GetVR(0x0010, 0x0020); if (vr) { memcpy(pat, vr->Data, vr->Length); pat[vr->Length]=0; if (pat[vr->Length-1]==' ') pat[vr->Length-1] = 0; } char series[66]; /* get the series UID */ series[0]=0; vr = DDOMask->GetVR(0x0020, 0x000e); if (vr) { memcpy(series, vr->Data, vr->Length); series[vr->Length]=0; if (series[vr->Length-1]==' ') series[vr->Length-1] = 0; } char study[66]; /* get the study UID */ study[0]=0; vr = DDOMask->GetVR(0x0020, 0x000d); if (vr) { memcpy(study, vr->Data, vr->Length); study[vr->Length]=0; if (study[vr->Length-1]==' ') study[vr->Length-1] = 0; } vr = DDOMask->GetVR(0x0008, 0x0018); /* The SOPInstanceUID */ if(!vr) return ( FALSE ); // it aint going to happen // New code uses cached database, but this connection might have hung up // New code: cache a database for as long as the RTCStorage exists // if (!RTCStorage.DB.Connected) // RTCStorage.DB.Open ( DataSource, UserName, Password, DataHost ); // if(!GetFileName(vr, Filename, Device, /* RTCStorage.DB, */ TRUE)) // return ( FALSE ); // not in database ? // Therefore use slower old code here: re-opens a database for each slice read if(!GetFileName(vr, Filename, Device, TRUE, pat, study, series)) return ( FALSE ); // not in database ? if (!FindPhysicalDevice(Device, FullFilename, Filename)) { OperatorConsole.printf("***Could not find file:%s\n", Filename); return FALSE; } strcat(FullFilename, Filename); // check the filename to determine format len = strlen(FullFilename); if (len>4) UseChapter10 = (stricmp(FullFilename+len-4, ".dcm")==0); int t = time(NULL); if (!UseChapter10) { /* Following load-routine works only for 'implicit' (i.e. no type-codes) LittleEndian files. It is able to skip large VRs; only NKI DicomNodes know how to add extra (private) VRs to the DCO, in order to accomplish this. */ iVrSizeLimit = 0xffffffff; if (pDCO) { /* Check whether there is a iVrSizeLimitLength */ pVR = pDCO->GetVR(0x9999, 0x0100); if (pVR) iVrSizeLimit = (unsigned int)(*((unsigned int*)pVR->Data)); } (*DDOOutPtr) = LoadImplicitLittleEndianFile(FullFilename, iVrSizeLimit); /* Decompression and (in the future) other processing takes place in ProcessDDO (c.f. NKIqrsop.cxx) */ } else // OR: code in filepdu.cxx (dicom.lib); does not decompress but supports all formats { (*DDOOutPtr) = PDU.LoadDICOMDataObject(FullFilename); // OR: Code in loadddo.c, this directory; includes decompression, does not support sequences // (*DDOOutPtr) = LoadDICOMDataObject(FullFilename); } LoadTime += time(NULL)-t; t= time(NULL); ProcessDDO(DDOOutPtr, pDCO); ProcessTime += time(NULL)-t; if(*DDOOutPtr) { OperatorConsole.printf("Sending file: %s\n", FullFilename); ImagesSent++; } else { OperatorConsole.printf("***Could not read file: %s\n", FullFilename); return ( FALSE ); } RTCStorage.SetUID(DDOMask->GetVR(0x0008, 0x00016)); (*SStorage) = &RTCStorage; SystemDebug.printf("Image Loaded, returning TRUE\n"); return ( TRUE ); } BOOL MyPatientRootRetrieve :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage) { SystemDebug.printf("MyPatientRootRetrieve :: RetrieveOn\n"); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage)); } BOOL MyPatientRootRetrieveNKI :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyPatientRootRetrieveNKI :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, GetDCO(), GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); } BOOL MyPatientRootRetrieveGeneric :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyPatientRootRetrieveGeneric :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, pADDO, ExtraBytes)); } BOOL MyStudyRootRetrieve :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage) { SystemDebug.printf("MyStudyRootRetrieve :: RetrieveOn\n"); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage)); } BOOL MyStudyRootRetrieveNKI :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyStudyRootRetrieveNKI :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, GetDCO(), GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); } BOOL MyStudyRootRetrieveGeneric :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyStudyRootRetrieveGeneric :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, pADDO, ExtraBytes)); } BOOL MyPatientStudyOnlyRetrieve :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage) { SystemDebug.printf("MyPatientStudyOnlyRetrieve :: RetrieveOn\n"); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage)); } BOOL MyPatientStudyOnlyRetrieveNKI :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyPatientStudyOnlyRetrieveNKI :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, GetDCO(), GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, pDCO, pADDO, ExtraBytes)); } BOOL MyPatientStudyOnlyRetrieveGeneric :: RetrieveOn ( DICOMDataObject *DDOMask, DICOMDataObject **DDOOutPtr, StandardStorage **SStorage, DICOMCommandObject *pDCO, Array < DICOMDataObject *> *pADDO, void *ExtraBytes) { SystemDebug.printf("MyPatientStudyOnlyRetrieveGeneric :: RetrieveOn\n"); // return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, GetADDO(), ExtraBytes)); return(::RetrieveOn(DDOMask, DDOOutPtr,SStorage,RTCStorage, NULL, pADDO, ExtraBytes)); } BOOL QualifyOn( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { strcpy((char*)MyACRNema, (char*)MYACRNEMA); if(!GetACRNema((char*)ACRNema, (char*)RemoteIP, (char*)RemotePort, (char*)Compress)) { // This is a non-standard "feature". Perhaps the ACR-Nema // is reversable via DNS. You should return FALSE here // if you don't want this. strcpy((char*)RemoteIP, (char*) ACRNema); strcpy((char*)RemotePort, "104"); SystemDebug.printf("(QualifyOn) (anonymous) IP:%s, PORT:%s\n", RemoteIP,RemotePort); return ( TRUE ); } /* GetACRNema is able to discern upper and lower case, so that when two different stations have the same AE, we can still map them to different IP addresses... However, when associating to a 'lower case AE station', it may very well be that that station wants an upper case 'Called AE title'. */ char szRootSC[64], Temp[64]; if (GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) if (GetPrivateProfileString(szRootSC, "SendUpperCaseAE", "0", Temp, 64, ConfigFile)) if (atoi(Temp)) strupr((char*)ACRNema); SystemDebug.printf("(QualifyOn) (mapped) IP:%s, PORT:%s\n", RemoteIP,RemotePort); return ( TRUE ); } BOOL MyPatientRootRetrieve :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort) { BYTE dummy[64]; return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy)); } BOOL MyPatientRootRetrieveNKI :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL MyPatientRootRetrieveGeneric :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL MyStudyRootRetrieve :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort) { BYTE dummy[64]; return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy)); } BOOL MyStudyRootRetrieveNKI :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL MyStudyRootRetrieveGeneric :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL MyPatientStudyOnlyRetrieve :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort) { BYTE dummy[64]; return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, dummy)); } BOOL MyPatientStudyOnlyRetrieveNKI :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL MyPatientStudyOnlyRetrieveGeneric :: QualifyOn ( BYTE *ACRNema, BYTE *MyACRNema, BYTE *RemoteIP, BYTE *RemotePort, BYTE *Compress) { return(::QualifyOn(ACRNema, MyACRNema, RemoteIP, RemotePort, Compress)); } BOOL RunTimeClassStorage :: GetUID ( UID &uid ) { uid = MyUID; return ( TRUE ); } BOOL RunTimeClassStorage :: SetUID ( UID &uid ) { MyUID = uid; return ( TRUE ); } BOOL RunTimeClassStorage :: SetUID ( VR *vr ) { char s [ 66 ]; memset((void*)s, 0, 66); if(vr) { memcpy((void*)s, vr->Data, vr->Length>64 ? 64 : vr->Length); MyUID.Set(s); return(TRUE); } return ( FALSE ); } BOOL RunTimeClassStorage :: SetUID ( DICOMDataObject *DDOPtr) { return(SetUID (DDOPtr->GetVR(0x0008, 0x0016))); } #ifndef UNIX BOOL WINAPI DriverHelper ( DriverApp * ); #else ThreadRoutineType DriverHelper ( ThreadRoutineArgType ); #endif BOOL DriverApp :: Server ( BYTE *port ) { Socket MSocket; #ifndef UNIX DWORD ThreadID; HANDLE ThreadHandle; #else pthread_t ThreadID; // NOTE: this Database is not used BUT, if you don't create/open the // Database in the main thread, you won't be able to in child threads... Database aDB; if(!aDB.Open(DataSource, UserName, Password, DataHost)) { OperatorConsole.printf("***Unable to open database %s as user %s on %s\n", DataSource, UserName, DataHost); return FALSE; } #endif MSocket.SetTimeOut(TCPIPTimeOut); if (!MSocket.Listen ((char*) port )) { OperatorConsole.printf("***Failed to Listen () - bind error\n"); return ( FALSE ); // failed on the bind } while (MSocket.Accept() ) { while ( Lock ) Sleep(50); Lock = 1; ChildSocketfd= MSocket.Socketfd; if (NoThread) DriverHelper(this); else { #ifndef UNIX if(!(ThreadHandle = CreateThread(NULL, 0x0000f000, (LPTHREAD_START_ROUTINE) DriverHelper, this, 0, &ThreadID))) #else // UNIX pthread_create(&ThreadID, NULL, DriverHelper, (void *)this); pthread_detach(ThreadID); if (!ThreadID) #endif { OperatorConsole.printf("***Failed to create thread for child\n"); closesocket ( MSocket.Socketfd ); } else CloseHandle(ThreadHandle); } MSocket.Socketfd = 0; MSocket.Connected = FALSE; #ifdef DO_LEAK_DETECTION if (kbhit()) { /* Only in debug-mode */ Sleep(10000); // Hope that other threads are finished by now /* Cleanup */ CloseACRNemaAddressArray(); free(PatientDB); free(StudyDB); free(SeriesDB); free(ImageDB); FreeDeviceTables(); break; } #endif } #ifdef DEBUG_MODE OperatorConsole.printf("***Error in Accept() function call\n"); SystemDebug.printf("***Attemping to re-bind socket\n"); #endif return ( FALSE ); } BOOL DriverApp :: ServerChildThread ( int Socketfd ) { //ExitThread ( (int) ServerChild ( Socketfd ) ); ServerChild( Socketfd ); return ( FALSE ); } // Technically this routine is not needed. However, Microsoft Visual C++ // has some odd quarks to it. This work around maintains MT safe. #ifndef UNIX BOOL WINAPI DriverHelper (DriverApp *App) { #else ThreadRoutineType DriverHelper(void *theApp) { DriverApp *App = (DriverApp *)theApp; #endif int Socketfd; // pick up data from passed-in object Socketfd = App->ChildSocketfd; // release lock on data App->Lock = 0; App->ServerChildThread ( Socketfd ); // we never technically get here // LJ: in M$VC-debug, we actually do get here, and a crash follows (at least when // ODBC is used) // ExitThread(0x00); return ( THREAD_RETURN_FALSE ); } // Log some user information void LogUser(char* pszOperation, AAssociateRQ* pARQ, DICOMCommandObject* pDCO) { UserLog.printf("\"%s\",\"%s\"\n", pszOperation, pARQ->CallingApTitle); // NonDestructiveDumpDICOMObject(pDCO); object does not exist anymore } // Helps when looking at crash dump void WipeStack(void) { char Dummy[512]; memset(Dummy, '?', sizeof(Dummy)); } #ifdef __BORLANDC__ extern "C" int _RTLENTRY _EXPFUNC _heapchk (void); #endif // Storage that does not require a database void StorageApp :: FailSafeStorage(CheckedPDU_Service *PDU) { DICOMDataObject *DDO; DICOMCommandObject DCO; char Filename[1024]; char Physical[1024]; int i; // defined here to make thread safe: multiple instances of SOPUnknownStorage.DB required MyUnknownStorage SOPUnknownStorage; DDO = new DICOMDataObject; while(TRUE) { DCO.Reset(); if (!PDU->Read(&DCO)) break; SOPUnknownStorage.DB = NULL; // no processing SOPUnknownStorage.nopreget = FALSE; if(!SOPUnknownStorage.Read(PDU, &DCO, DDO)) break; GetPhysicalDevice("MAG0", Physical); sprintf(Filename, "%sfailsafe_storage", Physical); mkdir(Filename); i = strlen(Filename); Filename[i] = PATHSEPCHAR; Filename[i+1] = 0; GenUID(Filename + strlen(Filename)); strcat(Filename, ".dcm"); PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_IMPLICIT, DDO); OperatorConsole.printf("***Failsafe storage saved incoming file as: %s\n", Filename); } delete DDO; } void TestCompress(char *filename, char *modes) { DICOMDataObject *pDDO; int len, i, syntax; PDU_Service PDU; VR *vrSOPInstanceUID; Database DB; char rFilename[1024]; char mode[3]; char SOP[66]; VR *vr; PDU.AttachRTC(&VRType); if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error Connecting to SQL\n"); return; } pDDO = LoadForGUI(filename); if(!pDDO) { OperatorConsole.printf("***[TestCompress] %s -FAILED: Error on Load\n", filename); return; } for(syntax=3; syntax<=4; syntax++) for(i=0; i<strlen(modes); i+=2) { memcpy(mode, modes+i, 2); mode[2]=0; Sleep(1); pDDO = LoadForGUI(filename); strcpy(rFilename, "org"); GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE ); pDDO->ReplaceVR(vr); SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax); pDDO = PDU.LoadDICOMDataObject(rFilename); OperatorConsole.printf("Added file: %s (filename syntax %d)\n", rFilename, syntax); // recompress dropped file recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N'); strcpy(rFilename, mode); GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE ); pDDO->ReplaceVR(vr); SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax); pDDO = PDU.LoadDICOMDataObject(rFilename); OperatorConsole.printf("Added file: %s (compression %s, syntax %d)\n", rFilename, mode, syntax); // uncompress dropped file recompress(&pDDO, "un"); strcpy(rFilename, mode); strcat(rFilename, "_un"); GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE ); pDDO->ReplaceVR(vr); SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax); pDDO = PDU.LoadDICOMDataObject(rFilename); OperatorConsole.printf("Added file: %s (compression %s_un, syntax %d)\n", rFilename, mode, syntax); // recompress dropped file again recompress(&pDDO, mode, "", mode[0]=='n' || mode[0]=='N'); strcpy(rFilename, mode); strcat(rFilename, "_un_"); strcat(rFilename, mode); GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); vr = new VR(0x0020, 0x0013, strlen(rFilename), (void*)rFilename, (BOOL) FALSE ); pDDO->ReplaceVR(vr); SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testcompress", (unsigned char *)"testcompress", syntax); pDDO = PDU.LoadDICOMDataObject(rFilename); OperatorConsole.printf("Added file: %s (compression %s_un_%s, syntax %d)\n", rFilename, mode, mode, syntax); } delete pDDO; } void TestForward(char *filename, char *mode, char *server) { char host[64], port[64], compress[64]; char *p; RunTimeClassStorage RTCStorage; ExtendedPDU_Service PDU; DICOMDataObject* pDDO; UID AppUID ("1.2.840.10008.3.1.1.1"); UID iUID; VR *vr; char SOP[66], temp[20]; BOOL StripGroup2; PDU.AttachRTC(&VRType); if(!GetACRNema(server, (char *)host, (char *)port, (char *)compress)) { strcpy(host, server); p = strchr(host, ':'); if (p) { *p=0; strcpy(port, p+1); } else strcpy(port, "5678"); } PDU.SetRequestedCompressionType(""); // default pDDO = LoadForGUI(filename); if (!pDDO) { OperatorConsole.printf("*** Test forward: failed to load DICOM object %s", filename); return; } // offer transfer syntax from forward string if (mode) PDU.SetRequestedCompressionType(mode); else // offer transfer syntax from acrnema.map PDU.SetRequestedCompressionType(compress); PDU.SetApplicationContext ( AppUID ); PDU.SetLocalAddress ( MYACRNEMA ); PDU.SetRemoteAddress ( (unsigned char *)server ); vr = pDDO -> GetVR(0x0008, 0x0016); if (!vr) { OperatorConsole.printf("*** Test forward: Forward failed because SopClass is missing in %s\n", filename); delete pDDO; return; } SetUID ( iUID, vr ); PDU.AddAbstractSyntax ( iUID ); PDU.SetTimeOut(TCPIPTimeOut); if (!PDU.Connect((unsigned char *)&host, (unsigned char *)&port)) { OperatorConsole.printf("*** Test forward: Forward failed to connect to host %s\n", server); delete pDDO; return; } if (!PDU.IsAbstractSyntaxAccepted(iUID)) { OperatorConsole.printf("*** Test forward: DICOM server %s does not accept type of forwarded images\n", server); PDU.Close(); delete pDDO; return; } OperatorConsole.printf("Test forward: requested %s, accepted %s, sending to %s = %s:%s\n", mode, PDU.GetAcceptedCompressionType(iUID), server, host, port); GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); sprintf(temp, "%s %s", mode, PDU.GetAcceptedCompressionType(iUID)); vr = new VR(0x0020, 0x0013, strlen(temp), (void*)temp, (BOOL) FALSE ); pDDO->ReplaceVR(vr); // recompress data to be forwarded here according to accepted compression mode p = PDU.GetAcceptedCompressionType(iUID); StripGroup2 = memicmp(p, "as", 2)!=0 && memicmp(p, "is", 2)!=0; recompress(&pDDO, p, "", StripGroup2); RTCStorage.SetUID(iUID); if (!RTCStorage.Write(&PDU, pDDO)) { OperatorConsole.printf("*** Test forward: Forward failed to send DICOM image to %s\n", server); PDU.Close(); delete pDDO; return; } delete pDDO; PDU.Close(); } void TestSyntax(char *filename, int syntax) { DICOMDataObject* pDDO; VR *vr; char SOP[66], temp[20]; Database DB; char rFilename[1024]; if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error Connecting to SQL\n"); return; } pDDO = LoadForGUI(filename); if (!pDDO) { OperatorConsole.printf("*** Test syntax: failed to load DICOM object %s", filename); return; } GenUID(SOP); vr = new VR(0x0008, 0x0018, strlen(SOP), (void*)SOP, (BOOL) FALSE ); pDDO->ReplaceVR(vr); sprintf(temp, "syntax %d", syntax); vr = new VR(0x0020, 0x0013, strlen(temp), (void*)temp, (BOOL) FALSE ); pDDO->ReplaceVR(vr); SaveToDisk(DB, pDDO, rFilename, TRUE, (unsigned char *)"testsyntax", (unsigned char *)"testsyntax", syntax); } static BOOL WINAPI testsavethread(char *filename) { TestSyntax(filename, 0); return TRUE; } void TestThreadedSave(char *filename) { #ifdef WIN32 unsigned long ThreadID; CreateThread(NULL, 0x000ff000, (LPTHREAD_START_ROUTINE) testsavethread, filename, 0, &ThreadID); #else pthread_t ThreadID; pthread_create(&ThreadID, NULL, (void*(*)(void*))testsavethread, (void *)filename); pthread_detach(ThreadID); #endif }; ///////////////////////////// elementary printer server support ////////////////////////// // basic film session: is created, deleted, set and action class CFSRQ : public NCreateRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class CFSRSP : public NCreateRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class DFSRQ : public NDeleteRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class DFSRSP : public NDeleteRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class SFSRQ : public NSetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class SFSRSP : public NSetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class AFSRQ : public NActionRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; class AFSRSP : public NActionRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.1"); return TRUE; } }; // basic film box: is created, set, action(printed) and deleted class CFBRQ : public NCreateRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class CFBRSP : public NCreateRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class DFBRQ : public NDeleteRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class DFBRSP : public NDeleteRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class AFBRQ : public NActionRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class AFBRSP : public NActionRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class SFBRQ : public NSetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; class SFBRSP : public NSetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.2"); return TRUE; } }; // Basic GrayScale ImageBox should only be set class SBGIBRQ : public NSetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4"); return TRUE; } }; class SBGIBRRSP : public NSetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4"); return TRUE; } }; // Basic Color ImageBox should only be set class SBCIBRQ : public NSetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4.1"); return TRUE; } }; class SBCIBRRSP : public NSetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.4.1"); return TRUE; } }; // Printer class GPRQ : public NGetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; } }; class GPRSP : public NGetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; } }; class EPRQ : public NEventReportRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; } }; class EPRSP : public NEventReportRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16"); return TRUE; } }; /* OPTIONAL sop classes // Basic Annotation Box should only be set class SBABRQ : public NSetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.15"); return TRUE; } } SetBasicAnnotationBoxRequest; class SBABRRSP : public NSetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.15"); return TRUE; } } SetBasicAnnotationBoxResponse; // Print job class GPJRQ : public NGetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; } } GetPrintJobRequest; class GPJRSP : public NGetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; } } GetPrintJobResponse; class EPJRQ : public NEventReportRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; } } EventReportPrintJobRequest; class EPJRSP : public NEventReportRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.14"); return TRUE; } } EventReportPrintJobResponse; // Presentation LUT: is created and deleted class CPLRQ : public NCreateRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; } } CreatePresentationLUTRequest; class CPLRSP : public NCreateRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; } } CreatePresentationLUTResponse; class DPLRQ : public NDeleteRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; } } DeletePresentationLUTRequest; class DPLRSP : public NDeleteRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.23"); return TRUE; } } DeletePresentationLUTResponse; // Printer configuration: get only class GPCRQ : public NGetRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16.376"); return TRUE; } } GetPrinterConfigurationRequest; class GPCRSP : public NGetRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.5.1.1.16.376"); return TRUE; } } GetPrinterConfigurationResponse; */ static int pcount=0; BOOL StorageApp :: PrinterSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject *PrintData[]) { DICOMDataObject *DDO; char uid[65], Filename[1024]; UID Uid; VR *vr, *vrs; UID aBasicGrayscalePrintManagementMetaSOPClass("1.2.840.10008.5.1.1.9"); UID aBasicColorPrintManagementMetaSOPClass("1.2.840.10008.5.1.1.18"); UID aBasicFilmSessionSOPClassUID("1.2.840.10008.5.1.1.1"); UID aBasicFilmBoxSOPClassUID("1.2.840.10008.5.1.1.2"); UID aBasicGrayscaleImageBoxSOPClassUID("1.2.840.10008.5.1.1.4"); UID aBasicColorImageBoxSOPClassUID("1.2.840.10008.5.1.1.4.1"); UID aBasicPrinterSOPClassUID("1.2.840.10008.5.1.1.16"); UID aAppuid("1.2.840.10008.3.1.1.1"); UID aPrinter("1.2.840.10008.5.1.1.17"); int i; char szPrintSOP[65]; CFSRQ CreateBasicFilmSessionRequest; CFSRSP CreateBasicFilmSessionResponse; DFSRQ DeleteBasicFilmSessionRequest; DFSRSP DeleteBasicFilmSessionResponse; SFSRQ SetBasicFilmSessionRequest; SFSRSP SetBasicFilmSessionResponse; AFSRQ ActionBasicFilmSessionRequest; AFSRSP ActionBasicFilmSessionResponse; CFBRQ CreateBasicFilmBoxRequest; CFBRSP CreateBasicFilmBoxResponse; DFBRQ DeleteBasicFilmBoxRequest; DFBRSP DeleteBasicFilmBoxResponse; AFBRQ ActionBasicFilmBoxRequest; AFBRSP ActionBasicFilmBoxResponse; SFBRQ SetBasicFilmBoxRequest; SFBRSP SetBasicFilmBoxResponse; SBGIBRQ SetBasicGrayScaleImageBoxRequest; SBGIBRRSP SetBasicGrayScaleImageBoxResponse; SBCIBRQ SetBasicColorImageBoxRequest; SBCIBRRSP SetBasicColorImageBoxResponse; GPRQ GetPrinterRequest; GPRSP GetPrinterResponse; EPRQ EventReportPrinterRequest; EPRSP EventReportPrinterResponse; DDO = new DICOMDataObject; vr = DCO->GetVR(0x0000, 0x0002); if (!vr) vr = DCO->GetVR(0x0000, 0x0003); if (vr && vr->Length >= strlen("1.2.840.10008.5.1.1.1 ")) { strncpy(szPrintSOP, (char*)vr->Data, vr->Length); szPrintSOP[vr->Length] = 0; if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.16") == 0) { if (GetPrinterRequest.Read(DCO, PDU, DDO)) { OperatorConsole.printf("getting Printer\n"); // open up PDU for class UIDs used by printer objects PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicFilmSessionSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicFilmBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicGrayscaleImageBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicPrinterSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicFilmSessionSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicFilmBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicColorImageBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicPrinterSOPClassUID); PrintData[0] = new DICOMDataObject; VR *aVR; aVR = new VR(0x2110, 0x0010, strlen("NORMAL"), (void *)"NORMAL", FALSE); PrintData[0]->Push(aVR); aVR = new VR(0x2110, 0x0020, strlen("NORMAL"), (void *)"NORMAL", FALSE); PrintData[0]->Push(aVR); aVR = new VR(0x2110, 0x0030, strlen("Conquest dicom printer"), (void *)"Conquest dicom printer", FALSE); PrintData[0]->Push(aVR); delete DDO; return GetPrinterResponse.Write(PDU, DCO, &aPrinter, 0, PrintData[0]); } if (EventReportPrinterRequest.Read(DCO, PDU, DDO)) { OperatorConsole.printf("N-event Printer\n"); delete DDO; return EventReportPrinterResponse.Write(PDU, DCO, &aPrinter, 0, PrintData[0]); } } else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.1") == 0) { if (CreateBasicFilmSessionRequest.Read(DCO, PDU, DDO)) { PrintData[1] = DDO; // open up PDU for class UIDs used by printer objects PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicFilmSessionSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicFilmBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicGrayscaleImageBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicGrayscalePrintManagementMetaSOPClass, aBasicPrinterSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicFilmSessionSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicFilmBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicColorImageBoxSOPClassUID); PDU->AddAbstractSyntaxAlias(aBasicColorPrintManagementMetaSOPClass, aBasicPrinterSOPClassUID); GenUID(uid); Uid.Set(uid); OperatorConsole.printf("Creating Basic Film Session\n"); CreateBasicFilmSession++; BOOL r = CreateBasicFilmSessionResponse.Write(PDU, DCO, &Uid, 0, DDO); delete DDO; return r; } if (DeleteBasicFilmSessionRequest.Read(DCO, PDU)) { OperatorConsole.printf("Deleting Basic Film Session\n"); //delete PrintData[1]; //PrintData[1] = NULL; DeleteBasicFilmSession++; delete DDO; return DeleteBasicFilmSessionResponse.Write(PDU, DCO, &Uid, 0); } if (ActionBasicFilmSessionRequest.Read(DCO, PDU, DDO)) { OperatorConsole.printf("Printing Basic Film Session\n"); ActionBasicFilmSession++; delete DDO; return ActionBasicFilmSessionResponse.Write(PDU, DCO, NULL, 0, 0, NULL); } if (SetBasicFilmSessionRequest.Read(DCO, PDU, DDO)) { PrintData[1] = DDO; OperatorConsole.printf("Set Basic Film Session\n"); SetBasicFilmSession++; delete DDO; return SetBasicFilmSessionResponse.Write(PDU, DCO, NULL, 0, NULL); } } else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.2") == 0) { if (CreateBasicFilmBoxRequest.Read(DCO, PDU, DDO)) { int n=1, rows=1, cols=1; char text[256]; PrintData[2] = DDO; GenUID(uid); Uid.Set(uid); VR *avr = DDO->GetVR(0x2010, 0x0010); if (avr) { char *p1, *p2; memset(text, 0, 256); memcpy(text, avr->Data, avr->Length); p1 = strchr(text, '\\'); p2 = strchr(text, ','); if (p1 && p2) { rows = atoi(p1+1); cols = atoi(p2+1); n = rows * cols; } } text[0]=0; avr = DDO->GetVR(0x2010, 0x0040); if (avr) { memset(text, 0, 256); memcpy(text, avr->Data, avr->Length); } OperatorConsole.printf("Creating Basic Film Box with %d Image boxes - %s - Film# %d\n", n, text, pcount); Array < DICOMDataObject * > *SQE = new Array < DICOMDataObject * >; vrs = new VR(0x2010, 0x0510, 0, NULL, FALSE); vrs->SQObjectArray = (void*) SQE; for (i=0; i<n; i++) { char *uid2 = (char *)malloc(65); strcpy(uid2, uid); if (uid2[50]=='.') uid2[50]=0; // make space for pcount, row/col info else uid2[51]=0; sprintf(uid2 + strlen(uid2), ".%d.%d.%d.%d", pcount%1000, rows, cols, i); DICOMDataObject *D = new DICOMDataObject; VR *aVR; aVR = new VR(0x0008, 0x1150, strlen("1.2.840.10008.5.1.1.4 "), (void *)"1.2.840.10008.5.1.1.4", FALSE); D->Push(aVR); aVR = new VR(0x0008, 0x1155, (strlen(uid2)+1)&0xfffe, (void *)uid2, TRUE); //leak D->Push(aVR); SQE->Add(D); } pcount++; DDO->Push(vrs); CreateBasicFilmBox++; BOOL r = CreateBasicFilmBoxResponse.Write(PDU, DCO, &Uid, 0, DDO); delete DDO; return r; } if (ActionBasicFilmBoxRequest.Read(DCO, PDU, DDO)) { OperatorConsole.printf("Printing Basic Film Box\n"); ActionBasicFilmBox++; delete DDO; return ActionBasicFilmBoxResponse.Write(PDU, DCO, NULL, 0, 0, NULL); } if (SetBasicFilmBoxRequest.Read(DCO, PDU, DDO)) { PrintData[2] = DDO; OperatorConsole.printf("Set Basic Film Box\n"); SetBasicFilmBox++; delete DDO; return SetBasicFilmBoxResponse.Write(PDU, DCO, NULL, 0, NULL); } if (DeleteBasicFilmBoxRequest.Read(DCO, PDU)) { OperatorConsole.printf("Deleting Basic Film Box\n"); //delete PrintData[2]; //PrintData[2] = NULL; DeleteBasicFilmBox++; delete DDO; return DeleteBasicFilmBoxResponse.Write(PDU, DCO, &Uid, 0); } } else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.4") == 0) { if (SetBasicGrayScaleImageBoxRequest.Read(DCO, PDU, DDO)) { vr = DCO->GetVR(0x0000, 0x1001); if (vr) { memset(Filename, 0, 1024); GetPhysicalDevice("MAG0", Filename); strcat(Filename, "printer_files"); mkdir(Filename); i = strlen(Filename); Filename[i] = PATHSEPCHAR; Filename[i+1] = 0; memcpy(Filename + strlen(Filename), vr->Data, vr->Length); strcat(Filename, ".dcm"); } //OperatorConsole.printf("Setting Basic GrayScale ImageBox\n"); vr = DDO->GetVR(0x2020, 0x0110); if(vr && vr->SQObjectArray) { Array < DICOMDataObject * > *aSQArray; aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray; if ( aSQArray->GetSize() ) { PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, aSQArray->Get(0)); OperatorConsole.printf("Print file: %s\n", Filename); } } SetBasicGrayScaleImageBox++; delete DDO; return SetBasicGrayScaleImageBoxResponse.Write(PDU, DCO, NULL, 0, NULL); } } else if (strcmp(szPrintSOP, "1.2.840.10008.5.1.1.4.1") == 0) { if (SetBasicColorImageBoxRequest.Read(DCO, PDU, DDO)) { vr = DCO->GetVR(0x0000, 0x1001); if (vr) { memset(Filename, 0, 1024); GetPhysicalDevice("MAG0", Filename); strcat(Filename, "printer_files"); mkdir(Filename); i = strlen(Filename); Filename[i] = PATHSEPCHAR; Filename[i+1] = 0; memcpy(Filename + strlen(Filename), vr->Data, vr->Length); strcat(Filename, ".dcm"); } //OperatorConsole.printf("Setting Basic Color ImageBox\n"); vr = DDO->GetVR(0x2020, 0x0111); if(vr && vr->SQObjectArray) { Array < DICOMDataObject * > *aSQArray; aSQArray = (Array < DICOMDataObject * > *) vr->SQObjectArray; if ( aSQArray->GetSize() ) { PDU->SaveDICOMDataObject(Filename, DICOM_CHAPTER_10_EXPLICIT, aSQArray->Get(0)); OperatorConsole.printf("Print file: %s\n", Filename); } } SetBasicColorImageBox++; delete DDO; return SetBasicColorImageBoxResponse.Write(PDU, DCO, NULL, 0, NULL); } } } delete DDO; return FALSE; } ///////////////////////////// elementary storage commitment support as SCP ////////////////////////// //////////// storage commitment as SCU would be needed for a safe Move/Delete operation ///////////// /* first is a sample transaction SEND ASSOCIATE-RQ ( PRESENTATION-CONTEXT-ITEMS ("Storage Commitment Push Model SOP Class", "Implicit VR Little Endian") ) RECEIVE ASSOCIATE-AC ( PRESENTATION-CONTEXT-ITEMS ("Storage Commitment Push Model SOP Class", 0, "Implicit VR Little Endian") ) SEND N-ACTION-RQ "Commitment Push" ( (0x00000003, "Storage Commitment Push Model SOP Class") (0x00001001, "1.2.840.10008.1.20.1.1") # Well-known Instance UID (0x00001008, 1) # Request Storage Commitment (0x00081195, UI, "NEW:TransactionUID") # Transaction UID (0x00081199, SQ, >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "NEW:ImageInstanceUID1") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "NEW:ImageInstanceUID2") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "NEW:ImageInstanceUID3") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "NEW:ImageInstanceUID4") # Referenced SOP Instance UID ) # Referenced SOP Sequence (0x00081111, SQ, >(0x00081150, UI, "1.2.840.10008.3.1.2.3.3") # Referenced SOP Class UID >(0x00081155, UI, "NEW:MppsUID") # Referenced SOP Instance UID ) # Referenced Study Component Sequence ) RECEIVE N-ACTION-RSP ( (0x00000002, "Storage Commitment Push Model SOP Class") (0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID (0x00000900, 0x0000) ) SEND RELEASE-RQ RECEIVE RELEASE-RP RECEIVE ASSOCIATE-RQ ( PRESENTATION-CONTEXT-ITEMS ("Storage Commitment Push Model SOP Class", "Implicit VR Little Endian") ) SEND ASSOCIATE-AC ( PRESENTATION-CONTEXT-ITEMS ("Storage Commitment Push Model SOP Class", 0, "Implicit VR Little Endian") ) RECEIVE N-EVENT-REPORT-RQ "Commitment Push" ( (0x00000002, "Storage Commitment Push Model SOP Class") (0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID (0x00001002, 1) # Storage Commitment Request Successful (0x00081195, UI, "TransactionUID") # Transaction UID (0x00080054, AE, "ARCHIVE") # Retrieve AE Title (0x00081199, SQ, >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "ImageInstanceUID1") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "ImageInstanceUID2") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "ImageInstanceUID3") # Referenced SOP Instance UID , >(0x00081150, UI, "1.2.840.10008.5.1.4.1.1.7") # Referenced SOP Class UID >(0x00081155, UI, "ImageInstanceUID4") # Referenced SOP Instance UID ) # Referenced SOP Sequence ) SEND N-EVENT-REPORT-RSP ( (0x00000002, "Storage Commitment Push Model SOP Class") (0x00001000, "1.2.840.10008.1.20.1.1") # Well-known Instance UID (0x00000900, 0x0000) ) RECEIVE RELEASE-RQ SEND RELEASE-RP */ class ASCPRQ : public NActionRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; } }; class ASCPRSP : public NActionRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; } }; class ESCPRQ : public NEventReportRQ { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; } }; class ESCPRSP : public NEventReportRSP { public: BOOL GetUID ( UID &theUID ) { theUID.Set("1.2.840.10008.1.20.1"); return TRUE; } }; BOOL StorageApp :: StorageCommitmentSupport( CheckedPDU_Service *PDU, DICOMCommandObject *DCO, DICOMDataObject **CommitData) { VR *vr; DICOMCommandObject DCOR; char Sop[65], Calling[20]; BYTE ip[64], port[64], compress[64]; int nfail=0; BOOL status; UID StorageCommitmentPushModelClassUID("1.2.840.10008.1.20.1"); UID StorageCommitmentPushModelInstanceUID("1.2.840.10008.1.20.1.1"); ASCPRQ ActionStorageCommitmentPushRequest; ASCPRSP ActionStorageCommitmentPushResponse; ESCPRQ EventStorageCommitmentPushRequest; ESCPRSP EventStorageCommitmentPushResponse; // association was closed after action: send response on new association if (*CommitData) { PDU_Service PDU2; UID uid; strcpy(Calling, (char *)(((AAssociateAC *)PDU)->CallingApTitle)); while (Calling[strlen(Calling)-1]==' ') Calling[strlen(Calling)-1] = 0; PDU2.AttachRTC(&VRType); if(!GetACRNema(Calling, (char *)ip, (char *)port, (char *)compress)) { OperatorConsole.printf("*** Storage commitment - host not found: %s\n", Calling); return FALSE; } PDU2.ClearAbstractSyntaxs(); PDU2.SetLocalAddress(MYACRNEMA); PDU2.SetRemoteAddress((unsigned char *)Calling); uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU2.SetApplicationContext(uid); uid.Set("1.2.840.10008.1.20.1"); PDU2.AddAbstractSyntax(uid); PDU2.SetTimeOut(TCPIPTimeOut); // Make new association for EVENT on port/ip if(!PDU2.Connect(ip, port)) { OperatorConsole.printf("*** Storage commitment - failed to reconnect to %s (%s %s) for N-EVENT\n", Calling, ip, port); return FALSE; } status = EventStorageCommitmentPushRequest.Write(&PDU2, *CommitData, &StorageCommitmentPushModelInstanceUID, nfail==0 ? 1 : 2); if (status) { status = PDU2.Read(&DCOR); if (status) { EventStorageCommitmentPushResponse.Read(&DCOR, &PDU2, NULL); PDU2.Close(); return FALSE; } } PDU2.Close(); return FALSE; } // is this a storage commitment action request ? vr = DCO->GetVR(0x0000, 0x0003); if (!vr) return FALSE; strncpy(Sop, (char*)vr->Data, vr->Length); Sop[vr->Length] = 0; if (strcmp(Sop, "1.2.840.10008.1.20.1")!=0) return FALSE; vr = DCO->GetVR(0x0000, 0x1001); if (!vr) return FALSE; strncpy(Sop, (char*)vr->Data, vr->Length); Sop[vr->Length] = 0; if (strcmp(Sop, "1.2.840.10008.1.20.1.1")!=0) return FALSE; vr = DCO->GetVR(0x0000, 0x1008); if (!vr) return FALSE; if ((int)(*((unsigned short*)vr->Data))!=1) return FALSE; // read and acknowledge the action *CommitData = new DICOMDataObject; if (ActionStorageCommitmentPushRequest.Read(DCO, PDU, *CommitData)) { OperatorConsole.printf("Storage commitment request recieved\n"); if (!ActionStorageCommitmentPushResponse.Write(PDU, DCO, &StorageCommitmentPushModelInstanceUID, 1, 0, NULL)) return FALSE; // delete retired study component sequence if there vr = (*CommitData)->GetVR(0x0008, 0x1111); if (vr) (*CommitData)->DeleteVR(vr); // add AE title SetStringVR(&vr, 0x0008, 0x0054, (char*)MYACRNEMA); (*CommitData)->Push(vr); // todo: // check presence of each SOPInstance 0008,1155 in sequence 0008,1199 // move failures from sequence 0008,1199 to sequence 0008,1198 // count failures in nfail // write an event (on same association) with results Sleep(200); status = EventStorageCommitmentPushRequest.Write(PDU, *CommitData, &StorageCommitmentPushModelInstanceUID, nfail==0 ? 1 : 2); if (status) { status = PDU->Read(&DCOR); if (status) { EventStorageCommitmentPushResponse.Read(&DCOR, PDU, NULL); delete *CommitData; *CommitData = NULL; return TRUE; } } // in this case, the link was closed: create a new link and try to send response again return FALSE; } return FALSE; } void ConfigDgate(void); BOOL ToGif(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window); BOOL ToBMP(DICOMDataObject* pDDO, char *filename, int size, int append, int level, int window); int MaybeDownsize(DICOMDataObject* pDDO, DICOMCommandObject* pDCO, int size); void CloneDB(char *AE) { VR *vr1; VR *vr; DICOMDataObject DDO; Array < DICOMDataObject * > ADDO; char patid[66]; int len; strncpy(VirtualServerFor[10], AE, 16); VirtualServerFor[10][16]=0; SetStringVR(&vr1, 0x0010, 0x0020, ""); DDO.Push(vr1); SetStringVR(&vr1, 0x0008, 0x0052, "PATIENT"); DDO.Push(vr1); VirtualQuery(&DDO, "PATIENT", 10, &ADDO); for (int i=0; i<ADDO.GetSize(); i++) { while(vr=ADDO.Get(i)->Pop()) { if (0x0020==vr->Element && 0x0010==vr->Group) { strncpy(patid, (char*)vr->Data, vr->Length); patid[vr->Length] = 0; len = vr->Length - 1; while(len>0) { if (patid[len] == ' ') patid[len] = 0; else break; len--; } OperatorConsole.printf("cloning db for patient id=%s", patid); DDO.Reset(); SetStringVR(&vr1, 0x0010, 0x0020, patid); DDO.Push(vr1); SetStringVR(&vr1, 0x0008, 0x0052, "IMAGE"); DDO.Push(vr1); VirtualQuery(&DDO, "IMAGE", 10, NULL); } delete vr; } } OperatorConsole.printf("clone db done\n"); } static void NewTempFile(char *name, char *ext) { int i; char name2[70]; name[0]=0; GetPhysicalDevice("MAG0", name); strcat(name, "printer_files"); mkdir(name); i = strlen(name); name[i] = PATHSEPCHAR; name[i+1] = 0; GenUID(name2); strcat(name2, ext); strcat(name, name2); } BOOL MakeQueryString ( DBENTRY *DBE, char *s) { UINT Index; char TempString [ 128 ]; s[0] = '\0'; Index = 0; while ( TRUE ) { if(!DBE [ Index ].Element) return ( TRUE ); if (DBE[Index].DICOMType!=DT_STARTSEQUENCE && DBE[Index].DICOMType!=DT_ENDSEQUENCE) { if(Index) strcat(s, ", "); strcat ( s, DBE [ Index ].SQLColumn); } ++Index; } return ( TRUE ); } BOOL MakeSafeStringValues (VR *vr, char *string); static char* CommaInFilenameWorkAround(char* SilentText) { char* pComma; char* pCopy; pComma = strchr(SilentText, ','); while (pComma) { /* */ pCopy = strdup(pComma); strlwr(pCopy); if ((strstr(pCopy, ".dcm") != NULL) || (strstr(pCopy, ".v2") != NULL) || (strstr(pCopy, ".hl7") != NULL) || (strstr(pCopy, ".gz") != NULL)) { /* The comma is apparently part of a filename; search for the next comma */ free(pCopy); pComma = strchr(pComma + 1, ','); } else { free(pCopy); break; } } return pComma; } BOOL StorageApp :: ServerChild (int theArg ) { CheckedPDU_Service PDU ( SOPClassFile ); DICOMCommandObject DCO; DICOMDataObject *DDO; VR *vr; VR *vr1; VR *vrsilent; UINT16 val, messageid, orgmessageid; Database DB; int socketfd = theArg; char SilentText[64000]; char TimeString[128]; time_t TimeOfDay, TimeOfDay2; int FirstTime=1; int ThreadNum; DICOMDataObject *PrintData[100]; char OrgMoveAE[17], OwnAE[17]; DebugLevel=DebugVRs; TimeOfDay = time(NULL); PDU.AttachRTC(&VRType); PDU.SetTimeOut(TCPIPTimeOut); // defined here to make thread safe: multiple instances of SOPUnknownStorage.DB required MyUnknownStorage SOPUnknownStorage; Verification SOPVerification; MyPatientRootQuery SOPPatientRootQuery; MyPatientRootRetrieve SOPPatientRootRetrieve; MyPatientRootRetrieveNKI SOPPatientRootRetrieveNKI; MyPatientRootRetrieveGeneric SOPPatientRootRetrieveGeneric; MyStudyRootQuery SOPStudyRootQuery; MyStudyRootRetrieve SOPStudyRootRetrieve; MyStudyRootRetrieveNKI SOPStudyRootRetrieveNKI; MyStudyRootRetrieveGeneric SOPStudyRootRetrieveGeneric; MyPatientStudyOnlyQuery SOPPatientStudyOnlyQuery; MyPatientStudyOnlyRetrieve SOPPatientStudyOnlyRetrieve; MyPatientStudyOnlyRetrieveNKI SOPPatientStudyOnlyRetrieveNKI; MyPatientStudyOnlyRetrieveGeneric SOPPatientStudyOnlyRetrieveGeneric; MyModalityWorkListQuery SOPModalityWorkListQuery; struct ReadAheadThreadData ratd; WipeStack(); if(!PDU.Multiplex ( socketfd )) { OperatorConsole.printf("*** multiplex: connection terminated\n"); return ( FALSE ); } memset(&ratd, 0, sizeof(ratd)); if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { SystemDebug.printf("***Error connecting: %s %s/%s\nRetrying\n", DataSource, UserName, Password ); if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("***Error connecting datasource:%s user:%s password:%s\n", DataSource, UserName, Password ); #ifdef FAILSAFE_STORAGE FailSafeStorage(&PDU); #endif PDU.Close(); return ( FALSE ); } } // pass the DB to the read ahead thread for getting filenames. // NOTE: THIS MEANS THAT THE DB MAY NOT BE USED WHILE RATD IS ACTIVE TO BE THREAD SAFE ratd.DB = &DB; while(TRUE) { #ifdef UNIX #ifndef DARWIN #ifndef SOLARIS if (DebugLevel>0) malloc_stats(); #endif //SOLARIS #endif //DARWIN #endif DCO.Reset(); if (!PDU.Read(&DCO)) { if (FirstTime) { char buf[64]; ThreadNum = ThreadCount++; strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; OperatorConsole.printf("\n"); OperatorConsole.printf("UPACS THREAD %d: STARTED AT: %s\n", ThreadNum, TimeString); if (PDU.ValidPresContexts) OperatorConsole.printf("*** connection terminated\n"); else { IARQ ( PDU, TRUE ); OperatorConsole.printf("*** Association rejected: you may need to add the listed presentation context as sop to dgatesop.lst\n"); } } break; } // 20060607 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov) ratd.TimeOut = FALSE; ratd.ForceEnd = FALSE; ratd.Busy = FALSE; SilentText[0]=0; vrsilent = DCO.GetVR(0x9999, 0x0400); if (vrsilent) { if ( *((unsigned int*)vrsilent->Data) == 0x44414544) { FirstTime = FirstTime-1; FirstTime = (FirstTime+1) / FirstTime; } if(vrsilent->Length) { memcpy(SilentText, vrsilent->Data, vrsilent->Length); SilentText[vrsilent->Length]=0; if (SilentText[vrsilent->Length-1]==' ') SilentText[vrsilent->Length-1]=0; } } else IncomingAssociations++; // do not count associations from GUI if (FirstTime) { if (!vrsilent) { // Print Date / Time in Log file char buf[64]; ThreadNum = ThreadCount++; strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; OperatorConsole.printf("\n"); OperatorConsole.printf("UPACS THREAD %d: STARTED AT: %s\n", ThreadNum, TimeString); IARQ ( PDU, FALSE ); } FirstTime = 0; } messageid = DCO.GetUINT16(0x0000, 0x0110); orgmessageid = DCO.GetUINT16(0x0000, 0x1031); /* get OrgMoveAE */ OrgMoveAE[0]=0; vr = DCO.GetVR(0x0000, 0x1030); if (vr) { memset(OrgMoveAE, ' ', 16); OrgMoveAE[16]=0; memcpy(OrgMoveAE, (char *)(vr->Data), vr->Length); } if (!vrsilent) { val = DCO.GetUINT16(0x0000, 0x0100); SystemDebug.printf("Server Command := %4.4x\n", val); SystemDebug.printf("Message ID := %4.4x\n", messageid); if (orgmessageid) SystemDebug.printf("Move Originator Message ID := %4.4x\n", orgmessageid); if (OrgMoveAE[0]) SystemDebug.printf("Move Originator AE := %s\n", OrgMoveAE); } /* print C-Move destination to console */ VR *vr1 = DCO.GetVR(0x0000, 0x0600); if (vr1 && !vrsilent) { char text[256]; memset(text, 0, 256); memcpy(text, (char *)(vr1->Data), vr1->Length); OperatorConsole.printf("\tC-Move Destination: \"%s\"\n", text); } if (DebugLevel>=1) NonDestructiveDumpDICOMObject(&DCO); /* check for NKI specific command command vr: echo to console */ vr = DCO.GetVR(0x9999, 0x0300); if (vr) { char text[1024]; memset(text, 0, 1024); memcpy(text, (char *)(vr->Data), vr->Length); OperatorConsole.printf("%s\n", text); } DDO = new DICOMDataObject; SOPUnknownStorage.DB = &DB; SOPUnknownStorage.nopreget = FALSE; if (orgmessageid==0xfbad) { sprintf(OwnAE, "%-16s", MYACRNEMA); SOPUnknownStorage.nopreget = memcmp(OwnAE, OrgMoveAE, 16)==0; // avoid loops } if(SOPUnknownStorage.Read(&PDU, &DCO, DDO)) { LogUser("C-Store", &PDU, &DCO); continue; } else { if(DCO.GetUINT16(0x0000, 0x0100)==1) { DebugLevel += 4; SystemDebug.printf("Failed STORAGE\n"); NonDestructiveDumpDICOMObject(DDO); DebugLevel -= 4; } delete DDO; // moved one line down: leak !!!! } // delete DDO; was double 20030704 if (SOPVerification.ReadRequest(&PDU, &DCO)) { char Response[512]; Response[0]=0; char tempfile[256]; tempfile[0]=0; if (!vrsilent) { OperatorConsole.printf("C-Echo\n"); EchoRequest++; } if (SilentText[0]) { char *p = strchr(SilentText, ','), *q=NULL, *r=NULL, *s; GuiRequest++; /* NOW ARRANGED FOR EACH COMMAND .... TO AVOID PROBLEM WITH , IN FILENAMES ETC if (memcmp(SilentText, "merge", 5)!=0) if (memcmp(SilentText, "query", 5)!=0) if (memcmp(SilentText, "put_amap", 8)!=0) if (memcmp(SilentText, "addrecord", 9)!=0) if (memcmp(SilentText, "addimagefile",12)!=0) { if (p) { *p++=0; // points after comma q = strchr(p, ','); if (q) { *q++=0; // points after 2nd comma r = strchr(q, ','); if (r) *r++=0; // points after 3rd comma } } } */ if (memcmp(SilentText, "extract:", 8)==0) { char t[512], u[512]; Database DB; char fld[48][256]; SQLLEN SQLResultLength; if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { if (DB.db_type == DT_DBASEIII && SilentText[8]) { sprintf(t, "%sX%s.DBF", DataSource, PatientTableName); DB.ExtractRecords("DICOMPatients",SilentText+8, t); sprintf(t, "%sX%s.DBF", DataSource, StudyTableName); DB.ExtractRecords("DICOMStudies", SilentText+8, t); sprintf(t, "%sX%s.DBF", DataSource, SeriesTableName); DB.ExtractRecords("DICOMSeries", SilentText+8, t); sprintf(t, "%sX%s.DBF", DataSource, ImageTableName); DB.ExtractRecords("DICOMImages", SilentText+8, t); //sprintf(t, "%sX%s.DBF", DataSource, WorkListTableName); //DB.ExtractRecords("DICOMWorkList",SilentText+8, t); } else { char s[8192]; char TempString[512]; char Physical[512]; Database DB2(DT_DBASEIIINOINDEX); GetPhysicalDevice("MAG0", Physical); sprintf(Physical+strlen(Physical), "dbase%c", PATHSEPCHAR); DB2.Open ( Physical, "", "", ""); DBENTRY *dbe; char *tabname; int i, k; for (int j=0; j<5; j++) { switch(j) { case 0: dbe = PatientDB; tabname = PatientTableName; break; case 1: dbe = PatientDB; tabname = PatientTableName; break; case 2: dbe = StudyDB; tabname = StudyTableName; break; case 3: dbe = SeriesDB; tabname = SeriesTableName; break; case 4: dbe = ImageDB; tabname = ImageTableName; break; } MakeTableString(dbe, s, 1); MakeQueryString(dbe, t); strcat(s, ", AccessTime int, qTimeStamp int, qFlags int, qSpare varchar(64)" ); strcat(t, ", AccessTime, qTimeStamp, qFlags, qSpare" ); if (j==4) { strcat(s, ", ObjectFile varchar(255), DeviceName varchar(32)"); strcat(t, ", ObjectFile, DeviceName"); } for (i=0, k=0; i<999 && dbe[i].Group!=0; i++) k++; // count fields if (j==4) k+=6; else k+=4; if (j==0) sprintf(u, "XA%s", tabname); // all patients else sprintf(u, "X%s", tabname); DB2.CreateTable (u, s); if (j==3) { p = strstr(SilentText+8, "PatientID"); if (p) memcpy(p, "SeriesPat", 9); } else if (j==4) { p = strstr(SilentText+8, "SeriesPat"); if (p) memcpy(p, "ImagePat ", 9); } if (j!=0) DB.Query(tabname, t, SilentText+8, NULL); else DB.Query(tabname, t, NULL, NULL); // all patients for (i=0; i<k; i++) DB.BindField(i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength); memset(fld, 0, sizeof(fld)); while (DB.NextRecord()) { s[0]=0; for (int i=0; i<k; i++) { VR vr; vr.Data = fld[i]; vr.Length = strlen(fld[i]); if (i) strcat ( s, ", "); MakeSafeStringValues ( &vr, TempString ); vr.Data = NULL; vr.Length = 0; strcat ( s, TempString ); } DB2.AddRecord(u, t, s); } if (SilentText[8]==0) break; } } ExtractFromGui++; } } else if (memcmp(SilentText, "query:", 6)==0 || memcmp(SilentText, "query2:", 7)==0 ) { int i, n=1, L, flds=1, mx; char *items[6]; SQLLEN SQLResultLength; memset(items, 0, sizeof(items)); p = strchr(SilentText, ':')+1; items[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]=='|') { p[i]=0; items[n++] = p+i+1; if(n==6) break; } } if (memcmp(SilentText, "query2:", 7)==0) p=items[5], mx=items[4] ? atoi(items[4]): 0; else p=items[4], mx=0; if (items[1]) for (i=0; i<strlen(items[1]); i++) if (items[1][i]==',') flds++; Database DB; if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { char fld[48][256]; FILE *f; char format[8192]; int pstars, first=1; if (items[3]) strcpy(format, items[3]); else for (i=0; i<flds; i++) strcat (format, "%s "); pstars = format[strlen(format)-1] == '*'; if (!pstars) strcat(format, "\n"); else format[strlen(format)-1]=0; memset(fld, 0, sizeof(fld)); if (items[2]) if (*items[2]==0) items[2]=NULL; if (mx) { DB.Query(items[0], items[1], items[2], NULL); for (i=0; i<flds; i++) DB.BindField (i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength); i = 0; while (DB.NextRecord()) i++; if (i>mx) mx=(i+mx-1)/mx; else mx=0; } DB.Query(items[0], items[1], items[2], NULL); for (i=0; i<flds; i++) DB.BindField (i+1, SQL_C_CHAR, fld[i], 255, &SQLResultLength); if (p==NULL || *p==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); } else if (strcmp(p, "cgi")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "Content-type: text/html\n\n"); } else f = fopen(p, "wt"); n=0; for (i=0; i<48; i++) fld[i][0]=0; while (DB.NextRecord()) { if (mx) if ((n++) % mx) continue; for (i=flds; i<48; i++) strcpy(fld[i], fld[i%flds]); // duplicate fields if (!first && pstars) fprintf(f, "*"); first=0; fprintf(f, format, fld[0], fld[1], fld[2], fld[3], fld[4], fld[5], fld[6], fld[7], fld[8], fld[9], fld[10],fld[11],fld[12],fld[13],fld[14],fld[15], fld[16],fld[17],fld[18],fld[19],fld[20],fld[21],fld[22],fld[23], fld[24],fld[25],fld[26],fld[27],fld[28],fld[29],fld[30],fld[31], fld[32],fld[33],fld[34],fld[35],fld[36],fld[37],fld[38],fld[39], fld[40],fld[41],fld[42],fld[43],fld[44],fld[45],fld[46],fld[47]); for (i=0; i<48; i++) fld[i][0]=0; } fclose(f); DB.Close(); QueryFromGui++; } } else if (memcmp(SilentText, "patientfinder:", 14)==0 || memcmp(SilentText, "studyfinder:", 12)==0 || memcmp(SilentText, "seriesfinder:", 13)==0 ) { int i, n=1, L, flds=1, mx; char *items[6]; FILE *f; char format[1024]; memset(items, 0, sizeof(items)); p = strchr(SilentText, ':')+1; items[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]=='|') { p[i]=0; items[n++] = p+i+1; if(n==6) break; } } p = items[3]; if (items[2]==0 || *items[2]==0) { if (memcmp(SilentText, "pat", 3)==0) items[2]="%s %s"; if (memcmp(SilentText, "stu", 3)==0) items[2]="%s %s %s %s %s"; if (memcmp(SilentText, "ser", 3)==0) items[2]="%s %s %s %s %s %s %s"; } strcpy(format, items[2]); strcat(format, "\n"); if (p==NULL || *p==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); } else if (strcmp(p, "cgi")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "Content-type: text/html\n\n"); } else f = fopen(p, "wt"); if (memcmp(SilentText, "pat", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "PATIENT"); if (memcmp(SilentText, "stu", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "STUDY"); if (memcmp(SilentText, "ser", 3)==0) PatientStudyFinder(items[0], items[1], format, f, "SERIES"); fclose(f); } else if (memcmp(SilentText, "imagelister:", 12)==0 || memcmp(SilentText, "serieslister:", 13)==0 ) { int i, n=1, L, flds=1, mx; char *items[6]; FILE *f; char format[256]; memset(items, 0, sizeof(items)); p = strchr(SilentText, ':')+1; items[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]=='|') { p[i]=0; items[n++] = p+i+1; if(n==6) break; } } p = items[4]; if (items[3]==0 || *items[3]==0) items[3]="%s*"; strcpy(format, items[3]); if (format[strlen(format)-1]!='*') strcat(format, "\n"); if (p==NULL || *p==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); } else if (strcmp(p, "cgi")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "Content-type: text/html\n\n"); } else f = fopen(p, "wt"); if (SilentText[1]=='m') ImageFileLister(items[0], items[1], items[2], format, f); else SeriesUIDLister(items[0], items[1], items[2], format, f); fclose(f); } else if (memcmp(SilentText, "addrecord:", 10)==0) { int i, n=1, L; char *items[3]; memset(items, 0, sizeof(items)); p = SilentText+10; items[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]=='|') { p[i]=0; items[n++] = p+i+1; if(n==3) break; } } Database DB; if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { DB.AddRecord(items[0], items[1], items[2]); DB.Close(); QueryFromGui++; } } else if (memcmp(SilentText, "deleterecord:", 13)==0) { Database DB; if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { if (p) *p++=0; // points after 1st comma DB.DeleteRecord(SilentText+13, p); DB.Close(); QueryFromGui++; } } else if (memcmp(SilentText, "deleteimagefromdb:", 18)==0) { DeleteImageFile(SilentText+18, TRUE); } else if (memcmp(SilentText, "deletesopfromdb:", 16)==0) { Database DB; if (DB.Open ( DataSource, UserName, Password, DataHost ) ) { if (p) *p++=0; // points after 1st comma q = strchr(p, ','); if (q) { *q++=0; // points after 2nd comma r = strchr(q, ','); if (r) *r++=0; // points after 3rd comma } NewDeleteSopFromDB(SilentText+16, p, q, r, DB); } } else if (memcmp(SilentText, "deleteimagefile:", 16)==0) { DeleteImageFile(SilentText+16, FALSE); DeleteImageFromGui++; } else if (memcmp(SilentText, "deletepatient:", 14)==0) { DeletePatient(SilentText+14, FALSE); DeletePatientFromGui++; } else if (memcmp(SilentText, "deletestudy:", 12)==0) { DeleteStudy(SilentText+12, FALSE); DeleteStudyFromGui++; } else if (memcmp(SilentText, "deletestudies:", 14)==0) { DeleteStudies(SilentText+14, FALSE); DeleteStudiesFromGui++; } else if (memcmp(SilentText, "deleteseries:", 13)==0) { DeleteSeries(SilentText+13, FALSE); DeleteSeriesFromGui++; } else if (memcmp(SilentText, "movepatient:", 12)==0) { if (p) *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma DcmMove(q, SilentText+12, p, "", "", "", "", "", "", "", "", 6); MovePatientFromGui++; } else if (memcmp(SilentText, "movestudy:", 10)==0) { if (p) *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma s = strchr(q, ':'); if (s) { *s=0; r = q; q = s+1; } else r = ""; DcmMove(r, SilentText+10, p, q, "", "", "", "", "", "", "", 7); MoveStudyFromGui++; } else if (memcmp(SilentText, "movestudies:", 12)==0) { if (p) *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma DcmMove("", SilentText+12, p, "", "", "", "", q, "", "", "", 8); MoveStudiesFromGui++; } else if (memcmp(SilentText, "moveseries:", 11)==0) { if (p) *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma s = strchr(q, ':'); if (s) { *s=0; r = q; q = s+1; } else r = ""; DcmMove(r, SilentText+11, p, "", q, "", "", "", "", "", "", 9); MoveSeriesFromGui++; } else if (memcmp(SilentText, "packdbf:", 8)==0) { Database DB; NeedPack = 3; // pack and threaded index creation DB.Open ( DataSource, UserName, Password, DataHost); } else if (memcmp(SilentText, "clonedb:", 8)==0) { CloneDB(SilentText+8); } else if (memcmp(SilentText, "indexdbf:", 9)==0) { Database DB; NeedPack = 4; // threaded index creation - used after full regen from GUI DB.Open ( DataSource, UserName, Password, DataHost); } else if (memcmp(SilentText, "regenfile:", 10)==0) RegenFile(SilentText+10); else if (memcmp(SilentText, "addimagefile:", 13)==0) { p = CommaInFilenameWorkAround(SilentText); //p = strchr(SilentText+13, '|'); if (p) *p++ = 0; AddImageFile(SilentText+13, p); AddedFileFromGui++; } else if (memcmp(SilentText, "modifypatid:", 12)==0 && p) { *p++=0; // points after 1st comma ModifyPATIDofImageFile(p, SilentText+12, TRUE, NULL); } else if (memcmp(SilentText, "anonymize:", 10)==0 && p) { char anonscript[] = "set 0010,0010 to \"anonymous\";" "set 0010,0030 to \"19010101\";" "set 0008,0090 to \"\";" "set 0020,1020 to \"\";" "set 0051,1010 to \"\";" "set 0009,1200 to \"\";"; *p++=0; // points after 1st comma ModifyPATIDofImageFile(p, SilentText+10, TRUE, anonscript); } else if (memcmp(SilentText, "mergeseriesfile:", 16)==0) MergeUIDofImageFile(SilentText+16, TRUE, "SeriesUID"); else if (memcmp(SilentText, "mergestudyfile:", 15)==0) MergeUIDofImageFile(SilentText+15, TRUE, "StudyUID"); else if (memcmp(SilentText, "mergeseries:", 12)==0) { char temp[128]; int i, n=1, L; char *uids[1000]; p = SilentText+12; uids[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]==',') { p[i]=0; uids[n++] = p+i+1; if(n==1000) break; } } MergeUIDs(uids, n, "SeriesUID", temp); } else if (memcmp(SilentText, "mergestudy:", 11)==0) { char temp[128]; int i, n=1, L; char *uids[16]; p = SilentText+11; uids[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]==',') { p[i]=0; uids[n++] = p+i+1; if(n==16) break; } } MergeUIDs(uids, n, "StudyUID", temp); } else if (memcmp(SilentText, "initializetables:", 17)==0) InitializeTables (atoi(SilentText+17)); else if (memcmp(SilentText, "regen:", 6)==0) Regen(); else if (memcmp(SilentText, "regendevice:", 12)==0) Regen(SilentText+12, FALSE); else if (memcmp(SilentText, "regendir:", 9)==0) { if (p) *p++=0; // points after 1st comma Regen(SilentText+9, FALSE, p); } else if (memcmp(SilentText, "makespace:", 10)==0) { if (LargestFreeMAG()<atoi(SilentText+10)) PanicKillOff(atoi(SilentText+10)); } else if (memcmp(SilentText, "selectlruforarchival:", 21)==0 && p) { if (p) *p++=0; // points after 1st comma SelectLRUForArchival(p, atoi(SilentText+21)); } else if (memcmp(SilentText, "preparebunchforburning:", 23)==0 && p) { if (p) *p++=0; // points after 1st comma PrepareBunchForBurning(p, SilentText+23); } else if (memcmp(SilentText, "movedatatodevice:", 17)==0 && p) { if (p) *p++=0; // points after 1st comma MoveDataToDevice(p, SilentText+17); } else if (memcmp(SilentText, "restoremagflags:", 16)==0) RestoreMAGFlags(); else if (memcmp(SilentText, "comparebunchafterburning:", 25)==0) CompareBunchAfterBurning(SilentText+25); else if (memcmp(SilentText, "verifymirrordisk:", 17)==0) VerifyMirrorDisk(SilentText+17); else if (memcmp(SilentText, "testimages:", 11)==0) TestImages(SilentText+11); else if (memcmp(SilentText, "deletebunchafterburning:", 24)==0) DeleteBunchAfterBurning(SilentText+24); else if (memcmp(SilentText, "renamedevice:", 13)==0 && p) { if (p) *p++=0; // points after 1st comma RenameDevice(SilentText+13, p); } else if (memcmp(SilentText, "testcompress:", 13)==0) TestCompress(SilentText+13, "unasn1n2n3n4j1j2j3j4j5j6k1k2k4k8"); else if (memcmp(SilentText, "debuglevel:", 11)==0) DebugVRs = DebugLevel = atoi(SilentText+11); else if (memcmp(SilentText, "debuglog_on:", 12)==0) { if (SilentText[12]>='0' && SilentText[12]<='9') { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.OnUDP(OCPipeName, SilentText+12); SystemDebug.OnUDP(OCPipeName, SilentText+12); OperatorConsole.AddTimeStamps(0); SystemDebug.AddTimeStamps(0); } else if (SilentText[12] == PATHSEPCHAR) { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.OnMsgPipe(SilentText+12); SystemDebug.OnMsgPipe(SilentText+12); OperatorConsole.AddTimeStamps(0); SystemDebug.AddTimeStamps(0); } else { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.On(SilentText+12); SystemDebug.On(SilentText+12); OperatorConsole.AddTimeStamps(1); SystemDebug.AddTimeStamps(1); } } else if (memcmp(SilentText, "log_on:", 7)==0) { if (SilentText[7]>='0' && SilentText[7]<='9') { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.OnUDP(OCPipeName, SilentText+7); OperatorConsole.AddTimeStamps(0); } else if (SilentText[7] == PATHSEPCHAR) { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.OnMsgPipe(SilentText+7); OperatorConsole.AddTimeStamps(0); } else { SystemDebug.Off(); OperatorConsole.Off(); OperatorConsole.On(SilentText+7); OperatorConsole.AddTimeStamps(1); } } else if (memcmp(SilentText, "read_amap:", 10)==0) { CloseACRNemaAddressArray(); if(!InitACRNemaAddressArray()) { OperatorConsole.printf("***Error loading acr-nema map file:%s\n",ACRNEMAMAP); } } else if (memcmp(SilentText, "read_ini:", 9)==0) { ConfigDgate(); ConfigMicroPACS(); } else if (memcmp(SilentText, "get_ini:", 8)==0) { FILE *f, *g; char line[512]; p = SilentText+8; if (*p==0) p = "%s"; f = fopen(ConfigFile, "rt"); NewTempFile(tempfile, ".txt"); g = fopen(tempfile, "wt"); while(fgets(line, sizeof(line), f) != NULL) fprintf(g, p, line); fclose(f); fclose(g); } else if (memcmp(SilentText, "get_param:", 10)==0) { char szRootSC[64], Parameter[512]; if (p) *p++=0; // points after 1st comma if (p==NULL) p = "%s"; if (GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) { if (GetPrivateProfileString(szRootSC, SilentText+10, "", Parameter, 512, ConfigFile)) sprintf(Response, p, Parameter); } } else if (memcmp(SilentText, "get_ini_param:", 14)==0) { char szRootSC[64], Parameter[512]; if (p) *p++=0; // points after 1st comma if (p==NULL) p = "%s"; if (GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) { if (GetPrivateProfileString(szRootSC, SilentText+14, "", Parameter, 512, ConfigFile)) sprintf(Response, p, Parameter); } } else if (memcmp(SilentText, "get_ini_num:", 12)==0) { char szRootSC[64], Parameter[512]; int r, i; FILE *f; char line[512]; if (p) *p++=0; // points after 1st comma if (p==NULL) p = "%s"; i = 0; r = atoi(SilentText+12); f = fopen(ConfigFile, "rt"); while(fgets(line, sizeof(line), f) != NULL && i <= r) { if (i == r) sprintf(Response, p, line); i++; } fclose(f); } else if (memcmp(SilentText, "put_param:", 10)==0) { FILE *f, *g; char line[512]; BOOL written=FALSE; time_t TimeOfDay; char TimeString[128], buf[64]; char newConfigFile[512]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; if (p) *p++=0; // points after 1st comma strcpy(newConfigFile, ConfigFile); strcat(newConfigFile, ".new"); f = fopen(ConfigFile, "rt"); g = fopen(newConfigFile, "wt"); sprintf(line, "# Written by put_param on %s\n", TimeString); fputs(line, g); while(fgets(line, sizeof(line), f) != NULL) { if (memicmp(line, "# Written by put_param on ", strlen("# Written by put_param on "))==0) continue; if (memicmp(line, SilentText+10, strlen(SilentText+10))==0 && isspace(line[strlen(SilentText+10)])) { sprintf(line, "%-24s = %s\n", SilentText+10, p); written=TRUE; } fputs(line, g); } if (!written) { fputs("\n", g); sprintf(line, "# Parameter added by put_param on %s\n", TimeString); fputs(line, g); sprintf(line, "%-24s = %s\n", SilentText+10, p); fputs(line, g); } fclose(f); fclose(g); unlink(ConfigFile); rename(newConfigFile, ConfigFile); } else if (memcmp(SilentText, "delete_param:", 13)==0) { FILE *f, *g; char line[512]; time_t TimeOfDay; char TimeString[128], buf[64]; char newConfigFile[512]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; strcpy(newConfigFile, ConfigFile); strcat(newConfigFile, ".new"); f = fopen(ConfigFile, "rt"); g = fopen(newConfigFile, "wt"); sprintf(line, "# Written by put_param on %s\n", TimeString); fputs(line, g); while(fgets(line, sizeof(line), f) != NULL) { if (memicmp(line, "# Written by put_param on ", strlen("# Written by put_param on "))==0) continue; if (memicmp(line, SilentText+13, strlen(SilentText+13))==0 && isspace(line[strlen(SilentText+13)])) continue; fputs(line, g); } fclose(f); fclose(g); unlink(ConfigFile); rename(newConfigFile, ConfigFile); } else if (memcmp(SilentText, "get_freestore:", 14)==0) { int r = -1; if (p) *p++=0; // points after 1st comma if (p==NULL) p = "%d"; if (memicmp("MAG", SilentText+14, 3)==0) r = CheckFreeStoreOnMAGDevice(atoi(SilentText+17)); if (memicmp("CACHE", SilentText+14, 5)==0) r = CheckFreeStoreOnCACHEDevice(atoi(SilentText+19)); if (memicmp("MIRROR", SilentText+14, 6)==0) r = CheckFreeStoreOnMIRRORDevice(atoi(SilentText+20)); sprintf(Response, p, r); } else if (memcmp(SilentText, "get_amap:", 9)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+9); if (p==NULL) p = "%-17s %-30s %-10s %-16s"; if (r < ACRNemaAddressArray.GetSize() ) { ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r); sprintf(Response, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress); } } else if (memcmp(SilentText, "get_amaps:", 10)==0) { FILE *g; p = SilentText+10; if (*p==0) p = "%-17s %-30s %-10s %-16s\n"; NewTempFile(tempfile, ".txt"); g = fopen(tempfile, "wt"); for (int r=0; r< ACRNemaAddressArray.GetSize(); r++ ) { ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r); if (strchr(AAPtr->Name, '*')==NULL) fprintf(g, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress); } fclose(g); } else if (memcmp(SilentText, "write_amap:", 11)==0) { int r = 0; if (p) *p++=0; // points after 1st comma p = "%-17s %-30s %-10s %-16s\n"; time_t TimeOfDay; char TimeString[128], buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; FILE *f = fopen("acrnema.map", "wt"); fprintf(f, "/* **********************************************************\n"); fprintf(f, " * *\n"); fprintf(f, " * DICOM AE (Application entity) -> IP address / Port map *\n"); fprintf(f, " * (This is file ACRNEMA.MAP) *\n"); fprintf(f, " * Written by write_amap on %-32s*\n", TimeString); fprintf(f, " * *\n"); fprintf(f, " * All DICOM systems that want to retrieve images from the *\n"); fprintf(f, " * Conquest DICOM server must be listed here with correct *\n"); fprintf(f, " * AE name, (IP adress or hostname) and port number. *\n"); fprintf(f, " * The first entry is the Conquest system as example. *\n"); fprintf(f, " * *\n"); fprintf(f, " * *\n"); fprintf(f, " * The syntax for each entry is : *\n"); fprintf(f, " * AE <IP adress|Host name> port number compression *\n"); fprintf(f, " * *\n"); fprintf(f, " * For compression see manual. Values are un=uncompressed; *\n"); fprintf(f, " * j1,j2=lossless jpeg;j3..j6=lossy jpeg;n1..n4=nki private *\n"); fprintf(f, " * *\n"); fprintf(f, " ********************************************************** */\n"); fprintf(f, "\n"); while (r < ACRNemaAddressArray.GetSize() ) { ACRNemaAddress *AAPtr = ACRNemaAddressArray.Get(r); fprintf(f, p, AAPtr->Name, AAPtr->IP, AAPtr->Port, AAPtr->Compress); r++; } fclose(f); } else if (memcmp(SilentText, "put_amap:", 9)==0) { int i, n=1, L; char *items[5]; ACRNemaAddress *AAPtr; memset(items, 0, sizeof(items)); p = SilentText+9; items[0]=p; L = strlen(p); for (i=0; i<L; i++) { if (p[i]==',') { p[i]=0; items[n++] = p+i+1; if(n==5) break; } } int r = atoi(items[0]); if (r < ACRNemaAddressArray.GetSize() ) AAPtr = ACRNemaAddressArray.Get(r); else { AAPtr = new ACRNemaAddress; strcpy(AAPtr->Name, ""); strcpy(AAPtr->IP, ""); strcpy(AAPtr->Port, ""); strcpy(AAPtr->Compress, "un"); ACRNemaAddressArray.Add(AAPtr); r = ACRNemaAddressArray.GetSize()-1; } if (items[1]) strcpy(AAPtr->Name, items[1]); if (items[2]) strcpy(AAPtr->IP, items[2]); if (items[3]) strcpy(AAPtr->Port, items[3]); if (items[4]) strcpy(AAPtr->Compress, items[4]); } else if (memcmp(SilentText, "delete_amap:", 12)==0) { ACRNemaAddress *AAPtr; int r = atoi(SilentText+12); if (r < ACRNemaAddressArray.GetSize() ) { AAPtr = ACRNemaAddressArray.Get(r); delete AAPtr; ACRNemaAddressArray.RemoveAt(r); } } else if (memcmp(SilentText, "get_sqldef:", 11)==0) { if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma } int r = atoi(p); if (q==NULL) q = "0x%4.4x, 0x%4.4x %20s %4d %10s %12s"; DBENTRY *DBE; if (stricmp(SilentText+11, "patient" )==0) DBE = PatientDB; if (stricmp(SilentText+11, "study" )==0) DBE = StudyDB; if (stricmp(SilentText+11, "series" )==0) DBE = SeriesDB; if (stricmp(SilentText+11, "image" )==0) DBE = ImageDB; if (stricmp(SilentText+11, "worklist")==0) DBE = WorkListDB; if (DBE) if (DBE[r].Group) sprintf(Response, q, DBE[r].Group, DBE[r].Element, DBE[r].SQLColumn, DBE[r].SQLLength, SQLTypeSymName(DBE[r].SQLType), DICOMTypeSymName(DBE[r].DICOMType)); } else if (memcmp(SilentText, "get_sop:", 8)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+8); if (p==NULL) p = "%s %s"; if (r<PDU.SOPUIDListCount) sprintf(Response, p, PDU.SOPUIDList[r], PDU.SOPUIDListNames[r]); } else if (memcmp(SilentText, "put_sop:", 8)==0 || memcmp(SilentText, "put_transfer:", 13)==0 || memcmp(SilentText, "put_localae:", 12)==0 || memcmp(SilentText, "put_remoteae:", 13)==0 || memcmp(SilentText, "put_application:", 16)==0 ) { int r = atoi(strchr(SilentText, ':')+1); char **List, **ListNames; unsigned int *Count; if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma } if (memcmp(SilentText, "put_sop:", 8)==0) { Count = &PDU.SOPUIDListCount; List = PDU.SOPUIDList; ListNames = PDU.SOPUIDListNames; } else if (memcmp(SilentText, "put_transfer:", 13)==0) { Count = &PDU.TransferUIDListCount; List = PDU.TransferUIDList; ListNames = PDU.TransferUIDListNames; } else if (memcmp(SilentText, "put_application:", 16)==0) { Count = &PDU.ApplicationUIDListCount; List = PDU.ApplicationUIDList; ListNames = PDU.ApplicationUIDListNames; } else if (memcmp(SilentText, "put_localae:", 12)==0) { Count = &PDU.LocalAEListCount; List = PDU.LocalAEList; ListNames = PDU.LocalAEListNames; } else if (memcmp(SilentText, "put_remoteae:", 12)==0) { Count = &PDU.RemoteAEListCount; List = PDU.RemoteAEList; ListNames = PDU.RemoteAEListNames; } if (r<*Count) { delete List[r]; delete ListNames[r]; } else r = *Count++; List[r] = new char[strlen(p)+1]; strcpy(List[r], p); ListNames[r] = new char[strlen(q)+1]; strcpy(ListNames[r], q); time_t TimeOfDay; char TimeString[128], buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; FILE *f = fopen(SOPClassFile, "wt"); fprintf(f, "#\n"); fprintf(f, "# DICOM Application / sop / transfer UID list.\n"); fprintf(f, "#\n"); fprintf(f, "# This list is used by the server (CheckedPDU_Service class).\n"); fprintf(f, "# All incoming associations are verified against this file.\n"); fprintf(f, "# File written by %s on: %s\n", SilentText, TimeString); fprintf(f, "#\n"); for (r=0; r<PDU.RemoteAEListCount; r++) fprintf(f, "%-42s %-44s RemoteAe\n", PDU.RemoteAEListNames[r], PDU.RemoteAEList[r]); for (r=0; r<PDU.LocalAEListCount; r++) fprintf(f, "%-42s %-44s LocalAe\n", PDU.LocalAEListNames[r], PDU.LocalAEList[r]); for (r=0; r<PDU.ApplicationUIDListCount; r++) fprintf(f, "%-42s %-44s application\n", PDU.ApplicationUIDListNames[r], PDU.ApplicationUIDList[r]); for (r=0; r<PDU.SOPUIDListCount; r++) fprintf(f, "%-42s %-44s sop\n", PDU.SOPUIDListNames[r], PDU.SOPUIDList[r]); for (r=0; r<PDU.TransferUIDListCount; r++) fprintf(f, "%-42s %-44s transfer\n", PDU.TransferUIDListNames[r], PDU.TransferUIDList[r]); fclose(f); } else if (memcmp(SilentText, "delete_sop:", 11)==0 || memcmp(SilentText, "delete_transfer:", 16)==0 || memcmp(SilentText, "delete_localae:", 15)==0 || memcmp(SilentText, "delete_remoteae:", 16)==0 || memcmp(SilentText, "delete_application:", 19)==0 ) { int r = atoi(strchr(SilentText, ':')+1), i; char **List, **ListNames; unsigned int *Count; if (memcmp(SilentText, "delete_sop:", 11)==0) { Count = &PDU.SOPUIDListCount; List = PDU.SOPUIDList; ListNames = PDU.SOPUIDListNames; } else if (memcmp(SilentText, "delete_transfer:", 16)==0) { Count = &PDU.TransferUIDListCount; List = PDU.TransferUIDList; ListNames = PDU.TransferUIDListNames; } else if (memcmp(SilentText, "delete_application:", 19)==0) { Count = &PDU.ApplicationUIDListCount; List = PDU.ApplicationUIDList; ListNames = PDU.ApplicationUIDListNames; } else if (memcmp(SilentText, "delete_localae:", 15)==0) { Count = &PDU.LocalAEListCount; List = PDU.LocalAEList; ListNames = PDU.LocalAEListNames; } else if (memcmp(SilentText, "delete_remoteae:", 16)==0) { Count = &PDU.RemoteAEListCount; List = PDU.RemoteAEList; ListNames = PDU.RemoteAEListNames; } if (r<*Count) { delete List[r]; delete ListNames[r]; for (i=r+1; i<*Count; i++) { List[i+1] = List[i]; ListNames[i+1] = ListNames[i]; } *Count--; } time_t TimeOfDay; char TimeString[128], buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; FILE *f = fopen(SOPClassFile, "wt"); fprintf(f, "#\n"); fprintf(f, "# DICOM Application / sop / transfer UID list.\n"); fprintf(f, "#\n"); fprintf(f, "# This list is used by the server (CheckedPDU_Service class).\n"); fprintf(f, "# All incoming associations are verified against this file.\n"); fprintf(f, "# File written by %s on: %s\n", SilentText, TimeString); fprintf(f, "#\n"); for (r=0; r<PDU.RemoteAEListCount; r++) fprintf(f, "%-42s %-44s RemoteAe\n", PDU.RemoteAEListNames[r], PDU.RemoteAEList[r]); for (r=0; r<PDU.LocalAEListCount; r++) fprintf(f, "%-42s %-44s LocalAe\n", PDU.LocalAEListNames[r], PDU.LocalAEList[r]); for (r=0; r<PDU.ApplicationUIDListCount; r++) fprintf(f, "%-42s %-44s application\n", PDU.ApplicationUIDListNames[r], PDU.ApplicationUIDList[r]); for (r=0; r<PDU.SOPUIDListCount; r++) fprintf(f, "%-42s %-44s sop\n", PDU.SOPUIDListNames[r], PDU.SOPUIDList[r]); for (r=0; r<PDU.TransferUIDListCount; r++) fprintf(f, "%-42s %-44s transfer\n", PDU.TransferUIDListNames[r], PDU.TransferUIDList[r]); fclose(f); } else if (memcmp(SilentText, "get_transfer:", 13)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+13); if (p==NULL) p = "%s %s"; if (r<PDU.TransferUIDListCount) sprintf(Response, p, PDU.TransferUIDList[r], PDU.TransferUIDListNames[r]); } else if (memcmp(SilentText, "get_application:", 16)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+16); if (p==NULL) p = "%s %s"; if (r<PDU.ApplicationUIDListCount) sprintf(Response, p, PDU.ApplicationUIDList[r], PDU.ApplicationUIDListNames[r]); } else if (memcmp(SilentText, "get_localae:", 12)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+12); if (p==NULL) p = "%s %s"; if (r<PDU.LocalAEListCount) sprintf(Response, p, PDU.LocalAEList[r], PDU.LocalAEListNames[r]); } else if (memcmp(SilentText, "get_remoteae:", 13)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+13); if (p==NULL) p = "%s %s"; if (r<PDU.RemoteAEListCount) sprintf(Response, p, PDU.RemoteAEList[r], PDU.RemoteAEListNames[r]); } else if (memcmp(SilentText, "get_dic:", 8)==0) { if (p) *p++=0; // points after 1st comma int r = atoi(SilentText+8); if (p==NULL) p = "%04x %04x %c%c %s"; if (r<VRType.TypeCodes->GetSize()) { RTCElement *e = &(VRType.TypeCodes->Get(r)); sprintf(Response, p, VRType.TypeCodes->Get(r).Group, VRType.TypeCodes->Get(r).Element, VRType.TypeCodes->Get(r).TypeCode>>8, VRType.TypeCodes->Get(r).TypeCode&255, VRType.TypeCodes->Get(r).Description); } } else if (memcmp(SilentText, "dump_header:", 12)==0) { FILE *f; if (p) *p++=0; // points after 1st comma if (p==NULL || *p==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); } else if (strcmp(p, "cgi")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "Content-type: text/html\n\n<pre>"); } else if (strcmp(p, "pre")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "<pre>"); } else f = fopen(p, "wt"); DICOMDataObject *pDDO = LoadForGUI(SilentText+12); if (pDDO) NonDestructiveDumpDICOMObject(pDDO, f); if (f) fclose(f); delete pDDO; DumpHeaderFromGui++; } else if (memcmp(SilentText, "display_status:", 15)==0) { FILE *f; p = SilentText+15; if (p==NULL || *p==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); } else if (strcmp(p, "cgi")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "Content-type: text/html\n\n<pre>"); } else if (strcmp(p, "pre")==0) { NewTempFile(tempfile, ".txt"); f = fopen(tempfile, "wt"); fprintf(f, "<pre>"); } else f = fopen(p, "wt"); StatusDisplay(f); if (f) fclose(f); } else if (memcmp(SilentText, "forward:", 8)==0) { if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma } TestForward(SilentText+8, p, q); ForwardFromGui++; } else if (memcmp(SilentText, "convert_to_gif:", 15)==0) { int level, window; DICOMDataObject *pDDO; if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) { *q++=0; // points after 2nd comma r = strchr(q, ','); if (r) *r++=0; // points after 3rd comma } } pDDO = LoadForGUI(SilentText+15); if (pDDO) { if (p==NULL) p = "256"; if (atoi(p)==0) p = "32"; if (r==NULL) r = "0/0"; level = atoi(r); r = strchr(r, '/'); if (r==NULL) r = "0"; else r++; window = atoi(r); if (q==NULL || *q==0) { NewTempFile(tempfile, ".gif"); ToGif(pDDO, tempfile, atoi(p), 0, level, window); } else if (strcmp(q, "cgi")==0) { NewTempFile(tempfile, ".gif"); FILE *f = fopen(tempfile, "wb"); fprintf(f, "Content-type: image/gif\n\n"); fclose(f); ToGif(pDDO, tempfile, atoi(p), 1, level, window); } else ToGif(pDDO, q, atoi(p), 0, level, window); ImagesToGifFromGui++; } delete pDDO; } else if (memcmp(SilentText, "convert_to_bmp:", 15)==0) { int level, window; DICOMDataObject *pDDO; if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) { *q++=0; // points after 2nd comma r = strchr(q, ','); if (r) *r++=0; // points after 3rd comma } } pDDO = LoadForGUI(SilentText+15); if (pDDO) { if (p==NULL) p = "256"; if (atoi(p)==0) p = "32"; if (r==NULL) r = "0/0"; level = atoi(r); r = strchr(r, '/'); if (r==NULL) r = "0"; else r++; window = atoi(r); if (q==NULL || *q==0) { NewTempFile(tempfile, ".bmp"); ToBMP(pDDO, tempfile, atoi(p), 0, level, window); } else if (strcmp(q, "cgi")==0) { NewTempFile(tempfile, ".bmp"); FILE *f = fopen(tempfile, "wb"); fprintf(f, "Content-type: image/bmp\n\n"); fclose(f); ToBMP(pDDO, tempfile, atoi(p), 1, level, window); } else ToBMP(pDDO, q, atoi(p), 0, level, window); ImagesToGifFromGui++; } delete pDDO; } else if (memcmp(SilentText, "convert_to_dicom:", 17)==0) { DICOMDataObject *pDDO; if (p) { *p++=0; // points after 1st comma q = strchr(p, ','); if (q) *q++=0; // points after 2nd comma } pDDO = LoadForGUI(SilentText+17); if (pDDO) { if (p==NULL) p = "0"; if (q==NULL) q = "un"; NewTempFile(tempfile, ".dcm"); MaybeDownsize(pDDO, NULL, atoi(p)); recompress(&pDDO, q, "", q[0]=='n' || q[0]=='N'); SaveDICOMDataObject(tempfile, pDDO); ImagesToDicomFromGui++; } delete pDDO; } else if (memcmp(SilentText, "grabimagesfromserver:", 21)==0) { if (p) *p++=0; // points after 1st comma GrabImagesFromServer((unsigned char *)SilentText+21, p, (char *)MYACRNEMA); GrabFromGui++; } else if (memcmp(SilentText, "prefetch:", 9)==0) { PrefetchPatientData((char *)SilentText+9, 0); } else if (memcmp(SilentText, "loadhl7:", 8)==0) { int len = DFileSize(SilentText+8); if (len) { char *p=(char*) malloc(len+1); FILE *f; f = fopen(SilentText+8, "rb"); fread(p, 1, len, f); p[len]=0; fclose(f); ProcessHL7Data(p); free(p); } } else if (memcmp(SilentText, "quit:", 5)==0) { exit(0); } else if (memcmp(SilentText, "checklargestmalloc:", 19)==0) { for(int i=0; i<1000; i++) { char *p = (char *)malloc(i*10*1024*1024); if (p) free(p); else { OperatorConsole.printf("Largest malloc = %d MB\n", i*10); break; } } } } if (tempfile[0]) { int len = DFileSize(tempfile); if (len) { int extra=0; if (memcmp(SilentText, "convert_to_dicom:", 17)==0) extra=27; VR *vr = new VR(0x9999, 0x0401, len+extra, TRUE); // better FILE *f; f = fopen(tempfile, "rb"); if (extra) sprintf((char *)(vr->Data), "Content-type: image/dicom\n\n"); fread((char*)(vr->Data)+extra, 1, len, f); fclose(f); SOPVerification.WriteResponse(&PDU, &DCO, vr); } else SOPVerification.WriteResponse(&PDU, &DCO, NULL); unlink(tempfile); } else if (Response[0]) { VR *vr = new VR(0x9999, 0x0401, strlen(Response), (void *)Response, FALSE); SOPVerification.WriteResponse(&PDU, &DCO, vr); } else SOPVerification.WriteResponse(&PDU, &DCO, NULL); continue; } if(SOPPatientRootQuery.Read (&PDU, &DCO)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Find (PatientRoot) located %d records\n", SOPPatientRootQuery.RecordsFound); #endif C_Find_PatientRoot++; continue; } if(SOPPatientRootRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (PatientRootNKI)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_PatientRootNKI++; continue; } if(SOPPatientRootRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (PatientRoot)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_PatientRoot++; continue; } if(SOPStudyRootQuery.Read (&PDU, &DCO)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Find (StudyRoot) located %d records\n", SOPStudyRootQuery.RecordsFound); #endif C_Find_StudyRoot++; continue; } if(SOPStudyRootRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (StudyRootNKI)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_StudyRootNKI++; continue; } if(SOPStudyRootRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (StudyRoot)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_StudyRoot++; continue; } if(SOPPatientStudyOnlyQuery.Read (&PDU, &DCO)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Find (PatientStudyOnly) located %d records\n", SOPPatientStudyOnlyQuery.RecordsFound); #endif C_Find_PatientStudyOnly++; continue; } if(SOPModalityWorkListQuery.Read (&PDU, &DCO)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Find (Modality Work List) located %d records\n", SOPModalityWorkListQuery.RecordsFound); #endif C_Find_ModalityWorkList++; continue; } if(SOPPatientStudyOnlyRetrieveNKI.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (PatientStudyOnlyNKI)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_PatientStudyOnlyNKI++; continue; } if(SOPPatientStudyOnlyRetrieveGeneric.Read (&PDU, &DCO, (void *)&ratd)) { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("C-Move (PatientStudyOnly)\n"); #endif LogUser("C-Move ", &PDU, &DCO); C_Move_PatientStudyOnly++; continue; } vr = DCO.GetVR(0x0000, 0x0100); if(vr && vr->Data) { #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian val = (* ((UINT16*)vr->Data) ); #else //Big Endian like Apple power pc val = SwitchEndian((UINT16)(* ((UINT16*)vr->Data) )); #endif //BigEndian } else val = 0xffff; if(val==0x0fff) // C-CANCEL = cancel request { #ifdef DEBUG_MODE if (!vrsilent) OperatorConsole.printf("Cancel request (ignored)\n"); #endif continue; } if(PrinterSupport (&PDU, &DCO, PrintData)) { continue; } DICOMDataObject *CommitData = NULL; if(StorageCommitmentSupport (&PDU, &DCO, &CommitData)) { continue; } if (CommitData) { PDU.Close(); OperatorConsole.printf("hi\n"); StorageCommitmentSupport (&PDU, &DCO, &CommitData); break; } //Note: Changed print val to hex, easier to read. OperatorConsole.printf("\n***Client Error: command %4.4x failed **\n", val); OperatorConsole.printf("***Connection Terminated\n"); UnknownRequest++; DebugLevel += 4; NonDestructiveDumpDICOMObject(&DCO); DebugLevel -= 4; PDU.Close(); return ( FALSE ); } // wait for the read ahead thread to end (otherwise ratd would point to nothing) ratd.ForceEnd = TRUE; while (ratd.Busy) Sleep(50); // free memory associated with thread if not already done so if (ratd.Devices) { if (ratd.pDCO) delete ratd.pDCO; ratd.pDCO = NULL; for (int i=0; i<ratd.NumToRead; i++) if (ratd.DDOOutPtr[i]) delete ratd.DDOOutPtr[i]; free(ratd.DDOOutPtr); ratd.DDOOutPtr = NULL; free(ratd.Filenames); ratd.Filenames = NULL; free(ratd.ObjectFiles);ratd.ObjectFiles = NULL; free(ratd.Devices); ratd.Devices = NULL; // 20060405 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov) free(ratd.SOPs); ratd.SOPs = NULL; free(ratd.Series); ratd.Series = NULL; free(ratd.Studies); ratd.Studies = NULL; free(ratd.pats); ratd.pats = NULL; CloseHandle(ratd.Handle); ratd.Handle = NULLHANDLE; } // 20060405 mvh Fix for multiple moves on same assoc (thanks Andrej Savelov) ratd.TimeOut = FALSE; ratd.Busy = FALSE; TimeOfDay2 = time(NULL); TotalTime += TimeOfDay2 - TimeOfDay; if (!vrsilent) { char buf[64]; strcpy(TimeString, ctime_r(&TimeOfDay2, buf)); TimeString[strlen(TimeString)-1] = '\0'; OperatorConsole.printf("UPACS THREAD %d: ENDED AT: %s\n", ThreadNum, TimeString); OperatorConsole.printf("UPACS THREAD %d: TOTAL RUNNING TIME: %d SECONDS\n", ThreadNum, TimeOfDay2 - TimeOfDay); } #ifdef __BORLANDC__ { int i = _heapchk(); if (i<0) OperatorConsole.printf("*** heap error *** : %d", i); } #endif return ( TRUE ); } StorageApp ServerApp; void ConfigDgate(void) { char szRootSC[64]; char szTemp[32]; int i; // allow enable/disable of read ahead thread if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return; if (!GetPrivateProfileString(szRootSC, "EnableReadAheadThread", "1", szTemp, 32, ConfigFile)) return; EnableReadAheadThread = atoi(szTemp); if (!GetPrivateProfileString(szRootSC, "WorkListMode", "0", szTemp, 32, ConfigFile)) return; WorkListMode = atoi(szTemp); // archive compression setting (new); note: returns length of entry; can be zero - is still OK! GetPrivateProfileString(szRootSC, "ArchiveCompression", "", ArchiveCompression, 16, ConfigFile); // compression default empty (same as as is) DroppedFileCompression[0] = 0; IncomingCompression [0] = 0; // still accept obsolete FileCompressMode - 1..4 interpreted as nki compression n1..n4 GetPrivateProfileString(szRootSC, "FileCompressMode", "0", szTemp, 32, ConfigFile); FileCompressMode = atoi(szTemp); if (FileCompressMode) { sprintf(DroppedFileCompression, "n%d", FileCompressMode); sprintf(IncomingCompression, "n%d", FileCompressMode); } // default no change of these settings GetPrivateProfileString(szRootSC, "DroppedFileCompression", DroppedFileCompression, DroppedFileCompression, 16, ConfigFile); GetPrivateProfileString(szRootSC, "IncomingCompression", IncomingCompression, IncomingCompression, 16, ConfigFile); GetPrivateProfileString(szRootSC, "StorageFailedErrorCode", "272", szTemp, 32, ConfigFile); StorageFailedErrorCode = atoi(szTemp); GetPrivateProfileString(szRootSC, "TCPIPTimeOut", "300", szTemp, 32, ConfigFile); TCPIPTimeOut = atoi(szTemp); GetPrivateProfileString(szRootSC, "FailHoldOff", "60", szTemp, 32, ConfigFile); FailHoldOff = atoi(szTemp); GetPrivateProfileString(szRootSC, "RetryDelay", "100", szTemp, 32, ConfigFile); RetryDelay = atoi(szTemp); GetPrivateProfileString(szRootSC, "QueueSize", "128", szTemp, 32, ConfigFile); QueueSize = atoi(szTemp); GetPrivateProfileString(szRootSC, "ForwardCollectDelay", "600", szTemp, 32, ConfigFile); ForwardCollectDelay = atoi(szTemp); for (i=0; i<10; i++) { sprintf(szTemp, "VirtualServerFor%d", i); GetPrivateProfileString(szRootSC, szTemp, "", VirtualServerFor[i], 48, ConfigFile); } GetPrivateProfileString(szRootSC, "CacheVirtualData", "1", szTemp, 32, ConfigFile); CacheVirtualData = atoi(szTemp); GetPrivateProfileString(szRootSC, "PadAEWithZeros", "0", szTemp, 32, ConfigFile); ConfigPadAEWithZeros = atoi(szTemp); } // main as console app or child process static void DgateCgi(char *query_string, char *ext); // forward reference int main ( int argc, char *argv[] ) { char TimeString[128]; time_t TimeOfDay, TimeOfDay2; char szRootSC[64]; char szTemp[32]; int i; BOOL MissingDict=FALSE; char *query_string = getenv( "QUERY_STRING" ); if (query_string && argc==1) { char *ext=strrchr(argv[0], '.'); DgateCgi(query_string, ext); exit(0); } StartTime = time(NULL); SetDicomErrorHandler(MyDcmError); #ifdef UNIX if (strrchr(argv[0], '/')) { strcpy(DicomDict, argv[0]); *strrchr(DicomDict, '/') = 0; strcat(DicomDict, "/dgate.dic"); } #endif if (!VRType.AttachRTC(DicomDict)) { MissingDict = TRUE; printf("File dgate.dic is missing, some server functions will not work correctly\n"); } // allow enable/disable of read ahead thread if (!GetPrivateProfileString(RootConfig, "MicroPACS", RootConfig, szRootSC, 64, ConfigFile)) return 0; ConfigDgate(); #ifdef UNIX // set that pesky broken pipe signal to be ignored // I/O that would have generated a SIGPIPE will return EPIPE instead // this applies to named pipe writes and read/write of sockets signal(SIGPIPE, SIG_IGN); // get ini file from same directory as binary if (strrchr(argv[0], '/')) { strcpy(ConfigFile, argv[0]); *strrchr(ConfigFile, '/') = 0; strcat(ConfigFile, "/dicom.ini"); } #endif int Socketfd; #if defined(DO_LEAK_DETECTION) || defined(DO_VIOLATION_DETECTION) int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); #ifdef DO_LEAK_DETECTION tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF; #endif #ifdef DO_VIOLATION_DETECTION tmpDbgFlag |= _CRTDBG_CHECK_ALWAYS_DF; #endif _CrtSetDbgFlag(tmpDbgFlag); /* If a leak is detected, run again after specifying the serial num of the leak using _CrtSetBreakAlloc(<id>); */ // _CrtSetBreakAlloc(37); #endif if ( ! (Socketfd = ParseArgs(argc, argv) )) { if (RunServer) { struct stat statbuf; char TimeString[100], buf[64]; int iNbConverters; memset((void *)&statbuf, 0, sizeof(statbuf)); // Start queue for export converters (may reprocess previously failed requests) stat(argv[0], &statbuf); strcpy(TimeString, ctime_r(&statbuf.st_mtime, buf)); TimeString[strlen(TimeString)-1] = '\0'; if (!(statbuf.st_mode & S_IFREG)) strcpy(TimeString, "?"); if (NoThread) OperatorConsole.printf("DGATE (%s, build %s) runs in non-threaded debug mode\n", VERSION, TimeString); else OperatorConsole.printf("DGATE (%s, build %s) is running as threaded server\n", VERSION, TimeString); if (MissingDict) OperatorConsole.printf("*** File dgate.dic is missing, some server functions will not work correctly\n"); GetPrivateProfileString(szRootSC, "ExportConverters", "0", szTemp, 32, ConfigFile); iNbConverters = atoi(szTemp); if (iNbConverters>MAXExportConverters) iNbConverters=MAXExportConverters; if (iNbConverters && !NoThread) { eqN = (struct conquest_queue **)malloc(iNbConverters * sizeof(struct conquest_queue *)); memset(eqN, 0, iNbConverters * sizeof(struct conquest_queue *)); for(i=0; i<iNbConverters; i++) export_queueN(&eqN[i], NULL, i, NULL, NULL, NULL, NULL, NULL, NULL); OperatorConsole.printf("Started %d export queue thread(s)\n", iNbConverters); } // Start queue for mirror copy (may reprocess previously failed requests) GetPrivateProfileString(szRootSC, "MIRROR0", "-1", szTemp, 32, ConfigFile); if (atoi(szTemp)!=-1 && !NoThread) { mirrorcopy_queue(NULL, NULL); OperatorConsole.printf("Started mirror copy queue thread\n"); } // Start prefetcher queue GetPrivateProfileString(szRootSC, "Prefetcher", "0", szTemp, 32, ConfigFile); if (atoi(szTemp) && !NoThread) { prefetchermode = atoi(szTemp); prefetcher(NULL, FALSE); OperatorConsole.printf("Started prefetcher queue thread\n"); } if (NoThread) while ( TRUE ) ServerApp.Server(Port); else ServerApp.Server(Port); } return(0); } // run a child from a driver application OperatorConsole.printf("Child: Socketfd = %d\n", Socketfd); // Print Date / Time in Log file char buf[64]; TimeOfDay = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay, buf)); TimeString[strlen(TimeString)-1] = '\0'; OperatorConsole.printf("UPACS: %s: STARTED AT: %s\n", argv[1], TimeString); ServerApp.ServerChild(Socketfd); TimeOfDay2 = time(NULL); strcpy(TimeString, ctime_r(&TimeOfDay2, buf)); TimeString[strlen(TimeString)-1] = '\0'; OperatorConsole.printf("UPACS: %s: ENDED AT: %s\n", argv[1], TimeString); OperatorConsole.printf("UPACS: %s: TOTAL RUNNING TIME: %d SECONDS\n", argv[1], TimeOfDay2 - TimeOfDay ); return ( 0 ); } /////////////////////////////////////////////////////////////////////////////// // grabbing code /////////////////////////////////////////////////////////////////////////////// void SetStringVR(VR **vr, int g, int e, char *String) { int len; char* pCopy; /* NOTE: Uneven length strings must be padded with a space. Uneven length UIDs must be padded with \0. */ len = strlen(String); pCopy = strdup(String); if (len & 1) pCopy[len++] = ' '; *vr = new VR(g, e, len, (void*)pCopy, (BOOL) TRUE); } BOOL GrabImagesFromServer(BYTE *calledae, char *studydate, char *destination) { BOOL quit, quit2; PDU_Service PDU, PDU2; DICOMCommandObject DCO; DICOMCommandObject DCOR, DCOR2; DICOMDataObject DDO; DICOMDataObject DDOR, DDOR2; UID uid, uid2; VR *vr; LE_UINT16 command, datasettype, messageid, priority, tempid; BYTE SOP[66]; unsigned char ip[64], port[64], compress[64]; PDU.AttachRTC(&VRType); PDU2.AttachRTC(&VRType); if(!GetACRNema((char *)calledae, (char *)ip, (char *)port, (char *)compress)) return FALSE; // Start setting up connection for C-FIND PDU.ClearAbstractSyntaxs(); PDU.SetLocalAddress(MYACRNEMA); PDU.SetRemoteAddress(calledae); uid.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU.SetApplicationContext(uid); uid.Set("1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery (C-Find SOP) PDU.AddAbstractSyntax(uid); // idem for the C-MOVE PDU2.ClearAbstractSyntaxs(); PDU2.SetLocalAddress(MYACRNEMA); PDU2.SetRemoteAddress(calledae); uid2.Set("1.2.840.10008.3.1.1.1"); // Application context (DICOM App) PDU2.SetApplicationContext(uid2); uid2.Set("1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootRetrieve (C-Move SOP) PDU2.AddAbstractSyntax(uid2); PDU.SetTimeOut(TCPIPTimeOut); PDU2.SetTimeOut(TCPIPTimeOut); // Make the association for the FIND on port/ip if(!PDU.Connect(ip, port)) { OperatorConsole.printf("*** Grab - failed to connect for C-FIND\n"); return ( FALSE ); } // Make the association for the MOVE on port/ip if(!PDU2.Connect(ip, port)) { PDU.Close(); OperatorConsole.printf("*** Grab - failed to connect for C-MOVE\n"); return(FALSE); } // Start a StudyRootQuery strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.1"); // StudyRootQuery (C-Find SOP) vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); command = EN0020; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); priority = 0; // MEDIUM vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE); DCO.Push(vr); datasettype = EN0102; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); messageid = EN0003; vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE); DCO.Push(vr); // Start of data object. Query level is image; ask for image UIDs and patid SetStringVR(&vr, 0x0008, 0x0052, "IMAGE"); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0020, studydate); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0018, ""); DDO.Push(vr); SetStringVR(&vr, 0x0010, 0x0020, ""); DDO.Push(vr); // Write query command object and data object PDU.Write(&DCO, uid); PDU.Write(&DDO, uid); // Get response quit = 0; while(!quit) { if(!PDU.Read(&DCOR)) { PDU2.Close(); OperatorConsole.printf("*** Grab - association lost in C-FIND\n"); return ( FALSE ); // association lost } // is this a C-Find-RSP ? if(DCOR.GetUINT16(0x0000, 0x0100)!=0x8020) { PDU.Close(); PDU2.Close(); OperatorConsole.printf("*** Grab - wrong response for C-FIND\n"); return(FALSE); } // is there a data set? if(DCOR.GetUINT16(0x0000, 0x0800)==0x0101) { PDU.Close(); PDU2.Close(); OperatorConsole.printf("Grab - finished\n"); return( TRUE ); } // no success if(DCOR.GetUINT16(0x0000, 0x0900)==0x0000) { PDU.Close(); PDU2.Close(); OperatorConsole.printf("*** Grab - C-FIND failed\n"); return ( FALSE ); } // read response data if(!PDU.Read(&DDOR)) { PDU.Close(); PDU2.Close(); OperatorConsole.printf("*** Grab - C-FIND failed\n"); return(FALSE); } while(vr = DCOR.Pop()) delete vr; while(vr = DDOR.Pop()) { if(vr->Group == 0x0000) // error response { PDU.Close(); PDU2.Close(); OperatorConsole.printf("*** Grab - C-FIND error\n"); return ( TRUE ); } // recieving a SOPInstanceUID if (vr->Group == 0x0008 && vr->Element == 0x0018) { char s[255]; memset(s, 0, 255); memcpy(s, vr->Data, vr->Length); // is it on the local server (note: test may be speeded by passing patid) ? if (!TestFilter("", s, 10)) { VR *vr; // move it to the destination if it is not strcpy((char*) SOP, "1.2.840.10008.5.1.4.1.2.2.2"); // StudyRootMove (C-Move SOP) vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); command = EN0021; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); priority = 0; // MEDIUM vr = new VR (0x0000, 0x0700, 0x0002, &priority, FALSE); DCO.Push(vr); datasettype = EN0102; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); messageid++; #if NATIVE_ENDIAN == LITTLE_ENDIAN //Little Endian tempid = messageid; #else //Big Endian like Apple power pc tempid = SwitchEndian((UINT16) messageid); #endif //Big Endian vr = new VR (0x0000, 0x0110, 0x0002, &tempid, FALSE); DCO.Push(vr); vr = new VR(0x0000, 0x0600, 16, (void*)destination, FALSE); DCO.Push(vr); // Data object. Query level is image; ask for date and SopInstanceUID SetStringVR(&vr, 0x0008, 0x0052, "IMAGE"); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0020, studydate); DDO.Push(vr); SetStringVR(&vr, 0x0008, 0x0018, s); DDO.Push(vr); // Write command object and data object PDU2.Write(&DCO, uid2); PDU2.Write(&DDO, uid2); // Get response quit2 = 0; while(!quit2) { if(!PDU2.Read(&DCOR2)) { PDU.Close(); OperatorConsole.printf("*** Grab - C-MOVE association lost\n"); return ( FALSE ); // associate lost } if(DCOR2.GetUINT16(0x0000, 0x0100)!=0x8021) { PDU.Close(); PDU2.Close(); OperatorConsole.printf("*** Grab - C-MOVE got a wrong response\n"); return(FALSE); } // ignore the data set if(DCOR2.GetUINT16(0x0000, 0x0800)!=0x0101) { PDU2.Read(&DDOR2); DDOR2.Reset(); } if(DCOR2.GetUINT16(0x0000, 0x0900)==0x0000) // success ? { OperatorConsole.printf("Grabbed %s\n", s); quit2=1; } else if (DCOR2.GetUINT16(0x0000, 0x0900)==0xff00) // continuing no problem { } else { UINT16 RemoteError = DCOR2.GetUINT16(0x0000, 0x0900); // mvh 20051208 OperatorConsole.printf("*** Grab - remote C-MOVE DICOM Error code %x (%d)\n", RemoteError, RemoteError); PDU.Close(); PDU2.Close(); return ( FALSE ); } DCOR2.Reset(); } } } delete vr; } } PDU.Close(); PDU2.Close(); return ( TRUE ); } ///////////////////////////////////////////////////////////////////////////////////////////// // Used to send commands (e.g, from linux gui to be developed) to running server without reindexing ///////////////////////////////////////////////////////////////////////////////////////////// int processhtml(char *out, char *in, int len) { int i, outlen=0, instring=0; for (i=0; i<len; i++) { if (i>3 && in[i-3]=='<' && in[i-2]=='A' && instring==0) instring=1; if (in[i]=='>' && instring==1) instring=0; if (in[i]==' ' && instring) { out[outlen++] = '%'; out[outlen++] = '2'; out[outlen++] = '0'; } else out[outlen++] = in[i]; } return outlen; } static char ServerCommandAddress[64] = "127.0.0.1"; static BOOL SendServerCommand(char *NKIcommand1, char *NKIcommand2, int con, char *buf, BOOL html) { PDU_Service PDU; DICOMCommandObject DCO; DICOMCommandObject DCOR; UID uid; VR *vr; LE_UINT16 tuint16, command, datasettype, messageid; BYTE SOP[64]; if (buf) *buf=0; PDU.ClearAbstractSyntaxs(); PDU.SetLocalAddress(MYACRNEMA); PDU.SetRemoteAddress(MYACRNEMA); uid.Set("1.2.840.10008.3.1.1.1"); // Dicom APP PDU.SetApplicationContext(uid); uid.Set("1.2.840.10008.1.1"); // Verification PDU.AddAbstractSyntax(uid); if(!PDU.Connect((unsigned char *)ServerCommandAddress, Port)) return ( FALSE ); strcpy((char*) SOP, "1.2.840.10008.1.1"); // Verification vr = new VR (0x0000, 0x0002, strlen((char*)SOP), (void*) SOP, FALSE); DCO.Push(vr); if (strlen(NKIcommand1)) { vr = new VR (0x9999, 0x0300, strlen((char*)NKIcommand1), (void*)NKIcommand1, FALSE); DCO.Push(vr); } if (strlen(NKIcommand2)) { vr = new VR (0x9999, 0x0400, strlen((char*)NKIcommand2), (void*)NKIcommand2, FALSE); DCO.Push(vr); } command = EN0030; vr = new VR (0x0000, 0x0100, 0x0002, &command, FALSE); DCO.Push(vr); datasettype = 0x0101; vr = new VR (0x0000, 0x0800, 0x0002, &datasettype, FALSE); DCO.Push(vr); messageid = EN0001; vr = new VR (0x0000, 0x0110, 0x0002, &messageid, FALSE); DCO.Push(vr); PDU.Write(&DCO, uid); if(!PDU.Read(&DCOR)) return ( FALSE ); // associate lost while(vr = DCOR.Pop()) { if (vr->Group == 0x9999 && vr->Element == 0x0401) { if (buf) { int len; if (html) len = processhtml(buf, (char *)vr->Data, vr->Length); else memcpy(buf, vr->Data, len = vr->Length); buf[len]=0; if (len>1 && buf[len-1]==' ') buf[len-1]=0; } else { if (con==0) { con = fileno(stdout); #ifdef WIN32 setmode(con, O_BINARY); #endif } if (html) { char *buf = (char *)malloc(1000000); int len = processhtml(buf, (char *)vr->Data, vr->Length); write(con, buf, len); free(buf); } else write(con, vr->Data, vr->Length); } } delete vr; } PDU.Close(); return ( TRUE ); } ///////////////////////////////////////////////////////////////////////////////////////////// // Elementary web interface ///////////////////////////////////////////////////////////////////////////////////////////// static int isxdig(char ch) { if ((ch>='0' && ch<='9') || (ch>='A' && ch<='F') || (ch>='a' && ch<='f')) return 1; else return 0; } static int xdigit(char ch) { if (ch>='0' && ch<='9') return ch - '0'; else return (ch & 15) + 9; } static int htoin(char *value, int len) { int i, result; result = 0; i = 0; while (i < len && value[i] == ' ') i++; while (i < len && isxdig(value[i])) { result = result * 16 + xdigit(value[i]); i++; } return result; } static int CGI(char *out, char *name, char *def) { char *p = getenv( "QUERY_STRING" ); char tmp[512]; char *q; int i, j; if (out!=def) *out = 0; if (p==NULL) return 0; strcpy(tmp, "&"); // & only hits on second item strcat(tmp, name); strcat(tmp, "="); q = strstr(p, tmp); if (q==NULL) // check first item if (memcmp(p, tmp+1, strlen(tmp+1))==0) q=p-1; if (q==NULL) { if (out!=def) strcpy(out, def); return 0; } q = q + strlen(tmp); i = 0; j = 0; while (q[i] != 0 && q[i] != '&') { if (q[i] == '%') { tmp[j++] = (char)(htoin(q+i+1, 2)); i = i+3; } else if (q[i] == '+') { tmp[j++] = ' '; i++; } else tmp[j++] = q[i++]; } tmp[j++] = 0; strcpy(out, tmp); return 0; } int console; static void HTML(char *string, ...) { char n[2]="\n"; char s[1250]; va_list vargs; va_start(vargs, string); vsprintf(s, string, vargs); va_end(vargs); write(console, s, strlen(s)); write(console, n, 1); } static BOOL Tabulate(char *c1, char *par, char *c4, BOOL edit=FALSE) { char *p=strchr(par, ':'); char buf[512]; SendServerCommand("", par, 0, buf); if (buf[0]) { if (edit) HTML("<TR><TD>%s<TD>%s<TD><INPUT SIZE=64 NAME=\"%s\" VALUE=\"%s\"><TD>%s<TD></TR>", c1, p+1, p+1, buf, c4, p+1); else HTML("<TR><TD>%s<TD>%s<TD>%s<TD>%s<TD></TR>", c1, p+1, buf, c4, p+1); return TRUE; } else return FALSE; } static void replace(char *string, char *key, char *value) { char temp[1000]; char *p = strstr(string, key), *q = string; if (p==NULL) return; if (value==NULL) return; temp[0] = 0; while(p) { *p = 0; strcat(temp, string); *p = key[0]; strcat(temp, value); string = p + strlen(key); p = strstr(string, key); }; strcat(temp, string); strcpy(q, temp); } static void DgateCgi(char *query_string, char *ext) { char mode[512], command[8192], size[32], dsize[32], iconsize[32], slice[512], slice2[512], query[512], buf[512], patientidmatch[512], patientnamematch[512], studydatematch[512], startdatematch[512], db[256], series[512], study[512], compress[64], WebScriptAddress[256], WebMAG0Address[256], WebServerFor[64], WebCodeBase[512], lw[64], source[64], dest[64], series2[512], study2[512]; char ex[128], extra[256], graphic[32], viewer[128]; int i, j; DBENTRY *DBE; char RootSC[64]; char Temp[128]; char *p; BOOL ReadOnly=FALSE; console = fileno(stdout); #ifdef WIN32 strcpy(ex, ".exe"); if (ext) strcpy(ex, ext); setmode(console, O_BINARY); #else ex[0]=0; if (ext) strcpy(ex, ext); #endif ConfigMicroPACS(); LoadKFactorFile((char*)KFACTORFILE); GetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig, RootSC, 64, ConfigFile); GetPrivateProfileString ( RootSC, "WEBReadOnly", "1", Temp, 64, ConfigFile); ReadOnly = atoi(Temp); sprintf(WebScriptAddress, "http://%s/cgi-bin/dgate%s", getenv("SERVER_NAME"), ex); GetPrivateProfileString ( RootSC, "WEBScriptAddress", WebScriptAddress, WebScriptAddress, 256, ConfigFile); sprintf(WebMAG0Address, "http://%s/mag0", getenv("SERVER_NAME"), ex); GetPrivateProfileString ( RootSC, "WEBMAG0Address", WebMAG0Address, WebMAG0Address, 256, ConfigFile); sprintf(WebServerFor, "127.0.0.1"); GetPrivateProfileString ( RootSC, "WebServerFor", WebServerFor, WebServerFor, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "address", WebServerFor, WebServerFor, 256, ConfigFile); strcpy(ServerCommandAddress, WebServerFor); strcpy(WebCodeBase, WebScriptAddress); // note: WebCodeBase should include trailing slash or backslash p = strrchr(WebCodeBase, '/'); if (p) p[0]=0; p = strrchr(WebCodeBase, '/'); if (p) p[1]=0; GetPrivateProfileString ( RootSC, "WebCodeBase", WebCodeBase, (char*)WebCodeBase, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "port", (char *)Port, (char*)Port, 256, ConfigFile); CGI((char *)Port, "port", (char *)Port); // allow serving any server CGI(ServerCommandAddress, "address", ServerCommandAddress); CGI(query, "query", ""); // query for most db selectors CGI(slice2, "slice", ""); // patid:sop for slice CGI(series2, "series", ""); // patid:seriesuid for seriesviewer/move/delete CGI(study2, "study", ""); // patid:studyuid for move/delete CGI(mode, "mode", ""); // web page CGI(db, "db", ""); // database to edit or list CGI(lw, "lw", "0/0"); // level/window CGI(source, "source", "(local)"); // source for move CGI(dest, "dest", ""); // destination for move j = 0; for(i=0; i<strlen(slice2); i++) if (slice2[i]==' ') { slice[j++]='%'; slice[j++]='2'; slice[j++]='0'; } else slice[j++]=slice2[i]; slice[j++]=0; j = 0; for(i=0; i<strlen(series2); i++) if (series2[i]==' ') { series[j++]='%'; series[j++]='2'; series[j++]='0'; } else series[j++]=series2[i]; series[j++]=0; j = 0; for(i=0; i<strlen(study2); i++) if (study2[i]==' ') { study[j++]='%'; study[j++]='2'; study[j++]='0'; } else study[j++]=study2[i]; study[j++]=0; GetPrivateProfileString ( "webdefaults", "size", "512", size, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "dsize", "0", dsize, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "compress", "n4", compress, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "iconsize", "48", iconsize, 256, ConfigFile); GetPrivateProfileString ( "webdefaults", "graphic", "bmp", graphic, 32, ConfigFile); GetPrivateProfileString ( "webdefaults", "viewer", "seriesviewer", viewer, 128, ConfigFile); CGI(size, "size", size); // size of viewer in pixels CGI(dsize, "dsize", dsize); // max size of transmitted dicom images in pixels, 0=original CGI(compress,"compress", compress); // compression of transmitted dicom images to (our) web viewer CGI(iconsize,"iconsize", iconsize); // size of icons in image table CGI(graphic, "graphic", graphic); // style of transmitting thumbnails and slices (gif or bmp) CGI(viewer, "viewer", viewer); // mode of used viewer CGI(patientidmatch, "patientidmatch", ""); // search strings CGI(patientnamematch, "patientnamematch", ""); CGI(studydatematch, "studydatematch", ""); CGI(startdatematch, "startdatematch", ""); sprintf(extra, "port=%s&address=%s", Port, ServerCommandAddress); if (patientidmatch[0]!=0) { if (query[0]) strcat(query, " and "); strcat(query, "PatientID like '%"); strcat(query, patientidmatch); strcat(query, "%'"); }; if (patientnamematch[0]!=0) { if (query[0]) strcat(query, " and "); strcat(query, "PatientNam like '%"); strcat(query, patientnamematch); strcat(query, "%'"); }; if (studydatematch[0]!=0) { if (query[0]) strcat(query, " and "); strcat(query, "StudyDate like '%"); strcat(query, studydatematch); strcat(query, "%'"); }; if (startdatematch[0]!=0) { if (query[0]) strcat(query, " and "); strcat(query, "StartDate like '%"); strcat(query, startdatematch); strcat(query, "%'"); }; if (stricmp(db, "dicomworklist")==0) DBE=WorkListDB; else if (stricmp(db, "dicompatients")==0) DBE=PatientDB; else if (stricmp(db, "dicomstudies" )==0) DBE=StudyDB; else if (stricmp(db, "dicomseries" )==0) DBE=SeriesDB; else if (stricmp(db, "dicomimages" )==0) DBE=ImageDB; else DBE=WorkListDB; /************************** top page **************************/ if (strcmp(mode, "")==0 || strcmp(mode, "top")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<IMG SRC='%sconquest.jpg' ALT='Developed in the Conquest project'>", WebCodeBase); HTML("<HR>"); HTML("<PRE>"); SendServerCommand("", "display_status:", console); HTML("</PRE>"); HTML("<HR>"); HTML("<table>"); HTML("<tr>"); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=querypatients>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<td>List local patients"); HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>"); HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>"); HTML("<td>"); HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>"); HTML("</FORM>"); HTML("</tr>"); HTML("<tr>"); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=querystudies>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<td>List local studies"); HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>"); HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>"); HTML("<td>Date: <INPUT NAME=studydatematch TYPE=Text VALUE=>"); HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>"); HTML("</FORM>"); HTML("</tr>"); HTML("<tr>"); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=queryworklist>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<td>List local worklist"); HTML("<td>Patient ID: <INPUT NAME=patientidmatch TYPE=Text VALUE=>"); HTML("<td>Name: <INPUT NAME=patientnamematch TYPE=Text VALUE=>"); HTML("<td>Date: <INPUT NAME=startdatematch TYPE=Text VALUE=>"); HTML("<td><INPUT TYPE=SUBMIT VALUE=Go>"); HTML("</FORM>"); HTML("</tr>"); HTML("<tr>"); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<td>Find "); HTML("<select name=mode>"); HTML(" <option value='patientfinder'>Patient</option>"); HTML(" <option value='studyfinder'>Study</option>"); HTML(" <option value='seriesfinder'>Series</option>"); HTML("</select>"); HTML("<td>on server"); HTML("<select name=dest>"); SendServerCommand("", "get_amaps:<option value='%s'>%0.0s%0.0s%0.0s%s</option>", console); HTML("</select>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<INPUT NAME=source TYPE=HIDDEN VALUE=%s>", source); HTML("<INPUT NAME=dest TYPE=HIDDEN VALUE=%s>", dest); HTML("<td>Search: <INPUT NAME=query TYPE=Text VALUE=>"); HTML("<td><td><INPUT TYPE=SUBMIT VALUE=Go>"); HTML("</FORM>"); HTML("</tr>"); HTML("</table>"); HTML("<HR>"); HTML("<BR><A HREF=\"dgate%s?%s&mode=showconfig\">Show server configuration</A>", ex, extra); HTML("<BR><A HREF=\"dgate%s?%s&mode=showsops\">Show server accepted SOPs</A>", ex, extra); HTML("<BR><A HREF=\"dgate%s?%s&mode=showdb\">Show database layout</A>", ex, extra); HTML("<BR><A HREF=\"dgate%s?%s&mode=showdictionary\">Show DICOM dictionary (Long!)</A>", ex, extra); HTML("</BODY>"); exit(0); }; /************************** configuration **************************/ if (strcmp(mode, "showconfig")==0) { ReadOnly = TRUE; HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<FORM ACTION=\"dgate%s\">", ex); if (!ReadOnly) HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=updateconfig>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<HR>"); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of configuration parameters</caption>"); HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>"); Tabulate("dicom.ini", "get_param:MyACRNema", "DICOM name of server", !ReadOnly); Tabulate("dicom.ini", "get_param:TCPPort", "TCP/IP port where server listens", !ReadOnly); Tabulate("dicom.ini", "get_param:FileNameSyntax", "Determines name for new files", !ReadOnly); Tabulate("dicom.ini", "get_param:FixPhilips", "Strip leading zeros from 10 digit patient ID", !ReadOnly); Tabulate("dicom.ini", "get_param:FixKodak", "Strip leading zeros from 8 digit patient ID", !ReadOnly); Tabulate("dicom.ini", "get_param:IncomingCompression", "Compression mode for incoming files", !ReadOnly); Tabulate("dicom.ini", "get_param:ArchiveCompression", "Compression mode for acrhived files", !ReadOnly); Tabulate("dicom.ini", "get_param:MAGDevices", "Number of storage devices", !ReadOnly); for (i=0; i<100; i++) { sprintf(command, "get_param:MAGDevice%d", i); if (!Tabulate("dicom.ini", command, "Directory where data is stored", !ReadOnly)) break; } HTML("<TR></TR>"); for (i=0; i<1000; i++) { sprintf(command, "get_amap:%d", i); if (!Tabulate("acrnema.map", command, "Known DICOM provider")) break; } HTML("</table>"); if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Update>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "showsops")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<HR>"); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of uids</caption>"); HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>"); for (i=0; i<1000; i++) { sprintf(command, "get_sop:%d", i); if (!Tabulate("dgatesop.lst", command, "Accepted SOP class uid")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_transfer:%d", i); if (!Tabulate("dgatesop.lst", command, "Accepted transfer syntax ")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_application:%d", i); if (!Tabulate("dgatesop.lst", command, "Accepted application uid")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_localae:%d", i); if (!Tabulate("dgatesop.lst", command, "Accepted called AE title")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_remotea:%d", i); if (!Tabulate("dgatesop.lst", command, "Accepted calling AE title")) break; } HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "showdb")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<HR>"); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of configuration parameters</caption>"); HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>"); for (i=0; i<1000; i++) { sprintf(command, "get_sqldef:PATIENT,%d", i); if (!Tabulate("dicom.sql", command, "Patient database field definition")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_sqldef:STUDY,%d", i); if (!Tabulate("dicom.sql", command, "Study database field definition")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_sqldef:SERIES,%d", i); if (!Tabulate("dicom.sql", command, "Series database field definition")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_sqldef:IMAGE,%d", i); if (!Tabulate("dicom.sql", command, "Image database field definition")) break; } for (i=0; i<1000; i++) { sprintf(command, "get_sqldef:WORKLIST,%d", i); if (!Tabulate("dicom.sql", command, "Worklist database field definition")) break; } HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "showdictionary")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<HR>"); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of configuration parameters</caption>"); HTML("<TR><TD>File<TD>Parameter<TD>Value<TD>Description</TR>"); for (i=0; i<9000; i++) { sprintf(command, "get_dic:%d", i); if (!Tabulate("dgate.dic", command, "Dictionary item")) break; } HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "updateconfig")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H1>Welcome to the Conquest DICOM server - version %s</H1>", VERSION); HTML("<HR>"); if (!ReadOnly) HTML("Updating the configuration through the WEB interface is not yet supported"); else HTML("Updating the configuration through the WEB interface is not allowed"); HTML("</BODY>"); exit(0); }; /************************** local browsers **************************/ if (strcmp(mode, "querypatients")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected patients on local server</caption>"); else HTML("<Caption>List of all patients on local server</caption>"); HTML("<TR><TD>Patient ID<TD>Name<TD>Sex<TD>Birth date</TR>"); strcpy(command, "query:DICOMPatients|patientid,patientnam,patientsex,patientbir|"); strcpy(command+strlen(command), query); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=querystudies&query=patientid+=+'%%s'>%%0.0s %%0.0s %%0.0s", ex, extra); strcpy(command+strlen(command), "%s</A><TD>%s<TD>%s<TD>%s</TR>"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "querystudies")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected studies on local server</caption>"); else HTML("<Caption>List of all studies on local server</caption>"); HTML("<TR><TD>Patient ID<TD>Name<TD>Study date<TD>Study description<TD>Study modality</TR>"); strcpy(command, "query:DICOMStudies|patientid,studyinsta,patientnam,studydate,studydescr,studymodal|"); strcpy(command+strlen(command), query); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=queryseries&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.studyinsta+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra); strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studymover&study=%%s:%%s&source=%s>push%%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source); if (!ReadOnly) sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studydeleter&study=%%s:%%s>delete%%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra); strcpy(command+strlen(command), "</TR>"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "queryseries")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of series on local server</caption>"); HTML("<TR><TD>Patient ID<TD>Name<TD>Series date<TD>Series time<TD>Series description<TD>Modality</TR>"); strcpy(command, "query:DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMSeries.seriesinst,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMSeries.seriestime,DICOMSeries.seriesdesc,DICOMSeries.modality|"); strcpy(command+strlen(command), query); strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta"); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=queryallimages&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.seriesinst+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%s %%0.0s</A>", ex, extra); strcpy(command+strlen(command), "<TD>%s<TD>%s<TD>%s<TD>%s<TD>%s"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=queryimages&query=DICOMStudies.patientid+=+'%%s'+and+DICOMSeries.seriesinst+=+'%%s'&size=%s>thumbs%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, size); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=%s&series=%%s:%%s&size=%s>view%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, viewer, size); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesmover&series=%%s:%%s&source=%s>push%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra, source); if (!ReadOnly) sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesdeleter&series=%%s:%%s>delete%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s</A>", ex, extra); strcpy(command+strlen(command), "</TR>"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "queryimages")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of images with thumbnails on local server (maximal 50)</caption>"); HTML("<TR><TD>Patient ID<TD>Name<TD>Date<TD>Image number<TD>Slice location<TD>Icon</TR>"); strcpy(command, "query2:DICOMImages,DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMImages.sopinstanc,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMImages.imagenumbe,DICOMImages.slicelocat|"); strcpy(command+strlen(command), query); strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta and DICOMSeries.seriesinst=DICOMImages.seriesinst"); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=sliceviewer&slice=%%s:%%s&size=%s&graphic=%s>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra, size, graphic); strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=headerdump&slice=%%s:%%s %%0.0s %%0.0s %%0.0s %%0.0s>", ex, extra); sprintf(command+strlen(command), "<IMG SRC=dgate%s?%s&mode=slice&slice=%%s:%%s&size=%s&graphic=%s></A></TR>", ex, extra, iconsize, graphic); strcpy(command+strlen(command), "|50"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "queryallimages")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>List of images on local server (all)</caption>"); HTML("<TR><TD>Patient ID<TD>Name<TD>Date<TD>Image number<TD>Slice location<TD>Header</TR>"); strcpy(command, "query:DICOMImages,DICOMSeries,DICOMStudies|DICOMStudies.patientid,DICOMImages.sopinstanc,DICOMStudies.patientnam,DICOMSeries.seriesdate,DICOMImages.imagenumbe,DICOMImages.slicelocat|"); strcpy(command+strlen(command), query); strcpy(command+strlen(command), " and DICOMStudies.studyinsta=DICOMSeries.studyinsta and DICOMSeries.seriesinst=DICOMImages.seriesinst"); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=sliceviewer&slice=%%s:%%s&size=%s&graphic=%s>%%0.0s %%0.0s %%0.0s %%0.0s", ex, extra, size, graphic); strcpy(command+strlen(command), "%s</A><TD>%0.0s %s<TD>%s<TD>%s<TD>%s"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=headerdump&slice=%%s:%%s %%0.0s %%0.0s %%0.0s %%0.0s>", ex, extra); strcpy(command+strlen(command), "*</A></TR>"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; /************************** remote query **************************/ if (strcmp(mode, "patientfinder")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected patients on %s</caption>", dest); else HTML("<Caption>List of all patients on %s</caption>", dest); HTML("<TR><TD>ID<TD>Name</TR>"); sprintf(command, "patientfinder:%s|%s", dest, query); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=studyfinder&dest=%s&query==%%0.0s%%s>", ex, extra, dest); strcpy(command+strlen(command), "%0.0s%s</A><TD>%s"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "studyfinder")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected studies on %s</caption>", dest); else HTML("<Caption>List of all studies on %s</caption>", dest); HTML("<TR><TD>Date<TD>Modality<TD>Name<TD>Id<TD>UID</TR>"); sprintf(command, "studyfinder:%s|%s", dest, query); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=seriesfinder&dest=%s&query==%%0.0s%%0.0s%%0.0s%%0.0s%%s>", ex, extra, dest); strcpy(command+strlen(command), "%s</A><TD>%s<TD>%s<TD>%s<TD>%s"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=studymover&study=%%0.0s%%0.0s%%0.0s%%s:%%s&source=%s>push</A>", ex, extra, dest); strcpy(command+strlen(command), "</TR>"); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "seriesfinder")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected series on %s</caption>", dest); else HTML("<Caption>List of all series on %s</caption>", dest); HTML("<TR><TD>Date<TD>Time<TD>Modality<TD>Name<TD>ID<TD>UID</TR>"); sprintf(command, "seriesfinder:%s|%s", dest, query); strcpy(command+strlen(command), "|<TR><TD>%s<TD>%s<TD>%s<TD>%s<TD>%s%0.0s<TD>%s</TR>"); sprintf(command+strlen(command), "<TD><A HREF=dgate%s?%s&mode=seriesmover&series=%%0.0s%%0.0s%%0.0s%%0.0s%%s:%%0.0s%%s&source=%s>push</A>", ex, extra, dest); SendServerCommand("", command, console); HTML("</table>"); HTML("</BODY>"); exit(0); }; /* unused */ if (strcmp(mode, "dicomfind")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("Find "); HTML("<select name=mode>"); HTML(" <option value='patientfinder'>Patient</option>"); HTML(" <option value='studyfinder'>Study</option>"); HTML(" <option value='seriesfinder'>Series</option>"); HTML("</select>"); HTML("on server"); HTML("<select name=dest>"); SendServerCommand("", "get_amaps:<option value='%s'>%0.0s%0.0s%0.0s%s</option>", console); HTML("</select>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<INPUT NAME=source TYPE=HIDDEN VALUE=%s>", source); HTML("<INPUT NAME=dest TYPE=HIDDEN VALUE=%s>", dest); HTML("Search: <INPUT NAME=query TYPE=Text VALUE=>"); HTML("<INPUT TYPE=SUBMIT VALUE=Go>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; /************************** movers **************************/ if (strcmp(mode, "studymover")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>Send study: %s</caption>", study2); HTML("<TR><TD>Source<TD>Destination</TR>"); for (i=0; i<1000; i++) { char com[80], buf[80]; sprintf(com, "get_amap:%d,%%s", i); SendServerCommand("", com, 0, buf); if (buf[0]==0) break; if (strchr(buf, '*')==NULL) { sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=movestudy&study=%s&source=%s&dest=%s>%s</A></TR>", source, ex, extra, study, source, buf, buf); HTML("%s", command); } } HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "seriesmover")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); HTML("<Caption>Send series: %s</caption>", series2); HTML("<TR><TD>Source<TD>Destination</TR>"); for (i=0; i<1000; i++) { char com[80], buf[80]; sprintf(com, "get_amap:%d,%%s", i); SendServerCommand("", com, 0, buf); if (buf[0]==0) break; if (strchr(buf, '*')==NULL) { sprintf(command, "<TR><TD>%s<TD><A HREF=dgate%s?%s&mode=moveseries&series=%s&source=%s&dest=%s>%s</A></TR>", source, ex, extra, series, source, buf, buf); HTML("%s", command); } } HTML("</table>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "movestudy")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); sprintf(command, "movestudy:%s,%s,%s", source, dest, study2); SendServerCommand("", command, 0, buf); HTML("%s", command); HTML("<BR>"); HTML("Done %s", study2); HTML("</BODY>"); exit(0); } if (strcmp(mode, "moveseries")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); sprintf(command, "moveseries:%s,%s,%s", source, dest, series2); SendServerCommand("", command, 0, buf); HTML("%s", command); HTML("<BR>"); HTML("Done %s", series2); HTML("</BODY>"); exit(0); } /************************** delete **************************/ if (!ReadOnly) { if (strcmp(mode, "studydeleter")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<Caption>Delete study: %s</caption>", study); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=deletestudy>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<INPUT NAME=study TYPE=HIDDEN VALUE='%s'>", study); HTML("<INPUT TYPE=SUBMIT VALUE='Delete the study'>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "seriesdeleter")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<Caption>Delete series: %s</caption>", series); HTML("<FORM ACTION=\"dgate%s\">", ex); HTML("<INPUT NAME=mode TYPE=HIDDEN VALUE=deleteseries>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<INPUT NAME=series TYPE=HIDDEN VALUE='%s'>", series); HTML("<INPUT TYPE=SUBMIT VALUE='Delete the series'>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "deletestudy")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); sprintf(command, "deletestudy:%s", study2); SendServerCommand("", command, 0, buf); HTML(command); HTML("<BR>"); HTML("Done"); HTML("</BODY>"); exit(0); } if (strcmp(mode, "deleteseries")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); sprintf(command, "deleteseries:%s", series2); SendServerCommand("", command, 0, buf); HTML(command); HTML("<BR>"); HTML("Done"); HTML("</BODY>"); exit(0); } } /************************** worklist browser and editor **************************/ if (strcmp(mode, "queryworklist")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<table RULES=ALL BORDER=1>"); if (query[0]) HTML("<Caption>List of selected worklist entries</caption>"); else HTML("<Caption>List of all worklist entries (not all fields displayed)</caption>"); HTML("<TR><TD>AccessionN<TD>Patient ID<TD>Name<TD>Birth date<TD>Sex<TD>Physician<TD>Description<TD>Modality<TD>Date<TD>Time</TR>"); strcpy(command, "query:dicomworklist|AccessionN,PatientID,PatientNam,PatientBir,PatientSex,ReqPhysici,ReqProcDes,Modality,StartDate,StartTime|"); strcpy(command+strlen(command), query); sprintf(command+strlen(command), "|<TR><TD><A HREF=dgate%s?%s&mode=editrecord&db=dicomworklist&query=AccessionN+=+'%%s'>%%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s %%0.0s", ex, extra); sprintf(command+strlen(command), "%%s</A><TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD>%%s<TD><A HREF=dgate%s?%s&mode=deleterecord&db=dicomworklist&query=AccessionN+=+'%%s'>Delete</A></TR>", ex, extra); SendServerCommand("", command, console); HTML("</table>"); sprintf(command, "<A HREF=dgate%s?%s&mode=addrecord&db=dicomworklist>Add worklist entry</A>", ex, extra); HTML(command); HTML("</BODY>"); exit(0); }; /************************** general purpose database editing **************************/ if (strcmp(mode, "editrecord")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); if (!DBE) { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>"); exit(0); } HTML("<FORM ACTION=\"dgate%s\">", ex); if (!ReadOnly) HTML("<INPUT TYPE=HIDDEN NAME=mode VALUE=saverecord>"); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<INPUT NAME=db TYPE=HIDDEN VALUE=%s>", db); HTML("<INPUT NAME=query TYPE=HIDDEN VALUE=%s>", query); HTML("<table RULES=ALL BORDER=2>"); HTML("<Caption>Edit %s entry</caption>", db); HTML("<TR><TD>Field<TD>Value</TR>"); strcpy(command, "query2:"); strcat(command, db); strcat(command, "|"); i = 0; while ( TRUE ) { if(!DBE[i].Element) break; // end of fields if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE) { strcat(command, DBE[i].SQLColumn); strcat(command, ","); } ++i; } command[strlen(command)-1]=0; // remove trailing , strcat(command, "|"); strcat(command, query); strcat(command, "|"); i = 0; while ( TRUE ) { if(!DBE[i].Element) break; // end of fields if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE) { strcat(command, "<TR><TD>"); strcat(command, DBE[i].SQLColumn); strcat(command, "<TD><INPUT NAME="); strcat(command, DBE[i].SQLColumn); strcat(command, " TYPE=Text VALUE='%s'></TR>"); } ++i; }; strcat(command, "|1"); // max 1 record !!!!! SendServerCommand("", command, console); HTML("</table>"); if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Save>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "addrecord")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); if (!DBE) { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>"); exit(0); } HTML("<FORM ACTION=\"dgate%s\">", ex); if (!ReadOnly) HTML("<INPUT TYPE=HIDDEN NAME=mode VALUE=saverecord>"); HTML("<INPUT NAME=db TYPE=HIDDEN VALUE=%s>", db); HTML("<INPUT NAME=port TYPE=HIDDEN VALUE=%s>", (char *)Port); HTML("<INPUT NAME=address TYPE=HIDDEN VALUE=%s>", ServerCommandAddress); HTML("<table RULES=ALL BORDER=2>"); sprintf(command, "<Caption>Add %s entry</caption>", db); HTML(command); HTML("<TR><TD>Field<TD>Value</TR>"); i = 0; while ( TRUE ) { if(!DBE[i].Element) break; // end of fields if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE) { strcpy(command, "<TR><TD>"); strcat(command, DBE[i].SQLColumn); strcat(command, "<TD><INPUT NAME="); strcat(command, DBE[i].SQLColumn); strcat(command, " TYPE=Text VALUE=''></TR>"); HTML(command); } ++i; } HTML("</table>"); if (!ReadOnly) HTML("<INPUT TYPE=SUBMIT VALUE=Save>"); HTML("</FORM>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "saverecord")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); if (!DBE) { HTML("<H2>File DICOM.SQL not found - please check configuration</H2>"); exit(0); } if (ReadOnly || DBE!=WorkListDB) { HTML("<H2>This table is readonly</H2>"); exit(0); } if (strlen(query)) { sprintf(command, "deleterecord:%s,%s", db, query); SendServerCommand("", command, console); sprintf(command, "Updated/added %s entry for %s", db, query); HTML(command); } else { sprintf(command, "Added new record in %s", db); HTML(command); }; sprintf(command, "addrecord:%s|", db); i = 0; while ( TRUE ) { if(!DBE[i].Element) break; // end of fields if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE) { strcat(command, DBE[i].SQLColumn); strcat(command, ","); } ++i; } command[strlen(command)-1]=0; // remove trailing , strcat(command, "|"); i = 0; while ( TRUE ) { if(!DBE[i].Element) break; // end of fields if (DBE[i].DICOMType!=DT_STARTSEQUENCE && DBE[i].DICOMType!=DT_ENDSEQUENCE) { strcat(command, "'"); CGI(buf, DBE[i].SQLColumn, ""); strcat(command, buf); strcat(command, "', "); } ++i; } command[strlen(command)-2]=0; // remove trailing , and space SendServerCommand("", command, console); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "deleterecord")==0) { HTML("Content-type: text/html\nCache-Control: no-cache\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); if (ReadOnly || DBE!=WorkListDB) { HTML("<H2>This table is readonly</H2>"); exit(0); } sprintf(command, "deleterecord:%s,%s", db, query); SendServerCommand("", command, console); HTML("Deleted record entry for "); HTML(db); HTML("Where "); HTML(query); HTML("</BODY>"); exit(0); }; /************************** viewers **************************/ /* page with one slice */ if (strcmp(mode, "sliceviewer")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<A HREF=dgate%s?%s&mode=headerdump&slice=%s>", ex, extra, slice); HTML("<IMG SRC=dgate%s?%s&mode=slice&slice=%s&size=%s&graphic=%s&lw=%s>", ex, extra, slice, size, graphic, lw); HTML("</A>"); HTML("</BODY>"); exit(0); }; if (strcmp(mode, "headerdump")==0) { HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<BR>Header dump of DICOM object:<BR>"); HTML("<PRE>"); sprintf(command, "dump_header:%s", slice2); SendServerCommand("", command, console, NULL, FALSE); HTML("</PRE>"); HTML("</BODY>"); exit(0); }; /* just generates the bitmap */ if (strcmp(mode, "slice")==0) { sprintf(command, "convert_to_%s:%s,%s,cgi,%s", graphic, slice2, size, lw); SendServerCommand("", command, console, NULL, FALSE); exit(0); }; /* transmits the image contents in dicom format */ if (strcmp(mode, "dicom")==0) { sprintf(command, "convert_to_dicom:%s,%s,%s", slice2, dsize, compress); SendServerCommand("", command, console, NULL, FALSE); exit(0); }; /* k-pacs viewer in an OCX; internet explorer only */ if (strcmp(mode, "seriesviewer")==0) { char *p; HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<OBJECT"); HTML(" classid=\"clsid:0AA480F2-78EB-4A31-B4C8-F981C5004BBB\""); HTML(" codebase=\"%sActiveFormProj1.ocx\"", WebCodeBase); HTML(" width=%s", size); HTML(" height=%s", size); HTML(" align=center"); HTML(" hspace=0"); HTML(" vspace=0"); HTML(">"); HTML("<PARAM name=DCMFilelist value="); p = strchr(series2, ':'); if (p) *p = '|'; sprintf(command, "imagelister:local|%s|:%s?%s&mode=dicom&slice=%%s:%%s&dsize=%s&compress=%s*", series2, WebScriptAddress, extra, dsize, compress); SendServerCommand("", command, console); HTML(">"); HTML("</OBJECT>"); HTML("</BODY>"); exit(0); }; /* k-pacs viewer in an OCX; internet explorer only; data access through http served image files */ if (strcmp(mode, "seriesviewer2")==0) { char wwwserveraddress[512] = "http://"; strcat(wwwserveraddress, getenv("SERVER_NAME")); HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<OBJECT"); HTML(" classid=\"clsid:0AA480F2-78EB-4A31-B4C8-F981C5004BBB\""); HTML(" codebase=\"%sActiveFormProj1.ocx\"", WebCodeBase); HTML(" width=%s", size); HTML(" height=%s", size); HTML(" align=center"); HTML(" hspace=0"); HTML(" vspace=0"); HTML(">"); HTML("<PARAM name=DCMFilelist value="); char *p = strchr(series2, ':'); if (p) *p = '|'; if (memcmp(wwwserveraddress, "file", 4)==0) sprintf(command, "imagelister:local|%s", series2); else sprintf(command, "imagelister:local|%s|@%s/%%0.0s%%s*", series2, WebMAG0Address); SendServerCommand("", command, console); HTML(">"); HTML("</OBJECT>"); HTML("</BODY>"); exit(0); }; /* no viewer */ if (strcmp(mode, "noviewer")==0) { char *p; HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s</H2>", VERSION); HTML("<HR>"); HTML("<H2>No viewer is installed</H2>"); HTML("</OBJECT>"); HTML("</BODY>"); exit(0); }; /* The Japanese java-based viewer; requires some modifications to work */ if (strcmp(mode, "aiviewer")==0) { char *p; HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s with AiViewer</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s with AiViewer</H2>", VERSION); HTML("<APPLET"); HTML(" CODEBASE = '%sdicomviewer100'", WebCodeBase); HTML(" CODE = 'dicomviewer.Viewer.class'"); HTML(" NAME = 'Viewer.java'"); HTML(" WIDTH = '100%%'"); HTML(" HEIGHT = '90%%'"); HTML(" HSPACE = 0"); HTML(" VSPACE = 0"); HTML(" ALIGN = middle >"); HTML("<PARAM NAME = tmpSize VALUE = 1>"); HTML("<PARAM NAME = NUM VALUE = 0>"); HTML("<PARAM NAME = currentNo VALUE = 0>"); HTML("<PARAM NAME = dicURL VALUE = '%sdicomviewer100/Dicom.dic'>", WebCodeBase); HTML("<PARAM NAME = imgURL0 VALUE = "); p = strchr(series2, ':'); if (p) *p = '|'; sprintf(command, "imagelister:local|%s|:%s?%s&mode=dicom&slice=%%s:%%s&dsize=%s&compress=%s*", series2, WebScriptAddress, extra, dsize, "un"); SendServerCommand("", command, console); HTML(">"); HTML("</APPLET>"); HTML("</BODY>"); exit(0); }; /* very simple jave-script based viewer with server side processing */ if (strcmp(mode, "serversideviewer")==0) { char *p; HTML("Content-type: text/html\n"); HTML("<HEAD><TITLE>Conquest DICOM server - version %s server side viewer</TITLE></HEAD>", VERSION); HTML("<BODY BGCOLOR='CFDFCF'>"); HTML("<H2>Conquest DICOM server - version %s server side viewer</H2>", VERSION); HTML("<SCRIPT language=JavaScript>"); HTML("function load()"); HTML("{ document.images[0].src = 'dgate%s?%s&mode=slice'+", ex, extra); HTML(" '&graphic=' + document.forms[0].graphic.value +"); HTML(" '&slice=' + document.forms[0].slice.value +"); HTML(" '&lw=' + document.forms[0].level.value + '/' + document.forms[0].window.value"); HTML("}"); HTML("</SCRIPT>"); HTML("<IMG SRC=loading.jpg BORDER=0 HEIGHT=%s>", size); HTML("<FORM>"); HTML("Slice: "); HTML(" <select name=slice onchange=load()>"); p = strchr(series2, ':'); if (p) *p = '|'; sprintf(command, "imagelister:local|%s|:<option value=%%s:%%s>%%04d</option>", series2); SendServerCommand("", command, console); HTML(" </select>"); HTML("Level:"); HTML(" <INPUT name=level size=4 onchange=load() >"); HTML("Window:"); HTML(" <INPUT name=window size=4 onchange=load() >"); HTML("Color:"); HTML(" <select name=graphic onchange=load()>"); if (strcmp(graphic, "bmp")==0) { HTML(" <option value=bmp>yes</option>"); HTML(" <option value=gif>no</option>"); } else { HTML(" <option value=gif>no</option>"); HTML(" <option value=bmp>yes</option>"); } HTML(" </select>"); HTML(" <INPUT TYPE=BUTTON VALUE=load onclick=load() >"); HTML("</FORM>"); HTML("<SCRIPT language=JavaScript>"); HTML(" document.onload=load()"); HTML("</SCRIPT>"); HTML("</BODY>"); exit(0); }; /************************** general purpose web scripting **************************/ /* This is a general purpose web script processor; it can be used to create any web page, not just viewers. This is a sample from dicom.ini: [flexviewer] line0 = <HEAD><TITLE>Conquest DICOM server - version %version% and %windowname%</TITLE></HEAD> line1 = <BODY BGCOLOR='CFDFCF'> line2 = <H2>Conquest DICOM server - version %version% and AiViewer v1.00</H2> line3 = <APPLET CODEBASE=%webcodebase%dicomviewer100 CODE='dicomviewer.Viewer.class' line4 = NAME='Viewer.java' WIDTH='100%' HEIGHT='90%' HSPACE=0 VSPACE=0 ALIGN=middle > line5 = <PARAM NAME = tmpSize VALUE = 10> line6 = <PARAM NAME = NUM VALUE = 0> line7 = <PARAM NAME = currentNo VALUE = 0> line8 = <PARAM NAME = dicURL VALUE = '%webcodebase%dicomviewer100/Dicom.dic'> line9 = <PARAM NAME = imgURL0 VALUE = line10 = --imagelister:local|%patid%|%seruid%|:%webscriptadress%?%extra%&mode=dicom&slice=%s:%s&compress=un* line11 = > line12 = </APPLET> line13 = </BODY> # this is the default; the variable can be passed in the url windowname = AiViewer V1.00 [flexviewer2] source = flexviewer2.cq windowname = AiViewer V1.00 */ /* check mode of web page against dicom.ini sections */ GetPrivateProfileString ( mode, "source", "", buf, 1000, ConfigFile); GetPrivateProfileString ( mode, "line0", buf, buf, 1000, ConfigFile); if (buf[0]) { char *p; char string[1000], temp[1000], server[1000], patid[66], patid2[200], seruid[66], studyuid[66], sopuid[66]; FILE *f=NULL; /* create several variables useful for scripting */ sprintf(server, "%s?%s", WebScriptAddress, extra); patid[0] = seruid[0] = studyuid[0] = sopuid[0] = 0; if (study2[0]) { strcpy(temp, study2); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid2, temp); *p = '|'; strcpy(studyuid, p+1); } strcpy(temp, study); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid, temp); } } if (series2[0]) { strcpy(temp, series2); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid2, temp); *p = '|'; strcpy(seruid, p+1); } strcpy(temp, series); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid, temp); } } if (slice2[0]) { strcpy(temp, slice2); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid2, temp); *p = '|'; strcpy(sopuid, p+1); } strcpy(temp, slice); p = strchr(temp, ':'); if (p) { *p = 0; strcpy(patid, temp); } } /* contents may come from file or from dicom.ini */ GetPrivateProfileString ( mode, "source", "", temp, 1000, ConfigFile); if (temp[0]) f = fopen(temp, "rt"); GetPrivateProfileString ( mode, "header", "Content-type: text/html\n", temp, 1000, ConfigFile); while (p = strstr(temp, "\\")) p[0]='\n'; HTML(temp); for (i=0; i<10000; i++) { if (f) { if (fgets(string, sizeof(string), f) == NULL) break; if (string[strlen(string)-1]=='\n') string[strlen(string)-1]=0; } else { sprintf(temp, "line%d", i); GetPrivateProfileString ( mode, temp, "", string, 1000, ConfigFile); if (string[0]==0) break; } /* fill in predefined scripting variables */ replace(string, "%query_string%", getenv( "QUERY_STRING" )); replace(string, "%server_name%", getenv( "SERVER_NAME" )); replace(string, "%script_name%", getenv( "SCRIPT_NAME" )); replace(string, "%path_translated%", getenv( "PATH_TRANSLATED" )); replace(string, "%port%", (char *)Port); replace(string, "%address%", ServerCommandAddress); replace(string, "%webcodebase%", WebCodeBase); replace(string, "%webscriptadress%", WebScriptAddress); replace(string, "%extra%", extra); replace(string, "%server%", server); replace(string, "%version%", VERSION); replace(string, "%mode%", mode); replace(string, "%series%", series2); // unprocessed replace(string, "%series2%", series); // replaced spaces by %20 replace(string, "%slice%", slice2); // unprocessed replace(string, "%slice2%", slice); // replaced spaces by %20 replace(string, "%study%", study2); // unprocessed replace(string, "%study2%", study); // replaced spaces by %20 replace(string, "%patid%", patid2); // unprocessed replace(string, "%patid2%", patid); // replaced spaces by %20 replace(string, "%seruid%", seruid); replace(string, "%studyuid%", studyuid); replace(string, "%sopuid%", sopuid); replace(string, "%size%", size); replace(string, "%dsize%", dsize); replace(string, "%compress%", compress); replace(string, "%iconsize%", iconsize); replace(string, "%graphic%", graphic); replace(string, "%viewer%", viewer); replace(string, "%lw%", lw); replace(string, "%query%", query); replace(string, "%db%", db); replace(string, "%source%", source); replace(string, "%dest%", dest); replace(string, "%patientidmatch%", patientidmatch); replace(string, "%patientnamematch%",patientnamematch); replace(string, "%studydatematch%", studydatematch); replace(string, "%startdatematch%", startdatematch); /* this code will substitute any other %var% with a cgi variable with a default given in section for this server mode in dicom.ini */ char *p = strchr(string, '%'); if (p) { char *q = strchr(p+1, '%'); if (q && q!=p+1) { char var[512], val[512], var2[512]; *q=0; strcpy(var, p+1); *q='%';; strcpy(var2, "%"); strcat(var2, var); strcat(var2, "%"); GetPrivateProfileString ( mode, var, var2, val, 512, ConfigFile); CGI(val, var, val); replace(string, var2, val); } } /* runs: #comment, --servercommand, or HTML output */ if (string[0]=='#') strcpy(string, ""); else if (string[0]=='-' && string[1]=='-') SendServerCommand("", string+2, console); else HTML("%s", string); }; if (f) fclose(f); exit(0); }; exit(0); } /* Dicom web viewer works as follows: client -> webserver url http://127.0.0.1/scripts/dgate.exe?mode=seriesviewer&series=... webserver -> dicomserver query imagelister:local|..... client <- webserver <- dicomserver query results (to build list of urls of dicom slices) client <- webserver activex control http://127.0.0.1/ActiveFormProj1.ocx Then for each slice that is required: control -> webserver url of slice http://127.0.0.1/scripts/dgate.exe?mode=dicom&slice=...... webserver -> dicomserver dicom request convert_to_dicom:.... control <- webserver <- dicomserver dicom data */ ////////////////////////////////////////////////////////////////// // Elementary HL7 interface ////////////////////////////////////////////////////////////////// // These contain HL7 DateTime code: provide .DATE and .TIME split, note: should start/end with | static char HL7DateTimeTypes[]= "|OBR.7|OBR.8|OBR.22|PID.7|PID.29|PV1.44|PV1.45|TXA.4|TXA.6|TXA.7|TXA.8|OBR.6|OBR.36|MSH.6|OBX.12|OBX.14|ORC.9|ORC.15|"; // read next item from data passed in p; data->item, type->name, tmp->internal // note that data, type, and tmp are also used to maintain the parser state void parseHL7(char **p, char *data, char *type, char *tmp, char *HL7FieldSep, char *HL7SubFieldSep, char *HL7RepeatSep) { int field; char *q; char t[32]; int i, dots=0; sprintf(t, "|%s|", type); // to seek types if (strlen(type)>2) // count .N for (i=0; i<strlen(type)-1; i++) dots += (type[i]=='.' && type[i+1]>='0' && type[i+1]<='9'); if (**p==0) { strcpy(type, "EOM"); // end of message data[0]=0; } else if (strstr(HL7DateTimeTypes, t)) // translate datetime type { tmp[0] = 0; if (strlen(data)>8) strcpy(tmp, data+8); // get time for later use data[8]=0; strcat(type, ".DATE"); // XXX.N.DATE } else if (strstr(type, ".DATE")>0) // date was returned, now get time { strcpy(data, tmp); // time strcpy(type+strlen(type)-4, "TIME"); // XXX.N.TIME } else if (strchr(data, *HL7SubFieldSep)) // translate field type, first entry { q = strchr(data, *HL7SubFieldSep); if (q) *q=0; if (q) strcpy(tmp, q+1); else tmp[0]=0; strcat(type, ".0"); // XXX.N.0 } else if (strchr(data, *HL7RepeatSep)) // translate repeat type, first entry { q = strchr(data, *HL7RepeatSep); if (q) *q=0; if (q) strcpy(tmp, q+1); else tmp[0]=0; strcat(type, ".0"); // XXX.N.0 } else if (dots>1) // process subfields/repeats { if (tmp[0]==0) { q = strrchr(type, '.'); if (q) *q=0; strcat(type, ".END"); // internal token data[0]=0; } else { strcpy(data, tmp); q = strchr(data, *HL7SubFieldSep); if (!q) q = strchr(data, *HL7RepeatSep); if (q) *q=0; if (q) strcpy(tmp, q+1); else tmp[0]=0; q = strrchr(type, '.'); sprintf(q+1, "%d", atoi(q+1)+1); // XXX.N.M } } else if (**p==0x0d) { strcpy(type, "EOS"); strcpy(data, ""); (*p)+=1; // end of segment if (**p==0x0a) (*p)+=1; if (strncmp(*p, "MSH", 3)==0) strcpy(type, "EOM"); // peek ahead for end of message } else if (strcmp(type, "EOS")==0 || strcmp(type, "EOM")==0 || strcmp(type, "")==0) // new segment { field = 0; if (strncmp(*p, "MSH", 3)==0) { *HL7FieldSep = (*p)[3]; *HL7SubFieldSep = (*p)[4]; *HL7RepeatSep = (*p)[5]; strncpy(type, *p, 3); strcat(type, ".0"); strncpy(data, *p, 3); (*p)+=4; } else if ((*p)[0]>='A' && (*p)[0] <='Z' && // message header (*p)[1]>='A' && (*p)[1] <='Z' && (((*p)[2]>='A' && (*p)[2] <='Z') || ((*p)[2]>='0' && (*p)[2] <='9'))) { strncpy(type, *p, 3); strcat(type, ".0"); strncpy(data, *p, 3); (*p)+=4; } else { strcpy(type, "UNK.0"); data[0]=0; } } else { field = atoi(type+4); // genererate new segment sprintf(type+4, "%d", field+1); q = strchr(*p, *HL7FieldSep); // upto segment separator if (q) { *q=0; strncpy(data, *p, 255); data[255]=0; *q = *HL7FieldSep; *p = q+1; } else { q = strchr(*p, 0x0d); // or 0x0d if (q) { *q = 0; strncpy(data, *p, 255); data[255]=0; *q = 0x0d; *p = q; // process 0x0d again } else { strcpy(data, ""); strcpy(type, "ERR"); // internal token } } } SystemDebug.printf("HL7 item: %s, contents: %s\n", type, data); } // load HL7 data into modality worklist using the translation table from dicom.sql void ProcessHL7Data(char *data) { char *p=data; char fields[1024], values[4096], command[8192], type[32], item[256], uid[66], tmp[256]; int i; char HL7FieldSep = '|'; char HL7SubFieldSep = '^'; char HL7RepeatSep = '~'; Database DB; if (!DB.Open ( DataSource, UserName, Password, DataHost ) ) { OperatorConsole.printf("*** HL7 import: cannot open database"); return; } fields[0]=0; values[0]=0; type[0]=0; // used for context of parser tmp[0]=0; while (TRUE) { parseHL7(&p, item, type, tmp, &HL7FieldSep, &HL7SubFieldSep, &HL7RepeatSep); if (strcmp(type, "ERR")==0) break; // error // search type in database; if found prepare strings to write i = 0; while ( TRUE ) { if(!WorkListDB[i].Element) break; if (WorkListDB[i].DICOMType!=DT_STARTSEQUENCE && WorkListDB[i].DICOMType!=DT_ENDSEQUENCE) { if (strcmp(type, WorkListDB[i].HL7Tag)==0) { strcat(fields, WorkListDB[i].SQLColumn); strcat(fields, ","); strcat(values, "'"); item[WorkListDB[i].SQLLength]=0; // truncate data to make fit strcat(values, item); strcat(values, "',"); } } ++i; } // on end of message save the data into the database if (strcmp(type, "EOM")==0) { // search for special items (start with *) that are not read from the HL7 parser i = 0; while ( TRUE ) { if(!WorkListDB[i].Element) break; if (WorkListDB[i].DICOMType!=DT_STARTSEQUENCE && WorkListDB[i].DICOMType!=DT_ENDSEQUENCE) { if (WorkListDB[i].HL7Tag[0]=='*') { strcat(fields, WorkListDB[i].SQLColumn); strcat(fields, ","); strcat(values, "'"); if (strcmp("*AN", WorkListDB[i].HL7Tag)==0) // generate new accession number { GenUID(uid); strcat(values, uid + strlen(uid)-16); } else if (strcmp("*UI", WorkListDB[i].HL7Tag)==0) // generate new uid { GenUID(uid); strcat(values, uid); } strcat(values, "',"); } } ++i; } fields[strlen(fields)-1]=0; // remove trailing , values[strlen(values)-1]=0; // remove trailing , DB.AddRecord("dicomworklist", fields, values); SystemDebug.printf("Entering modality worklist fields: %s\n", fields); QueryFromGui++; fields[0]=0; values[0]=0; HL7FieldSep = '|'; HL7SubFieldSep = '^'; HL7RepeatSep = '~'; } if (strcmp(type, "EOM")==0) // end of message if (*p==0) break; // end of file } DB.Close(); }
[ [ [ 1, 15937 ] ] ]
ae0aa6b123e3fbb070163659fff437569b06f8ef
3d7fc34309dae695a17e693741a07cbf7ee26d6a
/aluminizer/ScanSource.h
f75683cbd86ea022f7cd54f2f295f4498df5800c
[ "LicenseRef-scancode-public-domain" ]
permissive
nist-ionstorage/ionizer
f42706207c4fb962061796dbbc1afbff19026e09
70b52abfdee19e3fb7acdf6b4709deea29d25b15
refs/heads/master
2021-01-16T21:45:36.502297
2010-05-14T01:05:09
2010-05-14T01:05:09
20,006,050
5
0
null
null
null
null
UTF-8
C++
false
false
5,526
h
#pragma once #include "InputParametersGUI.h" //! An adjustable signal source for scans, e.g. a frequency synthesizer, or a voltage source /*! The experimental conditions are changed via objects of this class * to generate scans. Some housingkeeping is done so that the state can be * returned to "normal" when this experiment is over or on hold. */ class ScanSource { public: ScanSource(ParameterGUI_Base* pParam) : pParam(pParam), bHasNonScanningOutput(true), nonScanningOutput(0) { } virtual ~ScanSource() { } virtual void useFit(const std::string& scan_type, double x) = 0; //! Should a sine function be fitted to this scan? virtual bool fitsSine() { return false; } //! Should a Lorentzian be fitted to this scan? virtual bool fitsLorentzian() { return true; } void setDefaultValue(); std::string getXlabel(); //! Set the "non-scanning" default value of this parameter. /*! Doesn't this clash with scan_variable::default_state ? * Are we keeping track of the "same" information in two places ? * TODO: check for potential bug. */ void setNonScanningValue(double d); //! Return "non-scanning" default value of this parameter. double getNonScanningValue(); virtual void SetScanOutput(double d); virtual double GetOutput() = 0; virtual double GetMin() = 0; virtual double GetMax() = 0; virtual std::string getName() = 0; virtual std::string getType() = 0; virtual std::string GetUnit() = 0; virtual unsigned GetMode() { return 2; } virtual bool isCompatibleScanType(const std::string&) = 0; ParameterGUI_Base* pParam; protected: bool bHasNonScanningOutput; double nonScanningOutput; }; class FPGA_connection; //! Base class for scan sources that are FPGA parameters class FPGAScanSource : public ScanSource { public: FPGAScanSource(FPGA_connection* pFPGA, unsigned page_id, ParameterGUI_Base* pParam) : ScanSource(pParam), pFPGA(pFPGA), page_id(page_id) { } virtual ~FPGAScanSource() { } protected: FPGA_connection* pFPGA; unsigned page_id; }; //! Base class for scan sources that are FPGA pulse parameters class PulseScanSource : public FPGAScanSource { public: PulseScanSource(FPGA_connection* pFPGA, unsigned page_id, ParameterGUI_Base* pParam) : FPGAScanSource(pFPGA, page_id, pParam) { } virtual ~PulseScanSource() { } //! Return pulse time (non-scanning) virtual double getPulseTime() = 0; }; class DoubleScanSource : public FPGAScanSource { public: DoubleScanSource(FPGA_connection* pFPGA, unsigned page_id, GUI_double* pDouble) : FPGAScanSource(pFPGA, page_id, pDouble), pDouble(pDouble) { } //! Should a sine wave be fitted to this scan? virtual bool fitsSine() { return getName().find("phase") != std::string::npos; } //! Should a Lorentzian be fitted to this scan? virtual bool fitsLorentzian() { return !fitsSine(); } virtual ~DoubleScanSource() { } virtual void SetScanOutput(double d); virtual double GetOutput(); virtual double GetMin(); virtual double GetMax(); virtual std::string getName(); virtual std::string getType() { return "General"; } virtual std::string GetUnit(); virtual bool isCompatibleScanType(const std::string&); virtual void useFit(const std::string& scan_type, double x) { if (isCompatibleScanType(scan_type) && pDouble) pDouble->SetValue(x); } protected: GUI_double* pDouble; }; //! Connects to freq. pulse parameters on FPGA class FScanSource : public PulseScanSource { public: FScanSource(FPGA_connection* pFPGA, unsigned page_id, GUI_dds* pPulse) : PulseScanSource(pFPGA, page_id, pPulse), pPulse(pPulse) { } virtual ~FScanSource() { } //!Should a Lorentzian be fitted to this scan? virtual bool fitsLorentzian() { return getName().find("Detect") != std::string::npos; } virtual void SetScanOutput(double d); virtual double GetOutput(); virtual double GetMin(); virtual double GetMax(); virtual std::string getName(); virtual std::string getType() { return "Frequency"; } virtual std::string GetUnit(); virtual unsigned GetMode() { return 1; } virtual bool isCompatibleScanType(const std::string&); //!Return pulse time (non-scanning) virtual double getPulseTime(); //!Return pulse freq. (non-scanning) virtual double getPulseFreq(); virtual void useFit(const std::string& scan_type, double x); protected: GUI_dds* pPulse; }; //! Connects to time pulse parameters on FPGA class TScanSource : public PulseScanSource { public: TScanSource(FPGA_connection* pFPGA, unsigned page_id, GUI_dds* pPulseDDS) : PulseScanSource(pFPGA, page_id, pPulseDDS), pPulseDDS(pPulseDDS), pPulseTTL(0) { } TScanSource(FPGA_connection* pFPGA, unsigned page_id, GUI_ttl* pPulseTTL) : PulseScanSource(pFPGA, page_id, pPulseTTL), pPulseDDS(0), pPulseTTL(pPulseTTL) { } virtual ~TScanSource() { } //! Should a Lorentzian be fitted to this scan? virtual bool fitsLorentzian() { return false; } virtual void SetScanOutput(double d); virtual double GetOutput(); virtual double GetMin(); virtual double GetMax(); virtual std::string getName(); virtual std::string getType() { return "Time"; } virtual std::string GetUnit(); virtual bool isCompatibleScanType(const std::string&); virtual double getPulseTime(); virtual void useFit(const std::string& scan_type, double x); protected: GUI_dds* pPulseDDS; GUI_ttl* pPulseTTL; }; extern std::vector< ScanSource* > g_scan_sources;
[ "trosen@814e38a0-0077-4020-8740-4f49b76d3b44" ]
[ [ [ 1, 256 ] ] ]
63b54ae2c3427417e5ac376514a413eb13bc9621
f7d5fcb47d370751163d253ac0d705d52bd3c5d5
/tags/trunk/Sources/source/hapticgraphclasses/GraphScene.cpp
ba482d5fd2767a66248beff387afca4b436a95f4
[]
no_license
BackupTheBerlios/phantom-graphs-svn
b830eadf54c49ccecf2653e798e3a82af7e0e78d
6a585ecde8432394c732a72e4860e136d68cc4b4
refs/heads/master
2021-01-02T09:21:18.231965
2006-02-06T08:44:57
2006-02-06T08:44:57
40,820,960
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,205
cpp
//******************************************************************************* /// @file GraphScene.cpp /// @author Katharina Greiner, Matr.-Nr. 943471 /// @date Erstellt am 26.12.2005 /// @date Letzte Änderung 04.02.2006 //******************************************************************************* // Änderungen: // 30.12.05 - Alle Methoden bis auf initScene() implementiert // 02.01.06 - Anstoß für Event-Callbacks hinzugefügt. // 26.01.06 - initScene() hat neue Parameter bekommen. // - neue Methode getView() hinzugefügt und implementiert. // 28.01.06 - createObjects() implementiert. // 04.02.06 - Code aufgeräumt. // Haptics Library includes #include <HL/hl.h> // OpenGL includes #include <GL/gl.h> #include <GL/glu.h> #include "GraphScene.h" #include "Node.h" #include "DragObjectHandler.h" #include "DragNodeOnGridHandler.h" #include "DragSceneHandler.h" #include "Edge.h" //******************************************************************************* GraphScene::GraphScene( UnitConversionInfo & unitInfo ) : m_rUnitInfo(unitInfo) { // keine Objekte in der Scene m_SceneElements.clear(); m_pCamera = NULL; m_pDragSceneHandler = NULL; } //******************************************************************************* //******************************************************************************* GraphScene::~GraphScene() { // alle Objekte der Scene freigeben vector<HapticObject*>::iterator itObj; for (itObj = m_SceneElements.begin(); itObj != m_SceneElements.end(); itObj++) { if (*itObj != NULL) { delete *itObj; *itObj = NULL; } } m_SceneElements.clear(); // Kamera freigeben if (m_pCamera != NULL) { delete m_pCamera; m_pCamera = NULL; } // DragSceneHandler freigeben if (m_pDragSceneHandler != NULL) { m_pDragSceneHandler->unregisterAction(HL_OBJECT_ANY); delete m_pDragSceneHandler; m_pDragSceneHandler = NULL; } } //******************************************************************************* //******************************************************************************* void GraphScene::addObject( HapticObject * obj ) { if (obj != NULL) { m_SceneElements.push_back(obj); } } //******************************************************************************* //******************************************************************************* void GraphScene::initScene( int viewportWidth, int viewportHeight, HapticDevice * pHd, int gridColumns, int gridRows, IBusinessAdapter * rootNode) { // Kamera initialisieren m_pCamera = new Camera(40.0, viewportWidth, viewportHeight, pHd); m_pCamera->translateView(1.8, 0.0); // Hintergrundfarbe festlegen glClearColor(1.0, 1.0, 1.0, 1.0); // DragSceneHandler initialisieren m_pDragSceneHandler = new DragSceneHandler(this); m_pDragSceneHandler->registerAction(HL_OBJECT_ANY); // Darstellungsobjekte zum Graphen erzeugen: // Grid der entsprechenden Größe mit linker unterer Ecke bei [0.0, 0.0, 0.0] erzeugen Grid * pGrid = new Grid(m_rUnitInfo, gridColumns, gridRows); pGrid->setPosition(0.0, 0.0, 0.0); HapticConstraint * pGridConstraint = new HapticConstraint(1.0f); pGridConstraint->disable(); pGrid->setHapticConstraint(pGridConstraint); pGrid->addHapticAction(new DragSceneHandler(this)); addObject(pGrid); // vom rootNode ausgehend Haptische Objekte für Knoten und Kanten erzeugen // der rootNode selbst wird nicht dargestellt list<IBusinessAdapter*>& lsFollowingNodes = rootNode->getNextTasks(); list<IBusinessAdapter*>::iterator iterNext; for (iterNext = lsFollowingNodes.begin(); iterNext != lsFollowingNodes.end(); iterNext++) { createObjects(*iterNext, pGrid); } } //******************************************************************************* //******************************************************************************* Node * GraphScene::createObjects(IBusinessAdapter * businessObj, Grid * pGrid ) { Node * pNode = new Node(businessObj, m_rUnitInfo); addObject(pNode); pNode->addHapticAction(new DragNodeOnGridHandler(pNode, pGrid)); pNode->setHapticConstraint(new HapticConstraint(2.0)); // rekursiv die Nachfolger erzeugen und mit Kanten verbinden Node * pNextNode = NULL; Edge * pEdge = NULL; list<IBusinessAdapter*>& lsFollowingNodes = businessObj->getNextTasks(); list<IBusinessAdapter*>::iterator iterNext; for (iterNext = lsFollowingNodes.begin(); iterNext != lsFollowingNodes.end(); iterNext++) { pNextNode = createObjects(*iterNext, pGrid); pEdge = new Edge(); pNode->addOutgoingEdge(pEdge); pNextNode->addIncomingEdge(pEdge); addObject(pEdge); } return pNode; } //******************************************************************************* //******************************************************************************* void GraphScene::renderScene( bool bHapticsEnabled ) { // Haptik rendern, wenn die Anwendung mit haptischer Unterstützung läuft renderSceneHaptics(bHapticsEnabled); // Graphik rendern renderSceneGraphics(); } //******************************************************************************* //******************************************************************************* void GraphScene::renderSceneGraphics() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // alle Objekte der Scene durchlaufen und sie zum Rendern ihrer graphischen // Beschaffenheit auffordern vector<HapticObject*>::iterator itObj; for (itObj = m_SceneElements.begin(); itObj != m_SceneElements.end(); itObj++) { if (*itObj != NULL) { (*itObj)->renderGraphics(); } } } //******************************************************************************* //******************************************************************************* void GraphScene::renderSceneHaptics( bool bHapticsEnabled ) { // Haptik rendern, wenn die Anwendung mit haptischer Unterstützung läuft if (bHapticsEnabled) { // Haptic Frame starten - haptische Objekte können nur zwischen hlBeginFrame() // und hlEndFrame() gerendert werden hlBeginFrame(); // alle Objekte der Scene durchlaufen und sie zum Rendern ihrer haptischen // Beschaffenheit auffordern vector<HapticObject*>::iterator itObj; for (itObj = m_SceneElements.begin(); itObj != m_SceneElements.end(); itObj++) { if (*itObj != NULL) { (*itObj)->renderHaptics(); } } // Eventcallbacks des Client Thread anstoßen hlCheckEvents(); // Haptic Frame beenden hlEndFrame(); } } //******************************************************************************* //******************************************************************************* float GraphScene::getGraphPlaneZ() { // Dummy return -0.1f; } //******************************************************************************* //******************************************************************************* Camera * GraphScene::getView() { return m_pCamera; } //*******************************************************************************
[ "frosch@a1b688d3-ce07-0410-8a3f-c797401f78de" ]
[ [ [ 1, 224 ] ] ]
ff29cf82d4ff98a25bd26be1c96cc340cd1abc39
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SETools/SEManagedFramework/SEManagedRendering/SEManagedStencilState.cpp
f340273d77f5ac578e57d704beb7767982b92e8f
[]
no_license
pizibing/swingengine
d8d9208c00ec2944817e1aab51287a3c38103bea
e7109d7b3e28c4421c173712eaf872771550669e
refs/heads/master
2021-01-16T18:29:10.689858
2011-06-23T04:27:46
2011-06-23T04:27:46
33,969,301
0
0
null
null
null
null
UTF-8
C++
false
false
8,024
cpp
// Swing Engine Version 1 Source Code // Most of techniques in the engine are mainly based on David Eberly's // Wild Magic 4 open-source code.The author of Swing Engine learned a lot // from Eberly's experience of architecture and algorithm. // Several sub-systems are totally new,and others are re-implimented or // re-organized based on Wild Magic 4's sub-systems. // Copyright (c) 2007-2010. All Rights Reserved // // Eberly's permission: // Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation; either version 2.1 of the License, or (at // your option) any later version. The license is available for reading at // the location: // http://www.gnu.org/copyleft/lgpl.html #include "SEManagedFrameworkPCH.h" #include "SEManagedStencilState.h" using namespace Swing; using namespace Swing::Tools::ManagedFramework; //--------------------------------------------------------------------------- ManagedStencilState::ManagedStencilState() { m_pspStencilState = SE_NEW SEStencilStatePtr; (*m_pspStencilState) = SE_NEW SEStencilState; } //--------------------------------------------------------------------------- ManagedStencilState::ManagedStencilState(SEStencilState* pState) { m_pspStencilState = SE_NEW SEStencilStatePtr; (*m_pspStencilState) = pState; } //--------------------------------------------------------------------------- ManagedStencilState::~ManagedStencilState() { SE_DELETE m_pspStencilState; m_pspStencilState = 0; } //--------------------------------------------------------------------------- bool ManagedStencilState::Enabled::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (*m_pspStencilState)->Enabled; } //--------------------------------------------------------------------------- void ManagedStencilState::Enabled::set(bool bValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->Enabled = bValue; } //--------------------------------------------------------------------------- ManagedStencilState::CompareFunction ManagedStencilState::Compare::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (ManagedStencilState::CompareFunction)( *m_pspStencilState)->Compare; } //--------------------------------------------------------------------------- void ManagedStencilState::Compare::set( ManagedStencilState::CompareFunction eValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->Compare = (SEStencilState::CompareFunction)eValue; } //--------------------------------------------------------------------------- int ManagedStencilState::Reference::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (*m_pspStencilState)->Reference; } //--------------------------------------------------------------------------- void ManagedStencilState::Reference::set(int iValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->Reference = (unsigned int)iValue; } //--------------------------------------------------------------------------- int ManagedStencilState::Mask::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (int)(*m_pspStencilState)->Mask; } //--------------------------------------------------------------------------- void ManagedStencilState::Mask::set(int iValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->Mask = (unsigned int)iValue; } //--------------------------------------------------------------------------- int ManagedStencilState::WriteMask::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (int)(*m_pspStencilState)->WriteMask; } //--------------------------------------------------------------------------- void ManagedStencilState::WriteMask::set(int iValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->WriteMask = (unsigned int)iValue; } //--------------------------------------------------------------------------- ManagedStencilState::OperationType ManagedStencilState::OnFail::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (ManagedStencilState::OperationType)(*m_pspStencilState)->OnFail; } //--------------------------------------------------------------------------- void ManagedStencilState::OnFail::set( ManagedStencilState::OperationType eValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->OnFail = (SEStencilState::OperationType)eValue; } //--------------------------------------------------------------------------- ManagedStencilState::OperationType ManagedStencilState::OnZFail::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (ManagedStencilState::OperationType)(*m_pspStencilState)->OnZFail; } //--------------------------------------------------------------------------- void ManagedStencilState::OnZFail::set( ManagedStencilState::OperationType eValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->OnZFail = (SEStencilState::OperationType)eValue; } //--------------------------------------------------------------------------- ManagedStencilState::OperationType ManagedStencilState::OnZPass::get() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (ManagedStencilState::OperationType)(*m_pspStencilState)->OnZPass; } //--------------------------------------------------------------------------- void ManagedStencilState::OnZPass::set( ManagedStencilState::OperationType eValue) { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); (*m_pspStencilState)->OnZPass = (SEStencilState::OperationType)eValue; } //--------------------------------------------------------------------------- INativeGlobalState::StateType ManagedStencilState::GetStateType() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (INativeGlobalState::StateType)( *m_pspStencilState)->GetStateType(); } //--------------------------------------------------------------------------- void ManagedStencilState::SetName(String^ thName) { SE_NULL_ARGUMENT_CHECK(thName, "thName"); SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); const char* acName = ManagedUtility::StringToNativeCharBuffer(thName); std::string tempName(acName); ManagedUtility::FreeNativeCharBuffer(acName); (*m_pspStencilState)->SetName(tempName); } //--------------------------------------------------------------------------- String^ ManagedStencilState::GetName() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return gcnew String((*m_pspStencilState)->GetName().c_str()); } //--------------------------------------------------------------------------- int ManagedStencilState::GetNativeReferences() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (*m_pspStencilState)->GetReferences(); } //--------------------------------------------------------------------------- SEGlobalState* ManagedStencilState::GetNativeGlobalState() { SE_NULL_REFERENCE_CHECK(m_pspStencilState, "Native pointer is null"); return (SEGlobalState*)(*m_pspStencilState); } //---------------------------------------------------------------------------
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 182 ] ] ]
8809e4db27d54aa9bc01e85687be39081326ff4f
12203ea9fe0801d613bbb2159d4f69cab3c84816
/Export/cpp/windows/obj/include/cpp/FileSystem.h
8a116941e45df3d2e991e7d9fab8bc35a9c03e3a
[]
no_license
alecmce/haxe_game_of_life
91b5557132043c6e9526254d17fdd9bcea9c5086
35ceb1565e06d12c89481451a7bedbbce20fa871
refs/heads/master
2016-09-16T00:47:24.032302
2011-10-10T12:38:14
2011-10-10T12:38:14
2,547,793
0
0
null
null
null
null
UTF-8
C++
false
false
2,490
h
#ifndef INCLUDED_cpp_FileSystem #define INCLUDED_cpp_FileSystem #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS1(cpp,FileKind) HX_DECLARE_CLASS1(cpp,FileSystem) namespace cpp{ class FileSystem_obj : public hx::Object{ public: typedef hx::Object super; typedef FileSystem_obj OBJ_; FileSystem_obj(); Void __construct(); public: static hx::ObjectPtr< FileSystem_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~FileSystem_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); ::String __ToString() const { return HX_CSTRING("FileSystem"); } static bool exists( ::String path); static Dynamic exists_dyn(); static Void rename( ::String path,::String newpath); static Dynamic rename_dyn(); static Dynamic stat( ::String path); static Dynamic stat_dyn(); static ::String fullPath( ::String relpath); static Dynamic fullPath_dyn(); static ::cpp::FileKind kind( ::String path); static Dynamic kind_dyn(); static bool isDirectory( ::String path); static Dynamic isDirectory_dyn(); static Void createDirectory( ::String path); static Dynamic createDirectory_dyn(); static Void deleteFile( ::String path); static Dynamic deleteFile_dyn(); static Void deleteDirectory( ::String path); static Dynamic deleteDirectory_dyn(); static Array< ::String > readDirectory( ::String path); static Dynamic readDirectory_dyn(); static Dynamic sys_exists; /* REM */ Dynamic &sys_exists_dyn() { return sys_exists;} static Dynamic file_delete; /* REM */ Dynamic &file_delete_dyn() { return file_delete;} static Dynamic sys_rename; /* REM */ Dynamic &sys_rename_dyn() { return sys_rename;} static Dynamic sys_stat; /* REM */ Dynamic &sys_stat_dyn() { return sys_stat;} static Dynamic sys_file_type; /* REM */ Dynamic &sys_file_type_dyn() { return sys_file_type;} static Dynamic sys_create_dir; /* REM */ Dynamic &sys_create_dir_dyn() { return sys_create_dir;} static Dynamic sys_remove_dir; /* REM */ Dynamic &sys_remove_dir_dyn() { return sys_remove_dir;} static Dynamic sys_read_dir; /* REM */ Dynamic &sys_read_dir_dyn() { return sys_read_dir;} static Dynamic file_full_path; /* REM */ Dynamic &file_full_path_dyn() { return file_full_path;} }; } // end namespace cpp #endif /* INCLUDED_cpp_FileSystem */
[ [ [ 1, 84 ] ] ]
0b6a45b1cdd1f61d43490f76ac2d1d0c08ac03d0
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/GameEngine/Gfx/Ogl/OglSWVertexBufferResource.cpp
50c011a056cb9d614b62f4f8fce48e1087345eb4
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
#include "OglSWVertexBufferResource.hpp" #include "../../Resource/ResLockImpl.hpp" using namespace Spiral; using namespace boost; using namespace std; OglSWVertexBufferResource::OglSWVertexBufferResource( boost::int32_t size ): m_isValid( true ), m_data( NULL ), m_size( size ), m_mutex() { m_data = new int8_t[ size ]; } OglSWVertexBufferResource::~OglSWVertexBufferResource() { delete [] m_data; } bool OglSWVertexBufferResource::DoIsValid() const { return m_isValid; } bool OglSWVertexBufferResource::DoLock( int32_t start, int32_t size, ResLockInfo_t& info, bool bDiscard ) { int32_t totalSize = start + size; bool lockResults = false; if( m_mutex.try_lock() ) { if( totalSize <= m_size ) { info.data = (m_data + start); info.size = size; lockResults = true; } } return lockResults; } void OglSWVertexBufferResource::DoUnlock() { m_mutex.unlock(); } // cannot do a rectangle lock on a vertexbuffer bool OglSWVertexBufferResource::DoLock( ResLockRtInfo_t& /*info*/, bool /*bDiscard*/ ) { return false; } int32_t OglSWVertexBufferResource::DoSize() const { return m_size; } void OglSWVertexBufferResource::DoSize( Rect< int32_t >& /*rect*/ ) const { }
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
[ [ [ 1, 64 ] ] ]
d2701800a2ad40c4159ea70cf3db56f0d62f028d
61c263eb77eb64cf8ab42d2262fc553ac51a6399
/src/RageFileManager.h
ac130b0a164c2d70f26f8e41777aaaec65a1fbbe
[]
no_license
ycaihua/fingermania
20760830f6fe7c48aa2332b67f455eef8f9246a3
daaa470caf02169ea6533669aa511bf59f896805
refs/heads/master
2021-01-20T09:36:38.221802
2011-01-23T12:31:19
2011-01-23T12:31:19
40,102,565
1
0
null
null
null
null
UTF-8
C++
false
false
3,800
h
/* RageFileManager - File utilities and high-level manager for RageFile objects. */ #ifndef RAGE_FILE_MANAGER_H #define RAGE_FILE_MANAGER_H namespace RageFileManagerUtil { extern RString sInitialWorkingDirectory; extern RString sDirOfExecutable; } class RageFileDriver; class RageFileBasic; class RageFileManager { public: RageFileManager( const RString &argv0 ); ~RageFileManager(); void MountInitialFilesystems(); void MountUserFilesystems(); void GetDirListing( const RString &sPath, vector<RString> &AddTo, bool bOnlyDirs, bool bReturnPathToo ); bool Move( const RString &sOldPath, const RString &sNewPath ); bool Remove( const RString &sPath ); void CreateDir( const RString &sDir ); enum FileType { TYPE_FILE, TYPE_DIR, TYPE_NONE }; FileType GetFileType( const RString &sPath ); bool IsAFile( const RString &sPath ); bool IsADirectory( const RString &sPath ); bool DoesFileExist( const RString &sPath ); int GetFileSizeInBytes( const RString &sPath ); int GetFileHash( const RString &sPath ); bool Mount( const RString &sType, const RString &sRealPath, const RString &sMountPoint, bool bAddToEnd = true ); void Mount( RageFileDriver *pDriver, const RString &sMountPoint, bool bAddToEnd = true ); void Unmount( const RString &sType, const RString &sRoot, const RString &sMountPoint ); /* Change the root of a filesystem. Only a couple drivers support this; it's * used to change memory card mountpoints without having to actually unmount * the driver. */ void Remount( RString sMountpoint, RString sPath ); bool IsMounted( RString MountPoint ); struct DriverLocation { RString Type, Root, MountPoint; }; void GetLoadedDrivers( vector<DriverLocation> &asMounts ); void FlushDirCache( const RString &sPath = RString() ); /* Used only by RageFile: */ RageFileBasic *Open( const RString &sPath, int iMode, int &iError ); void CacheFile( const RageFileBasic *fb, const RString &sPath ); /* Retrieve or release a reference to the low-level driver for a mountpoint. */ RageFileDriver *GetFileDriver( RString sMountpoint ); void ReleaseFileDriver( RageFileDriver *pDriver ); private: RageFileBasic *OpenForReading( const RString &sPath, int iMode, int &iError ); RageFileBasic *OpenForWriting( const RString &sPath, int iMode, int &iError ); }; extern RageFileManager *FILEMAN; #endif // RAGE_FILE_MANAGER_H /* * Copyright (c) 2001-2004 Glenn Maynard, Chris Danford * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
[ [ [ 1, 95 ] ] ]
a6f19b38947646ef6eedc6eef1fd62176bba95e5
fba89bd35ead23881a7f15d3ff0ca300535c9801
/jni/SampleUtils.cpp
f3f2efe11a01f557782cb3b920fcaaee0a131dcc
[]
no_license
masoudsafa/virtualwimbledonpro
56e440be7d32457201bac5508ede9c14676a09c9
72ba75655d49a9cd0ea8ae3308394269ff22a0f1
refs/heads/master
2021-01-10T07:23:18.496832
2011-07-29T15:45:58
2011-07-29T15:45:58
43,097,253
0
0
null
null
null
null
UTF-8
C++
false
false
6,219
cpp
/*============================================================================== Copyright (c) 2010-2011 QUALCOMM Incorporated. All Rights Reserved. Qualcomm Confidential and Proprietary @file SampleUtils.cpp @brief Implementation of class SampleUtils. ==============================================================================*/ #include "SampleUtils.h" #include <math.h> #include <stdlib.h> #ifdef USE_OPENGL_ES_1_1 #include <GLES/gl.h> #include <GLES/glext.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif void SampleUtils::printMatrix(const float* mat) { for(int r=0; r<4; r++,mat+=4) LOG("[ %7.3f %7.3f %7.3f %7.3f ]", mat[0], mat[1], mat[2], mat[3]); } void SampleUtils::checkGlError(const char* operation) { for (GLint error = glGetError(); error; error = glGetError()) LOG("after %s() glError (0x%x)", operation, error); } void SampleUtils::translatePoseMatrix(float x, float y, float z, float* matrix) { // Sanity check if (!matrix) return; // matrix * translate_matrix matrix[12] += (matrix[0] * x + matrix[4] * y + matrix[8] * z); matrix[13] += (matrix[1] * x + matrix[5] * y + matrix[9] * z); matrix[14] += (matrix[2] * x + matrix[6] * y + matrix[10] * z); matrix[15] += (matrix[3] * x + matrix[7] * y + matrix[11] * z); } void SampleUtils::rotatePoseMatrix(float angle, float x, float y, float z, float* matrix) { // Sanity check if (!matrix) return; float rotate_matrix[16]; SampleUtils::setRotationMatrix(angle, x, y, z, rotate_matrix); // matrix * scale_matrix SampleUtils::multiplyMatrix(matrix, rotate_matrix, matrix); } void SampleUtils::scalePoseMatrix(float x, float y, float z, float* matrix) { // Sanity check if (!matrix) return; // matrix * scale_matrix matrix[0] *= x; matrix[1] *= x; matrix[2] *= x; matrix[3] *= x; matrix[4] *= y; matrix[5] *= y; matrix[6] *= y; matrix[7] *= y; matrix[8] *= z; matrix[9] *= z; matrix[10] *= z; matrix[11] *= z; } void SampleUtils::multiplyMatrix(float *matrixA, float *matrixB, float *matrixC) { int i, j, k; float aTmp[16]; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { aTmp[j * 4 + i] = 0.0; for (k = 0; k < 4; k++) aTmp[j * 4 + i] += matrixA[k * 4 + i] * matrixB[j * 4 + k]; } } for (i = 0; i < 16; i++) matrixC[i] = aTmp[i]; } void SampleUtils::setRotationMatrix(float angle, float x, float y, float z, float *matrix) { double radians, c, s, c1, u[3], length; int i, j; radians = (angle * M_PI) / 180.0; c = cos(radians); s = sin(radians); c1 = 1.0 - cos(radians); length = sqrt(x * x + y * y + z * z); u[0] = x / length; u[1] = y / length; u[2] = z / length; for (i = 0; i < 16; i++) matrix[i] = 0.0; matrix[15] = 1.0; for (i = 0; i < 3; i++) { matrix[i * 4 + (i + 1) % 3] = u[(i + 2) % 3] * s; matrix[i * 4 + (i + 2) % 3] = -u[(i + 1) % 3] * s; } for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) matrix[i * 4 + j] += c1 * u[i] * u[j] + (i == j ? c : 0.0); } } unsigned int SampleUtils::initShader(unsigned int shaderType, const char* source) { #ifdef USE_OPENGL_ES_2_0 GLuint shader = glCreateShader((GLenum)shaderType); if (shader) { glShaderSource(shader, 1, &source, NULL); glCompileShader(shader); GLint compiled = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = (char*) malloc(infoLen); if (buf) { glGetShaderInfoLog(shader, infoLen, NULL, buf); LOG("Could not compile shader %d: %s", shaderType, buf); free(buf); } glDeleteShader(shader); shader = 0; } } } return shader; #else return 0; #endif } unsigned int SampleUtils::createProgramFromBuffer(const char* vertexShaderBuffer, const char* fragmentShaderBuffer) { #ifdef USE_OPENGL_ES_2_0 GLuint vertexShader = initShader(GL_VERTEX_SHADER, vertexShaderBuffer); if (!vertexShader) return 0; GLuint fragmentShader = initShader(GL_FRAGMENT_SHADER, fragmentShaderBuffer); if (!fragmentShader) return 0; GLuint program = glCreateProgram(); if (program) { glAttachShader(program, vertexShader); checkGlError("glAttachShader"); glAttachShader(program, fragmentShader); checkGlError("glAttachShader"); glLinkProgram(program); GLint linkStatus = GL_FALSE; glGetProgramiv(program, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint bufLength = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength); if (bufLength) { char* buf = (char*) malloc(bufLength); if (buf) { glGetProgramInfoLog(program, bufLength, NULL, buf); LOG("Could not link program: %s", buf); free(buf); } } glDeleteProgram(program); program = 0; } } return program; #else return 0; #endif }
[ [ [ 1, 256 ] ] ]
36ab56a5054845f0e628a77d1714aa42cc907a60
ea613c6a4d531be9b5d41ced98df1a91320c59cc
/7-Zip/CPP/7zip/Archive/Nsis/NsisIn.cpp
68fe1ab1e647f5ecc78302b7309bf222879fa3a7
[]
no_license
f059074251/interested
939f938109853da83741ee03aca161bfa9ce0976
b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2
refs/heads/master
2021-01-15T14:49:45.217066
2010-09-16T10:42:30
2010-09-16T10:42:30
34,316,088
1
0
null
null
null
null
UTF-8
C++
false
false
37,690
cpp
// NsisIn.cpp #include "StdAfx.h" #include "../../../../C/CpuArch.h" #include "Common/IntToString.h" #include "../../Common/StreamUtils.h" #include "NsisIn.h" #define Get32(p) GetUi32(p) namespace NArchive { namespace NNsis { Byte kSignature[kSignatureSize] = NSIS_SIGNATURE; #ifdef NSIS_SCRIPT static const char *kCrLf = "\x0D\x0A"; #endif #define NS_UN_SKIP_CODE 0xE000 #define NS_UN_VAR_CODE 0xE001 #define NS_UN_SHELL_CODE 0xE002 #define NS_UN_LANG_CODE 0xE003 #define NS_UN_CODES_START NS_UN_SKIP_CODE #define NS_UN_CODES_END NS_UN_LANG_CODE Byte CInArchive::ReadByte() { if (_posInData >= _size) throw 1; return _data[_posInData++]; } UInt32 CInArchive::ReadUInt32() { UInt32 value = 0; for (int i = 0; i < 4; i++) value |= ((UInt32)(ReadByte()) << (8 * i)); return value; } void CInArchive::ReadBlockHeader(CBlockHeader &bh) { bh.Offset = ReadUInt32(); bh.Num = ReadUInt32(); } #define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; } static int CompareItems(void *const *p1, void *const *p2, void * /* param */) { const CItem &i1 = **(CItem **)p1; const CItem &i2 = **(CItem **)p2; RINOZ(MyCompare(i1.Pos, i2.Pos)); if (i1.IsUnicode) { RINOZ(i1.PrefixU.Compare(i2.PrefixU)); RINOZ(i1.NameU.Compare(i2.NameU)); } else { RINOZ(i1.PrefixA.Compare(i2.PrefixA)); RINOZ(i1.NameA.Compare(i2.NameA)); } return 0; } static AString UIntToString(UInt32 v) { char sz[32]; ConvertUInt64ToString(v, sz); return sz; } static AString IntToString(Int32 v) { char sz[32]; ConvertInt64ToString(v, sz); return sz; } AString CInArchive::ReadStringA(UInt32 pos) const { AString s; if (pos >= _size) return IntToString((Int32)pos); UInt32 offset = GetOffset() + _stringsPos + pos; for (;;) { if (offset >= _size) break; // throw 1; char c = _data[offset++]; if (c == 0) break; s += c; } return s; } UString CInArchive::ReadStringU(UInt32 pos) const { UString s; UInt32 offset = GetOffset() + _stringsPos + (pos * 2); for (;;) { if (offset >= _size || offset + 1 >= _size) return s; // throw 1; char c0 = _data[offset++]; char c1 = _data[offset++]; wchar_t c = (c0 | ((wchar_t)c1 << 8)); if (c == 0) break; s += c; } return s; } /* static AString ParsePrefix(const AString &prefix) { AString res = prefix; if (prefix.Length() >= 3) { if ((Byte)prefix[0] == 0xFD && (Byte)prefix[1] == 0x95 && (Byte)prefix[2] == 0x80) res = "$INSTDIR" + prefix.Mid(3); else if ((Byte)prefix[0] == 0xFD && (Byte)prefix[1] == 0x96 && (Byte)prefix[2] == 0x80) res = "$OUTDIR" + prefix.Mid(3); } return res; } */ #define SYSREGKEY "Software\\Microsoft\\Windows\\CurrentVersion" /* # define CSIDL_PROGRAMS 0x2 # define CSIDL_PRINTERS 0x4 # define CSIDL_PERSONAL 0x5 # define CSIDL_FAVORITES 0x6 # define CSIDL_STARTUP 0x7 # define CSIDL_RECENT 0x8 # define CSIDL_SENDTO 0x9 # define CSIDL_STARTMENU 0xB # define CSIDL_MYMUSIC 0xD # define CSIDL_MYVIDEO 0xE # define CSIDL_DESKTOPDIRECTORY 0x10 # define CSIDL_NETHOOD 0x13 # define CSIDL_FONTS 0x14 # define CSIDL_TEMPLATES 0x15 # define CSIDL_COMMON_STARTMENU 0x16 # define CSIDL_COMMON_PROGRAMS 0x17 # define CSIDL_COMMON_STARTUP 0x18 # define CSIDL_COMMON_DESKTOPDIRECTORY 0x19 # define CSIDL_APPDATA 0x1A # define CSIDL_PRINTHOOD 0x1B # define CSIDL_LOCAL_APPDATA 0x1C # define CSIDL_ALTSTARTUP 0x1D # define CSIDL_COMMON_ALTSTARTUP 0x1E # define CSIDL_COMMON_FAVORITES 0x1F # define CSIDL_INTERNET_CACHE 0x20 # define CSIDL_COOKIES 0x21 # define CSIDL_HISTORY 0x22 # define CSIDL_COMMON_APPDATA 0x23 # define CSIDL_WINDOWS 0x24 # define CSIDL_SYSTEM 0x25 # define CSIDL_PROGRAM_FILES 0x26 # define CSIDL_MYPICTURES 0x27 # define CSIDL_PROFILE 0x28 # define CSIDL_PROGRAM_FILES_COMMON 0x2B # define CSIDL_COMMON_TEMPLATES 0x2D # define CSIDL_COMMON_DOCUMENTS 0x2E # define CSIDL_COMMON_ADMINTOOLS 0x2F # define CSIDL_ADMINTOOLS 0x30 # define CSIDL_COMMON_MUSIC 0x35 # define CSIDL_COMMON_PICTURES 0x36 # define CSIDL_COMMON_VIDEO 0x37 # define CSIDL_RESOURCES 0x38 # define CSIDL_RESOURCES_LOCALIZED 0x39 # define CSIDL_CDBURN_AREA 0x3B */ struct CCommandPair { int NumParams; const char *Name; }; enum { // 0 EW_INVALID_OPCODE, // zero is invalid. useful for catching errors. (otherwise an all zeroes instruction // does nothing, which is easily ignored but means something is wrong. EW_RET, // return from function call EW_NOP, // Nop/Jump, do nothing: 1, [?new address+1:advance one] EW_ABORT, // Abort: 1 [status] EW_QUIT, // Quit: 0 EW_CALL, // Call: 1 [new address+1] EW_UPDATETEXT, // Update status text: 2 [update str, ui_st_updateflag=?ui_st_updateflag:this] EW_SLEEP, // Sleep: 1 [sleep time in milliseconds] EW_BRINGTOFRONT, // BringToFront: 0 EW_CHDETAILSVIEW, // SetDetailsView: 2 [listaction,buttonaction] // 10 EW_SETFILEATTRIBUTES, // SetFileAttributes: 2 [filename, attributes] EW_CREATEDIR, // Create directory: 2, [path, ?update$INSTDIR] EW_IFFILEEXISTS, // IfFileExists: 3, [file name, jump amount if exists, jump amount if not exists] EW_SETFLAG, // Sets a flag: 2 [id, data] EW_IFFLAG, // If a flag: 4 [on, off, id, new value mask] EW_GETFLAG, // Gets a flag: 2 [output, id] EW_RENAME, // Rename: 3 [old, new, rebootok] EW_GETFULLPATHNAME, // GetFullPathName: 2 [output, input, ?lfn:sfn] EW_SEARCHPATH, // SearchPath: 2 [output, filename] EW_GETTEMPFILENAME, // GetTempFileName: 2 [output, base_dir] // 20 EW_EXTRACTFILE, // File to extract: 6 [overwriteflag, output filename, compressed filedata, filedatetimelow, filedatetimehigh, allow ignore] // overwriteflag: 0x1 = no. 0x0=force, 0x2=try, 0x3=if date is newer EW_DELETEFILE, // Delete File: 2, [filename, rebootok] EW_MESSAGEBOX, // MessageBox: 5,[MB_flags,text,retv1:retv2,moveonretv1:moveonretv2] EW_RMDIR, // RMDir: 2 [path, recursiveflag] EW_STRLEN, // StrLen: 2 [output, input] EW_ASSIGNVAR, // Assign: 4 [variable (0-9) to assign, string to assign, maxlen, startpos] EW_STRCMP, // StrCmp: 5 [str1, str2, jump_if_equal, jump_if_not_equal, case-sensitive?] EW_READENVSTR, // ReadEnvStr/ExpandEnvStrings: 3 [output, string_with_env_variables, IsRead] EW_INTCMP, // IntCmp: 6 [val1, val2, equal, val1<val2, val1>val2, unsigned?] EW_INTOP, // IntOp: 4 [output, input1, input2, op] where op: 0=add, 1=sub, 2=mul, 3=div, 4=bor, 5=band, 6=bxor, 7=bnot input1, 8=lnot input1, 9=lor, 10=land], 11=1%2 // 30 EW_INTFMT, // IntFmt: [output, format, input] EW_PUSHPOP, // Push/Pop/Exchange: 3 [variable/string, ?pop:push, ?exch] EW_FINDWINDOW, // FindWindow: 5, [outputvar, window class,window name, window_parent, window_after] EW_SENDMESSAGE, // SendMessage: 6 [output, hwnd, msg, wparam, lparam, [wparamstring?1:0 | lparamstring?2:0 | timeout<<2] EW_ISWINDOW, // IsWindow: 3 [hwnd, jump_if_window, jump_if_notwindow] EW_GETDLGITEM, // GetDlgItem: 3: [outputvar, dialog, item_id] EW_SETCTLCOLORS, // SerCtlColors: 3: [hwnd, pointer to struct colors] EW_SETBRANDINGIMAGE, // SetBrandingImage: 1: [Bitmap file] EW_CREATEFONT, // CreateFont: 5: [handle output, face name, height, weight, flags] EW_SHOWWINDOW, // ShowWindow: 2: [hwnd, show state] // 40 EW_SHELLEXEC, // ShellExecute program: 4, [shell action, complete commandline, parameters, showwindow] EW_EXECUTE, // Execute program: 3,[complete command line,waitflag,>=0?output errorcode] EW_GETFILETIME, // GetFileTime; 3 [file highout lowout] EW_GETDLLVERSION, // GetDLLVersion: 3 [file highout lowout] EW_REGISTERDLL, // Register DLL: 3,[DLL file name, string ptr of function to call, text to put in display (<0 if none/pass parms), 1 - no unload, 0 - unload] EW_CREATESHORTCUT, // Make Shortcut: 5, [link file, target file, parameters, icon file, iconindex|show mode<<8|hotkey<<16] EW_COPYFILES, // CopyFiles: 3 [source mask, destination location, flags] EW_REBOOT, // Reboot: 0 EW_WRITEINI, // Write INI String: 4, [Section, Name, Value, INI File] EW_READINISTR, // ReadINIStr: 4 [output, section, name, ini_file] // 50 EW_DELREG, // DeleteRegValue/DeleteRegKey: 4, [root key(int), KeyName, ValueName, delkeyonlyifempty]. ValueName is -1 if delete key EW_WRITEREG, // Write Registry value: 5, [RootKey(int),KeyName,ItemName,ItemData,typelen] // typelen=1 for str, 2 for dword, 3 for binary, 0 for expanded str EW_READREGSTR, // ReadRegStr: 5 [output, rootkey(int), keyname, itemname, ==1?int::str] EW_REGENUM, // RegEnum: 5 [output, rootkey, keyname, index, ?key:value] EW_FCLOSE, // FileClose: 1 [handle] EW_FOPEN, // FileOpen: 4 [name, openmode, createmode, outputhandle] EW_FPUTS, // FileWrite: 3 [handle, string, ?int:string] EW_FGETS, // FileRead: 4 [handle, output, maxlen, ?getchar:gets] EW_FSEEK, // FileSeek: 4 [handle, offset, mode, >=0?positionoutput] EW_FINDCLOSE, // FindClose: 1 [handle] // 60 EW_FINDNEXT, // FindNext: 2 [output, handle] EW_FINDFIRST, // FindFirst: 2 [filespec, output, handleoutput] EW_WRITEUNINSTALLER, // WriteUninstaller: 3 [name, offset, icon_size] EW_LOG, // LogText: 2 [0, text] / LogSet: [1, logstate] EW_SECTIONSET, // SectionSetText: 3: [idx, 0, text] // SectionGetText: 3: [idx, 1, output] // SectionSetFlags: 3: [idx, 2, flags] // SectionGetFlags: 3: [idx, 3, output] EW_INSTTYPESET, // InstTypeSetFlags: 3: [idx, 0, flags] // InstTypeGetFlags: 3: [idx, 1, output] // instructions not actually implemented in exehead, but used in compiler. EW_GETLABELADDR, // both of these get converted to EW_ASSIGNVAR EW_GETFUNCTIONADDR, EW_LOCKWINDOW }; #ifdef NSIS_SCRIPT static CCommandPair kCommandPairs[] = { { 0, "Invalid" }, { 0, "Return" }, { 1, "Goto" }, { 0, "Abort" }, { 0, "Quit" }, { 1, "Call" }, { 2, "UpdateSatusText" }, { 1, "Sleep" }, { 0, "BringToFront" }, { 2, "SetDetailsView" }, { 2, "SetFileAttributes" }, { 2, "SetOutPath" }, { 3, "IfFileExists" }, { 2, "SetFlag" }, { 4, "IfFlag" }, { 2, "GetFlag" }, { 3, "Rename" }, { 2, "GetFullPathName" }, { 2, "SearchPath" }, { 2, "GetTempFileName" }, { 6, "File" }, { 2, "Delete" }, { 5, "MessageBox" }, { 2, "RMDir" }, { 2, "StrLen" }, { 4, "StrCpy" }, { 5, "StrCmp" }, { 3, "ReadEnvStr" }, { 6, "IntCmp" }, { 4, "IntOp" }, { 3, "IntFmt" }, { 3, "PushPop" }, { 5, "FindWindow" }, { 6, "SendMessage" }, { 3, "IsWindow" }, { 3, "GetDlgItem" }, { 3, "SerCtlColors" }, { 1, "SetBrandingImage" }, { 5, "CreateFont" }, { 2, "ShowWindow" }, { 4, "ShellExecute" }, { 3, "Execute" }, { 3, "GetFileTime" }, { 3, "GetDLLVersion" }, { 3, "RegisterDLL" }, { 5, "CreateShortCut" }, { 3, "CopyFiles" }, { 0, "Reboot" }, { 4, "WriteINIStr" }, { 4, "ReadINIStr" }, { 4, "DelReg" }, { 5, "WriteReg" }, { 5, "ReadRegStr" }, { 5, "RegEnum" }, { 1, "FileClose" }, { 4, "FileOpen" }, { 3, "FileWrite" }, { 4, "FileRead" }, { 4, "FileSeek" }, { 1, "FindClose" }, { 2, "FindNext" }, { 2, "FindFirst" }, { 3, "WriteUninstaller" }, { 2, "LogText" }, { 3, "Section?etText" }, { 3, "InstType?etFlags" }, { 6, "GetLabelAddr" }, { 2, "GetFunctionAddress" }, { 6, "LockWindow" } }; #endif static const char *kShellStrings[] = { "", "", "SMPROGRAMS", "", "PRINTERS", "DOCUMENTS", "FAVORITES", "SMSTARTUP", "RECENT", "SENDTO", "", "STARTMENU", "", "MUSIC", "VIDEO", "", "DESKTOP", "", "", "NETHOOD", "FONTS", "TEMPLATES", "COMMONSTARTMENU", "COMMONFILES", "COMMON_STARTUP", "COMMON_DESKTOPDIRECTORY", "QUICKLAUNCH", "PRINTHOOD", "LOCALAPPDATA", "ALTSTARTUP", "ALTSTARTUP", "FAVORITES", "INTERNET_CACHE", "COOKIES", "HISTORY", "APPDATA", "WINDIR", "SYSDIR", "PROGRAMFILES", "PICTURES", "PROFILE", "", "", "COMMONFILES", "", "TEMPLATES", "DOCUMENTS", "ADMINTOOLS", "ADMINTOOLS", "", "", "", "", "MUSIC", "PICTURES", "VIDEO", "RESOURCES", "RESOURCES_LOCALIZED", "", "CDBURN_AREA" }; static const int kNumShellStrings = sizeof(kShellStrings) / sizeof(kShellStrings[0]); /* # define CMDLINE 20 // everything before here doesn't have trailing slash removal # define INSTDIR 21 # define OUTDIR 22 # define EXEDIR 23 # define LANGUAGE 24 # define TEMP 25 # define PLUGINSDIR 26 # define HWNDPARENT 27 # define _CLICK 28 # define _OUTDIR 29 */ static const char *kVarStrings[] = { "CMDLINE", "INSTDIR", "OUTDIR", "EXEDIR", "LANGUAGE", "TEMP", "PLUGINSDIR", "EXEPATH", // test it "EXEFILE", // test it "HWNDPARENT", "_CLICK", "_OUTDIR" }; static const int kNumVarStrings = sizeof(kVarStrings) / sizeof(kVarStrings[0]); static AString GetVar(UInt32 index) { AString res = "$"; if (index < 10) res += UIntToString(index); else if (index < 20) { res += "R"; res += UIntToString(index - 10); } else if (index < 20 + kNumVarStrings) res += kVarStrings[index - 20]; else { res += "["; res += UIntToString(index); res += "]"; } return res; } #define NS_SKIP_CODE 252 #define NS_VAR_CODE 253 #define NS_SHELL_CODE 254 #define NS_LANG_CODE 255 #define NS_CODES_START NS_SKIP_CODE static AString GetShellString(int index) { AString res = "$"; if (index < kNumShellStrings) { const char *sz = kShellStrings[index]; if (sz[0] != 0) return res + sz; } res += "SHELL["; res += UIntToString(index); res += "]"; return res; } // Based on Dave Laundon's simplified process_string AString GetNsisString(const AString &s) { AString res; for (int i = 0; i < s.Length();) { unsigned char nVarIdx = s[i++]; if (nVarIdx > NS_CODES_START && i + 2 <= s.Length()) { int nData = s[i++] & 0x7F; unsigned char c1 = s[i++]; nData |= (((int)(c1 & 0x7F)) << 7); if (nVarIdx == NS_SHELL_CODE) res += GetShellString(c1); else if (nVarIdx == NS_VAR_CODE) res += GetVar(nData); else if (nVarIdx == NS_LANG_CODE) res += "NS_LANG_CODE"; } else if (nVarIdx == NS_SKIP_CODE) { if (i < s.Length()) res += s[i++]; } else // Normal char res += (char)nVarIdx; } return res; } UString GetNsisString(const UString &s) { UString res; for (int i = 0; i < s.Length();) { wchar_t nVarIdx = s[i++]; if (nVarIdx > NS_UN_CODES_START && nVarIdx <= NS_UN_CODES_END) { if (i == s.Length()) break; int nData = s[i++] & 0x7FFF; if (nVarIdx == NS_UN_SHELL_CODE) res += GetUnicodeString(GetShellString(nData >> 8)); else if (nVarIdx == NS_UN_VAR_CODE) res += GetUnicodeString(GetVar(nData)); else if (nVarIdx == NS_UN_LANG_CODE) res += L"NS_LANG_CODE"; } else if (nVarIdx == NS_UN_SKIP_CODE) { if (i == s.Length()) break; res += s[i++]; } else // Normal char res += (char)nVarIdx; } return res; } AString CInArchive::ReadString2A(UInt32 pos) const { return GetNsisString(ReadStringA(pos)); } UString CInArchive::ReadString2U(UInt32 pos) const { return GetNsisString(ReadStringU(pos)); } AString CInArchive::ReadString2(UInt32 pos) const { if (IsUnicode) return UnicodeStringToMultiByte(ReadString2U(pos)); else return ReadString2A(pos); } AString CInArchive::ReadString2Qw(UInt32 pos) const { return "\"" + ReadString2(pos) + "\""; } #define DEL_DIR 1 #define DEL_RECURSE 2 #define DEL_REBOOT 4 // #define DEL_SIMPLE 8 static const int kNumEntryParams = 6; struct CEntry { UInt32 Which; UInt32 Params[kNumEntryParams]; AString GetParamsString(int numParams); CEntry() { Which = 0; for (UInt32 j = 0; j < kNumEntryParams; j++) Params[j] = 0; } }; AString CEntry::GetParamsString(int numParams) { AString s; for (int i = 0; i < numParams; i++) { s += " "; UInt32 v = Params[i]; if (v > 0xFFF00000) s += IntToString((Int32)Params[i]); else s += UIntToString(Params[i]); } return s; } #ifdef NSIS_SCRIPT static AString GetRegRootID(UInt32 val) { const char *s; switch(val) { case 0: s = "SHCTX"; break; case 0x80000000: s = "HKCR"; break; case 0x80000001: s = "HKCU"; break; case 0x80000002: s = "HKLM"; break; case 0x80000003: s = "HKU"; break; case 0x80000004: s = "HKPD"; break; case 0x80000005: s = "HKCC"; break; case 0x80000006: s = "HKDD"; break; case 0x80000050: s = "HKPT"; break; case 0x80000060: s = "HKPN"; break; default: return UIntToString(val); break; } return s; } #endif HRESULT CInArchive::ReadEntries(const CBlockHeader &bh) { _posInData = bh.Offset + GetOffset(); AString prefixA; UString prefixU; for (UInt32 i = 0; i < bh.Num; i++) { CEntry e; e.Which = ReadUInt32(); for (UInt32 j = 0; j < kNumEntryParams; j++) e.Params[j] = ReadUInt32(); #ifdef NSIS_SCRIPT if (e.Which != EW_PUSHPOP && e.Which < sizeof(kCommandPairs) / sizeof(kCommandPairs[0])) { const CCommandPair &pair = kCommandPairs[e.Which]; Script += pair.Name; } #endif switch (e.Which) { case EW_CREATEDIR: { if (IsUnicode) { prefixU.Empty(); prefixU = ReadString2U(e.Params[0]); } else { prefixA.Empty(); prefixA = ReadString2A(e.Params[0]); } #ifdef NSIS_SCRIPT Script += " "; if (IsUnicode) Script += UnicodeStringToMultiByte(prefixU); else Script += prefixA; #endif break; } case EW_EXTRACTFILE: { CItem item; item.IsUnicode = IsUnicode; if (IsUnicode) { item.PrefixU = prefixU; item.NameU = ReadString2U(e.Params[1]); } else { item.PrefixA = prefixA; item.NameA = ReadString2A(e.Params[1]); } /* UInt32 overwriteFlag = e.Params[0]; */ item.Pos = e.Params[2]; item.MTime.dwLowDateTime = e.Params[3]; item.MTime.dwHighDateTime = e.Params[4]; /* UInt32 allowIgnore = e.Params[5]; */ if (Items.Size() > 0) { /* if (item.Pos == Items.Back().Pos) continue; */ } Items.Add(item); #ifdef NSIS_SCRIPT Script += " "; if (IsUnicode) Script += UnicodeStringToMultiByte(item.NameU); else Script += item.NameA; #endif break; } #ifdef NSIS_SCRIPT case EW_UPDATETEXT: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += UIntToString(e.Params[1]); break; } case EW_SETFILEATTRIBUTES: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += UIntToString(e.Params[1]); break; } case EW_IFFILEEXISTS: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += UIntToString(e.Params[1]); Script += " "; Script += UIntToString(e.Params[2]); break; } case EW_RENAME: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); Script += " "; Script += UIntToString(e.Params[2]); break; } case EW_GETFULLPATHNAME: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); Script += " "; Script += UIntToString(e.Params[2]); break; } case EW_SEARCHPATH: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); break; } case EW_GETTEMPFILENAME: { AString s; Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); break; } case EW_DELETEFILE: { UInt64 flag = e.Params[1]; if (flag != 0) { Script += " "; if (flag == DEL_REBOOT) Script += "/REBOOTOK"; else Script += UIntToString(e.Params[1]); } Script += " "; Script += ReadString2(e.Params[0]); break; } case EW_RMDIR: { UInt64 flag = e.Params[1]; if (flag != 0) { if ((flag & DEL_REBOOT) != 0) Script += " /REBOOTOK"; if ((flag & DEL_RECURSE) != 0) Script += " /r"; } Script += " "; Script += ReadString2(e.Params[0]); break; } case EW_STRLEN: { Script += " "; Script += GetVar(e.Params[0]);; Script += " "; Script += ReadString2Qw(e.Params[1]); break; } case EW_ASSIGNVAR: { Script += " "; Script += GetVar(e.Params[0]);; Script += " "; Script += ReadString2Qw(e.Params[1]); AString maxLen, startOffset; if (e.Params[2] != 0) maxLen = ReadString2(e.Params[2]); if (e.Params[3] != 0) startOffset = ReadString2(e.Params[3]); if (!maxLen.IsEmpty() || !startOffset.IsEmpty()) { Script += " "; if (maxLen.IsEmpty()) Script += "\"\""; else Script += maxLen; if (!startOffset.IsEmpty()) { Script += " "; Script += startOffset; } } break; } case EW_STRCMP: { Script += " "; Script += " "; Script += ReadString2Qw(e.Params[0]); Script += " "; Script += ReadString2Qw(e.Params[1]); for (int j = 2; j < 5; j++) { Script += " "; Script += UIntToString(e.Params[j]); } break; } case EW_INTCMP: { if (e.Params[5] != 0) Script += "U"; Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); for (int i = 2; i < 5; i++) { Script += " "; Script += UIntToString(e.Params[i]); } break; } case EW_INTOP: { Script += " "; Script += GetVar(e.Params[0]); Script += " "; int numOps = 2; AString op; switch (e.Params[3]) { case 0: op = '+'; break; case 1: op = '-'; break; case 2: op = '*'; break; case 3: op = '/'; break; case 4: op = '|'; break; case 5: op = '&'; break; case 6: op = '^'; break; case 7: op = '~'; numOps = 1; break; case 8: op = '!'; numOps = 1; break; case 9: op = "||"; break; case 10: op = "&&"; break; case 11: op = '%'; break; default: op = UIntToString(e.Params[3]); } AString p1 = ReadString2(e.Params[1]); if (numOps == 1) { Script += op; Script += p1; } else { Script += p1; Script += " "; Script += op; Script += " "; Script += ReadString2(e.Params[2]); } break; } case EW_PUSHPOP: { int isPop = (e.Params[1] != 0); if (isPop) { Script += "Pop"; Script += " "; Script += GetVar(e.Params[0]);; } else { int isExch = (e.Params[2] != 0); if (isExch) { Script += "Exch"; } else { Script += "Push"; Script += " "; Script += ReadString2(e.Params[0]); } } break; } case EW_SENDMESSAGE: { // SendMessage: 6 [output, hwnd, msg, wparam, lparam, [wparamstring?1:0 | lparamstring?2:0 | timeout<<2] Script += " "; // Script += ReadString2(e.Params[0]); // Script += " "; Script += ReadString2(e.Params[1]); Script += " "; Script += ReadString2(e.Params[2]); Script += " "; UInt32 spec = e.Params[5]; // if (spec & 1) Script += IntToString(e.Params[3]); // else // Script += ReadString2(e.Params[3]); Script += " "; // if (spec & 2) Script += IntToString(e.Params[4]); // else // Script += ReadString2(e.Params[4]); if ((Int32)e.Params[0] >= 0) { Script += " "; Script += GetVar(e.Params[1]); } spec >>= 2; if (spec != 0) { Script += " /TIMEOUT="; Script += IntToString(spec); } break; } case EW_GETDLGITEM: { Script += " "; Script += GetVar(e.Params[0]);; Script += " "; Script += ReadString2(e.Params[1]); Script += " "; Script += ReadString2(e.Params[2]); break; } case EW_REGISTERDLL: { Script += " "; Script += ReadString2(e.Params[0]); Script += " "; Script += ReadString2(e.Params[1]); Script += " "; Script += UIntToString(e.Params[2]); break; } case EW_CREATESHORTCUT: { AString s; Script += " "; Script += ReadString2Qw(e.Params[0]); Script += " "; Script += ReadString2Qw(e.Params[1]); for (int j = 2; j < 5; j++) { Script += " "; Script += UIntToString(e.Params[j]); } break; } /* case EW_DELREG: { AString keyName, valueName; keyName = ReadString2(e.Params[1]); bool isValue = (e.Params[2] != -1); if (isValue) { valueName = ReadString2(e.Params[2]); Script += "Key"; } else Script += "Value"; Script += " "; Script += UIntToString(e.Params[0]); Script += " "; Script += keyName; if (isValue) { Script += " "; Script += valueName; } Script += " "; Script += UIntToString(e.Params[3]); break; } */ case EW_WRITEREG: { AString s; switch(e.Params[4]) { case 1: s = "Str"; break; case 2: s = "ExpandStr"; break; case 3: s = "Bin"; break; case 4: s = "DWORD"; break; default: s = "?" + UIntToString(e.Params[4]); break; } Script += s; Script += " "; Script += GetRegRootID(e.Params[0]); Script += " "; AString keyName, valueName; keyName = ReadString2Qw(e.Params[1]); Script += keyName; Script += " "; valueName = ReadString2Qw(e.Params[2]); Script += valueName; Script += " "; valueName = ReadString2Qw(e.Params[3]); Script += valueName; Script += " "; break; } case EW_WRITEUNINSTALLER: { Script += " "; Script += ReadString2(e.Params[0]); for (int j = 1; j < 3; j++) { Script += " "; Script += UIntToString(e.Params[j]); } break; } default: { int numParams = kNumEntryParams; if (e.Which < sizeof(kCommandPairs) / sizeof(kCommandPairs[0])) { const CCommandPair &pair = kCommandPairs[e.Which]; // Script += pair.Name; numParams = pair.NumParams; } else { Script += "Unknown"; Script += UIntToString(e.Which); } Script += e.GetParamsString(numParams); } #endif } #ifdef NSIS_SCRIPT Script += kCrLf; #endif } { Items.Sort(CompareItems, 0); int i; // if (IsSolid) for (i = 0; i + 1 < Items.Size();) { bool sameName = IsUnicode ? (Items[i].NameU == Items[i + 1].NameU) : (Items[i].NameA == Items[i + 1].NameA); if (Items[i].Pos == Items[i + 1].Pos && (IsSolid || sameName)) Items.Delete(i + 1); else i++; } for (i = 0; i + 1 < Items.Size(); i++) { CItem &item = Items[i]; item.EstimatedSizeIsDefined = true; item.EstimatedSize = Items[i + 1].Pos - item.Pos - 4; } if (!IsSolid) { for (i = 0; i < Items.Size(); i++) { CItem &item = Items[i]; RINOK(_stream->Seek(GetPosOfNonSolidItem(i), STREAM_SEEK_SET, NULL)); const UInt32 kSigSize = 4 + 1 + 5; BYTE sig[kSigSize]; size_t processedSize = kSigSize; RINOK(ReadStream(_stream, sig, &processedSize)); if (processedSize < 4) return S_FALSE; UInt32 size = Get32(sig); if ((size & 0x80000000) != 0) { item.IsCompressed = true; // is compressed; size &= ~0x80000000; if (Method == NMethodType::kLZMA) { if (processedSize < 9) return S_FALSE; if (FilterFlag) item.UseFilter = (sig[4] != 0); item.DictionarySize = Get32(sig + 5 + (FilterFlag ? 1 : 0)); } } else { item.IsCompressed = false; item.Size = size; item.SizeIsDefined = true; } item.CompressedSize = size; item.CompressedSizeIsDefined = true; } } } return S_OK; } HRESULT CInArchive::Parse() { // UInt32 offset = ReadUInt32(); // ???? offset == FirstHeader.HeaderLength /* UInt32 ehFlags = */ ReadUInt32(); CBlockHeader bhPages, bhSections, bhEntries, bhStrings, bhLangTables, bhCtlColors, bhData; // CBlockHeader bgFont; ReadBlockHeader(bhPages); ReadBlockHeader(bhSections); ReadBlockHeader(bhEntries); ReadBlockHeader(bhStrings); ReadBlockHeader(bhLangTables); ReadBlockHeader(bhCtlColors); // ReadBlockHeader(bgFont); ReadBlockHeader(bhData); _stringsPos = bhStrings.Offset; UInt32 pos = GetOffset() + _stringsPos; int numZeros0 = 0; int numZeros1 = 0; int i; const int kBlockSize = 256; for (i = 0; i < kBlockSize; i++) { if (pos >= _size || pos + 1 >= _size) break; char c0 = _data[pos++]; char c1 = _data[pos++]; wchar_t c = (c0 | ((wchar_t)c1 << 8)); if (c >= NS_UN_CODES_START && c < NS_UN_CODES_END) { if (pos >= _size || pos + 1 >= _size) break; pos += 2; numZeros1++; } else { if (c0 == 0 && c1 != 0) numZeros0++; if (c1 == 0) numZeros1++; } // printf("\nnumZeros0 = %2x %2x", _data[pos + 0], _data[pos + 1]); } IsUnicode = (numZeros1 > numZeros0 * 3 + kBlockSize / 16); // printf("\nnumZeros0 = %3d numZeros1 = %3d", numZeros0, numZeros1); return ReadEntries(bhEntries); } static bool IsLZMA(const Byte *p, UInt32 &dictionary) { dictionary = Get32(p + 1); return (p[0] == 0x5D && p[1] == 0x00 && p[2] == 0x00 && p[5] == 0x00); } static bool IsLZMA(const Byte *p, UInt32 &dictionary, bool &thereIsFlag) { if (IsLZMA(p, dictionary)) { thereIsFlag = false; return true; } if (IsLZMA(p + 1, dictionary)) { thereIsFlag = true; return true; } return false; } HRESULT CInArchive::Open2( DECL_EXTERNAL_CODECS_LOC_VARS2 ) { RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &StreamOffset)); const UInt32 kSigSize = 4 + 1 + 5 + 1; // size, flag, lzma props, lzma first byte BYTE sig[kSigSize]; RINOK(ReadStream_FALSE(_stream, sig, kSigSize)); UInt64 position; RINOK(_stream->Seek(StreamOffset, STREAM_SEEK_SET, &position)); _headerIsCompressed = true; IsSolid = true; FilterFlag = false; UInt32 compressedHeaderSize = Get32(sig); if (compressedHeaderSize == FirstHeader.HeaderLength) { _headerIsCompressed = false; IsSolid = false; Method = NMethodType::kCopy; } else if (IsLZMA(sig, DictionarySize, FilterFlag)) { Method = NMethodType::kLZMA; } else if (IsLZMA(sig + 4, DictionarySize, FilterFlag)) { IsSolid = false; Method = NMethodType::kLZMA; } else if (sig[3] == 0x80) { IsSolid = false; Method = NMethodType::kDeflate; } else { Method = NMethodType::kDeflate; } _posInData = 0; if (!IsSolid) { _headerIsCompressed = ((compressedHeaderSize & 0x80000000) != 0); if (_headerIsCompressed) compressedHeaderSize &= ~0x80000000; _nonSolidStartOffset = compressedHeaderSize; RINOK(_stream->Seek(StreamOffset + 4, STREAM_SEEK_SET, NULL)); } UInt32 unpackSize = FirstHeader.HeaderLength; if (_headerIsCompressed) { // unpackSize = (1 << 23); _data.SetCapacity(unpackSize); RINOK(Decoder.Init( EXTERNAL_CODECS_LOC_VARS _stream, Method, FilterFlag, UseFilter)); size_t processedSize = unpackSize; RINOK(Decoder.Read(_data, &processedSize)); if (processedSize != unpackSize) return S_FALSE; _size = processedSize; if (IsSolid) { UInt32 size2 = ReadUInt32(); if (size2 < _size) _size = size2; } } else { _data.SetCapacity(unpackSize); _size = (size_t)unpackSize; RINOK(ReadStream_FALSE(_stream, (Byte *)_data, unpackSize)); } return Parse(); } /* NsisExe = { ExeStub Archive // must start from 512 * N #ifndef NSIS_CONFIG_CRC_ANAL { Some additional data } } Archive { FirstHeader Data #ifdef NSIS_CONFIG_CRC_SUPPORT && FirstHeader.ThereIsCrc() { CRC } } FirstHeader { UInt32 Flags; Byte Signature[16]; // points to the header+sections+entries+stringtable in the datablock UInt32 HeaderLength; UInt32 ArchiveSize; } */ HRESULT CInArchive::Open( DECL_EXTERNAL_CODECS_LOC_VARS IInStream *inStream, const UInt64 *maxCheckStartPosition) { Clear(); RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL)); UInt64 maxSize = ((maxCheckStartPosition != 0) ? *maxCheckStartPosition : 0); const UInt32 kStep = 512; Byte buffer[kStep]; UInt64 position = 0; for (; position <= maxSize; position += kStep) { RINOK(ReadStream_FALSE(inStream, buffer, kStep)); if (memcmp(buffer + 4, kSignature, kSignatureSize) == 0) break; } if (position > maxSize) return S_FALSE; const UInt32 kStartHeaderSize = 4 * 7; RINOK(inStream->Seek(0, STREAM_SEEK_END, &_archiveSize)); RINOK(inStream->Seek(position + kStartHeaderSize, STREAM_SEEK_SET, 0)); FirstHeader.Flags = Get32(buffer); FirstHeader.HeaderLength = Get32(buffer + kSignatureSize + 4); FirstHeader.ArchiveSize = Get32(buffer + kSignatureSize + 8); if (_archiveSize - position < FirstHeader.ArchiveSize) return S_FALSE; try { _stream = inStream; HRESULT res = Open2(EXTERNAL_CODECS_LOC_VARS2); if (res != S_OK) Clear(); _stream.Release(); return res; } catch(...) { Clear(); return S_FALSE; } } void CInArchive::Clear() { #ifdef NSIS_SCRIPT Script.Empty(); #endif Items.Clear(); _stream.Release(); } }}
[ "[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d" ]
[ [ [ 1, 1439 ] ] ]
cc7bfe329abb46dcba7113dd2f74f73bd0ce9889
d4b316c5dfe18916d6747e564a6bb8e814d4413a
/date_checker/kupjak/graphic_proj2/graphic_proj2/spline.h
41a83cbd9ed831e585794a85984aeaf7ba6e6443
[]
no_license
artemshynkarenko/ilsdev
3c8b485beb66cd9d33c9b844758bf2e79c5ea94f
e6cc62f14aae409cc1e462ba03b8dcb2c1a6aa02
refs/heads/master
2016-09-06T08:30:25.052724
2009-06-19T16:35:14
2009-06-19T16:35:14
32,579,868
0
0
null
null
null
null
UTF-8
C++
false
false
345
h
#pragma once #include <limits> class cubic_spline { private: struct spline_tuple{ double a, b, c, d, x; }; spline_tuple *splines; std::size_t n; void free_mem(); public: cubic_spline(); ~cubic_spline(); void build_spline(const double *x, const double *y, std::size_t n); double f(double x) const; };
[ "kupjak@0d0ad13b-7e51-0410-977d-d3f3eabcdc60" ]
[ [ [ 1, 24 ] ] ]
836e6aa3e80c2143bc88cd5b2d0ce5fae088dec1
db93a4d93dbeecef7a35d2b5c6833c1482b3fc63
/MastersThesis/ImageAnnotator/ImageAnnotator.cpp
0d7466d270a079d9b541fc6e3c562b1a493ea3c2
[]
no_license
schiappino/my-masters-thesis
d71bed348cfcd5587b7cb5b29b825eee4570ca01
b58c7e977c55ad90994d346cdbc23365c3439c9d
refs/heads/master
2021-01-10T04:06:25.661663
2011-12-01T22:21:47
2011-12-01T22:21:47
50,738,346
0
0
null
null
null
null
UTF-8
C++
false
false
2,136
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/features2d/features2d.hpp> using namespace std; using namespace cv; vector <string> imgFileList; Mat img; int imIt = 0; Point origin; const string colorFeretDB_fa = "../data/facedb/color feret/filelist_fa.txt", groundTruthXml = "00279_940422_fa.xml", wndName = "Image Annotator"; bool loadFileList( const string fileName ) { ifstream in; string line; in.open( fileName ); if( !in ) { cout << "--(!) Cannot read input file list" << endl; return false; } while( !in.eof() ) { getline(in, line ); imgFileList.push_back( line ); } if( imgFileList.size() > 0 ) return true; else { cout << "--(!) Cannot read input file list" << endl; return false; } } void drawPoint( Mat img, Point pt ) { Scalar color = CV_RGB(0,255,0); int r = 10; circle( img, pt, r, color ); Point vertic1 = Point( pt.x, pt.y - r ), vertic2 = Point( pt.x, pt.y + r ), horizo1 = Point( pt.x - r, pt.y ), horizo2 = Point( pt.x + r, pt.y ); line( img, vertic1, vertic2, color ); line( img, horizo1, horizo2, color ); } void onMouse( int event, int x, int y, int, void* ) { switch( event ) { case CV_EVENT_LBUTTONDOWN: origin = Point(x,y); cout << origin << endl; drawPoint( img, origin ); break; case CV_EVENT_LBUTTONUP: break; } } int main( int argc, char** argv ) { bool isFileLoaded = loadFileList( colorFeretDB_fa ); if ( !isFileLoaded ) return -1; namedWindow( wndName, CV_GUI_EXPANDED ); setMouseCallback( wndName, onMouse, 0 ); img = imread( imgFileList.at( imgFileList.size()-100 ), CV_LOAD_IMAGE_COLOR ); bool finish = true; char c; while (!finish) { imshow( wndName, img ); c = waitKey(1); if ( c == 27 ) finish = true; } FileStorage fs; fs.open( groundTruthXml, FileStorage::READ ); return 0; }
[ [ [ 1, 99 ] ] ]
23f944255f0a891e86d92f6ee64c811c3e5080c6
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/Syssetup.cpp
3560932e2c52c1b20cc1724042042b637c78e4f5
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
UTF-8
C++
false
false
3,857
cpp
// Syssetup.cpp : implementation file //tel:13366898744 #include "stdafx.h" #include "CTaiShanApp.h" #include "Syssetup.h" #include "CTaiShanDoc.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNCREATE(CSYSSETUP, CPropertyPage) CSYSSETUP::CSYSSETUP() : CPropertyPage(CSYSSETUP::IDD) { //{{AFX_DATA_INIT(CSYSSETUP) m_AlarmSound = FALSE; m_AutoOrganizeData = FALSE; m_autoclose = FALSE; m_autoday = FALSE; m_showxline = FALSE; m_showyline = FALSE; m_autosavezb = FALSE; m_cjmxyester = FALSE; m_tjxgpower = FALSE; m_showinfohq = FALSE; m_startalert = FALSE; m_volpower = FALSE; m_backpower = FALSE; m_autominute = FALSE; m_kline = -1; m_fourgraph = -1; //}}AFX_DATA_INIT pDoc =CMainFrame::m_taiShanDoc; m_autoclose=pDoc->m_systemOption.autoclose; m_autominute=pDoc->m_systemOption.autominute; m_autoday=pDoc->m_systemOption.autoday; m_showxline=pDoc->m_systemOption.showxline; m_showyline=pDoc->m_systemOption.showyline; m_AlarmSound=pDoc->m_systemOption.alarmsound; m_AutoOrganizeData=pDoc->m_systemOption.organizedata; m_tjxgpower=pDoc->m_propertyInitiate.bDoPowerSelectingStock; m_volpower=pDoc->m_propertyInitiate.bDoVolPowering; m_backpower=pDoc->m_propertyInitiate.bDoPowerAfter; m_autosavezb=pDoc->m_propertyInitiate.bSaveParam; m_showinfohq=pDoc->m_propertyInitiate.bShowCrossDlg; m_startalert=pDoc->m_propertyInitiate.bRunAlarmBegin; m_cjmxyester=pDoc->m_propertyInitiate.bUseMin5ChenBen; m_kline=pDoc->m_systemOption.kline; m_fourgraph=pDoc->m_systemOption.fourgraph; } CSYSSETUP::~CSYSSETUP() { } void CSYSSETUP::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CSYSSETUP) DDX_Check(pDX, IDC_ALARM_SOUND, m_AlarmSound); DDX_Check(pDX, IDC_AUTO_ORGANIZEDATA, m_AutoOrganizeData); DDX_Check(pDX, IDC_AUTOCLOSE, m_autoclose); DDX_Check(pDX, IDC_AUTODAY, m_autoday); DDX_Check(pDX, IDC_SHOWXLINE, m_showxline); DDX_Check(pDX, IDC_SHOWYLINE, m_showyline); DDX_Check(pDX, IDC_SYSSET_AUTOSAVEZHIBIAO, m_autosavezb); DDX_Check(pDX, IDC_SYSSET_HSTODAYADDLAST, m_cjmxyester); DDX_Check(pDX, IDC_SYSSET_POWERSELECTSTOCK, m_tjxgpower); DDX_Check(pDX, IDC_SYSSET_SHOWINFOCROSS, m_showinfohq); DDX_Check(pDX, IDC_SYSSET_STARTALERT, m_startalert); DDX_Check(pDX, IDC_SYSSET_VOLPOWER, m_volpower); DDX_Check(pDX, IDC_BACKPOWER, m_backpower); DDX_Check(pDX, IDC_AUTOMINUTE, m_autominute); DDX_Radio(pDX, IDC_RADIO3, m_kline); DDX_Radio(pDX, IDC_RADIO4T, m_fourgraph); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CSYSSETUP, CPropertyPage) //{{AFX_MSG_MAP(CSYSSETUP) ON_WM_HELPINFO() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// BOOL CSYSSETUP::OnInitDialog() { CPropertyPage::OnInitDialog(); #ifdef WIDE_NET_VERSION GetDlgItem(IDC_AUTOMINUTE)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_AUTOMINUTE))->SetCheck(0); GetDlgItem(IDC_AUTODAY)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_AUTODAY))->SetCheck(0); GetDlgItem(IDC_ALARM_SOUND)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_ALARM_SOUND))->SetCheck(0); GetDlgItem(IDC_AUTO_ORGANIZEDATA)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_AUTO_ORGANIZEDATA))->SetCheck(0); GetDlgItem(IDC_SYSSET_STARTALERT)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_SYSSET_STARTALERT))->SetCheck(0); GetDlgItem(IDC_AUTOCLOSE)->EnableWindow(FALSE); ((CButton*)GetDlgItem(IDC_AUTOCLOSE))->SetCheck(0); #endif return TRUE; } BOOL CSYSSETUP::OnHelpInfo(HELPINFO* pHelpInfo) { DoHtmlHelp(this);return TRUE; }
[ [ [ 1, 129 ] ] ]
528c47f359f748e2bd88cd3c87f79461500a1ecf
6d680e20e4a703f0aa0d4bb5e50568143241f2d5
/src/MobiHealth/moc_PatientItemWidget.cpp
8ac326184fdd4b0ae553553d0dcfff29d4f007df
[]
no_license
sirnicolaz/MobiHealt
f7771e53a4a80dcea3d159eca729e9bd227e8660
bbfd61209fb683d5f75f00bbf81b24933922baac
refs/heads/master
2021-01-20T12:21:17.215536
2010-04-21T14:21:16
2010-04-21T14:21:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,522
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'PatientItemWidget.h' ** ** Created: Sun Apr 11 11:47:59 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "PatientItemWidget.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'PatientItemWidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_PatientItemWidget[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 19, 18, 18, 18, 0x08, 0 // eod }; static const char qt_meta_stringdata_PatientItemWidget[] = { "PatientItemWidget\0\0selectPatientButtonSlot()\0" }; const QMetaObject PatientItemWidget::staticMetaObject = { { &QFrame::staticMetaObject, qt_meta_stringdata_PatientItemWidget, qt_meta_data_PatientItemWidget, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &PatientItemWidget::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *PatientItemWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *PatientItemWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_PatientItemWidget)) return static_cast<void*>(const_cast< PatientItemWidget*>(this)); return QFrame::qt_metacast(_clname); } int PatientItemWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QFrame::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: selectPatientButtonSlot(); break; default: ; } _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ [ [ 1, 79 ] ] ]