text
stringlengths
1
1.05M
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC/GEOS MODULE: fades FILE: fades.asm AUTHOR: Gene Anderson, Sep 11, 1991 REVISION HISTORY: Name Date Description ---- ---- ----------- Gene 9/11/91 Initial revision DESCRIPTION: fades & wipes specific screen-saver library $Id: fades.asm,v 1.1 97/04/04 16:44:53 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include stdapp.def include timer.def include initfile.def UseLib ui.def UseLib saver.def ;============================================================================== ; ; CONSTANTS AND DATA TYPES ; ;============================================================================== include fades.def ;============================================================================= ; ; OBJECT CLASSES ; ;============================================================================= FadesApplicationClass class SaverApplicationClass MSG_FADES_APP_DRAW message ; ; Start drawing the fade (sent by timer). ; ; Pass: nothing ; Return: nothing ; FAI_speed word SAVER_FADE_MEDIUM_SPEED FAI_type word FADE_WIPE_TO_0000 FAI_timerHandle hptr 0 noreloc FAI_timerHandle FAI_timerID word 0 FadesApplicationClass endc FadesProcessClass class GenProcessClass FadesProcessClass endc ;============================================================================== ; ; VARIABLES ; ;============================================================================== include fades.rdef ForceRef FadesApp udata segment udata ends idata segment FadesProcessClass mask CLASSF_NEVER_SAVED FadesApplicationClass idata ends FadesCode segment resource .warn -private fadesOptionTable SAOptionTable < fadesCategory, length fadesOptions > fadesOptions SAOptionDesc < fadesSpeedKey, size FAI_speed, offset FAI_speed >, < fadesTypeKey, size FAI_type, offset FAI_type > .warn @private fadesCategory char 'fades', 0 fadesSpeedKey char 'speed', 0 fadesTypeKey char 'type', 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FadesLoadOptions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Load our options from the ini file. CALLED BY: MSG_META_LOAD_OPTIONS PASS: *ds:si = FadesApplicationClass object RETURN: nothing DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- stevey 12/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FadesLoadOptions method dynamic FadesApplicationClass, MSG_META_LOAD_OPTIONS uses ax, es .enter segmov es, cs mov bx, offset fadesOptionTable call SaverApplicationGetOptions .leave mov di, offset FadesApplicationClass GOTO ObjCallSuperNoLock FadesLoadOptions endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FadesAppSetWin %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Record the window & gstate to use, and start things going. CALLED BY: MSG_SAVER_APP_SET_WIN PASS: *ds:si = FadesApplicationClass object dx = window bp = gstate RETURN: nothing DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- stevey 12/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FadesAppSetWin method dynamic FadesApplicationClass, MSG_SAVER_APP_SET_WIN ; ; Let the superclass do its little thing. ; mov di, offset FadesApplicationClass call ObjCallSuperNoLock ; ; Do the fade. ; mov di, ds:[si] add di, ds:[di].FadesApplication_offset call FadesStart ret FadesAppSetWin endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FadesAppGetWinColor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Makes sure the window is transparent. CALLED BY: MSG_SAVER_APP_GET_WIN_COLOR PASS: *ds:si = FadesApplicationClass object ds:di = FadesApplicationClass instance data RETURN: ax = WinColorFlags DESTROYED: nothing PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- stevey 12/20/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FadesAppGetWinColor method dynamic FadesApplicationClass, MSG_SAVER_APP_GET_WIN_COLOR ; ; Let the superclass do its thing. ; mov di, offset FadesApplicationClass call ObjCallSuperNoLock ornf ah, mask WCF_TRANSPARENT ret FadesAppGetWinColor endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FadesStart %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Start saving the screen in our own little way CALLED BY: FadesAppSetWin PASS: ds:[di] = FadesApplicationInstance RETURN: nothing DESTROYED: everything PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- stevey 12/20/92 port to 2.0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FadesStart proc near class FadesApplicationClass ; ; We fade to black ; mov bp, di ; bp = instance data mov di, ds:[di].SAI_curGState mov ax, C_BLACK or (CF_INDEX shl 8) call GrSetAreaColor mov di, bp ; di = instance data ; ; Fade me jesus ; clrdw axbx ; window left & top mov cx, ds:[di].SAI_bounds.R_right ; cx <- window right mov dx, ds:[di].SAI_bounds.R_bottom ; dx <- window bottom mov si, ds:[di].FAI_type ; si <- FadeTypes cmp si, FADE_WIPE_TO_LTRB jbe doFadeWipe ; ; A "normal" fade or wipe -- table drive it... ; sub si, FADE_WIPE_TO_LTRB+1 shl si, 1 ; table of words mov bp, cs:fadeRoutines[si] ; bp <- routine to call mov si, ds:[di].FAI_speed ; si <- SaverFadeSpeeds mov di, ds:[di].SAI_curGState ; di = gstate call bp done: ret doFadeWipe: mov bp, ds:[di].FAI_type ; bp <- SaverWipeTypes mov si, ds:[di].FAI_speed ; si <- SaverFadeSpeeds mov di, ds:[di].SAI_curGState ; di = gstate call SaverFadeWipe jmp short done FadesStart endp CheckHack <FADE_WIPE_TO_0000 eq 0> CheckHack <FADE_WIPE_TO_LTRB eq 15> CheckHack <FADE_PATTERN eq 16> fadeRoutines nptr \ FadePatternFade FadePatternFade proc near call SaverFadePatternFade ret FadePatternFade endp FadesCode ends
// N64 Exception Test arch n64.cpu endian msb output "ExceptionTest.N64", create // 1024 KB + 4 KB = 1028 KB fill $0010'1000 // Set ROM Size origin $00000000 base $80000000 include "../LIB/N64.INC" include "../LIB/A64.INC" include "N64_Header.asm" insert "../LIB/N64_BOOTCODE.BIN" constant fb1($A010'0000) Start: // NOTE: base $80001000 init() nop nop ScreenNTSC(320,240, BPP16, fb1) // 153,600 = 0x2'5800 nop nop nop la t0, eret_inst lw t0, 0(t0) lui t1, 0x8000 sw t0, 0(t1) addi t1, t1, 0x0180 sw t0, 0(t1) nop nop //la t0, 0x7000'0000 //sw r0, 0(t0) nop nop mfc0 t0, Count li t1, 0x100000 add t0, t1, t0 mtc0 t0, Compare nop nop mfc0 t0, Status ori t1, r0, 0xFF01 or t0, t0, t1 mtc0 t0, Status nop nop nop nop Loop: // while(true); j Loop nop nop nop eret_inst: eret
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x1a609, %rcx clflush (%rcx) nop nop nop xor $12716, %rbp mov $0x6162636465666768, %rsi movq %rsi, (%rcx) nop nop add $59137, %rdi lea addresses_WC_ht+0x14ec9, %rsi lea addresses_WC_ht+0x14fb1, %rdi nop nop nop nop add $1547, %r12 mov $75, %rcx rep movsq xor $24392, %rcx lea addresses_WC_ht+0x3dc9, %r10 sub $6150, %rsi movb (%r10), %r12b nop sub $27178, %rdi lea addresses_UC_ht+0x1a7c9, %rsi lea addresses_D_ht+0x16cc9, %rdi cmp %rbp, %rbp mov $73, %rcx rep movsb nop sub $25574, %rdi lea addresses_UC_ht+0xdbc9, %rsi lea addresses_WC_ht+0x843d, %rdi nop nop nop inc %rbx mov $64, %rcx rep movsl nop nop nop nop nop xor %rbx, %rbx lea addresses_WC_ht+0x8204, %rcx clflush (%rcx) inc %r10 mov $0x6162636465666768, %rsi movq %rsi, %xmm6 vmovups %ymm6, (%rcx) nop nop nop and $3801, %rcx lea addresses_UC_ht+0xf519, %rcx clflush (%rcx) nop nop nop nop add $29150, %r12 movb $0x61, (%rcx) nop and %r12, %r12 pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_WT+0x334d, %rsi lea addresses_normal+0x13c27, %rdi nop nop nop cmp $10339, %r13 mov $89, %rcx rep movsw sub %r13, %r13 // Load lea addresses_UC+0x111c9, %rdi dec %rdx mov (%rdi), %r15 nop nop sub $59038, %rdi // Store lea addresses_normal+0x57c9, %r13 nop nop nop nop xor $7765, %r9 movl $0x51525354, (%r13) nop nop nop xor $6948, %r13 // Store lea addresses_D+0x91c9, %r13 nop nop nop dec %rsi mov $0x5152535455565758, %rdx movq %rdx, (%r13) nop nop nop nop nop cmp %r13, %r13 // Store lea addresses_PSE+0x13169, %rcx nop nop nop and %rdi, %rdi movw $0x5152, (%rcx) nop mfence // REPMOV lea addresses_RW+0xc7c9, %rsi lea addresses_UC+0x5a91, %rdi nop nop nop and $5159, %rax mov $39, %rcx rep movsl nop nop nop add %r13, %r13 // Store lea addresses_WT+0x6fc9, %rdx nop xor $48469, %rsi mov $0x5152535455565758, %r13 movq %r13, %xmm0 vmovups %ymm0, (%rdx) xor %rcx, %rcx // Store lea addresses_RW+0x9605, %rsi nop nop nop cmp $32453, %rcx mov $0x5152535455565758, %rdx movq %rdx, %xmm2 vmovups %ymm2, (%rsi) and %rsi, %rsi // Faulty Load lea addresses_D+0x17fc9, %r15 clflush (%r15) nop nop nop nop sub %rdx, %rdx mov (%r15), %r9 lea oracles, %rsi and $0xff, %r9 shlq $12, %r9 mov (%rsi,%r9,1), %r9 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal', 'congruent': 0, 'same': False}} {'src': {'type': 'addresses_UC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 5}} {'src': {'type': 'addresses_RW', 'congruent': 4, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC', 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 6}} {'src': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 4}} {'36': 21} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
//===--- ModernizeTidyModule.cpp - clang-tidy -----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "AvoidBindCheck.h" #include "AvoidCArraysCheck.h" #include "ConcatNestedNamespacesCheck.h" #include "DeprecatedHeadersCheck.h" #include "DeprecatedIosBaseAliasesCheck.h" #include "LoopConvertCheck.h" #include "MacroToEnumCheck.h" #include "MakeSharedCheck.h" #include "MakeUniqueCheck.h" #include "PassByValueCheck.h" #include "RawStringLiteralCheck.h" #include "RedundantVoidArgCheck.h" #include "ReplaceAutoPtrCheck.h" #include "ReplaceDisallowCopyAndAssignMacroCheck.h" #include "ReplaceRandomShuffleCheck.h" #include "ReturnBracedInitListCheck.h" #include "ShrinkToFitCheck.h" #include "UnaryStaticAssertCheck.h" #include "UseAutoCheck.h" #include "UseBoolLiteralsCheck.h" #include "UseDefaultMemberInitCheck.h" #include "UseEmplaceCheck.h" #include "UseEqualsDefaultCheck.h" #include "UseEqualsDeleteCheck.h" #include "UseNodiscardCheck.h" #include "UseNoexceptCheck.h" #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" #include "UseTrailingReturnTypeCheck.h" #include "UseTransparentFunctorsCheck.h" #include "UseUncaughtExceptionsCheck.h" #include "UseUsingCheck.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace modernize { class ModernizeModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<AvoidBindCheck>("modernize-avoid-bind"); CheckFactories.registerCheck<AvoidCArraysCheck>("modernize-avoid-c-arrays"); CheckFactories.registerCheck<ConcatNestedNamespacesCheck>( "modernize-concat-nested-namespaces"); CheckFactories.registerCheck<DeprecatedHeadersCheck>( "modernize-deprecated-headers"); CheckFactories.registerCheck<DeprecatedIosBaseAliasesCheck>( "modernize-deprecated-ios-base-aliases"); CheckFactories.registerCheck<LoopConvertCheck>("modernize-loop-convert"); CheckFactories.registerCheck<MacroToEnumCheck>("modernize-macro-to-enum"); CheckFactories.registerCheck<MakeSharedCheck>("modernize-make-shared"); CheckFactories.registerCheck<MakeUniqueCheck>("modernize-make-unique"); CheckFactories.registerCheck<PassByValueCheck>("modernize-pass-by-value"); CheckFactories.registerCheck<RawStringLiteralCheck>( "modernize-raw-string-literal"); CheckFactories.registerCheck<RedundantVoidArgCheck>( "modernize-redundant-void-arg"); CheckFactories.registerCheck<ReplaceAutoPtrCheck>( "modernize-replace-auto-ptr"); CheckFactories.registerCheck<ReplaceDisallowCopyAndAssignMacroCheck>( "modernize-replace-disallow-copy-and-assign-macro"); CheckFactories.registerCheck<ReplaceRandomShuffleCheck>( "modernize-replace-random-shuffle"); CheckFactories.registerCheck<ReturnBracedInitListCheck>( "modernize-return-braced-init-list"); CheckFactories.registerCheck<ShrinkToFitCheck>("modernize-shrink-to-fit"); CheckFactories.registerCheck<UnaryStaticAssertCheck>( "modernize-unary-static-assert"); CheckFactories.registerCheck<UseAutoCheck>("modernize-use-auto"); CheckFactories.registerCheck<UseBoolLiteralsCheck>( "modernize-use-bool-literals"); CheckFactories.registerCheck<UseDefaultMemberInitCheck>( "modernize-use-default-member-init"); CheckFactories.registerCheck<UseEmplaceCheck>("modernize-use-emplace"); CheckFactories.registerCheck<UseEqualsDefaultCheck>("modernize-use-equals-default"); CheckFactories.registerCheck<UseEqualsDeleteCheck>( "modernize-use-equals-delete"); CheckFactories.registerCheck<UseNodiscardCheck>( "modernize-use-nodiscard"); CheckFactories.registerCheck<UseNoexceptCheck>("modernize-use-noexcept"); CheckFactories.registerCheck<UseNullptrCheck>("modernize-use-nullptr"); CheckFactories.registerCheck<UseOverrideCheck>("modernize-use-override"); CheckFactories.registerCheck<UseTrailingReturnTypeCheck>( "modernize-use-trailing-return-type"); CheckFactories.registerCheck<UseTransparentFunctorsCheck>( "modernize-use-transparent-functors"); CheckFactories.registerCheck<UseUncaughtExceptionsCheck>( "modernize-use-uncaught-exceptions"); CheckFactories.registerCheck<UseUsingCheck>("modernize-use-using"); } ClangTidyOptions getModuleOptions() override { ClangTidyOptions Options; auto &Opts = Options.CheckOptions; // For types whose size in bytes is above this threshold, we prefer taking a // const-reference than making a copy. Opts["modernize-loop-convert.MaxCopySize"] = "16"; Opts["modernize-loop-convert.MinConfidence"] = "reasonable"; Opts["modernize-loop-convert.NamingStyle"] = "CamelCase"; Opts["modernize-pass-by-value.IncludeStyle"] = "llvm"; // Also: "google". Opts["modernize-replace-auto-ptr.IncludeStyle"] = "llvm"; // Also: "google". // Comma-separated list of macros that behave like NULL. Opts["modernize-use-nullptr.NullMacros"] = "NULL"; return Options; } }; // Register the ModernizeTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<ModernizeModule> X("modernize-module", "Add modernize checks."); } // namespace modernize // This anchor is used to force the linker to link in the generated object file // and thus register the ModernizeModule. volatile int ModernizeModuleAnchorSource = 0; } // namespace tidy } // namespace clang
#include "CGameExporter.h" #include "CGameInfo.h" #include "CResourceIterator.h" #include "CResourceStore.h" #include "Core/CompressionUtil.h" #include "Core/Resource/CWorld.h" #include "Core/Resource/Script/CGameTemplate.h" #include <Common/Macros.h> #include <Common/CScopedTimer.h> #include <Common/FileIO.h> #include <Common/FileUtil.h> #include <Common/Serialization/CXMLWriter.h> #include <nod/nod.hpp> #include <nod/DiscBase.hpp> #include <tinyxml2.h> #define LOAD_PAKS 1 #define SAVE_PACKAGE_DEFINITIONS 1 #define USE_ASSET_NAME_MAP 1 #define EXPORT_COOKED 1 #if NOD_UCS2 #define TStringToNodString(string) ToWChar(string) #else #define TStringToNodString(string) *string #endif CGameExporter::CGameExporter(EDiscType DiscType, EGame Game, bool FrontEnd, ERegion Region, const TString& rkGameName, const TString& rkGameID, float BuildVersion) : mGame(Game) , mRegion(Region) , mGameName(rkGameName) , mGameID(rkGameID) , mBuildVersion(BuildVersion) , mDiscType(DiscType) , mFrontEnd(FrontEnd) { ASSERT(mGame != EGame::Invalid); ASSERT(mRegion != ERegion::Unknown); } bool CGameExporter::Export(nod::DiscBase *pDisc, const TString& rkOutputDir, CAssetNameMap *pNameMap, CGameInfo *pGameInfo, IProgressNotifier *pProgress) { SCOPED_TIMER(ExportGame); mpDisc = pDisc; mpNameMap = pNameMap; mpGameInfo = pGameInfo; mExportDir = FileUtil::MakeAbsolute(rkOutputDir); mDiscDir = "Disc/"; mWorldsDirName = "Worlds/"; // Export directory must be empty! if (FileUtil::Exists(mExportDir) && !FileUtil::IsEmpty(mExportDir)) return false; FileUtil::MakeDirectory(mExportDir); // Init progress mpProgress = pProgress; mpProgress->SetNumTasks(eES_NumSteps); // Extract disc if (!ExtractDiscData()) return false; // Create project mpProject = CGameProject::CreateProjectForExport( mExportDir, mGame, mRegion, mGameID, mBuildVersion); mpProject->SetProjectName(mGameName); mpStore = mpProject->ResourceStore(); mResourcesDir = mpStore->ResourcesDir(); CResourceStore *pOldStore = gpResourceStore; gpResourceStore = mpStore; // Export cooked data LoadPaks(); ExportCookedResources(); // Export editor data if (!mpProgress->ShouldCancel()) { mpProject->AudioManager()->LoadAssets(); ExportResourceEditorData(); } // Export finished! mProjectPath = mpProject->ProjectPath(); mpProject.reset(); if (pOldStore != nullptr) gpResourceStore = pOldStore; return !mpProgress->ShouldCancel(); } void CGameExporter::LoadResource(const CAssetID& rkID, std::vector<uint8>& rBuffer) { SResourceInstance *pInst = FindResourceInstance(rkID); if (pInst != nullptr) LoadResource(*pInst, rBuffer); } bool CGameExporter::ShouldExportDiscNode(const nod::Node *pkNode, bool IsInRoot) const { if (IsInRoot && mDiscType != EDiscType::Normal) { // Directories - exclude the filesystem for other games if (pkNode->getKind() == nod::Node::Kind::Directory) { // Frontend is always included; this is for compatibility with Dolphin if (pkNode->getName() == "fe") return true; if (mFrontEnd) return false; switch (mGame) { case EGame::Prime: return mDiscType == EDiscType::WiiDeAsobu && pkNode->getName() == "MP1JPN" || mDiscType == EDiscType::Trilogy && pkNode->getName() == "MP1"; case EGame::Echoes: return mDiscType == EDiscType::WiiDeAsobu && pkNode->getName() == "MP2JPN" || mDiscType == EDiscType::Trilogy && pkNode->getName() == "MP2"; case EGame::Corruption: return mDiscType == EDiscType::Trilogy && pkNode->getName() == "MP3"; default: return false; } } else // Files - exclude the DOLs for other games { // Again - always include frontend. Always include opening.bnr as well. if (pkNode->getName() == "rs5fe_p.dol" || pkNode->getName() == "opening.bnr") return true; if (mFrontEnd) return false; switch (mGame) { case EGame::Prime: return mDiscType == EDiscType::WiiDeAsobu && pkNode->getName() == "rs5mp1jpn_p.dol" || mDiscType == EDiscType::Trilogy && pkNode->getName() == "rs5mp1_p.dol"; case EGame::Echoes: return mDiscType == EDiscType::WiiDeAsobu && pkNode->getName() == "rs5mp2jpn_p.dol" || mDiscType == EDiscType::Trilogy && pkNode->getName() == "rs5mp2_p.dol"; case EGame::Corruption: return mDiscType == EDiscType::Trilogy && pkNode->getName() == "rs5mp3_p.dol"; default: return false; } } } return true; } // ************ PROTECTED ************ bool CGameExporter::ExtractDiscData() { // todo: handle dol, apploader, multiple partitions, wii ticket blob SCOPED_TIMER(ExtractDiscData); // Init progress mpProgress->SetTask(eES_ExtractDisc, "Extracting disc files"); // Create Disc output folder TString AbsDiscDir = mExportDir + mDiscDir; bool IsWii = (mBuildVersion >= 3.f); if (IsWii) AbsDiscDir += "DATA/"; FileUtil::MakeDirectory(AbsDiscDir); // Extract disc filesystem nod::IPartition *pDataPartition = mpDisc->getDataPartition(); nod::ExtractionContext Context; Context.force = false; Context.progressCB = [&](const std::string_view rkDesc, float ProgressPercent) { mpProgress->Report((int) (ProgressPercent * 10000), 10000, rkDesc.data()); }; TString FilesDir = AbsDiscDir + "files/"; FileUtil::MakeDirectory(FilesDir); bool Success = ExtractDiscNodeRecursive(&pDataPartition->getFSTRoot(), FilesDir, true, Context); if (!Success) return false; if (!mpProgress->ShouldCancel()) { Context.progressCB = nullptr; if (IsWii) { // Extract crypto files if (!pDataPartition->extractCryptoFiles(TStringToNodString(AbsDiscDir), Context)) return false; // Extract disc header files if (!mpDisc->extractDiscHeaderFiles(TStringToNodString(AbsDiscDir), Context)) return false; } // Extract system files if (!pDataPartition->extractSysFiles(TStringToNodString(AbsDiscDir), Context)) return false; return true; } else return false; } bool CGameExporter::ExtractDiscNodeRecursive(const nod::Node *pkNode, const TString& rkDir, bool RootNode, const nod::ExtractionContext& rkContext) { for (nod::Node::DirectoryIterator Iter = pkNode->begin(); Iter != pkNode->end(); ++Iter) { if (!ShouldExportDiscNode(&*Iter, RootNode)) continue; if (Iter->getKind() == nod::Node::Kind::File) { TString FilePath = rkDir + Iter->getName().data(); bool Success = Iter->extractToDirectory(TStringToNodString(rkDir), rkContext); if (!Success) return false; if (FilePath.GetFileExtension().CaseInsensitiveCompare("pak")) { // For multi-game Wii discs, don't track packages for frontend unless we're exporting frontend if (mDiscType == EDiscType::Normal || mFrontEnd || pkNode->getName() != "fe") mPaks.push_back(FilePath); } } else { TString Subdir = rkDir + Iter->getName().data() + "/"; bool Success = FileUtil::MakeDirectory(Subdir); if (!Success) return false; Success = ExtractDiscNodeRecursive(&*Iter, Subdir, false, rkContext); if (!Success) return false; } } return true; } // ************ RESOURCE LOADING ************ void CGameExporter::LoadPaks() { #if LOAD_PAKS SCOPED_TIMER(LoadPaks); mPaks.sort([](const TString& rkLeft, const TString& rkRight) -> bool { return rkLeft.ToUpper() < rkRight.ToUpper(); }); for (auto It = mPaks.begin(); It != mPaks.end(); It++) { TString PakPath = *It; CFileInStream Pak(PakPath, EEndian::BigEndian); if (!Pak.IsValid()) { errorf("Couldn't open pak: %s", *PakPath); continue; } TString RelPakPath = FileUtil::MakeRelative(PakPath.GetFileDirectory(), mpProject->DiscFilesystemRoot(false)); auto pPackage = std::make_unique<CPackage>(mpProject.get(), PakPath.GetFileName(false), RelPakPath); // MP1-MP3Proto if (mGame < EGame::Corruption) { [[maybe_unused]] const uint32 PakVersion = Pak.ReadULong(); Pak.Seek(0x4, SEEK_CUR); ASSERT(PakVersion == 0x00030005); // Echoes demo disc has a pak that ends right here. if (!Pak.EoF()) { uint32 NumNamedResources = Pak.ReadULong(); ASSERT(NumNamedResources > 0); for (uint32 iName = 0; iName < NumNamedResources; iName++) { const CFourCC ResType = Pak.ReadULong(); const CAssetID ResID(Pak, mGame); const uint32 NameLen = Pak.ReadULong(); const TString Name = Pak.ReadString(NameLen); pPackage->AddResource(Name, ResID, ResType); } uint32 NumResources = Pak.ReadLong(); // Keep track of which areas have duplicate resources std::set<CAssetID> PakResourceSet; bool AreaHasDuplicates = true; // Default to true so that first area is always considered as having duplicates for (uint32 iRes = 0; iRes < NumResources; iRes++) { const bool Compressed = Pak.ReadULong() == 1; const CFourCC ResType = Pak.ReadULong(); const CAssetID ResID(Pak, mGame); const uint32 ResSize = Pak.ReadULong(); const uint32 ResOffset = Pak.ReadULong(); if (mResourceMap.find(ResID) == mResourceMap.cend()) mResourceMap.insert_or_assign(ResID, SResourceInstance{PakPath, ResID, ResType, ResOffset, ResSize, Compressed, false}); // Check for duplicate resources if (ResType == "MREA") { mAreaDuplicateMap[ResID] = AreaHasDuplicates; AreaHasDuplicates = false; } else if (!AreaHasDuplicates && PakResourceSet.find(ResID) != PakResourceSet.cend()) { AreaHasDuplicates = true; } else { PakResourceSet.insert(ResID); } } } } else // MP3 + DKCR { [[maybe_unused]] const uint32 PakVersion = Pak.ReadULong(); const uint32 PakHeaderLen = Pak.ReadULong(); Pak.Seek(PakHeaderLen - 0x8, SEEK_CUR); ASSERT(PakVersion == 2); struct SPakSection { CFourCC Type; uint32 Size; }; std::vector<SPakSection> PakSections; const uint32 NumPakSections = Pak.ReadULong(); ASSERT(NumPakSections == 3); for (uint32 iSec = 0; iSec < NumPakSections; iSec++) { const CFourCC Type = Pak.ReadULong(); const uint32 Size = Pak.ReadULong(); PakSections.push_back(SPakSection{Type, Size}); } Pak.SeekToBoundary(64); for (uint32 iSec = 0; iSec < NumPakSections; iSec++) { const uint32 Next = Pak.Tell() + PakSections[iSec].Size; // Named Resources if (PakSections[iSec].Type == "STRG") { const uint32 NumNamedResources = Pak.ReadULong(); for (uint32 iName = 0; iName < NumNamedResources; iName++) { const TString Name = Pak.ReadString(); const CFourCC ResType = Pak.ReadULong(); const CAssetID ResID(Pak, mGame); pPackage->AddResource(Name, ResID, ResType); } } else if (PakSections[iSec].Type == "RSHD") { ASSERT(PakSections[iSec + 1].Type == "DATA"); const uint32 DataStart = Next; const uint32 NumResources = Pak.ReadULong(); // Keep track of which areas have duplicate resources std::set<CAssetID> PakResourceSet; bool AreaHasDuplicates = true; // Default to true so that first area is always considered as having duplicates for (uint32 iRes = 0; iRes < NumResources; iRes++) { const bool Compressed = Pak.ReadULong() == 1; const CFourCC Type = Pak.ReadULong(); const CAssetID ResID(Pak, mGame); const uint32 Size = Pak.ReadULong(); const uint32 Offset = DataStart + Pak.ReadULong(); if (mResourceMap.find(ResID) == mResourceMap.cend()) mResourceMap.insert_or_assign(ResID, SResourceInstance{PakPath, ResID, Type, Offset, Size, Compressed, false}); // Check for duplicate resources (unnecessary for DKCR) if (mGame != EGame::DKCReturns) { if (Type == "MREA") { mAreaDuplicateMap.insert_or_assign(ResID, AreaHasDuplicates); AreaHasDuplicates = false; } else if (!AreaHasDuplicates && PakResourceSet.find(ResID) != PakResourceSet.cend()) { AreaHasDuplicates = true; } else { PakResourceSet.insert(ResID); } } } } Pak.Seek(Next, SEEK_SET); } } // Add package to project and save #if SAVE_PACKAGE_DEFINITIONS [[maybe_unused]] const bool SaveSuccess = pPackage->Save(); ASSERT(SaveSuccess); #endif mpProject->AddPackage(std::move(pPackage)); } #endif } void CGameExporter::LoadResource(const SResourceInstance& rkResource, std::vector<uint8>& rBuffer) { CFileInStream Pak(rkResource.PakFile, EEndian::BigEndian); if (Pak.IsValid()) { Pak.Seek(rkResource.PakOffset, SEEK_SET); // Handle compression if (rkResource.Compressed) { bool ZlibCompressed = (mGame <= EGame::EchoesDemo || mGame == EGame::DKCReturns); if (mGame <= EGame::CorruptionProto) { std::vector<uint8> CompressedData(rkResource.PakSize); const uint32 UncompressedSize = Pak.ReadULong(); rBuffer.resize(UncompressedSize); Pak.ReadBytes(CompressedData.data(), CompressedData.size()); if (ZlibCompressed) { uint32 TotalOut; CompressionUtil::DecompressZlib(CompressedData.data(), CompressedData.size(), rBuffer.data(), rBuffer.size(), TotalOut); } else { CompressionUtil::DecompressSegmentedData(CompressedData.data(), CompressedData.size(), rBuffer.data(), rBuffer.size()); } } else { [[maybe_unused]] const CFourCC Magic = Pak.ReadULong(); ASSERT(Magic == "CMPD"); const uint32 NumBlocks = Pak.ReadULong(); struct SCompressedBlock { uint32 CompressedSize; uint32 UncompressedSize; }; std::vector<SCompressedBlock> CompressedBlocks; uint32 TotalUncompressedSize = 0; for (uint32 iBlock = 0; iBlock < NumBlocks; iBlock++) { const uint32 CompressedSize = (Pak.ReadULong() & 0x00FFFFFF); const uint32 UncompressedSize = Pak.ReadULong(); TotalUncompressedSize += UncompressedSize; CompressedBlocks.push_back(SCompressedBlock{CompressedSize, UncompressedSize}); } rBuffer.resize(TotalUncompressedSize); uint32 Offset = 0; for (uint32 iBlock = 0; iBlock < NumBlocks; iBlock++) { const uint32 CompressedSize = CompressedBlocks[iBlock].CompressedSize; const uint32 UncompressedSize = CompressedBlocks[iBlock].UncompressedSize; // Block is compressed if (CompressedSize != UncompressedSize) { std::vector<uint8> CompressedData(CompressedBlocks[iBlock].CompressedSize); Pak.ReadBytes(CompressedData.data(), CompressedData.size()); if (ZlibCompressed) { uint32 TotalOut; CompressionUtil::DecompressZlib(CompressedData.data(), CompressedData.size(), rBuffer.data() + Offset, UncompressedSize, TotalOut); } else { CompressionUtil::DecompressSegmentedData(CompressedData.data(), CompressedData.size(), rBuffer.data() + Offset, UncompressedSize); } } else // Block is uncompressed { Pak.ReadBytes(rBuffer.data() + Offset, UncompressedSize); } Offset += UncompressedSize; } } } else // Handle uncompressed { rBuffer.resize(rkResource.PakSize); Pak.ReadBytes(rBuffer.data(), rBuffer.size()); } } } void CGameExporter::ExportCookedResources() { SCOPED_TIMER(ExportCookedResources); FileUtil::MakeDirectory(mResourcesDir); mpProgress->SetTask(eES_ExportCooked, "Unpacking cooked assets"); int ResIndex = 0; for (auto It = mResourceMap.begin(); It != mResourceMap.end() && !mpProgress->ShouldCancel(); ++It, ResIndex++) { SResourceInstance& rRes = It->second; // Update progress if ((ResIndex & 0x3) == 0) mpProgress->Report(ResIndex, mResourceMap.size(), TString::Format("Unpacking asset %d/%d", ResIndex, mResourceMap.size()) ); // Export resource ExportResource(rRes); } } void CGameExporter::ExportResourceEditorData() { { // Save raw versions of resources + resource cache data files // Note this has to be done after all cooked resources are exported // because we have to load the resource to build its dependency tree and // some resources will fail to load if their dependencies don't exist SCOPED_TIMER(SaveRawResources); mpProgress->SetTask(eES_GenerateRaw, "Generating editor data"); int ResIndex = 0; // todo: we're wasting a ton of time loading the same resources over and over because most resources automatically // load all their dependencies and then we just clear it out from memory even though we'll need it again later. we // should really be doing this by dependency order instead of by ID order. for (CResourceIterator It(mpStore); It && !mpProgress->ShouldCancel(); ++It, ++ResIndex) { // Update progress if ((ResIndex & 0x3) == 0 || It->ResourceType() == EResourceType::Area) { mpProgress->Report(ResIndex, mpStore->NumTotalResources(), TString::Format("Processing asset %u/%u: %s", ResIndex, mpStore->NumTotalResources(), *It->CookedAssetPath(true).GetFileName())); } // Worlds need some info we can only get from the pak at export time; namely, which areas can // have duplicates, as well as the world's internal name. if (It->ResourceType() == EResourceType::World) { auto* pWorld = static_cast<CWorld*>(It->Load()); // Set area duplicate flags for (size_t iArea = 0; iArea < pWorld->NumAreas(); iArea++) { const CAssetID AreaID = pWorld->AreaResourceID(iArea); const auto Find = mAreaDuplicateMap.find(AreaID); if (Find != mAreaDuplicateMap.cend()) pWorld->SetAreaAllowsPakDuplicates(iArea, Find->second); } // Set world name TString WorldName = MakeWorldName(pWorld->ID()); pWorld->SetName(std::move(WorldName)); } // Save raw resource + generate dependencies if (It->TypeInfo()->CanBeSerialized()) It->Save(true); else It->UpdateDependencies(); // Set flags, save metadata It->SaveMetadata(true); } } if (!mpProgress->ShouldCancel()) { // All resources should have dependencies generated, so save the project files SCOPED_TIMER(SaveResourceDatabase); #if EXPORT_COOKED [[maybe_unused]] const bool ResDBSaveSuccess = mpStore->SaveDatabaseCache(); ASSERT(ResDBSaveSuccess); #endif [[maybe_unused]] const bool ProjectSaveSuccess = mpProject->Save(); ASSERT(ProjectSaveSuccess); } } void CGameExporter::ExportResource(SResourceInstance& rRes) { if (!rRes.Exported) { std::vector<uint8> ResourceData; LoadResource(rRes, ResourceData); // Register resource and write to file TString Directory, Name; bool AutoDir, AutoName; #if USE_ASSET_NAME_MAP mpNameMap->GetNameInfo(rRes.ResourceID, Directory, Name, AutoDir, AutoName); #else Directory = mpStore->DefaultAssetDirectoryPath(mpStore->Game()); Name = rRes.ResourceID.ToString(); #endif CResourceEntry *pEntry = mpStore->CreateNewResource(rRes.ResourceID, CResTypeInfo::TypeForCookedExtension(mGame, rRes.ResourceType)->Type(), Directory, Name, true); // Set flags pEntry->SetFlag(EResEntryFlag::IsBaseGameResource); pEntry->SetFlagEnabled(EResEntryFlag::AutoResDir, AutoDir); pEntry->SetFlagEnabled(EResEntryFlag::AutoResName, AutoName); #if EXPORT_COOKED // Save cooked asset const TString OutCookedPath = pEntry->CookedAssetPath(); FileUtil::MakeDirectory(OutCookedPath.GetFileDirectory()); CFileOutStream Out(OutCookedPath, EEndian::BigEndian); if (Out.IsValid()) Out.WriteBytes(ResourceData.data(), ResourceData.size()); ASSERT(pEntry->HasCookedVersion()); #endif rRes.Exported = true; } } TString CGameExporter::MakeWorldName(CAssetID WorldID) { [[maybe_unused]] const CResourceEntry *pWorldEntry = mpStore->FindEntry(WorldID); ASSERT(pWorldEntry && pWorldEntry->ResourceType() == EResourceType::World); // Find the original world name in the package resource names TString WorldName; for (size_t iPkg = 0; iPkg < mpProject->NumPackages(); iPkg++) { CPackage *pPkg = mpProject->PackageByIndex(iPkg); for (size_t iRes = 0; iRes < pPkg->NumNamedResources(); iRes++) { const SNamedResource& rkRes = pPkg->NamedResourceByIndex(iRes); if (rkRes.ID == WorldID) { WorldName = rkRes.Name; if (WorldName.EndsWith("_NODEPEND")) WorldName = WorldName.ChopBack(9); break; } } if (!WorldName.IsEmpty()) break; } // Fix up the name; remove date/time, leading exclamation points, etc if (!WorldName.IsEmpty()) { // World names are basically formatted differently in every game... // MP1 demo - Remove ! from the beginning if (mGame == EGame::PrimeDemo) { if (WorldName.StartsWith('!')) WorldName = WorldName.ChopFront(1); } // MP1 - Remove prefix characters and ending date else if (mGame == EGame::Prime) { WorldName = WorldName.ChopFront(2); bool StartedDate = false; while (!WorldName.IsEmpty()) { const char Chr = WorldName.Back(); if (!StartedDate && Chr >= '0' && Chr <= '9') StartedDate = true; else if (StartedDate && Chr != '_' && (Chr < '0' || Chr > '9')) break; WorldName = WorldName.ChopBack(1); } } // MP2 demo - Use text between the first and second underscores else if (mGame == EGame::EchoesDemo) { const uint32 UnderscoreA = WorldName.IndexOf('_'); const uint32 UnderscoreB = WorldName.IndexOf('_', UnderscoreA + 1); if (UnderscoreA != UnderscoreB && UnderscoreA != UINT32_MAX && UnderscoreB != UINT32_MAX) WorldName = WorldName.SubString(UnderscoreA + 1, UnderscoreB - UnderscoreA - 1); } // MP2 - Remove text before first underscore and after last underscore, strip remaining underscores (except multiplayer maps, which have one underscore) else if (mGame == EGame::Echoes) { const uint32 FirstUnderscore = WorldName.IndexOf('_'); const uint32 LastUnderscore = WorldName.LastIndexOf('_'); if (FirstUnderscore != LastUnderscore && FirstUnderscore != UINT32_MAX && LastUnderscore != UINT32_MAX) { WorldName = WorldName.ChopBack(WorldName.Size() - LastUnderscore); WorldName = WorldName.ChopFront(FirstUnderscore + 1); WorldName.Remove('_'); } } // MP3 proto - Remove ! from the beginning and all text after last underscore else if (mGame == EGame::CorruptionProto) { if (WorldName.StartsWith('!')) WorldName = WorldName.ChopFront(1); const uint32 LastUnderscore = WorldName.LastIndexOf('_'); WorldName = WorldName.ChopBack(WorldName.Size() - LastUnderscore); } // MP3 - Remove text after last underscore else if (mGame == EGame::Corruption) { const uint32 LastUnderscore = WorldName.LastIndexOf('_'); if (LastUnderscore != UINT32_MAX && !WorldName.StartsWith("front_end_")) WorldName = WorldName.ChopBack(WorldName.Size() - LastUnderscore); } // DKCR - Remove text prior to first underscore else if (mGame == EGame::DKCReturns) { const uint32 Underscore = WorldName.IndexOf('_'); WorldName = WorldName.ChopFront(Underscore + 1); } } return WorldName; }
.size 8000 .text@49 inc a ldff(45), a jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld a, ff ldff(45), a ld b, 03 call lwaitly_b ld a, 40 ldff(41), a ld a, 02 ldff(ff), a ei ld a, b inc a inc a ldff(45), a ld c, 41 .text@1000 lstatint: xor a, a ldff(c), a ldff(0f), a .text@1068 ld a, 00 ldff(c), a xor a, a ldff(0f), a ld a, ff ldff(c), a ldff a, (0f) and a, b jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; ReadDr4.Asm ; ; Abstract: ; ; AsmReadDr4 function ; ; Notes: ; ;------------------------------------------------------------------------------ .586p .model flat,C .code ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmReadDr4 ( ; VOID ; ); ;------------------------------------------------------------------------------ AsmReadDr4 PROC ; ; DR4 is alias to DR6 only if DE (in CR4) is cleared. Otherwise, reading ; this register will cause a #UD exception. ; ; MS assembler doesn't support this instruction since no one would use it ; under normal circustances. Here opcode is used. ; DB 0fh, 21h, 0e0h ret AsmReadDr4 ENDP END
; A016742: Even squares: a(n) = (2*n)^2. ; 0,4,16,36,64,100,144,196,256,324,400,484,576,676,784,900,1024,1156,1296,1444,1600,1764,1936,2116,2304,2500,2704,2916,3136,3364,3600,3844,4096,4356,4624,4900,5184,5476,5776,6084,6400,6724,7056,7396,7744,8100,8464,8836,9216,9604,10000,10404,10816,11236,11664,12100,12544,12996,13456,13924,14400,14884,15376,15876,16384,16900,17424,17956,18496,19044,19600,20164,20736,21316,21904,22500,23104,23716,24336,24964,25600,26244,26896,27556,28224,28900,29584,30276,30976,31684,32400,33124,33856,34596,35344,36100,36864,37636,38416,39204,40000,40804,41616,42436,43264,44100,44944,45796,46656,47524,48400,49284,50176,51076,51984,52900,53824,54756,55696,56644,57600,58564,59536,60516,61504,62500,63504,64516,65536,66564,67600,68644,69696,70756,71824,72900,73984,75076,76176,77284,78400,79524,80656,81796,82944,84100,85264,86436,87616,88804,90000,91204,92416,93636,94864,96100,97344,98596,99856,101124,102400,103684,104976,106276,107584,108900,110224,111556,112896,114244,115600,116964,118336,119716,121104,122500,123904,125316,126736,128164,129600,131044,132496,133956,135424,136900,138384,139876,141376,142884,144400,145924,147456,148996,150544,152100,153664,155236,156816,158404,160000,161604,163216,164836,166464,168100,169744,171396,173056,174724,176400,178084,179776,181476,183184,184900,186624,188356,190096,191844,193600,195364,197136,198916,200704,202500,204304,206116,207936,209764,211600,213444,215296,217156,219024,220900,222784,224676,226576,228484,230400,232324,234256,236196,238144,240100,242064,244036,246016,248004 mov $1,$0 pow $1,2 mul $1,4
/****************************************************************************** * $Id: ogrwfslayer.cpp 27044 2014-03-16 23:41:27Z rouault $ * * Project: WFS Translator * Purpose: Implements OGRWFSLayer class. * Author: Even Rouault, <even dot rouault at mines dash paris dot org> * ****************************************************************************** * Copyright (c) 2010-2013, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_port.h" #include "ogr_wfs.h" #include "ogr_api.h" #include "cpl_minixml.h" #include "cpl_http.h" #include "parsexsd.h" CPL_CVSID("$Id: ogrwfslayer.cpp 27044 2014-03-16 23:41:27Z rouault $"); /************************************************************************/ /* OGRWFSRecursiveUnlink() */ /************************************************************************/ static void OGRWFSRecursiveUnlink( const char *pszName ) { char **papszFileList; int i; papszFileList = CPLReadDir( pszName ); for( i = 0; papszFileList != NULL && papszFileList[i] != NULL; i++ ) { VSIStatBufL sStatBuf; if( EQUAL(papszFileList[i],".") || EQUAL(papszFileList[i],"..") ) continue; CPLString osFullFilename = CPLFormFilename( pszName, papszFileList[i], NULL ); VSIStatL( osFullFilename, &sStatBuf ); if( VSI_ISREG( sStatBuf.st_mode ) ) { VSIUnlink( osFullFilename ); } else if( VSI_ISDIR( sStatBuf.st_mode ) ) { OGRWFSRecursiveUnlink( osFullFilename ); } } CSLDestroy( papszFileList ); VSIRmdir( pszName ); } /************************************************************************/ /* OGRWFSLayer() */ /************************************************************************/ OGRWFSLayer::OGRWFSLayer( OGRWFSDataSource* poDS, OGRSpatialReference* poSRS, int bAxisOrderAlreadyInverted, const char* pszBaseURL, const char* pszName, const char* pszNS, const char* pszNSVal ) { this->poDS = poDS; this->poSRS = poSRS; this->bAxisOrderAlreadyInverted = bAxisOrderAlreadyInverted; this->pszBaseURL = CPLStrdup(pszBaseURL); this->pszName = CPLStrdup(pszName); this->pszNS = pszNS ? CPLStrdup(pszNS) : NULL; this->pszNSVal = pszNSVal ? CPLStrdup(pszNSVal) : NULL; poFeatureDefn = NULL; poGMLFeatureClass = NULL; bGotApproximateLayerDefn = FALSE; bStreamingDS = FALSE; poBaseDS = NULL; poBaseLayer = NULL; bReloadNeeded = FALSE; bHasFetched = FALSE; eGeomType = wkbUnknown; nFeatures = -1; bCountFeaturesInGetNextFeature = FALSE; dfMinX = dfMinY = dfMaxX = dfMaxY = 0; bHasExtents = FALSE; poFetchedFilterGeom = NULL; nExpectedInserts = 0; bInTransaction = FALSE; bUseFeatureIdAtLayerLevel = FALSE; bPagingActive = FALSE; nPagingStartIndex = 0; nFeatureRead = 0; nFeatureCountRequested = 0; pszRequiredOutputFormat = NULL; bAscFlag = TRUE; } /************************************************************************/ /* Clone() */ /************************************************************************/ OGRWFSLayer* OGRWFSLayer::Clone() { OGRWFSLayer* poDupLayer = new OGRWFSLayer(poDS, poSRS, bAxisOrderAlreadyInverted, pszBaseURL, pszName, pszNS, pszNSVal); if (poSRS) poSRS->Reference(); poDupLayer->poFeatureDefn = GetLayerDefn()->Clone(); poDupLayer->poFeatureDefn->Reference(); poDupLayer->bGotApproximateLayerDefn = bGotApproximateLayerDefn; poDupLayer->eGeomType = poDupLayer->poFeatureDefn->GetGeomType(); poDupLayer->pszRequiredOutputFormat = pszRequiredOutputFormat ? CPLStrdup(pszRequiredOutputFormat) : NULL; poDupLayer->bAscFlag = bAscFlag; /* Copy existing schema file if already found */ CPLString osSrcFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this); CPLString osTargetFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", poDupLayer); CPLCopyFile(osTargetFileName, osSrcFileName); return poDupLayer; } /************************************************************************/ /* ~OGRWFSLayer() */ /************************************************************************/ OGRWFSLayer::~OGRWFSLayer() { if (bInTransaction) CommitTransaction(); if( poSRS != NULL ) poSRS->Release(); if (poFeatureDefn != NULL) poFeatureDefn->Release(); delete poGMLFeatureClass; CPLFree(pszBaseURL); CPLFree(pszName); CPLFree(pszNS); CPLFree(pszNSVal); OGRDataSource::DestroyDataSource(poBaseDS); delete poFetchedFilterGeom; CPLString osTmpDirName = CPLSPrintf("/vsimem/tempwfs_%p", this); OGRWFSRecursiveUnlink(osTmpDirName); CPLFree(pszRequiredOutputFormat); } /************************************************************************/ /* GetDescribeFeatureTypeURL() */ /************************************************************************/ CPLString OGRWFSLayer::GetDescribeFeatureTypeURL(int bWithNS) { CPLString osURL(pszBaseURL); osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS"); osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion()); osURL = CPLURLAddKVP(osURL, "REQUEST", "DescribeFeatureType"); osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName)); osURL = CPLURLAddKVP(osURL, "PROPERTYNAME", NULL); osURL = CPLURLAddKVP(osURL, "MAXFEATURES", NULL); osURL = CPLURLAddKVP(osURL, "COUNT", NULL); osURL = CPLURLAddKVP(osURL, "FILTER", NULL); osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", pszRequiredOutputFormat ? WFS_EscapeURL(pszRequiredOutputFormat).c_str() : NULL); if (pszNS && poDS->GetNeedNAMESPACE()) { /* Older Deegree version require NAMESPACE (e.g. http://www.nokis.org/deegree2/ogcwebservice) */ /* This has been now corrected */ CPLString osValue("xmlns("); osValue += pszNS; osValue += "="; osValue += pszNSVal; osValue += ")"; osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue)); } return osURL; } /************************************************************************/ /* DescribeFeatureType() */ /************************************************************************/ OGRFeatureDefn* OGRWFSLayer::DescribeFeatureType() { CPLString osURL = GetDescribeFeatureTypeURL(TRUE); CPLDebug("WFS", "%s", osURL.c_str()); CPLHTTPResult* psResult = poDS->HTTPFetch( osURL, NULL); if (psResult == NULL) { return NULL; } if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL) { if (poDS->IsOldDeegree((const char*)psResult->pabyData)) { CPLHTTPDestroyResult(psResult); return DescribeFeatureType(); } CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return NULL; } CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return NULL; } CPLHTTPDestroyResult(psResult); CPLXMLNode* psSchema = WFSFindNode(psXML, "schema"); if (psSchema == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <Schema>"); CPLDestroyXMLNode( psXML ); return NULL; } OGRFeatureDefn* poFDefn = ParseSchema(psSchema); if (poFDefn) poDS->SaveLayerSchema(pszName, psSchema); CPLDestroyXMLNode( psXML ); return poFDefn; } /************************************************************************/ /* ParseSchema() */ /************************************************************************/ OGRFeatureDefn* OGRWFSLayer::ParseSchema(CPLXMLNode* psSchema) { osTargetNamespace = CPLGetXMLValue(psSchema, "targetNamespace", ""); CPLString osTmpFileName; osTmpFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this); CPLSerializeXMLTreeToFile(psSchema, osTmpFileName); std::vector<GMLFeatureClass*> aosClasses; int bHaveSchema = GMLParseXSD( osTmpFileName, aosClasses ); if (bHaveSchema && aosClasses.size() == 1) { //CPLDebug("WFS", "Creating %s for %s", osTmpFileName.c_str(), GetName()); return BuildLayerDefnFromFeatureClass(aosClasses[0]); } else if (bHaveSchema) { std::vector<GMLFeatureClass*>::const_iterator iter = aosClasses.begin(); std::vector<GMLFeatureClass*>::const_iterator eiter = aosClasses.end(); while (iter != eiter) { GMLFeatureClass* poClass = *iter; iter ++; delete poClass; } } VSIUnlink(osTmpFileName); return NULL; } /************************************************************************/ /* BuildLayerDefnFromFeatureClass() */ /************************************************************************/ OGRFeatureDefn* OGRWFSLayer::BuildLayerDefnFromFeatureClass(GMLFeatureClass* poClass) { this->poGMLFeatureClass = poClass; OGRFeatureDefn* poFDefn = new OGRFeatureDefn( pszName ); poFDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS); if( poGMLFeatureClass->GetGeometryPropertyCount() > 0 ) poFDefn->SetGeomType( (OGRwkbGeometryType)poGMLFeatureClass->GetGeometryProperty(0)->GetType() ); /* -------------------------------------------------------------------- */ /* Added attributes (properties). */ /* -------------------------------------------------------------------- */ OGRFieldDefn oField( "gml_id", OFTString ); poFDefn->AddFieldDefn( &oField ); for( int iField = 0; iField < poGMLFeatureClass->GetPropertyCount(); iField++ ) { GMLPropertyDefn *poProperty = poGMLFeatureClass->GetProperty( iField ); OGRFieldType eFType; if( poProperty->GetType() == GMLPT_Untyped ) eFType = OFTString; else if( poProperty->GetType() == GMLPT_String ) eFType = OFTString; else if( poProperty->GetType() == GMLPT_Integer ) eFType = OFTInteger; else if( poProperty->GetType() == GMLPT_Real ) eFType = OFTReal; else if( poProperty->GetType() == GMLPT_StringList ) eFType = OFTStringList; else if( poProperty->GetType() == GMLPT_IntegerList ) eFType = OFTIntegerList; else if( poProperty->GetType() == GMLPT_RealList ) eFType = OFTRealList; else eFType = OFTString; OGRFieldDefn oField( poProperty->GetName(), eFType ); if ( EQUALN(oField.GetNameRef(), "ogr:", 4) ) oField.SetName(poProperty->GetName()+4); if( poProperty->GetWidth() > 0 ) oField.SetWidth( poProperty->GetWidth() ); if( poProperty->GetPrecision() > 0 ) oField.SetPrecision( poProperty->GetPrecision() ); poFDefn->AddFieldDefn( &oField ); } if( poGMLFeatureClass->GetGeometryPropertyCount() > 0 ) { const char* pszGeometryColumnName = poGMLFeatureClass->GetGeometryProperty(0)->GetSrcElement(); if (pszGeometryColumnName[0] != '\0') { osGeometryColumnName = pszGeometryColumnName; if( poFDefn->GetGeomFieldCount() > 0 ) poFDefn->GetGeomFieldDefn(0)->SetName(pszGeometryColumnName); } } return poFDefn; } /************************************************************************/ /* MakeGetFeatureURL() */ /************************************************************************/ CPLString OGRWFSLayer::MakeGetFeatureURL(int nRequestMaxFeatures, int bRequestHits) { CPLString osURL(pszBaseURL); osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS"); osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion()); osURL = CPLURLAddKVP(osURL, "REQUEST", "GetFeature"); if( atoi(poDS->GetVersion()) >= 2 ) osURL = CPLURLAddKVP(osURL, "TYPENAMES", WFS_EscapeURL(pszName)); else osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName)); if (pszRequiredOutputFormat) osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", WFS_EscapeURL(pszRequiredOutputFormat)); if (poDS->IsPagingAllowed() && !bRequestHits) { osURL = CPLURLAddKVP(osURL, "STARTINDEX", CPLSPrintf("%d", nPagingStartIndex + poDS->GetBaseStartIndex())); nRequestMaxFeatures = poDS->GetPageSize(); nFeatureCountRequested = nRequestMaxFeatures; bPagingActive = TRUE; } if (nRequestMaxFeatures) { osURL = CPLURLAddKVP(osURL, atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES", CPLSPrintf("%d", nRequestMaxFeatures)); } if (pszNS && poDS->GetNeedNAMESPACE()) { /* Older Deegree version require NAMESPACE (e.g. http://www.nokis.org/deegree2/ogcwebservice) */ /* This has been now corrected */ CPLString osValue("xmlns("); osValue += pszNS; osValue += "="; osValue += pszNSVal; osValue += ")"; osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue)); } delete poFetchedFilterGeom; poFetchedFilterGeom = NULL; CPLString osGeomFilter; if (m_poFilterGeom != NULL && osGeometryColumnName.size() > 0) { OGREnvelope oEnvelope; m_poFilterGeom->getEnvelope(&oEnvelope); poFetchedFilterGeom = m_poFilterGeom->clone(); osGeomFilter = "<BBOX>"; if (atoi(poDS->GetVersion()) >= 2) osGeomFilter += "<ValueReference>"; else osGeomFilter += "<PropertyName>"; if (pszNS) { osGeomFilter += pszNS; osGeomFilter += ":"; } osGeomFilter += osGeometryColumnName; if (atoi(poDS->GetVersion()) >= 2) osGeomFilter += "</ValueReference>"; else osGeomFilter += "</PropertyName>"; CPLLocaleC oLocaleEnforcer; if ( atoi(poDS->GetVersion()) >= 2 ) { osGeomFilter += "<gml:Envelope"; CPLString osSRSName = CPLURLGetValue(pszBaseURL, "SRSNAME"); if( osSRSName.size() ) { osGeomFilter += " srsName=\""; osGeomFilter += osSRSName; osGeomFilter += "\""; } osGeomFilter += ">"; if (bAxisOrderAlreadyInverted) { osGeomFilter += CPLSPrintf("<gml:lowerCorner>%.16f %.16f</gml:lowerCorner><gml:upperCorner>%.16f %.16f</gml:upperCorner>", oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX); } else osGeomFilter += CPLSPrintf("<gml:lowerCorner>%.16f %.16f</gml:lowerCorner><gml:upperCorner>%.16f %.16f</gml:upperCorner>", oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY); osGeomFilter += "</gml:Envelope>"; } else if ( poDS->RequiresEnvelopeSpatialFilter() ) { osGeomFilter += "<Envelope xmlns=\"http://www.opengis.net/gml\">"; if (bAxisOrderAlreadyInverted) { /* We can go here in WFS 1.1 with geographic coordinate systems */ /* that are natively return in lat,long order, but as we have */ /* presented long,lat order to the user, we must switch back */ /* for the server... */ osGeomFilter += CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></coord><coord><X>%.16f</X><Y>%.16f</Y></coord>", oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX); } else osGeomFilter += CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></coord><coord><X>%.16f</X><Y>%.16f</Y></coord>", oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY); osGeomFilter += "</Envelope>"; } else { osGeomFilter += "<gml:Box>"; osGeomFilter += "<gml:coordinates>"; if (bAxisOrderAlreadyInverted) { /* We can go here in WFS 1.1 with geographic coordinate systems */ /* that are natively return in lat,long order, but as we have */ /* presented long,lat order to the user, we must switch back */ /* for the server... */ osGeomFilter += CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX); } else osGeomFilter += CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY); osGeomFilter += "</gml:coordinates>"; osGeomFilter += "</gml:Box>"; } osGeomFilter += "</BBOX>"; } if (osGeomFilter.size() != 0 || osWFSWhere.size() != 0) { CPLString osFilter; if (atoi(poDS->GetVersion()) >= 2) osFilter = "<Filter xmlns=\"http://www.opengis.net/fes/2.0\""; else osFilter = "<Filter xmlns=\"http://www.opengis.net/ogc\""; if (pszNS) { osFilter += " xmlns:"; osFilter += pszNS; osFilter += "=\""; osFilter += pszNSVal; osFilter += "\""; } if (atoi(poDS->GetVersion()) >= 2) osFilter += " xmlns:gml=\"http://www.opengis.net/gml/3.2\">"; else osFilter += " xmlns:gml=\"http://www.opengis.net/gml\">"; if (osGeomFilter.size() != 0 && osWFSWhere.size() != 0) osFilter += "<And>"; osFilter += osWFSWhere; osFilter += osGeomFilter; if (osGeomFilter.size() != 0 && osWFSWhere.size() != 0) osFilter += "</And>"; osFilter += "</Filter>"; osURL = CPLURLAddKVP(osURL, "FILTER", WFS_EscapeURL(osFilter)); } if (bRequestHits) { osURL = CPLURLAddKVP(osURL, "RESULTTYPE", "hits"); } else if (osFieldToSort.size() != 0) { CPLString osSortBy(osFieldToSort); if (!bAscFlag) { if (atoi(poDS->GetVersion()) >= 2) osSortBy += " DESC"; else osSortBy += " D"; } osURL = CPLURLAddKVP(osURL, "SORTBY", WFS_EscapeURL(osSortBy)); } /* If no PROPERTYNAME is specified, build one if there are ignored fields */ CPLString osPropertyName = CPLURLGetValue(osURL, "PROPERTYNAME"); const char* pszPropertyName = osPropertyName.c_str(); if (pszPropertyName[0] == 0 && poFeatureDefn != NULL) { int bHasIgnoredField = FALSE; CPLString osPropertyName; for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ ) { if (EQUAL(poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), "gml_id")) { /* fake field : skip it */ } else if (poFeatureDefn->GetFieldDefn(iField)->IsIgnored()) { bHasIgnoredField = TRUE; } else { if (osPropertyName.size() != 0) osPropertyName += ","; osPropertyName += poFeatureDefn->GetFieldDefn(iField)->GetNameRef(); } } if (osGeometryColumnName.size() != 0) { if (poFeatureDefn->IsGeometryIgnored()) { bHasIgnoredField = TRUE; } else { if (osPropertyName.size() != 0) osPropertyName += ","; osPropertyName += osGeometryColumnName; } } if (bHasIgnoredField && osPropertyName.size()) { osPropertyName = "(" + osPropertyName + ")"; osURL = CPLURLAddKVP(osURL, "PROPERTYNAME", WFS_EscapeURL(osPropertyName)); } } return osURL; } /************************************************************************/ /* OGRWFSFetchContentDispositionFilename() */ /************************************************************************/ const char* OGRWFSFetchContentDispositionFilename(char** papszHeaders) { char** papszIter = papszHeaders; while(papszIter && *papszIter) { /* For multipart, we have in raw format, but without end-of-line characters */ if (strncmp(*papszIter, "Content-Disposition: attachment; filename=", 42) == 0) { return *papszIter + 42; } /* For single part, the headers are in KEY=VAL format, but with e-o-l ... */ else if (strncmp(*papszIter, "Content-Disposition=attachment; filename=", 41) == 0) { char* pszVal = (char*)(*papszIter + 41); char* pszEOL = strchr(pszVal, '\r'); if (pszEOL) *pszEOL = 0; pszEOL = strchr(pszVal, '\n'); if (pszEOL) *pszEOL = 0; return pszVal; } papszIter ++; } return NULL; } /************************************************************************/ /* MustRetryIfNonCompliantServer() */ /************************************************************************/ int OGRWFSLayer::MustRetryIfNonCompliantServer(const char* pszServerAnswer) { int bRetry = FALSE; /* Deegree server does not support PropertyIsNotEqualTo */ /* We have to turn it into <Not><PropertyIsEqualTo> */ if (osWFSWhere.size() != 0 && poDS->PropertyIsNotEqualToSupported() && strstr(pszServerAnswer, "Unknown comparison operation: 'PropertyIsNotEqualTo'") != NULL) { poDS->SetPropertyIsNotEqualToUnSupported(); bRetry = TRUE; } /* Deegree server requires the gml: prefix in GmlObjectId element, but ESRI */ /* doesn't like it at all ! Other servers don't care... */ if (osWFSWhere.size() != 0 && !poDS->DoesGmlObjectIdNeedGMLPrefix() && strstr(pszServerAnswer, "&lt;GmlObjectId&gt; requires 'gml:id'-attribute!") != NULL) { poDS->SetGmlObjectIdNeedsGMLPrefix(); bRetry = TRUE; } /* GeoServer can return the error 'Only FeatureIds are supported when encoding id filters to SDE' */ if (osWFSWhere.size() != 0 && !bUseFeatureIdAtLayerLevel && strstr(pszServerAnswer, "Only FeatureIds are supported") != NULL) { bUseFeatureIdAtLayerLevel = TRUE; bRetry = TRUE; } if (bRetry) { SetAttributeFilter(osSQLWhere); bHasFetched = TRUE; bReloadNeeded = FALSE; } return bRetry; } /************************************************************************/ /* FetchGetFeature() */ /************************************************************************/ OGRDataSource* OGRWFSLayer::FetchGetFeature(int nRequestMaxFeatures) { CPLString osURL = MakeGetFeatureURL(nRequestMaxFeatures, FALSE); CPLDebug("WFS", "%s", osURL.c_str()); CPLHTTPResult* psResult = NULL; CPLString osOutputFormat = CPLURLGetValue(osURL, "OUTPUTFORMAT"); /* Try streaming when the output format is GML and that we have a .xsd */ /* that we are able to understand */ CPLString osXSDFileName = CPLSPrintf("/vsimem/tempwfs_%p/file.xsd", this); VSIStatBufL sBuf; OGRSFDriverH hGMLDrv = OGRGetDriverByName("GML"); if (CSLTestBoolean(CPLGetConfigOption("OGR_WFS_USE_STREAMING", "YES")) && (osOutputFormat.size() == 0 || osOutputFormat.ifind("GML") != std::string::npos) && VSIStatL(osXSDFileName, &sBuf) == 0 && hGMLDrv != NULL) { const char* pszStreamingName = CPLSPrintf("/vsicurl_streaming/%s", osURL.c_str()); const char* pszStreamingNameWithXSD = CPLSPrintf("%s,xsd=%s", pszStreamingName, osXSDFileName.c_str()); OGRDataSource* poGML_DS = (OGRDataSource*) OGR_Dr_Open(hGMLDrv, pszStreamingNameWithXSD, FALSE); if (poGML_DS) { bStreamingDS = TRUE; return poGML_DS; } /* In case of failure, read directly the content to examine */ /* it, if it is XML error content */ char szBuffer[2048]; int nRead = 0; VSILFILE* fp = VSIFOpenL(pszStreamingName, "rb"); if (fp) { nRead = (int)VSIFReadL(szBuffer, 1, sizeof(szBuffer) - 1, fp); szBuffer[nRead] = '\0'; VSIFCloseL(fp); } if (nRead != 0) { if (MustRetryIfNonCompliantServer(szBuffer)) return FetchGetFeature(nRequestMaxFeatures); if (strstr(szBuffer, "<ServiceExceptionReport") != NULL || strstr(szBuffer, "<ows:ExceptionReport") != NULL) { if (poDS->IsOldDeegree(szBuffer)) { return FetchGetFeature(nRequestMaxFeatures); } CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", szBuffer); return NULL; } } } bStreamingDS = FALSE; psResult = poDS->HTTPFetch( osURL, NULL); if (psResult == NULL) { return NULL; } const char* pszContentType = ""; if (psResult->pszContentType) pszContentType = psResult->pszContentType; CPLString osTmpDirName = CPLSPrintf("/vsimem/tempwfs_%p", this); VSIMkdir(osTmpDirName, 0); GByte *pabyData = psResult->pabyData; int nDataLen = psResult->nDataLen; int bIsMultiPart = FALSE; const char* pszAttachementFilename = NULL; if(strstr(pszContentType,"multipart") && CPLHTTPParseMultipartMime(psResult) ) { int i; bIsMultiPart = TRUE; OGRWFSRecursiveUnlink(osTmpDirName); VSIMkdir(osTmpDirName, 0); for(i=0;i<psResult->nMimePartCount;i++) { CPLString osTmpFileName = osTmpDirName + "/"; pszAttachementFilename = OGRWFSFetchContentDispositionFilename( psResult->pasMimePart[i].papszHeaders); if (pszAttachementFilename) osTmpFileName += pszAttachementFilename; else osTmpFileName += CPLSPrintf("file_%d", i); GByte* pData = (GByte*)VSIMalloc(psResult->pasMimePart[i].nDataLen); if (pData) { memcpy(pData, psResult->pasMimePart[i].pabyData, psResult->pasMimePart[i].nDataLen); VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName, pData, psResult->pasMimePart[i].nDataLen, TRUE); VSIFCloseL(fp); } } } else pszAttachementFilename = OGRWFSFetchContentDispositionFilename( psResult->papszHeaders); int bJSON = FALSE; int bCSV = FALSE; int bKML = FALSE; int bKMZ = FALSE; int bZIP = FALSE; int bGZIP = FALSE; const char* pszOutputFormat = osOutputFormat.c_str(); if (FindSubStringInsensitive(pszContentType, "json") || FindSubStringInsensitive(pszOutputFormat, "json")) { bJSON = TRUE; } else if (FindSubStringInsensitive(pszContentType, "csv") || FindSubStringInsensitive(pszOutputFormat, "csv")) { bCSV = TRUE; } else if (FindSubStringInsensitive(pszContentType, "kml") || FindSubStringInsensitive(pszOutputFormat, "kml")) { bKML = TRUE; } else if (FindSubStringInsensitive(pszContentType, "kmz") || FindSubStringInsensitive(pszOutputFormat, "kmz")) { bKMZ = TRUE; } else if (strstr(pszContentType, "application/zip") != NULL) { bZIP = TRUE; } else if (strstr(pszContentType, "application/gzip") != NULL) { bGZIP = TRUE; } if (MustRetryIfNonCompliantServer((const char*)pabyData)) { CPLHTTPDestroyResult(psResult); return FetchGetFeature(nRequestMaxFeatures); } if (strstr((const char*)pabyData, "<ServiceExceptionReport") != NULL || strstr((const char*)pabyData, "<ows:ExceptionReport") != NULL) { if (poDS->IsOldDeegree((const char*)pabyData)) { CPLHTTPDestroyResult(psResult); return FetchGetFeature(nRequestMaxFeatures); } CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", pabyData); CPLHTTPDestroyResult(psResult); return NULL; } CPLString osTmpFileName; if (!bIsMultiPart) { if (bJSON) osTmpFileName = osTmpDirName + "/file.geojson"; else if (bZIP) osTmpFileName = osTmpDirName + "/file.zip"; else if (bCSV) osTmpFileName = osTmpDirName + "/file.csv"; else if (bKML) osTmpFileName = osTmpDirName + "/file.kml"; else if (bKMZ) osTmpFileName = osTmpDirName + "/file.kmz"; /* GML is a special case. It needs the .xsd file that has been saved */ /* as file.xsd, so we cannot used the attachement filename */ else if (pszAttachementFilename && !EQUAL(CPLGetExtension(pszAttachementFilename), "GML")) { osTmpFileName = osTmpDirName + "/"; osTmpFileName += pszAttachementFilename; } else { osTmpFileName = osTmpDirName + "/file.gfs"; VSIUnlink(osTmpFileName); osTmpFileName = osTmpDirName + "/file.gml"; } VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName, pabyData, nDataLen, TRUE); VSIFCloseL(fp); psResult->pabyData = NULL; if (bZIP) { osTmpFileName = "/vsizip/" + osTmpFileName; } else if (bGZIP) { osTmpFileName = "/vsigzip/" + osTmpFileName; } } else { pabyData = NULL; nDataLen = 0; osTmpFileName = osTmpDirName; } CPLHTTPDestroyResult(psResult); OGRDataSource* poDS; poDS = (OGRDataSource*) OGROpen(osTmpFileName, FALSE, NULL); if (poDS == NULL && (bZIP || bIsMultiPart)) { char** papszFileList = VSIReadDir(osTmpFileName); int i; for( i = 0; papszFileList != NULL && papszFileList[i] != NULL; i++ ) { CPLString osFullFilename = CPLFormFilename( osTmpFileName, papszFileList[i], NULL ); poDS = (OGRDataSource*) OGROpen(osFullFilename, FALSE, NULL); if (poDS != NULL) break; } CSLDestroy( papszFileList ); } if (poDS == NULL) { if (pabyData != NULL && !bJSON && !bZIP && strstr((const char*)pabyData, "<wfs:FeatureCollection") == NULL && strstr((const char*)pabyData, "<gml:FeatureCollection") == NULL) { if (nDataLen > 1000) pabyData[1000] = 0; CPLError(CE_Failure, CPLE_AppDefined, "Error: cannot parse %s", pabyData); } return NULL; } OGRLayer* poLayer = poDS->GetLayer(0); if (poLayer == NULL) { OGRDataSource::DestroyDataSource(poDS); return NULL; } return poDS; } /************************************************************************/ /* GetLayerDefn() */ /************************************************************************/ OGRFeatureDefn * OGRWFSLayer::GetLayerDefn() { if (poFeatureDefn) return poFeatureDefn; poDS->LoadMultipleLayerDefn(GetName(), pszNS, pszNSVal); if (poFeatureDefn) return poFeatureDefn; return BuildLayerDefn(); } /************************************************************************/ /* BuildLayerDefn() */ /************************************************************************/ OGRFeatureDefn * OGRWFSLayer::BuildLayerDefn(OGRFeatureDefn* poSrcFDefn) { int bUnsetWidthPrecision = FALSE; poFeatureDefn = new OGRFeatureDefn( pszName ); poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS); poFeatureDefn->Reference(); OGRDataSource* poDS = NULL; if (poSrcFDefn == NULL) poSrcFDefn = DescribeFeatureType(); if (poSrcFDefn == NULL) { poDS = FetchGetFeature(1); if (poDS == NULL) { return poFeatureDefn; } poSrcFDefn = poDS->GetLayer(0)->GetLayerDefn(); bGotApproximateLayerDefn = TRUE; /* We cannot trust width and precision based on a single feature */ bUnsetWidthPrecision = TRUE; } CPLString osPropertyName = CPLURLGetValue(pszBaseURL, "PROPERTYNAME"); const char* pszPropertyName = osPropertyName.c_str(); int i; poFeatureDefn->SetGeomType(poSrcFDefn->GetGeomType()); for(i=0;i<poSrcFDefn->GetFieldCount();i++) { if (pszPropertyName[0] != 0) { if (strstr(pszPropertyName, poSrcFDefn->GetFieldDefn(i)->GetNameRef()) != NULL) poFeatureDefn->AddFieldDefn(poSrcFDefn->GetFieldDefn(i)); else bGotApproximateLayerDefn = TRUE; } else { OGRFieldDefn oFieldDefn(poSrcFDefn->GetFieldDefn(i)); if (bUnsetWidthPrecision) { oFieldDefn.SetWidth(0); oFieldDefn.SetPrecision(0); } poFeatureDefn->AddFieldDefn(&oFieldDefn); } } if (poDS) OGRDataSource::DestroyDataSource(poDS); else delete poSrcFDefn; return poFeatureDefn; } /************************************************************************/ /* ResetReading() */ /************************************************************************/ void OGRWFSLayer::ResetReading() { GetLayerDefn(); if (bPagingActive) bReloadNeeded = TRUE; nPagingStartIndex = 0; nFeatureRead = 0; nFeatureCountRequested = 0; if (bReloadNeeded) { OGRDataSource::DestroyDataSource(poBaseDS); poBaseDS = NULL; poBaseLayer = NULL; bHasFetched = FALSE; bReloadNeeded = FALSE; } if (poBaseLayer) poBaseLayer->ResetReading(); } /************************************************************************/ /* GetNextFeature() */ /************************************************************************/ OGRFeature *OGRWFSLayer::GetNextFeature() { GetLayerDefn(); if (bPagingActive && nFeatureRead == nPagingStartIndex + nFeatureCountRequested) { bReloadNeeded = TRUE; nPagingStartIndex = nFeatureRead; } if (bReloadNeeded) { OGRDataSource::DestroyDataSource(poBaseDS); poBaseDS = NULL; poBaseLayer = NULL; bHasFetched = FALSE; bReloadNeeded = FALSE; } if (poBaseDS == NULL && !bHasFetched) { bHasFetched = TRUE; poBaseDS = FetchGetFeature(0); if (poBaseDS) { poBaseLayer = poBaseDS->GetLayer(0); poBaseLayer->ResetReading(); /* Check that the layer field definition is consistant with the one */ /* we got in BuildLayerDefn() */ if (poFeatureDefn->GetFieldCount() != poBaseLayer->GetLayerDefn()->GetFieldCount()) bGotApproximateLayerDefn = TRUE; else { int iField; for(iField = 0;iField < poFeatureDefn->GetFieldCount(); iField++) { OGRFieldDefn* poFDefn1 = poFeatureDefn->GetFieldDefn(iField); OGRFieldDefn* poFDefn2 = poBaseLayer->GetLayerDefn()->GetFieldDefn(iField); if (strcmp(poFDefn1->GetNameRef(), poFDefn2->GetNameRef()) != 0 || poFDefn1->GetType() != poFDefn2->GetType()) { bGotApproximateLayerDefn = TRUE; break; } } } } } if (!poBaseLayer) return NULL; while(TRUE) { OGRFeature* poSrcFeature = poBaseLayer->GetNextFeature(); if (poSrcFeature == NULL) return NULL; nFeatureRead ++; if( bCountFeaturesInGetNextFeature ) nFeatures ++; OGRGeometry* poGeom = poSrcFeature->GetGeometryRef(); if( m_poFilterGeom != NULL && poGeom != NULL && !FilterGeometry( poGeom ) ) { delete poSrcFeature; continue; } /* Client-side attribue filtering with underlying layer defn */ /* identical to exposed layer defn */ if( !bGotApproximateLayerDefn && osWFSWhere.size() == 0 && m_poAttrQuery != NULL && !m_poAttrQuery->Evaluate( poSrcFeature ) ) { delete poSrcFeature; continue; } OGRFeature* poNewFeature = new OGRFeature(poFeatureDefn); if (bGotApproximateLayerDefn) { poNewFeature->SetFrom(poSrcFeature); /* Client-side attribue filtering */ if( m_poAttrQuery != NULL && osWFSWhere.size() == 0 && !m_poAttrQuery->Evaluate( poNewFeature ) ) { delete poSrcFeature; delete poNewFeature; continue; } } else { int iField; for(iField = 0;iField < poFeatureDefn->GetFieldCount(); iField++) poNewFeature->SetField( iField, poSrcFeature->GetRawFieldRef(iField) ); poNewFeature->SetStyleString(poSrcFeature->GetStyleString()); poNewFeature->SetGeometryDirectly(poSrcFeature->StealGeometry()); } poNewFeature->SetFID(poSrcFeature->GetFID()); poGeom = poNewFeature->GetGeometryRef(); /* FIXME? I don't really know what we should do with WFS 1.1.0 */ /* and non-GML format !!! I guess 50% WFS servers must do it wrong anyway */ /* GeoServer does currently axis inversion for non GML output, but */ /* apparently this is not correct : http://jira.codehaus.org/browse/GEOS-3657 */ if (poGeom != NULL && bAxisOrderAlreadyInverted && strcmp(poBaseDS->GetDriver()->GetName(), "GML") != 0) { poGeom->swapXY(); } if (poGeom && poSRS) poGeom->assignSpatialReference(poSRS); delete poSrcFeature; return poNewFeature; } } /************************************************************************/ /* SetSpatialFilter() */ /************************************************************************/ void OGRWFSLayer::SetSpatialFilter( OGRGeometry * poGeom ) { if (bStreamingDS) bReloadNeeded = TRUE; else if (poFetchedFilterGeom == NULL && poBaseDS != NULL) { /* If there was no filter set, and that we set one */ /* the new result set can only be a subset of the whole */ /* so no need to reload from source */ bReloadNeeded = FALSE; } else if (poFetchedFilterGeom != NULL && poGeom != NULL && poBaseDS != NULL) { OGREnvelope oOldEnvelope, oNewEnvelope; poFetchedFilterGeom->getEnvelope(&oOldEnvelope); poGeom->getEnvelope(&oNewEnvelope); /* Optimization : we don't need to request the server */ /* if the new BBOX is inside the old BBOX as we have */ /* already all the features */ bReloadNeeded = ! oOldEnvelope.Contains(oNewEnvelope); } else bReloadNeeded = TRUE; nFeatures = -1; OGRLayer::SetSpatialFilter(poGeom); ResetReading(); } /************************************************************************/ /* SetAttributeFilter() */ /************************************************************************/ OGRErr OGRWFSLayer::SetAttributeFilter( const char * pszFilter ) { if (pszFilter != NULL && pszFilter[0] == 0) pszFilter = NULL; OGRErr eErr = OGRLayer::SetAttributeFilter(pszFilter); if (eErr != CE_None) return eErr; CPLString osOldWFSWhere(osWFSWhere); if (poDS->HasMinOperators() && pszFilter != NULL) { int bNeedsNullCheck = FALSE; int nVersion = (strcmp(poDS->GetVersion(),"1.0.0") == 0) ? 100 : (atoi(poDS->GetVersion()) >= 2) ? 200 : 110; osWFSWhere = WFS_TurnSQLFilterToOGCFilter(pszFilter, GetLayerDefn(), nVersion, poDS->PropertyIsNotEqualToSupported(), poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel, poDS->DoesGmlObjectIdNeedGMLPrefix(), &bNeedsNullCheck); if (bNeedsNullCheck && !poDS->HasNullCheck()) osWFSWhere = ""; if (osWFSWhere.size() == 0) { CPLDebug("WFS", "Using client-side only mode for filter \"%s\"", pszFilter); } } else osWFSWhere = ""; osSQLWhere = (pszFilter) ? pszFilter : ""; if (osWFSWhere != osOldWFSWhere) bReloadNeeded = TRUE; else bReloadNeeded = FALSE; nFeatures = -1; return CE_None; } /************************************************************************/ /* TestCapability() */ /************************************************************************/ int OGRWFSLayer::TestCapability( const char * pszCap ) { if( EQUAL(pszCap,OLCFastFeatureCount) ) { if (nFeatures >= 0) return TRUE; return poBaseLayer != NULL && m_poFilterGeom == NULL && m_poAttrQuery == NULL && poBaseLayer->TestCapability(pszCap); } else if( EQUAL(pszCap,OLCFastGetExtent) ) { if (bHasExtents) return TRUE; return poBaseLayer != NULL && poBaseLayer->TestCapability(pszCap); } else if( EQUAL(pszCap,OLCStringsAsUTF8) ) return poBaseLayer != NULL && poBaseLayer->TestCapability(pszCap); else if( EQUAL(pszCap, OLCSequentialWrite) || EQUAL(pszCap, OLCDeleteFeature) || EQUAL(pszCap, OLCRandomWrite) ) { GetLayerDefn(); return poDS->SupportTransactions() && poDS->UpdateMode() && poFeatureDefn->GetFieldIndex("gml_id") == 0; } else if ( EQUAL(pszCap, OLCTransactions) ) { return poDS->SupportTransactions() && poDS->UpdateMode(); } else if( EQUAL(pszCap,OLCIgnoreFields) ) { return poBaseDS == NULL; } return FALSE; } /************************************************************************/ /* ExecuteGetFeatureResultTypeHits() */ /************************************************************************/ int OGRWFSLayer::ExecuteGetFeatureResultTypeHits() { char* pabyData = NULL; CPLString osURL = MakeGetFeatureURL(0, TRUE); if (pszRequiredOutputFormat) osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT", WFS_EscapeURL(pszRequiredOutputFormat)); CPLDebug("WFS", "%s", osURL.c_str()); CPLHTTPResult* psResult = poDS->HTTPFetch( osURL, NULL); if (psResult == NULL) { return -1; } /* http://demo.snowflakesoftware.com:8080/Obstacle_AIXM_ZIP/GOPublisherWFS returns */ /* zip content, including for RESULTTYPE=hits */ if (psResult->pszContentType != NULL && strstr(psResult->pszContentType, "application/zip") != NULL) { CPLString osTmpFileName; osTmpFileName.Printf("/vsimem/wfstemphits_%p.zip", this); VSILFILE *fp = VSIFileFromMemBuffer( osTmpFileName, psResult->pabyData, psResult->nDataLen, FALSE); VSIFCloseL(fp); CPLString osZipTmpFileName("/vsizip/" + osTmpFileName); char** papszDirContent = CPLReadDir(osZipTmpFileName); if (CSLCount(papszDirContent) != 1) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot parse result of RESULTTYPE=hits request : more than one file in zip"); CSLDestroy(papszDirContent); CPLHTTPDestroyResult(psResult); VSIUnlink(osTmpFileName); return -1; } CPLString osFileInZipTmpFileName = osZipTmpFileName + "/"; osFileInZipTmpFileName += papszDirContent[0]; fp = VSIFOpenL(osFileInZipTmpFileName.c_str(), "rb"); if (fp == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot parse result of RESULTTYPE=hits request : cannot open one file in zip"); CSLDestroy(papszDirContent); CPLHTTPDestroyResult(psResult); VSIUnlink(osTmpFileName); return -1; } VSIStatBufL sBuf; VSIStatL(osFileInZipTmpFileName.c_str(), &sBuf); pabyData = (char*) CPLMalloc((size_t)(sBuf.st_size + 1)); pabyData[sBuf.st_size] = 0; VSIFReadL(pabyData, 1, (size_t)sBuf.st_size, fp); VSIFCloseL(fp); CSLDestroy(papszDirContent); VSIUnlink(osTmpFileName); } else { pabyData = (char*) psResult->pabyData; psResult->pabyData = NULL; } if (strstr(pabyData, "<ServiceExceptionReport") != NULL || strstr(pabyData, "<ows:ExceptionReport") != NULL) { if (poDS->IsOldDeegree(pabyData)) { CPLHTTPDestroyResult(psResult); return ExecuteGetFeatureResultTypeHits(); } CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", pabyData); CPLHTTPDestroyResult(psResult); CPLFree(pabyData); return -1; } CPLXMLNode* psXML = CPLParseXMLString( pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", pabyData); CPLHTTPDestroyResult(psResult); CPLFree(pabyData); return -1; } CPLStripXMLNamespace( psXML, NULL, TRUE ); CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=FeatureCollection" ); if (psRoot == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <FeatureCollection>"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); CPLFree(pabyData); return -1; } const char* pszValue = CPLGetXMLValue(psRoot, "numberOfFeatures", NULL); if (pszValue == NULL) pszValue = CPLGetXMLValue(psRoot, "numberMatched", NULL); /* WFS 2.0.0 */ if (pszValue == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find numberOfFeatures"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); CPLFree(pabyData); poDS->DisableSupportHits(); return -1; } int nFeatures = atoi(pszValue); /* Hum, http://deegree3-testing.deegree.org:80/deegree-inspire-node/services?MAXFEATURES=10&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=ad:Address&OUTPUTFORMAT=text/xml;%20subtype=gml/3.2.1&RESULTTYPE=hits */ /* returns more than MAXFEATURES features... So truncate to MAXFEATURES */ CPLString osMaxFeatures = CPLURLGetValue(osURL, atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES"); if (osMaxFeatures.size() != 0) { int nMaxFeatures = atoi(osMaxFeatures); if (nFeatures > nMaxFeatures) { CPLDebug("WFS", "Truncating result from %d to %d", nFeatures, nMaxFeatures); nFeatures = nMaxFeatures; } } CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); CPLFree(pabyData); return nFeatures; } /************************************************************************/ /* CanRunGetFeatureCountAndGetExtentTogether() */ /************************************************************************/ int OGRWFSLayer::CanRunGetFeatureCountAndGetExtentTogether() { /* In some cases, we can evaluate the result of GetFeatureCount() */ /* and GetExtent() with the same data */ CPLString osRequestURL = MakeGetFeatureURL(0, FALSE); return( !bHasExtents && nFeatures < 0 && osRequestURL.ifind("FILTER") == std::string::npos && osRequestURL.ifind("MAXFEATURES") == std::string::npos && osRequestURL.ifind("COUNT") == std::string::npos && !(GetLayerDefn()->IsGeometryIgnored()) ); } /************************************************************************/ /* GetFeatureCount() */ /************************************************************************/ int OGRWFSLayer::GetFeatureCount( int bForce ) { if (nFeatures >= 0) return nFeatures; if (TestCapability(OLCFastFeatureCount)) return poBaseLayer->GetFeatureCount(bForce); if ((m_poAttrQuery == NULL || osWFSWhere.size() != 0) && poDS->GetFeatureSupportHits()) { nFeatures = ExecuteGetFeatureResultTypeHits(); if (nFeatures >= 0) return nFeatures; } /* If we have not yet the base layer, try to read one */ /* feature, and then query again OLCFastFeatureCount on the */ /* base layer. In case the WFS response would contain the */ /* number of features */ if (poBaseLayer == NULL) { ResetReading(); OGRFeature* poFeature = GetNextFeature(); delete poFeature; ResetReading(); if (TestCapability(OLCFastFeatureCount)) return poBaseLayer->GetFeatureCount(bForce); } /* In some cases, we can evaluate the result of GetFeatureCount() */ /* and GetExtent() with the same data */ if( CanRunGetFeatureCountAndGetExtentTogether() ) { OGREnvelope sDummy; GetExtent(&sDummy); } if( nFeatures < 0 ) nFeatures = OGRLayer::GetFeatureCount(bForce); return nFeatures; } /************************************************************************/ /* SetExtent() */ /************************************************************************/ void OGRWFSLayer::SetExtents(double dfMinX, double dfMinY, double dfMaxX, double dfMaxY) { this->dfMinX = dfMinX; this->dfMinY = dfMinY; this->dfMaxX = dfMaxX; this->dfMaxY = dfMaxY; bHasExtents = TRUE; } /************************************************************************/ /* GetExtent() */ /************************************************************************/ OGRErr OGRWFSLayer::GetExtent(OGREnvelope *psExtent, int bForce) { if (bHasExtents) { psExtent->MinX = dfMinX; psExtent->MinY = dfMinY; psExtent->MaxX = dfMaxX; psExtent->MaxY = dfMaxY; return OGRERR_NONE; } /* If we have not yet the base layer, try to read one */ /* feature, and then query again OLCFastGetExtent on the */ /* base layer. In case the WFS response would contain the */ /* global extent */ if (poBaseLayer == NULL) { ResetReading(); OGRFeature* poFeature = GetNextFeature(); delete poFeature; ResetReading(); } if (TestCapability(OLCFastGetExtent)) return poBaseLayer->GetExtent(psExtent, bForce); /* In some cases, we can evaluate the result of GetFeatureCount() */ /* and GetExtent() with the same data */ if( CanRunGetFeatureCountAndGetExtentTogether() ) { bCountFeaturesInGetNextFeature = TRUE; nFeatures = 0; } OGRErr eErr = OGRLayer::GetExtent(psExtent, bForce); if( bCountFeaturesInGetNextFeature ) { if( eErr == OGRERR_NONE ) { dfMinX = psExtent->MinX; dfMinY = psExtent->MinY; dfMaxX = psExtent->MaxX; dfMaxY = psExtent->MaxY; bHasExtents = TRUE; } else { nFeatures = -1; } bCountFeaturesInGetNextFeature = FALSE; } return eErr; } /************************************************************************/ /* GetShortName() */ /************************************************************************/ const char* OGRWFSLayer::GetShortName() { const char* pszShortName = strchr(pszName, ':'); if (pszShortName == NULL) pszShortName = pszName; else pszShortName ++; return pszShortName; } /************************************************************************/ /* GetPostHeader() */ /************************************************************************/ CPLString OGRWFSLayer::GetPostHeader() { CPLString osPost; osPost += "<?xml version=\"1.0\"?>\n"; osPost += "<wfs:Transaction xmlns:wfs=\"http://www.opengis.net/wfs\"\n"; osPost += " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"; osPost += " service=\"WFS\" version=\""; osPost += poDS->GetVersion(); osPost += "\"\n"; osPost += " xmlns:gml=\"http://www.opengis.net/gml\"\n"; osPost += " xmlns:ogc=\"http://www.opengis.net/ogc\"\n"; osPost += " xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/"; osPost += poDS->GetVersion(); osPost += "/wfs.xsd "; osPost += osTargetNamespace; osPost += " "; char* pszXMLEncoded = CPLEscapeString( GetDescribeFeatureTypeURL(FALSE), -1, CPLES_XML); osPost += pszXMLEncoded; CPLFree(pszXMLEncoded); osPost += "\">\n"; return osPost; } /************************************************************************/ /* CreateFeature() */ /************************************************************************/ OGRErr OGRWFSLayer::CreateFeature( OGRFeature *poFeature ) { if (!TestCapability(OLCSequentialWrite)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "CreateFeature() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "CreateFeature() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (poGMLFeatureClass == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot insert feature because we didn't manage to parse the .XSD schema"); return OGRERR_FAILURE; } if (poFeatureDefn->GetFieldIndex("gml_id") != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field"); return OGRERR_FAILURE; } if (poFeature->IsFieldSet(0)) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot insert a feature when gml_id field is already set"); return OGRERR_FAILURE; } CPLString osPost; const char* pszShortName = GetShortName(); if (!bInTransaction) { osPost += GetPostHeader(); osPost += " <wfs:Insert>\n"; } osPost += " <feature:"; osPost += pszShortName; osPost += " xmlns:feature=\""; osPost += osTargetNamespace; osPost += "\">\n"; CPLLocaleC oLocaleEnforcer; int i; for(i=1; i <= poFeature->GetFieldCount(); i++) { if (poGMLFeatureClass->GetGeometryPropertyCount() == 1 && poGMLFeatureClass->GetGeometryProperty(0)->GetAttributeIndex() == i - 1) { OGRGeometry* poGeom = poFeature->GetGeometryRef(); if (poGeom != NULL && osGeometryColumnName.size() != 0) { if (poGeom->getSpatialReference() == NULL) poGeom->assignSpatialReference(poSRS); char* pszGML; if (strcmp(poDS->GetVersion(), "1.1.0") == 0) { char** papszOptions = CSLAddString(NULL, "FORMAT=GML3"); pszGML = OGR_G_ExportToGMLEx((OGRGeometryH)poGeom, papszOptions); CSLDestroy(papszOptions); } else pszGML = OGR_G_ExportToGML((OGRGeometryH)poGeom); osPost += " <feature:"; osPost += osGeometryColumnName; osPost += ">"; osPost += pszGML; osPost += "</feature:"; osPost += osGeometryColumnName; osPost += ">\n"; CPLFree(pszGML); } } if (i == poFeature->GetFieldCount()) break; if (poFeature->IsFieldSet(i)) { OGRFieldDefn* poFDefn = poFeature->GetFieldDefnRef(i); osPost += " <feature:"; osPost += poFDefn->GetNameRef(); osPost += ">"; if (poFDefn->GetType() == OFTInteger) osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i)); else if (poFDefn->GetType() == OFTReal) osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i)); else { char* pszXMLEncoded = CPLEscapeString(poFeature->GetFieldAsString(i), -1, CPLES_XML); osPost += pszXMLEncoded; CPLFree(pszXMLEncoded); } osPost += "</feature:"; osPost += poFDefn->GetNameRef(); osPost += ">\n"; } } osPost += " </feature:"; osPost += pszShortName; osPost += ">\n"; if (!bInTransaction) { osPost += " </wfs:Insert>\n"; osPost += "</wfs:Transaction>\n"; } else { osGlobalInsert += osPost; nExpectedInserts ++; return OGRERR_NONE; } CPLDebug("WFS", "Post : %s", osPost.c_str()); char** papszOptions = NULL; papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str()); papszOptions = CSLAddNameValue(papszOptions, "HEADERS", "Content-Type: application/xml; charset=UTF-8"); CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions); CSLDestroy(papszOptions); if (psResult == NULL) { return OGRERR_FAILURE; } if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL || strstr((const char*)psResult->pabyData, "<ows:ExceptionReport") != NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLDebug("WFS", "Response: %s", psResult->pabyData); CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLStripXMLNamespace( psXML, NULL, TRUE ); int bUse100Schema = FALSE; CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" ); if (psRoot == NULL) { psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" ); if (psRoot) bUse100Schema = TRUE; } if (psRoot == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <TransactionResponse>"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLXMLNode* psFeatureID = NULL; if (bUse100Schema) { if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" )) { CPLError(CE_Failure, CPLE_AppDefined, "Insert failed : %s", psResult->pabyData); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } psFeatureID = CPLGetXMLNode( psRoot, "InsertResult.FeatureId"); if (psFeatureID == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find InsertResult.FeatureId"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } } else { psFeatureID = CPLGetXMLNode( psRoot, "InsertResults.Feature.FeatureId"); if (psFeatureID == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find InsertResults.Feature.FeatureId"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } } const char* pszFID = CPLGetXMLValue(psFeatureID, "fid", NULL); if (pszFID == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find fid"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } poFeature->SetField("gml_id", pszFID); /* If the returned fid is of the form layer_name.num, then use */ /* num as the OGR FID */ if (strncmp(pszFID, pszShortName, strlen(pszShortName)) == 0 && pszFID[strlen(pszShortName)] == '.') { int nFID = atoi(pszFID + strlen(pszShortName) + 1); char szTemp[12]; sprintf(szTemp, "%d", nFID); /* Check that it fits on a int32 */ if (strcmp(szTemp, pszFID + strlen(pszShortName) + 1) == 0) poFeature->SetFID(nFID); } CPLDebug("WFS", "Got FID = %ld", poFeature->GetFID()); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); /* Invalidate layer */ bReloadNeeded = TRUE; nFeatures = -1; bHasExtents = FALSE; return OGRERR_NONE; } /************************************************************************/ /* SetFeature() */ /************************************************************************/ OGRErr OGRWFSLayer::SetFeature( OGRFeature *poFeature ) { if (!TestCapability(OLCRandomWrite)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "SetFeature() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "SetFeature() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (poFeatureDefn->GetFieldIndex("gml_id") != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field"); return OGRERR_FAILURE; } if (poFeature->IsFieldSet(0) == FALSE) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot update a feature when gml_id field is not set"); return OGRERR_FAILURE; } if (bInTransaction) { CPLError(CE_Warning, CPLE_AppDefined, "SetFeature() not yet dealt in transaction. Issued immediately"); } const char* pszShortName = GetShortName(); CPLString osPost; osPost += GetPostHeader(); osPost += " <wfs:Update typeName=\"feature:"; osPost += pszShortName; osPost += "\" xmlns:feature=\""; osPost += osTargetNamespace; osPost += "\">\n"; CPLLocaleC oLocaleEnforcer; OGRGeometry* poGeom = poFeature->GetGeometryRef(); if ( osGeometryColumnName.size() != 0 ) { osPost += " <wfs:Property>\n"; osPost += " <wfs:Name>"; osPost += osGeometryColumnName; osPost += "</wfs:Name>\n"; if (poGeom != NULL) { if (poGeom->getSpatialReference() == NULL) poGeom->assignSpatialReference(poSRS); char* pszGML; if (strcmp(poDS->GetVersion(), "1.1.0") == 0) { char** papszOptions = CSLAddString(NULL, "FORMAT=GML3"); pszGML = OGR_G_ExportToGMLEx((OGRGeometryH)poGeom, papszOptions); CSLDestroy(papszOptions); } else pszGML = OGR_G_ExportToGML((OGRGeometryH)poGeom); osPost += " <wfs:Value>"; osPost += pszGML; osPost += "</wfs:Value>\n"; CPLFree(pszGML); } osPost += " </wfs:Property>\n"; } int i; for(i=1; i < poFeature->GetFieldCount(); i++) { OGRFieldDefn* poFDefn = poFeature->GetFieldDefnRef(i); osPost += " <wfs:Property>\n"; osPost += " <wfs:Name>"; osPost += poFDefn->GetNameRef(); osPost += "</wfs:Name>\n"; if (poFeature->IsFieldSet(i)) { osPost += " <wfs:Value>"; if (poFDefn->GetType() == OFTInteger) osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i)); else if (poFDefn->GetType() == OFTReal) osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i)); else { char* pszXMLEncoded = CPLEscapeString(poFeature->GetFieldAsString(i), -1, CPLES_XML); osPost += pszXMLEncoded; CPLFree(pszXMLEncoded); } osPost += "</wfs:Value>\n"; } osPost += " </wfs:Property>\n"; } osPost += " <ogc:Filter>\n"; if (poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel) osPost += " <ogc:FeatureId fid=\""; else if (atoi(poDS->GetVersion()) >= 2) osPost += " <ogc:ResourceId rid=\""; else osPost += " <ogc:GmlObjectId gml:id=\""; osPost += poFeature->GetFieldAsString(0); osPost += "\"/>\n"; osPost += " </ogc:Filter>\n"; osPost += " </wfs:Update>\n"; osPost += "</wfs:Transaction>\n"; CPLDebug("WFS", "Post : %s", osPost.c_str()); char** papszOptions = NULL; papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str()); papszOptions = CSLAddNameValue(papszOptions, "HEADERS", "Content-Type: application/xml; charset=UTF-8"); CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions); CSLDestroy(papszOptions); if (psResult == NULL) { return OGRERR_FAILURE; } if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL || strstr((const char*)psResult->pabyData, "<ows:ExceptionReport") != NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLDebug("WFS", "Response: %s", psResult->pabyData); CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLStripXMLNamespace( psXML, NULL, TRUE ); int bUse100Schema = FALSE; CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" ); if (psRoot == NULL) { psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" ); if (psRoot) bUse100Schema = TRUE; } if (psRoot == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <TransactionResponse>"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } if (bUse100Schema) { if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" )) { CPLError(CE_Failure, CPLE_AppDefined, "Update failed : %s", psResult->pabyData); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } } CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); /* Invalidate layer */ bReloadNeeded = TRUE; nFeatures = -1; bHasExtents = FALSE; return OGRERR_NONE; } /************************************************************************/ /* GetFeature() */ /************************************************************************/ OGRFeature* OGRWFSLayer::GetFeature(long nFID) { GetLayerDefn(); if (poBaseLayer == NULL && poFeatureDefn->GetFieldIndex("gml_id") == 0) { /* This is lovely hackish. We assume that then gml_id will be */ /* layer_name.number. This is actually what we can observe with */ /* GeoServer and TinyOWS */ CPLString osVal = CPLSPrintf("gml_id = '%s.%ld'", GetShortName(), nFID); CPLString osOldSQLWhere(osSQLWhere); SetAttributeFilter(osVal); OGRFeature* poFeature = GetNextFeature(); const char* pszOldFilter = osOldSQLWhere.size() ? osOldSQLWhere.c_str() : NULL; SetAttributeFilter(pszOldFilter); if (poFeature) return poFeature; } return OGRLayer::GetFeature(nFID); } /************************************************************************/ /* DeleteFromFilter() */ /************************************************************************/ OGRErr OGRWFSLayer::DeleteFromFilter( CPLString osOGCFilter ) { if (!TestCapability(OLCDeleteFeature)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "DeleteFromFilter() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "DeleteFromFilter() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (poFeatureDefn->GetFieldIndex("gml_id") != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field"); return OGRERR_FAILURE; } const char* pszShortName = GetShortName(); CPLString osPost; osPost += GetPostHeader(); osPost += " <wfs:Delete xmlns:feature=\""; osPost += osTargetNamespace; osPost += "\" typeName=\"feature:"; osPost += pszShortName; osPost += "\">\n"; osPost += " <ogc:Filter>\n"; osPost += osOGCFilter; osPost += " </ogc:Filter>\n"; osPost += " </wfs:Delete>\n"; osPost += "</wfs:Transaction>\n"; CPLDebug("WFS", "Post : %s", osPost.c_str()); char** papszOptions = NULL; papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str()); papszOptions = CSLAddNameValue(papszOptions, "HEADERS", "Content-Type: application/xml; charset=UTF-8"); CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions); CSLDestroy(papszOptions); if (psResult == NULL) { return OGRERR_FAILURE; } if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL || strstr((const char*)psResult->pabyData, "<ows:ExceptionReport") != NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLDebug("WFS", "Response: %s", psResult->pabyData); CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLStripXMLNamespace( psXML, NULL, TRUE ); int bUse100Schema = FALSE; CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" ); if (psRoot == NULL) { psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" ); if (psRoot) bUse100Schema = TRUE; } if (psRoot == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <TransactionResponse>"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } if (bUse100Schema) { if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" )) { CPLError(CE_Failure, CPLE_AppDefined, "Delete failed : %s", psResult->pabyData); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } } CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); /* Invalidate layer */ bReloadNeeded = TRUE; nFeatures = -1; bHasExtents = FALSE; return OGRERR_NONE; } /************************************************************************/ /* DeleteFeature() */ /************************************************************************/ OGRErr OGRWFSLayer::DeleteFeature( long nFID ) { if (!TestCapability(OLCDeleteFeature)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "DeleteFeature() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "DeleteFeature() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (poFeatureDefn->GetFieldIndex("gml_id") != 0) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field"); return OGRERR_FAILURE; } OGRFeature* poFeature = GetFeature(nFID); if (poFeature == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find feature %ld", nFID); return OGRERR_FAILURE; } const char* pszGMLID = poFeature->GetFieldAsString("gml_id"); if (pszGMLID == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot delete a feature with gml_id unset"); delete poFeature; return OGRERR_FAILURE; } if (bInTransaction) { CPLError(CE_Warning, CPLE_AppDefined, "DeleteFeature() not yet dealt in transaction. Issued immediately"); } CPLString osGMLID = pszGMLID; pszGMLID = NULL; delete poFeature; poFeature = NULL; CPLString osFilter; osFilter = "<ogc:FeatureId fid=\""; osFilter += osGMLID; osFilter += "\"/>\n"; return DeleteFromFilter(osFilter); } /************************************************************************/ /* StartTransaction() */ /************************************************************************/ OGRErr OGRWFSLayer::StartTransaction() { if (!TestCapability(OLCTransactions)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "StartTransaction() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "StartTransaction() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (bInTransaction) { CPLError(CE_Failure, CPLE_AppDefined, "StartTransaction() has already been called"); return OGRERR_FAILURE; } bInTransaction = TRUE; osGlobalInsert = ""; nExpectedInserts = 0; aosFIDList.resize(0); return OGRERR_NONE; } /************************************************************************/ /* CommitTransaction() */ /************************************************************************/ OGRErr OGRWFSLayer::CommitTransaction() { if (!TestCapability(OLCTransactions)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "CommitTransaction() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "CommitTransaction() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (!bInTransaction) { CPLError(CE_Failure, CPLE_AppDefined, "StartTransaction() has not yet been called"); return OGRERR_FAILURE; } if (osGlobalInsert.size() != 0) { CPLString osPost = GetPostHeader(); osPost += " <wfs:Insert>\n"; osPost += osGlobalInsert; osPost += " </wfs:Insert>\n"; osPost += "</wfs:Transaction>\n"; bInTransaction = FALSE; osGlobalInsert = ""; int nExpectedInserts = this->nExpectedInserts; this->nExpectedInserts = 0; CPLDebug("WFS", "Post : %s", osPost.c_str()); char** papszOptions = NULL; papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str()); papszOptions = CSLAddNameValue(papszOptions, "HEADERS", "Content-Type: application/xml; charset=UTF-8"); CPLHTTPResult* psResult = poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions); CSLDestroy(papszOptions); if (psResult == NULL) { return OGRERR_FAILURE; } if (strstr((const char*)psResult->pabyData, "<ServiceExceptionReport") != NULL || strstr((const char*)psResult->pabyData, "<ows:ExceptionReport") != NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLDebug("WFS", "Response: %s", psResult->pabyData); CPLXMLNode* psXML = CPLParseXMLString( (const char*) psResult->pabyData ); if (psXML == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s", psResult->pabyData); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLStripXMLNamespace( psXML, NULL, TRUE ); int bUse100Schema = FALSE; CPLXMLNode* psRoot = CPLGetXMLNode( psXML, "=TransactionResponse" ); if (psRoot == NULL) { psRoot = CPLGetXMLNode( psXML, "=WFS_TransactionResponse" ); if (psRoot) bUse100Schema = TRUE; } if (psRoot == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <TransactionResponse>"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } if (bUse100Schema) { if (CPLGetXMLNode( psRoot, "TransactionResult.Status.FAILED" )) { CPLError(CE_Failure, CPLE_AppDefined, "Insert failed : %s", psResult->pabyData); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } /* TODO */ } else { int nGotInserted = atoi(CPLGetXMLValue(psRoot, "TransactionSummary.totalInserted", "")); if (nGotInserted != nExpectedInserts) { CPLError(CE_Failure, CPLE_AppDefined, "Only %d features were inserted whereas %d where expected", nGotInserted, nExpectedInserts); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } CPLXMLNode* psInsertResults = CPLGetXMLNode( psRoot, "InsertResults"); if (psInsertResults == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find node InsertResults"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } aosFIDList.resize(0); CPLXMLNode* psChild = psInsertResults->psChild; while(psChild) { const char* pszFID = CPLGetXMLValue(psChild, "FeatureId.fid", NULL); if (pszFID == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot find fid"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } aosFIDList.push_back(pszFID); psChild = psChild->psNext; } if ((int)aosFIDList.size() != nGotInserted) { CPLError(CE_Failure, CPLE_AppDefined, "Inconsistant InsertResults: did not get expected FID count"); CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); return OGRERR_FAILURE; } } CPLDestroyXMLNode( psXML ); CPLHTTPDestroyResult(psResult); } bInTransaction = FALSE; osGlobalInsert = ""; nExpectedInserts = 0; return OGRERR_NONE; } /************************************************************************/ /* RollbackTransaction() */ /************************************************************************/ OGRErr OGRWFSLayer::RollbackTransaction() { if (!TestCapability(OLCTransactions)) { if (!poDS->SupportTransactions()) CPLError(CE_Failure, CPLE_AppDefined, "RollbackTransaction() not supported: no WMS-T features advertized by server"); else if (!poDS->UpdateMode()) CPLError(CE_Failure, CPLE_AppDefined, "RollbackTransaction() not supported: datasource opened as read-only"); return OGRERR_FAILURE; } if (!bInTransaction) { CPLError(CE_Failure, CPLE_AppDefined, "StartTransaction() has not yet been called"); return OGRERR_FAILURE; } bInTransaction = FALSE; osGlobalInsert = ""; nExpectedInserts = 0; return OGRERR_NONE; } /************************************************************************/ /* SetRequiredOutputFormat() */ /************************************************************************/ void OGRWFSLayer::SetRequiredOutputFormat(const char* pszRequiredOutputFormatIn) { CPLFree(pszRequiredOutputFormat); if (pszRequiredOutputFormatIn) { pszRequiredOutputFormat = CPLStrdup(pszRequiredOutputFormatIn); } else { pszRequiredOutputFormat = NULL; } } /************************************************************************/ /* SetOrderBy() */ /************************************************************************/ void OGRWFSLayer::SetOrderBy(const char* pszFieldToSort, int bAscFlag) { osFieldToSort = pszFieldToSort ? pszFieldToSort : ""; this->bAscFlag = bAscFlag; }
; A182241: a(n) = A161151(2*n)/2 ; 3,10,7,36,11,26,15,136,19,42,23,100,27,58,31,528,35,74,39,164,43,90,47,392,51,106,55,228,59,122,63,2080,67,138,71,292,75,154,79,648,83,170,87,356,91,186,95,1552,99 mov $3,10 mov $7,1 add $7,$0 mov $5,$7 add $5,$0 mov $0,2 add $3,$5 mov $2,$3 mov $5,9 mov $6,5 mov $9,9 sub $9,$7 add $9,$7 lpb $0 div $0,$2 mov $1,1 mov $4,$6 add $4,1 add $4,$9 add $4,6988081 sub $5,$2 sub $1,$5 mov $8,$5 gcd $8,$4 lpe mul $1,2 mul $1,$8 sub $1,12 div $1,4 add $1,3
// This file is here only to bring in the parts of Reflection.mm that apply // when not using an objc runtime. #include "swift/Runtime/Config.h" #if !SWIFT_OBJC_INTEROP #include "Reflection.mm" #endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: spreadsheetChart.asm AUTHOR: John Wedgwood, Sep 16, 1991 METHODS: Name Description ---- ----------- MSG_SPREADSHEET_CHART_RANGE Chart the selected range REVISION HISTORY: Name Date Description ---- ---- ----------- John 9/16/91 Initial revision DESCRIPTION: Charting code for the spreadsheet library. $Id: spreadsheetChart.asm,v 1.2 98/03/11 21:20:15 gene Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetChartCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Template for the Chart cell. The chart cell consists of a header CellChart structure, (which is basically just a CellFormula structure), followed by the expression of the formula itself. Since the chart formula never returns a value, we use the ERR formula (this is a catch-all formula that simply dumps all its arguments, and propagates the error to its dependents). As the chart cell never has any dependents, this is no problem. Since there is no value stored in RV_VALUE, the VM block handle of the chart objects is stored there. The chart formula is: =ERR(range), where the range is made up of two cells, for example: =ERR(A1:C5). Cell references are absolute, since the chart cell isn't expected to move at any time. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ chartCellTemplate CellChart << < ; CF_common 0, ; CC_dependencies CT_CHART, ; CC_type 0, ; CC_recalcFlags DEFAULT_STYLE_TOKEN, ; CC_attrs 0 ; CC_nots >, RT_VALUE, ; CF_return <RV_VALUE <0,0,0,0,0>>, ; CF_current (FloatNum) CHART_FORMULA_SIZE ; CF_formulaSize >> ; ; Template for the formula that defines the chart. ; ; ; Function token ; byte PARSER_TOKEN_FUNCTION ParserTokenFunctionData < FUNCTION_ID_ERR ; bullshit value > CHART_TEMPLATE_RANGE_FIRST_CELL = $-chartCellTemplate ; ; First cell (absolute references) ; byte PARSER_TOKEN_CELL ParserTokenCellData < < <1, 0>, <1, 0> > > ; ; The separator between the two cells in the range. ; byte PARSER_TOKEN_OPERATOR ParserTokenOperatorData < OP_RANGE_SEPARATOR > CHART_TEMPLATE_RANGE_SECOND_CELL = $-chartCellTemplate ; ; Last cell ; byte PARSER_TOKEN_CELL ParserTokenCellData < < <1, 0>, <1, 0> > > byte PARSER_TOKEN_ARG_END byte PARSER_TOKEN_CLOSE_FUNCTION byte PARSER_TOKEN_END_OF_EXPRESSION align 2 CHART_CELL_SIZE = $-chartCellTemplate ; Formula size is size of entire cell minus the (fixed-size) header part CHART_FORMULA_SIZE = CHART_CELL_SIZE - (size CellChart) if _CHARTS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetChartRange %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Chart the current range. CALLED BY: via MSG_SPREADSHEET_CHART_RANGE PASS: *ds:si = Instance ptr ds:di = Instance ptr es = Class segment ax = MSG_SPREADSHEET_CHART_RANGE cl = ChartType ch = ChartVariation RETURN: al - ChartReturnType if CRT_OTHER_ERROR ah - SpreadsheetChartReturnType DESTROYED: cx,dx,bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/16/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetChartRange method dynamic SpreadsheetClass, MSG_SPREADSHEET_CHART_RANGE locals local SpreadsheetChartLocals call SpreadsheetMarkBusy .enter CheckHack <offset SCL_variation eq offset SCL_type+1 > mov {word} locals.SCL_type, cx mov si, di ; ds:si <- instance ptr ; No chart body, no chart! mov ax, CRT_OTHER_ERROR or (SCRT_INSUFFICIENT_MEMORY shl 8) tst ds:[si].SSI_chartBody.chunk EC < ERROR_Z SPREADSHEET_NO_CHART_BODY ;> NEC < LONG jz quit ;> ; ; Find a cell to put the chart in. ; mov ax, offset FindEmptyCellCB mov dl, mask REF_ALL_CELLS or mask REF_NO_LOCK call FindChartCell ; cx <- column to hold the ; chart mov ax, CRT_OTHER_ERROR or (SCRT_TOO_MANY_CHARTS shl 8) LONG jnc quit ; Branch if there's no space for it mov locals.SCL_cell, cx ; Figure out call GetRangeToChart LONG jc quit mov locals.SCL_enum.REP_bounds.R_left, cx mov locals.SCL_enum.REP_bounds.R_top, ax mov locals.SCL_enum.REP_bounds.R_right, bx mov locals.SCL_enum.REP_bounds.R_bottom, dx ; ; Allocate a chart cell ; mov cx, locals.SCL_cell ; cx <- column for chart cell call AllocChartCell ; Create the cell itself ; ; Create data block for charting ; call CreateChartData LONG jc errorNotEnoughMemory ; Branch on error mov locals.SCL_block, ax ; store VM handle ; ; Create a GState so we can get the window bounds. If no ; gstate, then we don't know where to draw the chart, so bail. ; push bp mov si, ds:[si].SSI_chunk mov ax, MSG_VIS_VUP_CREATE_GSTATE call ObjCallInstanceNoLock mov di, bp pop bp pushf mov si, ds:[si] add si, ds:[si].Spreadsheet_offset popf LONG jnc noGState ; ; Set up the chart creation parameters ; mov ax, locals.SCL_block mov bx, {word} locals.SCL_type push bp sub sp, size ChartCreateParameters mov bp, sp mov ss:[bp].CCP_data, ax CheckHack <offset CCP_variation eq offset CCP_type+1> mov {word} ss:[bp].CCP_type, bx push ds, si sub sp, size RectDWord segmov ds, ss, si mov si, sp call GrGetWinBoundsDWord call GrDestroyState ; Place chart in the lower-right hand quarter of the screen ; -- 1/4 the screen size, unless that is too small ; -- positioned in the lower right ; Leave some room for the grobj handles! movdw bxax, ds:[si].RD_right subdw bxax, ds:[si].RD_left sardw bxax ;ax <- window width / 2 EC < tst bx ;> EC < ERROR_NZ SPREADSHEET_CHART_TOO_LARGE ;> cmp ax, DEFAULT_CHART_WIDTH jae widthOK mov ax, DEFAULT_CHART_WIDTH widthOK: mov ss:[bp].CCP_size.P_x, ax ;set width clr bx ;bx:ax <- chart width movdw dxcx, ds:[si].RD_right subdw dxcx, CHART_MARGIN subdw dxcx, bxax ;dx:cx <- chart left movdw ss:[bp].CCP_position.PD_x, dxcx ;set left coord movdw bxax, ds:[si].RD_bottom subdw bxax, ds:[si].RD_top sardw bxax EC < tst bx ;> EC < ERROR_NZ SPREADSHEET_CHART_TOO_LARGE ;> cmp ax, DEFAULT_CHART_HEIGHT jae heightOK mov ax, DEFAULT_CHART_HEIGHT heightOK: mov ss:[bp].CCP_size.P_y, ax ;set height clr bx ;bx:ax <- chart height movdw dxcx, ds:[si].RD_bottom subdw dxcx, CHART_MARGIN subdw dxcx, bxax ;dx:cx <- chart top movdw ss:[bp].CCP_position.PD_y, dxcx ;set top coord add sp, size RectDWord pop ds, si push si movdw bxsi, ds:[si].SSI_chartBody mov ax, MSG_CHART_BODY_CREATE_CHART mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage mov bx, cx ; VM block handle of created chart pop si add sp, size ChartCreateParameters pop bp cmp al, CRT_OK jne errorFreeCell ; ; Save VM block handle of new chart. ; mov ax, CHART_ROW ; ax <- cell row mov cx, locals.SCL_cell SpreadsheetCellLock ; *es:di <- chart cell EC < ERROR_NC CELL_DOES_NOT_EXIST ;baby, baby, where did my cell go?> mov di, es:[di] ; es:di <- chart cell mov {word} es:[di].CG_formula.CF_current, bx SpreadsheetCellDirty ; Dirty the cell SpreadsheetCellUnlock ; Release the cell mov al, CRT_OK quit: .leave call SpreadsheetMarkNotBusy ret noGState: ; AX is a VM block that won't be needed, so free it. mov bx, ds:[si].SSI_cellParams.CFP_file call VMFree ; ax <- new vm block handle errorNotEnoughMemory: mov ax, CRT_OTHER_ERROR or (SCRT_INSUFFICIENT_MEMORY shl 8) errorFreeCell: ; ; Free the chart cell ; mov cx, ss:[locals].SCL_cell call SpreadsheetDeleteChartCell jmp quit SpreadsheetChartRange endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetRangeToChart %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the range to chart CALLED BY: SpreadsheetChartRange() PASS: ds:si - ptr to RETURN: (ax,cx), (dx,bx) - range to chart carry - set for error al - ChartReturnType if CRT_OTHER_ERROR ah - SpreadsheetChartReturnType DESTROYED: none PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- gene 2/28/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetRangeToChart proc near uses di class SpreadsheetClass extent local CellRange reParams local RangeEnumParams ForceRef extent ForceRef reParams .enter ; ; Get the extent of the data within the selection ; mov cx, ds:[si].SSI_selected.CR_start.CR_column mov ax, ds:[si].SSI_selected.CR_start.CR_row mov bx, ds:[si].SSI_selected.CR_end.CR_column mov dx, ds:[si].SSI_selected.CR_end.CR_row mov di, SET_NO_EMPTY_CELLS call CallRangeExtent mov di, CRT_OTHER_ERROR or (SCRT_NO_DATA shl 8) je errorCommon ;branch if no data ; ; See if there are too many rows (categories) or columns (series) ; mov di, bx sub di, cx inc di ;di <- # of columns cmp di, MAX_SERIES_COUNT mov di, CRT_TOO_MANY_SERIES ja errorCommon mov di, dx sub di, ax inc di ;di <- # of rows cmp di, MAX_CATEGORY_COUNT mov di, CRT_TOO_MANY_CATEGORIES ja errorCommon clc ;carry <- no error quit: .leave ret errorCommon: mov ax, di ;ax <- ChartReturnType, etc. stc ;carry <- error jmp quit GetRangeToChart endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetDeleteChart %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Delete a chart from the spreadsheet. CALLED BY: via MSG_SPREADSHEET_DELETE_CHART PASS: *ds:si = Instance ptr ds:di = Instance ptr cx = VM block handle of chart that's being deleted RETURN: nothing DESTROYED: ax,cx,dx,bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetDeleteChart method dynamic SpreadsheetClass, MSG_SPREADSHEET_DELETE_CHART .enter mov si, di ; ds:si - spreadsheet instance mov ax, offset FindPassedChartCB clr dl ; RangeEnumFlags call FindChartCell ; cx <- column jnc done call SpreadsheetDeleteChartCell done: .leave ret SpreadsheetDeleteChart endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetDeleteChartCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Delete the cell containing the chart formula CALLED BY: SpreadsheetDeleteChart, SpreadsheetChartRange PASS: cx - column of chart cell RETURN: nothing DESTROYED: bx,cx,dx PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chrisb 12/28/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetDeleteChartCell proc near uses ax .enter mov ax, CHART_ROW ; ax <- row mov dx, -1 ; Signal: remove dependencies call FormulaCellAddParserRemoveDependencies ; ; Remove the cell itself. ; clr dx SpreadsheetCellReplaceAll .leave ret SpreadsheetDeleteChartCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindChartCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Find an empty cell to put the chart in. CALLED BY: SpreadsheetChartRange PASS: ds:si = Spreadsheet instance ax - offset of callback routine cx - data to pass to callback dl - RangeEnumFlags RETURN: if found carry set cx = column # of cell else carry clear DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindChartCell proc near uses dx locals local RangeEnumParams .enter mov locals.REP_bounds.R_top, CHART_ROW mov locals.REP_bounds.R_bottom, CHART_ROW mov locals.REP_bounds.R_left, 0 mov locals.REP_bounds.R_right, LARGEST_COLUMN mov locals.REP_callback.segment, SEGMENT_CS mov locals.REP_callback.offset, ax push bp lea bx, locals mov bp, cx ; starting value call RangeEnum ; mov cx, bp ; column # pop bp .leave ret FindChartCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindPassedChartCB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: callback routine to find the passed chart vm block CALLED BY: SpreadsheetDeleteChart via RangeEnum PASS: bp - VM block handle of chart block *es:di - chart cell RETURN: if found: carry set bp - column else carry clear DESTROYED: di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- cdb 8/29/92 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindPassedChartCB proc far .enter mov di, es:[di] cmp {word} es:[di].CG_formula.CF_current, bp je found clc done: .leave ret found: mov bp, cx ; column number stc jmp done FindPassedChartCB endp if _CHARTS COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindEmptyCellCB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Find an empty cell if one exists. CALLED BY: FindChartCell via RangeEnum PASS: carry clear if we've found an empty cell cx - column # RETURN: carry set to abort bp = Column of the cell DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindEmptyCellCB proc far cmc ; set carry if empty, clear carry ; otherwise mov bp, cx ; bp <- column ret FindEmptyCellCB endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AllocChartCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate a chart cell for the currently selected range. CALLED BY: SpreadsheetChartRange PASS: ds:si = Spreadsheet instance cx = Column to hold the chart ss:bp - inherited locals locals.SCL_enum.REP_bounds - area to chart RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The only argument to the chart formula is the range of data in the chart. The chart formula looks like: Chart Function Chart Range End Function End Expression KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AllocChartCell proc near uses ax, bx, cx, dx, di, bp, es .enter inherit SpreadsheetChartRange sub sp, CHART_CELL_SIZE ; Allocate stack frame mov bx, sp ; ss:bp <- frame ptr ; ; Fill the buffer with the cell data. ; ; ds:si = Spreadsheet instance ; ss:bx = Pointer to of block to build in ; cx = Column of the chart cell ; segmov es, ss, di ; es:di <- ptr to data mov di, bx call FillInChartCellData ; Put the cell data in there ; ; Create the cell and copy in the data. ; mov dx, CHART_CELL_SIZE ; dx <- size of the data mov ax, CHART_ROW ; ax <- row SpreadsheetCellReplaceAll ; Poof... A chart cell ; ; Now add add the dependencies for the chart cell. ; ax/cx = Row/Column of the cell ; ds:si = Spreadsheet instance ; clr dx ; Signal: add dependencies call FormulaCellAddParserRemoveDependencies add sp, CHART_CELL_SIZE ; Restore stack frame .leave ret AllocChartCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FillInChartCellData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fill in the cell data associated with a chart cell. CALLED BY: AllocChartCell() PASS: es:di = Pointer to the block to fill in. ds:si = Spreadsheet object ss:bp - inherited locals locals.SCL_enum.REP_bounds - area to chart RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FillInChartCellData proc near uses cx, di, si, ds .enter inherit AllocChartCell EC < call ECCheckPointerESDI > push ds, si, di ; Save ptr to buffer segmov ds, cs, si ; ds:si <- source mov si, offset chartCellTemplate mov cx, CHART_CELL_SIZE ; cx <- size rep movsb ; Copy the data pop ds, si, di ; Restore ptr to buffer call FillInChartFormula ; Fill in the formula .leave ret FillInChartCellData endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FillInChartFormula %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fill in the chart-formula block. CALLED BY: FillInChartCellData() PASS: ds:si = Spreadsheet instance es:di = Place to put the formula ss:bp - inherited locals locals.SCL_enum.REP_bounds - area to chart RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FillInChartFormula proc near class SpreadsheetClass uses ax, bx EC < call ECCheckInstancePtr > .enter inherit FillInChartCellData ; ; Stuff the range, being careful not to overwrite CRC_ABSOLUTE ; flags. ; mov bx, CHART_TEMPLATE_RANGE_FIRST_CELL mov ax, ss:locals.SCL_enum.REP_bounds.R_top ornf es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_row, ax mov ax, ss:locals.SCL_enum.REP_bounds.R_left ornf es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_column, ax mov bx, CHART_TEMPLATE_RANGE_SECOND_CELL mov ax, ss:locals.SCL_enum.REP_bounds.R_bottom ornf es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_row, ax mov ax, ss:locals.SCL_enum.REP_bounds.R_right ornf es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_column, ax .leave ret FillInChartFormula endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateChartData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create a chart data block for a given chart. CALLED BY: SpreadsheetChartRange, SpreadsheetRecalcChart PASS: ds:si = Spreadsheet instance ss:bp = inherited SpreadsheetChartLocals SCL_enum.REP_bounds filled in RETURN: ax - data block VM handle carry - set if error DESTROYED: nothing PSEUDO CODE/STRATEGY: Create a block block.nCols = nColumns block.nRows = nRows curCell = &block.cellHdr ptr = end of block.cellHdr Foreach cell in range: curCell->ptr = ptr ptr->cellType = cell.type ptr = CopyCellData(cell,ptr) KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/20/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CreateChartData proc near class SpreadsheetClass uses bx, cx, dx, bp, es .enter inherit SpreadsheetChartRange ; ; Allocate the parameter block ; call AllocParameterBlock ; bx <- block handle ; es <- block segment ; cx <- block size LONG jc quit ; Branch if couldn't allocate mov locals.SCL_block, bx ; Save block handle mov locals.SCL_blockSize, cx ; Save block size ; ; Initialize it. ; mov es:CD_endOfData, cx mov ax, locals.SCL_enum.REP_bounds.R_bottom sub ax, locals.SCL_enum.REP_bounds.R_top inc ax mov es:CD_nRows, ax mov cx, locals.SCL_enum.REP_bounds.R_right sub cx, locals.SCL_enum.REP_bounds.R_left inc cx mov es:CD_nColumns, cx call MemUnlock ; Release the block ; ; Set up the next cell ptr / data ptr ; mov locals.SCL_nextCellPtr, size ChartData mul cx ; ax <- # of cells shl ax, 1 ; ax <- size of table add ax, size ChartData ; Account for header mov locals.SCL_nextCellData, ax ; Set up callback address for RangeEnum mov locals.SCL_enum.REP_callback.segment, SEGMENT_CS mov locals.SCL_enum.REP_callback.offset, \ offset CreateDataCallback ; ; Call a callback for each cell in the selection ; lea bx, locals.SCL_enum ; ss:bx <- RangeEnumParams mov dl, mask REF_ALL_CELLS ; Callback for all cells call RangeEnum ; Fill in the block jc quitError ; Branch on error ; ; Resize the block down to the final size. This realloc should always ; succeed since we are always making the block smaller or keeping it ; the same size. ; mov ax, locals.SCL_nextCellData ; ax <- ptr past block end mov bx, locals.SCL_block ; bx <- block handle clr ch ; No HeapAllocFlags call MemReAlloc ; ax <- segment address ; ; Associate the memory block with the VM file. ; mov cx, bx ; cx <- block handle clr ax ; Allocate new vm block mov bx, ds:[si].SSI_cellParams.CFP_file call VMAttach ; ax <- new vm block handle clc ; Signal no error quit: ; ; Carry set on error ; Carry clear otherwise, ax = VM block handle ; .leave ret quitError: ; ; Free up the block ; mov bx, locals.SCL_block call MemFree stc ; Signal error again jmp quit CreateChartData endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AllocParameterBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Allocate a chart-parameter block CALLED BY: CreateChartData PASS: ds:si = Spreadsheet instance RETURN: bx = Block handle es = Segment address of locked block cx = Size of block carry set if the block couldn't be allocated DESTROYED: nothing PSEUDO CODE/STRATEGY: The size to allocate is: size ChartData + size word * (nColumn * nRows) KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AllocParameterBlock proc near class SpreadsheetClass uses ax, dx locals local SpreadsheetChartLocals .enter inherit mov ax, locals.SCL_enum.REP_bounds.R_bottom sub ax, locals.SCL_enum.REP_bounds.R_top inc ax mov cx, locals.SCL_enum.REP_bounds.R_right ; cx <- nColumns sub cx, locals.SCL_enum.REP_bounds.R_left inc cx mul cx ; ax <- nRows*nColumns shl ax, 1 ; size of a word add ax, size ChartData ; Size of header ; ; ax = Size of block to allocate ; push ax ; Save size mov cx, ALLOC_DYNAMIC_LOCK or \ (mask HAF_ZERO_INIT shl 8) call MemAlloc ; bx <- block handle ; ax <- segment address ; ; Carry set on error ; pop cx ; cx <- size of block mov es, ax ; es <- segment address .leave ret AllocParameterBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateDataCallback %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Add another cell to the parameters block CALLED BY: via RangeEnum PASS: ds:si = Spreadsheet instance *es:di = Cell data (if any) ax = Row cx = Column ss:bp = SpreadsheetChartLocals carry clear if cell is empty RETURN: carry set on alloc error DESTROYED: nothing PSEUDO CODE/STRATEGY: type = cell type dsize = data size ptr = nextCellData if (ptr + dsize + 1 > blockSize) { ReAlloc block larger if (error) { quit error } } block.ptr.type = type CopyData(cellData, &block.ptr.data, dsize) nextCellPtr = nextCellData nextCellData += dsize + 1 nextCellPtr += size word quit no error KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CreateDataCallback proc far uses ax, bx, cx, dx, di, si, ds, es locals local SpreadsheetChartLocals .enter inherit call GetCellDataAndSize ; al <- cell type ; cx <- cell data size ; ; al = Cell type ; cx = Cell data size ; *es:di= Cell (if it exists) ; mov bx, locals.SCL_block ; bx <- block handle mov dx, locals.SCL_nextCellData ; dx <- ptr past data add dx, cx ; ; Bail if we're going to wrap beyond 64K or even 16K ; jc quit ; branch if overflow cmp dx, 1024*16 ja quitError ; branch if too large inc dx ; +1 for ? cmp dx, locals.SCL_blockSize ; Check for not enough block jbe gotSpace call ReAllocParamBlock ; Make block bigger jc quit ; Branch if there's an error mov locals.SCL_blockSize, dx ; Save new block size gotSpace: ; ; There is enough space in the block. Lock it down and copy the data. ; push ax ; Save cell type call MemLock ; ax <- segment address mov ds, ax ; ds <- param block segment mov si, locals.SCL_nextCellData ; ds:si <- place for data pop ax ; Restore cell type ; ; al = Cell type ; bx = Block handle ; cx = Size of cell data ; ds:si = Place to put cell data ; locals.SCL_buffer = data to copy ; push cx, ds, si segmov es, ds, di ; es:di <- ptr to buffer mov di, si stosb ; Save the cell type jcxz afterCopy ; Branch if no data segmov ds, ss, si ; ds:si <- data lea si, locals.SCL_buffer rep movsb ; Copy the data afterCopy: pop cx, ds, si ; ; Update local variables ; add cx, locals.SCL_nextCellData ; cx <- offset past data inc cx ; Account for type byte mov locals.SCL_nextCellData, cx ; Save new end of data mov ds:CD_endOfData, cx mov di, locals.SCL_nextCellPtr ; di <- place to store ptr mov {word} ds:[di], si ; Save ptr add locals.SCL_nextCellPtr, size word ; ; Release the block ; call MemUnlock ; Release the parameter block clc ; Signal: no error quit: .leave ret quitError: stc ;carry <- error jmp quit CreateDataCallback endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetCellDataAndSize %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Given a pointer to a cell figure the type of the cell data and the size of the cell data. CALLED BY: CreateDataCallback PASS: *es:di = Cell data ds:si = Spreadsheet instance ax = Row cx = Column ss:bp = SpreadsheetChartLocals carry set if cell exists RETURN: al = ChartDataCellType cx = Size of data SCL_buffer filled with cell data DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetCellDataAndSize proc near uses bx, di, bp locals local SpreadsheetChartLocals .enter inherit jnc noCell lea bp, locals.SCL_buffer ; ss:bp <- destination buffer mov di, es:[di] ; es:di <- cell data clr bh ; bx <- cell type mov bl, es:[di].CC_type call cs:getDataHandler[bx] ; Call the handler quit: .leave ret noCell: mov al, CDCT_EMPTY ; Empty cell clr cx ; No data jmp quit GetCellDataAndSize endp getDataHandler nptr offset cs:GetTextCell, ; CT_TEXT offset cs:GetConstantCell, ; CT_CONSTANT offset cs:GetFormulaCell, ; CT_FORMULA offset cs:GetError, ; CT_NAME offset cs:GetError, ; CT_CHART offset cs:GetEmpty, ; CT_EMPTY offset cs:GetDisplayFormulaCell ; CT_DISPLAY_FORMULA .assert (size getDataHandler) eq CellType GetError proc near ERROR UNEXPECTED_CELL_DATA_TYPE GetError endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the text from a text cell. CALLED BY: GetCellDataAndSize PASS: es:di = Cell data ds:si = Spreadsheet instance ss:bp = Buffer to fill with text RETURN: al = Cell type cx = Size of cell data Buffer filled with text DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextCell proc near uses di .enter add di, size CellText ; es:di <- ptr to the text call GetString ; Copy the string... .leave ret GetTextCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy a string into a buffer CALLED BY: GetTextCell, GetFormulaCell PASS: ss:bp = Buffer to fill es:di = Text to copy RETURN: cx = Length of text (including NULL) al = CDCT_TEXT DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetString proc near uses di, si, ds, es .enter call GetStringSetup ; ; Copy the bytes, stopping after a NULL ; push di ; Save ptr to buffer start LocalCopyString pop ax ; ax <- buffer start sub di, ax ; di <- # of bytes copied mov cx, di ; Return length in cx mov al, CDCT_TEXT ; al <- type .leave ret GetString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetFormulaString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy a formula string into a buffer CALLED BY: GetFormulaCell() PASS: ss:bp = Buffer to fill es:di = Text to copy cx = # of characters to copy RETURN: al = CDCT_TEXT cx = # of characters including NULL DESTROYED: ah PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/9/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetFormulaString proc near uses di, si, ds, es .enter push cx call GetStringSetup LocalCopyNString pop cx inc cx ;cx <- +1 for NULL LocalLoadChar ax, NULL LocalPutChar esdi, ax mov al, CDCT_TEXT ;al <- type .leave ret GetFormulaString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetStringSetup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Setup to copy a string into a buffer CALLED BY: GetString(), GetFormulaString() PASS: ss:bp = buffer to fill es:di = text to copy RETURN: ds:si = text to copy es:di = buffer to fill DESTROYED: ax PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- eca 3/9/98 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetStringSetup proc near .enter segmov ds, ss, si ;ds:si <- ptr to buffer mov si, bp segxchg ds, es ;ds:si <- ptr to text xchg di, si ;es:di <- ptr to buffer LocalGetChar ax, dssi, NO_ADVANCE ;ax <- character of string SBCS< cmp al, C_SNG_QUOTE > DBCS< cmp ax, C_APOSTROPHE_QUOTE > je skipChar SBCS< cmp al, C_QUOTE > DBCS< cmp ax, C_QUOTATION_MARK > jne doCopy skipChar: LocalNextChar dssi ;skip initial quote doCopy: .leave ret GetStringSetup endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetConstantCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get a constant cell into a buffer... CALLED BY: GetCellDataAndSize PASS: es:di = Cell data ds:si = Spreadsheet instance ss:bp = Buffer to fill RETURN: al = Cell type cx = Size of data Buffer filled with the number DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetConstantCell proc near uses di .enter lea di, es:[di].CC_current ; es:di <- Number to copy call GetNumber ; al/cx <- Return values .leave ret GetConstantCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetNumber %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy a number to the buffer CALLED BY: GetConstantCell, GetFormulaCell PASS: es:di = Number to copy ss:bp = Buffer to put it in RETURN: cx = size FloatNum al = CDCT_NUMBER DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetNumber proc near uses di, si, ds, es .enter segmov ds, es, si ; ds:si <- source mov si, di segmov es, ss, di ; es:di <- dest mov di, bp ; ; Copy the data ; mov cx, size FloatNum ; cx <- # of bytes rep movsb ; Copy the data ; ; Return values ; mov cx, size FloatNum ; cx <- # of bytes mov al, CDCT_NUMBER ; al <- type .leave ret GetNumber endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetFormulaCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the result of a formula into the buffer CALLED BY: GetCellDataAndSize PASS: es:di = Cell data ds:si = Spreadsheet instance ss:bp = Buffer to fill RETURN: al = Cell type cx = Size of data Buffer filled with the data DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetFormulaCell proc near uses bx, di, es .enter cmp es:[di].CF_return, RT_VALUE je copyConstant cmp es:[di].CF_return, RT_TEXT je copyText cmp es:[di].CF_return, RT_ERROR je copyError ; ; We shouldn't get here... ; EC < ERROR UNEXPECTED_CELL_DATA_TYPE > quit: .leave ret copyConstant: ; ; Copy the constant into the buffer ; lea di, ds:[di].CF_current ; es:di <- Number to copy call GetNumber ; al/cx <- Return values jmp quit copyText: ; ; Copy the text into the buffer ; mov cx, es:[di].CF_current.RV_TEXT mov ax, es:[di].CF_formulaSize add ax, size CellFormula add di, ax ;es:di <- ptr to text call GetFormulaString ;al/cx <- Return values jmp quit copyError: ; ; Format the error into the buffer ; mov bl, es:[di].CF_current.RV_ERROR segmov es, ss, di ; es:di <- buffer ptr mov di, bp call CalcFormatError ; Format error into buffer ; di <- ptr past buffer sub di, bp ; di <- size mov cx, di ; cx <- size mov al, CDCT_TEXT ; al <- type jmp quit GetFormulaCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetEmpty %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy an empty cell to the buffer. CALLED BY: GetCellDataAndSize PASS: es:di = Cell data ds:si = Spreadsheet instance ss:bp = Buffer to fill RETURN: al = Cell type cx = Size of data DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetEmpty proc near mov al, CDCT_EMPTY ; al <- type clr cx ; cx <- data size ret GetEmpty endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetDisplayFormulaCell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the result of a display formula into the buffer CALLED BY: GetCellDataAndSize PASS: es:di = Cell data ds:si = Spreadsheet instance ss:bp = Buffer to fill RETURN: al = Cell type cx = Size of data Buffer filled with the data DESTROYED: nothing PSEUDO CODE/STRATEGY: Format a "TYPE" error into the buffer and return that. KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetDisplayFormulaCell proc near uses bx, di, es .enter mov bl, CE_TYPE ; bl <- error code segmov es, ss, di ; es:di <- buffer ptr mov di, bp call CalcFormatError ; Format error into buffer ; di <- ptr past buffer sub di, bp ; di <- size mov cx, di ; cx <- size mov al, CDCT_TEXT ; al <- type .leave ret GetDisplayFormulaCell endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ReAllocParamBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Reallocate the chart parameter block CALLED BY: CreateDataCallback PASS: bx = Block handle dx = Minimum total size for the block RETURN: dx = Size we realloc'd the block to carry set if we were unable to realloc DESTROYED: nothing PSEUDO CODE/STRATEGY: For now we just allocate as much space as we need an no more. At some time we may want to change this so that extra space is allocated. KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 11/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ReAllocParamBlock proc near uses ax, cx .enter mov ax, dx ; ax <- new size clr ch ; No HeapAllocFlags call MemReAlloc ; Make block bigger .leave ret ReAllocParamBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SpreadsheetRecalcChart %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Recalculate a chart cell. CALLED BY: RecalcOneCell PASS: ds:si = Instance ptr es:di = Pointer to a chart cell ss:bp = Pointer to PCT_vars on the stack cx = column number of chart RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jcw 9/18/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpreadsheetRecalcChart proc far locals local SpreadsheetChartLocals uses ax,bx,cx,si,di class SpreadsheetClass .enter EC < call ECCheckInstancePtr > ; No chart body, no chart! tst ds:[si].SSI_chartBody.chunk jz done ; extract the range from the formula, and stick it in the ; local variables structure, clearing the high bit. Values ; should be unsigned, so I won't worry about sign-extending. mov bx, CHART_TEMPLATE_RANGE_FIRST_CELL mov ax, es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_row call checkAndFixupAX mov locals.SCL_enum.REP_bounds.R_top, ax mov ax, es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_column call checkAndFixupAX mov locals.SCL_enum.REP_bounds.R_left, ax mov bx, CHART_TEMPLATE_RANGE_SECOND_CELL mov ax, es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_row call checkAndFixupAX mov locals.SCL_enum.REP_bounds.R_bottom, ax mov ax, es:[di][bx].PT_data.PTD_cell.PTCD_cellRef.CR_column call checkAndFixupAX mov locals.SCL_enum.REP_bounds.R_right, ax lea bx, locals.SCL_enum.REP_bounds call FixupChartRecalcRange jc noData ; get chart's VM block handle mov cx, {word} es:[di].CG_formula.CF_current ; Create the parameters block call CreateChartData jc done mov_tr dx, ax ; vm block of chart data mov bx, ds:[si].SSI_chartBody.handle mov si, ds:[si].SSI_chartBody.chunk mov ax, MSG_META_SUSPEND mov di, mask MF_FIXUP_DS or mask MF_FIXUP_ES call ObjMessage mov ax, MSG_CHART_BODY_UPDATE_CHART mov di, mask MF_FIXUP_DS or mask MF_FIXUP_ES call ObjMessage mov ax, MSG_META_UNSUSPEND mov di, mask MF_FORCE_QUEUE call ObjMessage done: .leave ret checkAndFixupAX: ; ; See if AX is bogus. There's probably a constant for this, ; but I don't know what it is. If so, just bail, as we don't ; have time for a more robust solution. ; cmp ax, 0xffff je bogus andnf ax, not mask CRC_ABSOLUTE retn bogus: pop ax ; nuke the return address -- we won't ; be needing it jmp done noData: mov bx, ds:[si].SSI_chartBody.handle mov si, ds:[si].SSI_chartBody.chunk mov ax, MSG_GB_DELETE_SELECTED_GROBJS clr di call ObjMessage jmp done SpreadsheetRecalcChart endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FixupChartRecalcRange %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fix cell range for recalculating a chart cell (removing empty cells) CALLED BY: SpreadsheetRecalcChart PASS: ds:si = Instance ptr ss:bx = Rectangle range to check RETURN: carry clear if ok ss:[bx] = fixed range carry set if no data DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- brianc 9/29/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FixupChartRecalcRange proc near uses di, bp extent local CellRange reParams local RangeEnumParams .enter ; Used by called procedure. ForceRef extent ForceRef reParams push bx mov ax, ss:[bx].R_top mov cx, ss:[bx].R_left mov dx, ss:[bx].R_bottom mov bx, ss:[bx].R_right mov di, SET_NO_EMPTY_CELLS call CallRangeExtent mov di, bx ; di = R_right pop bx ; ss:bx = range stc ; assume no data je done ; yep, no data mov ss:[bx].R_top, ax mov ss:[bx].R_left, cx mov ss:[bx].R_bottom, dx mov ss:[bx].R_right, di clc done: .leave ret FixupChartRecalcRange endp endif SpreadsheetChartCode ends
TITLE QUICK - Copyright (c) SLR Systems 1994 INCLUDE MACROS INCLUDE SYMBOLS INCLUDE MODULES if fg_segm INCLUDE SEGMSYMS endif if fg_pe INCLUDE RESSTRUC endif PUBLIC TQUICK_NUMERIC,TQUICK_ALPHA,TQUICK_ALPHA_XREF .DATA EXTERNDEF XR_CURNMOD_GINDEX:DWORD EXTERNDEF FIRST_IMPMOD_GINDEX:DWORD,FIRST_MODULE_GINDEX:DWORD,FIRST_ENTRYNAME_GINDEX:DWORD EXTERNDEF FIRST_RESNAME_GINDEX:DWORD,FIRST_EXTERNAL_GINDEX:DWORD,FIRST__IMP__GINDEX:DWORD EXTERNDEF MODULE_GARRAY:STD_PTR_S,SYMBOL_GARRAY:STD_PTR_S,ENTRYNAME_GARRAY:STD_PTR_S,IMPNAME_GARRAY:STD_PTR_S EXTERNDEF RESNAME_GARRAY:STD_PTR_S .CODE PASS2_TEXT EXTERNDEF GET_NEW_LOG_BLK:PROC,STORE_XREF_ENTRY:PROC QEXCHANGE MACRO MOV EAX,[ESI] MOV EBX,[EDI] MOV [EDI],EAX MOV [ESI],EBX ENDM QUICK_VARS STRUC QN_SYMBOL_TEXT_BP DB SYMBOL_TEXT_SIZE DUP(?) QAX_TO_DSSI_BP DD ? QAX_TO_ESDI_BP DD ? QAX_COMPARE_BP DD ? QAX_MOVE_TEXT_BP DD ? QDELTA_BP DD ? QLEFT_NUMBER_BP DD ? QRIGHT_NUMBER_BP DD ? Q_OS2_NUMBER_BP DD ? QLEFT_PTR_BP DD ? QRIGHT_PTR_BP DD ? QMIDDLE_PTR_BP DD ? QN_BUFFER_PTR_BP DD ? QN_SYMBOL_MODULE_BP DD ? QN_SYMBOL_HASH_BP DD ? QN_SYMBOL_LENGTH_BP DD ? QN_PTR_BP DD ? QUICK_VARS ENDS FIX MACRO X X EQU ([EBP-SIZE QUICK_VARS].(X&_BP)) ENDM FIX QAX_TO_DSSI FIX QAX_TO_ESDI FIX QAX_COMPARE FIX QAX_MOVE_TEXT FIX QDELTA FIX QLEFT_NUMBER FIX QRIGHT_NUMBER FIX Q_OS2_NUMBER FIX QLEFT_PTR FIX QRIGHT_PTR FIX QMIDDLE_PTR FIX QN_BUFFER_PTR FIX QN_SYMBOL_MODULE FIX QN_SYMBOL_HASH FIX QN_SYMBOL_LENGTH FIX QN_SYMBOL_TEXT FIX QN_PTR TQUICK_NUMERIC PROC ; ;USE QUICKSORT ALGORITHM TO SORT SYMBOL TABLE IN NUMERIC ;ORDER ; ; ;FIRST COPY INDEXES TO ANOTHER AREA FOR EASY SORTING ; PUSHM EBP,EDI,ESI,EBX ;SAVE THAT STACK FRAME MOV EBP,ESP ASSUME EBP:PTR QUICK_VARS ; ; Adjust ESP in 4K increments ; SUB ESP,SIZEOF QUICK_VARS - SYMBOL_TEXT_SIZE - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP MOV QN_BUFFER_PTR,EAX CALL QUICK_INIT CALL QUICK_NUM MOV ESP,EBP POPM EBX,ESI,EDI,EBP RET TQUICK_NUMERIC ENDP QUICK_NUMERIC_1 PROC NEAR PRIVATE QUICK_2: ; ;JUST SORT THE TWO AND RETURN... ; CALL Q_SET_LEFT_BLOCK ;DS:SI CALL Q_SET_RIGHT_BLOCK ;ES:DI JMP QN_SORT2 QUICK3: POP EAX QUICK2_FINISH: QUICK_DONE: RET QUICK_NUM:: ; ;OK BOYS, HERE GOES A QUICK-SORT IMPLEMENTATION... ; ;ESI IS LEFT SYMBOL #, EDI IS RIGHT SYMBOL # ; MOV ECX,EDI QUICK_NUM_1: SUB ECX,ESI JNA QUICK_DONE ;RIGHT <= LEFT, QUIT ; ;WHAT ABOUT REAL SMALL CX ? ; INC ECX JZ QUICK_DONE ;NO SYMBOLS AT ALL... CMP ECX,2 JZ QUICK_2 MOV QDELTA,ECX SHR ECX,1 PUSH ESI ;SAVE ORIGINAL LEFTY ADD ECX,ESI ;HALF WAY IN BETWEEN... MOV QRIGHT_NUMBER,EDI MOV QLEFT_NUMBER,ESI CALL Q_SET_LEFT_BLOCK ;DS:SI MOV QLEFT_PTR,ESI CALL Q_SET_RIGHT_BLOCK ;ES:DI MOV QRIGHT_PTR,EDI CALL Q_SET_MIDDLE_BLOCK ;ES:DI MOV QMIDDLE_PTR,EDI ; ;DO THREE-SOME SORT ; ;IF LEFT>MIDDLE, XCHG LEFT&MIDDLE ; CALL QN_SORT2 ; ;IF LEFT > RIGHT, XCHG LEFT&RIGHT ; MOV EDI,QRIGHT_PTR CALL QN_SORT2 ; ;LASTLY, IF MIDDLE > RIGHT, XCHG MIDDLE&RIGHT ; MOV ESI,QMIDDLE_PTR CALL QN_SORT2 CMP QDELTA,3 JZ QUICK3 ; ;NOW XCHG MIDDLE WITH RIGHT-1 ; CALL DEC_RIGHT_ESDI QEXCHANGE MOV EAX,QRIGHT_NUMBER ;SAVE RIGHTY ; ;DEFINE TEST SYMBOL FROM RIGHT END (ORIGINALLY FROM MIDDLE) ; MOV ESI,[EDI] ;GET RIGHT SYMBOL VALUE CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT PUSH EAX MOV EBX,[ESI]._S_OFFSET CALL DEC_RIGHT_ESDI MOV ECX,[ESI]._S_OS2_NUMBER ;SECTION INDEX AND SELECTOR NUM ARE SAME ADDRESS MOV QRIGHT_PTR,EDI MOV ESI,QLEFT_PTR ASSUME ESI:NOTHING CALL INC_LEFT_DSSI ; ;SCAN FROM LEFT UNTIL SOMETHING FOUND >= CX:BX ; MOV EDX,QLEFT_NUMBER QNL_AGAIN: QNL_LOOP: ; ;COMPARE LEFT SYMBOL ; MOV EDI,[ESI] ;GET NEXT INDEX ADD ESI,4 CONVERT EDI,EDI,SYMBOL_GARRAY ASSUME EDI:PTR SYMBOL_STRUCT MOV EAX,[EDI]._S_OS2_NUMBER CMP EAX,ECX ;IF OVERLAYS, THIS IS SECTION # JC QNL_NEXT MOV EAX,[EDI]._S_OFFSET JNZ QNL_TRY_RIGHT CMP EAX,EBX JNC QNL_TRY_RIGHT QNL_NEXT: LEA EAX,[EDX+1] INC EDX TEST EAX,PAGE_SIZE/4 - 1 JNZ QNL_LOOP MOV ESI,EDX CALL Q_SET_LEFT_BLOCK JMP QNL_LOOP QNL_TRY_RIGHT: ; ;OOPS, CHANGE AND SCAN FROM OTHER DIRECTION ; SUB ESI,4 MOV EDI,QRIGHT_PTR ASSUME EDI:NOTHING MOV QLEFT_NUMBER,EDX MOV EDX,QRIGHT_NUMBER MOV QLEFT_PTR,ESI ; ;SCAN FROM RIGHT UNTIL SOMETHING FOUND <= CX:BX ; QNR_LOOP: MOV ESI,[EDI] SUB EDI,4 CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT CMP [ESI]._S_OS2_NUMBER,ECX ;IF OVERLAYS, THIS IS SECTION # JC QNR_SWAP MOV EAX,[ESI]._S_OFFSET JNZ QNR_NEXT CMP EAX,EBX JBE QNR_SWAP QNR_NEXT: MOV EAX,EDX DEC EDX TEST EAX,PAGE_SIZE/4-1 JNZ QNR_LOOP MOV EDI,EDX CALL Q_SET_RIGHT_BLOCK JMP QNR_LOOP QNR_SWAP: ; ;SWAP INDEXES IN TABLE PLEASE ; ADD EDI,4 MOV ESI,QLEFT_PTR ASSUME ESI:NOTHING MOV QRIGHT_PTR,EDI MOV EAX,QLEFT_NUMBER MOV QRIGHT_NUMBER,EDX CMP EAX,EDX MOV EAX,[ESI] JNC QN_DONE1 ;SAME, CANNOT SWAP MOV EDX,[EDI] MOV [EDI],EAX MOV [ESI],EDX ; ;MOVE BOTH POINTERS ; CALL DEC_RIGHT_ESDI MOV QRIGHT_PTR,EDI CALL INC_LEFT_DSSI MOV EDX,QLEFT_NUMBER MOV EAX,QRIGHT_NUMBER CMP EAX,EDX JAE QNL_AGAIN ;JUMP IF ANY LEFT QN_DONE1: ; ;SWAP R+1 WITH ORIGINAL PTR... ; POP EDI ; THIS BECOMES i PUSH EDI CALL Q_SET_RIGHT_BLOCK QEXCHANGE ;SWAP THEM... ; ;DETERMINE WHICH HALF WILL BE PROCESSED...(WE WANT TO DO SMALLER HALF) ; POP ECX ;ORIGINAL RIGHTY - WHERE MIDDLE WAS STORED POP EDX ;ORIGINAL LEFT INC ECX MOV EAX,QRIGHT_NUMBER MOV EBX,ECX MOV EDI,QLEFT_NUMBER SUB EAX,EDX SUB EBX,EDI CMP EAX,EBX JC QN_DONE2 ; ;LETS SAY DO SECOND HALF FIRST ; MOV EAX,QRIGHT_NUMBER PUSH EDX ;SAVE ORIGINAL LEFT NUMBER PUSH EAX ;RIGHT TO USE THERE LEA ESI,[EDI+1] MOV EDI,ECX CALL QUICK_NUM POPM EDI,ESI MOV ECX,EDI JMP QUICK_NUM_1 QN_DONE2: ; ;LETS SAY DO FIRST HALF FIRST ; INC EDI MOV ESI,EDX PUSH EDI PUSH ECX MOV EDI,QRIGHT_NUMBER CALL QUICK_NUM POPM EDI,ESI MOV ECX,EDI JMP QUICK_NUM_1 QUICK_NUMERIC_1 ENDP QUICK_INIT PROC NEAR PRIVATE ; ;DO SETUP FOR A QUICKSORT ; MOV ECX,QN_BUFFER_PTR MOV EAX,[ECX] ADD ECX,4 TEST EAX,EAX ;ANY BLOCKS ALLOCATED? JNZ L51$ ;YES, PTRS ALREADY COPIED MOV QN_PTR,ECX ;PLACE FOR BLOCK #'S CALL QUICK_ANOTHER_BLOCK ; ;FIRST DO ALL IMPORTED SYMBOLS ; OR ECX,-1 CALL ADD_IMPORTS OR ECX,-1 CALL ADD__IMPS ; ;NOW, DO ALL DEFINED SYMBOLS, BY MODULE ; MOV ESI,FIRST_MODULE_GINDEX XOR ECX,ECX JMP TEST_MODULE MODULE_LOOP: CONVERT ESI,ESI,MODULE_GARRAY ASSUME ESI:PTR MODULE_STRUCT MOV EAX,[ESI]._M_NEXT_MODULE_GINDEX MOV ESI,[ESI]._M_FIRST_PUB_GINDEX PUSH EAX JMP TEST_PUBLIC L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ PUBLIC_LOOP: MOV EDX,ESI CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT MOV EAX,DPTR [ESI]._S_NSYM_TYPE MOV ECX,[ESI]._S_NEXT_SYM_GINDEX AND AH,MASK S_SPACES PUSH ECX JNZ NEXT_PUBLIC CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV DPTR [EBX+EDI],EDX ADD EDI,4 NEXT_PUBLIC: POP ESI TEST_PUBLIC: TEST ESI,ESI JNZ PUBLIC_LOOP POP ESI JMP TEST_MODULE L405$: CALL QUICK_ANOTHER_BLOCK JMP L406$ TEST_MODULE: TEST ESI,ESI JNZ MODULE_LOOP INIT_FINAL:: CMP EDI,PAGE_SIZE JZ L405$ L406$: MOV [EBX+EDI],ECX ;MARK END OF INDEXES WITH A ZERO ADD EDI,4 ;FOR TBLNEXT? ; ;NOW WE GET READY TO SORT! ; ASSUME ESI:NOTHING ; ;HOW MANY SYMBOLS ARE THERE? ; MOV ECX,QN_BUFFER_PTR MOV EAX,QN_PTR SHR EDI,2 SUB EAX,ECX SUB EAX,8 SHL EAX,PAGE_BITS-4 ADD EAX,EDI MOV [ECX],EAX L51$: MOV ECX,QN_BUFFER_PTR MOV EDI,[ECX] ; ;EDI IS # OF SYMBOLS ; XOR EAX,EAX XOR ESI,ESI ;SI (LEFT) SYMBOL IS 0 DEC EAX SUB EDI,2 ;DI (RIGHT) SYMBOL IS LAST_SYMBOL RET QUICK_INIT ENDP if fg_segm OR fg_pe QUICK_ENTRY_INIT PROC NEAR ; ;DO SETUP FOR A QUICKSORT ; MOV EAX,QN_BUFFER_PTR ADD EAX,4 ;SKIP COUNT MOV QN_PTR,EAX ;PLACE FOR BLOCK #'S CALL QUICK_ANOTHER_BLOCK MOV ESI,FIRST_ENTRYNAME_GINDEX JMP TEST_ENTRY ENTRY_LOOP: MOV EDX,ESI CONVERT ESI,ESI,ENT_GARRAY ASSUME ESI:PTR ENT_STRUCT MOV ECX,[ESI]._ENT_NEXT_ENT_GINDEX CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV [EBX+EDI],EDX ADD EDI,4 MOV ESI,ECX TEST_ENTRY: TEST ESI,ESI JNZ ENTRY_LOOP JMP INIT_FINAL L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ QUICK_ENTRY_INIT ENDP ASSUME ESI:NOTHING endif if fg_pe QUICK_RESNAMES_INIT PROC NEAR ; ;DO SETUP FOR A QUICKSORT ; MOV EAX,QN_BUFFER_PTR ADD EAX,4 MOV QN_PTR,EAX ;PLACE FOR BLOCK #'S CALL QUICK_ANOTHER_BLOCK MOV ESI,FIRST_RESNAME_GINDEX JMP TEST_RESNAME RESNAME_LOOP: MOV EDX,ESI CONVERT ESI,ESI,RESNAME_GARRAY ASSUME ESI:PTR RESNAME_STRUCT MOV ECX,[ESI]._RN_NEXT_RN_GINDEX CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV [EBX+EDI],EDX ADD EDI,4 MOV ESI,ECX TEST_RESNAME: TEST ESI,ESI JNZ RESNAME_LOOP JMP INIT_FINAL L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ ASSUME ESI:NOTHING QUICK_RESNAMES_INIT ENDP endif QUICK_XREF_INIT PROC NEAR ; ;DO SETUP FOR A QUICKSORT ; MOV EAX,QN_BUFFER_PTR ADD EAX,4 MOV QN_PTR,EAX ;PLACE FOR BLOCK #'S CALL QUICK_ANOTHER_BLOCK ; ;ADD FROM FIRST_EXTERNAL_GINDEX, ALL MODULE PUBLICS, IMPORTED SYMBOLS IF REFERENCED, WEAK, LAZY, ALIAS TOO? ; ; ;FIRST DO ALL IMPORTED SYMBOLS ; XOR ECX,ECX CALL ADD_IMPORTS XOR ECX,ECX CALL ADD__IMPS ; ;NOW, DO ALL DEFINED SYMBOLS, BY MODULE ; MOV ESI,FIRST_MODULE_GINDEX XOR ECX,ECX JMP TEST_MODULE MODULE_LOOP: CONVERT ESI,ESI,MODULE_GARRAY ASSUME ESI:PTR MODULE_STRUCT MOV EAX,[ESI]._M_NEXT_MODULE_GINDEX MOV ESI,[ESI]._M_FIRST_PUB_GINDEX PUSH EAX JMP TEST_PUBLIC L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ PUBLIC_LOOP: MOV EDX,ESI CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT MOV EAX,DPTR [ESI]._S_NSYM_TYPE MOV ECX,[ESI]._S_NEXT_SYM_GINDEX AND AH,MASK S_SPACES PUSH ECX JNZ NEXT_PUBLIC CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV DPTR [EBX+EDI],EDX XOR ECX,ECX ADD EDI,4 MOV [ESI]._S_LAST_XREF,ECX NEXT_PUBLIC: POP ESI TEST_PUBLIC: TEST ESI,ESI JNZ PUBLIC_LOOP POP ESI ; JMP TEST_MODULE TEST_MODULE: TEST ESI,ESI JNZ MODULE_LOOP ; ;ADD UNDEFINED SYMBOLS TO LIST ; MOV EAX,FIRST_EXTERNAL_GINDEX CALL ADD_LIST_NOMOD ; MOV EAX,FIRST_ALIAS_DEFINED_GINDEX ; CALL ADD_LIST ; MOV EAX,FIRST_WEAK_DEFINED_GINDEX ; CALL ADD_LIST ; MOV EAX,FIRST_LAZY_DEFINED_GINDEX ; CALL ADD_LIST ; ;NOW WE GET READY TO SORT! ; ;HOW MANY SYMBOLS ARE THERE? ; JMP INIT_FINAL ASSUME ESI:NOTHING QUICK_XREF_INIT ENDP ADD_LIST_NOMOD PROC ; ;EAX IS SYMBOL ; MOV ESI,EAX JMP TEST_PUBLIC PUBLIC_LOOP: MOV EDX,ESI CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT MOV EAX,DPTR [ESI]._S_NSYM_TYPE MOV ECX,[ESI]._S_NEXT_SYM_GINDEX AND AH,MASK S_SPACES PUSH ECX JNZ NEXT_PUBLIC CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV DPTR [EBX+EDI],EDX XOR ECX,ECX ADD EDI,4 MOV [ESI]._S_LAST_XREF,ECX MOV [ESI]._S_DEFINING_MOD,ECX NEXT_PUBLIC: POP ESI TEST_PUBLIC: TEST ESI,ESI JNZ PUBLIC_LOOP RET L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ ASSUME ESI:NOTHING ADD_LIST_NOMOD ENDP ADD_IMPORTS PROC ; ;ECX IS XREF FLAG ; MOV ESI,FIRST_IMPMOD_GINDEX JMP TEST_IMPMOD IMPMOD_LOOP: CONVERT ESI,ESI,IMPMOD_GARRAY ASSUME ESI:PTR IMPMOD_STRUCT MOV EDX,[ESI]._IMPM_NAME_SYM_GINDEX CALL ADD_IMPORTED_SYMBOLS MOV EDX,[ESI]._IMPM_ORD_SYM_GINDEX CALL ADD_IMPORTED_SYMBOLS MOV ESI,[ESI]._IMPM_NEXT_GINDEX TEST_IMPMOD: TEST ESI,ESI JNZ IMPMOD_LOOP RET ADD_IMPORTS ENDP ADD_IMPORTED_SYMBOLS PROC ; ; ; TEST EDX,EDX JZ L9$ PUSH ESI MOV ESI,EDX PUBLIC_LOOP: MOV EDX,ESI CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT MOV AL,[ESI]._S_REF_FLAGS TEST AL,MASK S_SPACES JNZ NEXT_PUBLIC TEST AL,MASK S_REFERENCED JZ NEXT_PUBLIC CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV DPTR [EBX+EDI],EDX ADD EDI,4 TEST ECX,ECX JNZ NEXT_PUBLIC MOV [ESI]._S_LAST_XREF,ECX NEXT_PUBLIC: MOV ESI,[ESI]._S_NEXT_SYM_GINDEX TEST_PUBLIC: TEST ESI,ESI JNZ PUBLIC_LOOP POP ESI L9$: RET L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ ASSUME ESI:NOTHING ADD_IMPORTED_SYMBOLS ENDP ADD__IMPS PROC ; ; ; MOV EDX,FIRST__IMP__GINDEX TEST EDX,EDX JZ L9$ PUSH ESI MOV ESI,EDX PUBLIC_LOOP: MOV EDX,ESI CONVERT ESI,ESI,SYMBOL_GARRAY ASSUME ESI:PTR SYMBOL_STRUCT MOV AL,[ESI]._S_REF_FLAGS TEST AL,MASK S_SPACES JNZ NEXT_PUBLIC ; TEST AL,MASK S_REFERENCED ; JZ NEXT_PUBLIC CMP EDI,PAGE_SIZE JZ L265$ L266$: MOV DPTR [EBX+EDI],EDX ADD EDI,4 TEST ECX,ECX JNZ NEXT_PUBLIC MOV [ESI]._S_LAST_XREF,ECX NEXT_PUBLIC: MOV ESI,[ESI]._S_NEXT_SYM_GINDEX TEST_PUBLIC: TEST ESI,ESI JNZ PUBLIC_LOOP POP ESI L9$: RET L265$: CALL QUICK_ANOTHER_BLOCK JMP L266$ ASSUME ESI:NOTHING ADD__IMPS ENDP QUICK_ANOTHER_BLOCK PROC NEAR PRIVATE ; ;ES:DI:AX ; MOV EDI,QN_PTR CALL GET_NEW_LOG_BLK ;CAN STAY IN FASTER MEMORY... MOV [EDI],EAX ADD EDI,4 MOV EBX,EAX MOV QN_PTR,EDI MOV DPTR [EDI],0 XOR EDI,EDI RET QUICK_ANOTHER_BLOCK ENDP Q_SET_LEFT_BLOCK PROC NEAR PRIVATE ; ;ESI IS SYMBOL # ;SET ESI TO BE LEFT POINTER... ; PUSH ECX MOV EAX,ESI SHR EAX,PAGE_BITS-2 MOV ECX,QN_BUFFER_PTR AND ESI,PAGE_SIZE/4-1 SHL ESI,2 MOV EAX,[ECX+EAX*4+4] POP ECX ADD ESI,EAX RET Q_SET_LEFT_BLOCK ENDP Q_SET_RIGHT_BLOCK PROC NEAR PRIVATE ; ;SET EDI TO BE RIGHT POINTER... ; PUSH ECX MOV EAX,EDI SHR EAX,PAGE_BITS-2 MOV ECX,QN_BUFFER_PTR AND EDI,PAGE_SIZE/4-1 SHL EDI,2 MOV EAX,[ECX+EAX*4+4] ;LOGICAL BLOCK ADDRESS POP ECX ADD EDI,EAX RET Q_SET_RIGHT_BLOCK ENDP Q_SET_MIDDLE_BLOCK PROC NEAR PRIVATE ; ;SET ES:DI TO BE RIGHT POINTER... ; MOV EAX,ECX MOV EDI,ECX PUSH ECX MOV ECX,QN_BUFFER_PTR SHR EAX,PAGE_BITS-2 AND EDI,PAGE_SIZE/4-1 SHL EDI,2 MOV EAX,[ECX+EAX*4+4] ;LOGICAL BLOCK ADDRESS POP ECX ADD EDI,EAX RET Q_SET_MIDDLE_BLOCK ENDP QN_SORT2 PROC NEAR ; ;SORT [DS:SI] VS [ES:DI] ; MOV EAX,[ESI] MOV EBX,[EDI] CONVERT EAX,EAX,SYMBOL_GARRAY CONVERT EBX,EBX,SYMBOL_GARRAY ASSUME EAX:PTR SYMBOL_STRUCT ASSUME EBX:PTR SYMBOL_STRUCT if fg_prot OR any_overlays MOV EDX,[EAX]._S_OS2_NUMBER MOV ECX,[EBX]._S_OS2_NUMBER CMP ECX,EDX JNZ L1$ endif MOV EDX,[EAX]._S_OFFSET ; MOV ECX,[EBX]._S_OFFSET CMP ECX,EDX L1$: JNC L3$ ; ;XCHG THEM ; QEXCHANGE L3$: RET ASSUME EAX:NOTHING,EBX:NOTHING QN_SORT2 ENDP QAX_TO_DSSI_SYMBOL PROC NEAR ; ; ; CONVERT ESI,ESI,SYMBOL_GARRAY ADD ESI,SYMBOL_STRUCT._S_NAME_TEXT RET QAX_TO_DSSI_SYMBOL ENDP QAX_TO_ESDI_SYMBOL PROC NEAR ; ; ; CONVERT EDI,EDI,SYMBOL_GARRAY ADD EDI,SYMBOL_STRUCT._S_NAME_TEXT RET QAX_TO_ESDI_SYMBOL ENDP QA_SORT2 PROC NEAR ; ;SORT [DS:SI] VS [ES:DI] ; PUSHM ESI,EDI MOV ESI,[ESI] ;PT TO SYMBOL MOV EDI,[EDI] ;PT TO SYMBOL CALL QAX_TO_DSSI CALL QAX_TO_ESDI MOV ECX,-1 CALL QAX_COMPARE POPM EDI,ESI JBE L2$ QEXCHANGE L2$: RET QA_SORT2 ENDP QAX_COMPARE_BYTE PROC NEAR ; ; ; REPE CMPSB RET QAX_COMPARE_BYTE ENDP QAX_COMPARE_WORD PROC NEAR REPE CMPSW RET QAX_COMPARE_WORD ENDP DEC_RIGHT_ESDI PROC NEAR PRIVATE ; ; ; MOV EAX,QRIGHT_NUMBER SUB EDI,4 TEST EAX,PAGE_SIZE/4-1 JZ L9$ DEC EAX MOV QRIGHT_NUMBER,EAX RET L9$: DEC EAX MOV QRIGHT_NUMBER,EAX MOV EDI,EAX JMP Q_SET_RIGHT_BLOCK DEC_RIGHT_ESDI ENDP INC_LEFT_DSSI PROC NEAR PRIVATE ; ; ; MOV EAX,QLEFT_NUMBER ADD ESI,4 INC EAX MOV QLEFT_NUMBER,EAX TEST EAX,PAGE_SIZE/4-1 JZ L9$ RET L9$: MOV ESI,EAX JMP Q_SET_LEFT_BLOCK INC_LEFT_DSSI ENDP QAX_MOVE_ASCIZ PROC NEAR ; ; ; LEA ECX,QN_SYMBOL_TEXT LEA EBX,QN_SYMBOL_TEXT NEG ECX L1$: MOV EAX,[ESI] ADD ESI,4 MOV [EBX],EAX ADD EBX,4 OR AL,AL JZ L2$ OR AH,AH JZ L3$ TEST EAX,000FF0000H JZ L4$ TEST EAX,0FF000000H JNZ L1$ ADD EBX,ECX ;LENGTH PLUS ONE ZERO... RET L2$: LEA EBX,[EBX+ECX-3] RET L3$: LEA EBX,[EBX+ECX-2] RET L4$: LEA EBX,[EBX+ECX-1] RET QAX_MOVE_ASCIZ ENDP if fg_segm PUBLIC TQUICK_ENTRYNAMES QAX_TO_DSSI_ENTRY PROC NEAR ; ; ; CONVERT ESI,ESI,ENTRYNAME_GARRAY ADD ESI,ENT_STRUCT._ENT_TEXT RET QAX_TO_DSSI_ENTRY ENDP QAX_TO_ESDI_ENTRY PROC NEAR ; ; ; CONVERT EDI,EDI,ENTRYNAME_GARRAY ADD EDI,ENT_STRUCT._ENT_TEXT RET QAX_TO_ESDI_ENTRY ENDP TQUICK_ENTRYNAMES PROC ; ; ; PUSHM EBP,EDI,ESI,EBX MOV EBP,ESP ; ; Adjust ESP in 4K increments ; SUB ESP,SIZEOF QUICK_VARS - SYMBOL_TEXT_SIZE - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP MOV QN_BUFFER_PTR,EAX CALL QUICK_ENTRY_INIT MOV QAX_TO_DSSI,OFF QAX_TO_DSSI_ENTRY MOV QAX_TO_ESDI,OFF QAX_TO_ESDI_ENTRY MOV QAX_COMPARE,OFF QAX_COMPARE_BYTE MOV QAX_MOVE_TEXT,OFF QAX_MOVE_ASCIZ JMP QAX_HELP_ENTRY TQUICK_ENTRYNAMES ENDP endif if fg_pe PUBLIC TQUICK_RESNAMES QAX_MOVE_UNICODE PROC NEAR ; ; ; LEA EBX,QN_SYMBOL_TEXT LEA ECX,QN_SYMBOL_TEXT+2 L1$: MOV EAX,[ESI] ADD ESI,4 MOV [EBX],EAX ADD EBX,4 TEST EAX,00000FFFFH JZ L2$ TEST EAX,0FFFF0000H JNZ L1$ ADD EBX,2 L2$: SUB EBX,ECX SHR EBX,1 RET QAX_MOVE_UNICODE ENDP QAX_TO_DSSI_RES PROC NEAR ; ; ; CONVERT ESI,ESI,RESNAME_GARRAY ADD ESI,RESNAME_STRUCT._RN_UNITEXT RET QAX_TO_DSSI_RES ENDP QAX_TO_ESDI_RES PROC NEAR ; ; ; CONVERT EDI,EDI,RESNAME_GARRAY ADD EDI,RESNAME_STRUCT._RN_UNITEXT RET QAX_TO_ESDI_RES ENDP TQUICK_RESNAMES PROC ; ; ; PUSHM EBP,EDI,ESI,EBX MOV EBP,ESP ; ; Adjust ESP in 4K increments ; SUB ESP,SIZEOF QUICK_VARS - SYMBOL_TEXT_SIZE - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP MOV QN_BUFFER_PTR,EAX CALL QUICK_RESNAMES_INIT MOV QAX_TO_DSSI,OFF QAX_TO_DSSI_RES MOV QAX_TO_ESDI,OFF QAX_TO_ESDI_RES MOV QAX_COMPARE,OFF QAX_COMPARE_WORD MOV QAX_MOVE_TEXT,OFF QAX_MOVE_UNICODE JMP QAX_HELP_RES TQUICK_RESNAMES ENDP endif TQUICK_ALPHA_XREF PROC ; ; PUSHM EBP,EDI,ESI,EBX MOV EBP,ESP ASSUME EBP:PTR QUICK_VARS ; ; Adjust ESP in 4K increments ; SUB ESP,SIZEOF QUICK_VARS - SYMBOL_TEXT_SIZE - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP MOV QN_BUFFER_PTR,EAX CALL QUICK_XREF_INIT JMP QAX_HELP TQUICK_ALPHA_XREF ENDP TQUICK_ALPHA PROC ; ; ; ;OK BOYS, HERE GOES A QUICK-SORT IMPLEMENTATION... ; ;SI IS LEFT SYMBOL #, DI IS RIGHT SYMBOL # ; PUSHM EBP,EDI,ESI,EBX ;SAVE THAT STACK FRAME MOV EBP,ESP ; ; Adjust ESP in 4K increments ; SUB ESP,SIZEOF QUICK_VARS - SYMBOL_TEXT_SIZE - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP SUB ESP,SYMBOL_TEXT_SIZE/2 - 4 PUSH EBP MOV QN_BUFFER_PTR,EAX CALL QUICK_INIT QAX_HELP:: MOV QAX_TO_DSSI,OFF QAX_TO_DSSI_SYMBOL MOV QAX_TO_ESDI,OFF QAX_TO_ESDI_SYMBOL MOV QAX_COMPARE,OFF QAX_COMPARE_BYTE MOV QAX_MOVE_TEXT,OFF QAX_MOVE_ASCIZ QAX_HELP_ENTRY:: QAX_HELP_RES:: CALL QUICK_ALPH MOV ESP,EBP POPM EBX,ESI,EDI,EBP RET TQUICK_ALPHA ENDP QUICK_ALPHA_1 PROC NEAR QA_2: ; ;JUST SORT THE TWO AND RETURN... ; CALL Q_SET_LEFT_BLOCK ;DS:SI CALL Q_SET_RIGHT_BLOCK ;ES:DI JMP QA_SORT2 QA_3: POP EAX QA_DONE: RET QUICK_ALPH:: MOV ECX,EDI QUICK_ALPH_1:: SUB ECX,ESI JNA QA_DONE ;RIGHT <= LEFT, QUIT ; ;WHAT ABOUT REAL SMALL CX ? ; INC ECX JZ QA_DONE CMP ECX,2 JZ QA_2 MOV QDELTA,ECX SHR ECX,1 PUSH ESI ADD ECX,ESI ;HALF WAY IN BETWEEN... MOV QRIGHT_NUMBER,EDI MOV QLEFT_NUMBER,ESI CALL Q_SET_LEFT_BLOCK ;DS:SI MOV QLEFT_PTR,ESI CALL Q_SET_RIGHT_BLOCK ;ES:DI MOV QRIGHT_PTR,EDI CALL Q_SET_MIDDLE_BLOCK MOV QMIDDLE_PTR,EDI ; ;DO THREE-SOME SORT ; ;IF LEFT>MIDDLE, XCHG LEFT&MIDDLE ; CALL QA_SORT2 ; ;IF LEFT > RIGHT, XCHG LEFT&RIGHT ; MOV EDI,QRIGHT_PTR CALL QA_SORT2 ; ;LASTLY, IF MIDDLE > RIGHT, XCHG MIDDLE&RIGHT ; MOV ESI,QMIDDLE_PTR CALL QA_SORT2 CMP QDELTA,3 JZ QA_3 ;NOW XCHG MIDDLE WITH RIGHT-1 ; CALL DEC_RIGHT_ESDI QEXCHANGE ; ;DEFINE TEST SYMBOL BY MOVING TEXT TO DGROUP ; MOV EAX,QRIGHT_NUMBER ;SAVE RIGHTY MOV ESI,[EDI] ;MOVE SYMBOL TEXT TO PUSH EAX CALL QAX_TO_DSSI CALL QAX_MOVE_TEXT CALL DEC_RIGHT_ESDI MOV ESI,QLEFT_PTR CALL INC_LEFT_DSSI MOV EAX,ESI MOV QRIGHT_PTR,EDI ; ;SCAN FROM LEFT UNTIL SOMETHING FOUND >= DX:BX ; MOV EDX,QLEFT_NUMBER QAL_AGAIN: QAL_LOOP: MOV EDI,[EAX] ;PT TO SYMBOL LEA ESI,QN_SYMBOL_TEXT ADD EAX,4 MOV ECX,EBX CALL QAX_TO_ESDI CALL QAX_COMPARE LEA ECX,[EDX+1] JBE QAL_TRY_RIGHT INC EDX AND ECX,PAGE_SIZE/4 - 1 JNZ QAL_LOOP MOV ESI,EDX CALL Q_SET_LEFT_BLOCK MOV EAX,ESI JMP QAL_LOOP QAL_TRY_RIGHT: LEA ECX,[EAX-4] MOV EAX,QRIGHT_PTR MOV QLEFT_PTR,ECX MOV QLEFT_NUMBER,EDX MOV EDX,QRIGHT_NUMBER ; ;SCAN FROM RIGHT UNTIL SOMETHING FOUND <= SYMBOL_TEXT ; QAR_LOOP: MOV EDI,[EAX] ;PT TO SYMBOL LEA ESI,QN_SYMBOL_TEXT SUB EAX,4 MOV ECX,EBX CALL QAX_TO_ESDI CALL QAX_COMPARE MOV ECX,EDX JAE QAR_SWAP DEC EDX AND ECX,PAGE_SIZE/4-1 JNZ QAR_LOOP MOV EDI,EDX CALL Q_SET_RIGHT_BLOCK MOV EAX,EDI JMP QAR_LOOP QAR_SWAP: LEA EDI,[EAX+4] MOV ESI,QLEFT_PTR MOV QRIGHT_PTR,EDI MOV ECX,QLEFT_NUMBER MOV QRIGHT_NUMBER,EDX MOV EAX,[ESI] CMP ECX,EDX JNC QA_DONE1 MOV ECX,[EDI] MOV [EDI],EAX MOV [ESI],ECX CALL DEC_RIGHT_ESDI MOV QRIGHT_PTR,EDI CALL INC_LEFT_DSSI MOV EDX,QLEFT_NUMBER MOV ECX,QRIGHT_NUMBER MOV EAX,ESI CMP ECX,EDX JAE QAL_AGAIN QA_DONE1: ; ;SWAP R+1 WITH ORIGINAL PTR... ; POP EDI ; THIS BECOMES i PUSH EDI CALL Q_SET_RIGHT_BLOCK QEXCHANGE ;SWAP THEM... ;DETERMINE WHICH HALF WILL BE PROCESSED... ; POP ECX ;ORIGINAL RIGHTY - WHERE MIDDLE WAS STORED POP EDX ;ORIGINAL LEFT INC ECX MOV EAX,QRIGHT_NUMBER MOV EBX,ECX MOV EDI,QLEFT_NUMBER SUB EAX,EDX SUB EBX,EDI CMP EAX,EBX JC QA_DONE2 ; ;LET SAY DO SECOND HALF FIRST ; MOV EAX,QRIGHT_NUMBER ;RIGHT TO USE THERE PUSH EDX ;SAVE ORIGINAL LEFT NUMBER PUSH EAX LEA ESI,[EDI+1] MOV EDI,ECX CALL QUICK_ALPH POPM EDI,ESI MOV ECX,EDI JMP QUICK_ALPH_1 QA_DONE2: ; ;LETS SAY DO FIRST HALF FIRST ; INC EDI MOV ESI,EDX PUSH EDI PUSH ECX MOV EDI,QRIGHT_NUMBER CALL QUICK_ALPH POPM EDI,ESI MOV ECX,EDI JMP QUICK_ALPH_1 QUICK_ALPHA_1 ENDP END
/* * Copyright 2020 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/effects/SkImageFilters.h" #include "modules/svg/include/SkSVGFe.h" #include "modules/svg/include/SkSVGFilter.h" #include "modules/svg/include/SkSVGFilterContext.h" #include "modules/svg/include/SkSVGRenderContext.h" #include "modules/svg/include/SkSVGValue.h" void SkSVGFilter::onSetAttribute(SkSVGAttribute attr, const SkSVGValue& v) { switch (attr) { case SkSVGAttribute::kX: if (const auto* x = v.as<SkSVGLengthValue>()) { this->setX(*x); } break; case SkSVGAttribute::kY: if (const auto* y = v.as<SkSVGLengthValue>()) { this->setY(*y); } break; case SkSVGAttribute::kWidth: if (const auto* w = v.as<SkSVGLengthValue>()) { this->setWidth(*w); } break; case SkSVGAttribute::kHeight: if (const auto* h = v.as<SkSVGLengthValue>()) { this->setHeight(*h); } break; case SkSVGAttribute::kFilterUnits: if (const auto* filterUnits = v.as<SkSVGObjectBoundingBoxUnitsValue>()) { this->setFilterUnits(*filterUnits); } break; default: this->INHERITED::onSetAttribute(attr, v); } } SkRect SkSVGFilter::resolveFilterRegion(const SkSVGRenderContext& ctx) const { const SkSVGLengthContext lctx = fFilterUnits.type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox ? SkSVGLengthContext({1, 1}) : ctx.lengthContext(); SkRect filterRegion = lctx.resolveRect(fX, fY, fWidth, fHeight); if (fFilterUnits.type() == SkSVGObjectBoundingBoxUnits::Type::kObjectBoundingBox) { SkASSERT(ctx.node()); const SkRect objBounds = ctx.node()->objectBoundingBox(ctx); filterRegion = SkRect::MakeXYWH( objBounds.fLeft + filterRegion.fLeft * objBounds.fLeft, objBounds.fTop + filterRegion.fTop * objBounds.fTop, filterRegion.width() * objBounds.width(), filterRegion.height() * objBounds.height()); } return filterRegion; } sk_sp<SkImageFilter> SkSVGFilter::buildFilterDAG(const SkSVGRenderContext& ctx) const { sk_sp<SkImageFilter> filter; SkSVGFilterContext fctx(resolveFilterRegion(ctx)); for (const auto& child : fChildren) { if (!SkSVGFe::IsFilterEffect(child)) { continue; } const auto& feNode = static_cast<const SkSVGFe&>(*child); const auto& feResultType = feNode.getResult(); // TODO: there are specific composition rules that need to be followed filter = feNode.makeImageFilter(ctx, fctx); if (!feResultType.isEmpty()) { fctx.registerResult(feResultType, filter); } } return filter; }
stage_pit_palette_data: ; Background .byt $09,$08,$18,$28, $09,$0d,$1a,$28, $09,$0d,$16,$25, $09,$01,$11,$21 ; Sprites .byt $09,$08,$1a,$20, $09,$08,$10,$37, $09,$08,$16,$10, $09,$08,$28,$37 nametable_stage_pit: .byt $00,$26 .byt $01, $00,$14, $01, $00,$07 .byt $01, $02, $03, $04, $05, $00,$1c .byt $06, $07, $08, $09, $00,$04, $1c, $1d, $01, $00,$04, $0e, $00,$03, $01, $00,$10 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $01, $00,$03, $20, $21, $00,$06, $02, $03, $04, $05, $00,$02, $0a, $0b, $00,$07 .byt $01, $00,$10, $06, $07, $08, $09, $00,$02, $0c, $0d, $00,$0e .byt $0a, $0b, $00,$04, $19, $1a, $00,$06, $01, $00,$03, $1c, $1d, $00,$0b .byt $01, $0c, $0d, $00,$04, $1e, $1f, $00,$02, $01, $00,$07, $20, $21, $00,$07 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $0e, $00,$04, $02, $03, $04, $05, $00,$15 .byt $1c, $1d, $00,$05, $06, $07, $08, $09, $00,$13 .byt $01, ZIPZ,$20, $21, $00,$0f, $0a, $0b, $00,$1e .byt $0c, $0d, $00,$04, $0e, $00,$0c ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $01, $00,$06, $1c, $1d, $00,$04, $01, ZIPZ,$02, $03, $04, $05, $00,$14 .byt $20, $21, $00,$06, $06, $07, $08, $09, $00,$08 .byt $02, $03, $04, $05, $00,$14, $0a, $0b, $00,$02, $01, ZIPZ .byt $0a, $0b, $06, $07, $08, $09, $00,$0a, $01, $00,$03, $1c, $1d, $00,$02, $01, ZIPZ,$0c, $0d, $00,$04 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $0c, $0d, $00,$12, $20, $21, $00,$05, $0e, $00,$04 .byt $23, ZIPZ,$24, $0e, $24, $23, $24, $00,$12, $23, $24, $11, $23, $24, ZIPZ,$23 .byt $27, $26, $27, $26, $27, $26, $27, $28, $00,$02, $01, $00,$0d, $25, $26, $27, $26, $27, $26, $27, $26 .byt $2b, $29, $2a, $2c, $2b, $2c, $2a, $2d, $00,$07, $02, $03, $04, $05, $00,$05, $29, $2a, $2b, $29, $2a, $2c, $2b, $29 ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $2f, $34, $35, $2f, $2f, $2f, $2f, $41, $00,$07, $06, $07, $08, $09, $00,$05, $38, $2a, $2f, $2f, $2f, $2f, $30, $31 .byt $2f, $3f, $40, $2f, $2f, $2f, $2f, $2d, $00,$04, $01, $00,$0b, $29, $2f, $32, $33, $2f, $2f, $43, $44 .byt $2f, $2f, $34, $35, $30, $31, $2f, $41, $00,$10, $38, $2f, $3b, $3c, $2f, $2f, $2f, $2f .byt $2f, $2f, $3f, $40, $43, $44, $2f, $2d, $00,$10, $29, $2f, $2f, $2f, $2f, $34, $35, $2f ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $32, $33, $2f, $2f, $2f, $2f, $2f, $41, ZIPZ,$d1, $d2, $00,$0a, $d6, $d7, ZIPZ, $38, $2f, $30, $31, $2f, $3f, $40, $2f .byt $3b, $3c, $2f, $2f, $2f, $30, $31, $2d, ZIPZ,$d3, $d4, $00,$0a, $d8, $d9, ZIPZ, $29, $2f, $43, $44, $2f, $2f, $2f, $2f .byt $2a, $2f, $2f, $2a, $2f, $43, $44, $41, $00,$03, $e5, $00,$02, $1c, $1d, $00,$07, $e5, $38, $2a, $2f, $2f, $32, $33, $2f, $2f .byt $2f, $30, $31, $2f, $2f, $2f, $2f, $2d, $00,$06, $20, $21, $00,$08, $29, $34, $35, $2f, $3b, $3c, $2f, $2f ; ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- ------------------- .byt $2f, $43, $44, $32, $33, $2a, $2f, $41, $36, $37, $36, $37, $36, $37, $36, $37, $36, $37, $36, $37, $36, $37, $36, $37, $38, $3f, $40, $2f, $2f, $2f, $2a, $2f .byt $2f, $2f, $2f, $3b, $3c, $2f, $2f, $2d, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $42, $29, $2f, $2f, $2f, $2f, $2f, $2f, $2f nametable_stage_pit_attributes: .byt %01010101, %01010101, %01010101, %01010101, %01010101, %01010101, %01010101, %01010101 .byt %01010101, %01010101, %10010101, %01010101, %01010101, %01010101, %01011001, %01010101 .byt %01010101, %01010101, %01010101, %01010101, %01010101, %01100101, %01010101, %01010101 .byt %01100101, %01010101, %01010101, %01010101, %01010101, %01010101, %10010101, %01010101 .byt %00000110, ZIPZ, %01000000, %01000000, %01010000, %00000001, %00000100 .byt ZIPNT_ZEROS(1+3) .byt %00000101, %00000101 .byt ZIPNT_ZEROS(3+3) .byt %01000000 .byt ZIPNT_ZEROS(4+8) nametable_stage_pit_end: .byt ZIPNT_END
%macro read 2 mov rax,0 mov rdi,0 mov rsi,%1 mov rdx,%2 syscall %endmacro %macro display 2 mov rax,1 mov rdi,1 mov rsi,%1 mov rdx,%2 syscall %endmacro %macro fopen 1 mov rax,2 mov rdi,%1 mov rsi,2 mov rdx,0777o syscall %endmacro %macro fread 3 mov rax,0 mov rdi,%1 mov rsi,%2 mov rdx,%3 syscall %endmacro %macro fwrite 3 mov rax,1 mov rdi,%1 mov rsi,%2 mov rdx,%3 syscall %endmacro %macro fclose 1 mov rax,3 mov rdi,%1 syscall %endmacro %macro fdelete 1 mov rax, 87 mov rdi, %1 syscall %endmacro
;@DOES HL+=A ;@INPUT HL number ;@INPUT A increment ;@OUTPUT HL number+increment ;@DESTROYS AF sys_AddHLAndA: push bc ld bc,0 ld c,a add hl,bc pop bc ret
// Copyright 2020 Emelkhovsky Ekaterina #include <gtest-mpi-listener.hpp> #include <gtest/gtest.h> #include <algorithm> #include <vector> #include "./shell_sort.h" TEST(shell_sort, Test_1) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<int> result_list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<int> sortArray = shell_sort(list); if (rank == 0) { ASSERT_EQ(sortArray, result_list); } } TEST(shell_sort, Test_2) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> list = {5, 6, 4, 3, 8, 2, 1, 10, 7, 9}; std::vector<int> result_list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; std::vector<int> sortArray = shell_sort(list); if (rank == 0) { ASSERT_EQ(sortArray, result_list); } } TEST(shell_sort, Test_3) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> list = {-1, -2, -3, -4, -5}; std::vector<int> result_list = {-5, -4, -3, -2, -1}; std::vector<int> sortArray = shell_sort(list); if (rank == 0) { ASSERT_EQ(sortArray, result_list); } } TEST(shell_sort, Test_4) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> list = {1, -10, 0, 123}; std::vector<int> result_list = {-10, 0, 1, 123}; std::vector<int> sortArray = shell_sort(list); if (rank == 0) { ASSERT_EQ(sortArray, result_list); } } TEST(shell_sort, Test_5) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::vector<int> list = {831}; std::vector<int> result_list = {831}; std::vector<int> sortArray = shell_sort(list); if (rank == 0) { ASSERT_EQ(sortArray, result_list); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
; ; STNP lib ; STNP_CLI_MSG_TYPE_CONNECTION = 0 STNP_CLI_MSG_TYPE_CONTROLLER_STATE = 1 STNP_SRV_MSG_TYPE_CONNECTED = 0 STNP_SRV_MSG_TYPE_START_GAME = 1 STNP_SRV_MSG_TYPE_NEWSTATE = 2 STNP_SRV_MSG_TYPE_GAMEOVER = 3 STNP_SRV_MSG_TYPE_DISCONNECTED = 4 STNP_START_GAME_FIELD_STAGE = 1 STNP_START_GAME_FIELD_STOCK = 2 STNP_START_GAME_FIELD_PLAYER_NUMBER = 3 STNP_START_GAME_FIELD_PLAYER_CONNECTIONS = 4 STNP_START_GAME_FIELD_PA_CHARACTER = 5 STNP_START_GAME_FIELD_PB_CHARACTER = 6 STNP_START_GAME_FIELD_PA_PALETTE = 7 STNP_START_GAME_FIELD_PB_PALETTE = 8 STNP_DISCONNECTED_FIELD_REASON = 1 ; ; Netcode ; network_init_stage: .( ; Enable ESP lda #1 sta RAINBOW_FLAGS ; Clear rolling mode lda #0 sta network_rollback_mode ; Clear input history ; lda #0 ; ensured by above code ldx #0 clear_one_input: sta network_player_local_btns_history, x sta network_player_remote_btns_history, x inx cpx #32 bne clear_one_input sta network_last_known_remote_input ; Reinit frame counter lda #$00 sta network_current_frame_byte0 sta network_current_frame_byte1 sta network_current_frame_byte2 sta network_current_frame_byte3 ; Initialize controllers state sta network_last_sent_btns rts .) network_tick_ingame: .( .( ; Do nothing in rollback mode, it would be recursive lda network_rollback_mode beq do_tick jmp end do_tick: ; Update local controller's history lda network_current_frame_byte0 clc adc #NETWORK_INPUT_LAG and #%00011111 tay lda controller_a_btns sta network_player_local_btns_history, y ; Send controller's state lda network_last_sent_btns ; NOTE - optimizable as "controller_a_btns" is already in register A cmp controller_a_btns beq controller_sent ; ESP header lda #11 ; Message length (10 bytes of payload + 1 byte for ESP message type) sta RAINBOW_DATA lda #TOESP_MSG_SEND_MESSAGE_TO_SERVER ; ESP message type sta RAINBOW_DATA ; Payload lda #STNP_CLI_MSG_TYPE_CONTROLLER_STATE ; message_type sta RAINBOW_DATA lda network_client_id_byte0 ; client_id sta RAINBOW_DATA lda network_client_id_byte1 sta RAINBOW_DATA lda network_client_id_byte2 sta RAINBOW_DATA lda network_client_id_byte3 sta RAINBOW_DATA lda network_current_frame_byte0 ; timestamp sta RAINBOW_DATA lda network_current_frame_byte1 sta RAINBOW_DATA lda network_current_frame_byte2 sta RAINBOW_DATA lda network_current_frame_byte3 sta RAINBOW_DATA lda controller_a_btns ; controller state sta RAINBOW_DATA sta network_last_sent_btns controller_sent: ; Receive new state bit RAINBOW_FLAGS bpl state_updated ; Burn garbage byte lda RAINBOW_DATA nop ; Trash length byte (consistency check is not trivial as message has variable length) lda RAINBOW_DATA nop ; Check message type lda RAINBOW_DATA cmp #FROMESP_MSG_MESSAGE_FROM_SERVER bne skip_message lda RAINBOW_DATA ; Message type from payload cmp #STNP_SRV_MSG_TYPE_NEWSTATE bne skip_message ; Burn prediction ID ; TODO use it to avoid useless state reset lda RAINBOW_DATA ; Override gamestate with the one in message's payload jsr update_state jmp state_updated skip_message: ; Clear buffered message lda #1 sta RAINBOW_DATA lda #TOESP_MSG_CLEAR_BUFFERS sta RAINBOW_DATA state_updated: ; Overwrite players input with delayed input ldx network_local_player_number ; X = local player number lda network_current_frame_byte0 ; Y = input offset in history ;FIXME if just got a message in the futur, it may be in garbage part of the input history (should rewrite next four inputs when receiving a message in the futur) and #%00011111 tay lda network_player_local_btns_history, y ; write current input sta controller_a_btns, x jsr switch_selected_player jsr set_opponent_buttons_from_history ; Increment frame counter inc network_current_frame_byte0 bne inc_ok inc network_current_frame_byte1 bne inc_ok inc network_current_frame_byte2 bne inc_ok inc network_current_frame_byte3 inc_ok: end: rts .) update_state: .( ; Extract frame counter lda RAINBOW_DATA sta server_current_frame_byte0 lda RAINBOW_DATA sta server_current_frame_byte1 lda RAINBOW_DATA sta server_current_frame_byte2 lda RAINBOW_DATA sta server_current_frame_byte3 ;TODO select action from message type - ancient, past or futur ;NOTE in a first draft the current rollback implementation should handle all cases ; correctly, even if sub-optimal (notably doing unecessary rollbacks for "past" ; messages. ; one advantage of this solution is to resync with server on any occasion ancient: jsr rollback_state jmp end past: ;TODO future: ;TODO end: rts .) rollback_state: .( ; Copy delayed inputs from message in opponent's input history .( ; Get first delayed input index in history lda server_current_frame_byte0 clc adc #1 and #%00011111 tay ; Copy delayed inputs ldx #NETWORK_INPUT_LAG copy_one_byte: lda RAINBOW_DATA sta network_player_remote_btns_history, y sty network_last_known_remote_input iny tya and #%00011111 tay dex bne copy_one_byte .) ; Copy gamestate .( ldx #0 copy_one_byte: lda RAINBOW_DATA ; 4 cycles sta $00, x ; 4 cycles inx ; 2 cycles cpx #$4f ; 3 cycles bne copy_one_byte ; 3 cycles .) ; Note ; Total - (4+4+2+3+3) * 79 = 16 * 79 = 1264 ; Unroll - (4+3) * 79 = 7 * 79 = 553 ; Copy hitboxes MSB .( ldx #0 copy_one_byte: lda RAINBOW_DATA ; 4 cycles sta player_a_hurtbox_left_msb, x ; 4 cycles inx ; 2 cycles cpx #$10 ; 3 cycles bne copy_one_byte ; 3 cycles .) ; Note ; Total - (4+4+2+3+3) * 16 = 16 * 16 = 256 ; Unroll - (4+3) * 16 = 7 * 16 = 112 ; Copy special state lda RAINBOW_DATA sta screen_shake_counter bne screen_shake_updated ; Received a "no screen shake", ensure that scrolling is reset ;lda #$00 ; useless - ensured by bne sta scroll_y sta scroll_x lda #%10010000 sta ppuctrl_val screen_shake_updated: ; Copy controllers state lda RAINBOW_DATA sta controller_a_btns lda RAINBOW_DATA sta controller_b_btns lda RAINBOW_DATA sta controller_a_last_frame_btns lda RAINBOW_DATA sta controller_b_last_frame_btns ; Copy actually pressed opponent btns (keep_input_dirty may mess with normal values, but not this one) .( ;TODO Investigate ; We may want to write received buttons in local player history instead of burning it ; That would avoid desynchronizing if a ControllerState packet is lost (= not seen by server) ; Beware of race conditions, if the server receives the ControllerState packet after sending the NewState ; That would cause desychronization (until next NewGameState received), because we updated history with predicted info from server lda network_local_player_number bne player_b player_a: ; Local player is player A, burn its buttons (already in our history) lda RAINBOW_DATA nop lda RAINBOW_DATA pha jmp ok player_b: ; Local player is player B, burn its buttons (already in our history) lda RAINBOW_DATA pha lda RAINBOW_DATA ok: ; Register it in opponent's input history lda server_current_frame_byte0 and #%00011111 tay pla sta network_player_remote_btns_history, y .) ; Copy animation states .( lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_DATA_VECTOR_LSB lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_DATA_VECTOR_MSB lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_DIRECTION lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_CLOCK lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_FRAME_VECTOR_LSB lda RAINBOW_DATA sta player_a_animation+ANIMATION_STATE_OFFSET_FRAME_VECTOR_MSB lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_DATA_VECTOR_LSB lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_DATA_VECTOR_MSB lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_DIRECTION lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_CLOCK lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_FRAME_VECTOR_LSB lda RAINBOW_DATA sta player_b_animation+ANIMATION_STATE_OFFSET_FRAME_VECTOR_MSB .) ; Copy character specific data .( ldx #0 copy_one_char: ldy config_player_a_character, x lda characters_netload_routine_lsb, y sta tmpfield1 lda characters_netload_routine_msb, y sta tmpfield2 SWITCH_BANK(characters_bank_number COMMA y) stx player_number jsr call_pointed_subroutine ldx player_number inx cpx #2 bne copy_one_char .) ; Copy stage specific data .( ldy config_selected_stage lda stages_netload_routine_lsb, y sta tmpfield1 lda stages_netload_routine_msb, y sta tmpfield2 SWITCH_BANK(stages_bank COMMA y) jsr call_pointed_subroutine .) ; Update game state until the current frame is at least equal to the one we where before reading the message lda #1 sta network_rollback_mode roll_forward_one_step: .( ; If sever's frame is inferior to local frame ; TODO optimization - could be implemented like in signed_cmp ; one CMP, followed by SBCs, branching at the end on carry flag ; to be determined, but considering 255 out of 256 times only the LSB is changing, it should be speeder lda server_current_frame_byte3 cmp network_current_frame_byte3 bcc do_it bne dont_do_it lda server_current_frame_byte2 cmp network_current_frame_byte2 bcc do_it bne dont_do_it lda server_current_frame_byte1 cmp network_current_frame_byte1 bcc do_it bne dont_do_it lda server_current_frame_byte0 cmp network_current_frame_byte0 bcc do_it jmp dont_do_it do_it: ; Update last_frame_btns ; it is not done by fetch_controller because we don't use the main loop lda controller_a_btns sta controller_a_last_frame_btns lda controller_b_btns sta controller_b_last_frame_btns ; Set local player input according to history ldx network_local_player_number ; X = local player number lda server_current_frame_byte0 ; Y = input offset in history and #%00011111 tay lda network_player_local_btns_history, y ; write current input sta controller_a_btns, x ; Set remote player input according to history jsr switch_selected_player jsr set_opponent_buttons_from_history ; Update game state jsr game_tick ; Inc server_current_frame_byte inc server_current_frame_byte0 bne end_inc inc server_current_frame_byte1 bne end_inc inc server_current_frame_byte2 bne end_inc inc server_current_frame_byte3 end_inc: ; Loop jmp roll_forward_one_step end_loop: dont_do_it: .) lda #0 sta network_rollback_mode ; Copy (updated) server frame number to the local one lda server_current_frame_byte0 sta network_current_frame_byte0 lda server_current_frame_byte1 sta network_current_frame_byte1 lda server_current_frame_byte2 sta network_current_frame_byte2 lda server_current_frame_byte3 sta network_current_frame_byte3 rts .) ; Get opponent'input if known, else predict it set_opponent_buttons_from_history: .( ; Determine if we know the next input or have to predict it cpy network_last_known_remote_input beq mark_nexts_unknown lda network_last_known_remote_input cmp #$80 bcc known unknown: and #%00011111 tay jmp known ; not known per see, but we predict it being the same as last known mark_nexts_unknown: lda #$80 ora network_last_known_remote_input sta network_last_known_remote_input known: lda network_player_remote_btns_history, y sta controller_a_btns, x rts .) .)
SafariZoneEastRestHouse_Object: db $a ; border block db 2 ; warps warp 2, 7, 4, SAFARI_ZONE_EAST warp 3, 7, 4, SAFARI_ZONE_EAST db 0 ; signs db 3 ; objects object SPRITE_OAK_AIDE, 1, 3, WALK, 1, 1 ; person object SPRITE_ROCKER, 4, 2, STAY, NONE, 2 ; person object SPRITE_LAPRAS_GIVER, 5, 2, STAY, NONE, 3 ; person ; warp-to warp_to 2, 7, SAFARI_ZONE_EAST_REST_HOUSE_WIDTH ; SAFARI_ZONE_EAST warp_to 3, 7, SAFARI_ZONE_EAST_REST_HOUSE_WIDTH ; SAFARI_ZONE_EAST
; size_t b_vector_push_back(b_vector_t *v, int c) SECTION code_adt_b_vector PUBLIC b_vector_push_back EXTERN b_vector_append defc b_vector_push_back = b_vector_append
; A334085: GCD of n and the product of all primes < n. ; 1,1,1,2,1,6,1,2,3,10,1,6,1,14,15,2,1,6,1,10,21,22,1,6,5,26,3,14,1,30,1,2,33,34,35,6,1,38,39,10,1,42,1,22,15,46,1,6,7,10,51,26,1,6,55,14,57,58,1,30,1,62,21,2,65,66,1,34,69,70,1,6,1,74,15,38,77,78,1,10,3,82,1,42,85,86,87,22,1,30,91,46,93,94,95,6,1,14,33,10 add $0,1 mov $1,1 mov $2,2 mov $3,$0 sub $3,2 mov $4,$0 lpb $3 mov $5,$4 mov $6,0 lpb $5 add $6,1 mov $7,$0 div $0,$2 mod $7,$2 cmp $7,0 sub $5,$7 lpe cmp $6,0 cmp $6,0 mov $7,$2 pow $7,$6 mul $1,$7 add $2,1 sub $3,2 lpe mov $0,$1
; A063886: Number of n-step walks on a line starting from the origin but not returning to it. ; 1,2,2,4,6,12,20,40,70,140,252,504,924,1848,3432,6864,12870,25740,48620,97240,184756,369512,705432,1410864,2704156,5408312,10400600,20801200,40116600,80233200,155117520,310235040,601080390,1202160780,2333606220,4667212440,9075135300,18150270600,35345263800,70690527600,137846528820,275693057640,538257874440,1076515748880,2104098963720,4208197927440,8233430727600,16466861455200,32247603683100,64495207366200,126410606437752,252821212875504,495918532948104,991837065896208,1946939425648112,3893878851296224,7648690600760440 lpb $0 sub $0,1 mov $1,$0 mov $2,$0 sub $0,$0 div $2,2 bin $1,$2 mul $1,2 sub $1,1 lpe add $1,1
; A319658: a(n) is the minimal number of successive ON cells that appears in n-th generation of rule-30 1D cellular automaton started from a single ON cell. ; 1,3,1,2,1,2,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 mov $11,$0 mov $13,2 lpb $13 clr $0,11 mov $0,$11 sub $13,1 add $0,$13 sub $0,1 mov $3,8 mov $6,$0 lpb $0 mul $3,2 mov $9,$6 add $9,3 mov $7,$9 add $7,1 div $3,$7 mov $7,1 trn $7,$3 mov $0,$7 mov $10,11 trn $10,$9 mov $9,5 div $10,2 sub $9,$10 add $9,$7 lpe mov $1,$9 mov $14,$13 lpb $14 mov $12,$1 sub $14,1 lpe lpe lpb $11 mov $11,0 sub $12,$1 lpe mov $1,$12 add $1,1
; A121470: Expansion of x*(1+5*x+2*x^2+x^3)/((1+x)*(1-x)^3). ; 1,7,16,31,49,73,100,133,169,211,256,307,361,421,484,553,625,703,784,871,961,1057,1156,1261,1369,1483,1600,1723,1849,1981,2116,2257,2401,2551,2704,2863,3025,3193,3364,3541,3721,3907,4096,4291,4489,4693,4900 mul $0,6 add $0,4 pow $0,2 mov $1,$0 div $1,48 mul $1,3 add $1,1
; A091957: a(1)=0, a(2)=1, a(n)=A000217(a(n-1)) + A000217(a(n-2)). ; Submitted by Christian Krause ; 0,1,1,2,4,13,101,5242,13747054,94490767454888,4464252567107002358694986701,9964775491460730298984873909049635615687553262572198767 lpb $0 sub $0,1 mov $2,$3 mul $2,$3 bin $3,2 add $3,$1 add $1,$2 add $3,1 lpe mov $0,$3
; A176393: a(n) = A176100(n) + 1 = 2*A141468(n) + 1. ; 1,3,9,13,17,19,21,25,29,31,33,37,41,43,45,49,51,53,55,57,61,65,67,69,71,73,77,79,81,85,89,91,93,97,99,101,103,105,109,111,113,115,117,121,125,127,129,131,133,137,139,141,145,149,151,153,155,157,161,163,165 add $0,1 mov $1,100 lpb $1,36 mov $2,$0 mov $3,130665 lpb $3,1 cal $0,230980 ; Number of primes <= n, starting at n=0. sub $0,$2 mov $1,6 div $3,5 mov $5,1 lpe lpb $5,1 add $0,1 div $5,3 lpe lpe mov $1,$0 sub $1,1 mul $1,2 add $1,1
/*! * Copyright 2014-2019 by Contributors * \file updater_histmaker.cc * \brief use histogram counting to construct a tree * \author Tianqi Chen */ #include <rabit/rabit.h> #include <vector> #include <algorithm> #include "xgboost/tree_updater.h" #include "xgboost/base.h" #include "xgboost/logging.h" #include "../common/quantile.h" #include "../common/group_data.h" #include "./updater_basemaker-inl.h" #include "constraints.h" namespace xgboost { namespace tree { DMLC_REGISTRY_FILE_TAG(updater_histmaker); class HistMaker: public BaseMaker { public: void Update(HostDeviceVector<GradientPair> *gpair, DMatrix *p_fmat, const std::vector<RegTree*> &trees) override { interaction_constraints_.Configure(param_, p_fmat->Info().num_col_); // rescale learning rate according to size of trees float lr = param_.learning_rate; param_.learning_rate = lr / trees.size(); // build tree for (auto tree : trees) { this->UpdateTree(gpair->ConstHostVector(), p_fmat, tree); } param_.learning_rate = lr; } char const* Name() const override { return "grow_histmaker"; } protected: /*! \brief a single column of histogram cuts */ struct HistUnit { /*! \brief cutting point of histogram, contains maximum point */ const float *cut; /*! \brief content of statistics data */ GradStats *data; /*! \brief size of histogram */ uint32_t size; // default constructor HistUnit() = default; // constructor HistUnit(const float *cut, GradStats *data, uint32_t size) : cut{cut}, data{data}, size{size} {} /*! \brief add a histogram to data */ }; /*! \brief a set of histograms from different index */ struct HistSet { /*! \brief the index pointer of each histunit */ const uint32_t *rptr; /*! \brief cutting points in each histunit */ const bst_float *cut; /*! \brief data in different hist unit */ std::vector<GradStats> data; /*! \brief return a column of histogram cuts */ inline HistUnit operator[](size_t fid) { return {cut + rptr[fid], &data[0] + rptr[fid], rptr[fid+1] - rptr[fid]}; } }; // thread workspace struct ThreadWSpace { /*! \brief actual unit pointer */ std::vector<unsigned> rptr; /*! \brief cut field */ std::vector<bst_float> cut; // per thread histset std::vector<HistSet> hset; // initialize the hist set inline void Configure(int nthread) { hset.resize(nthread); // cleanup statistics for (int tid = 0; tid < nthread; ++tid) { for (auto& d : hset[tid].data) { d = GradStats(); } hset[tid].rptr = dmlc::BeginPtr(rptr); hset[tid].cut = dmlc::BeginPtr(cut); hset[tid].data.resize(cut.size(), GradStats()); } } /*! \brief clear the workspace */ inline void Clear() { cut.clear(); rptr.resize(1); rptr[0] = 0; } /*! \brief total size */ inline size_t Size() const { return rptr.size() - 1; } }; // workspace of thread ThreadWSpace wspace_; // reducer for histogram rabit::Reducer<GradStats, GradStats::Reduce> histred_; // set of working features std::vector<bst_feature_t> selected_features_; // update function implementation virtual void UpdateTree(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, RegTree *p_tree) { CHECK(param_.max_depth > 0) << "max_depth must be larger than 0"; this->InitData(gpair, *p_fmat, *p_tree); this->InitWorkSet(p_fmat, *p_tree, &selected_features_); // mark root node as fresh. (*p_tree)[0].SetLeaf(0.0f, 0); for (int depth = 0; depth < param_.max_depth; ++depth) { // reset and propose candidate split this->ResetPosAndPropose(gpair, p_fmat, selected_features_, *p_tree); // create histogram this->CreateHist(gpair, p_fmat, selected_features_, *p_tree); // find split based on histogram statistics this->FindSplit(selected_features_, p_tree); // reset position after split this->ResetPositionAfterSplit(p_fmat, *p_tree); this->UpdateQueueExpand(*p_tree); // if nothing left to be expand, break if (qexpand_.size() == 0) break; } for (int const nid : qexpand_) { (*p_tree)[nid].SetLeaf(p_tree->Stat(nid).base_weight * param_.learning_rate); } } // this function does two jobs // (1) reset the position in array position, to be the latest leaf id // (2) propose a set of candidate cuts and set wspace.rptr wspace.cut correctly virtual void ResetPosAndPropose(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, const std::vector <bst_feature_t> &fset, const RegTree &tree) = 0; // initialize the current working set of features in this round virtual void InitWorkSet(DMatrix *, const RegTree &tree, std::vector<bst_feature_t> *p_fset) { p_fset->resize(tree.param.num_feature); for (size_t i = 0; i < p_fset->size(); ++i) { (*p_fset)[i] = static_cast<unsigned>(i); } } // reset position after split, this is not a must, depending on implementation virtual void ResetPositionAfterSplit(DMatrix *p_fmat, const RegTree &tree) { } virtual void CreateHist(const std::vector<GradientPair> &gpair, DMatrix *, const std::vector <bst_feature_t> &fset, const RegTree &) = 0; private: void EnumerateSplit(const HistUnit &hist, const GradStats &node_sum, bst_uint fid, SplitEntry *best, GradStats *left_sum) const { if (hist.size == 0) return; double root_gain = CalcGain(param_, node_sum.GetGrad(), node_sum.GetHess()); GradStats s, c; for (bst_uint i = 0; i < hist.size; ++i) { s.Add(hist.data[i]); if (s.sum_hess >= param_.min_child_weight) { c.SetSubstract(node_sum, s); if (c.sum_hess >= param_.min_child_weight) { double loss_chg = CalcGain(param_, s.GetGrad(), s.GetHess()) + CalcGain(param_, c.GetGrad(), c.GetHess()) - root_gain; if (best->Update(static_cast<bst_float>(loss_chg), fid, hist.cut[i], false, s, c)) { *left_sum = s; } } } } s = GradStats(); for (bst_uint i = hist.size - 1; i != 0; --i) { s.Add(hist.data[i]); if (s.sum_hess >= param_.min_child_weight) { c.SetSubstract(node_sum, s); if (c.sum_hess >= param_.min_child_weight) { double loss_chg = CalcGain(param_, s.GetGrad(), s.GetHess()) + CalcGain(param_, c.GetGrad(), c.GetHess()) - root_gain; if (best->Update(static_cast<bst_float>(loss_chg), fid, hist.cut[i-1], true, c, s)) { *left_sum = c; } } } } } void FindSplit(const std::vector <bst_feature_t> &feature_set, RegTree *p_tree) { const size_t num_feature = feature_set.size(); // get the best split condition for each node std::vector<SplitEntry> sol(qexpand_.size()); std::vector<GradStats> left_sum(qexpand_.size()); auto nexpand = static_cast<bst_omp_uint>(qexpand_.size()); #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint wid = 0; wid < nexpand; ++wid) { const int nid = qexpand_[wid]; CHECK_EQ(node2workindex_[nid], static_cast<int>(wid)); SplitEntry &best = sol[wid]; GradStats &node_sum = wspace_.hset[0][num_feature + wid * (num_feature + 1)].data[0]; for (size_t i = 0; i < feature_set.size(); ++i) { // Query is thread safe as it's a const function. if (!this->interaction_constraints_.Query(nid, feature_set[i])) { continue; } EnumerateSplit(this->wspace_.hset[0][i + wid * (num_feature+1)], node_sum, feature_set[i], &best, &left_sum[wid]); } } // get the best result, we can synchronize the solution for (bst_omp_uint wid = 0; wid < nexpand; ++wid) { const bst_node_t nid = qexpand_[wid]; SplitEntry const& best = sol[wid]; const GradStats &node_sum = wspace_.hset[0][num_feature + wid * (num_feature + 1)].data[0]; this->SetStats(p_tree, nid, node_sum); // set up the values p_tree->Stat(nid).loss_chg = best.loss_chg; // now we know the solution in snode[nid], set split if (best.loss_chg > kRtEps) { bst_float base_weight = CalcWeight(param_, node_sum); bst_float left_leaf_weight = CalcWeight(param_, best.left_sum.sum_grad, best.left_sum.sum_hess) * param_.learning_rate; bst_float right_leaf_weight = CalcWeight(param_, best.right_sum.sum_grad, best.right_sum.sum_hess) * param_.learning_rate; p_tree->ExpandNode(nid, best.SplitIndex(), best.split_value, best.DefaultLeft(), base_weight, left_leaf_weight, right_leaf_weight, best.loss_chg, node_sum.sum_hess, best.left_sum.GetHess(), best.right_sum.GetHess()); GradStats right_sum; right_sum.SetSubstract(node_sum, left_sum[wid]); auto left_child = (*p_tree)[nid].LeftChild(); auto right_child = (*p_tree)[nid].RightChild(); this->SetStats(p_tree, left_child, left_sum[wid]); this->SetStats(p_tree, right_child, right_sum); this->interaction_constraints_.Split(nid, best.SplitIndex(), left_child, right_child); } else { (*p_tree)[nid].SetLeaf(p_tree->Stat(nid).base_weight * param_.learning_rate); } } } inline void SetStats(RegTree *p_tree, int nid, const GradStats &node_sum) { p_tree->Stat(nid).base_weight = static_cast<bst_float>(CalcWeight(param_, node_sum)); p_tree->Stat(nid).sum_hess = static_cast<bst_float>(node_sum.sum_hess); } }; class CQHistMaker: public HistMaker { public: CQHistMaker() = default; char const* Name() const override { return "grow_local_histmaker"; } protected: struct HistEntry { HistMaker::HistUnit hist; unsigned istart; /*! * \brief add a histogram to data, * do linear scan, start from istart */ inline void Add(bst_float fv, const std::vector<GradientPair> &gpair, const bst_uint ridx) { while (istart < hist.size && !(fv < hist.cut[istart])) ++istart; CHECK_NE(istart, hist.size); hist.data[istart].Add(gpair[ridx]); } /*! * \brief add a histogram to data, * do linear scan, start from istart */ inline void Add(bst_float fv, GradientPair gstats) { if (fv < hist.cut[istart]) { hist.data[istart].Add(gstats); } else { while (istart < hist.size && !(fv < hist.cut[istart])) ++istart; if (istart != hist.size) { hist.data[istart].Add(gstats); } else { LOG(INFO) << "fv=" << fv << ", hist.size=" << hist.size; for (size_t i = 0; i < hist.size; ++i) { LOG(INFO) << "hist[" << i << "]=" << hist.cut[i]; } LOG(FATAL) << "fv=" << fv << ", hist.last=" << hist.cut[hist.size - 1]; } } } }; // sketch type used for this using WXQSketch = common::WXQuantileSketch<bst_float, bst_float>; // initialize the work set of tree void InitWorkSet(DMatrix *p_fmat, const RegTree &tree, std::vector<bst_feature_t> *p_fset) override { if (p_fmat != cache_dmatrix_) { feat_helper_.InitByCol(p_fmat, tree); cache_dmatrix_ = p_fmat; } feat_helper_.SyncInfo(); feat_helper_.SampleCol(this->param_.colsample_bytree, p_fset); } // code to create histogram void CreateHist(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, const std::vector<bst_feature_t> &fset, const RegTree &tree) override { const MetaInfo &info = p_fmat->Info(); // fill in reverse map feat2workindex_.resize(tree.param.num_feature); std::fill(feat2workindex_.begin(), feat2workindex_.end(), -1); for (size_t i = 0; i < fset.size(); ++i) { feat2workindex_[fset[i]] = static_cast<int>(i); } // start to work this->wspace_.Configure(1); // if it is C++11, use lazy evaluation for Allreduce, // to gain speedup in recovery auto lazy_get_hist = [&]() { thread_hist_.resize(omp_get_max_threads()); // start accumulating statistics for (const auto &batch : p_fmat->GetBatches<SortedCSCPage>()) { auto page = batch.GetView(); // start enumeration const auto nsize = static_cast<bst_omp_uint>(fset.size()); #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint i = 0; i < nsize; ++i) { int fid = fset[i]; int offset = feat2workindex_[fid]; if (offset >= 0) { this->UpdateHistCol(gpair, page[fid], info, tree, fset, offset, &thread_hist_[omp_get_thread_num()]); } } } // update node statistics. this->GetNodeStats(gpair, *p_fmat, tree, &thread_stats_, &node_stats_); for (int const nid : this->qexpand_) { const int wid = this->node2workindex_[nid]; this->wspace_.hset[0][fset.size() + wid * (fset.size() + 1)] .data[0] = node_stats_[nid]; } }; // sync the histogram this->histred_.Allreduce(dmlc::BeginPtr(this->wspace_.hset[0].data), this->wspace_.hset[0].data.size(), lazy_get_hist); } void ResetPositionAfterSplit(DMatrix *, const RegTree &tree) override { this->GetSplitSet(this->qexpand_, tree, &fsplit_set_); } void ResetPosAndPropose(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, const std::vector<bst_feature_t> &fset, const RegTree &tree) override { const MetaInfo &info = p_fmat->Info(); // fill in reverse map feat2workindex_.resize(tree.param.num_feature); std::fill(feat2workindex_.begin(), feat2workindex_.end(), -1); work_set_.clear(); for (auto fidx : fset) { if (feat_helper_.Type(fidx) == 2) { feat2workindex_[fidx] = static_cast<int>(work_set_.size()); work_set_.push_back(fidx); } else { feat2workindex_[fidx] = -2; } } const size_t work_set_size = work_set_.size(); sketchs_.resize(this->qexpand_.size() * work_set_size); for (auto& sketch : sketchs_) { sketch.Init(info.num_row_, this->param_.sketch_eps); } // intitialize the summary array summary_array_.resize(sketchs_.size()); // setup maximum size unsigned max_size = this->param_.MaxSketchSize(); for (size_t i = 0; i < sketchs_.size(); ++i) { summary_array_[i].Reserve(max_size); } { // get smmary thread_sketch_.resize(omp_get_max_threads()); // TWOPASS: use the real set + split set in the column iteration. this->SetDefaultPostion(p_fmat, tree); work_set_.insert(work_set_.end(), fsplit_set_.begin(), fsplit_set_.end()); std::sort(work_set_.begin(), work_set_.end()); work_set_.resize(std::unique(work_set_.begin(), work_set_.end()) - work_set_.begin()); // start accumulating statistics for (const auto &batch : p_fmat->GetBatches<SortedCSCPage>()) { // TWOPASS: use the real set + split set in the column iteration. this->CorrectNonDefaultPositionByBatch(batch, fsplit_set_, tree); auto page = batch.GetView(); // start enumeration const auto nsize = static_cast<bst_omp_uint>(work_set_.size()); #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint i = 0; i < nsize; ++i) { int fid = work_set_[i]; int offset = feat2workindex_[fid]; if (offset >= 0) { this->UpdateSketchCol(gpair, page[fid], tree, work_set_size, offset, &thread_sketch_[omp_get_thread_num()]); } } } for (size_t i = 0; i < sketchs_.size(); ++i) { common::WXQuantileSketch<bst_float, bst_float>::SummaryContainer out; sketchs_[i].GetSummary(&out); summary_array_[i].SetPrune(out, max_size); } CHECK_EQ(summary_array_.size(), sketchs_.size()); } if (summary_array_.size() != 0) { size_t nbytes = WXQSketch::SummaryContainer::CalcMemCost(max_size); sreducer_.Allreduce(dmlc::BeginPtr(summary_array_), nbytes, summary_array_.size()); } // now we get the final result of sketch, setup the cut this->wspace_.cut.clear(); this->wspace_.rptr.clear(); this->wspace_.rptr.push_back(0); for (size_t wid = 0; wid < this->qexpand_.size(); ++wid) { for (unsigned int i : fset) { int offset = feat2workindex_[i]; if (offset >= 0) { const WXQSketch::Summary &a = summary_array_[wid * work_set_size + offset]; for (size_t i = 1; i < a.size; ++i) { bst_float cpt = a.data[i].value - kRtEps; if (i == 1 || cpt > this->wspace_.cut.back()) { this->wspace_.cut.push_back(cpt); } } // push a value that is greater than anything if (a.size != 0) { bst_float cpt = a.data[a.size - 1].value; // this must be bigger than last value in a scale bst_float last = cpt + fabs(cpt) + kRtEps; this->wspace_.cut.push_back(last); } this->wspace_.rptr.push_back(static_cast<unsigned>(this->wspace_.cut.size())); } else { CHECK_EQ(offset, -2); bst_float cpt = feat_helper_.MaxValue(i); this->wspace_.cut.push_back(cpt + fabs(cpt) + kRtEps); this->wspace_.rptr.push_back(static_cast<unsigned>(this->wspace_.cut.size())); } } // reserve last value for global statistics this->wspace_.cut.push_back(0.0f); this->wspace_.rptr.push_back(static_cast<unsigned>(this->wspace_.cut.size())); } CHECK_EQ(this->wspace_.rptr.size(), (fset.size() + 1) * this->qexpand_.size() + 1); } inline void UpdateHistCol(const std::vector<GradientPair> &gpair, const SparsePage::Inst &col, const MetaInfo &info, const RegTree &tree, const std::vector<bst_feature_t> &fset, bst_uint fid_offset, std::vector<HistEntry> *p_temp) { if (col.size() == 0) return; // initialize sbuilder for use std::vector<HistEntry> &hbuilder = *p_temp; hbuilder.resize(tree.param.num_nodes); for (int const nid : this->qexpand_) { const unsigned wid = this->node2workindex_[nid]; hbuilder[nid].istart = 0; hbuilder[nid].hist = this->wspace_.hset[0][fid_offset + wid * (fset.size()+1)]; } if (this->param_.cache_opt != 0) { constexpr bst_uint kBuffer = 32; bst_uint align_length = col.size() / kBuffer * kBuffer; int buf_position[kBuffer]; GradientPair buf_gpair[kBuffer]; for (bst_uint j = 0; j < align_length; j += kBuffer) { for (bst_uint i = 0; i < kBuffer; ++i) { bst_uint ridx = col[j + i].index; buf_position[i] = this->position_[ridx]; buf_gpair[i] = gpair[ridx]; } for (bst_uint i = 0; i < kBuffer; ++i) { const int nid = buf_position[i]; if (nid >= 0) { hbuilder[nid].Add(col[j + i].fvalue, buf_gpair[i]); } } } for (bst_uint j = align_length; j < col.size(); ++j) { const bst_uint ridx = col[j].index; const int nid = this->position_[ridx]; if (nid >= 0) { hbuilder[nid].Add(col[j].fvalue, gpair[ridx]); } } } else { for (const auto& c : col) { const bst_uint ridx = c.index; const int nid = this->position_[ridx]; if (nid >= 0) { hbuilder[nid].Add(c.fvalue, gpair, ridx); } } } } inline void UpdateSketchCol(const std::vector<GradientPair> &gpair, const SparsePage::Inst &col, const RegTree &tree, size_t work_set_size, bst_uint offset, std::vector<BaseMaker::SketchEntry> *p_temp) { if (col.size() == 0) return; // initialize sbuilder for use std::vector<BaseMaker::SketchEntry> &sbuilder = *p_temp; sbuilder.resize(tree.param.num_nodes); for (int const nid : this->qexpand_) { const unsigned wid = this->node2workindex_[nid]; sbuilder[nid].sum_total = 0.0f; sbuilder[nid].sketch = &sketchs_[wid * work_set_size + offset]; } // first pass, get sum of weight, TODO, optimization to skip first pass for (const auto& c : col) { const bst_uint ridx = c.index; const int nid = this->position_[ridx]; if (nid >= 0) { sbuilder[nid].sum_total += gpair[ridx].GetHess(); } } // if only one value, no need to do second pass if (col[0].fvalue == col[col.size()-1].fvalue) { for (int const nid : this->qexpand_) { sbuilder[nid].sketch->Push( col[0].fvalue, static_cast<bst_float>(sbuilder[nid].sum_total)); } return; } // two pass scan unsigned max_size = this->param_.MaxSketchSize(); for (int const nid : this->qexpand_) { sbuilder[nid].Init(max_size); } // second pass, build the sketch if (this->param_.cache_opt != 0) { constexpr bst_uint kBuffer = 32; bst_uint align_length = col.size() / kBuffer * kBuffer; int buf_position[kBuffer]; bst_float buf_hess[kBuffer]; for (bst_uint j = 0; j < align_length; j += kBuffer) { for (bst_uint i = 0; i < kBuffer; ++i) { bst_uint ridx = col[j + i].index; buf_position[i] = this->position_[ridx]; buf_hess[i] = gpair[ridx].GetHess(); } for (bst_uint i = 0; i < kBuffer; ++i) { const int nid = buf_position[i]; if (nid >= 0) { sbuilder[nid].Push(col[j + i].fvalue, buf_hess[i], max_size); } } } for (bst_uint j = align_length; j < col.size(); ++j) { const bst_uint ridx = col[j].index; const int nid = this->position_[ridx]; if (nid >= 0) { sbuilder[nid].Push(col[j].fvalue, gpair[ridx].GetHess(), max_size); } } } else { for (const auto& c : col) { const bst_uint ridx = c.index; const int nid = this->position_[ridx]; if (nid >= 0) { sbuilder[nid].Push(c.fvalue, gpair[ridx].GetHess(), max_size); } } } for (int const nid : this->qexpand_) { sbuilder[nid].Finalize(max_size); } } // cached dmatrix where we initialized the feature on. const DMatrix* cache_dmatrix_{nullptr}; // feature helper BaseMaker::FMetaHelper feat_helper_; // temp space to map feature id to working index std::vector<int> feat2workindex_; // set of index from fset that are current work set std::vector<bst_feature_t> work_set_; // set of index from that are split candidates. std::vector<bst_uint> fsplit_set_; // thread temp data std::vector<std::vector<BaseMaker::SketchEntry> > thread_sketch_; // used to hold statistics std::vector<std::vector<GradStats> > thread_stats_; // used to hold start pointer std::vector<std::vector<HistEntry> > thread_hist_; // node statistics std::vector<GradStats> node_stats_; // summary array std::vector<WXQSketch::SummaryContainer> summary_array_; // reducer for summary rabit::SerializeReducer<WXQSketch::SummaryContainer> sreducer_; // per node, per feature sketch std::vector<common::WXQuantileSketch<bst_float, bst_float> > sketchs_; }; // global proposal class GlobalProposalHistMaker: public CQHistMaker { public: char const* Name() const override { return "grow_histmaker"; } protected: void ResetPosAndPropose(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, const std::vector<bst_feature_t> &fset, const RegTree &tree) override { if (this->qexpand_.size() == 1) { cached_rptr_.clear(); cached_cut_.clear(); } if (cached_rptr_.size() == 0) { CHECK_EQ(this->qexpand_.size(), 1U); CQHistMaker::ResetPosAndPropose(gpair, p_fmat, fset, tree); cached_rptr_ = this->wspace_.rptr; cached_cut_ = this->wspace_.cut; } else { this->wspace_.cut.clear(); this->wspace_.rptr.clear(); this->wspace_.rptr.push_back(0); for (size_t i = 0; i < this->qexpand_.size(); ++i) { for (size_t j = 0; j < cached_rptr_.size() - 1; ++j) { this->wspace_.rptr.push_back( this->wspace_.rptr.back() + cached_rptr_[j + 1] - cached_rptr_[j]); } this->wspace_.cut.insert(this->wspace_.cut.end(), cached_cut_.begin(), cached_cut_.end()); } CHECK_EQ(this->wspace_.rptr.size(), (fset.size() + 1) * this->qexpand_.size() + 1); CHECK_EQ(this->wspace_.rptr.back(), this->wspace_.cut.size()); } } // code to create histogram void CreateHist(const std::vector<GradientPair> &gpair, DMatrix *p_fmat, const std::vector<bst_feature_t> &fset, const RegTree &tree) override { const MetaInfo &info = p_fmat->Info(); // fill in reverse map this->feat2workindex_.resize(tree.param.num_feature); this->work_set_ = fset; std::fill(this->feat2workindex_.begin(), this->feat2workindex_.end(), -1); for (size_t i = 0; i < fset.size(); ++i) { this->feat2workindex_[fset[i]] = static_cast<int>(i); } // start to work this->wspace_.Configure(1); // to gain speedup in recovery { this->thread_hist_.resize(omp_get_max_threads()); // TWOPASS: use the real set + split set in the column iteration. this->SetDefaultPostion(p_fmat, tree); this->work_set_.insert(this->work_set_.end(), this->fsplit_set_.begin(), this->fsplit_set_.end()); XGBOOST_PARALLEL_SORT(this->work_set_.begin(), this->work_set_.end(), std::less<>{}); this->work_set_.resize( std::unique(this->work_set_.begin(), this->work_set_.end()) - this->work_set_.begin()); // start accumulating statistics for (const auto &batch : p_fmat->GetBatches<SortedCSCPage>()) { // TWOPASS: use the real set + split set in the column iteration. this->CorrectNonDefaultPositionByBatch(batch, this->fsplit_set_, tree); auto page = batch.GetView(); // start enumeration const auto nsize = static_cast<bst_omp_uint>(this->work_set_.size()); #pragma omp parallel for schedule(dynamic, 1) for (bst_omp_uint i = 0; i < nsize; ++i) { int fid = this->work_set_[i]; int offset = this->feat2workindex_[fid]; if (offset >= 0) { this->UpdateHistCol(gpair, page[fid], info, tree, fset, offset, &this->thread_hist_[omp_get_thread_num()]); } } } // update node statistics. this->GetNodeStats(gpair, *p_fmat, tree, &(this->thread_stats_), &(this->node_stats_)); for (const int nid : this->qexpand_) { const int wid = this->node2workindex_[nid]; this->wspace_.hset[0][fset.size() + wid * (fset.size()+1)] .data[0] = this->node_stats_[nid]; } } this->histred_.Allreduce(dmlc::BeginPtr(this->wspace_.hset[0].data), this->wspace_.hset[0].data.size()); } // cached unit pointer std::vector<unsigned> cached_rptr_; // cached cut value. std::vector<bst_float> cached_cut_; }; XGBOOST_REGISTER_TREE_UPDATER(LocalHistMaker, "grow_local_histmaker") .describe("Tree constructor that uses approximate histogram construction.") .set_body([]() { return new CQHistMaker(); }); // The updater for approx tree method. XGBOOST_REGISTER_TREE_UPDATER(HistMaker, "grow_histmaker") .describe("Tree constructor that uses approximate global of histogram construction.") .set_body([]() { return new GlobalProposalHistMaker(); }); } // namespace tree } // namespace xgboost
; ; Startup Code for Z88 applications ; ; The entry point is a dummy function in the DOR which then ; jumps to routine in this file ; ; 1/4/99 djm ; ; 7/4/99 djm Added function to handle commands - this requires ; the user to do something for it! ; ; 4/5/99 djm Added in functionality to remove check for expanded ; machine, not to give those people reluctant to ug something to ; use, but to save memory in very small apps ; ; 1/4/2000 djm Added in conditionals for: ; - far heap stuff (Ask GWL for details!) ; - "ANSI" stdio - i.e. flagged and ungetc'able ; ; 6/10/2001 djm Clean up (after Henk) ; ; $Id: app_crt0.asm,v 1.30 2016-07-15 19:32:43 dom Exp $ PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) PUBLIC processcmd ;Processing <> commands PUBLIC _cpfar2near ;Conversion of far to near data INCLUDE "stdio.def" INCLUDE "fileio.def" INCLUDE "memory.def" INCLUDE "error.def" INCLUDE "time.def" INCLUDE "syspar.def" INCLUDE "director.def" PUBLIC app_entrypoint ;Start of execution in this file EXTERN applname ;Application name (in DOR) EXTERN in_dor ;DOR address IF !DEFINED_CRT_ORG_CODE defc CRT_ORG_CODE = 49152 ENDIF IF !DEFINED_CLIB_FOPEN_MAX defc DEFINED_CLIB_FOPEN_MAX = 1 defc CLIB_FOPEN_MAX = 5 ENDIF defc TAR__clib_exit_stack_size = 32 defc TAR__register_sp = -1 defc CRT_KEY_DEL = 127 INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE ; Graphics map and segment EXTERN z88_map_bank EXTERN z88_map_segment defc z88_map_bank = $4D1 defc z88_map_segment = 64 IF !DEFINED_CRT_Z88_SAFEDATA defc CRT_Z88_SAFEDATA = 0 ENDIF IF !DEFINED_CRT_Z88_EXPANDED defc CRT_Z88_EXPANDED = 1 ENDIF ;-------- ; Start of execution. We enter with ix pointing to info table about ; memory allocated to us by OZ. ;-------- app_entrypoint: crt0_reqpag_check: ld a,0 and a IF CRT_Z88_EXPANDED=0 jr z,init_continue ELSE jr z,init_check_expanded ENDIF add 32 ld c,a ld a,(ix+2) ;Check allocated bad memory if needed cp c ld hl,nomemory IF CRT_Z88_EXPANDED = 0 jr nc,init_continue ELSE jr c,init_error ENDIF IF CRT_Z88_EXPANDED != 0 init_check_expanded: ld ix,-1 ;Check for an expanded machine ld a,FA_EOF call_oz(os_frm) jr z,init_continue ld hl,need_expanded_text ENDIF init_error: ;Code to deal with an initialisation error push hl ;The text that we are printing ld hl,clrscr ;Clear the screen call_oz(gn_sop) ld hl,windini ;Define a small window call_oz(gn_sop) pop hl call_oz(gn_sop) ;Print text ld bc,500 call_oz(os_dly) ;Pause xor a call_oz(os_bye) ;Exit init_continue: ;We had enough memory ld a,SC_DIS ;Disable escape call_oz(Os_Esc) xor a ;Setup our error handler ld b,a ld hl,errhan call_oz(os_erh) ld (l_errlevel),a ;Save previous values ld (l_erraddr),hl ld hl,applname ;Name application call_oz(dc_nam) ld hl,clrscr ;Setup a BASIC sized window call_oz(gn_sop) ld hl,clrscr2 call_oz(gn_sop) INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld (exitsp),sp IF DEFINED_USING_amalloc crt0_reqpag_check1: ld hl,0 ; reqpag address INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF IF DEFINED_farheapsz call init_far ;Initialise far memory if required ENDIF call _main ;Call the users code ld l,0 ;Default return value is 0 cleanup: ;Jump back to here from exit() push hl ;Save exit value call crt0_exit IF DEFINED_farheapsz EXTERN freeall_far call freeall_far ;Deallocate far memory ENDIF pop hl ;Get exit value back ld a,l call_oz(os_bye) ;Exit back to OZ l_dcal: jp (hl) ;Used by various things ;------- ; Process a <> command, we call the users handlecmds APPFUNC ;------- processcmd: IF DEFINED_handlecmds ld l,a ld h,0 push hl call handlecmds pop bc ENDIF ld hl,0 ;dummy return value ret ;-------- ; Fairly simple error handler ;-------- errhan: ret z ;Fatal error - far mem probs? IF DEFINED_redrawscreen cp RC_Draw ;(Rc_susp for BASIC!) jr nz,errhan2 push af ;Call users screen redraw fn if defined call redrawscreen pop af ENDIF errhan2: cp RC_Quit ;they don't like us! jr nz,not_quit IF DEFINED_applicationquit call applicationquit ENDIF xor a ;Standard cleanup jr cleanup not_quit: xor a ret ;-------- ; This bit of code allows us to use OZ ptrs transparently ; We copy any data from up far to a near buffer so that OZ ; is happy about it ; Prototype is extern void __FASTCALL__ *cpfar2near(far void *) ;-------- IF DEFINED_farheapsz EXTERN strcpy_far _cpfar2near: pop bc ;ret address pop hl pop de ;far ptr push bc ;keep ret address ld a,e and a ret z ;already local push ix ;keep ix safe ld bc,0 ;local push bc ld bc,copybuff push bc ;dest push de ;source push hl call strcpy_far pop bc ;dump args pop bc pop bc pop bc pop ix ;get ix back ld hl,copybuff ret ELSE ; We have no far code installed so all we have to do is fix the stack _cpfar2near: pop bc pop hl pop de push bc ret ENDIF INCLUDE "crt/classic/crt_runtime_selection.asm" ;------- ; Text to define the BASIC style window ;------- clrscr: defb 1,'7','#','1',32,32,32+94,32+8,128,1,'2','C','1',0 clrscr2: defb 1,'2','+','S',1,'2','+','C',0 windini: defb 1,'7','#','3',32+7,32+1,32+34,32+7,131 ;dialogue box defb 1,'2','C','3',1,'4','+','T','U','R',1,'2','J','C' defb 1,'3','@',32,32 ;reset to (0,0) defm "z88dk Application" defb 1,'3','@',32,32 ,1,'2','A',32+34 ;keep settings for 10 defb 1,'7','#','3',32+8,32+3,32+32,32+5,128 ;dialogue box defb 1,'2','C','3' defb 1,'3','@',32,32,1,'2','+','B' defb 0 nomemory: defb 1,'3','@',32,32,1,'2','J','C' defm "No memory available" defb 13,10,13,10 defm "Sorry, please try again later!" defb 0 IF CRT_Z88_EXPANDED != 0 need_expanded_text: defb 1,'3','@',32,32,1,'2','J','C' defm "Expanded machine needed!" defb 0 ENDIF ; If we were given a model then use it IF DEFINED_CRT_MODEL defc __crt_model = CRT_MODEL ELSE defc __crt_model = 1 ENDIF ; We use a split BSS - so that some basic apps can run without needing bad memory ; Expose to appmake PUBLIC __crt_z88_safedata defc __crt_z88_safedata = 120 + CRT_Z88_SAFEDATA defc __crt_org_bss = $1ffD - 100 ; __crt_z88_safedata ; We have to get user variables to start at 0x2000, and far ; data at 8192 to match up with CamelForth IF CRT_Z88_SAFEDATA = 0 defc __crt_org_bss_fardata_start = 8192 ENDIF INCLUDE "crt/classic/crt_section.asm" SECTION bss_crt l_erraddr: defw 0 ;Not sure if these are used... l_errlevel: defb 0 IF DEFINED_farheapsz IF !CRT_Z88_SAFEDATA SECTION code_crt_init INCLUDE "target/z88/classic/init_far.asm" SECTION bss_fardata ; If we use CRT_Z88_SAFEDATA then we can't have far memory PUBLIC pool_table PUBLIC malloc_table PUBLIC farpages PUBLIC farmemspec pool_table: defs 224 malloc_table: defw 0 farpages: defw 1 farmemspec: defb 1 copybuff: defs 258 actual_malloc_table: defs ((farheapsz/256)+1)*2 ENDIF ENDIF
; A105133: Numbers n such that 8n + 5 is prime. ; 0,1,3,4,6,7,12,13,18,19,21,22,24,28,33,34,36,39,43,46,48,49,52,57,63,67,69,76,81,82,84,87,88,91,94,96,99,102,103,106,109,117,124,126,127,132,133,136,138,139,147,151,153,154,159,162,171,172,178,181,186,193,199,201,202,204,208,211,213,216,217,223,232,234,237,241,243,246,249,253,256,258,267,276,277,279,283,286,288,291,292,294,297,298,304,309,318,319,327,334 mov $1,1 mov $2,$0 pow $2,2 mul $2,2 mov $5,1 lpb $2 add $1,3 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,4 add $1,$5 sub $2,1 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe div $1,2 mul $1,2 sub $1,6 div $1,8 mov $0,$1
; A003314: Binary entropy function: a(1)=0; for n > 1, a(n) = n + min { a(k)+a(n-k) : 1 <= k <= n-1 }. ; 0,2,5,8,12,16,20,24,29,34,39,44,49,54,59,64,70,76,82,88,94,100,106,112,118,124,130,136,142,148,154,160,167,174,181,188,195,202,209,216,223,230,237,244,251,258,265,272,279,286,293,300,307,314,321,328,335,342,349,356,363,370,377,384,392,400,408,416,424,432,440,448,456,464,472,480,488,496,504,512,520,528,536,544,552,560,568,576,584,592,600,608,616,624,632,640,648,656,664,672,680,688,696,704,712,720,728,736,744,752,760,768,776,784,792,800,808,816,824,832,840,848,856,864,872,880,888,896,905,914,923,932,941,950,959,968,977,986,995,1004,1013,1022,1031,1040,1049,1058,1067,1076,1085,1094,1103,1112,1121,1130,1139,1148,1157,1166,1175,1184,1193,1202,1211,1220,1229,1238,1247,1256,1265,1274,1283,1292,1301,1310,1319,1328,1337,1346,1355,1364,1373,1382,1391,1400,1409,1418,1427,1436,1445,1454,1463,1472,1481,1490,1499,1508,1517,1526,1535,1544,1553,1562,1571,1580,1589,1598,1607,1616,1625,1634,1643,1652,1661,1670,1679,1688,1697,1706,1715,1724,1733,1742,1751,1760,1769,1778,1787,1796,1805,1814,1823,1832,1841,1850,1859,1868,1877,1886,1895,1904,1913,1922,1931,1940,1949,1958,1967,1976,1985,1994 mov $1,$0 lpb $0 add $2,$0 mul $0,2 sub $0,1 trn $0,$1 lpe add $1,$2
;;----------------------------------------------------------------------------;; ;; Change filter ATTR1 to select the correct files from server by language. ;; Copyright 2014 Benito Palacios (aka pleonex) ;; ;; 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. ;;----------------------------------------------------------------------------;; ; Filter with base64 encoding in ascii. Write it inversed due to low-endiannes. @langBase64 equ "U1BB" ; inv(base64("SPA")) = inv("U1BB") = "BB1U" @wifiStringCopy equ 0x0208A780 .arm ; # Originally, here it frees the string allocated. Since we are not ; allocating, it's hard-coded, we don't need to free. I have try to ; allocate a string using the same function as other parameters like ; MAC, token and so, but I don't know why, the game takes other path ; and ends with an error 31020. I have debug that many many hours ; (7 hours at least) and I haven't found any solution. That would be the ; best way, but this works too if and only if, the game does not use ; filters by itself (like in this case), sice we wouldn't be freeing the mem. .org 0x0208A468 NOP .org 0x0208A7CC .area 0x198 STMFD SP!, {R3-R9,LR} LDR R6, =0x20ABA84 MOV R5, R0 MOV R4, R1 STR R5, [R6,#4] LDR R0, [SP,#0x28] STR R0, [R6] @load_filter: ADD r0, PC, (@filter - @load_filter) - 8 ; Filter ATTR1 = base64("SPA") ;BL @wifiStringCopy ; [old] Copy ATTR1 filter ;STR r8, [r0] ; [old] Write ATTR1 MOV r8, #0 ; ;STRB r8, [r0,#4] ; [old] Write null char MOV R9, #0 ; Null pointers for everyone ADD r7, r6, #0x3C ; Saving space, batch writing! STMIA r7, {r0,r8,r9} ; ... ;STR R9, [R6,#0x3C] ; ATTR1 ;STR R9, [R6,#0x40] ; ATTR2 ;STR R9, [R6,#0x44] ; ATTR3 ADD r7, r6, #0xC ; More saving with batching STMIA r7!, {r8,r9} ; ... ;STR R9, [R6,#0xC] ;STR R9, [R6,#0x10] STMIA r7, {r4,r8,r9} ; And even more! ;STR R4, [R6,#0x14] ;STR R9, [R6,#0x18] LDR R0, =0x20ABACC MOV R8, R2 MOV R7, R3 ;STR R9, [R6,#0x1C] BL 0x208BDE8 LDR R0, =0x20ABB51 BL 0x208AC84 MOV R0, R8 BL 0x208A780 STR R0, [R6,#0x1C] CMP R0, #0 BEQ @loc_208A904 MOV R0, R7 BL 0x208A780 STR R0, [R6,#0x18] CMP R0, #0 BEQ @loc_208A904 LDR R8, =0x20ABAB5 LDR R1, [SP,#0x20] MOV R0, R8 MOV R2, #4 BL 0x208A54C LDR R7, =0x20ABB38 STRB R9, [R8,R0] LDR R1, [SP,#0x24] MOV R0, R7 MOV R2, #0x10 BL 0x208A54C STRB R9, [R7,R0] BL 0x208BD30 CMP R0, #0 BEQ @loc_208A8D0 BL 0x208BCEC CMP R0, #0 BEQ @loc_208A8D0 MOV R7, #0x11 MOV R0, R5 MOV R1, R4 MOV R2, R7 BL 0x209095C SUB R1, R7, #0x12 CMP R0, R1 BEQ @loc_208A8D0 LDR R0, =0x20ABADD BL 0x208AAF0 STR R0, [R6,#0xC] MOV R0, #1 STR R0, [R6,#8] LDMFD SP!, {R3-R9,PC} @loc_208A8D0: LDR R4, =0x20ABA84 LDR R0, [R4,#0x18] LDR R1, [R4,#0x14] BLX R1 LDR R0, [R4,#0x1C] LDR R1, [R4,#0x14] BLX R1 MOV R4, #0 MOV R1, R4 MOV R0, #8 BL 0x208AA20 MOV R0, R4 LDMFD SP!, {R3-R9,PC} @loc_208A904: LDR R1, =0x20ABA84 LDR R0, [R1,#0x18] CMP R0, #0 BEQ @loc_208A91C LDR R1, [R1,#0x14] BLX R1 @loc_208A91C: LDR R1, =0x20ABA84 LDR R0, [R1,#0x1C] CMP R0, #0 BEQ @loc_208A934 LDR R1, [R1,#0x14] BLX R1 @loc_208A934: MOV R4, #0 MOV R1, R4 MOV R0, #1 BL 0x208AA20 MOV R0, R4 LDMFD SP!, {R3-R9,PC} @filter: .db @langBase64, 0x00 .pool .endarea
.386 STACK segment USE16 STACK DB 200 DUP(0) STACK ENDS ;数据段 DATA SEGMENT USE16 TIP DB 'ENROLLED $' DATA ENDS ;代码段 CODE SEGMENT USE16 ASSUME CS:CODE,DS:CODE,SS:STACK COUNT DB 18 HOUR DB ?,?,':' MIN db ?,?,':' SEC DB ?,? BUF_LEN = $ - HOUR CURSOR DW ? OLDBX DW 00E0H OLDES DW 0F100H OLD_INT DW ?,? NEW08H PROC FAR PUSHF CALL DWORD PTR CS:OLD_INT DEC CS:COUNT JZ DISP IRET DISP: MOV CS:COUNT,18 STI PUSHA PUSH DS PUSH ES MOV AX,CS MOV DS,AX MOV ES,AX CALL GET_TIME MOV BH,0 MOV AH,3 INT 10H MOV CURSOR,DX MOV BP,OFFSET HOUR MOV BH,0 MOV DH,0 MOV DL,80 - BUF_LEN MOV BL,07H MOV CX,BUF_LEN MOV AL,0 MOV AH,13H INT 10H MOV BH,0 MOV DX,CURSOR MOV AH,2 INT 10H POP ES POP DS POPA IRET NEW08H ENDP GET_TIME PROC MOV AL,4 OUT 70H,AL JMP $+2 IN AL,71H MOV AH,AL AND AL,0FH SHR AH,4 ADD AX,3030H XCHG AH,AL MOV WORD PTR HOUR , AX MOV AL,2 OUT 70H,AL JMP $+2 IN AL,71H MOV AH,AL AND AL,0FH SHR AH,4 ADD AX,3030H XCHG AH,AL MOV WORD PTR MIN,AX MOV AL,0 OUT 70H,AL JMP $+2 IN AL,71H MOV AH,AL AND AL,0FH SHR AH,4 ADD AX,3030H XCHG AH,AL MOV WORD PTR SEC,AX RET GET_TIME ENDP BEGIN: PUSH CS POP DS MOV AX,3508H INT 21H CMP BX,OLDBX JNE ENROLLED mov AX,ES cmp AX,OLDES JNE ENROLLED MOV OLD_INT,BX MOV OLD_INT+2,ES MOV DX,OFFSET NEW08H MOV AX,2508H INT 21H NEXT: MOV AH,0 INT 16H CMP AL,'q' JNE NEXT JMP EXIT ENROLLED: MOV AX, DATA MOV DS, AX LEA DX, TIP MOV AH, 9H INT 21H EXIT: MOV DX, OFFSET BEGIN +15 MOV CL, 4 SHR DX, CL ADD DX, 20H MOV AL, 0 MOV AH, 31H INT 21H CODE ENDS END BEGIN
; A195034: Vertex number of a square spiral in which the length of the first two edges are the legs of the primitive Pythagorean triple [21, 20, 29]. The edges of the spiral have length A195033. ; 0,21,41,83,123,186,246,330,410,515,615,741,861,1008,1148,1316,1476,1665,1845,2055,2255,2486,2706,2958,3198,3471,3731,4025,4305,4620,4920,5256,5576,5933,6273,6651,7011,7410,7790,8210,8610,9051,9471,9933,10373,10856,11316,11820,12300,12825,13325,13871,14391,14958,15498,16086,16646,17255,17835,18465,19065,19716,20336,21008,21648,22341,23001,23715,24395,25130,25830,26586,27306,28083,28823,29621,30381,31200,31980,32820,33620,34481,35301,36183,37023,37926,38786,39710,40590,41535,42435,43401,44321 mov $2,3 mov $3,2 mov $7,5 mov $8,$0 mov $9,$0 lpb $2 mov $5,$9 mul $7,2 lpb $5 add $7,1 add $1,$7 trn $5,$3 lpe mov $2,2 lpe mov $4,$8 mul $4,5 add $1,$4 mov $6,$8 mul $6,$8 mov $4,$6 mul $4,5 add $1,$4 mov $0,$1
; A173044: Product plus sum of five consecutive nonnegative numbers. ; 10,135,740,2545,6750,15155,30280,55485,95090,154495,240300,360425,524230,742635,1028240,1395445,1860570,2441975,3160180,4037985,5100590,6375715,7893720,9687725,11793730,14250735,17100860,20389465,24165270,28480475,33390880,38956005,45239210,52307815,60233220,69091025,78961150,89927955,102080360,115511965,130321170,146611295,164490700,184072905,205476710,228826315,254251440,281887445,311875450,344362455,379501460,417451585,458378190,502452995,549854200,600766605,655381730,713897935,776520540,843461945,914941750,991186875,1072431680,1158918085,1250895690,1348621895,1452362020,1562389425,1678985630,1802440435,1933052040,2071127165,2216981170,2370938175,2533331180,2704502185,2884802310,3074591915,3274240720,3484127925,3704642330,3936182455,4179156660,4433983265,4701090670,4980917475,5273912600,5580535405,5901255810,6236554415,6586922620,6952862745,7334888150,7733523355,8149304160,8582777765,9034502890,9505049895,9995000900,10504949905 mov $2,$0 seq $0,158874 ; a(n) = (n + 4)*(n + 3)*(n + 2)*(n + 1)*n / 5 = 24*A000389(n+4). add $0,$2 mul $0,5 add $0,10
; A104474: a(n) = binomial(n+3,3)*binomial(n+7,3). ; Submitted by Christian Krause, https://github.com/ckrause ; 35,224,840,2400,5775,12320,24024,43680,75075,123200,194480,297024,440895,638400,904400,1256640,1716099,2307360,3059000,4004000,5180175,6630624,8404200,10556000,13147875,16248960,19936224,24295040,29419775 add $0,2 mov $1,3 add $1,$0 bin $1,$0 add $0,2 sub $0,$1 pow $0,2 sub $0,1
; A173316: 6*n! - 1. ; 5,5,11,35,143,719,4319,30239,241919,2177279,21772799,239500799,2874009599,37362124799,523069747199,7846046207999,125536739327999,2134124568575999 gcd $1,$0 cal $1,142 mul $1,6 sub $1,1
; A342423: a(n) = Sum_{k=1..n} gcd(k,n)^gcd(k,n). ; Submitted by Jamie Morken(s1.) ; 1,5,29,262,3129,46693,823549,16777484,387420549,10000003145,285311670621,8916100495490,302875106592265,11112006826381589,437893890380865741,18446744073726329368,827240261886336764193,39346408075296925089309,1978419655660313589123997,104857600000000010000007298,5842587018385982521382771681,341427877364219557681958394245,20880467999847912034355032910589,1333735776850284124457997606940420,88817841970012523233890533447278145,6156119580207157310796977163506796089 add $0,1 mov $2,$0 lpb $0 mul $3,206913 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 mov $4,$2 gcd $4,$3 mov $3,$4 pow $3,$4 add $1,$3 lpe add $0,$1
IDEAL P386 SEGMENT lerssicode ASSUME cs:lerssicode,ds:nothing,es:nothing LABEL body BYTE INCLUDE 'exebody.inc' LABEL header BYTE INCLUDE 'exehead.inc' PROC start NEAR mov ax, cs add [word cs:header+0eh], ax add [word cs:header+16h], ax sub ax, 10h mov es, ax mov ds, ax mov ss, [word cs:header+0eh] mov sp, [word cs:header+10h] jmp [dword cs:header+14h] ENDP jmp start ENDS END body
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/autofill_field.h" #include "base/logging.h" #include "base/sha1.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "components/autofill/core/browser/autofill_country.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/phone_number.h" #include "components/autofill/core/browser/state_names.h" #include "grit/component_strings.h" #include "ui/base/l10n/l10n_util.h" using base::ASCIIToUTF16; using base::StringToInt; namespace autofill { namespace { const char* const kMonthsAbbreviated[] = { NULL, // Padding so index 1 = month 1 = January. "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; const char* const kMonthsFull[] = { NULL, // Padding so index 1 = month 1 = January. "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", }; // Returns true if the value was successfully set, meaning |value| was found in // the list of select options in |field|. bool SetSelectControlValue(const base::string16& value, FormFieldData* field) { base::string16 value_lowercase = StringToLowerASCII(value); DCHECK_EQ(field->option_values.size(), field->option_contents.size()); base::string16 best_match; for (size_t i = 0; i < field->option_values.size(); ++i) { if (value == field->option_values[i] || value == field->option_contents[i]) { // An exact match, use it. best_match = field->option_values[i]; break; } if (value_lowercase == StringToLowerASCII(field->option_values[i]) || value_lowercase == StringToLowerASCII(field->option_contents[i])) { // A match, but not in the same case. Save it in case an exact match is // not found. best_match = field->option_values[i]; } } if (best_match.empty()) return false; field->value = best_match; return true; } // Try to fill a numeric |value| into the given |field|. bool FillNumericSelectControl(int value, FormFieldData* field) { DCHECK_EQ(field->option_values.size(), field->option_contents.size()); for (size_t i = 0; i < field->option_values.size(); ++i) { int option; if ((StringToInt(field->option_values[i], &option) && option == value) || (StringToInt(field->option_contents[i], &option) && option == value)) { field->value = field->option_values[i]; return true; } } return false; } bool FillStateSelectControl(const base::string16& value, FormFieldData* field) { base::string16 full, abbreviation; state_names::GetNameAndAbbreviation(value, &full, &abbreviation); // Try the abbreviation first. if (!abbreviation.empty() && SetSelectControlValue(abbreviation, field)) return true; return !full.empty() && SetSelectControlValue(full, field); } bool FillCountrySelectControl(const base::string16& value, const std::string& app_locale, FormFieldData* field_data) { std::string country_code = AutofillCountry::GetCountryCode(value, app_locale); if (country_code.empty()) return false; DCHECK_EQ(field_data->option_values.size(), field_data->option_contents.size()); for (size_t i = 0; i < field_data->option_values.size(); ++i) { // Canonicalize each <option> value to a country code, and compare to the // target country code. base::string16 value = field_data->option_values[i]; base::string16 contents = field_data->option_contents[i]; if (country_code == AutofillCountry::GetCountryCode(value, app_locale) || country_code == AutofillCountry::GetCountryCode(contents, app_locale)) { field_data->value = value; return true; } } return false; } bool FillExpirationMonthSelectControl(const base::string16& value, FormFieldData* field) { int index = 0; if (!StringToInt(value, &index) || index <= 0 || static_cast<size_t>(index) >= arraysize(kMonthsFull)) return false; bool filled = SetSelectControlValue(ASCIIToUTF16(kMonthsAbbreviated[index]), field) || SetSelectControlValue(ASCIIToUTF16(kMonthsFull[index]), field) || FillNumericSelectControl(index, field); return filled; } // Returns true if the last two digits in |year| match those in |str|. bool LastTwoDigitsMatch(const base::string16& year, const base::string16& str) { int year_int; int str_int; if (!StringToInt(year, &year_int) || !StringToInt(str, &str_int)) return false; return (year_int % 100) == (str_int % 100); } // Try to fill a year |value| into the given |field| by comparing the last two // digits of the year to the field's options. bool FillYearSelectControl(const base::string16& value, FormFieldData* field) { if (value.size() != 2U && value.size() != 4U) return false; DCHECK_EQ(field->option_values.size(), field->option_contents.size()); for (size_t i = 0; i < field->option_values.size(); ++i) { if (LastTwoDigitsMatch(value, field->option_values[i]) || LastTwoDigitsMatch(value, field->option_contents[i])) { field->value = field->option_values[i]; return true; } } return false; } // Try to fill a credit card type |value| (Visa, MasterCard, etc.) into the // given |field|. bool FillCreditCardTypeSelectControl(const base::string16& value, FormFieldData* field) { // Try stripping off spaces. base::string16 value_stripped; base::RemoveChars(StringToLowerASCII(value), base::kWhitespaceUTF16, &value_stripped); for (size_t i = 0; i < field->option_values.size(); ++i) { base::string16 option_value_lowercase; base::RemoveChars(StringToLowerASCII(field->option_values[i]), base::kWhitespaceUTF16, &option_value_lowercase); base::string16 option_contents_lowercase; base::RemoveChars(StringToLowerASCII(field->option_contents[i]), base::kWhitespaceUTF16, &option_contents_lowercase); // Perform a case-insensitive comparison; but fill the form with the // original text, not the lowercased version. if (value_stripped == option_value_lowercase || value_stripped == option_contents_lowercase) { field->value = field->option_values[i]; return true; } } // For American Express, also try filling as "AmEx". if (value == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX)) return FillCreditCardTypeSelectControl(ASCIIToUTF16("AmEx"), field); return false; } // Set |field_data|'s value to |number|, or possibly an appropriate substring of // |number|. The |field| specifies the type of the phone and whether this is a // phone prefix or suffix. void FillPhoneNumberField(const AutofillField& field, const base::string16& number, FormFieldData* field_data) { // Check to see if the size field matches the "prefix" or "suffix" sizes and // fill accordingly. base::string16 value = number; if (number.length() == PhoneNumber::kPrefixLength + PhoneNumber::kSuffixLength) { if (field.phone_part() == AutofillField::PHONE_PREFIX || field_data->max_length == PhoneNumber::kPrefixLength) { value = number.substr(PhoneNumber::kPrefixOffset, PhoneNumber::kPrefixLength); } else if (field.phone_part() == AutofillField::PHONE_SUFFIX || field_data->max_length == PhoneNumber::kSuffixLength) { value = number.substr(PhoneNumber::kSuffixOffset, PhoneNumber::kSuffixLength); } } field_data->value = value; } // Fills in the select control |field| with |value|. If an exact match is not // found, falls back to alternate filling strategies based on the |type|. bool FillSelectControl(const AutofillType& type, const base::string16& value, const std::string& app_locale, FormFieldData* field) { DCHECK_EQ("select-one", field->form_control_type); // Guard against corrupted values passed over IPC. if (field->option_values.size() != field->option_contents.size()) return false; if (value.empty()) return false; // First, search for exact matches. if (SetSelectControlValue(value, field)) return true; // If that fails, try specific fallbacks based on the field type. ServerFieldType storable_type = type.GetStorableType(); if (storable_type == ADDRESS_HOME_STATE) { return FillStateSelectControl(value, field); } else if (storable_type == ADDRESS_HOME_COUNTRY) { return FillCountrySelectControl(value, app_locale, field); } else if (storable_type == CREDIT_CARD_EXP_MONTH) { return FillExpirationMonthSelectControl(value, field); } else if (storable_type == CREDIT_CARD_EXP_2_DIGIT_YEAR || storable_type == CREDIT_CARD_EXP_4_DIGIT_YEAR) { return FillYearSelectControl(value, field); } else if (storable_type == CREDIT_CARD_TYPE) { return FillCreditCardTypeSelectControl(value, field); } return false; } // Fills in the month control |field| with |value|. |value| should be a date // formatted as MM/YYYY. If it isn't, filling will fail. bool FillMonthControl(const base::string16& value, FormFieldData* field) { // Autofill formats a combined date as month/year. std::vector<base::string16> pieces; base::SplitString(value, base::char16('/'), &pieces); if (pieces.size() != 2) return false; // HTML5 input="month" is formatted as year-month. base::string16 month = pieces[0]; base::string16 year = pieces[1]; if ((month.size() != 1 && month.size() != 2) || year.size() != 4) return false; // HTML5 input="month" expects zero-padded months. if (month.size() == 1) month = ASCIIToUTF16("0") + month; field->value = year + ASCIIToUTF16("-") + month; return true; } // Fills |field| with the street address in |value|. Translates newlines into // equivalent separators when necessary, i.e. when filling a single-line field. void FillStreetAddress(const base::string16& value, FormFieldData* field) { if (field->form_control_type == "textarea") { field->value = value; return; } base::string16 one_line_value; const base::char16 kNewline[] = { '\n', 0 }; const base::string16 separator = l10n_util::GetStringUTF16(IDS_AUTOFILL_ADDRESS_LINE_SEPARATOR); base::ReplaceChars(value, kNewline, separator, &one_line_value); field->value = one_line_value; } std::string Hash32Bit(const std::string& str) { std::string hash_bin = base::SHA1HashString(str); DCHECK_EQ(20U, hash_bin.length()); uint32 hash32 = ((hash_bin[0] & 0xFF) << 24) | ((hash_bin[1] & 0xFF) << 16) | ((hash_bin[2] & 0xFF) << 8) | (hash_bin[3] & 0xFF); return base::UintToString(hash32); } } // namespace AutofillField::AutofillField() : server_type_(NO_SERVER_DATA), heuristic_type_(UNKNOWN_TYPE), html_type_(HTML_TYPE_UNKNOWN), html_mode_(HTML_MODE_NONE), phone_part_(IGNORED) { } AutofillField::AutofillField(const FormFieldData& field, const base::string16& unique_name) : FormFieldData(field), unique_name_(unique_name), server_type_(NO_SERVER_DATA), heuristic_type_(UNKNOWN_TYPE), html_type_(HTML_TYPE_UNKNOWN), html_mode_(HTML_MODE_NONE), phone_part_(IGNORED) { } AutofillField::~AutofillField() {} void AutofillField::set_heuristic_type(ServerFieldType type) { if (type >= 0 && type < MAX_VALID_FIELD_TYPE && type != FIELD_WITH_DEFAULT_VALUE) { heuristic_type_ = type; } else { NOTREACHED(); // This case should not be reachable; but since this has potential // implications on data uploaded to the server, better safe than sorry. heuristic_type_ = UNKNOWN_TYPE; } } void AutofillField::set_server_type(ServerFieldType type) { // Chrome no longer supports fax numbers, but the server still does. if (type >= PHONE_FAX_NUMBER && type <= PHONE_FAX_WHOLE_NUMBER) return; server_type_ = type; } void AutofillField::SetHtmlType(HtmlFieldType type, HtmlFieldMode mode) { html_type_ = type; html_mode_ = mode; if (type == HTML_TYPE_TEL_LOCAL_PREFIX) phone_part_ = PHONE_PREFIX; else if (type == HTML_TYPE_TEL_LOCAL_SUFFIX) phone_part_ = PHONE_SUFFIX; else phone_part_ = IGNORED; } AutofillType AutofillField::Type() const { if (html_type_ != HTML_TYPE_UNKNOWN) return AutofillType(html_type_, html_mode_); if (server_type_ != NO_SERVER_DATA) return AutofillType(server_type_); return AutofillType(heuristic_type_); } bool AutofillField::IsEmpty() const { return value.empty(); } std::string AutofillField::FieldSignature() const { std::string field_name = base::UTF16ToUTF8(name); std::string field_string = field_name + "&" + form_control_type; return Hash32Bit(field_string); } bool AutofillField::IsFieldFillable() const { return should_autocomplete && !Type().IsUnknown(); } // static bool AutofillField::FillFormField(const AutofillField& field, const base::string16& value, const std::string& app_locale, FormFieldData* field_data) { AutofillType type = field.Type(); if (type.GetStorableType() == PHONE_HOME_NUMBER) { FillPhoneNumberField(field, value, field_data); return true; } else if (field_data->form_control_type == "select-one") { return FillSelectControl(type, value, app_locale, field_data); } else if (field_data->form_control_type == "month") { return FillMonthControl(value, field_data); } else if (type.GetStorableType() == ADDRESS_HOME_STREET_ADDRESS) { FillStreetAddress(value, field_data); return true; } field_data->value = value; return true; } } // namespace autofill
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ie_format_parser.h" #include "ie_layer_validators.hpp" #include <fstream> #include <set> #include <sstream> #include <unordered_set> #include "ie_blob_proxy.hpp" #include "ie_layer_parsers.h" #include "xml_parse_utils.h" using namespace InferenceEngine; using namespace InferenceEngine::details; using namespace XMLParseUtils; using namespace std; void LayerParseParameters::addOutputPort(const LayerPortData& port) { outputPorts.insert(std::upper_bound(outputPorts.begin(), outputPorts.end(), port, [=](const LayerParseParameters::LayerPortData& lhs, const LayerParseParameters::LayerPortData& rhs) { return lhs.portId < rhs.portId; }), port); } void LayerParseParameters::addInputPort(const LayerPortData& port) { inputPorts.insert(std::upper_bound(inputPorts.begin(), inputPorts.end(), port, [=](const LayerParseParameters::LayerPortData& lhs, const LayerParseParameters::LayerPortData& rhs) { return lhs.portId < rhs.portId; }), port); } IE_SUPPRESS_DEPRECATED_START inline void ParseSegment(LayerParseParameters& prms, const pugi::xml_node& blob) { uint64_t size = GetUInt64Attr(blob, "size", 0); uint64_t start = GetUInt64Attr(blob, "offset", 0); if (!size) return; WeightSegment& segment = prms.blobs[blob.name()]; segment.start = static_cast<size_t>(start); segment.size = static_cast<size_t>(size); const std::string& preStr = GetStrAttr(blob, "precision", ""); if (!preStr.empty()) segment.precision = Precision::FromStr(preStr); else segment.precision = prms.prms.precision; } void FormatParser::ParsePort(LayerParseParameters::LayerPortData& port, pugi::xml_node& node) const { port.portId = GetIntAttr(node, "id"); ParseDims(port.dims, node); const std::string& preStr = GetStrAttr(node, "precision", ""); if (!preStr.empty()) port.precision = Precision::FromStr(preStr); } void FormatParser::ParseGenericParams(pugi::xml_node& node, LayerParseParameters& layerParsePrms) const { layerParsePrms.layerId = GetIntAttr(node, "id"); layerParsePrms.underIRVersion = _version; InferenceEngine::LayerParams& prms = layerParsePrms.prms; prms.type = XMLParseUtils::GetStrAttr(node, "type"); prms.precision = _defPrecision; prms.name = GetStrAttr(node, "name"); const std::string& preStr = GetStrAttr(node, "precision", ""); if (!preStr.empty()) prms.precision = Precision::FromStr(preStr); if (prms.precision == Precision::MIXED) { IE_THROW() << "Layer precision must not be MIXED, at layer name: " << prms.name << ", offset: " << node.offset_debug(); } auto outNode = node.child("output"); if (!outNode.empty()) { FOREACH_CHILD(_cn, outNode, "port") { LayerParseParameters::LayerPortData port; port.precision = prms.precision; ParsePort(port, _cn); if (prms.type == "Const" || !prms.precision) prms.precision = port.precision; layerParsePrms.addOutputPort(port); } } auto inpNode = node.child("input"); if (!inpNode.empty()) { FOREACH_CHILD(_cn, inpNode, "port") { LayerParseParameters::LayerPortData port; port.precision = prms.precision; ParsePort(port, _cn); layerParsePrms.addInputPort(port); } } auto blob = node.child("biases"); if (!blob.empty()) { ParseSegment(layerParsePrms, blob); } blob = node.child("weights"); if (!blob.empty()) { ParseSegment(layerParsePrms, blob); } auto blobs = node.child("blobs"); if (!blobs.empty()) { for (blob = blobs.first_child(); !blob.empty(); blob = blob.next_sibling()) { ParseSegment(layerParsePrms, blob); } } } IE_SUPPRESS_DEPRECATED_END static inline std::string gen_id(int layer_id, int port_id) { return (std::to_string(layer_id) + '.' + std::to_string(port_id)); } InferenceEngine::CNNLayer::Ptr FormatParser::CreateLayer(pugi::xml_node& node, LayerParseParameters& layerParsePrms) const { for (auto& creator : creators) { if (!creator->shouldCreate(layerParsePrms.prms.type)) continue; return creator->CreateLayer(node, layerParsePrms); } LayerCreator<GenericLayer> genericCreator(""); return genericCreator.CreateLayer(node, layerParsePrms); } void FormatParser::SetLayerInput(CNNNetworkImpl& network, const std::string& dataId, CNNLayerPtr& targetLayer, int inputPort) { DataPtr& dataPtr = _portsToData[dataId]; if (!dataPtr) IE_THROW() << "in Layer " << targetLayer->name << ": trying to connect an edge to non existing output port: " << dataId; getInputTo(dataPtr)[targetLayer->name] = targetLayer; const LayerParseParameters& parseInfo = layersParseInfo[targetLayer->name]; if (targetLayer->insData.empty()) { targetLayer->insData.resize(parseInfo.inputPorts.size()); } for (unsigned i = 0; i < parseInfo.inputPorts.size(); i++) { if (parseInfo.inputPorts[i].portId != inputPort) continue; if (parseInfo.inputPorts[i].precision != dataPtr->getPrecision()) { if (dataPtr->getPrecision() == Precision::UNSPECIFIED) { dataPtr->setPrecision(parseInfo.inputPorts[i].precision); } else { // TODO: Make a correct exception /*IE_THROW() << "in Layer " << targetLayer->name << ": trying to connect an edge to mismatch precision of output port: " << dataPtr->getName();*/ } } if (!equal(parseInfo.inputPorts[i].dims, dataPtr->getDims())) IE_THROW() << "in Layer " << targetLayer->name << ": trying to connect an edge to mismatch dimensions of output port: " << dataPtr->getName() << " dims input: " << dumpVec(parseInfo.inputPorts[i].dims) << " dims output: " << dumpVec(dataPtr->getDims()); targetLayer->insData[i] = dataPtr; const auto insId = gen_id(parseInfo.layerId, parseInfo.inputPorts[i].portId); _portsToData[insId] = dataPtr; return; } IE_THROW() << "input port " << inputPort << " does not exist in layer " << targetLayer->name; } FormatParser::FormatParser(size_t version): _version(version) { // there should be unique_ptr but it cant be used with initializer lists creators = {std::make_shared<LayerCreator<PowerLayer>>("Power"), std::make_shared<LayerCreator<ConvolutionLayer>>("Convolution"), std::make_shared<LayerCreator<DeconvolutionLayer>>("Deconvolution"), std::make_shared<LayerCreator<DeformableConvolutionLayer>>("DeformableConvolution"), std::make_shared<LayerCreator<PoolingLayer>>("Pooling"), std::make_shared<LayerCreator<FullyConnectedLayer>>("InnerProduct"), std::make_shared<LayerCreator<FullyConnectedLayer>>("FullyConnected"), std::make_shared<LayerCreator<NormLayer>>("LRN"), std::make_shared<LayerCreator<NormLayer>>("Norm"), std::make_shared<LayerCreator<SoftMaxLayer>>("Softmax"), std::make_shared<LayerCreator<SoftMaxLayer>>("LogSoftmax"), std::make_shared<LayerCreator<GRNLayer>>("GRN"), std::make_shared<LayerCreator<MVNLayer>>("MVN"), std::make_shared<LayerCreator<ReLULayer>>("ReLU"), std::make_shared<LayerCreator<ClampLayer>>("Clamp"), std::make_shared<LayerCreator<SplitLayer>>("Split"), std::make_shared<LayerCreator<SplitLayer>>("Slice"), std::make_shared<LayerCreator<ConcatLayer>>("Concat"), std::make_shared<LayerCreator<EltwiseLayer>>("Eltwise"), std::make_shared<LayerCreator<GemmLayer>>("Gemm"), std::make_shared<LayerCreator<PadLayer>>("Pad"), std::make_shared<LayerCreator<GatherLayer>>("Gather"), std::make_shared<LayerCreator<StridedSliceLayer>>("StridedSlice"), std::make_shared<LayerCreator<ShuffleChannelsLayer>>("ShuffleChannels"), std::make_shared<LayerCreator<DepthToSpaceLayer>>("DepthToSpace"), std::make_shared<LayerCreator<SpaceToDepthLayer>>("SpaceToDepth"), std::make_shared<LayerCreator<SpaceToBatchLayer>>("SpaceToBatch"), std::make_shared<LayerCreator<BatchToSpaceLayer>>("BatchToSpace"), std::make_shared<LayerCreator<SparseFillEmptyRowsLayer>>("SparseFillEmptyRows"), std::make_shared<LayerCreator<SparseSegmentReduceLayer>>("SparseSegmentMean"), std::make_shared<LayerCreator<SparseSegmentReduceLayer>>("SparseSegmentSqrtN"), std::make_shared<LayerCreator<SparseSegmentReduceLayer>>("SparseSegmentSum"), std::make_shared<LayerCreator<ExperimentalSparseWeightedReduceLayer>>("ExperimentalSparseWeightedSum"), std::make_shared<LayerCreator<SparseToDenseLayer>>("SparseToDense"), std::make_shared<LayerCreator<BucketizeLayer>>("Bucketize"), std::make_shared<LayerCreator<ReverseSequenceLayer>>("ReverseSequence"), std::make_shared<LayerCreator<CNNLayer>>("Squeeze"), std::make_shared<LayerCreator<CNNLayer>>("Unsqueeze"), std::make_shared<LayerCreator<RangeLayer>>("Range"), std::make_shared<LayerCreator<BroadcastLayer>>("Broadcast"), std::make_shared<LayerCreator<ScaleShiftLayer>>("ScaleShift"), std::make_shared<LayerCreator<PReLULayer>>("PReLU"), std::make_shared<LayerCreator<CropLayer>>("Crop"), std::make_shared<LayerCreator<ReshapeLayer>>("Reshape"), std::make_shared<LayerCreator<ReshapeLayer>>("Flatten"), std::make_shared<LayerCreator<TileLayer>>("Tile"), std::make_shared<ActivationLayerCreator>("Activation"), std::make_shared<LayerCreator<BatchNormalizationLayer>>("BatchNormalization"), std::make_shared<TILayerCreator>("TensorIterator"), std::make_shared<LayerCreator<LSTMCell>>("LSTMCell"), std::make_shared<LayerCreator<GRUCell>>("GRUCell"), std::make_shared<LayerCreator<RNNCell>>("RNNCell"), std::make_shared<LayerCreator<OneHotLayer>>("OneHot"), std::make_shared<LayerCreator<RNNSequenceLayer>>("RNNSequence"), std::make_shared<LayerCreator<RNNSequenceLayer>>("GRUSequence"), std::make_shared<LayerCreator<RNNSequenceLayer>>("LSTMSequence"), std::make_shared<LayerCreator<BinaryConvolutionLayer>>("BinaryConvolution"), std::make_shared<LayerCreator<SelectLayer>>("Select"), std::make_shared<LayerCreator<MathLayer>>("Abs"), std::make_shared<LayerCreator<MathLayer>>("Acos"), std::make_shared<LayerCreator<MathLayer>>("Acosh"), std::make_shared<LayerCreator<MathLayer>>("Asin"), std::make_shared<LayerCreator<MathLayer>>("Asinh"), std::make_shared<LayerCreator<MathLayer>>("Atan"), std::make_shared<LayerCreator<MathLayer>>("Atanh"), std::make_shared<LayerCreator<MathLayer>>("Ceil"), std::make_shared<LayerCreator<MathLayer>>("Cos"), std::make_shared<LayerCreator<MathLayer>>("Cosh"), std::make_shared<LayerCreator<MathLayer>>("Erf"), std::make_shared<LayerCreator<MathLayer>>("Floor"), std::make_shared<LayerCreator<MathLayer>>("HardSigmoid"), std::make_shared<LayerCreator<MathLayer>>("Log"), std::make_shared<LayerCreator<MathLayer>>("Neg"), std::make_shared<LayerCreator<MathLayer>>("Reciprocal"), std::make_shared<LayerCreator<MathLayer>>("Selu"), std::make_shared<LayerCreator<MathLayer>>("Sign"), std::make_shared<LayerCreator<MathLayer>>("Sin"), std::make_shared<LayerCreator<MathLayer>>("Sinh"), std::make_shared<LayerCreator<MathLayer>>("Softplus"), std::make_shared<LayerCreator<MathLayer>>("Softsign"), std::make_shared<LayerCreator<MathLayer>>("Tan"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceAnd"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceL1"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceL2"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceLogSum"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceLogSumExp"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceMax"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceMean"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceMin"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceOr"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceProd"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceSum"), std::make_shared<LayerCreator<ReduceLayer>>("ReduceSumSquare"), std::make_shared<LayerCreator<CNNLayer>>("GatherTree"), std::make_shared<LayerCreator<TopKLayer>>("TopK"), std::make_shared<LayerCreator<UniqueLayer>>("Unique"), std::make_shared<LayerCreator<NonMaxSuppressionLayer>>("NonMaxSuppression"), std::make_shared<LayerCreator<ScatterUpdateLayer>>("ScatterUpdate"), std::make_shared<LayerCreator<ScatterElementsUpdateLayer>>("ScatterElementsUpdate"), std::make_shared<LayerCreator<ExperimentalDetectronPriorGridGeneratorLayer>>("ExperimentalDetectronPriorGridGenerator"), std::make_shared<LayerCreator<ExperimentalDetectronGenerateProposalsSingleImageLayer>>("ExperimentalDetectronGenerateProposalsSingleImage"), std::make_shared<LayerCreator<ExperimentalDetectronTopKROIs>>("ExperimentalDetectronTopKROIs")}; creators.emplace_back(_version < 6 ? std::make_shared<LayerCreator<QuantizeLayer>>("Quantize") : std::make_shared<LayerCreator<QuantizeLayer>>("FakeQuantize")); } CNNNetworkImplPtr FormatParser::Parse(pugi::xml_node& root) { _network.reset(new CNNNetworkImpl()); _network->setName(GetStrAttr(root, "name", "")); _defPrecision = Precision::FromStr(GetStrAttr(root, "precision", "UNSPECIFIED")); // parse the input Data DataPtr inputData; // parse the graph layers auto allLayersNode = root.child("layers"); std::vector<CNNLayer::Ptr> inputLayers; int nodeCnt = 0; std::map<int, CNNLayer::Ptr> layerById; FOREACH_CHILD(node, allLayersNode, "layer") { LayerParseParameters lprms; ParseGenericParams(node, lprms); CNNLayer::Ptr layer = CreateLayer(node, lprms); if (!layer) IE_THROW() << "Don't know how to create Layer type: " << lprms.prms.type; layersParseInfo[layer->name] = lprms; _network->addLayer(layer); layerById[lprms.layerId] = layer; if (equal(layer->type, "input")) { inputLayers.push_back(layer); } for (size_t i = 0; i < lprms.outputPorts.size(); i++) { const auto& outPort = lprms.outputPorts[i]; const auto outId = gen_id(lprms.layerId, outPort.portId); const std::string outName = lprms.outputPorts.size() == 1 ? lprms.prms.name : lprms.prms.name + "." + std::to_string(i); DataPtr& ptr = _network->getData(outName.c_str()); if (!ptr) { ptr.reset( new Data(outName, {outPort.precision, outPort.dims, TensorDesc::getLayoutByDims(outPort.dims)})); } _portsToData[outId] = ptr; if (getCreatorLayer(ptr).lock()) IE_THROW() << "two layers set to the same output [" << outName << "], conflict at offset " << node.offset_debug(); getCreatorLayer(ptr) = layer; layer->outData.push_back(ptr); } nodeCnt++; } // connect the edges pugi::xml_node edges = root.child("edges"); FOREACH_CHILD(_ec, edges, "edge") { int fromLayer = GetIntAttr(_ec, "from-layer"); int fromPort = GetIntAttr(_ec, "from-port"); int toLayer = GetIntAttr(_ec, "to-layer"); int toPort = GetIntAttr(_ec, "to-port"); const auto dataId = gen_id(fromLayer, fromPort); auto targetLayer = layerById[toLayer]; if (!targetLayer) IE_THROW() << "Layer ID " << toLayer << " was not found while connecting edge at offset " << _ec.offset_debug(); SetLayerInput(*_network, dataId, targetLayer, toPort); } auto keep_input_info = [&](DataPtr& in_data) { InputInfo::Ptr info(new InputInfo()); info->setInputData(in_data); Precision prc = info->getPrecision(); // Convert precision into native format (keep element size) prc = prc == Precision::Q78 ? Precision::I16 : prc == Precision::FP16 ? Precision::FP32 : static_cast<Precision::ePrecision>(prc); info->setPrecision(prc); _network->setInputInfo(info); }; // Keep all data from InputLayers for (auto inLayer : inputLayers) { if (inLayer->outData.size() != 1) IE_THROW() << "Input layer must have 1 output. " "See documentation for details."; keep_input_info(inLayer->outData[0]); } // Keep all data which has no creator layer for (auto& kvp : _network->allLayers()) { const CNNLayer::Ptr& layer = kvp.second; auto pars_info = layersParseInfo[layer->name]; if (layer->insData.empty()) layer->insData.resize(pars_info.inputPorts.size()); for (size_t i = 0; i < layer->insData.size(); i++) { if (!layer->insData[i].lock()) { std::string data_name = (layer->insData.size() == 1) ? layer->name : layer->name + "." + std::to_string(i); DataPtr data(new Data(data_name, {pars_info.inputPorts[i].precision, pars_info.inputPorts[i].dims, TensorDesc::getLayoutByDims(pars_info.inputPorts[i].dims)})); layer->insData[i] = data; getInputTo(data)[layer->name] = layer; const auto insId = gen_id(pars_info.layerId, pars_info.inputPorts[i].portId); _portsToData[insId] = data; keep_input_info(data); } } /* * TODO: WA. IR v6 has no precision specification for input data ports. * So they have default values (generally FP32), which doesn't consists * with TI port precision. Remove this line after switching onto IR v7 * and v10. */ if (layer->type == "TensorIterator") { auto ti = dynamic_cast<TensorIterator*>(layer.get()); if (!ti) IE_THROW() << "Failed to cast to 'TensorIterator'"; for (auto &in_map_rule : ti->input_port_map) { auto exter_data = ti->insData[in_map_rule.from].lock(); auto inter_data = ti->body.inputs[in_map_rule.to]; auto ti_specified_precision = exter_data->getPrecision(); inter_data->setPrecision(ti_specified_precision); } } } if (!_network->allLayers().size()) IE_THROW() << "Incorrect model! Network doesn't contain layers."; size_t inputLayersNum(0); CaselessEq<std::string> cmp; for (const auto& kvp : _network->allLayers()) { const CNNLayer::Ptr& layer = kvp.second; if (cmp(layer->type, "Input") || cmp(layer->type, "Const")) inputLayersNum++; } if (!inputLayersNum && !cmp(root.name(), "body")) IE_THROW() << "Incorrect model! Network doesn't contain input layers."; // check all input ports are occupied for (const auto& kvp : _network->allLayers()) { const CNNLayer::Ptr& layer = kvp.second; const LayerParseParameters& parseInfo = layersParseInfo[layer->name]; size_t inSize = layer->insData.size(); if (inSize != parseInfo.inputPorts.size()) IE_THROW() << "Layer " << layer->name << " does not have any edge connected to it"; for (unsigned i = 0; i < inSize; i++) { if (!layer->insData[i].lock()) { IE_THROW() << "Layer " << layer->name.c_str() << " input port " << parseInfo.inputPorts[i].portId << " is not connected to any data"; } } layer->parseParams(); details::validateLayer(layer.get()); } // parse mean image ParsePreProcess(root); _network->resolveOutput(); // Set default output precision to FP32 (for back-compatibility) OutputsDataMap outputsInfo; _network->getOutputsInfo(outputsInfo); for (auto outputInfo : outputsInfo) { if (outputInfo.second->getPrecision() == Precision::I64) { outputInfo.second->setPrecision(Precision::I32); } else if (outputInfo.second->getPrecision() != Precision::FP32 && outputInfo.second->getPrecision() != Precision::I32) { outputInfo.second->setPrecision(Precision::FP32); } } return _network; } template <typename BlobType> inline Blob::Ptr GetTypedBlobFromSegment(const TBlob<uint8_t>::Ptr& weights, const WeightSegment& segment) { if (segment.getEnd() > weights->size()) IE_THROW() << "segment size(" << segment.getEnd() << ") exceeds given buffer limits(" << weights->size() <<"). Please, validate weights file"; size_t noOfElement = segment.size / sizeof(BlobType); // RanC: TODO: IR does not provide me with weight slayout. // So far I knew it since I know what layer it is. In generic layers I don't // so until the IR will have the layout and sizes I will pass it as vector and the plugin will have to // validate and undertand what he should get... SizeVector w_dims({noOfElement}); typename TBlobProxy<BlobType>::Ptr binBlob( new TBlobProxy<BlobType>(segment.precision, Layout::C, weights, segment.start, w_dims)); /* this validation is not reduntant I have no prior knowledge of the weights anymore... if (pbpWeights->byteSize() != lprms.weights.size) IE_THROW() << "bytes size weights for " << pWL->name << " mismatch, expecting " << pbpWeights->byteSize() << " bytes which are " << pbpWeights->size() << " elements"; */ return binBlob; } Blob::Ptr FormatParser::GetBlobFromSegment(const TBlob<uint8_t>::Ptr& weights, const WeightSegment& segment) const { if (segment.precision == Precision::FP32) { return GetTypedBlobFromSegment<float>(weights, segment); } else if (segment.precision == Precision::I64) { return GetTypedBlobFromSegment<int64_t>(weights, segment); } else if (segment.precision == Precision::I32) { return GetTypedBlobFromSegment<int32_t>(weights, segment); } else if (segment.precision == Precision::I16 || segment.precision == Precision::Q78 || segment.precision == Precision::FP16) { return GetTypedBlobFromSegment<short>(weights, segment); } else if (segment.precision == Precision::U8 || segment.precision == Precision::BOOL) { return GetTypedBlobFromSegment<uint8_t>(weights, segment); } else if (segment.precision == Precision::I8 || segment.precision == Precision::BIN) { return GetTypedBlobFromSegment<int8_t>(weights, segment); } else { IE_THROW() << "precision " << segment.precision << " is not supported..."; } } void FormatParser::SetWeights(const TBlob<uint8_t>::Ptr& weights) { if (weights == nullptr) return; for (auto& kvp : _network->allLayers()) { auto fit = layersParseInfo.find(kvp.second->name); // todo: may check that earlier - while parsing... if (fit == layersParseInfo.end()) IE_THROW() << "Internal Error: ParseInfo for " << kvp.second->name << " are missing..."; auto& lprms = fit->second; WeightableLayer* pWL = dynamic_cast<WeightableLayer*>(kvp.second.get()); if (pWL != nullptr) { if (lprms.blobs.find("weights") != lprms.blobs.end()) { if (lprms.prms.type == "BinaryConvolution") { auto segment = lprms.blobs["weights"]; if (segment.getEnd() > weights->size()) IE_THROW() << "segment exceeds given buffer limits. Please, validate weights file"; size_t noOfElement = segment.size; SizeVector w_dims({noOfElement}); typename TBlobProxy<uint8_t>::Ptr binBlob( new TBlobProxy<uint8_t>(Precision::BIN, Layout::C, weights, segment.start, w_dims)); pWL->_weights = binBlob; } else { pWL->_weights = GetBlobFromSegment(weights, lprms.blobs["weights"]); } pWL->blobs["weights"] = pWL->_weights; } if (lprms.blobs.find("biases") != lprms.blobs.end()) { pWL->_biases = GetBlobFromSegment(weights, lprms.blobs["biases"]); pWL->blobs["biases"] = pWL->_biases; } } auto pGL = kvp.second.get(); if (pGL == nullptr) continue; for (auto s : lprms.blobs) { pGL->blobs[s.first] = GetBlobFromSegment(weights, s.second); if (pGL->type == "Const") { auto shapes = pGL->outData[0]->getTensorDesc().getDims(); pGL->blobs[s.first]->getTensorDesc().reshape(shapes, TensorDesc::getLayoutByDims(shapes)); } } // Some layer can specify additional action to prepare weights if (fit->second.internalWeightSet) fit->second.internalWeightSet(weights); } for (auto& kvp : _preProcessSegments) { const std::string& inputName = kvp.first; auto& segments = kvp.second; auto inputInfo = _network->getInput(inputName); if (!inputInfo) IE_THROW() << "Internal error: missing input name " << inputName; auto dims = inputInfo->getTensorDesc().getDims(); size_t width = 0ul, height = 0ul; if (dims.size() == 3) { height = dims.at(1); width = dims.at(2); } else if (dims.size() == 4) { height = dims.at(2); width = dims.at(3); } else if (dims.size() == 5) { height = dims.at(3); width = dims.at(4); } else { IE_THROW() << inputName << " has unsupported layout " << inputInfo->getTensorDesc().getLayout(); } PreProcessInfo& pp = inputInfo->getPreProcess(); for (size_t c = 0; c < segments.size(); c++) { if (segments[c].size == 0) continue; Blob::Ptr blob = GetBlobFromSegment(weights, segments[c]); blob->getTensorDesc().reshape({height, width}, Layout::HW); // to fit input image sizes (summing it is an image) pp.setMeanImageForChannel(blob, c); } } } void FormatParser::ParseDims(SizeVector& dims, const pugi::xml_node& parentNode) const { FOREACH_CHILD(node, parentNode, "dim") { unsigned int dim = 0; const pugi::char_t* dimVal = node.child_value(); stringstream ss(dimVal); if (!(ss >> dim) || dim == 0) { IE_THROW() << "dimension (" << dimVal << ") in node " << node.name() << " must be a positive integer: at offset " << node.offset_debug(); } dims.push_back(dim); } } const DataPtr& FormatParser::GetDataBy(int layer_id, int port_id) const { const auto id = gen_id(layer_id, port_id); const auto& found = _portsToData.find(id); if (found == _portsToData.end()) IE_THROW() << "No data found for layer_id=" << layer_id << " port_id=" << port_id; return found->second; } void FormatParser::ParsePreProcess(pugi::xml_node& root) { /* <pre-process mean-precision="FP32"> <channel id = ”0”> <mean value = ”104” / > // in case of constant // or <mean offset = "121930449" size = "51529" / > // in case of array – ref to the .bin file <scale value = "1.2"> </channel> </pre-process> */ auto ppNode = root.child("pre-process"); if (ppNode.empty()) { return; } // find out to what input this belongs to std::string inputName; InputInfo::Ptr preProcessInput; inputName = GetStrAttr(ppNode, "reference-layer-name", ""); inputName = trim(inputName); if (inputName.empty()) { // fallback (old format), look for the picture in the inputs InputsDataMap inputs; _network->getInputsInfo(inputs); if (inputs.empty()) IE_THROW() << "network has no input"; for (auto i : inputs) { if (i.second->getTensorDesc().getDims().size() == 4) { preProcessInput = i.second; break; } } if (!preProcessInput) { preProcessInput = inputs.begin()->second; } inputName = preProcessInput->name(); } else { preProcessInput = _network->getInput(inputName); if (!preProcessInput) IE_THROW() << "pre-process name ref '" << inputName << "' refers to un-existing input"; } // dims vector without batch size SizeVector inputDims = preProcessInput->getTensorDesc().getDims(); size_t noOfChannels = 0, width = 0, height = 0; if (inputDims.size() < 2) { IE_THROW() << "network did not define input dimensions properly"; } else if (inputDims.size() == 2) { // NC noOfChannels = inputDims[1]; width = inputDims[1]; height = inputDims[0]; } else if (inputDims.size() == 3) { width = inputDims[2]; height = inputDims[1]; noOfChannels = inputDims[0]; } else if (inputDims.size() == 4) { width = inputDims[3]; height = inputDims[2]; noOfChannels = inputDims[1]; } else if (inputDims.size() == 5) { width = inputDims[4]; height = inputDims[3]; noOfChannels = inputDims[2]; } PreProcessInfo& pp = preProcessInput->getPreProcess(); std::vector<WeightSegment>& segments = _preProcessSegments[inputName]; pp.init(noOfChannels); segments.resize(noOfChannels); auto meanSegmentPrecision = GetPrecisionAttr(ppNode, "mean-precision", Precision::UNSPECIFIED); InferenceEngine::PreProcessChannel::Ptr preProcessChannel; int lastChanNo = -1; std::unordered_set<int> idsForMeanValue; std::unordered_set<int> idsForMeanImage; FOREACH_CHILD(chan, ppNode, "channel") { int chanNo = GetIntAttr(chan, "id", lastChanNo + 1); if (chanNo >= static_cast<int>(noOfChannels) || chanNo < 0) { IE_THROW() << "Pre-process channel id invalid: " << chanNo; } lastChanNo = chanNo; preProcessChannel = pp[chanNo]; WeightSegment& preProcessSegment = segments[chanNo]; auto meanNode = chan.child("mean"); if (!meanNode.empty()) { if (!meanNode.attribute("value") && (!meanNode.attribute("size"))) { IE_THROW() << "mean should have at least one of the following attribute: value, size"; } if (meanNode.attribute("value")) { preProcessChannel->meanValue = GetFloatAttr(meanNode, "value"); idsForMeanValue.insert(chanNo); } if (meanNode.attribute("size")) { idsForMeanImage.insert(chanNo); preProcessSegment.size = static_cast<size_t>(GetIntAttr(meanNode, "size")); preProcessSegment.start = static_cast<size_t>(GetIntAttr(meanNode, "offset")); preProcessSegment.precision = meanSegmentPrecision; if (width * height * meanSegmentPrecision.size() != preProcessSegment.size) { IE_THROW() << "mean blob size mismatch expected input, got: " << preProcessSegment.size << " extpecting " << width << " x " << height << " x " << meanSegmentPrecision.size(); } if (!meanSegmentPrecision || meanSegmentPrecision == Precision::MIXED) IE_THROW() << "mean blob defined without specifying precision."; } } auto scaleNode = chan.child("scale"); if (!scaleNode.empty() && scaleNode.attribute("value")) { preProcessChannel->stdScale = GetFloatAttr(scaleNode, "value"); } } if (idsForMeanImage.size() == noOfChannels) { pp.setVariant(MEAN_IMAGE); } else if (idsForMeanValue.size() == noOfChannels) { pp.setVariant(MEAN_VALUE); } else if ((idsForMeanImage.size() == 0) && (idsForMeanValue.size() == 0)) { pp.setVariant(NONE); } else { std::string validMeanValuesIds = ""; std::string validMeanImageIds = ""; for (auto id : idsForMeanValue) { validMeanValuesIds += std::to_string(id) + " "; } for (auto id : idsForMeanImage) { validMeanImageIds += std::to_string(id) + " "; } IE_THROW() << "mean is not provided for all channels\n" "Provided mean values for : " << validMeanValuesIds << "\n" "Provided mean image for: " << validMeanImageIds; } }
; A102785: G.f.: (x-1)/(-2*x^2 + 3*x^3 + 2*x - 1). ; Submitted by Jon Maiga ; 1,1,0,1,5,8,9,17,40,73,117,208,401,737,1296,2321,4261,7768,13977,25201,45752,83033,150165,271520,491809,891073,1613088,2919457,5285957,9572264,17330985,31375313,56805448 mov $1,3 lpb $0 sub $0,1 add $3,$1 add $1,$2 sub $3,1 sub $1,$3 mul $1,3 sub $1,$2 add $2,$3 lpe mov $0,$1 div $0,2
; A075871: Numbers n such that 13*n^2 + 1 is a square. ; 0,180,233640,303264540,393637139280,510940703520900,663200639532988920,860833919173116097260,1117361763886065161254560,1450334708690193406192321620,1882533334518107155172472208200,2443526817869794397220462733921980 mul $0,6 seq $0,52991 ; Expansion of (1-x-x^2)/(1-3x-x^2). div $0,4
; =============================================================== ; Jun 2007 ; =============================================================== ; ; uint zx_saddr2py(void *saddr) ; ; Pixel y coordinate corresponding to screen address. ; ; =============================================================== SECTION code_clib SECTION code_arch PUBLIC asm_zx_saddr2py asm_zx_saddr2py: ; enter : hl = screen address ; ; exit : hl = pixel y coordinate ; ; uses : af, hl ld a,l rra rra and $38 ld l,a ld a,h add a,a add a,a add a,a and $c0 or l ld l,a ld a,h and $07 or l ld l,a ld h,0 ret
.include "vc4.qinc" .func gvpm_wr_setup(stride, addr) # Ignored, Horizontal, Laned (ignored), 32-bit gvpm_setup(0, stride, 1, 0, 2, addr) .endf .func gvpm_rd_setup(num, stride, addr) # Horizontal, Laned (ignored), 32-bit gvpm_setup(num, stride, 1, 0, 2, addr) .endf .func gvpm_setup(num, stride, horiz, laned, size, addr) 0x00000000 | (num & 0xf) << 20 |(stride & 0x3f) << 12 | (horiz & 0x1) << 11 | (laned & 0x1) << 10 | (size & 0x3) << 8 | (addr & 0xff) # Table 32: VPM Generic Block Write Setup Format .endf .func dma_wr_setup(units, depth, laned, horiz, vpmbase, modew) 0x80000000 | (units & 0x7f) << 23 | (depth & 0x7f) << 16 | (laned & 0x1) << 15 | (horiz & 0x1) << 14 | (vpmbase & 0x7ff) << 3 | (modew & 0x7) # Table 34: VCD DMA Store (VDW) Basic Setup Format .endf .func dma_rd_setup(modew, mpitch, rowlen, nrows, vpitch, vert, addrxy) 0x80000000 | (modew & 0x7) << 28 | (mpitch & 0xf) << 24 | (rowlen & 0xf) << 20 | (nrows & 0xf) << 16 | (vpitch & 0xf) << 12 | (vert & 0x1) << 11 | (addrxy & 0x7ff) # Table 36: VCD DMA Load (VDR) Basic Setup Format .endf mov r1, unif mov r3, unif # Configure the VPM for writing ldi vw_setup, gvpm_wr_setup(1, 0) # Increase addr by 1, start from 0 # Write a full block of VPM memory .rep i, 64 nop nop nop mov vpm, 0xffffffff # ((i+1) * 16) .endr # Load whole block of memory into VPM with DMA .rep i, 4 ldi vr_setup, dma_rd_setup(0, 3, 16, 16, 1, 0, 0x100 * i) # 64 times 16 words, horizontal mov vr_addr, r3 # initiate the DMA read vr_wait # Wait for the DMA to complete ldi r1, 0x400 add r3, r3, r1 .endr #.ifset NO # Read one vector ldi vr_setup, gvpm_rd_setup(1, 1, 0) nop nop nop mov r2, vpm add r2, r2, r2 ldi r0, 0xee000000 sub r2, r2, r0 sub r2, r2, r0 ldi r0, 0xc0 sub.setf -, r2, r0 mov r2, 1 mov.ifc r2, 0 #mov.ifnz r0, r2 #mov r0.z, r2 #mov r2, r0 #mov r0, 0 #mov r2, 0 # # #mov.ifz r2, r2 #nop #nop #nop # Write one vector back ldi vw_setup, gvpm_wr_setup(1, 0) nop nop nop mov vpm, r2 #.endif ## move 16 words (1 vector) back to the host (DMA) # ldi vw_setup, vdw_setup_0(1, 16, dma_h32(0, 0)) ldi vw_setup, dma_wr_setup(64, 16, 0, 1, 0, 0) # 64 times 16 words, horizontal ## initiate the DMA (the next uniform - ra32 - is the host address to write to)) mov vw_addr, unif # Wait for the DMA to complete read vw_wait # trigger a host interrupt (writing rb38) to stop the program mov.setf irq, nop; read rb0 nop; thrend nop nop
C x86_64/fat/aes-encrypt-internal.asm ifelse(< Copyright (C) 2015 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * 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. or * 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. or both in parallel, as here. GNU Nettle 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 copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. >) define(<fat_transform>, <$1_x86_64>) include_src(<x86_64/aes-encrypt-internal.asm>)
; This file contains the Global Descriptor Table that will tell ; - the CPU about the available memory segments. ; I don't see the point of having both userland and kernel code and data segments. ; - When in our kernel we really don't have the paradigm of a kernel vs. a user. [bits 16] ; Tell our assembler to use 16-bits. gdt_start: ; The start of the GDT. gdt_null: dd 0x0 dd 0x0 ;; Kernel Code Segment gdt_kernel_code: dw 0xFFFF dw 0x0 db 0x0 db 10011010b db 11001111b db 0x0 ;; Kernel Data Segment gdt_kernel_data: dw 0xFFFF dw 0x0 db 0x0 db 10010010b db 11001111b db 0x0 ;; Userland Code Segment gdt_userland_code: dw 0xFFFF dw 0x0 db 0x0 db 11111010b db 11001111b db 0x0 ;; Userland Data Segment gdt_userland_data: dw 0xFFFF dw 0x0 db 0x0 db 11110010b db 11001111b db 0x0 gdt_end: ; The ending of the GDT. gdt_pointer: ; Create the pointer structure to our GDT. dw gdt_end - gdt_start - 1 ; This is for our entire GDT which is 16-bits. dd gdt_start ; This is for the start of our GDT which is 32-bits. CODE_SEG equ gdt_kernel_code - gdt_start ; Set an offset into our GDT for the code segment. DATA_SEG equ gdt_kernel_data - gdt_start ; Set an offset into our GDT for the data segment.
; ============================================= ; Модуль обслуживания клавиатуры в ROM1 ; ============================================= ; --------------------------------------------- ;Статус клавиатуры ; --------------------------------------------- STTS IN A,(0x0) AND 0x4 JR Z,STTS1 XOR A OUT (PORT_18_KBD),A IN A,(PORT_19_KBD) XOR 0xff RET Z LD A,0xff RET STTS1 XOR A OUT (PORT_1A_KBD),A OUT (PORT_19_KBD),A IN A,(PORT_18_KBD) INC A RET Z LD A,0xff OUT (PORT_1A_KBD),A LD A,0xfc OUT (PORT_19_KBD),A NOP IN A,(PORT_18_KBD) AND 0xe3 CP 0xe3 JR NZ,LAB_ram_1051 LD A,0x3 OUT (PORT_19_KBD),A NOP IN A,(PORT_18_KBD) INC A JR NZ,LAB_ram_1051 OUT (PORT_1A_KBD),A NOP IN A,(PORT_18_KBD) INC A RET Z LAB_ram_1051 LD A,0xff RET ; --------------------------------------------- ; Процедура опроса клавиатуры с миганием курсором ; Вход: ; C - режим курсора, старший бит - признак того, что курсор отображается ; DE - счетчик задержки мигания ; Выход: ; A, "CY" - результат INKEY ; --------------------------------------------- CURINK CALL INKEY BIT 0x5,C RET Z BIT 0x4,C RET Z DEC DE INC E DEC E RET NZ INC D DEC D RET NZ LD DE,(CURTM) BIT 0x7,C JR Z,CURON CUROFF RES 0x7,C PUSH BC PUSH DE PUSH HL PUSH AF LD A,0x6 ; Получить позицию курсора CALL TVOUT LD A,0x3 ; Погасить графический курсор в заданн... CO1 CALL TVOUT POP AF POP HL POP DE POP BC RET CURON SET 0x7,C PUSH BC PUSH DE PUSH HL PUSH AF LD A,0x6 CALL TVOUT LD A,0x2 JR CO1 ; --------------------------------------------- ; Определение кодировки клавиатуры ; "CY","NZ" - ALT, koi-8 ; "NC","Z" - koi-7 n2 ; "NC","NZ" - koi-7 n1,0 ; --------------------------------------------- IS_KOI7 LD A,(KBMODE) AND 0x3 CP 0x2 RET ; --------------------------------------------- ; Определение старого режима клавиатуры ; "NZ" - rk-86 или старый режим ms7007 ; "Z" - новый режим ms7007 ; --------------------------------------------- IS_OLD IN A,(0x0) AND 0x4 RET NZ LD A,(KBMODE) BIT 0x7,A RET ; --------------------------------------------- ; Ввод символа с клавиатуры ; Выход: ; A - Код нажатой клавиши ; Для формироввания звука "rus/lat" используется процедура ; "SOUND" монитора. она может быть заменена на другую. ; На ее вход подпрограмма "KBRD" подает признак RUS/LAT в регистре A (A=0 - lat, A<>0 - rus). ; В стандартной процедуре SOUND этот признак не используется, параметры звука задаются в регистрах BC, DE. ; Особенности: обеспечивается обработка буфера KBRD. ; --------------------------------------------- KBRD PUSH BC PUSH DE PUSH HL DB 3EH ;LD A,... KBRD1 POP AF CALL RDBUF LD A,C JR NC,KBRD3 CALL KBD PUSH AF CALL GETKBM CP 0x3 JR NC,KBRD2 LD B,(HL) LD A,D AND 0x3 CP 0x3 JR Z,KBRD2 LD E,A ADD A,A ADD A,E LD E,A LD D,0x0 LD HL,FUNTAB ADD HL,DE LD A,C CP 0x4 JR Z,KBRD01 CP 0x0A ; упр? JR NZ,KBRD02 KBRD01 LD A,B KBRD02 CALL FUNKEY JR NC,KBRD1 KBRD2 POP AF KBRD3 POP HL POP DE POP BC RET ; --------------------------------------------- ; Обработка функциональных клавиш ; Вход: ; HL - адрес таблицы ФК ; A - код сканирования ; Выход: ; "CY" - нет в таблице, иначе строка -> в буфер KBRD ; --------------------------------------------- FUNKEY LD C,PORT_0A_MEM_CFG IN B,(C) PUSH BC SET SHIFT,B OUT (C),B SRL C IN B,(C) PUSH BC LD E,(HL) INC HL LD D,(HL) INC HL OUTI EX DE,HL RES 0x7,H SET 0x6,H PUSH HL CALL SRCKEY POP HL CALL NC,STRADR ; HL- адрес строки CALL NC,BUFSTR POP BC OUT (C),B POP BC OUT (C),B RET ; --------------------------------------------- ; Поиск функциональной клавиши в таблице ; Вход: ; A - код сканирования ; HL - адрес начала таблицы ; Выход: ; B = 0, ; "CY" - не найден, иначе A - порядковый номер в таблице ; --------------------------------------------- SRCKEY LD B,0x0 LD C,(HL) SCF INC C DEC C RET Z INC HL PUSH BC CPIR LD A,C POP BC SCF RET NZ SUB C CPL OR A RET ; --------------------------------------------- ; Определение адреса строки в таблице ; Вход: ; A - порядковый номер клавиши ; HL - адрес начала таблицы ; B = 0 ; Выход: ; HL - адрес начала строки ; "NC"- всегда ; --------------------------------------------- STRADR LD C,(HL) INC HL ADD HL,BC INC A SA1 DEC A OR A RET Z LD C,(HL) INC HL ADD HL,BC JR SA1 ; --------------------------------------------- ; Запись строки в буфер клавиатуры ; Вход: ; HL - адрес начала строки ; Выход: ; "CY" - строка пуста, иначе строка заносится в буфер ; --------------------------------------------- BUFSTR LD B,(HL) SCF INC B DEC B RET Z BS1 INC HL LD C,(HL) CALL WRBUF JR C,BS2 DJNZ BS1 BS2 OR A RET ; --------------------------------------------- ; Процедура KBRD без поддержки буфера ; --------------------------------------------- KBD LD A,NCURMR CALL TVOUT RES 0x7,C BIT ENACUR,C CALL NZ,CURON LD DE,(CURTM) JR KBD3 KBD0 POP AF LD HL,(KBAUTO) JR KBD21 KBD1 POP AF KBD2 LD HL,1 KBD21 LD (STAUTO),HL KBD3 CALL CURINK LD B,A JR NC,KBD32 PUSH BC CALL KBD8 POP BC JR KBD2 KBD32 CALL KBD20 JR NC,KBD2 LD HL,(STAUTO) PUSH HL KBD4 XOR A KBD5 DEC A JR NZ,KBD5 CALL CURINK JR C,KBD1 CP B JR NZ,KBD0 DEC HL LD A,H OR L JR NZ,KBD4 POP HL DEC HL LD A,H OR L LD HL,(KBAUTO) JR Z,KBD6 LD HL,0x2 KBD6 LD (STAUTO),HL BIT 0x7,C CALL NZ,CUROFF LD A,B LD (KBSYM),A LD DE,(KBMODE) PUSH AF CALL KBSND ; Звук клавиатуры POP AF RET ; --------------------------------------------- ; Обработка спецклавиш ; Вход: ; B - выходное значение INKEY ; --------------------------------------------- KBD8 LD HL,KBFLAG LD C,(HL) CALL IS_OLD LD A,B JR Z,KBD18 CP 0xfe JR NZ,KBD11 KBD9 CALL IS_KOI7 JR Z,KBD13 JR NC,KBD19 BIT GRFALF,(HL) JR NZ,KBD10 KBD13 LD A,(HL) XOR ruslat LD (HL),A KBD10F PUSH BC PUSH DE PUSH HL LD A,C LD DE,(KBMODE) CALL KBSIG POP HL POP DE POP BC KBD10 CALL INKEY JR NC,KBD10 INC A JR NZ,KBD10 LD A,(HL) AND 0x1f JR NZ,KBD10 RET KBD11 CP 0xf JR NZ,KBD14 KBD12 RES GRFALF,(HL) JR KBD10F KBD14 CP 0xe JR NZ,KBD16 KBD15 CALL IS_KOI7 JR NC,KBD10 SET GRFALF,(HL) JR KBD10F KBD16 BIT SHIFT,(HL) RET Z BIT CTRL,(HL) RET Z KBD17 CALL IS_KOI7 JR Z,KBD13 KBD19 LD A,(HL) XOR bolmal LD (HL),A JR KBD10F KBD18 BIT FIX,(HL) RET Z BIT SHIFT,(HL) JR NZ,KBD17 BIT ALF,(HL) JR NZ,KBD9 BIT GRF,(HL) RET Z CALL IS_KOI7 JR NC,KBD10 LD A,(HL) XOR grfalf LD (HL),A JR KBD10F ; --------------------------------------------- ; Обработка ^O,^N rk86 и ms7007(OLD MODE) ; Вход: ; (B) - код на выходе INKEY ; "CY" - ^O,^N не нажаты ; --------------------------------------------- KBD20 CALL IS_OLD SCF RET Z CALL IS_KOI7 CCF RET C LD HL,OLDGRF LD A,(HL) DEC HL CP (HL) JR NZ,KBD22 CP B SCF RET NZ LD HL,KBFLAG BIT GRFALF,(HL) JR Z,KBD15 JR KBD12 KBD22 LD A,(HL) CP B INC HL LD A,(HL) LD HL,KBFLAG JR Z,KBD12 CP B JR Z,KBD15 SCF RET ; ============================================= ; INKEY ; ============================================= ; --------------------------------------------- ; INKEY с обработкой спецклавиш ; "NC", A - код клавиши ; "CY", A - не нажата или спецклавиша ; --------------------------------------------- INKEY2 IN A,(PORT_00_DIPSW) AND 4 ; Тип клавиатуры JR Z,INK23 ; Полный опрос матрицы РК86 XOR A OUT (PORT_18_KBD),A IN A,(PORT_19_KBD) OR A JR NZ,INK24 IN A,(PORT_1A_KBD) OR 0x1f INC A JR NZ,INK24 INK22 OR 0xff SCF RET ; Полный опрос матрицы МС7007 INK23 XOR A OUT (PORT_19_KBD),A OUT (PORT_1A_KBD),A IN A,(PORT_18_KBD) INC A JR Z,INK22 INK24 CALL INKEY PUSH HL PUSH BC PUSH DE LD B,A JR NC,INK26 CALL KBD8 INK25 OR 0xff SCF JP INK8 INK26 CALL KBD20 JR NC,INK25 LD A,B OR A JP INK8 ; --------------------------------------------- ; Опрос нажатой клавиши (старый вариант, базовая) ; Выход: ; если "NC": клавиша нажата A - код клавиши (кроме CTRL,SHIFT,FIX,ALF,GRF) ; если "CY": ; A = 0FFH - клавиша не нажата ; A = 0FEH - нажата одна клавиша "ФИКС" (РУС/LAT) ; A = 0EH - нажата одна клавиша "ГРАФ" на МС7007 ; A = 0FH - нажата одна клавиша "АЛФ" на МС7007 ; --------------------------------------------- INKEY PUSH HL PUSH BC PUSH DE CALL NUMINK AND A JR Z,INK3 CP 0x4 JR NC,INK3 LD HL,KBFLAG LD D,A LD E,0x0 LD A,(HL) AND 0x1f JR Z,INK10 LD B,0x5 INK1 RRCA JR NC,INK2 INC E INK2 DJNZ INK1 LD A,D CP E JR NZ,INK9 DEC A JR NZ,INK3 BIT FIX,(HL) JR NZ,INK4 BIT GRF,(HL) JR NZ,INK5 BIT ALF,(HL) JR NZ,INK6 ; INK3 LD A,0xFF DB 0x21 INK4 LD A,0xFE DB 0x21 INK5 LD A,0x0E ; граф DB 0x21 INK6 LD A,0x0F ; АЛФ ; INK7 SCF ; INK8 POP DE POP BC POP HL RET INK9 LD A,C CP 0xd JR NC,INK92 LD A,D CP 0x2 JR NZ,INK3 LD A,C CP 0xa JR NC,INK91 CP 0x4 JR NZ,INK92 INK91 PUSH HL LD HL,(BAZA) INC HL LD C,(HL) POP HL INK92 BIT FIX,(HL) JR NZ,INK3 INK10 LD D,C LD A,C LD HL,CURTAB LD BC,0x0004 CPIR ;= JR NZ,INK11 LD A,0x3 SUB C LD C,A LD HL,CURCOD ADD HL,BC LD A,(KBFLAG) AND 0x3 ADD A,A ADD A,A LD C,A LD A,E CP 0x2 JR C,INK101 LD C,0x0 INK101 ADD HL,BC LD A,(HL) JR INK8 INK11 LD C,D LD HL,KBTAB LD DE,KBTAB+88 CALL IS_KOI7 LD A,(KBFLAG) JR C,INK12 EX DE,HL JR NZ,INK16 BIT ALF,A JR Z,INK01 XOR ruslat INK01 BIT RUSLAT,A ; CHECK RUSLAT+1? JR NZ,INK17 EX DE,HL JR INK17 INK12 BIT CTRL,A JR NZ,INK17 LD HL,KBTAB+88*4 LD DE,-(88*2) BIT GRF,A JR Z,INK13 XOR grfalf INK13 BIT GRFALF,A JR NZ,INK15 ADD HL,DE BIT ALF,A JR Z,INK14 XOR ruslat INK14 BIT RUSLAT,A JR NZ,INK15 ADD HL,DE INK15 EX DE,HL LD HL,88 ADD HL,DE INK16 BIT CPSLCK,A JR Z,INK17 EX DE,HL INK17 BIT SHIFT,A JR Z,INK18 EX DE,HL ADD HL,BC IN A,(PORT_00_DIPSW) AND KBD_TYPE JR NZ,INK19 INK171 LD A,C PUSH HL LD HL,SPECTB LD C,SPECTE-SPECTB ; BC - длина таблицы CPIR POP HL JR NZ,INK19 LD A,(HL) XOR 0x10 JR INC20 INK18 ADD HL,BC IN A,(CTRL) AND KBD_TYPE JR NZ,INK171 INK19 LD A,(HL) INC20 LD C,A CALL IS_KOI7 DEC A JR NZ,INK21 LD HL,ALTK8 LD A,C SUB 0x80 JR C,INK21 LD C,A ADD HL,BC LD C,(HL) ; --------------------------------------------- ; Обработка клавиши CTRL ; --------------------------------------------- INK21 LD HL,INK8 PUSH HL LD A,(KBFLAG) OR A BIT CTRL,A ; Нажата CTRL? LD A,C RET Z ; Не нажата CP ruslat CCF RET NC ; Не буква CP 0x7F RET NC ; Не буква AND 0x1F RET ;-- Таблица номеров клавиш курсора -- CURTAB DB 4Ch,35h,3Eh,3Dh ; LEFT, RIGHT, UP, DOWN ;-- Таблица перекодирования номеров клавиш по SHIFT SPECTB DB 19h,21h,29h,30h,39h,41h,48h,50h DB 57h,4Fh,47h,46h,10h,37h,54h,45h SPECTE ; конец таблицы ; Таблица перевода сканкодов МС7007 в коды клавиш ; используется 4 таблицы по 88 байт каждая: ; 1). для больших латинских букв; ; 2). для маленьких латинских букв; ; (или русские в верхнем КОИ-7); ; 3). для больших русских букв ALT-кодировки; ; 4). для маленьких русских букв; ; 5). для набора 1 псевдографики ALT-кодировки; ; 6). для набора 2 псевдографики ALT-кодировки; ; Примечание: коды клавиш курсора не учитываются ; KBTAB ; Большие латинские DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,4AH,46H,51H,00H,30H,2EH,2CH ;10-17 DB 00H,21H,43H,59H,5EH,31H,32H,33H ;18-1F DB 01H,22H,55H,57H,53H,37H,0CH,1FH ;20-27 DB 02H,23H,4BH,41H,4DH,7FH,1EH,0AH ;28-2F DB 24H,45H,50H,49H,20H,18H,0DH,3FH ;30-37 DB 03H,25H,4EH,52H,54H,1AH,19H,5FH ;38-3F DB 04H,26H,47H,4FH,58H,3EH,2AH,3DH ;40-47 DB 27H,5BH,4CH,42H,08H,5CH,48H,20H ;48-4F DB 28H,5DH,44H,40H,3CH,56H,5AH,29H ;50-57 ; ; Малые латинские (или русские для КОИ-7 n2) DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,6AH,66H,71H,00H,30H,2EH,2CH ;10-17 DB 00H,21H,63H,79H,7EH,31H,32H,33H ;18-1F DB 01H,22H,75H,77H,73H,37H,0CH,1FH ;20-27 DB 02H,23H,6BH,61H,6DH,7FH,1EH,0AH ;28-2F DB 24H,65H,70H,69H,20H,18H,0DH,3FH ;30-37 DB 03H,25H,6EH,72H,74H,1AH,19H,5FH ;38-3F DB 04H,26H,67H,6FH,78H,3EH,2AH,3DH ;40-47 DB 27H,7BH,6CH,62H,08H,7CH,68H,20H ;48-4F DB 28H,7DH,64H,60H,3CH,76H,7AH,29H ;50-57 ; ; Русские большие DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,89H,94H,9FH,00H,30H,2EH,2CH ;10-17 DB 00H,21H,96H,9BH,97H,31H,32H,33H ;18-1F DB 01H,22H,93H,82H,91H,37H,0CH,1FH ;20-27 DB 02H,23H,8AH,80H,8CH,7FH,1EH,0AH ;28-2F DB 24H,85H,8FH,88H,20H,18H,0DH,3FH ;30-37 DB 03H,25H,8DH,90H,92H,1AH,19H,9AH ;38-3F DB 04H,26H,83H,8EH,9CH,3EH,2AH,3DH ;40-47 DB 27H,98H,8BH,81H,08H,9DH,95H,20H ;48-4F DB 28H,99H,84H,9EH,3CH,86H,87H,29H ;50-57 ; ; Русские малые DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,0A9H,0E4H,0EFH,00H,30H,2EH,2CH ;10-17 DB 00H,21H,0E6H,0EBH,0E7H,31H,32H,33H ;18-1F DB 01H,22H,0E3H,0A2H,0E1H,37H,0CH,1FH ;20-27 DB 02H,23H,0AAH,0A0H,0ACH,7FH,1EH,0AH ;28-2F DB 24H,0A5H,0AFH,0A8H,20H,18H,0DH,3FH ;30-37 DB 03H,25H,0ADH,0E0H,0E2H,1AH,19H,0EAH ;38-3F DB 04H,26H,0A3H,0AEH,0ECH,3EH,2AH,3DH ;40-47 DB 27H,0E8H,0ABH,0A1H,08H,0EDH,0E5H,20H ;48-4F DB 28H,0E9H,0A4H,0EEH,3CH,0A6H,0A7H,29H ;50-57 ; ; Псевдографика 1 DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,0C9H,0CCH,0C8H,00H,30H,2EH,2CH ;10-17 DB 00H,21H,0CBH,0CEH,0CAH,31H,32H,33H ;18-1F DB 01H,22H,0BBH,0B9H,0BCH,37H,0CH,1FH ;20-27 DB 02H,23H,0D6H,0C7H,0D3H,7FH,1EH,0AH ;28-2F DB 24H,0D2H,0D7H,0D0H,20H,18H,0DH,3FH ;30-37 DB 03H,25H,0B7H,0B6H,0BDH,1AH,19H,0F0H ;38-3F DB 04H,26H,0B0H,0DDH,0B2H,3EH,2AH,3DH ;40-47 DB 27H,0DFH,0FEH,0DCH,08H,0BAH,0CDH,20H ;48-4F DB 28H,0B1H,0DEH,0DBH,3CH,0FDH,0FBH,29H ;50-57 ; ; Псевдографика 2 DB 39H,38H,00H,00H,00H,34H,35H,36H ;0-7 DB 1BH,09H,00H,0EH,0FH,2BH,2DH,0DH ;8-F DB 2BH,0DAH,0C3H,0C0H,00H,30H,2EH,2CH ;10-17 DB 00H,21H,0C2H,0C5H,0C1H,31H,32H,33H ;18-1F DB 01H,22H,0BFH,0B4H,0D9H,37H,0CH,1FH ;20-27 DB 02H,23H,0D5H,0C6H,0D4H,7FH,1EH,0AH ;28-2F DB 24H,0D1H,0D8H,0CFH,20H,18H,0DH,3FH ;30-37 DB 03H,25H,0B8H,0B5H,0BEH,1AH,19H,0F1H ;38-3F DB 04H,26H,0F5H,0F7H,0F2H,3EH,2AH,3DH ;40-47 DB 27H,0F8H,0FFH,0F9H,08H,0B3H,0C4H,20H ;48-4F DB 28H,0F4H,0F6H,0F3H,3CH,0FCH,0FAH,29H ;50-57 ; ; ; Таблица перекодировки ALT -> КОИ-8 ALTK8 DB 0E1H,0E2H,0F7H,0E7H,0E4H,0E5H,0F6H,0FAH ;А-З DB 0E9H,0EAH,0EBH,0ECH,0EDH,0EEH,0EFH,0F0H ;И-П DB 0F2H,0F3H,0F4H,0F5H,0E6H,0E8H,0E3H,0FEH ;Р-Ч DB 0FBH,0FDH,0FFH,0F9H,0F8H,0FCH,0E0H,0F1H ;Ш-Я DB 0C1H,0C2H,0D7H,0C7H,0C4H,0C5H,0D6H,0DAH ;а-з DB 0C9H,0CAH,0CBH,0CCH,0CDH,0CEH,0CFH,0D0H ;и-п DB 0B0H,0B1H,0B2H,0B3H,0B4H,0B5H,0B6H,0B7H ;графика DB 0B8H,0B9H,0BAH,0BBH,0BCH,0BDH,0BEH,0BFH DB 80H,81H,82H,83H,84H,85H,86H,87H DB 88H,89H,8AH,8BH,8CH,8DH,8EH,8FH DB 90H,91H,92H,93H,94H,95H,96H,97H DB 98H,99H,9AH,9BH,9CH,9DH,9EH,9FH DB 0D2H,0D3H,0D4H,0D5H,0C6H,0C8H,0C3H,0DEH ;р-ч DB 0DBH,0DDH,0DFH,0D9H,0D8H,0DCH,0C0H,0D1H ;ш-я DB 0A0H,0A1H,0A2H,0A3H,0A4H,0A5H,0A6H,0A7H ;спецсимволы DB 0A8H,0A9H,0AAH,0ABH,0ACH,0ADH,0AEH,0AFH ; --------------------------------------------- ; Опрос номеров нажатых клавиш ; Выход: ; A - число нажатых клавиш ; HL- адрес буфера с кодами клавиш ; C - номер последней (по таблице) нажатой клавиши ; если С=0FFh, то ни одна клавиша не нажата ; Особенности: данная пп формирует флаги клавиатуры CTRL, SHIFT, FIX в байте "KBFLAG" ; при нажатии соответствующей клавиши (для МС7007 - еще и флаги ALF, GRF). ; --------------------------------------------- NUMINK LD HL,KBFLAG LD A,0xe0 AND (HL) LD (HL),A XOR A LD HL,(BAZA) LD (HL),A INC HL EX DE,HL LD HL,POS1 IN A,(0x0) AND KBD_TYPE JR NZ,NUM11 LD C,0x0 NUM1 LD A,L OUT (PORT_19_KBD),A LD A,H OUT (PORT_1A_KBD),A IN A,(PORT_18_KBD) CP 0xff JR Z,NUM7 LD B,A LD A,(IKEYTM) NUM2 DEC A JR NZ,NUM2 IN A,(PORT_18_KBD) CP B JR NZ,NUM7 LD B,0x9 DEC C NUM3 INC C DEC B JR Z,NUM8 RRCA JR C,NUM3 EX DE,HL LD (HL),C INC HL OR 0x80 LD (HL),A EX DE,HL PUSH HL PUSH AF LD HL,KBFLAG LD A,C CP 0x4 JR NZ,NUM4 SET SHIFT,(HL) NUM4 CP 0xa JR NZ,NUM5 SET CTRL,(HL) NUM5 CP 0x14 JR NZ,NUM51 SET FIX,(HL) NUM51 CP 0xb JR NZ,NUM52 SET GRF,(HL) NUM52 CP 0xc JR NZ,NUM6 SET ALF,(HL) NUM6 LD HL,(BAZA) INC (HL) POP AF POP HL JR NUM3 NUM7 LD A,C ADD A,0x8 LD C,A NUM8 ; db 0CBh SLL L ; DEC (HL) RL H LD A,H CP 0xf7 ; Конец опроса? JR NZ,NUM1 NUM9 LD HL,(BAZA) EX DE,HL LD A,(DE) AND A LD C,0xff JR Z,NUM10 DEC HL LD C,(HL) NUM10 EX DE,HL INC HL RET NUM11 LD HL,0x97f LD C,0x0 IN A,(PORT_1A_KBD) OR 0x1f CP 0xff JR Z,NUM19 JR NUM14 NUM12 LD A,L OUT (PORT_18_KBD),A IN A,(PORT_19_KBD) CP 0xff JR Z,NUM19 LD B,A LD A,(IKEYTM) NUM13 DEC A JR NZ,NUM13 IN A,(PORT_19_KBD) CP B JR NZ,NUM19 NUM14 LD B,0x9 DEC C NUM15 INC C DEC B JR Z,NUM20 RRCA JR C,NUM15 EX DE,HL PUSH AF PUSH BC PUSH HL LD HL,KBFLAG LD A,C CP 0x5 JR NZ,NUM16 SET SHIFT,(HL) NUM16 CP 0x6 JR NZ,NUM17 SET CTRL,(HL) NUM17 CP 0x7 JR NZ,NUM18 ;РУС/LAT? SET FIX,(HL) NUM18 LD HL,(BAZA) INC (HL) LD HL,TBNUM-5 LD B,0x0 ADD HL,BC LD A,(HL) POP HL LD (HL),A POP BC POP AF INC HL OR 0x80 LD (HL),A EX DE,HL JR NUM15 NUM19 LD A,C ADD A,0x8 LD C,A NUM20 RLC L DEC H JR NZ,NUM12 JR NUM9 ; --------------------------------------------- ; Таблица перевода скан-кодов РК86 в скан-коды МС7007 ; Начало таблицы = TBNUM-05H ; --------------------------------------------- TBNUM DB 4,0AH,14H ; ss, us, rus/LAT DB 26H,27H,8,18H,20H,28H,38H,40H ; 0-7 DB 9,2FH,36H,2DH,4CH,3EH,35H,3DH ; 8-F DB 4FH,19H,21H,29H,30H,39H,41H,48H ; 10-17 DB 50H,57H,46H,10H,54H,47H,45H,37H ; 18-1F DB 53H,2BH,4BH,1AH,52H,31H,12H,42H ; 20-27 DB 4EH,33H,11H,2AH,4AH,2CH,3AH,43H ; 28-2F DB 32H,13H,3BH,24H,3CH,22H,55H,23H ; 30-37 DB 44H,1BH,56H,49H,4DH,51H,1CH,34H ; 38-3F ;
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cdn/model/SetIgnoreQueryStringConfigResult.h> #include <json/json.h> using namespace AlibabaCloud::Cdn; using namespace AlibabaCloud::Cdn::Model; SetIgnoreQueryStringConfigResult::SetIgnoreQueryStringConfigResult() : ServiceResult() {} SetIgnoreQueryStringConfigResult::SetIgnoreQueryStringConfigResult(const std::string &payload) : ServiceResult() { parse(payload); } SetIgnoreQueryStringConfigResult::~SetIgnoreQueryStringConfigResult() {} void SetIgnoreQueryStringConfigResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); }
; A178222: Partial sums of floor(3^n/4). ; 0,2,8,28,88,270,816,2456,7376,22138,66424,199284,597864,1793606,5380832,16142512,48427552,145282674,435848040,1307544140,3922632440,11767897342,35303692048,105911076168,317733228528,953199685610,2859599056856,8578797170596,25736391511816,77209174535478,231627523606464,694882570819424,2084647712458304,6253943137374946,18761829412124872,56285488236374652,168856464709123992,506569394127372014,1519708182382116080,4559124547146348280,13677373641439044880,41032120924317134682,123096362772951404088,369289088318854212308,1107867264956562636968,3323601794869687910950,9970805384609063732896,29912416153827191198736,89737248461481573596256,269211745384444720788818,807635236153334162366504,2422905708460002487099564,7268717125380007461298744,21806151376140022383896286,65418454128420067151688912,196255362385260201455066792,588766087155780604365200432,1766298261467341813095601354,5298894784402025439286804120,15896684353206076317860412420,47690053059618228953581237320,143070159178854686860743712022,429210477536564060582231136128,1287631432609692181746693408448,3862894297829076545240080225408,11588682893487229635720240676290,34766048680461688907160722028936,104298146041385066721482166086876,312894438124155200164446498260696,938683314372465600493339494782158,2816049943117396801480018484346544,8448149829352190404440055453039704,25344449488056571213320166359119184,76033348464169713639960499077357626,228100045392509140919881497232072952,684300136177527422759644491696218932 lpb $0 mov $2,$0 trn $0,2 seq $2,3462 ; a(n) = (3^n - 1)/2. add $1,$2 lpe mul $1,2 mov $0,$1
; Program values spc .BYT 32 ret .BYT 10 EOT .BYT 3 ; End of text LTUE .INT -42 ; Program strings facmsg1 .BYT 'F' .BYT 'a' .BYT 'c' .BYT 't' .BYT 'o' .BYT 'r' .BYT 'i' .BYT 'a' .BYT 'l' .BYT 32 .BYT 'o' .BYT 'f' .BYT 32 .BYT 3 facmsg2 .BYT 'i' .BYT 's' .BYT 32 .BYT 3 ; Other useful values ZERO .INT 0 I .INT 1 II .INT 2 III .INT 3 IV .INT 4 V .INT 5 VI .INT 6 VII .INT 7 VIII .INT 8 IX .INT 9 X .INT 10 JMP MAIN ; === print ========================================================= print MOV R1 FP ; Copy over the FP ADI R1 -36 ; Bypass the ret addr, PFP, and Registers LDR R2 (R1) ; Load in the value at the 3rd slot up in AR LDB R3 (R2) ; R2 = addr of argument ps_ LDB R0 EOT CMP R0 R3 BRZ R0 eps_ TRP 3 ADI R2 1 LDB R3 (R2) JMP ps_ ; === Begin return call eps_ MOV SP FP ; Test for underflow MOV R5 SP CMP R6 SB BGT R6 UNDERFLOW ; === Store Ret value LDR R7 ZERO ; Return value ; === Return to last location MOV R6 FP ; Return address pointed to by FP ADI R6 -4 LDR R6 (R6) JMR R6 ; === END print ===================================================== ;======== FUNCTION START factorial ================================== factorial MOV R5 SP CMP R5 SB BGT R5 UNDERFLOW ; Load the parameter MOV R1 FP ; Copy over the FP ADI R1 -36 ; Bypass the ret addr, PFP, and Registers LDR R2 (R1) ; Load in the value at the 3rd slot up in AR MOV R0 R2 ; LDR R0 (R2) ; R2 = addr of argument ; Factorial code BRZ R0 froot ; Call factorial again with R0 - 1 MOV R1 R0 ADI R1 -1 ; === Begin Function call MOV R7 SP ; Test for overflow ADI R7 -8 ; Adjust for Rtn address & PFP ADI R7 -24 ; Registers ADI R7 -4 ; Vars CMP R7 SL BLT R7 OVERFLOW ; === Store Ret and PFP MOV R7 FP ; Save FP in R1, this will be PFP MOV FP SP ; Point at current activation record ADI SP -4 ; Adjust SP for ret address MOV R6 PC ; PC incremented by 1 instruction ADI R6 240 ; Compute return address STR R6 (SP) ; Push return address ADI SP -4 ; Adjust for PFP STR R7 (SP) ; Push PFP to top of stack ; === Store registers ADI SP -4 ; R0 STR R0 (SP) ADI SP -4 ; R1 STR R1 (SP) ADI SP -4 ; R2 STR R2 (SP) ADI SP -4 ; R3 STR R3 (SP) ADI SP -4 ; R4 STR R4 (SP) ADI SP -4 ; R5 STR R5 (SP) ; === Store variables ADI SP -4 STR R1 (SP) ; === Function call JMP factorial ; === Restore the registers MOV R6 FP ADI R6 -12 LDR R0 (R6) ADI R6 -4 LDR R1 (R6) ADI R6 -4 LDR R2 (R6) ADI R6 -4 LDR R3 (R6) ADI R6 -4 LDR R4 (R6) ADI R6 -4 LDR R5 (R6) ; === Get return value MOV R6 FP ADI R6 -4 LDR R4 (R6) ; === Roll back SP and FP MOV SP FP ADI FP -8 LDR FP (FP) ; === End function call ; MOV R3 R0 ; TRP 1 JMP endfroot froot LDR R4 I LDR R0 I ; === Begin return call endfroot MOV SP FP ; Test for underflow MOV R5 SP CMP R6 SB BGT R6 UNDERFLOW ; === Store Ret value MUL R4 R0 ; Return value ; === Return to last location MOV R6 FP ; Return address pointed to by FP ADI R6 -4 MOV R7 R6 LDR R6 (R6) STR R4 (R7) ; Store return value JMR R6 ; === END print ===================================================== MAIN TRP 2 ; === Begin Function call MOV R7 SP ; Test for overflow ADI R7 -8 ; Adjust for Rtn address & PFP ADI R7 -24 ; Registers ADI R7 -4 ; Vars CMP R7 SL BLT R7 OVERFLOW ; === Store Ret and PFP MOV R7 FP ; Save FP in R1, this will be PFP MOV FP SP ; Point at current activation record ADI SP -4 ; Adjust SP for ret address MOV R6 PC ; PC incremented by 1 instruction ADI R6 240 ; Compute return address STR R6 (SP) ; Push return address ADI SP -4 ; Adjust for PFP STR R7 (SP) ; Push PFP to top of stack ; === Store registers ADI SP -4 ; R0 STR R0 (SP) ADI SP -4 ; R1 STR R1 (SP) ADI SP -4 ; R2 STR R2 (SP) ADI SP -4 ; R3 STR R3 (SP) ADI SP -4 ; R4 STR R4 (SP) ADI SP -4 ; R5 STR R5 (SP) ; === Store variables ADI SP -4 STR R3 (SP) ; === Function call JMP factorial ; === Restore the registers ; === Get return value MOV R6 FP ADI R6 -4 LDR R3 (R6) ; === Roll back SP and FP MOV SP FP ADI FP -8 LDR FP (FP) ; === End function call TRP 1 TRP 0 UNDERFLOW TRP 0 OVERFLOW TRP 0
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .text .p2align 5, 0x90 .p2align 5, 0x90 .globl _gf256_add _gf256_add: push %r12 push %r13 push %r14 xor %r14, %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 addq (%rdx), %r8 adcq (8)(%rdx), %r9 adcq (16)(%rdx), %r10 adcq (24)(%rdx), %r11 adc $(0), %r14 mov %r8, %rax mov %r9, %rdx mov %r10, %r12 mov %r11, %r13 subq (%rcx), %rax sbbq (8)(%rcx), %rdx sbbq (16)(%rcx), %r12 sbbq (24)(%rcx), %r13 sbb $(0), %r14 cmove %rax, %r8 cmove %rdx, %r9 cmove %r12, %r10 cmove %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax vzeroupper pop %r14 pop %r13 pop %r12 ret .p2align 5, 0x90 .globl _gf256_sub _gf256_sub: push %r12 push %r13 push %r14 xor %r14, %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 subq (%rdx), %r8 sbbq (8)(%rdx), %r9 sbbq (16)(%rdx), %r10 sbbq (24)(%rdx), %r11 sbb $(0), %r14 mov %r8, %rax mov %r9, %rdx mov %r10, %r12 mov %r11, %r13 addq (%rcx), %rax adcq (8)(%rcx), %rdx adcq (16)(%rcx), %r12 adcq (24)(%rcx), %r13 test %r14, %r14 cmovne %rax, %r8 cmovne %rdx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax vzeroupper pop %r14 pop %r13 pop %r12 ret .p2align 5, 0x90 .globl _gf256_neg _gf256_neg: push %r12 push %r13 push %r14 xor %r14, %r14 xor %r8, %r8 xor %r9, %r9 xor %r10, %r10 xor %r11, %r11 subq (%rsi), %r8 sbbq (8)(%rsi), %r9 sbbq (16)(%rsi), %r10 sbbq (24)(%rsi), %r11 sbb $(0), %r14 mov %r8, %rax mov %r9, %rcx mov %r10, %r12 mov %r11, %r13 addq (%rdx), %rax adcq (8)(%rdx), %rcx adcq (16)(%rdx), %r12 adcq (24)(%rdx), %r13 test %r14, %r14 cmovne %rax, %r8 cmovne %rcx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax vzeroupper pop %r14 pop %r13 pop %r12 ret .p2align 5, 0x90 .globl _gf256_div2 _gf256_div2: push %r12 push %r13 push %r14 movq (%rsi), %r8 movq (8)(%rsi), %r9 movq (16)(%rsi), %r10 movq (24)(%rsi), %r11 xor %r14, %r14 xor %rsi, %rsi mov %r8, %rax mov %r9, %rcx mov %r10, %r12 mov %r11, %r13 addq (%rdx), %rax adcq (8)(%rdx), %rcx adcq (16)(%rdx), %r12 adcq (24)(%rdx), %r13 adc $(0), %r14 test $(1), %r8 cmovne %rax, %r8 cmovne %rcx, %r9 cmovne %r12, %r10 cmovne %r13, %r11 cmovne %r14, %rsi shrd $(1), %r9, %r8 shrd $(1), %r10, %r9 shrd $(1), %r11, %r10 shrd $(1), %rsi, %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) mov %rdi, %rax vzeroupper pop %r14 pop %r13 pop %r12 ret .p2align 5, 0x90 .globl _gf256_mulm _gf256_mulm: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 sub $(24), %rsp movq %rdi, (%rsp) mov %rdx, %rbx mov %rcx, %rdi movq %r8, (8)(%rsp) movq (%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 mov %rax, %r8 mov %rdx, %r9 imul %r8, %r15 movq (8)(%rsi), %rax mul %r14 add %rax, %r9 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rsi), %rax mul %r14 add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rsi), %rax mul %r14 add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 xor %r13, %r13 movq (%rdi), %rax mul %r15 add %rax, %r8 adc $(0), %rdx mov %rdx, %r8 movq (8)(%rdi), %rax mul %r15 add %r8, %r9 adc $(0), %rdx add %rax, %r9 adc $(0), %rdx mov %rdx, %r8 movq (16)(%rdi), %rax mul %r15 add %r8, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r8 movq (24)(%rdi), %rax mul %r15 add %r8, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx add %rdx, %r12 adc $(0), %r13 xor %r8, %r8 movq (8)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r9 adc $(0), %rdx mov %rdx, %rcx imul %r9, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc %rdx, %r13 adc $(0), %r8 movq (%rdi), %rax mul %r15 add %rax, %r9 adc $(0), %rdx mov %rdx, %r9 movq (8)(%rdi), %rax mul %r15 add %r9, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r9 movq (16)(%rdi), %rax mul %r15 add %r9, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r9 movq (24)(%rdi), %rax mul %r15 add %r9, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx add %rdx, %r13 adc $(0), %r8 xor %r9, %r9 movq (16)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r10 adc $(0), %rdx mov %rdx, %rcx imul %r10, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc %rdx, %r8 adc $(0), %r9 movq (%rdi), %rax mul %r15 add %rax, %r10 adc $(0), %rdx mov %rdx, %r10 movq (8)(%rdi), %rax mul %r15 add %r10, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rdi), %rax mul %r15 add %r10, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r10 movq (24)(%rdi), %rax mul %r15 add %r10, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx add %rdx, %r8 adc $(0), %r9 xor %r10, %r10 movq (24)(%rbx), %r14 movq (8)(%rsp), %r15 movq (%rsi), %rax mul %r14 add %rax, %r11 adc $(0), %rdx mov %rdx, %rcx imul %r11, %r15 movq (8)(%rsi), %rax mul %r14 add %rcx, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %rcx movq (16)(%rsi), %rax mul %r14 add %rcx, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %rcx movq (24)(%rsi), %rax mul %r14 add %rcx, %r8 adc $(0), %rdx add %rax, %r8 adc %rdx, %r9 adc $(0), %r10 movq (%rdi), %rax mul %r15 add %rax, %r11 adc $(0), %rdx mov %rdx, %r11 movq (8)(%rdi), %rax mul %r15 add %r11, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r11 movq (16)(%rdi), %rax mul %r15 add %r11, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rdi), %rax mul %r15 add %r11, %r8 adc $(0), %rdx add %rax, %r8 adc $(0), %rdx add %rdx, %r9 adc $(0), %r10 xor %r11, %r11 movq (%rsp), %rsi mov %r12, %rax mov %r13, %rbx mov %r8, %rcx mov %r9, %rdx subq (%rdi), %rax sbbq (8)(%rdi), %rbx sbbq (16)(%rdi), %rcx sbbq (24)(%rdi), %rdx sbb $(0), %r10 cmovnc %rax, %r12 cmovnc %rbx, %r13 cmovnc %rcx, %r8 cmovnc %rdx, %r9 movq %r12, (%rsi) movq %r13, (8)(%rsi) movq %r8, (16)(%rsi) movq %r9, (24)(%rsi) mov %rsi, %rax add $(24), %rsp vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret .p2align 5, 0x90 .globl _gf256_sqrm _gf256_sqrm: push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 sub $(24), %rsp movq %rdi, (%rsp) mov %rdx, %rdi movq %rcx, (8)(%rsp) movq (%rsi), %rbx movq (8)(%rsi), %rax mul %rbx mov %rax, %r9 mov %rdx, %r10 movq (16)(%rsi), %rax mul %rbx add %rax, %r10 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %r12 movq (8)(%rsi), %rbx movq (16)(%rsi), %rax mul %rbx add %rax, %r11 adc $(0), %rdx mov %rdx, %rbp movq (24)(%rsi), %rax mul %rbx add %rax, %r12 adc $(0), %rdx add %rbp, %r12 adc $(0), %rdx mov %rdx, %r13 movq (16)(%rsi), %rbx movq (24)(%rsi), %rax mul %rbx add %rax, %r13 adc $(0), %rdx mov %rdx, %r14 xor %r15, %r15 shld $(1), %r14, %r15 shld $(1), %r13, %r14 shld $(1), %r12, %r13 shld $(1), %r11, %r12 shld $(1), %r10, %r11 shld $(1), %r9, %r10 shl $(1), %r9 movq (%rsi), %rax mul %rax mov %rax, %r8 add %rdx, %r9 adc $(0), %r10 movq (8)(%rsi), %rax mul %rax add %rax, %r10 adc %rdx, %r11 adc $(0), %r12 movq (16)(%rsi), %rax mul %rax add %rax, %r12 adc %rdx, %r13 adc $(0), %r14 movq (24)(%rsi), %rax mul %rax add %rax, %r14 adc %rdx, %r15 movq (8)(%rsp), %rcx imul %r8, %rcx movq (%rdi), %rax mul %rcx add %rax, %r8 adc $(0), %rdx mov %rdx, %r8 movq (8)(%rdi), %rax mul %rcx add %r8, %r9 adc $(0), %rdx add %rax, %r9 adc $(0), %rdx mov %rdx, %r8 movq (16)(%rdi), %rax mul %rcx add %r8, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r8 movq (24)(%rdi), %rax mul %rcx add %r8, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx add %rdx, %r12 adc $(0), %r13 xor %r8, %r8 movq (8)(%rsp), %rcx imul %r9, %rcx movq (%rdi), %rax mul %rcx add %rax, %r9 adc $(0), %rdx mov %rdx, %r9 movq (8)(%rdi), %rax mul %rcx add %r9, %r10 adc $(0), %rdx add %rax, %r10 adc $(0), %rdx mov %rdx, %r9 movq (16)(%rdi), %rax mul %rcx add %r9, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r9 movq (24)(%rdi), %rax mul %rcx add %r9, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx add %rdx, %r13 adc $(0), %r14 xor %r9, %r9 movq (8)(%rsp), %rcx imul %r10, %rcx movq (%rdi), %rax mul %rcx add %rax, %r10 adc $(0), %rdx mov %rdx, %r10 movq (8)(%rdi), %rax mul %rcx add %r10, %r11 adc $(0), %rdx add %rax, %r11 adc $(0), %rdx mov %rdx, %r10 movq (16)(%rdi), %rax mul %rcx add %r10, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r10 movq (24)(%rdi), %rax mul %rcx add %r10, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx add %rdx, %r14 adc $(0), %r15 xor %r10, %r10 movq (8)(%rsp), %rcx imul %r11, %rcx movq (%rdi), %rax mul %rcx add %rax, %r11 adc $(0), %rdx mov %rdx, %r11 movq (8)(%rdi), %rax mul %rcx add %r11, %r12 adc $(0), %rdx add %rax, %r12 adc $(0), %rdx mov %rdx, %r11 movq (16)(%rdi), %rax mul %rcx add %r11, %r13 adc $(0), %rdx add %rax, %r13 adc $(0), %rdx mov %rdx, %r11 movq (24)(%rdi), %rax mul %rcx add %r11, %r14 adc $(0), %rdx add %rax, %r14 adc $(0), %rdx add %rdx, %r15 adc $(0), %r8 xor %r11, %r11 movq (%rsp), %rsi mov %r12, %rax mov %r13, %rbx mov %r14, %rcx mov %r15, %rdx subq (%rdi), %rax sbbq (8)(%rdi), %rbx sbbq (16)(%rdi), %rcx sbbq (24)(%rdi), %rdx sbb $(0), %r8 cmovnc %rax, %r12 cmovnc %rbx, %r13 cmovnc %rcx, %r14 cmovnc %rdx, %r15 movq %r12, (%rsi) movq %r13, (8)(%rsi) movq %r14, (16)(%rsi) movq %r15, (24)(%rsi) mov %rsi, %rax add $(24), %rsp vzeroupper pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx ret
; A162669: a(n) = n*(n+1)*(n+2)*(n+3)*(n+4)*(n+5)/5. ; 0,144,1008,4032,12096,30240,66528,133056,247104,432432,720720,1153152,1782144,2673216,3907008,5581440,7814016,10744272,14536368,19381824,25502400,33153120,42625440,54250560,68402880,85503600,106024464,130491648,159489792,193666176,233735040,280482048,334768896,397538064,469817712,552726720,647479872,755393184,877889376,1016503488,1172888640,1348821936,1546210512,1767097728,2013669504,2288260800,2593362240,2931626880,3305877120,3719111760,4174513200,4675454784,5225508288,5828451552,6488276256,7209195840,7995653568,8852330736,9784155024,10796308992,11894238720,13083662592,14370580224,15761281536,17262355968,18880701840,20623535856,22498402752,24513185088,26676113184,28995775200,31481127360,34141504320,36986629680,40026626640,43272028800,46733791104,50423300928,54352389312,58533342336,62978912640,67702331088,72717318576,78038097984,83679406272,89656506720,95985201312,102681843264,109763349696,117247214448,125151521040,133494955776,142296820992,151577048448,161356212864,171655545600,182496948480,193903007760,205897008240,218502947520 sub $1,$0 bin $1,6 mul $1,144 mov $0,$1
; 4.6 ; Use a loop with indirect or indexed addressing to reverse the elements of an integer array in ; place. Do not copy the elements to any other array. Use the SIZEOF, TYPE, and LENGTHOF ; operators to make the program as flexible as possible if the array size and type should be ; changed in the future. .386 .model flat, STDCALL option casemap:none ; Case Sensitive include kernel32.inc .data array DWORD 10, 12, 32, 45, 11, 22 arrayType DWORD ? .code main PROC xor edx, edx mov arrayType, TYPE array mov eax, LENGTHOF array mov ebx, 2 div ebx; in order to get always pair to exchange mov ecx, eax; loop counter or edx, edx; it there is a reminder ; ebx is the first on the right ; esi is the first on the left jne odd_len jmp even_len; if no reminder odd_len: mov ebx, eax inc ebx; the first on the right of the middle mov esi, eax dec esi; the first on the left of the middle jmp swipe even_len: mov ebx, eax mov esi, eax dec esi swipe: mov eax, esi mul arrayType mov edx, array[eax] push eax push edx mov eax, ebx mul arrayType pop edx; edx was modified by mul mov edi, array[eax] mov array[eax], edx; move the one got from the left pop eax; old index mov array[eax], edi; move the one got from the right dec esi; go towards the left inc ebx; go towards the right loop swipe mov eax, OFFSET array invoke ExitProcess, 0 main ENDP end main
#include <bits/stdc++.h> #include <time.h> #define int long long int #define pb push_back #define all(a) a.begin(), a.end() #define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i] #define vi vector<int> #define si set<int> #define pii pair <int, int> #define sii set<pii> #define vii vector<pii> #define mii map <int, int> #define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) using namespace std; using namespace chrono; /* Things to remember : check for coners n = 1, pass references instead */ /* -------------------------------Solution Sarted--------------------------------------*/ void __print(int x) {cerr << x;} void __print(long x) {cerr << x;} void __print(unsigned x) {cerr << x;} void __print(unsigned long x) {cerr << x;} void __print(unsigned long long x) {cerr << x;} void __print(float x) {cerr << x;} void __print(double x) {cerr << x;} void __print(long double x) {cerr << x;} void __print(char x) {cerr << '\'' << x << '\'';} void __print(const char *x) {cerr << '\"' << x << '\"';} void __print(const string &x) {cerr << '\"' << x << '\"';} void __print(bool x) {cerr << (x ? "true" : "false");} template<typename T, typename V> void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';} template<typename T> void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";} void _print() {cerr << "]\n";} template <typename T, typename... V> void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);} #ifndef ONLINE_JUDGE #define debug(x...) cerr << "[" << #x << "] = ["; _print(x) #else #define debug(x...) #endif //Constants const int MOD = 1000000007; // 1e9 + 7 const int MAXN = 1000005; // 1e6 +5 const int INF = 100000000000005; // 1e15 +5 void solve(){ int n; string s; cin >> n >> s; vi a; a.push_back(0); for(auto itr: s){ a.push_back(itr - '0'); } int cnt = 0; vi pre(n +1, 0); for(int i = 1; i <= n; ++i){ pre[i] = pre[i -1] + a[i]; } mii m; for(int i = 0; i <= n; ++i){ m[pre[i] - i]++; } int ans = 0; for(auto itr: m){ ans += (itr.second*(itr.second -1))/2; } cout << ans << endl; } signed main() { faster; #ifndef ONLINE_JUDGE freopen("ip.txt", "r", stdin); freopen("op.txt", "w", stdout); #endif int t; cin >> t; while(t--) solve(); return 0; } //Author : Ankit Raj //Problem Link : /*Snippets*/ /* sieve - prime factorization using sieve and primes in range zpower - pow with mod plate - Initial template bfs dfs fenwik - BIT binary_search segment_tree */
// Test declarations of variables without definition // Commodore 64 PRG executable file .file [name="cstyle-decl-var.prg", type="prg", segments="Program"] .segmentdef Program [segments="Basic, Code, Data"] .segmentdef Basic [start=$0801] .segmentdef Code [start=$80d] .segmentdef Data [startAfter="Code"] .segment Basic :BasicUpstart(main) // The actual declarations .label SCREEN = $400 .segment Code // And a little code using them main: { // SCREEN[idx++] = 'c' lda #'c' sta SCREEN // SCREEN[idx++] = 'm' lda #'m' sta SCREEN+1 // SCREEN[idx++] = 'l' lda #'l' sta SCREEN+2 // } rts }
#include "sample_application.h" #ifdef WIN32 #include <windows.h> #endif #include <GL/gl.h> #include <cmath> using namespace std; using namespace cgv::gui; point::point(int _x, int _y) : x(_x), y(_y) { } line::line(int x0, int y0, int x1, int y1) : p0(x0,y0), p1(x1,y1) { } void drawing::add_point(int x, int y) { points.push_back(point(x,y)); } void drawing::add_line(int x, int y, int dx, int dy) { if (dx != 0 || dy != 0) lines.push_back(line(x-dx,y-dy,x,y)); } void drawing::render() const { glLineWidth(1); glBegin(GL_LINES); for (unsigned l=0; l<lines.size(); ++l) { glVertex2i(lines[l].p0.x, lines[l].p0.y); glVertex2i(lines[l].p1.x, lines[l].p1.y); } glEnd(); if (points.size() > 0) { glPointSize(5); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); for (unsigned p=0; p<points.size(); ++p) glVertex2i(points[p].x, points[p].y); glEnd(); } } void sample_application::init_mice(int w, int h) { if (mice.empty()) scan_mouse_devices(mice); int r = 20; for (unsigned i=0; i<mice.size(); ++i) { double a = 2*3.14*i/mice.size(); set_mouse_rectangle(mice[i].device_id,0,w,0,h); set_mouse_position(mice[i].device_id,(int)(w/2+r*cos(a)),(int)(h/2+r*sin(a))); } } void sample_application::process_mouse_change_event(bool attach, void* device_id, int w, int h) { if (attach) cout << "attached " << device_id << endl; else cout << "detached " << device_id << endl; mice.clear(); mice_drawings.clear(); init_mice(w, h); } bool sample_application::handle_mouse_event(const multi_mouse_event& mme) { switch (mme.get_action()) { case MA_PRESS: mice_drawings[mme.get_device_id()].add_point(mme.get_x(),mme.get_y()); break; case MA_DRAG: mice_drawings[mme.get_device_id()].add_line(mme.get_x(),mme.get_y(),mme.get_dx(),mme.get_dy()); break; default: return false; } return true; } sample_application::sample_application() { } void sample_application::draw_scene(double time) { // used rgb colors for different mice static GLfloat colors[] = { 1,1,1, 1,1,0, 0,1,1, 1,0,1, 1,0,0, 0,1,0, 0,0,1 }; // create default mouse pointer if (!c.is_created()) c.create(); // draw drawings in different colors unsigned i; for (i=0; i<mice.size(); ++i) { glColor3fv(colors+3*(i%7)); mice_drawings[mice[i].device_id].render(); } // draw mouse pointers in different colors glPushAttrib(GL_DEPTH_BUFFER_BIT); glDisable(GL_DEPTH_TEST); for (i=0; i<mice.size(); ++i) { int x,y; get_mouse_position(mice[i].device_id, x, y); glColor3fv(colors+3*(i%7)); c.draw(x,y,true,c.get_step_frame(c.find_step_index(time))); } glPopAttrib(); }
#ifndef ORG_EEROS_HAL_XBOX_HPP_ #define ORG_EEROS_HAL_XBOX_HPP_ #include <string> #include <functional> #include <linux/joystick.h> #include <eeros/hal/Input.hpp> #include <eeros/core/Thread.hpp> #define XBOX_BUTTON_COUNT (8) #define XBOX_AXIS_COUNT (8) namespace eeros { namespace hal { struct XBoxState { double axis[XBOX_AXIS_COUNT]; bool button_state[XBOX_BUTTON_COUNT]; bool button_up[XBOX_BUTTON_COUNT]; bool button_down[XBOX_BUTTON_COUNT]; static const double axis_max; }; struct XBoxController { struct Axis { static constexpr int LX = 0; static constexpr int LY = 1; static constexpr int LT = 2; static constexpr int RY = 3; static constexpr int RX = 4; static constexpr int RT = 5; static constexpr int CX = 6; static constexpr int CY = 7; }; struct Button { static constexpr int A = 0; static constexpr int B = 1; static constexpr int X = 2; static constexpr int Y = 3; static constexpr int LB = 4; static constexpr int RB = 5; static constexpr int back = 6; static constexpr int start = 7; }; }; class XBox : public eeros::Thread{ public: explicit XBox(std::string dev, int priority); ~XBox(); virtual void on_event(std::function<void(struct js_event)> action); virtual void on_button(std::function<void(int, bool)> action); virtual void on_axis(std::function<void(int, double)> action); virtual std::string name(); XBoxState last; XBoxState current; private: virtual void run(); virtual bool open(const char* device); virtual void close(); int fd; bool running; std::function<void(struct js_event)> event_action; std::function<void(int, bool)> button_action; std::function<void(int, double)> axis_action; Input<bool>* button[XBOX_BUTTON_COUNT]; }; } } #endif // ORG_EEROS_HAL_XBOX_HPP_
; A016756: a(n) = (2*n+1)^4. ; 1,81,625,2401,6561,14641,28561,50625,83521,130321,194481,279841,390625,531441,707281,923521,1185921,1500625,1874161,2313441,2825761,3418801,4100625,4879681,5764801,6765201,7890481,9150625,10556001,12117361,13845841,15752961,17850625,20151121,22667121,25411681,28398241,31640625,35153041,38950081,43046721,47458321,52200625,57289761,62742241,68574961,74805201,81450625,88529281,96059601,104060401,112550881,121550625,131079601,141158161,151807041,163047361,174900625,187388721,200533921,214358881,228886641,244140625,260144641,276922881,294499921,312900721,332150625,352275361,373301041,395254161,418161601,442050625,466948881,492884401,519885601,547981281,577200625,607573201,639128961,671898241,705911761,741200625,777796321,815730721,855036081,895745041,937890625,981506241,1026625681,1073283121,1121513121,1171350625,1222830961,1275989841,1330863361,1387488001,1445900625,1506138481,1568239201 mul $0,2 add $0,1 pow $0,4
; A117667: a(n) = n^n-n^(n-1)-n^(n-2)-n^(n-3)-...-n^3-n^2-n. ; 1,2,15,172,2345,37326,686287,14380472,338992929,8888888890,256780503551,8105545862052,277635514376233,10257237069745862,406615755353655135,17216961135462248176,775537745518440716417,37031913482632035365106,1868507452568073945283759,99338778947368421052631580,5550457667466683395312068201,325169407013542435615854022462,19931355818036643305520713232815,1275747264813315249473034452285352,85117098554595334765811761220296225 add $0,1 mov $1,2 mov $2,$0 lpb $2 sub $1,1 mul $1,$0 sub $2,1 lpe mov $0,$1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /* * Copyright (c) 2018, Open AI Lab * Author: jingyou@openailab.com */ #include "tm1_op_serializer.hpp" namespace TEngine { namespace TMSerializer1 { bool LoadTmAccuracyOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_ACCURACY); SetNodeOp(node, op); return true; } bool LoadTmBatchNormOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_BATCHNORMALIZATION; BatchNormParam param = any_cast<BatchNormParam>(OpManager::GetOpDefParam(op_str)); const TM_BatchNormParam* tm_param = GetTmPtr<TM_BatchNormParam>(start_ptr, tm_op->offset_t_param); param.rescale_factor = tm_param->rescale_factor; param.eps = tm_param->eps; param.caffe_flavor = tm_param->caffe_flavor; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmResizeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_BILINEARRESIZE; ResizeParam param = any_cast<ResizeParam>(OpManager::GetOpDefParam(op_str)); const TM_ResizeParam* tm_param = GetTmPtr<TM_ResizeParam>(start_ptr, tm_op->offset_t_param); param.scale_w = tm_param->scale_x; param.scale_h = tm_param->scale_y; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmConcatOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_CONCAT; ConcatParam param = any_cast<ConcatParam>(OpManager::GetOpDefParam(op_str)); const TM_ConcatParam* tm_param = GetTmPtr<TM_ConcatParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmConstOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_CONST); SetNodeOp(node, op); return true; } bool LoadTmConvOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_CONVOLUTION; ConvParam param = any_cast<ConvParam>(OpManager::GetOpDefParam(op_str)); const TM_ConvParam* tm_param = GetTmPtr<TM_ConvParam>(start_ptr, tm_op->offset_t_param); param.kernel_h = tm_param->kernel_h; param.kernel_w = tm_param->kernel_w; param.stride_h = tm_param->stride_h; param.stride_w = tm_param->stride_w; param.dilation_h = tm_param->dilation_h; param.dilation_w = tm_param->dilation_w; param.output_channel = tm_param->output_channel; param.activation = tm_param->activation; param.group = tm_param->group; param.pad_h0 = tm_param->pad_h; param.pad_h1 = tm_param->pad_h; param.pad_w0 = tm_param->pad_w; param.pad_w1 = tm_param->pad_w; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDeconvOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_DECONVOLUTION; DeconvParam param = any_cast<DeconvParam>(OpManager::GetOpDefParam(op_str)); const TM_DeconvParam* tm_param = GetTmPtr<TM_DeconvParam>(start_ptr, tm_op->offset_t_param); param.kernel_h = tm_param->kernel_size; param.kernel_w = tm_param->kernel_size; param.stride_h = tm_param->stride; param.stride_w = tm_param->stride; param.pad_w0 = tm_param->pad; param.pad_w1 = tm_param->pad; param.pad_h0 = tm_param->pad; param.pad_h1 = tm_param->pad; param.num_output = tm_param->num_output; param.dilation_h = tm_param->dilation; param.dilation_w = tm_param->dilation; param.group = 1; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDetectionOutputOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_DETECTIONOUTPUT; DetectionOutputParam param = any_cast<DetectionOutputParam>(OpManager::GetOpDefParam(op_str)); const TM_DetectionOutputParam* tm_param = GetTmPtr<TM_DetectionOutputParam>(start_ptr, tm_op->offset_t_param); param.num_classes = tm_param->num_classes; param.keep_top_k = tm_param->keep_top_k; param.nms_top_k = tm_param->nms_top_k; param.confidence_threshold = tm_param->confidence_threshold; param.nms_threshold = tm_param->nms_threshold; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmDropoutOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_DROPOUT); SetNodeOp(node, op); return true; } bool LoadTmEltwiseOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_ELTWISE; EltwiseParam param = any_cast<EltwiseParam>(OpManager::GetOpDefParam(op_str)); const TM_EltwiseParam* tm_param = GetTmPtr<TM_EltwiseParam>(start_ptr, tm_op->offset_t_param); param.type = static_cast<EltType>(tm_param->type); param.caffe_flavor = tm_param->caffe_flavor; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmFlattenOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_FLATTEN; FlattenParam param = any_cast<FlattenParam>(OpManager::GetOpDefParam(op_str)); const TM_FlattenParam* tm_param = GetTmPtr<TM_FlattenParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; param.end_axis = tm_param->end_axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmFCOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_FULLYCONNECTED; FCParam param = any_cast<FCParam>(OpManager::GetOpDefParam(op_str)); const TM_FCParam* tm_param = GetTmPtr<TM_FCParam>(start_ptr, tm_op->offset_t_param); param.num_output = tm_param->num_output; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmInputOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_INPUTOP); SetNodeOp(node, op); return true; } bool LoadTmLRNOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_LRN; LRNParam param = any_cast<LRNParam>(OpManager::GetOpDefParam(op_str)); const TM_LRNParam* tm_param = GetTmPtr<TM_LRNParam>(start_ptr, tm_op->offset_t_param); param.local_size = tm_param->local_size; param.alpha = tm_param->alpha; param.beta = tm_param->beta; param.norm_region = tm_param->norm_region; param.k = tm_param->k; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmNormalizeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_NORMALIZE; NormalizeParam param = any_cast<NormalizeParam>(OpManager::GetOpDefParam(op_str)); const TM_NormalizeParam* tm_param = GetTmPtr<TM_NormalizeParam>(start_ptr, tm_op->offset_t_param); param.across_spatial = tm_param->across_spatial; param.channel_shared = tm_param->channel_shared; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPermuteOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_PERMUTE; PermuteParam param = any_cast<PermuteParam>(OpManager::GetOpDefParam(op_str)); const TM_PermuteParam* tm_param = GetTmPtr<TM_PermuteParam>(start_ptr, tm_op->offset_t_param); param.flag = tm_param->flag; param.order0 = tm_param->order0; param.order1 = tm_param->order1; param.order2 = tm_param->order2; param.order3 = tm_param->order3; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPoolingOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_POOLING; PoolParam param = any_cast<PoolParam>(OpManager::GetOpDefParam(op_str)); const TM_PoolParam* tm_param = GetTmPtr<TM_PoolParam>(start_ptr, tm_op->offset_t_param); param.alg = static_cast<PoolArg>(tm_param->alg); param.kernel_h = tm_param->kernel_h; param.kernel_w = tm_param->kernel_w; param.stride_h = tm_param->stride_h; param.stride_w = tm_param->stride_w; param.global = tm_param->global; param.caffe_flavor = tm_param->caffe_flavor; param.pad_h0 = tm_param->pads[0]; param.pad_w0 = tm_param->pads[1]; param.pad_h1 = tm_param->pads[2]; param.pad_w1 = tm_param->pads[3]; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmPreluOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_PRELU); SetNodeOp(node, op); return true; } bool LoadTmPriorBoxOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_PRIORBOX; PriorBoxParam param = any_cast<PriorBoxParam>(OpManager::GetOpDefParam(op_str)); const TM_PriorBoxParam* tm_param = GetTmPtr<TM_PriorBoxParam>(start_ptr, tm_op->offset_t_param); const TM_Vector_floats* v_minsizes = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_min_size); const TM_Vector_floats* v_maxsizes = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_max_size); const TM_Vector_floats* v_variances = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_variance); const TM_Vector_floats* v_ratios = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_aspect_ratio); for(unsigned int i = 0; i < v_minsizes->v_num; i++) param.min_size.push_back(v_minsizes->data[i]); for(unsigned int i = 0; i < v_maxsizes->v_num; i++) param.max_size.push_back(v_maxsizes->data[i]); for(unsigned int i = 0; i < v_variances->v_num; i++) param.variance.push_back(v_variances->data[i]); for(unsigned int i = 0; i < v_ratios->v_num; i++) param.aspect_ratio.push_back(v_ratios->data[i]); param.flip = tm_param->flip; param.clip = tm_param->clip; param.img_size = tm_param->img_size; param.img_h = tm_param->img_h; param.img_w = tm_param->img_w; param.step_w = tm_param->step_w; param.step_h = tm_param->step_h; param.offset = tm_param->offset; param.num_priors_ = tm_param->num_priors; param.out_dim_ = tm_param->out_dim; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRegionOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_REGION; RegionParam param = any_cast<RegionParam>(OpManager::GetOpDefParam(op_str)); const TM_RegionParam* tm_param = GetTmPtr<TM_RegionParam>(start_ptr, tm_op->offset_t_param); const TM_Vector_floats* v_biases = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_biases); for(unsigned int i = 0; i < v_biases->v_num; i++) param.biases.push_back(v_biases->data[i]); param.num_classes = tm_param->num_classes; param.side = tm_param->side; param.num_box = tm_param->num_box; param.coords = tm_param->coords; param.confidence_threshold = tm_param->confidence_threshold; param.nms_threshold = tm_param->nms_threshold; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmReLuOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_RELU; ReLuParam param = any_cast<ReLuParam>(OpManager::GetOpDefParam(op_str)); const TM_ReLuParam* tm_param = GetTmPtr<TM_ReLuParam>(start_ptr, tm_op->offset_t_param); param.negative_slope = tm_param->negative_slope; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRelu6Op(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_RELU6); SetNodeOp(node, op); return true; } bool LoadTmReorgOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_REORG; ReorgParam param = any_cast<ReorgParam>(OpManager::GetOpDefParam(op_str)); const TM_ReorgParam* tm_param = GetTmPtr<TM_ReorgParam>(start_ptr, tm_op->offset_t_param); param.stride = tm_param->stride; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmReshapeOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_RESHAPE; ReshapeParam param = any_cast<ReshapeParam>(OpManager::GetOpDefParam(op_str)); const TM_ReshapeParam* tm_param = GetTmPtr<TM_ReshapeParam>(start_ptr, tm_op->offset_t_param); param.dim_0 = tm_param->dim_0; param.dim_1 = tm_param->dim_1; param.dim_2 = tm_param->dim_2; param.dim_3 = tm_param->dim_3; param.dim_size = tm_param->dim_size; param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmROIPoolingOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_ROIPOOLING; ROIPoolingParam param = any_cast<ROIPoolingParam>(OpManager::GetOpDefParam(op_str)); const TM_ROIPoolingParam* tm_param = GetTmPtr<TM_ROIPoolingParam>(start_ptr, tm_op->offset_t_param); param.pooled_h = tm_param->pooled_h; param.pooled_w = tm_param->pooled_w; param.spatial_scale = tm_param->spatial_scale; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmRPNOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_RPN; RPNParam param = any_cast<RPNParam>(OpManager::GetOpDefParam(op_str)); const TM_RPNParam* tm_param = GetTmPtr<TM_RPNParam>(start_ptr, tm_op->offset_t_param); const TM_Vector_floats* v_ratios = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_ratios); const TM_Vector_floats* v_scales = GetTmPtr<TM_Vector_floats>(start_ptr, tm_param->offset_vf_anchor_scales); for(unsigned int i = 0; i < v_ratios->v_num; i++) param.ratios.push_back(v_ratios->data[i]); for(unsigned int i = 0; i < v_scales->v_num; i++) param.anchor_scales.push_back(v_scales->data[i]); param.feat_stride = tm_param->feat_stride; param.basesize = tm_param->basesize; param.min_size = tm_param->min_size; param.per_nms_topn = tm_param->per_nms_topn; param.post_nms_topn = tm_param->post_nms_topn; param.nms_thresh = tm_param->nms_thresh; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmScaleOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_SCALE; ScaleParam param = any_cast<ScaleParam>(OpManager::GetOpDefParam(op_str)); const TM_ScaleParam* tm_param = GetTmPtr<TM_ScaleParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; param.num_axes = tm_param->num_axes; param.bias_term = tm_param->bias_term; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSliceOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_SLICE; SliceParam param = any_cast<SliceParam>(OpManager::GetOpDefParam(op_str)); const TM_SliceParam* tm_param = GetTmPtr<TM_SliceParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; param.iscaffe = true; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSoftmaxOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { const std::string& op_str = OP_STR_SOFTMAX; SoftmaxParam param = any_cast<SoftmaxParam>(OpManager::GetOpDefParam(op_str)); const TM_SoftmaxParam* tm_param = GetTmPtr<TM_SoftmaxParam>(start_ptr, tm_op->offset_t_param); param.axis = tm_param->axis; StaticOp* op = CreateStaticOp(graph, op_str); SetOperatorParam(op, param); SetNodeOp(node, op); return true; } bool LoadTmSplitOp(StaticGraph* graph, StaticNode* node, void* const start_ptr, const TM_Operator* tm_op) { StaticOp* op = CreateStaticOp(graph, OP_STR_SPLIT); SetNodeOp(node, op); return true; } op_load_t LoadTmOpFunc(uint32_t op_type) { switch(op_type) { case TM_OPTYPE_ACCURACY: return LoadTmAccuracyOp; case TM_OPTYPE_BATCHNORMALIZATION: return LoadTmBatchNormOp; case TM_OPTYPE_BILINEARRESIZE: return LoadTmResizeOp; case TM_OPTYPE_CONCAT: return LoadTmConcatOp; case TM_OPTYPE_CONST: return LoadTmConstOp; case TM_OPTYPE_CONVOLUTION: return LoadTmConvOp; case TM_OPTYPE_DECONVOLUTION: return LoadTmDeconvOp; case TM_OPTYPE_DETECTIONOUTPUT: return LoadTmDetectionOutputOp; case TM_OPTYPE_DROPOUT: return LoadTmDropoutOp; case TM_OPTYPE_ELTWISE: return LoadTmEltwiseOp; case TM_OPTYPE_FLATTEN: return LoadTmFlattenOp; case TM_OPTYPE_FULLYCONNECTED: return LoadTmFCOp; case TM_OPTYPE_INPUTOP: return LoadTmInputOp; case TM_OPTYPE_LRN: return LoadTmLRNOp; case TM_OPTYPE_NORMALIZE: return LoadTmNormalizeOp; case TM_OPTYPE_PERMUTE: return LoadTmPermuteOp; case TM_OPTYPE_POOLING: return LoadTmPoolingOp; case TM_OPTYPE_PRELU: return LoadTmPreluOp; case TM_OPTYPE_PRIORBOX: return LoadTmPriorBoxOp; case TM_OPTYPE_REGION: return LoadTmRegionOp; case TM_OPTYPE_RELU: return LoadTmReLuOp; case TM_OPTYPE_RELU6: return LoadTmRelu6Op; case TM_OPTYPE_REORG: return LoadTmReorgOp; case TM_OPTYPE_RESHAPE: return LoadTmReshapeOp; case TM_OPTYPE_ROIPOOLING: return LoadTmROIPoolingOp; case TM_OPTYPE_RPN: return LoadTmRPNOp; case TM_OPTYPE_SCALE: return LoadTmScaleOp; case TM_OPTYPE_SLICE: return LoadTmSliceOp; case TM_OPTYPE_SOFTMAX: return LoadTmSoftmaxOp; case TM_OPTYPE_SPLIT: return LoadTmSplitOp; default: LOG_ERROR() << "Operator #" << op_type << " not supported in tengine model yet\n"; return nullptr; } } std::string GetOpStr(uint32_t op_type) { switch(op_type) { case TM_OPTYPE_ACCURACY: return std::string(OP_STR_ACCURACY); case TM_OPTYPE_BATCHNORMALIZATION: return std::string(OP_STR_BATCHNORMALIZATION); case TM_OPTYPE_BILINEARRESIZE: return std::string(OP_STR_BILINEARRESIZE); case TM_OPTYPE_CONCAT: return std::string(OP_STR_CONCAT); case TM_OPTYPE_CONST: return std::string(OP_STR_CONST); case TM_OPTYPE_CONVOLUTION: return std::string(OP_STR_CONVOLUTION); case TM_OPTYPE_DECONVOLUTION: return std::string(OP_STR_DECONVOLUTION); case TM_OPTYPE_DETECTIONOUTPUT: return std::string(OP_STR_DETECTIONOUTPUT); case TM_OPTYPE_DROPOUT: return std::string(OP_STR_DROPOUT); case TM_OPTYPE_ELTWISE: return std::string(OP_STR_ELTWISE); case TM_OPTYPE_FLATTEN: return std::string(OP_STR_FLATTEN); case TM_OPTYPE_FULLYCONNECTED: return std::string(OP_STR_FULLYCONNECTED); case TM_OPTYPE_INPUTOP: return std::string(OP_STR_INPUTOP); case TM_OPTYPE_LRN: return std::string(OP_STR_LRN); case TM_OPTYPE_NORMALIZE: return std::string(OP_STR_NORMALIZE); case TM_OPTYPE_PERMUTE: return std::string(OP_STR_PERMUTE); case TM_OPTYPE_POOLING: return std::string(OP_STR_POOLING); case TM_OPTYPE_PRELU: return std::string(OP_STR_PRELU); case TM_OPTYPE_PRIORBOX: return std::string(OP_STR_PRIORBOX); case TM_OPTYPE_REGION: return std::string(OP_STR_REGION); case TM_OPTYPE_RELU: return std::string(OP_STR_RELU); case TM_OPTYPE_RELU6: return std::string(OP_STR_RELU6); case TM_OPTYPE_REORG: return std::string(OP_STR_REORG); case TM_OPTYPE_RESHAPE: return std::string(OP_STR_RESHAPE); case TM_OPTYPE_ROIPOOLING: return std::string(OP_STR_ROIPOOLING); case TM_OPTYPE_RPN: return std::string(OP_STR_RPN); case TM_OPTYPE_SCALE: return std::string(OP_STR_SCALE); case TM_OPTYPE_SLICE: return std::string(OP_STR_SLICE); case TM_OPTYPE_SOFTMAX: return std::string(OP_STR_SOFTMAX); case TM_OPTYPE_SPLIT: return std::string(OP_STR_SPLIT); default: LOG_ERROR() << "Get operator string failed\n"; return std::string(""); } } } // namespace TMSerializer1 } // namespace TEngine
; A016930: a(n) = (6*n + 1)^10. ; 1,282475249,137858491849,6131066257801,95367431640625,819628286980801,4808584372417849,21611482313284249,79792266297612001,253295162119140625,713342911662882601,1822837804551761449,4297625829703557649,9468276082626847201,19687440434072265625,38941611811810745401,73742412689492826049,134391637934412192049,236736367459211723401,404555773570791015625,672749994932560009201,1091533853073393531649,1731874467807835667449,2692452204196940400601,4108469075197275390625,6162677950336718514001,9099059901039401398249,13239635967018160063849,19004963774880799438801,26938938999176025390625,37738596846955704499801,52289689788971837545849,71708904873278937061249,97393677359695041798001,131080657325707041015625,174913992535407978606601,231524704452345220694449,304122555034158459939649,396601930091015154838201,513663400740527822265625,660952768068482275874401,845219547726738091164049,1074497011086501939579049,1358306067936240628319401,1707885452788213369140625,2136450862855381637743201,2659485890900719634874649,3295067800663118480459449,4064231406647572522401601,4991374543951576181640625,6104708847704064244053001,7436759805837217107346249,9024920303514444856660849,10912062142819279835644801,13147210297489166259765625,15786284949774657045043801,18892916655137732057698849,22539340290692258087863249,26807373765254438673009001,31789487802830871103515625,37589973457545958193355601,44326214376618333352652449,52130071199257068815346649,61149385863482168213854201,71549613990099615712890625,83515593923598484276028401,97253461433805715000527049,112992719519952587477991049,130988473210595027479940401,151523839718807162587890625,174912544792453358346502201,201501716594357766775242649,231674888957051615288276449,265855226381706476903427601,304508983691076011728515625,348149213801988574756617001,397339737654378065640319249,452699390921229872008282849,514906562727372148694875801,584704042224979400634765625,662904189510194816788612801,750394448018639455972876849,848143216207979632525690249,957206097023388110011245001,1078732544346879404306640625,1213972926354344043087129601,1364286026444870446587635449,1531147003165845604229778649,1716155831334586342923895201,1921046247353091135244140625,2147695222527137498891207401,2398132989034601512560915049,2674553644040763237187428049,2979326358330704305186586401,3315007216720921043447265625,3684351718424187648066286201,4090327966473728549854635649,4536130576265116619119118449,5025195334247223675803478601,5561214638787231316416015625 mul $0,6 add $0,1 pow $0,10
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <dirent.h> #include <sys/stat.h> #include <fstream> #include <AzFramework/IO/LocalFileIO.h> #include <AzCore/Android/APKFileHandler.h> #include <AzCore/Android/Utils.h> #include <AzCore/IO/IOUtils.h> #include <AzCore/IO/Path/Path.h> #include <AzCore/IO/SystemFile.h> #include <AzCore/std/functional.h> #include <android/api-level.h> #if __ANDROID_API__ == 19 // The following were apparently introduced in API 21, however in earlier versions of the // platform specific headers they were defines. In the move to unified headers, the following // defines were removed from stat.h #ifndef stat64 #define stat64 stat #endif #ifndef fstat64 #define fstat64 fstat #endif #ifndef lstat64 #define lstat64 lstat #endif #endif // __ANDROID_API__ == 19 namespace AZ { namespace IO { bool LocalFileIO::IsDirectory(const char* filePath) { ANDROID_IO_PROFILE_SECTION_ARGS("IsDir:%s", filePath); char resolvedPath[AZ_MAX_PATH_LEN]; ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN); if (AZ::Android::Utils::IsApkPath(resolvedPath)) { return AZ::Android::APKFileHandler::IsDirectory(AZ::Android::Utils::StripApkPrefix(resolvedPath).c_str()); } struct stat result; if (stat(resolvedPath, &result) == 0) { return S_ISDIR(result.st_mode); } return false; } Result LocalFileIO::Copy(const char* sourceFilePath, const char* destinationFilePath) { char resolvedSourcePath[AZ_MAX_PATH_LEN]; char resolvedDestPath[AZ_MAX_PATH_LEN]; ResolvePath(sourceFilePath, resolvedSourcePath, AZ_MAX_PATH_LEN); ResolvePath(destinationFilePath, resolvedDestPath, AZ_MAX_PATH_LEN); if (AZ::Android::Utils::IsApkPath(sourceFilePath) || AZ::Android::Utils::IsApkPath(destinationFilePath)) { return ResultCode::Error; //copy from APK still to be implemented (and of course you can't copy to an APK) } // note: Android, without root, has no reliable way to update modtimes // on files on internal storage - this includes "emulated" SDCARD storage // that actually resides on internal, and thus we can't depend on modtimes. { std::ifstream sourceFile(resolvedSourcePath, std::ios::binary); if (sourceFile.fail()) { return ResultCode::Error; } std::ofstream destFile(resolvedDestPath, std::ios::binary); if (destFile.fail()) { return ResultCode::Error; } destFile << sourceFile.rdbuf(); } return ResultCode::Success; } Result LocalFileIO::FindFiles(const char* filePath, const char* filter, LocalFileIO::FindFilesCallbackType callback) { ANDROID_IO_PROFILE_SECTION_ARGS("FindFiles:%s", filePath); char resolvedPath[AZ_MAX_PATH_LEN]; ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN); AZ::OSString pathWithoutSlash = RemoveTrailingSlash(resolvedPath); bool isInAPK = AZ::Android::Utils::IsApkPath(pathWithoutSlash.c_str()); if (isInAPK) { AZ::IO::FixedMaxPath strippedPath = AZ::Android::Utils::StripApkPrefix(pathWithoutSlash.c_str()); char tempBuffer[AZ_MAX_PATH_LEN] = {0}; AZ::Android::APKFileHandler::ParseDirectory(strippedPath.c_str(), [&](const char* name) { AZStd::string_view filenameView = name; // Skip over the current and parent directory paths if (filenameView != "." && filenameView != ".." && NameMatchesFilter(name, filter)) { AZ::OSString foundFilePath = CheckForTrailingSlash(resolvedPath); foundFilePath += name; // if aliased, de-alias! azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, foundFilePath.c_str()); ConvertToAlias(tempBuffer, AZ_MAX_PATH_LEN); if (!callback(tempBuffer)) { return false; } } return true; }); } else { DIR* dir = opendir(pathWithoutSlash.c_str()); if (dir != nullptr) { // because the absolute path might actually be SHORTER than the alias ("c:/r/dev" -> "@devroot@"), we need to // use a static buffer here. char tempBuffer[AZ_MAX_PATH_LEN]; // clear the errno state so we can distinguish between errors and end of stream errno = 0; struct dirent* entry = readdir(dir); // List all the other files in the directory. while (entry != nullptr) { AZStd::string_view filenameView = entry->d_name; // Skip over the current and parent directory paths if (filenameView != "." && filenameView != ".." && NameMatchesFilter(entry->d_name, filter)) { AZ::OSString foundFilePath = CheckForTrailingSlash(resolvedPath); foundFilePath += entry->d_name; // if aliased, de-alias! azstrcpy(tempBuffer, AZ_MAX_PATH_LEN, foundFilePath.c_str()); ConvertToAlias(tempBuffer, AZ_MAX_PATH_LEN); if (!callback(tempBuffer)) { break; } } entry = readdir(dir); } if (errno != 0) { closedir(dir); return ResultCode::Error; } closedir(dir); return ResultCode::Success; } else { return ResultCode::Error; } } return ResultCode::Success; } Result LocalFileIO::CreatePath(const char* filePath) { char resolvedPath[AZ_MAX_PATH_LEN]; ResolvePath(filePath, resolvedPath, AZ_MAX_PATH_LEN); if (AZ::Android::Utils::IsApkPath(resolvedPath)) { return ResultCode::Error; //you can't write to the APK } // create all paths up to that directory. // its not an error if the path exists. if ((Exists(resolvedPath)) && (!IsDirectory(resolvedPath))) { return ResultCode::Error; // that path exists, but is not a directory. } // make directories from bottom to top. AZ::OSString pathBuffer; size_t pathLength = strlen(resolvedPath); pathBuffer.reserve(pathLength); for (size_t pathPos = 0; pathPos < pathLength; ++pathPos) { if ((resolvedPath[pathPos] == '\\') || (resolvedPath[pathPos] == '/')) { if (pathPos > 0) { mkdir(pathBuffer.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (!IsDirectory(pathBuffer.c_str())) { return ResultCode::Error; } } } pathBuffer.push_back(resolvedPath[pathPos]); } mkdir(pathBuffer.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); return IsDirectory(resolvedPath) ? ResultCode::Success : ResultCode::Error; } bool LocalFileIO::IsAbsolutePath(const char* path) const { return path && path[0] == '/'; } bool LocalFileIO::ConvertToAbsolutePath(const char* path, char* absolutePath, AZ::u64 maxLength) const { if (AZ::Android::Utils::IsApkPath(path)) { azstrncpy(absolutePath, maxLength, path, maxLength); return true; } AZ_Assert(maxLength >= AZ_MAX_PATH_LEN, "Path length is larger than AZ_MAX_PATH_LEN"); if (!IsAbsolutePath(path)) { // note that realpath fails if the path does not exist and actually changes the return value // to be the actual place that FAILED, which we don't want. // if we fail, we'd prefer to fall through and at least use the original path. const char* result = realpath(path, absolutePath); if (result) { return true; } } azstrcpy(absolutePath, maxLength, path); return IsAbsolutePath(absolutePath); } } // namespace IO }//namespace AZ
; A077118: Nearest integer square to n^3. ; 0,1,9,25,64,121,225,361,529,729,1024,1296,1764,2209,2704,3364,4096,4900,5776,6889,7921,9216,10609,12100,13924,15625,17689,19600,21904,24336,26896,29929,32761,36100,39204,42849,46656,50625,54756,59536 seq $0,2821 ; a(n) = nearest integer to n^(3/2). add $1,$0 pow $1,2 mov $0,$1
#include <iostream> #include <fstream> // #define CGAL_USE_BASIC_VIEWER #include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/IO/OBJ_reader.h> #include <CGAL/Surface_mesh_simplification/edge_collapse.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h> #include <CGAL/Polygon_mesh_processing/orient_polygon_soup.h> #include <CGAL/Polygon_mesh_processing/repair.h> #include <algorithm> #include <string> #include <CGAL/Polyhedron_3.h> #include <CGAL/Polyhedron_items_3.h> #include <CGAL/array.h> #include <CGAL/Bbox_3.h> #include <CGAL/Polygon_mesh_processing/internal/named_function_params.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Polygon_2.h> #include <CGAL/Polygon_mesh_processing/internal/named_params_helper.h> #include <CGAL/Arr_circle_segment_traits_2.h> #include <CGAL/Arrangement_2.h> #include <CGAL/Cartesian.h> #include <CGAL/Exact_rational.h> #include <CGAL/IO/binary_file_io.h> #include <CGAL/IO/File_header_OFF.h> #include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> #include <CGAL/Surface_mesh_simplification/edge_collapse.h> #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <CGAL/draw_surface_mesh.h> #include <CGAL/AABB_tree.h> #include <CGAL/AABB_traits.h> #include <CGAL/AABB_triangle_primitive.h> #include <CGAL/AABB_face_graph_triangle_primitive.h> #include <CGAL/Kernel_traits.h> #include <samurai/box.hpp> #include <samurai/cell_array.hpp> #include <samurai/field.hpp> #include <samurai/hdf5.hpp> #include <samurai/static_algorithm.hpp> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_3 Point_3; typedef CGAL::Surface_mesh<Point_3> Surface_mesh; namespace SMS = CGAL::Surface_mesh_simplification; typedef CGAL::Surface_mesh<Point_3> Mesh_3; typedef std::vector<std::size_t> Polygon_3; using namespace std; std::string path_extension(const string& filename) { const auto pos = filename.rfind('.'); if (pos == string::npos) return ""; return filename.substr(pos); } Mesh_3* ReadMesh(const char* modelPath) { const auto ext = path_extension(modelPath); Mesh_3* mesh = new Mesh_3(); if (ext == ".obj" || ext == ".OBJ") { std::ifstream input(modelPath); vector<Point_3> points; std::vector<Polygon_3> faces; std::cout << modelPath << "\n"; if (!CGAL::read_OBJ(input, points, faces)) return nullptr; namespace PMP = CGAL::Polygon_mesh_processing; PMP::is_polygon_soup_a_polygon_mesh(faces); PMP::orient_polygon_soup(points, faces); try { PMP::polygon_soup_to_polygon_mesh(points, faces, *mesh); } catch (char *str) { std::cout << str << std::endl; } input.close(); } else if (ext == ".off" || ext == ".OFF") { std::ifstream input(modelPath); if (!input || !(input >> *mesh)) { std::cerr << "mesh is not a valid off file." << std::endl; return nullptr; } input.close(); } else { std::cerr << "unsupported file type:" << ext << std::endl; return nullptr; } if (mesh->is_empty()) { std::cerr << "mesh is empty." << std::endl; delete mesh; return nullptr; } SMS::Count_ratio_stop_predicate<Surface_mesh> stop(0.1); // int r = SMS::edge_collapse(*mesh, stop); return mesh; } int main(int argc, char** argv) { auto p_m = ReadMesh("../demos/apple/Apple.obj"); auto m = *p_m; typedef CGAL::AABB_face_graph_triangle_primitive<Mesh_3> Primitive; typedef CGAL::AABB_traits<Kernel, Primitive> Traits; typedef CGAL::AABB_tree< Traits > Tree; Tree tree( faces(m).first, faces(m).second, m); tree.accelerate_distance_queries(); tree.build(); typedef typename boost::property_map<Mesh_3, boost::vertex_point_t>::const_type VPMap; VPMap vpmap = get(boost::vertex_point, m); typename Traits::Point_3 hint = get(vpmap, *vertices(m).begin()); constexpr std::size_t dim = 3; std::size_t start_level = 2; std::size_t max_level = 8; int start = 1.2 * std::pow(start_level, 2); samurai::Box<int, dim> box({-start, -start, -start}, {start, start, start}); samurai::CellArray<dim> ca; ca[start_level] = {start_level, box}; for(std::size_t rep = 0; rep <= 10; ++rep) { std::cout << "iteration: " << rep << "\n"; auto tag = samurai::make_field<bool, 1>("tag", ca); tag.fill(false); samurai::for_each_cell(ca, [&](auto cell) { auto center = 50*cell.center(); Kernel::Point_3 p(center[0], center[1], center[2]); hint = tree.closest_point(p, hint); Kernel::FT dist = squared_distance(hint, p); double d = CGAL::sqrt(dist); if (d < 2.5 && cell.level > 4) { tag[cell] = true; } if (d < 10 && cell.level <= 4) { tag[cell] = true; } }); samurai::CellList<dim> cl; samurai::for_each_interval(ca, [&](std::size_t level, const auto& interval, const auto& index_yz) { for (int i = interval.start; i < interval.end; ++i) { if (tag[i + interval.index] && level < max_level) { samurai::static_nested_loop<dim - 1, 0, 2>([&](auto stencil) { auto index = 2 * index_yz + stencil; cl[level + 1][index].add_interval({2 * i, 2 * i + 2}); }); } else { cl[level][index_yz].add_point(i); } } }); ca = {cl, true}; } auto level = samurai::make_field<std::size_t, 1>("level", ca); samurai::for_each_cell(ca, [&](auto cell) { level[cell] = cell.level; }); std::cout << ca.nb_cells() << "\n"; samurai::save("mesh_apple", ca, level); return EXIT_SUCCESS; }
.text main: # Same sign li $t0, 300 li $t1, 200 blt $t0, $t1, branch li $a0, 0 li $v0, 1 syscall j next branch: li $a0, 1 li $v0, 1 syscall next: # Diff sign li $t0, 300 li $t1, -200 blt $t0, $t1, branch_2 li $a0, 0 li $v0, 1 syscall j next_2 branch_2: li $a0, 1 li $v0, 1 syscall next_2: # Same sign li $t0, 300 li $t1, 200 bltu $t0, $t1, branch_3 li $a0, 0 li $v0, 1 syscall j next_3 branch_3: li $a0, 1 li $v0, 1 syscall next_3: li $t0, 300 li $t1, -200 bltu $t0, $t1, branch_4 li $a0, 0 li $v0, 1 syscall j next_4 branch_4: li $a0, 1 li $v0, 1 syscall next_4:
SECTION code_clib SECTION code_string PUBLIC __str_locate_nul __str_locate_nul: ; enter : hl = char *s ; ; exit : hl = ptr in s to terminating 0 ; bc = -(strlen + 1) ; a = 0 ; carry reset ; ; uses : af, bc, hl xor a ld c,a ld b,a IF __CPU_INTEL__ || __CPU_GBZ80__ loop: dec bc ld a,(hl) and a ret Z inc hl ld a,b or c jr NZ,loop ELSE cpir ENDIF dec hl ret
/*============================================================================= Copyright (c) 2003 Hartmut Kaiser http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_SWITCH_IPP #define BOOST_SPIRIT_SWITCH_IPP #include <boost/mpl/if.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/static_assert.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/inc.hpp> #include <boost/preprocessor/repeat.hpp> #include <boost/preprocessor/repeat_from_to.hpp> #include <boost/spirit/home/classic/core/parser.hpp> #include <boost/spirit/home/classic/core/primitives/primitives.hpp> #include <boost/spirit/home/classic/core/composite/composite.hpp> #include <boost/spirit/home/classic/meta/as_parser.hpp> #include <boost/spirit/home/classic/phoenix/actor.hpp> #include <boost/spirit/home/classic/phoenix/tuples.hpp> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN // forward declaration template <int N, typename ParserT, bool IsDefault> struct case_parser; /////////////////////////////////////////////////////////////////////////////// namespace impl { /////////////////////////////////////////////////////////////////////////////// // parse helper functions template <typename ParserT, typename ScannerT> inline typename parser_result<ParserT, ScannerT>::type delegate_parse(ParserT const &p, ScannerT const &scan, typename ScannerT::iterator_t const save) { typedef typename parser_result<ParserT, ScannerT>::type result_t; result_t result (p.subject().parse(scan)); if (!result) scan.first = save; return result; } /////////////////////////////////////////////////////////////////////////////// // General default case handling (no default_p case branch given). // First try to match the current parser node (if the condition value is // matched) and, if that fails, return a no_match template <int N, bool IsDefault, bool HasDefault> struct default_delegate_parse { template < typename ParserT, typename DefaultT, typename ValueT, typename ScannerT > static typename parser_result<ParserT, ScannerT>::type parse (ValueT const &value, ParserT const &p, DefaultT const &, ScannerT const &scan, typename ScannerT::iterator_t const save) { if (value == N) return delegate_parse(p, scan, save); return scan.no_match(); } }; // The current case parser node is the default parser. // Ignore the given case value and try to match the given default parser. template <int N, bool HasDefault> struct default_delegate_parse<N, true, HasDefault> { template < typename ParserT, typename DefaultT, typename ValueT, typename ScannerT > static typename parser_result<ParserT, ScannerT>::type parse (ValueT const& /*value*/, ParserT const &, DefaultT const &d, ScannerT const &scan, typename ScannerT::iterator_t const save) { // Since there is a default_p case branch defined, the corresponding // parser shouldn't be the nothing_parser BOOST_STATIC_ASSERT((!boost::is_same<DefaultT, nothing_parser>::value)); return delegate_parse(d, scan, save); } }; // The current case parser node is not the default parser, but there is a // default_p branch given inside the switch_p parser. // First try to match the current parser node (if the condition value is // matched) and, if that fails, match the given default_p parser. template <int N> struct default_delegate_parse<N, false, true> { template < typename ParserT, typename DefaultT, typename ValueT, typename ScannerT > static typename parser_result<ParserT, ScannerT>::type parse (ValueT const &value, ParserT const &p, DefaultT const &d, ScannerT const &scan, typename ScannerT::iterator_t const save) { // Since there is a default_p case branch defined, the corresponding // parser shouldn't be the nothing_parser BOOST_STATIC_ASSERT((!boost::is_same<DefaultT, nothing_parser>::value)); if (value == N) return delegate_parse(p, scan, save); return delegate_parse(d, scan, save); } }; /////////////////////////////////////////////////////////////////////////////// // Look through the case parser chain to test, if there is a default case // branch defined (returned by 'value'). template <typename CaseT, bool IsSimple = CaseT::is_simple> struct default_case; //////////////////////////////////////// template <typename ResultT, bool IsDefault> struct get_default_parser { template <typename ParserT> static ResultT get(parser<ParserT> const &p) { return default_case<typename ParserT::derived_t::left_t>:: get(p.derived().left()); } }; template <typename ResultT> struct get_default_parser<ResultT, true> { template <typename ParserT> static ResultT get(parser<ParserT> const &p) { return p.derived().right(); } }; //////////////////////////////////////// template <typename CaseT, bool IsSimple> struct default_case { // The 'value' constant is true, if the current case_parser or one of its // left siblings is a default_p generated case_parser. BOOST_STATIC_CONSTANT(bool, value = (CaseT::is_default || default_case<typename CaseT::left_t>::value)); // The 'is_epsilon' constant is true, if the current case_parser or one of // its left siblings is a default_p generated parser with an attached // epsilon_p (this is generated by the plain default_p). BOOST_STATIC_CONSTANT(bool, is_epsilon = ( (CaseT::is_default && CaseT::is_epsilon) || default_case<typename CaseT::left_t>::is_epsilon )); // The computed 'type' represents the type of the default case branch // parser (if there is one) or nothing_parser (if there isn't any default // case branch). typedef typename boost::mpl::if_c< CaseT::is_default, typename CaseT::right_embed_t, typename default_case<typename CaseT::left_t>::type >::type type; // The get function returns the parser attached to the default case branch // (if there is one) or an instance of a nothing_parser (if there isn't // any default case branch). template <typename ParserT> static type get(parser<ParserT> const &p) { return get_default_parser<type, CaseT::is_default>::get(p); } }; //////////////////////////////////////// template <typename ResultT, bool IsDefault> struct get_default_parser_simple { template <typename ParserT> static ResultT get(parser<ParserT> const &p) { return p.derived(); } }; template <typename ResultT> struct get_default_parser_simple<ResultT, false> { template <typename ParserT> static nothing_parser get(parser<ParserT> const &) { return nothing_p; } }; //////////////////////////////////////// // Specialization of the default_case template for the last (leftmost) element // of the case parser chain. template <typename CaseT> struct default_case<CaseT, true> { // The 'value' and 'is_epsilon' constant, the 'type' type and the function // 'get' are described above. BOOST_STATIC_CONSTANT(bool, value = CaseT::is_default); BOOST_STATIC_CONSTANT(bool, is_epsilon = ( CaseT::is_default && CaseT::is_epsilon )); typedef typename boost::mpl::if_c< CaseT::is_default, CaseT, nothing_parser >::type type; template <typename ParserT> static type get(parser<ParserT> const &p) { return get_default_parser_simple<type, value>::get(p); } }; /////////////////////////////////////////////////////////////////////////////// // The case_chain template calculates recursivly the depth of the left // subchain of the given case branch node. template <typename CaseT, bool IsSimple = CaseT::is_simple> struct case_chain { BOOST_STATIC_CONSTANT(int, depth = ( case_chain<typename CaseT::left_t>::depth + 1 )); }; template <typename CaseT> struct case_chain<CaseT, true> { BOOST_STATIC_CONSTANT(int, depth = 0); }; /////////////////////////////////////////////////////////////////////////////// // The chain_parser template is used to extract the type and the instance of // a left or a right parser, burried arbitrary deep inside the case parser // chain. template <int Depth, typename CaseT> struct chain_parser { typedef typename CaseT::left_t our_left_t; typedef typename chain_parser<Depth-1, our_left_t>::left_t left_t; typedef typename chain_parser<Depth-1, our_left_t>::right_t right_t; static left_t left(CaseT const &p) { return chain_parser<Depth-1, our_left_t>::left(p.left()); } static right_t right(CaseT const &p) { return chain_parser<Depth-1, our_left_t>::right(p.left()); } }; template <typename CaseT> struct chain_parser<1, CaseT> { typedef typename CaseT::left_t left_t; typedef typename CaseT::right_t right_t; static left_t left(CaseT const &p) { return p.left(); } static right_t right(CaseT const &p) { return p.right(); } }; template <typename CaseT> struct chain_parser<0, CaseT>; // shouldn't be instantiated /////////////////////////////////////////////////////////////////////////////// // Type computing meta function for calculating the type of the return value // of the used conditional switch expression template <typename TargetT, typename ScannerT> struct condition_result { typedef typename TargetT::template result<ScannerT>::type type; }; /////////////////////////////////////////////////////////////////////////////// template <typename LeftT, typename RightT, bool IsDefault> struct compound_case_parser : public binary<LeftT, RightT, parser<compound_case_parser<LeftT, RightT, IsDefault> > > { typedef compound_case_parser<LeftT, RightT, IsDefault> self_t; typedef binary_parser_category parser_category_t; typedef binary<LeftT, RightT, parser<self_t> > base_t; BOOST_STATIC_CONSTANT(int, value = RightT::value); BOOST_STATIC_CONSTANT(bool, is_default = IsDefault); BOOST_STATIC_CONSTANT(bool, is_simple = false); BOOST_STATIC_CONSTANT(bool, is_epsilon = ( is_default && boost::is_same<typename RightT::subject_t, epsilon_parser>::value )); compound_case_parser(parser<LeftT> const &lhs, parser<RightT> const &rhs) : base_t(lhs.derived(), rhs.derived()) {} template <typename ScannerT> struct result { typedef typename match_result<ScannerT, nil_t>::type type; }; template <typename ScannerT, typename CondT> typename parser_result<self_t, ScannerT>::type parse(ScannerT const& scan, CondT const &cond) const; template <int N1, typename ParserT1, bool IsDefault1> compound_case_parser< self_t, case_parser<N1, ParserT1, IsDefault1>, IsDefault1 > operator, (case_parser<N1, ParserT1, IsDefault1> const &p) const { // If the following compile time assertion fires, you've probably used // more than one default_p case inside the switch_p parser construct. BOOST_STATIC_ASSERT(!default_case<self_t>::value || !IsDefault1); // If this compile time assertion fires, you've probably want to use // more case_p/default_p case branches, than possible. BOOST_STATIC_ASSERT( case_chain<self_t>::depth < BOOST_SPIRIT_SWITCH_CASE_LIMIT ); typedef case_parser<N1, ParserT1, IsDefault1> right_t; return compound_case_parser<self_t, right_t, IsDefault1>(*this, p); } }; /////////////////////////////////////////////////////////////////////////////// // The parse_switch::do_ functions dispatch to the correct parser, which is // selected through the given conditional switch value. template <int Value, int Depth, bool IsDefault> struct parse_switch; /////////////////////////////////////////////////////////////////////////////// // // The following generates a couple of parse_switch template specializations // with an increasing number of handled case branches (for 1..N). // // template <int Value, bool IsDefault> // struct parse_switch<Value, N, IsDefault> { // // template <typename ParserT, typename ScannerT> // static typename parser_result<ParserT, ScannerT>::type // do_(ParserT const &p, ScannerT const &scan, long cond_value, // typename ScannerT::iterator_t const &save) // { // typedef ParserT left_t0; // typedef typename left_t0::left left_t1; // ... // // switch (cond_value) { // case left_tN::value: // return delegate_parse(chain_parser< // case_chain<ParserT>::depth, ParserT // >::left(p), scan, save); // ... // case left_t1::value: // return delegate_parse(chain_parser< // 1, left_t1 // >::right(p.left()), scan, save); // // case left_t0::value: // default: // typedef default_case<ParserT> default_t; // typedef default_delegate_parse< // Value, IsDefault, default_t::value> // default_parse_t; // // return default_parse_t::parse(cond_value, p.right(), // default_t::get(p), scan, save); // } // } // }; // /////////////////////////////////////////////////////////////////////////////// #define BOOST_SPIRIT_PARSE_SWITCH_TYPEDEFS(z, N, _) \ typedef typename BOOST_PP_CAT(left_t, N)::left_t \ BOOST_PP_CAT(left_t, BOOST_PP_INC(N)); \ /**/ #define BOOST_SPIRIT_PARSE_SWITCH_CASES(z, N, _) \ case (long)(BOOST_PP_CAT(left_t, N)::value): \ return delegate_parse(chain_parser<N, left_t1>::right(p.left()), \ scan, save); \ /**/ #define BOOST_SPIRIT_PARSE_SWITCHES(z, N, _) \ template <int Value, bool IsDefault> \ struct parse_switch<Value, BOOST_PP_INC(N), IsDefault> { \ \ template <typename ParserT, typename ScannerT> \ static typename parser_result<ParserT, ScannerT>::type \ do_(ParserT const &p, ScannerT const &scan, long cond_value, \ typename ScannerT::iterator_t const &save) \ { \ typedef ParserT left_t0; \ BOOST_PP_REPEAT_FROM_TO_ ## z(0, BOOST_PP_INC(N), \ BOOST_SPIRIT_PARSE_SWITCH_TYPEDEFS, _) \ \ switch (cond_value) { \ case (long)(BOOST_PP_CAT(left_t, BOOST_PP_INC(N))::value): \ return delegate_parse( \ chain_parser< \ case_chain<ParserT>::depth, ParserT \ >::left(p), scan, save); \ \ BOOST_PP_REPEAT_FROM_TO_ ## z(1, BOOST_PP_INC(N), \ BOOST_SPIRIT_PARSE_SWITCH_CASES, _) \ \ case (long)(left_t0::value): \ default: \ typedef default_case<ParserT> default_t; \ typedef \ default_delegate_parse<Value, IsDefault, default_t::value> \ default_parse_t; \ \ return default_parse_t::parse(cond_value, p.right(), \ default_t::get(p), scan, save); \ } \ } \ }; \ /**/ BOOST_PP_REPEAT(BOOST_PP_DEC(BOOST_SPIRIT_SWITCH_CASE_LIMIT), BOOST_SPIRIT_PARSE_SWITCHES, _) #undef BOOST_SPIRIT_PARSE_SWITCH_TYPEDEFS #undef BOOST_SPIRIT_PARSE_SWITCH_CASES #undef BOOST_SPIRIT_PARSE_SWITCHES /////////////////////////////////////////////////////////////////////////////// template <typename LeftT, typename RightT, bool IsDefault> template <typename ScannerT, typename CondT> inline typename parser_result< compound_case_parser<LeftT, RightT, IsDefault>, ScannerT >::type compound_case_parser<LeftT, RightT, IsDefault>:: parse(ScannerT const& scan, CondT const &cond) const { scan.at_end(); // allow skipper to take effect return parse_switch<value, case_chain<self_t>::depth, is_default>:: do_(*this, scan, cond(scan), scan.first); } /////////////////////////////////////////////////////////////////////////////// // The switch condition is to be evaluated from a parser result value. template <typename ParserT> struct cond_functor { typedef cond_functor<ParserT> self_t; cond_functor(ParserT const &p_) : p(p_) {} template <typename ScannerT> struct result { typedef typename parser_result<ParserT, ScannerT>::type::attr_t type; }; template <typename ScannerT> typename condition_result<self_t, ScannerT>::type operator()(ScannerT const &scan) const { typedef typename parser_result<ParserT, ScannerT>::type result_t; typedef typename result_t::attr_t attr_t; result_t result(p.parse(scan)); return !result ? attr_t() : result.value(); } typename ParserT::embed_t p; }; template <typename ParserT> struct make_cond_functor { typedef as_parser<ParserT> as_parser_t; static cond_functor<typename as_parser_t::type> do_(ParserT const &cond) { return cond_functor<typename as_parser_t::type>( as_parser_t::convert(cond)); } }; /////////////////////////////////////////////////////////////////////////////// // The switch condition is to be evaluated from a phoenix actor template <typename ActorT> struct cond_actor { typedef cond_actor<ActorT> self_t; cond_actor(ActorT const &actor_) : actor(actor_) {} template <typename ScannerT> struct result { typedef typename ::phoenix::actor_result<ActorT, ::phoenix::tuple<> >::type type; }; template <typename ScannerT> typename condition_result<self_t, ScannerT>::type operator()(ScannerT const& /*scan*/) const { return actor(); } ActorT const &actor; }; template <typename ActorT> struct make_cond_functor< ::phoenix::actor<ActorT> > { static cond_actor< ::phoenix::actor<ActorT> > do_(::phoenix::actor<ActorT> const &actor) { return cond_actor< ::phoenix::actor<ActorT> >(actor); } }; /////////////////////////////////////////////////////////////////////////////// // The switch condition is to be taken directly from the input stream struct get_next_token_cond { typedef get_next_token_cond self_t; template <typename ScannerT> struct result { typedef typename ScannerT::value_t type; }; template <typename ScannerT> typename condition_result<self_t, ScannerT>::type operator()(ScannerT const &scan) const { typename ScannerT::value_t val(*scan); ++scan.first; return val; } }; template <> struct make_cond_functor<get_next_token_cond> { static get_next_token_cond do_(get_next_token_cond const &cond) { return cond; } }; /////////////////////////////////////////////////////////////////////////////// } // namespace impl BOOST_SPIRIT_CLASSIC_NAMESPACE_END }} // namespace boost::spirit #endif // BOOST_SPIRIT_SWITCH_IPP
; A246172: a(n) = (n^2+9*n-8)/2. ; 1,7,14,22,31,41,52,64,77,91,106,122,139,157,176,196,217,239,262,286,311,337,364,392,421,451,482,514,547,581,616,652,689,727,766,806,847,889,932,976,1021,1067,1114,1162,1211,1261,1312,1364,1417,1471,1526,1582,1639,1697,1756,1816,1877,1939,2002,2066,2131,2197,2264,2332,2401,2471,2542,2614,2687,2761,2836,2912,2989,3067,3146,3226,3307,3389,3472,3556,3641,3727,3814,3902,3991,4081,4172,4264,4357,4451,4546,4642,4739,4837,4936,5036,5137,5239,5342,5446 add $0,6 bin $0,2 sub $0,14
;[]-----------------------------------------------------------------[] ;| CONSTRUC.ASM -- string constructors | ;[]-----------------------------------------------------------------[] ; ; $Copyright: 2005$ ; $Revision: 1.1.1.1 $ ; ; ;AnsiString& __fastcall operator =(const AnsiString& rhs); ;static AnsiString __fastcall StringOfChar(char ch, int count); %include 'constant.inc' EXTERN @FastString@Unique$qqrv PUBLIC @FastString@$bctr$qqrv PUBLIC @FastString@$bctr$qqrxo PUBLIC @FastString@$bctr$qqrxc PUBLIC @FastString@$bctr$qqrxuc PUBLIC @FastString@$bctr$qqrxs PUBLIC @FastString@$bctr$qqrxus PUBLIC @FastString@$bctr$qqrxi PUBLIC @FastString@$bctr$qqrxl PUBLIC @FastString@$bctr$qqrxui PUBLIC @FastString@$bctr$qqrxul PUBLIC @FastString@$bctr$qqrxj PUBLIC @FastString@$bctr$qqrxuj PUBLIC @FastString@$bctr$qqrxf PUBLIC @FastString@$bctr$qqrxd PUBLIC @FastString@$bctr$qqrxg PUBLIC @FastString@$bctr$qqrpxc PUBLIC @FastString@$bctr$qqrpxb PUBLIC @FastString@$bctr$qqrrx17System@AnsiString PUBLIC @FastString@$bctr$qqrrx17System@WideString PUBLIC @FastString@$bctr$qqrrx11MathVariant PUBLIC @FastString@$bctr$qqrrx10FastString PUBLIC @FastString@$bdtr$qqrv PUBLIC @FastString@$basg$qqrxo PUBLIC @FastString@$basg$qqrxc PUBLIC @FastString@$basg$qqrxuc PUBLIC @FastString@$basg$qqrxs PUBLIC @FastString@$basg$qqrxus PUBLIC @FastString@$basg$qqrxi PUBLIC @FastString@$basg$qqrxl PUBLIC @FastString@$basg$qqrxui PUBLIC @FastString@$basg$qqrxul PUBLIC @FastString@$basg$qqrxj PUBLIC @FastString@$basg$qqrxuj PUBLIC @FastString@$basg$qqrxf PUBLIC @FastString@$basg$qqrxd PUBLIC @FastString@$basg$qqrxg PUBLIC @FastString@$basg$qqrrx17System@AnsiString PUBLIC @FastString@$basg$qqrrx17System@WideString PUBLIC @FastString@$basg$qqrpxc PUBLIC @FastString@$basg$qqrpxb PUBLIC @FastString@$basg$qqrrx11MathVariant PUBLIC @FastString@$basg$qqrrx10FastString GLOBAL CopyString GLOBAL StringRedim ; EXTRN @Memblock@$bctr$qqrrx8Memblock ; EXTRN @Memblock@$bctr$qqri EXTRN @Memblock@$bdtr$qqrv ; EXTRN @Locale@GetSystemCodepage$qqrv EXTRN @Locale@$bctr$qqrv EXTRN @Memblock@Resize$qqrul EXTRN @Memblock@$bctr$qqrul section _TEXT StringRedim proc near ;in ;ecx: size of buffer ;eax: this ;carry flag: force new buffer ;out ;eax: new pointer of string buffer ;ebx: new pointer to begin of system area of string ;ecx: size of buffer ;edx: this ;edi: new pointer of string buffer ;carry flag: error push eax push ecx mov eax, [eax] mov edx, ecx jc StringDim_new or eax, eax jz StringDim_new sub eax, SIZEOF_FASTSTRING ; call @Memblock@$bctr$qqrrx8Memblock ; lea edx, [ebx+FastString.MemBlock - SIZEOF_FASTSTRING] call @Memblock@Resize$qqrul jmp StringRedim_exit StringDim_new: push eax push eax mov eax, esp call @Memblock@$bctr$qqrul pop ebx pop eax ; pop dword [ebx+FistString.MemBlock] ; mov ebx, [eax+MemBlock.Ptr] mov [ebx+FastString.MemBlock], eax StringRedim_exit: pop ecx pop edx jc StringRedim_error mov eax, ebx ; mov [eax+FastString.BufferSize], ecx lock inc dword ptr[ebx+FastString.RefCount] add eax, SIZEOF_FASTSTRING mov [edx], eax mov edi, eax StringRedim_error: ret ;StringDim proc near ;in ;ecx: size of buffer ;ebx: this ;out ;eax: new pointer of buffer ;carry flag: error ; push edx ; push eax ; push ecx ;StringDim endp @FastString@$bctr$qqrv proc near mov dword ptr [eax], 0 ret @FastString@$bdtr$qqrv proc near StringFree: ;in ;eax: this mov eax, [eax] or eax, eax jz StringFree_exit lock dec dword ptr[eax-SIZEOF_FASTSTRING+FastString.RefCount] jnz StringFree_exit sub eax, SIZEOF_FASTSTRING push dword ptr[eax+FastString.MemBlock] push eax mov eax, esp call @Memblock@$bdtr$qqrv pop eax pop eax StringFree_exit: ret Clear proc near push eax call StringFree pop eax mov dword ptr[eax], 0 ret @FastString@$basg$qqrxo proc near call Clear @FastString@$bctr$qqrxo: ret @FastString@$basg$qqrxc proc near ;eax: this ;dl: char call Clear @FastString@$bctr$qqrxc: push edx movsx edx, byte ptr[esp] pop ecx jmp CreateIntegerNumber @FastString@$basg$qqrxuc proc near ;eax: this ;dl: unsigned char call Clear @FastString@$bctr$qqrxuc: and edx,0ffh xor ecx, ecx jmp Construct_string_from_number @FastString@$basg$qqrxs proc near ;eax: this ;edx: char call Clear @FastString@$bctr$qqrxs: push edx movsx edx, word ptr[esp] pop ecx jmp CreateIntegerNumber @FastString@$basg$qqrxus proc near ;eax: this ;edx: unsigned char call Clear @FastString@$bctr$qqrxus: and edx,0ffffh xor ecx, ecx jmp Construct_string_from_number @FastString@$basg$qqrxi proc near @FastString@$basg$qqrxl: call Clear @FastString@$bctr$qqrxi: @FastString@$bctr$qqrxl: ;eax: this ;edx: char mov ecx, edx CreateIntegerNumber: sar ecx, 31 stc jmp Construct_string_from_number ;Ctr_convert: ; mov ecx, INT_STRING_LENGTH * SIZEOF_CHAR + SIZEOF_FASTSTRING ; call StringDim ; xchg edi, [esp] ; xchg eax, edi ; push edi ; push ebx ; test dl, SIGN_INT ; jnz short Ctr_convert_plus ; test eax, eax ; jns short Ctr_convert_plus ; neg eax ; mov byte ptr[edi], '-' ; jmp short Ctr_convert_add1 ;Ctr_convert_plus: ; test dl, FORCE_SIGN ; jz Ctr_convert_tostring ; mov byte ptr[edi], '+' ;Ctr_convert_add1: ; inc edi ;Ctr_convert_tostring: ; mov ecx, 10 ; mov ebx, 1 ;Ctr_convert_loop: ; cmp eax, ecx ; jbe short Ctr_convert_loop_exit ; xor edx, edx ; div ecx ; push edx ; inc ebx ; jmp short Ctr_convert_loop ;Ctr_convert_loop_exit: ; add al, '0' ; stosb ; dec ebx ; jz Ctr_convert_loop1_exit ; pop eax ; jmp Ctr_convert_loop_exit ;Ctr_convert_loop1_exit: ; pop ebx ; sub edi, [esp] ; pop eax ; mov [eax-SIZEOF_FASTSTRING+FastString.Length], edi ; pop edi ; pop eax ; ret ;@FastString@$basg$qqrxl: ;eax: this ;edx: char ; push eax ; push edx ;Asg_int_convert: ; xor dl, dl ;Asg_convert1: ; call @FastString@Unique$qqrv ;Asg_convert: ; mov ecx, INT_STRING_LENGTH * SIZEOF_CHAR + SIZEOF_FASTSTRING ; call StringRedim ; xchg edi, [esp] ; xchg eax, edi ; push edi ; push ebx ; test dl, SIGN_INT ; jnz Asg_convert_plus ; test eax, eax ; jns Asg_convert_plus ; neg eax ; mov byte ptr[edi], '-' ; jmp Asg_convert_add1 ;Asg_convert_plus: ; test dl, FORCE_SIGN ; jz Asg_convert_tostring ; mov byte ptr[edi], '+' ;Asg_convert_add1: ; inc edi ;Asg_convert_tostring: ; mov ecx, 10 ; mov ebx, 1 ;Asg_convert_loop: ; cmp eax, ecx ; jbe Asg_convert_loop_exit ; xor edx, edx ; div ecx ; push edx ; inc ebx ; jmp Asg_convert_loop ;Asg_convert_loop_exit: ; add al, '0' ; stosb ; dec ebx ; jz Asg_convert_loop1_exit ; pop eax ; jmp Asg_convert_loop_exit ;Asg_convert_loop1_exit: ; pop ebx ; sub edi, [esp] ; pop eax ; mov [eax-SIZEOF_FASTSTRING+FastString.Length], edi ; pop edi ; pop eax ; ret @FastString@$basg$qqrxui proc near @FastString@$basg$qqrxul: ;Asg_dword_convert: ;eax: this ;edx: unsigned char call Clear @FastString@$bctr$qqrxui: @FastString@$bctr$qqrxul: ;Ctr_convert: xor ecx, ecx jmp Construct_string_from_number @FastString@$basg$qqrxj proc near ;eax: this ;esp[4,8]: qword call Clear @FastString@$bctr$qqrxj: stc Construct_string_from_qword: pop edx pop ecx xchg [esp], edx mov dword ptr [eax], 0 ; jmp Construct_string_from_number ; ; clc ;Assign_qword_to_string: ; pop edx ; pop ecx ; xchg [esp], edx ;Assign_number_to_string: ; call @FastString@Unique$qqrv Construct_string_from_number: ;in ecx:edx - number ;c = 0 - signed integer number push ebx push esi push edi push eax push ecx ; mov ebx, ecx mov ecx, QWORD_STRING_LENGTH * SIZEOF_CHAR + SIZEOF_FASTSTRING pushfd ; call StringRedim ;out - eax: pointer ; StringRedim ;out - eax: pointer mov esi, edx call StringRedim ;out - eax: pointer jc Assign_StringRedim_error ; push eax ; push ecx ; mov eax, [eax] ; or eax, eax ; jz Assign_StringDim_new ; sub eax, SIZEOF_FASTSTRING ; call MemoryReAlloc ; jmp Assign_StringRedim_exit ;Assign_StringDim_new: ; call MemoryAlloc ;Assign_StringRedim_exit: ; pop ecx ; jc Assign_StringRedim_error ; mov esi, eax ; mov [eax+FastString.BufferSize], ecx ; add eax, SIZEOF_FASTSTRING ; pop edx ; mov [edx], eax ; mov edi, eax popfd pop eax ; xchg edi, [esp] ; xchg eax, edi ; SignCheck ; test ch, SIGN_INT ; jnz SignCheck_plus push edi jnc Assign_SignCheck_plus test eax, eax jns Assign_SignCheck_plus not eax not esi add esi, 1 adc eax, 0 mov byte ptr[edi], '-' jmp Assign_SignCheck_add1 Assign_SignCheck_plus: test byte ptr[ebx+FastString.Mode], FORCE_SIGN jz Assign_SignCheck_exit mov byte ptr[edi], '+' Assign_SignCheck_add1: inc edi Assign_SignCheck_exit: ; mov eax, ebx ; mov ebx, edx xor ecx, ecx call Asg_convert_loop pop eax sub edi, eax mov [eax-SIZEOF_FASTSTRING+FastString.Length], edi Assign_exit: pop eax pop edi pop esi pop ebx ret Assign_StringRedim_error: ; pop eax ; pop edx popfd pop ecx jmp Assign_exit @FastString@$basg$qqrxuj proc near call Clear @FastString@$bctr$qqrxuj: clc jmp Construct_string_from_qword @FastString@$basg$qqrxf proc near call Clear @FastString@$bctr$qqrxf: mov ecx, 7 AssignFloat: pop edx fld dword ptr[esp] mov [esp], edx mov dword ptr[eax], 0 push eax push ebx push edi push ecx mov ecx, FLOAT_STRING_LENGTH * SIZEOF_CHAR + SIZEOF_FASTSTRING call StringRedim ;out - eax: pointer pop ecx jc AssignFloat_StringRedim_error ; mov edi, eax push edi call FloatSignCheck call StdFloatConvert pop eax sub edi, eax mov [eax-SIZEOF_FASTSTRING+FastString.Length], edi pop edi pop ebx pop eax ret AssignFloat_StringRedim_error: pop edi pop ebx pop eax ret @FastString@$basg$qqrxd proc near call Clear @FastString@$bctr$qqrxd: mov ecx, 12 jmp AssignFloat @FastString@$basg$qqrxg proc near call Clear @FastString@$bctr$qqrxg: mov ecx, 20 jmp AssignFloat GetBufferSizeFromStringLength proc near cmp ecx, 20 ja Size_greater_20W mov ecx, 20 ret Size_greater_20W: cmp ecx, 0ffffh ja Size_greater_64KW shr ecx, 1 lea ecx, [ecx+ecx*2] ret Size_greater_64KW: cmp ecx, 7ffffh ja Size_greater_512KW sub ecx, 10000h shr ecx, 4 neg ecx add ecx, 8000h ret Size_greater_512KW: add ecx, 400h ret @FastString@$basg$qqrrx17System@AnsiString proc near call Clear @FastString@$bctr$qqrrx17System@AnsiString: mov edx, [edx] or edx, edx jnz @FastString@$bctr$qqrpxc Create_from_ansistring_empty: mov [eax], ecx ret @FastString@$basg$qqrpxc: call Clear @FastString@$bctr$qqrpxc: push ebx push esi push edi mov esi, edx ; mov ecx, [edx-SIZEOF_INT] mov ecx, -1 mov edi, edx push eax xor eax, eax repnz scasb pop eax not ecx dec ecx push ecx call GetBufferSizeFromStringLength add ecx, SIZEOF_FASTSTRING stc call StringRedim pop ecx mov [ebx+FastString.Length], ecx mov byte ptr[ebx+FastString.Mode], 0 call SetupDefaultCodepage jmp CopyString @FastString@$basg$qqrrx17System@WideString proc near call Clear @FastString@$bctr$qqrrx17System@WideString: mov edx, [edx] or edx, edx jz Create_from_ansistring_empty jmp @FastString@$bctr$qqrpxb @FastString@$basg$qqrpxb: call Clear @FastString@$bctr$qqrpxb: push ebx push esi push edi mov esi, edx mov ecx, -1 ; mov ecx, [edx - SIZEOF_INT] mov edi, edx push eax xor eax, eax repnz scasw pop eax not ecx ; shr ecx, 1 dec ecx push ecx call GetBufferSizeFromStringLength shl ecx, 1 add ecx, SIZEOF_FASTSTRING stc call StringRedim pop ecx mov [ebx + FastString.Length], ecx shl ecx, 1 mov byte ptr[ebx + FastString.Mode], 0 ; mov [ebx + FastString.CodePage.Type], WCHARCP mov eax, [ebx + FastString.Locale], mov byte ptr[eax + Locale.CPType], WCHARCP jmp CopyString ret @FastString@$basg$qqrrx11MathVariant proc near call Clear @FastString@$bctr$qqrrx11MathVariant: ret @FastString@$basg$qqrrx10FastString proc near call Clear @FastString@$bctr$qqrrx10FastString: mov ecx, [edx] lock inc dword ptr[ecx-SIZEOF_FASTSTRING+FastString.RefCount] mov [eax], ecx ret SetupDefaultCodepage proc near ;in ;ebx: pointer to FastString data ; ;ecx: destructed push ecx push edx ; call @Locale@GetSystemCodepage$qqrv lea eax, [ebx+FastString.Locale] call @Locale@$bctr$qqrv ; mov ecx, [ebx+FastString.Locale] ; mov [eax+Locale.CP], ax ; mov byte ptr[eax+Locale.CPType], 0 pop edx pop ecx ; mov [ebx+FastString.CodePage.Page], 1251 ; mov [ebx+FastString.CodePage.Type], WINANSICP ret Asg_convert_loop proc near ;in ;eax:esi: number ;ecx = 0ffh if zero is need to be counted ;eax, ebx, ecx, edx: destroyed ;Asg_convert_loop_init: mov ebx, 10 Asg_convert_loop1: xor edx, edx Asg_convert_loop2: inc ch cmp eax, ebx jb Asg_convert_loop_check div ebx push edx or cl, cl jz Asg_convert_loop1 or edx, edx jnz Asg_convert_loop_clear_zero mov cl, ch jmp Asg_convert_loop1 Asg_convert_loop_clear_zero: mov cl, 0ffh jmp Asg_convert_loop1 Asg_convert_loop_check: test ecx, ecx js Asg_convert_loop_back or ecx, 80000000h mov edx, eax mov eax, esi dec ch jmp Asg_convert_loop2 Asg_convert_loop_back1: mov al, dl Asg_convert_loop_back: add al, '0' stosb dec ch jz Asg_convert_loop_exit pop eax jmp Asg_convert_loop_back Asg_convert_loop_exit: ret FloatSignCheck proc near ;in ;edi: pointer to string buffer ;ebx: pointer to begin of faststring buffer ;st0: floating point value ;out ;st0: floating point absolute value ftst ; fstsw ax jfge FloatSignCheck_plus fabs mov byte ptr[edi], '-' inc edi ret ; jmp FloatSignCheck_add1 FloatSignCheck_plus: test byte ptr[ebx+FastString.Mode], FORCE_SIGN jz FloatSignCheck_exit mov byte ptr[edi], '+' FloatSignCheck_add1: inc edi FloatSignCheck_exit: ret StdFloatConvert proc near ;in ;edi: pointer to string buffer ;ecx: number of symbols after floating point ;st0: floating point absolute value fld st0 fld tbyte ptr[float_1e10] fcomp st1 jfl ExpFloatConvert frndint fsub st1, st0 sub esp, 10h fistp qword ptr[esp] push ecx fild dword ptr[esp] pop eax xor ecx, ecx fld tbyte ptr[float_10] fyl2x fld st0 frndint fsub st1,st0 fxch st1 f2xm1 fld1 faddp st1, st0 fscale fxch st1 ffree st0 fincstp fmulp st1, st0 fistp qword ptr[esp+8] pop esi pop eax call Asg_convert_loop pop esi pop ebx mov eax, ebx or eax, esi jz StdFloatConvert_int_value call GetFloatingPointSymbol stosb mov eax, ebx mov ecx, 0ffh call Asg_convert_loop StdFloatConvert_int_value: ret ; fld tbyte ptr[float_10] ; fxch st1 ; fld st0 ; fincstp ;StdFloatConvert_loop1: ; fcom st1 ; jfl StdFloatConvert_check_zero ; fprem ; push eax ; inc dl ; fistp dword ptr[esp] ; fdiv st6, st0 ; fld st6 ; cmp byte ptr[esp], 0ah ; jnz StdFloatConvert_loop1 ; mov byte ptr[esp], 0 ; jmp StdFloatConvert_loop1 ;StdFloatConvert_check_zero: ; push eax ; fistp dword ptr[esp] ; inc dl ;StdFloatConvert_loop1_back: ; pop eax ; add al, '0' ; stosb ; dec dl ; jnz StdFloatConvert_loop1_back ;StdFloatConvert_loop1_back_exit: ; ffree st6 ; fxch st1 ; push ecx ; fild dword ptr[esp] ; pop ecx ; fld st2 ; fyl2x ; fld st0 ; frndint ; fsub st1,st0 ; fxch st1 ; f2xm1 ; fld1 ; faddp st1, st0 ; fscale ; fxch st1 ; ffree st0 ; fincstp ; fmulp st1, st0 ; fld st0 ; fincstp ; mov dh, cl ;StdFloatConvert_loop: ; fprem ; push eax ; fistp dword ptr[esp] ; fdiv st6, st0 ; fld st6 ; cmp byte ptr[esp], 0ah ; jnz StdFloatConvert_loop_next ; mov [esp], ch ;StdFloatConvert_loop_next: ; cmp dh, cl ; jnz StdFloatConvert_loop_check ; cmp ch, [esp] ; jz StdFloatConvert_loop_check ; mov dh, dl ;StdFloatConvert_loop_check: ; inc dl ; cmp dl, cl ; jb StdFloatConvert_loop ; call GetFloatingPointSymbol ; stosb ;StdFloatConvert_loop_back: ; pop eax ; cmp dh, dl ; jae StdFloatConvert_loop_back_next ; add al, '0' ; stosb ;StdFloatConvert_loop_back_next: ; dec dl ; jnz StdFloatConvert_loop_back ;StdFloatConvert_loop_back_exit: ; ret ; fld tbyte ptr[float_1_5] ; fld1 ; fscale ; sub esp, 12 ; fst tbyte ptr[esp] fld st0 fld tbyte ptr[float_1e10] fcomp st1 ; fstsw ax ; test ah,20;>= ; jz ExpFloatConvert jfl ExpFloatConvert xor edx, edx frndint fsub st1, st0 fld tbyte ptr[float_10] fxch st1 fld st0 fincstp StdFloatConvert_loop1: fcom st1 jfl StdFloatConvert_check_zero fprem ; fld tbyte ptr[float_0_1] ; fmulp st1, st0 ; fld st0 ; frndint ; fxch st1 ; fsub st0, st1 ; fld tbyte ptr[float_10] ; fmulp st1, st0 push eax inc dl fistp dword ptr[esp] fdiv st6, st0 fld st6 cmp byte ptr[esp], 0ah jnz StdFloatConvert_loop1 mov byte ptr[esp], 0 jmp StdFloatConvert_loop1 StdFloatConvert_check_zero: ; or dh, dh ; jnz StdFloatConvert_loop1_back push eax fistp dword ptr[esp] inc dl StdFloatConvert_loop1_back: pop eax add al, '0' stosb dec dl jnz StdFloatConvert_loop1_back StdFloatConvert_loop1_back_exit: ffree st6 fxch st1 ; push ecx ; fild dword ptr[esp] ; pop ecx ; fldl2t ; fmulp st1 ; fld st0 ; frndint ; fsub st1, st0 ; fxch st1 ; fld1 ; fscale ; fscale push ecx fild dword ptr[esp] pop ecx fld st2 fyl2x fld st0 frndint fsub st1,st0 fxch st1 f2xm1 fld1 faddp st1, st0 fscale fxch st1 ffree st0 fincstp fmulp st1, st0 ; fld tbyte ptr[float_10] ; fxch st1 fld st0 fincstp mov dh, cl StdFloatConvert_loop: fprem ; fld tbyte ptr[float_0_1] ; fmulp st1, st0 ; fld st0 ; frndint ; fxch st1 ; fsub st0, st1 ; fld tbyte ptr[float_10] ; fmulp st1, st0 push eax fistp dword ptr[esp] fdiv st6, st0 fld st6 cmp byte ptr[esp], 0ah jnz StdFloatConvert_loop_next mov [esp], ch ;StdFloatConvert_loop_not_10: ; cmp ch, [esp] ; jnz StdFloatConvert_loop_not_zero ;StdFloatConvert_loop_increment_zero_counter: ; inc dh ; jmp StdFloatConvert_loop_next ;StdFloatConvert_loop_not_zero: ; xor dh, dh StdFloatConvert_loop_next: cmp dh, cl jnz StdFloatConvert_loop_check cmp ch, [esp] jz StdFloatConvert_loop_check mov dh, dl StdFloatConvert_loop_check: inc dl cmp dl, cl jb StdFloatConvert_loop ; fld tbyte ptr[float_0_1] ; fmulp st1, st0 ; fdecstp ; ffree st0 ; fdecstp ; ffree st0 ; fdecstp call GetFloatingPointSymbol stosb StdFloatConvert_loop_back: pop eax cmp dh, dl jae StdFloatConvert_loop_back_next add al, '0' stosb StdFloatConvert_loop_back_next: dec dl jnz StdFloatConvert_loop_back StdFloatConvert_loop_back_exit: ret ;; sub esp, 12 ;; fst tbyte ptr[esp] ; fld st0 ; fld tbyte ptr[float_1e10] ; fcomp st1 ;; fstsw ax ;; test ah,20;>= ;; jz ExpFloatConvert ; jfl ExpFloatConvert ; xor edx, edx ; frndint ; fsub st1, st0 ; fxch st1 ; lea eax, [edx+ecx*4] ; sub esp, eax ;StdFloatConvert_loop: ; fld tbyte ptr[float_10] ; fmulp st1, st0 ; fld st0 ; frndint ; fsub st1, st0 ; push eax ;; fistp dword ptr[esp] ; fistp dword ptr[esp+edx*4] ; inc dl ; cmp ch, [esp] ; jz StdFloatConvert_loop_zero_value ; xor dh, dh ; jmp StdFloatConvert_loop_check_cond ;StdFloatConvert_loop_zero_value: ; inc dh ;StdFloatConvert_loop_check_cond: ; cmp dl, cl ; jb StdFloatConvert_loop ; sub dl, dh ; xor dh, dh ;; fld tbyte ptr[esp] ; ffree st0 ; fincstp ;StdFloatConvert_loop1: ; ftst ;; fstsw ax ;; test ah, 10 ;; jnz StdFloatConvert_check_zero ; jfe StdFloatConvert_check_zero ; fld tbyte ptr[float_0_1] ; fmulp st1, st0 ; fld st0 ; frndint ; fxch st1 ; fsub st0, st1 ; fld tbyte ptr[float_10] ; fmulp st1, st0 ; push eax ; inc dh ; fistp dword ptr[esp] ; jmp StdFloatConvert_loop1 ;StdFloatConvert_check_zero: ; or dh, dh ; jnz StdFloatConvert_loop_back ; push 0 ; inc dh ;StdFloatConvert_loop_back: ; pop eax ; add al, '0' ; stosb ; dec dh ; jnz StdFloatConvert_loop_back ; or dl, dl ; jz StdFloatConvert_exit ; call GetFloatingPointSymbol ; stosb ;; xor eax, eax ;; sub cl, dl ;; mov al, cl ;; lea esp, [esp+eax*4] ;StdFloatConvert_loop_back1: ; pop eax ; add al, '0' ; stosb ; dec cl ; dec dl ; jnz StdFloatConvert_loop_back1 ;; add esp, 12 ;StdFloatConvert_exit: ; lea esp, [esp+ecx*4] ; ret ExpFloatConvert proc near ret GetFloatingPointSymbol proc near mov eax, ',' ret CopyString: mov edx, ecx shr ecx, 2 repz movsd and edx, 3 jz CopyString_exit mov ecx, edx repz movsb CopyString_exit: pop edi pop esi pop ebx ret section _DATA float_1e10: db 0,0,0,0,0,0f9h,2,95h,20h,40h ;float_0_1 label tbyte ; db 0,0d0h,0cch,0cch,0cch,0cch,0cch,0cch,0fbh,3fh float_10: db 0,0,0,0,0,0,0,0a0h,2,40h ;float_1_5 label tbyte ; db 0,0,0,0,0,0,0,0c0h,0ffh,3fh ;end
; A331147: Triangle read by rows: T(n,k) (n>=k>=1) = floor((n/k)*floor(n/k)). ; Submitted by Christian Krause ; 1,4,1,9,1,1,16,4,1,1,25,5,1,1,1,36,9,4,1,1,1,49,10,4,1,1,1,1,64,16,5,4,1,1,1,1,81,18,9,4,1,1,1,1,1,100,25,10,5,4,1,1,1,1,1,121,27,11,5,4,1,1,1,1,1,1,144,36,16,9,4,4,1,1,1,1,1,1,169,39,17,9,5,4,1,1,1,1,1,1,1 lpb $0 add $1,1 sub $0,$1 lpe add $0,1 add $1,1 mov $2,$1 div $1,$0 mul $2,$1 div $2,$0 mov $0,$2
; A304833: a(n) = 3*n^2 + 38*n - 76 (n>=2). ; 12,65,124,189,260,337,420,509,604,705,812,925,1044,1169,1300,1437,1580,1729,1884,2045,2212,2385,2564,2749,2940,3137,3340,3549,3764,3985,4212,4445,4684,4929,5180,5437,5700,5969,6244,6525,6812,7105,7404,7709,8020,8337,8660,8989,9324,9665,10012,10365,10724,11089,11460,11837,12220,12609,13004,13405,13812,14225,14644,15069,15500,15937,16380,16829,17284,17745,18212,18685,19164,19649,20140,20637,21140,21649,22164,22685,23212,23745,24284,24829,25380,25937,26500,27069,27644,28225,28812,29405,30004,30609,31220,31837,32460,33089,33724,34365,35012,35665,36324,36989,37660,38337,39020,39709,40404,41105,41812,42525,43244,43969,44700,45437,46180,46929,47684,48445,49212,49985,50764,51549,52340,53137,53940,54749,55564,56385,57212,58045,58884,59729,60580,61437,62300,63169,64044,64925,65812,66705,67604,68509,69420,70337,71260,72189,73124,74065,75012,75965,76924,77889,78860,79837,80820,81809,82804,83805,84812,85825,86844,87869,88900,89937,90980,92029,93084,94145,95212,96285,97364,98449,99540,100637,101740,102849,103964,105085,106212,107345,108484,109629,110780,111937,113100,114269,115444,116625,117812,119005,120204,121409,122620,123837,125060,126289,127524,128765,130012,131265,132524,133789,135060,136337,137620,138909,140204,141505,142812,144125,145444,146769,148100,149437,150780,152129,153484,154845,156212,157585,158964,160349,161740,163137,164540,165949,167364,168785,170212,171645,173084,174529,175980,177437,178900,180369,181844,183325,184812,186305,187804,189309,190820,192337,193860,195389,196924,198465 mov $1,3 mul $1,$0 add $1,50 mul $1,$0 add $1,12
; A170383: Number of reduced words of length n in Coxeter group on 38 generators S_i with relations (S_i)^2 = (S_i S_j)^43 = I. ; 1,38,1406,52022,1924814,71218118,2635070366,97497603542,3607411331054,133474219248998,4938546112212926,182726206151878262,6760869627619495694,250152176221921340678,9255630520211089605086 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,37 lpe mov $0,$2 div $0,37
// // Created by Haoyu Huang on 2/12/20. // Copyright (c) 2020 University of Southern California. All rights reserved. // #include <fmt/core.h> #include "rdma_write_server_worker.h" namespace nova { void RDMAWRITEServerWorker::AddCompleteTasks( const std::vector<nova::ServerWorkerCompleteTask> &tasks) { mutex_.lock(); for (auto &task : tasks) { async_cq_.push_back(task); } mutex_.unlock(); } void RDMAWRITEServerWorker::AddCompleteTask( const nova::ServerWorkerCompleteTask &task) { mutex_.lock(); async_cq_.push_back(task); mutex_.unlock(); } void RDMAWRITEServerWorker::AddAsyncTask( const nova::ServerWorkerAsyncTask &task) { async_workers_[task.dc_req_id % async_workers_.size()]->AddTask(task); } int RDMAWRITEServerWorker::PullAsyncCQ() { int nworks = 0; mutex_.lock(); nworks = async_cq_.size(); while (!async_cq_.empty()) { auto &task = async_cq_.front(); if (task.request_type == BenchRequestType::BENCH_PERSIST) { if (!is_local_disk_bench_) { char *sendbuf = rdma_broker_->GetSendBuf( task.remote_server_id); sendbuf[0] = BenchRequestType::BENCH_PERSIST_RESPONSE; uint32_t msg_size = 1; rdma_broker_->PostSend(sendbuf, msg_size, task.remote_server_id, task.dc_req_id); } req_context_.erase(task.dc_req_id); } else { NOVA_ASSERT(false); } NOVA_LOG(DEBUG) << fmt::format( "server[{}]: persist complete req:{} for server {}", thread_id_, task.dc_req_id, task.remote_server_id); async_cq_.pop_front(); } mutex_.unlock(); if (nworks > 0 && !is_local_disk_bench_) { rdma_broker_->FlushPendingSends(); } return nworks; } RDMAWRITEServerWorker::RDMAWRITEServerWorker(uint32_t max_run_time, uint32_t write_size_kb, bool is_local_disk_bench, bool eval_disk_horizontal_scalability, uint32_t server_id) : max_run_time_(max_run_time), write_size_kb_(write_size_kb), is_local_disk_bench_(is_local_disk_bench), eval_disk_horizontal_scalability_( eval_disk_horizontal_scalability), server_id_(server_id) { } void RDMAWRITEServerWorker::Start() { struct ::timeval start_timeval; ::gettimeofday(&start_timeval, nullptr); int64_t start_unix_time = start_timeval.tv_sec; NOVA_LOG(INFO) << fmt::format("worker[{}]: Started", thread_id_); if (is_local_disk_bench_) { // uint32_t scid = mem_manager_->slabclassid(thread_id_, // write_size_kb_ * // 1024); // char *buf = mem_manager_->ItemAlloc(thread_id_, scid); // RDMA_ASSERT(buf); // // std::string path = fmt::format("{}/{}", table_path_, thread_id_); // mkdirs(path.c_str()); // MockRTable *rtable = new MockRTable(env_, path, rtable_size_, // max_num_rtables_); while (true) { rtable_->Read(4096); // int read = rand() % 100; // if (read <= 1) { // rtable->Persist(buf, write_size_kb_ * 1024); // } else { // if () { // // } else { // rtable->Persist(buf, write_size_kb_ * 1024); // } // } // ServerWorkerAsyncTask task = {}; // task.local_buf = buf; // task.dc_req_id = processed_number_of_req_; // task.remote_server_id = 0; // task.request_type = BenchRequestType::BENCH_PERSIST; // task.cc_server_thread_id = thread_id_; // AddAsyncTask(task); // // while (PullAsyncCQ() != 1); processed_number_of_req_ += 1; if (processed_number_of_req_ % 10 == 0) { struct ::timeval timeval; ::gettimeofday(&timeval, nullptr); int64_t unix_time = timeval.tv_sec; if (unix_time - start_unix_time > max_run_time_) { break; } } } return; } rdma_broker_->Init(rdma_ctrl_); while (true) { if (eval_disk_horizontal_scalability_ && server_id_ != 0) { // rdma_store_->PollSQ(); // rdma_store_->PollRQ(); PullAsyncCQ(); processed_number_of_req_ += 1; if (processed_number_of_req_ % 10000 == 0) { struct ::timeval timeval; ::gettimeofday(&timeval, nullptr); int64_t unix_time = timeval.tv_sec; if (unix_time - start_unix_time > max_run_time_) { break; } } continue; } uint32_t req_id = client_->Initiate(); processed_number_of_req_ += 1; while (!client_->IsDone(req_id)) { // rdma_store_->PollSQ(); // rdma_store_->PollRQ(); PullAsyncCQ(); } if (processed_number_of_req_ % 1000 == 0) { struct ::timeval timeval; ::gettimeofday(&timeval, nullptr); int64_t unix_time = timeval.tv_sec; if (unix_time - start_unix_time > max_run_time_) { break; } } } NOVA_LOG(INFO) << fmt::format("worker[{}]: Prepare to terminate", thread_id_); usleep(100000); for (int i = 0; i < 1000000; i++) { // rdma_store_->PollSQ(); // rdma_store_->PollRQ(); PullAsyncCQ(); } } bool RDMAWRITEServerWorker::ProcessRDMAWC(ibv_wc_opcode type, uint64_t wr_id, int remote_server_id, char *buf, uint32_t req_id, bool *new_request) { bool processed_by_client = client_->ProcessRDMAWC(type, wr_id, remote_server_id, buf, req_id, new_request); bool processed_by_server = false; switch (type) { case IBV_WC_SEND: processed_by_server = true; break; case IBV_WC_RDMA_WRITE: break; case IBV_WC_RDMA_READ: processed_by_server = true; break; case IBV_WC_RECV: case IBV_WC_RECV_RDMA_WITH_IMM: auto it = req_context_.find(req_id); if (it != req_context_.end()) { // Mark as written. processed_by_server = true; NOVA_ASSERT(it->second.local_buf[0] == '1'); NOVA_LOG(DEBUG) << fmt::format( "server[{}]: written req:{} for server {}", thread_id_, req_id, remote_server_id); if (buf[0] == BenchRequestType::BENCH_PERSIST) { ServerWorkerAsyncTask task = {}; task.request_type = BenchRequestType::BENCH_PERSIST; task.remote_server_id = remote_server_id; task.local_buf = it->second.local_buf; task.dc_req_id = req_id; task.cc_server_thread_id = thread_id_; AddAsyncTask(task); NOVA_LOG(DEBUG) << fmt::format( "server[{}]: persist req:{} for server {}", thread_id_, req_id, remote_server_id); } break; } if (buf[0] == BenchRequestType::BENCH_ALLOCATE) { uint64_t asize = leveldb::DecodeFixed64(buf + 1); uint64_t size = write_size_kb_ * 1024; NOVA_ASSERT(asize == size); uint32_t scid = mem_manager_->slabclassid(thread_id_, size); char *local_buf = mem_manager_->ItemAlloc(thread_id_, scid); NOVA_ASSERT(local_buf); local_buf[0] = '2'; RequestContext ctx = {}; ctx.local_buf = local_buf; req_context_[req_id] = ctx; char *sendbuf = rdma_broker_->GetSendBuf(remote_server_id); sendbuf[0] = BenchRequestType::BENCH_ALLOCATE_RESPONSE; leveldb::EncodeFixed64(sendbuf + 1, (uint64_t) (local_buf)); rdma_broker_->PostSend(sendbuf, 9, remote_server_id, req_id); processed_by_server = true; NOVA_LOG(DEBUG) << fmt::format( "server[{}]: allocate req:{} for server {}", thread_id_, req_id, remote_server_id); } break; } NOVA_ASSERT((processed_by_client || processed_by_server)); NOVA_ASSERT(!(processed_by_client && processed_by_server)); } RDMAWRITEDiskWorker::RDMAWRITEDiskWorker(const std::string &table_path, uint32_t write_size_kb, uint32_t rtable_size, uint32_t max_num_rtables) : table_path_(table_path), write_size_kb_(write_size_kb), rtable_size_(rtable_size), max_num_rtables_(max_num_rtables) { } void RDMAWRITEDiskWorker::Init() { std::string path = fmt::format("{}/{}", table_path_, worker_id_); mkdirs(path.c_str()); rtable_ = new MockRTable(env_, path, rtable_size_, max_num_rtables_); sem_init(&sem_, 0, 0); } void RDMAWRITEDiskWorker::AddTask( const nova::ServerWorkerAsyncTask &task) { mutex_.lock(); queue_.push_back(task); mutex_.unlock(); sem_post(&sem_); } void RDMAWRITEDiskWorker::Start() { NOVA_LOG(DEBUG) << "CC server worker started"; while (is_running_) { sem_wait(&sem_); std::vector<ServerWorkerAsyncTask> tasks; mutex_.lock(); while (!queue_.empty()) { auto task = queue_.front(); tasks.push_back(task); queue_.pop_front(); } mutex_.unlock(); if (tasks.empty()) { continue; } std::map<uint32_t, std::vector<ServerWorkerCompleteTask>> t_tasks; for (auto &task : tasks) { ServerWorkerCompleteTask ct = {}; ct.remote_server_id = task.remote_server_id; ct.dc_req_id = task.dc_req_id; ct.request_type = task.request_type; if (task.request_type == BenchRequestType::BENCH_PERSIST) { rtable_->Persist(task.local_buf, write_size_kb_ * 1024); uint32_t scid = mem_manager_->slabclassid( task.cc_server_thread_id, write_size_kb_ * 1024); mem_manager_->FreeItem(task.cc_server_thread_id, task.local_buf, scid); } else { NOVA_ASSERT(false); } NOVA_LOG(DEBUG) << fmt::format( "CCWorker: Working on t:{} ss:{} req:{} type:{}", task.cc_server_thread_id, ct.remote_server_id, ct.dc_req_id, ct.request_type); t_tasks[task.cc_server_thread_id].push_back(ct); } for (auto &it : t_tasks) { cc_servers_[it.first]->AddCompleteTasks(it.second); } } } }
; A253472: Square Pairs: Numbers n such that 1, 2, ..., 2n can be partitioned into n pairs, where each pair adds up to a perfect square. ; 4,7,8,9,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80 mov $2,$0 mul $2,9 lpb $2 add $0,2 div $2,36 lpe add $0,4
// Copyright 2022 Tulkina Olga #include <gtest/gtest.h> #include "../../modules/task_3/tulkina_o_labeling/labeling.h" TEST(TBB, Test_1x1) { std::vector<std::vector<int>> binary_image = {{0}}; binary_image = labeling(binary_image); std::vector<std::vector<int>> expected = {{0}}; int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(expected[i], binary_image[i]); } TEST(TBB, Test_1x5) { std::vector<std::vector<int>> binary_image = {{0, 1, 1, 0, 1}}; binary_image = labeling(binary_image); std::vector<std::vector<int>> expected = {{0, 2, 2, 0, 5}}; int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(expected[i], binary_image[i]); } TEST(TBB, Test_5x1) { std::vector<std::vector<int>> binary_image = {{0}, {1}, {1}, {1}, {1}}; binary_image = labeling(binary_image); std::vector<std::vector<int>> expected = {{0}, {2}, {2}, {2}, {2}}; int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(expected[i], binary_image[i]); } TEST(TBB, Test_10x10) { std::vector<std::vector<int>> binary_image = { {0, 1, 1, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 0, 1, 1, 0, 1, 0}, {1, 0, 0, 0, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 1, 0, 1, 0, 0}, {1, 0, 1, 0, 1, 1, 1, 0, 0, 1}, {1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {1, 0, 0, 0, 1, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 0, 0, 1, 1, 1, 1}}; binary_image = labeling(binary_image); std::vector<std::vector<int>> expected = { {0, 2, 2, 0, 2, 0, 0, 0, 0, 0}, {0, 0, 2, 2, 0, 0, 0, 0, 2, 0}, {21, 0, 2, 2, 2, 2, 2, 2, 0, 0}, {21, 0, 0, 0, 0, 2, 2, 0, 2, 0}, {21, 0, 0, 0, 0, 0, 0, 2, 0, 2}, {21, 0, 0, 2, 0, 2, 0, 2, 0, 0}, {21, 0, 2, 0, 2, 2, 2, 0, 0, 70}, {21, 0, 0, 2, 2, 2, 0, 0, 70, 70}, {21, 0, 0, 0, 2, 0, 0, 0, 70, 70}, {21, 0, 0, 0, 0, 0, 70, 70, 70, 70}}; int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(expected[i], binary_image[i]); } TEST(TBB, Test_10x10_version2) { int width = 10; int height = 10; std::vector<std::vector<int>> binary_image = { {0, 1, 1, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 0, 0, 0, 1, 0}, {1, 0, 1, 1, 1, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 0, 1, 1, 0, 1, 0}, {1, 0, 0, 0, 0, 0, 0, 1, 0, 1}, {1, 0, 0, 1, 0, 1, 0, 1, 0, 0}, {1, 0, 1, 0, 1, 1, 1, 0, 0, 1}, {1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {1, 0, 0, 0, 1, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 0, 0, 1, 1, 1, 1}}; std::vector<std::vector<int>> binary_image_tbb(height, std::vector<int>(width)); binary_image_tbb = labeling_tbb(binary_image); std::vector<std::vector<int>> expected = { {0, 2, 2, 0, 2, 0, 0, 0, 0, 0}, {0, 0, 2, 2, 0, 0, 0, 0, 2, 0}, {21, 0, 2, 2, 2, 2, 2, 2, 0, 0}, {21, 0, 0, 0, 0, 2, 2, 0, 2, 0}, {21, 0, 0, 0, 0, 0, 0, 2, 0, 2}, {21, 0, 0, 2, 0, 2, 0, 2, 0, 0}, {21, 0, 2, 0, 2, 2, 2, 0, 0, 70}, {21, 0, 0, 2, 2, 2, 0, 0, 70, 70}, {21, 0, 0, 0, 2, 0, 0, 0, 70, 70}, {21, 0, 0, 0, 0, 0, 70, 70, 70, 70}}; int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(binary_image_tbb[i], expected[i]); } TEST(TBB, Test_3000x3000) { int width = 3000; int height = 3000; std::random_device dev; std::mt19937 gen(dev()); std::uniform_real_distribution<> urd(0, 2); std::vector<std::vector<int>> binary_image(height, std::vector<int>(width)); for (int y = 0; y < height; y++) { for (int x = 0; x < height; x++) { binary_image[y][x] = urd(gen); } } std::vector<std::vector<int>> binary_image_seq(height, std::vector<int>(width)); double t1 = omp_get_wtime(); binary_image_seq = labeling(binary_image); double t2 = omp_get_wtime(); std::vector<std::vector<int>> binary_image_tbb(height, std::vector<int>(width)); double t3 = omp_get_wtime(); binary_image_tbb = labeling_tbb(binary_image); double t4 = omp_get_wtime(); int a = binary_image.size(); for (int i = 0; i < a; i++) EXPECT_EQ(binary_image_tbb[i], binary_image_seq[i]); printf("seq labeling: %lf\n", t2 - t1); printf("parallel labeling: %lf\n", t4 - t3); printf("labeling: %lf\n", (t2 - t1) / (t4 - t3)); }
BITS 16 cmp ax, 1 o16 cmp ax, 1 o32 cmp ax, 1 cmp eax, 1 o16 cmp eax, 1 o32 cmp eax, 1 BITS 32 cmp ax, 1 o16 cmp ax, 1 o32 cmp ax, 1 cmp eax, 1 o16 cmp eax, 1 o32 cmp eax, 1 BITS 64 cmp ax, 1 o16 cmp ax, 1 o32 cmp ax, 1 cmp eax, 1 o16 cmp eax, 1 o32 cmp eax, 1
section .data msg1 : db 'debug here --',10 l1 : equ $-msg1 msg2 : db 'enter the size of array 1 (n1): ' l2 : equ $-msg2 msg3 : db 'enter the sorted array 1 (ascending) : ',10 l3 : equ $-msg3 msg4 : db 'enter the size of array 2 (n2): ' l4: equ $-msg4 msg5 : db 'enter the sorted array 2 (decending) : ',10 l5: equ $-msg5 msg6 : db 'the merged array is (ascending) =>',10 l6: equ $-msg6 space:db ' ' newline:db '',10 section .bss num: resd 1 counter: resd 1 n: resd 10 array: resd 50 n1: resd 10 n2: resd 10 array1: resd 50 array2: resd 50 merged: resd 100 merge_count: resd 1 section .text global _start _start: mov eax, 4 mov ebx, 1 mov ecx, msg2 mov edx, l2 int 80h call read_num mov ax,word[num] mov [n1],ax mov eax, 4 mov ebx, 1 mov ecx, msg3 mov edx, l3 int 80h mov ebx, array1 mov ax,word[n1] mov [n],ax call read_array mov eax, 4 mov ebx, 1 mov ecx, msg4 mov edx, l4 int 80h call read_num mov ax,word[num] mov [n2],ax mov eax, 4 mov ebx, 1 mov ecx, msg5 mov edx, l5 int 80h mov ebx, array2 mov ax,word[n2] mov [n],ax call read_array call merge_array ;; array have been merged .. now print the array mov eax, 4 mov ebx, 1 mov ecx, msg6 mov edx, l6 int 80h mov ebx,merged mov eax,[merge_count] mov [n],eax mov eax , 0 call print_array exit: mov eax,1 mov ebx,0 int 80h ; section for procedures ;---------------------------- merge_array: section .bss cond1: resb 1 cond2: resb 1 num1: resd 1 num2: resd 1 counterFirst: resd 1 counterSecond: resd 1 section .text push rax push rbx push rcx mov ebx, array1 mov eax,0 mov word[counterFirst],0 mov ax, word[n2] mov word[counterSecond],ax mov word[merge_count],0 mov eax,0 loop1: mov eax,[counterFirst] cmp eax,dword[n1] setb cl mov byte[cond1], cl mov eax,[counterSecond] cmp eax, 1 setae cl mov byte[cond2], cl mov bl, [cond1] mov cl,[cond2] and bl,cl cmp bl,1 jne exit_loop1 ; call debugger mov ebx, array1 ;; taking num1 = array1[i] mov eax, [counterFirst] mov cx,word[ebx+2*eax] mov word[num1],cx dec word[counterSecond] mov ebx, array2 mov eax, [counterSecond] ;; taking num2 = array2[j] mov cx,word[ebx+2*eax] mov word[num2],cx inc word[counterSecond] ; mov bx,word[num1] ; mov word[num], bx ; call print_num ; mov word[num], cx ; call print_num cmp word[num1],cx jbe selec_num1 mov cx,word[num2] mov ebx,merged mov eax,[merge_count] ; call debugger mov word[ebx+2*eax],cx inc word[merge_count] dec word[counterSecond] jmp exit_check_cond selec_num1: mov cx,word[num1] mov ebx,merged mov eax,[merge_count] ; call debugger2 mov word[ebx+2*eax],cx inc word[merge_count] inc word[counterFirst] exit_check_cond: jmp loop1 exit_loop1: loop2: mov eax,[counterFirst] cmp eax,dword[n1] jae exit_loop2 mov ebx, array1 ;; taking num1 = array1[i] mov eax, [counterFirst] mov cx,word[ebx+2*eax] mov word[num1],cx mov cx,word[num1] ; putting residue values to merge array mov ebx,merged mov eax,[merge_count] mov word[ebx+2*eax],cx inc word[merge_count] inc word[counterFirst] jmp loop2 exit_loop2: loop3: mov eax,[counterSecond] cmp eax,1 jb exit_loop3 dec word[counterSecond] mov ebx, array2 ;; taking num2 = array2[i] mov eax, [counterSecond] mov cx,word[ebx+2*eax] mov word[num2],cx mov cx,word[num2] inc word[counterSecond] ; putting residue values to merge array mov ebx,merged mov eax,[merge_count] mov word[ebx+2*eax],cx inc word[merge_count] dec word[counterSecond] jmp loop3 exit_loop3: pop rcx pop rbx pop rax ret debugger2: section .data msg_debugger2 : db 'execution stops here',10 msg_debugger_l2 : equ $-msg_debugger2 section .text push rax push rbx push rcx ; debug---- mov eax, 4 mov ebx, 1 mov ecx, msg_debugger2 mov edx, msg_debugger_l2 int 80h ;debug --- pop rcx pop rbx pop rax ; action ret debugger: section .data msg_debugger : db 'debug here --',10 msg_debugger_l : equ $-msg_debugger section .text push rax push rbx push rcx ; debug---- mov eax, 4 mov ebx, 1 mov ecx, msg_debugger mov edx, msg_debugger_l int 80h ;debug --- pop rcx pop rbx pop rax ; action ret print_array: ; usage ;------- ; 1: base address of array in ebx mov ebx,array ; 2: size of array in n push rax ; push all push rbx push rcx mov eax,0 print_loop: cmp eax,dword[n] je end_print1 mov cx,word[ebx+2*eax] mov word[num],cx ;;The number to be printed is copied to ’num’ ; before calling print num function push rax push rbx call print_num pop rbx pop rax inc eax jmp print_loop end_print1: ; popa pop rcx pop rbx pop rax ; pop all ret read_array: ; usage ;------- ; 1: base address of array in ebx ; 2: size of array in n push rax ; push all push rbx push rcx mov eax ,0 read_loop: cmp eax,dword[n] je end_read_1 push rax push rbx call read_num pop rbx pop rax ;;read num stores the input in ’num’ mov cx,word[num] mov word[ebx+2*eax],cx inc eax ;;Here, each word consists of two bytes, so the counter should be ; incremented by multiples of two. If the array is declared in bytes do mov word[ebx+eax],cx jmp read_loop end_read_1: pop rcx pop rbx pop rax ; pop all ret print_num: ;usage ;------ ; 1: create a variable num(word) ; 2: move number to print to num (word) section .data nwl_for_printnum :db ' ',10 nwl_l_printnum : equ $-nwl_for_printnum section .bss count_printnum : resb 10 temp_printnum : resb 1 section .text push rax ; push all push rbx push rcx mov byte[count_printnum],0 ;call push_reg extract_no: cmp word[num], 0 je print_no inc byte[count_printnum] mov dx, 0 mov ax, word[num] mov bx, 10 div bx push dx ; recursion here mov word[num], ax jmp extract_no print_no: cmp byte[count_printnum], 0 je end_print dec byte[count_printnum] pop dx mov byte[temp_printnum], dl ; dx is further divided into dh and dl add byte[temp_printnum], 30h mov eax, 4 mov ebx, 1 mov ecx, temp_printnum mov edx, 1 int 80h jmp print_no end_print: mov eax,4 mov ebx,1 mov ecx,nwl_for_printnum mov edx,nwl_l_printnum int 80h ;;The memory location ’newline’ should be declared with the ASCII key for new popa ;call pop_reg pop rcx pop rbx pop rax ; pop all ret read_num: ;usage ;------ ; 1: create a variable num(word) ; 2: the input number is stored into num(word) section .bss temp_for_read: resb 1 section .text push rax ; push all push rbx push rcx mov word[num], 0 loop_read: ;; read a digit mov eax, 3 mov ebx, 0 mov ecx, temp_for_read mov edx, 1 int 80h ;;check if the read digit is the end of number, i.e, the enter-key whose ASCII cmp byte[temp], 10 cmp byte[temp_for_read], 10 je end_read mov ax, word[num] mov bx, 10 mul bx mov bl, byte[temp_for_read] sub bl, 30h mov bh, 0 add ax, bx mov word[num], ax jmp loop_read end_read: ;;pop all the used registers from the stack using popa ;call pop_reg pop rcx pop rbx pop rax ret
CSEG SEGMENT ASSUME CS:CSEG START PROC FAR PUSH CS POP DS MOV AX,351CH INT 21H MOV CS:WORD PTR OLD1C,BX MOV CS:WORD PTR OLD1C+2,ES MOV DX,OFFSET INT1C MOV AX,251CH INT 21H WAITN: MOV AH,1 INT 16H JZ WAITN MOV AH,0 INT 16H LDS DX,CS:OLD1C MOV AX,251CH INT 21H MOV AH,4CH INT 21H START ENDP OLD1C DD ? COUNT DW 0 HHH DB ?,?,':' MMM DB ?,?,':' SSS DB ?,?,'$' INT1C PROC FAR CMP COUNT,0 JZ NEXT DEC COUNT IRET NEXT: MOV COUNT,1091 STI PUSH DS PUSH ES PUSH AX PUSH BX PUSH CX PUSH DX PUSH SI PUSH DI MOV AH,2 INT 1AH MOV AL,CH CALL TTASC MOV WORD PTR HHH,AX MOV AL,CL CALL TTASC MOV WORD PTR MMM,AX MOV AL,DH CALL TTASC MOV WORD PTR SSS,AX CALL CLS MOV BH,0 MOV DX,0140H MOV AH,2 INT 10H PUSH CS POP DS MOV DX,OFFSET HHH MOV AH,9 INT 21H POP DI POP SI POP DX POP CX POP BX POP AX POP ES POP DS IRET INT1C ENDP TTASC PROC MOV AH,AL AND AL,0FH SHR AH,1 SHR AH,1 SHR AH,1 SHR AH,1 ADD AX,3030H XCHG AH,AL RET TTASC ENDP CLS PROC MOV AX,0600H MOV CX,0 MOV DX,184FH MOV BH,7 INT 10H RET CLS ENDP CSEG ENDS END START
SPECTRUM: LD HL,L15AF LD DE,(CHANS) LD BC,$15 RST $30 DEFW LDIRR RES 4,(IY+FLAGS-ERR_NR) ; SPECTRUM mode LD A,$80 OUT ($FF),A ; SPECTRUM video mode RST $10
PokemonTower7Script: call EnableAutoTextBoxDrawing ld hl, PokemonTower7ScriptPointers ld a, [wPokemonTower7CurScript] call JumpTable ret PokemonTower7Script_60d01: xor a ld [wJoyIgnore], a PokemonTower7Script_60d05: ld [wPokemonTower7CurScript], a ret PokemonTower7ScriptPointers: dw PokemonTower7Script0 dw PokemonTower7Script1 dw PokemonTower7Script2 dw PokemonTower7Script3 dw PokemonTower7Script4 dw PokemonTower7Script5 dw PokemonTower7Script6 dw PokemonTower7Script7 dw PokemonTower7Script8 dw PokemonTower7Script9 dw PokemonTower7Script10 dw PokemonTower7Script11 PokemonTower7Script0: CheckEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_0 call z, PokemonTower7Script_60d2a ret PokemonTower7Script_60d2a: ld a, [wYCoord] cp $c ret nz ResetEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 ld a, [wXCoord] cp $a jr z, .asm_60d47 ld a, [wXCoord] ; why? cp $b ret nz SetEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 .asm_60d47 call StopAllMusic ld c, BANK(Music_MeetJessieJames) ld a, MUSIC_MEET_JESSIE_JAMES call PlayMusic xor a ld [hJoyHeld], a ld a, $FF ^ (A_BUTTON | B_BUTTON) ld [wJoyIgnore], a ld a, HS_POKEMONTOWER_7_JESSIE call PokemonTower7Script_60eaf ld a, HS_POKEMONTOWER_7_JAMES call PokemonTower7Script_60eaf ld a, $1 ld [wDoNotWaitForButtonPressAfterDisplayingText], a ld a, $4 ld [hSpriteIndexOrTextID], a call DisplayTextID ld a, $ff ld [wJoyIgnore], a ld a, $1 call PokemonTower7Script_60d05 ret PokemonTower7MovementData_60d7a: db $4 PokemonTower7MovementData_60d7b: db $4 db $4 db $4 db $FF PokemonTower7Script1: ld de, PokemonTower7MovementData_60d7b CheckEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 jr z, .asm_60d8c ld de, PokemonTower7MovementData_60d7a .asm_60d8c ld a, $1 ld [hSpriteIndexOrTextID], a call MoveSprite ld a, $ff ld [wJoyIgnore], a ld a, $2 call PokemonTower7Script_60d05 ret PokemonTower7Script2: ld a, $ff ld [wJoyIgnore], a ld a, [wd730] bit 0, a ret nz PokemonTower7Script3: ld a, $0 ld [wSpriteStateData1 + 1 * $10 + 9], a CheckEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 jr z, .asm_60dba ld a, $c ld [wSpriteStateData1 + 1 * $10 + 9], a .asm_60dba ld a, $2 ld [wSpriteStateData1 + 1 * $10 + 1], a PokemonTower7Script4: ld de, PokemonTower7MovementData_60d7a CheckEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 jr z, .asm_60dcc ld de, PokemonTower7MovementData_60d7b .asm_60dcc ld a, $2 ld [hSpriteIndexOrTextID], a call MoveSprite ld a, $ff ld [wJoyIgnore], a ld a, $5 call PokemonTower7Script_60d05 ret PokemonTower7Script5: ld a, $ff ld [wJoyIgnore], a ld a, [wd730] bit 0, a ret nz PokemonTower7Script6: ld a, $2 ld [wSpriteStateData1 + $2 * $10 + $1], a ld a, $8 ld [wSpriteStateData1 + $2 * $10 + $9], a CheckEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_1 jr z, .asm_60dff ld a, $0 ld [wSpriteStateData1 + $2 * $10 + $9], a .asm_60dff call Delay3 ld a, $FF ^ (A_BUTTON | B_BUTTON) ld [wJoyIgnore], a ld a, $5 ld [hSpriteIndexOrTextID], a call DisplayTextID PokemonTower7Script7: ld hl, wd72d set 6, [hl] set 7, [hl] ld hl, PokemonTower7JessieJamesEndBattleText ld de, PokemonTower7JessieJamesEndBattleText call SaveEndBattleTextPointers ld a, OPP_ROCKET ld [wCurOpponent], a ld a, $2c ld [wTrainerNo], a xor a ld [hJoyHeld], a ld [wJoyIgnore], a ld a, $8 call PokemonTower7Script_60d05 ret PokemonTower7Script8: ld a, $ff ld [wJoyIgnore], a ld a, [wIsInBattle] cp $ff jp z, PokemonTower7Script_60d01 ld a, $2 ld [wSpriteStateData1 + 1 * $10 + 1], a ld [wSpriteStateData1 + 2 * $10 + 1], a xor a ld [wSpriteStateData1 + 1 * $10 + 9], a ld [wSpriteStateData1 + 2 * $10 + 9], a ld a, $FF ^ (A_BUTTON | B_BUTTON) ld [wJoyIgnore], a ld a, $1 ld [wDoNotWaitForButtonPressAfterDisplayingText], a ld a, $6 ld [hSpriteIndexOrTextID], a call DisplayTextID xor a ld [wDoNotWaitForButtonPressAfterDisplayingText], a call StopAllMusic ld c, BANK(Music_MeetJessieJames) ld a, MUSIC_MEET_JESSIE_JAMES call PlayMusic ld a, $ff ld [wJoyIgnore], a ld a, $9 call PokemonTower7Script_60d05 ret PokemonTower7Script9: ld a, $ff ld [wJoyIgnore], a call GBFadeOutToBlack ld a, HS_POKEMONTOWER_7_JESSIE call PokemonTower7Script_60ebe ld a, HS_POKEMONTOWER_7_JAMES call PokemonTower7Script_60ebe call UpdateSprites call Delay3 call GBFadeInFromBlack ld a, $a call PokemonTower7Script_60d05 ret PokemonTower7Script10: call PlayDefaultMusic xor a ld [hJoyHeld], a ld [wJoyIgnore], a SetEvent EVENT_BEAT_POKEMONTOWER_7_TRAINER_0 ld a, $0 call PokemonTower7Script_60d05 ret PokemonTower7Script_60eaf: ld [wMissableObjectIndex], a predef ShowObject call UpdateSprites call Delay3 ret PokemonTower7Script_60ebe ld [wMissableObjectIndex], a predef HideObject ret PokemonTower7Script11: ld a, $ff ld [wJoyIgnore], a ld a, HS_POKEMONTOWER_7_MR_FUJI ld [wMissableObjectIndex], a predef HideObject ld a, SPRITE_FACING_UP ld [wPlayerFacingDirection], a ld a, LAVENDER_HOUSE_1 ld [hWarpDestinationMap], a ld a, $1 ld [wDestinationWarpID], a ld a, LAVENDER_TOWN ld [wLastMap], a ld hl, wd72d set 3, [hl] ld a, $0 ld [wPokemonTower7CurScript], a ret PokemonTower7TextPointers: dw PokemonTower7Text1 dw PokemonTower7Text2 dw PokemonTower7Text3 dw PokemonTower7Text4 dw PokemonTower7Text5 dw PokemonTower7Text6 PokemonTower7Text1: PokemonTower7Text2: db "@" PokemonTower7Text4: TX_FAR _PokemonTowerJessieJamesText1 TX_ASM ld c, 10 call DelayFrames ld a, PLAYER_DIR_UP ld [wPlayerMovingDirection], a ld a, $0 ld [wEmotionBubbleSpriteIndex], a ld a, $0 ld [wWhichEmotionBubble], a predef EmotionBubble ld c, 20 call DelayFrames jp TextScriptEnd PokemonTower7Text5: TX_FAR _PokemonTowerJessieJamesText2 db "@" PokemonTower7JessieJamesEndBattleText: TX_FAR _PokemonTowerJessieJamesText3 db "@" PokemonTower7Text6: TX_FAR _PokemonTowerJessieJamesText4 TX_ASM ld c, 64 call DelayFrames jp TextScriptEnd PokemonTower7Text3: TX_ASM ld hl, PokemonTower7Text_60f75 call PrintText SetEvent EVENT_RESCUED_MR_FUJI SetEvent EVENT_RESCUED_MR_FUJI_2 ld a, HS_LAVENDER_HOUSE_1_MR_FUJI ld [wMissableObjectIndex], a predef ShowObject ld a, HS_SAFFRON_CITY_E ld [wMissableObjectIndex], a predef HideObject ld a, HS_SAFFRON_CITY_F ld [wMissableObjectIndex], a predef ShowObject ld a, $b ld [wPokemonTower7CurScript], a jp TextScriptEnd PokemonTower7Text_60f75: TX_FAR _TowerRescueFujiText db "@"
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0xcb97, %rbp nop nop nop cmp $57000, %r11 movl $0x61626364, (%rbp) nop nop xor $36756, %rax lea addresses_D_ht+0x13e97, %rsi lea addresses_WC_ht+0x18f4f, %rdi nop nop add $39751, %r8 mov $92, %rcx rep movsw nop nop nop nop dec %r15 lea addresses_UC_ht+0x1597, %rbp nop nop nop nop nop add $3676, %r15 movw $0x6162, (%rbp) nop nop cmp %rdi, %rdi lea addresses_WC_ht+0x16197, %rax and %rbp, %rbp mov $0x6162636465666768, %rcx movq %rcx, %xmm4 vmovups %ymm4, (%rax) nop nop nop sub $1997, %r15 lea addresses_D_ht+0x1eb2b, %r11 nop nop sub $57393, %rcx mov $0x6162636465666768, %rbp movq %rbp, %xmm5 vmovups %ymm5, (%r11) nop nop nop nop nop sub %rdi, %rdi lea addresses_normal_ht+0x16997, %rsi lea addresses_UC_ht+0xfd7, %rdi and $13004, %r11 mov $53, %rcx rep movsb inc %rdi lea addresses_WC_ht+0xa36f, %rcx nop nop nop nop nop xor $425, %rax mov (%rcx), %si nop nop cmp $27997, %rsi lea addresses_D_ht+0x3981, %r15 xor %r8, %r8 movl $0x61626364, (%r15) nop nop nop nop sub %r8, %r8 lea addresses_WC_ht+0x2f97, %r15 add $35, %rbp mov (%r15), %cx nop nop dec %r8 lea addresses_D_ht+0x18b97, %rsi lea addresses_D_ht+0x997, %rdi nop nop mfence mov $89, %rcx rep movsb nop nop nop nop nop add $49787, %rbp lea addresses_WT_ht+0xe797, %rsi lea addresses_D_ht+0x9597, %rdi clflush (%rdi) nop nop nop sub $48238, %r8 mov $3, %rcx rep movsl nop nop nop nop nop xor $18651, %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %rcx push %rdi push %rdx push %rsi // REPMOV lea addresses_PSE+0x3197, %rsi lea addresses_D+0x7997, %rdi nop nop inc %r14 mov $118, %rcx rep movsl nop add %rdi, %rdi // Faulty Load lea addresses_PSE+0x3197, %rsi nop nop nop nop nop sub $17746, %rdx movntdqa (%rsi), %xmm4 vpextrq $1, %xmm4, %r11 lea oracles, %rcx and $0xff, %r11 shlq $12, %r11 mov (%rcx,%r11,1), %r11 pop %rsi pop %rdx pop %rdi pop %rcx pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'src': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_D', 'congruent': 4, 'same': False}} [Faulty Load] {'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 16, 'NT': True, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 10}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 11}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': False}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 1}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 1}} {'src': {'type': 'addresses_WC_ht', 'AVXalign': True, 'size': 2, 'NT': False, 'same': False, 'congruent': 7}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 10, 'same': True}} {'48': 1, '18': 2, '33': 21508, '44': 41, '46': 102, '00': 175} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 46 33 33 33 33 33 33 33 33 33 33 33 00 33 33 33 33 33 33 33 44 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
; A010963: Binomial coefficient C(47,n). ; 1,47,1081,16215,178365,1533939,10737573,62891499,314457495,1362649145,5178066751,17417133617,52251400851,140676848445,341643774795,751616304549,1503232609098,2741188875414,4568648125690,6973199770790,9762479679106,12551759587422,14833897694226,16123801841550,16123801841550,14833897694226,12551759587422,9762479679106,6973199770790,4568648125690,2741188875414,1503232609098,751616304549,341643774795,140676848445,52251400851,17417133617,5178066751,1362649145,314457495,62891499,10737573,1533939,178365,16215,1081,47,1 mov $1,47 bin $1,$0
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; EXPORT |vp8_short_idct4x4llm_neon| ARM REQUIRE8 PRESERVE8 AREA ||.text||, CODE, READONLY, ALIGN=2 ;************************************************************* ;void vp8_short_idct4x4llm_c(short *input, short *output, int pitch) ;r0 short * input ;r1 short * output ;r2 int pitch ;************************************************************* ;static const int cospi8sqrt2minus1=20091; ;static const int sinpi8sqrt2 =35468; ;static const int rounding = 0; ;Optimization note: The resulted data from dequantization are signed 13-bit data that is ;in the range of [-4096, 4095]. This allows to use "vqdmulh"(neon) instruction since ;it won't go out of range (13+16+1=30bits<32bits). This instruction gives the high half ;result of the multiplication that is needed in IDCT. |vp8_short_idct4x4llm_neon| PROC adr r12, idct_coeff vld1.16 {q1, q2}, [r0] vld1.16 {d0}, [r12] vswp d3, d4 ;q2(vp[4] vp[12]) vqdmulh.s16 q3, q2, d0[2] vqdmulh.s16 q4, q2, d0[0] vqadd.s16 d12, d2, d3 ;a1 vqsub.s16 d13, d2, d3 ;b1 vshr.s16 q3, q3, #1 vshr.s16 q4, q4, #1 vqadd.s16 q3, q3, q2 ;modify since sinpi8sqrt2 > 65536/2 (negtive number) vqadd.s16 q4, q4, q2 ;d6 - c1:temp1 ;d7 - d1:temp2 ;d8 - d1:temp1 ;d9 - c1:temp2 vqsub.s16 d10, d6, d9 ;c1 vqadd.s16 d11, d7, d8 ;d1 vqadd.s16 d2, d12, d11 vqadd.s16 d3, d13, d10 vqsub.s16 d4, d13, d10 vqsub.s16 d5, d12, d11 vtrn.32 d2, d4 vtrn.32 d3, d5 vtrn.16 d2, d3 vtrn.16 d4, d5 vswp d3, d4 vqdmulh.s16 q3, q2, d0[2] vqdmulh.s16 q4, q2, d0[0] vqadd.s16 d12, d2, d3 ;a1 vqsub.s16 d13, d2, d3 ;b1 vshr.s16 q3, q3, #1 vshr.s16 q4, q4, #1 vqadd.s16 q3, q3, q2 ;modify since sinpi8sqrt2 > 65536/2 (negtive number) vqadd.s16 q4, q4, q2 vqsub.s16 d10, d6, d9 ;c1 vqadd.s16 d11, d7, d8 ;d1 vqadd.s16 d2, d12, d11 vqadd.s16 d3, d13, d10 vqsub.s16 d4, d13, d10 vqsub.s16 d5, d12, d11 vrshr.s16 d2, d2, #3 vrshr.s16 d3, d3, #3 vrshr.s16 d4, d4, #3 vrshr.s16 d5, d5, #3 add r3, r1, r2 add r12, r3, r2 add r0, r12, r2 vtrn.32 d2, d4 vtrn.32 d3, d5 vtrn.16 d2, d3 vtrn.16 d4, d5 vst1.16 {d2}, [r1] vst1.16 {d3}, [r3] vst1.16 {d4}, [r12] vst1.16 {d5}, [r0] bx lr ENDP ;----------------- idct_coeff DCD 0x4e7b4e7b, 0x8a8c8a8c ;20091, 20091, 35468, 35468 END
; A097482: a(1) = 1, a(2) = 1, a(n) = floor(sqrt(a(n-2)*a(n-1))) + 3 for n > 2. ; 1,1,4,5,7,8,10,11,13,14,16,17,19,20,22,23,25,26,28,29,31,32,34,35,37,38,40,41,43,44,46,47,49,50,52,53,55,56,58,59,61,62,64,65,67,68,70,71,73,74,76,77,79,80,82,83,85,86,88,89,91,92,94,95,97,98,100 mul $0,3 lpb $0 bin $0,4 lpe div $0,2 mov $1,$0 add $1,1
lda #0 sta {m1} lda {m2} asl sta {m1}+1 lda {m2}+1 rol sta {m1}+2 lda {m2}+2 rol sta {m1}+3
;;; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ;;; ;;; ASM Source code for Red GBC, by Evan Bowman, 2021 ;;; ;;; ;;; The following licence covers the source code included in this file. The ;;; game's characters and artwork belong to Evan Bowman, and should not be used ;;; without permission. ;;; ;;; ;;; 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. ;;; ;;; $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ;;; ---------------------------------------------------------------------------- r1_InitSnowflakes: ld b, BLIZZARD_SNOWFLAKE_COUNT ld hl, var_blizzard_snowflakes .loop: ld a, b or a ret Z push hl fcall GetRandom ld a, l pop hl ld [hl+], a inc hl inc hl inc hl dec b jr .loop ;;; ---------------------------------------------------------------------------- r1_UpdateSnowflakes: ld b, BLIZZARD_SNOWFLAKE_COUNT ld hl, var_blizzard_snowflakes .loop: ld a, b or a ret Z ld a, [hl] ; \ inc a ; | Inc timer byte ld [hl+], a ; / ld a, [hl] add 2 ld c, a ld a, 168 cp c jr C, .reset0 ld a, c ld [hl+], a ld a, [hl] inc a ld c, a ld a, 144 cp c jr C, .reset1 ld a, c ld [hl+], a .resume: inc hl ; skip unused fourth byte dec b jr .loop .reset1: dec hl ; backtrack to first byte of struct .reset0: .setPosRandom: push hl fcall GetRandom ld a, h pop hl bit 0, a jr Z, .pinLeft .pinTop: ld [hl+], a ld a, 0 ld [hl+], a jr .resume .pinLeft: inc hl ld [hl], a ld a, 0 dec hl ld [hl+], a inc hl jr .resume ;;; ---------------------------------------------------------------------------- r1_DrawSnowflakes: fcall r1_UpdateSnowflakes ld b, BLIZZARD_SNOWFLAKE_COUNT ld hl, var_blizzard_snowflakes .loop: ld a, b or a ret Z ld d, b dec d ; otherwise off-by-one push bc ld a, [hl+] ; Timer ld c, a push hl fcall r1_HalfSine pop hl srl b srl b srl b srl b srl b srl b ld c, b ld a, [hl+] ; x-coordinate ld b, a ld a, [hl+] ; y-coordinate add c ld c, a push hl ld l, d ld d, 1 ld e, $78 fcall ShowSpriteSingle pop hl pop bc inc hl dec b jr .loop ;;; ----------------------------------------------------------------------------
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation ; All rights reserved. This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; SupportItpDebug.asm ; ; Abstract: ; ; This is the code for debuging X64, to add a break hook at loading every module ; ;------------------------------------------------------------------------------ ; PROC:PRIVATE .CODE ;------------------------------------------------------------------------------ ; VOID ; AsmEfiSetBreakSupport ( ; IN UINTN LoadAddr // rcx ; ) ;------------------------------------------------------------------------------ AsmEfiSetBreakSupport PROC PUBLIC mov dx, 60000 out dx, eax nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop nop ret AsmEfiSetBreakSupport ENDP END
SafariZoneSecretHouseObject: db $17 ; border block db $2 ; warps db $7, $2, $6, SAFARI_ZONE_WEST db $7, $3, $6, SAFARI_ZONE_WEST db $0 ; signs db $1 ; objects object SPRITE_FISHER, $3, $3, STAY, DOWN, $1 ; person ; warp-to EVENT_DISP SAFARI_ZONE_SECRET_HOUSE_WIDTH, $7, $2 ; SAFARI_ZONE_WEST EVENT_DISP SAFARI_ZONE_SECRET_HOUSE_WIDTH, $7, $3 ; SAFARI_ZONE_WEST
include uXmx86asm.inc option casemap:none ifndef __X64__ .686P .xmm .model flat, c else .X64P .xmm option win64:11 option stackbase:rsp endif option frame:auto .code align 16 uXm_has_CMPXCHG8B proto VECCALL (byte) align 16 uXm_has_CMPXCHG8B proc VECCALL (byte) mov eax, 1 cpuid and edx, bit_CMPXCHG8B cmp edx, bit_CMPXCHG8B ; CMPXCHG8B support by microprocessor .if EQUAL? mov al, true .else mov al, false .endif ret uXm_has_CMPXCHG8B endp end ;.code
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2013 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "src/xenia/kernel/xsocket.h" #include <cstring> #include "xenia/base/platform.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/xam/xam_module.h" // #include "xenia/kernel/xnet.h" #ifdef XE_PLATFORM_WIN32 // clang-format off #include "xenia/base/platform_win.h" #include <WS2tcpip.h> #include <WinSock2.h> // clang-format on #else #include <arpa/inet.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/socket.h> #include <unistd.h> #endif namespace xe { namespace kernel { XSocket::XSocket(KernelState* kernel_state) : XObject(kernel_state, kObjectType) {} XSocket::XSocket(KernelState* kernel_state, uint64_t native_handle) : XObject(kernel_state, kObjectType), native_handle_(native_handle) {} XSocket::~XSocket() { Close(); } X_STATUS XSocket::Initialize(AddressFamily af, Type type, Protocol proto) { af_ = af; type_ = type; proto_ = proto; if (proto == Protocol::IPPROTO_VDP) { // VDP is a layer on top of UDP. proto = Protocol::IPPROTO_UDP; } native_handle_ = socket(af, type, proto); if (native_handle_ == -1) { return X_STATUS_UNSUCCESSFUL; } return X_STATUS_SUCCESS; } X_STATUS XSocket::Close() { #if XE_PLATFORM_WIN32 int ret = closesocket(native_handle_); #elif XE_PLATFORM_LINUX int ret = close(native_handle_); #endif if (ret != 0) { return X_STATUS_UNSUCCESSFUL; } return X_STATUS_SUCCESS; } X_STATUS XSocket::SetOption(uint32_t level, uint32_t optname, void* optval_ptr, uint32_t optlen) { if (level == 0xFFFF && (optname == 0x5801 || optname == 0x5802)) { // Disable socket encryption secure_ = false; return X_STATUS_SUCCESS; } int ret = setsockopt(native_handle_, level, optname, (char*)optval_ptr, optlen); if (ret < 0) { // TODO: WSAGetLastError() return X_STATUS_UNSUCCESSFUL; } // SO_BROADCAST if (level == 0xFFFF && optname == 0x0020) { broadcast_socket_ = true; } return X_STATUS_SUCCESS; } X_STATUS XSocket::IOControl(uint32_t cmd, uint8_t* arg_ptr) { #ifdef XE_PLATFORM_WIN32 int ret = ioctlsocket(native_handle_, cmd, (u_long*)arg_ptr); if (ret < 0) { // TODO: Get last error return X_STATUS_UNSUCCESSFUL; } return X_STATUS_SUCCESS; #elif XE_PLATFORM_LINUX return X_STATUS_UNSUCCESSFUL; #endif } X_STATUS XSocket::Connect(N_XSOCKADDR* name, int name_len) { int ret = connect(native_handle_, (sockaddr*)name, name_len); if (ret < 0) { return X_STATUS_UNSUCCESSFUL; } return X_STATUS_SUCCESS; } X_STATUS XSocket::Bind(N_XSOCKADDR_IN* name, int name_len) { int ret = bind(native_handle_, (sockaddr*)name, name_len); if (ret < 0) { return X_STATUS_UNSUCCESSFUL; } bound_ = true; bound_port_ = name->sin_port; return X_STATUS_SUCCESS; } X_STATUS XSocket::Listen(int backlog) { int ret = listen(native_handle_, backlog); if (ret < 0) { return X_STATUS_UNSUCCESSFUL; } return X_STATUS_SUCCESS; } object_ref<XSocket> XSocket::Accept(N_XSOCKADDR* name, int* name_len) { sockaddr n_sockaddr; socklen_t n_name_len = sizeof(sockaddr); uintptr_t ret = accept(native_handle_, &n_sockaddr, &n_name_len); if (ret == -1) { std::memset(name, 0, *name_len); *name_len = 0; return nullptr; } std::memcpy(name, &n_sockaddr, n_name_len); *name_len = n_name_len; // Create a kernel object to represent the new socket, and copy parameters // over. auto socket = object_ref<XSocket>(new XSocket(kernel_state_, ret)); socket->af_ = af_; socket->type_ = type_; socket->proto_ = proto_; return socket; } int XSocket::Shutdown(int how) { return shutdown(native_handle_, how); } int XSocket::Recv(uint8_t* buf, uint32_t buf_len, uint32_t flags) { return recv(native_handle_, reinterpret_cast<char*>(buf), buf_len, flags); } int XSocket::RecvFrom(uint8_t* buf, uint32_t buf_len, uint32_t flags, N_XSOCKADDR_IN* from, uint32_t* from_len) { // Pop from secure packets first // TODO(DrChat): Enable when I commit XNet /* { std::lock_guard<std::mutex> lock(incoming_packet_mutex_); if (incoming_packets_.size()) { packet* pkt = (packet*)incoming_packets_.front(); int data_len = pkt->data_len; std::memcpy(buf, pkt->data, std::min((uint32_t)pkt->data_len, buf_len)); from->sin_family = 2; from->sin_addr = pkt->src_ip; from->sin_port = pkt->src_port; incoming_packets_.pop(); uint8_t* pkt_ui8 = (uint8_t*)pkt; delete[] pkt_ui8; return data_len; } } */ sockaddr_in nfrom; socklen_t nfromlen = sizeof(sockaddr_in); int ret = recvfrom(native_handle_, reinterpret_cast<char*>(buf), buf_len, flags, (sockaddr*)&nfrom, &nfromlen); if (from) { from->sin_family = nfrom.sin_family; from->sin_addr = ntohl(nfrom.sin_addr.s_addr); // BE <- BE from->sin_port = nfrom.sin_port; std::memset(from->x_sin_zero, 0, sizeof(from->x_sin_zero)); } if (from_len) { *from_len = nfromlen; } return ret; } int XSocket::Send(const uint8_t* buf, uint32_t buf_len, uint32_t flags) { return send(native_handle_, reinterpret_cast<const char*>(buf), buf_len, flags); } int XSocket::SendTo(uint8_t* buf, uint32_t buf_len, uint32_t flags, N_XSOCKADDR_IN* to, uint32_t to_len) { // Send 2 copies of the packet: One to XNet (for network security) and an // unencrypted copy for other Xenia hosts. // TODO(DrChat): Enable when I commit XNet. /* auto xam = kernel_state()->GetKernelModule<xam::XamModule>("xam.xex"); auto xnet = xam->xnet(); if (xnet) { xnet->SendPacket(this, to, buf, buf_len); } */ sockaddr_in nto; if (to) { nto.sin_addr.s_addr = to->sin_addr; nto.sin_family = to->sin_family; nto.sin_port = to->sin_port; } return sendto(native_handle_, reinterpret_cast<char*>(buf), buf_len, flags, to ? (sockaddr*)&nto : nullptr, to_len); } bool XSocket::QueuePacket(uint32_t src_ip, uint16_t src_port, const uint8_t* buf, size_t len) { packet* pkt = reinterpret_cast<packet*>(new uint8_t[sizeof(packet) + len]); pkt->src_ip = src_ip; pkt->src_port = src_port; pkt->data_len = (uint16_t)len; std::memcpy(pkt->data, buf, len); std::lock_guard<std::mutex> lock(incoming_packet_mutex_); incoming_packets_.push((uint8_t*)pkt); // TODO: Limit on number of incoming packets? return true; } X_STATUS XSocket::GetSockName(uint8_t* buf, int* buf_len) { struct sockaddr sa = {}; int ret = getsockname(native_handle_, &sa, (socklen_t*)buf_len); if (ret < 0) { return X_STATUS_UNSUCCESSFUL; } std::memcpy(buf, &sa, *buf_len); return X_STATUS_SUCCESS; } uint32_t XSocket::GetLastWSAError() const { // Todo(Gliniak): Provide error mapping table // Xbox error codes might not match with what we receive from OS #ifdef XE_PLATFORM_WIN32 return WSAGetLastError(); #endif return errno; } } // namespace kernel } // namespace xe
; A052540: Expansion of (1-x)/(1-2*x-x^3+x^4). ; Submitted by Christian Krause ; 1,1,2,5,10,21,45,95,201,426,902,1910,4045,8566,18140,38415,81351,172276,364827,772590,1636105,3464761,7337285,15538085,32904826,69682176,147565152,312497045,661771440,1401425856,2967783605,6284841605,13309337626,28185033001,59687124002,126398744025,267673183425,566848457851,1200408535725,2542091510850,5383358296126,11400276670126,24142236315377,51125739416030,108268397206060,229278754057371,485541011215395,1028224680220820,2177459717292951,4611181691743926,9765047052493277,20679329142058685 add $0,3 mov $2,1 lpb $0 sub $0,1 sub $3,$4 add $1,$3 mov $4,$2 mov $2,$3 add $4,$1 add $5,$4 mov $3,$5 lpe mov $0,$2
INCLUDE "sdk/hardware.inc" ; use this for inspiration :) ; https://codepen.io/MillerTime/pen/XgpNwb RSRESET DEF FIREWORK_YPOS RB 2 ; 8.8 fixed point DEF FIREWORK_YVEL RB 2 ; int part is first byte, fraction part second byte DEF FIREWORK_XPOS RB 2 DEF FIREWORK_XVEL RB 2 DEF FIREWORK_SIZE RB 0 DEF FIREWORK_STARTY EQU 150 + OAM_Y_OFS ; Y position it starts at before shooting up DEF FIREWORK_ALIVETIME EQU 17 ; Number of frames after exploding before firework fades out DEF FIREWORK_FADETIME EQU 6 ; Number of frames between each fade state DEF FIREWORK_START_YVEL EQU -$0440 ; Starting Y velocity of the first particle that shoots up. 8.8 fixed point DEF FIREWORK_NUM_FADE_TILES EQU 4 ; Number of animation frames in the fadeout DEF FIREWORK_TILEINDEX EQU $02 DEF FIREWORK_FIRST_SPRITE EQU 1 ; Sprite index of the first firework sprite DEF NUM_FIREWORK_SPRITES EQU 30 DEF AIR_RESISTANCE EQU $0002 ; Amount the firework X velocity decreases by every frame. 8.8 fixed DEF GRAVITY EQU $0014 ; Amount the firework Y velocity decreases by each frame. 8.8 fixed SECTION "FireworksRAM", WRAM0 wFireworkArray: DS FIREWORK_SIZE * NUM_FIREWORK_SPRITES wFireworkState: DS 1 ; 0 = Idle, 1 = Shooting up, 2 = Exploding, 3 = Fading out wFireworkTimer: DS 1 ; Holds frame counts for various states wFireworkCurTile: DS 1 ; Current sprite tile, used for fading. wFireworkCurPalette: DS 1 ; Cycles through 4 palettes. Only on CGB SECTION "FireworksHRAM", HRAM hFireworkSpritePtr: DB SECTION "FireworkVelocityTable", ROM0 ; angles are measured 0 - 65536.0 in rgbasm DEF VEL_MULTIPLIER1 EQU 120000 DEF VEL_MULTIPLIER2 EQU 70000 DEF NUM_DIRECTIONS EQU 30 ANGLE = 0.0 REPT NUM_DIRECTIONS / 2 YVEL = MUL(SIN(ANGLE), VEL_MULTIPLIER1) ; 16.16 fixed point number db (YVEL >> 16) & $FF ; save integer part db (YVEL >> 8) & $FF ; save fractional part XVEL = MUL(COS(ANGLE), VEL_MULTIPLIER1) ; 16.16 fixed point number db (XVEL >> 16) & $FF ; save integer part db (XVEL >> 8) & $FF ; save fractional part ANGLE = ANGLE + ((65536 / (NUM_DIRECTIONS / 2)) << 16) ; left shift to convert to fixed point ENDR ANGLE = 0.0 REPT NUM_DIRECTIONS / 2 YVEL = MUL(SIN(ANGLE), VEL_MULTIPLIER2) ; 16.16 fixed point number db (YVEL >> 16) & $FF ; save integer part db (YVEL >> 8) & $FF ; save fractional part XVEL = MUL(COS(ANGLE), VEL_MULTIPLIER2) ; 16.16 fixed point number db (XVEL >> 16) & $FF ; save integer part db (XVEL >> 8) & $FF ; save fractional part ANGLE = ANGLE + ((65536 / (NUM_DIRECTIONS / 2)) << 16) ; left shift to convert to fixed point ENDR SECTION "FireworksCode", ROM0 _startFireworks:: xor a ld [wFireworkCurPalette], a ; initialise the palette ld [wFireworkState], a ; go to idle state ld a, 90 ; wait 1.5 seconds before firing ld [wFireworkTimer], a ret _clearFireworks:: ld e, NUM_FIREWORK_SPRITES ld hl, wShadowOAM + (FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS) + OAMA_Y xor a .clearSprites: ; move all sprites offscreen ld [hli], a inc hl inc hl inc hl dec e jr nz, .clearSprites ret _updateFireworks:: ld a, [wFireworkState] and a jr z, .idleState dec a jr z, .flyingState dec a jp z, .explodingState ; Fading State ld hl, wFireworkTimer dec [hl] jp nz, .explodingStateFade ld a, FIREWORK_FADETIME ld [hl], a ; reset timer ld hl, wFireworkCurTile inc [hl] ld a, [hl] cp a, FIREWORK_TILEINDEX + FIREWORK_NUM_FADE_TILES jr z, .doneFade ld b, NUM_FIREWORK_SPRITES ld hl, wShadowOAM + (FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS) + OAMA_TILEID .setFadeSprites: ; set new fade tiles ld [hli], a inc hl inc hl inc hl dec b jr nz, .setFadeSprites jp .explodingStateFade .doneFade: ld a, $01 ; basically no delay, is a delay even necessary? todo: remove delay? ld [wFireworkTimer], a ; delay before shooting another firework xor a ld [wFireworkState], a ; go to idle state jp .explodingStateFade .idleState: ld hl, wFireworkTimer dec [hl] ret nz ; setup shooting up state ld a, [wFireworkCurPalette] inc a and %11 or %100 ld [wFireworkCurPalette], a ; go to next palette ld hl, wShadowOAM + (FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS) ld a, FIREWORK_STARTY ; starting Y pos ld [hli], a ; set sprite Y push hl call genRandom ; generate random X position ld a, h pop hl and $7F ; 0 - 127 add OAM_X_OFS + 15 ; 15 - 142 (+ OAM_X_OFS) ld [hli], a ; set sprite X ld c, a ; save X for later ld a, FIREWORK_TILEINDEX ld [hli], a ; set sprite tile ld a, [wFireworkCurPalette] ; or OAMF_PAL1 ; use OBJ PAL 1 on DMG, FireworkCurPalette on CGB ld [hli], a ; set sprite attributes ld hl, wFireworkArray ; use first array entry to store Y data for initial particle ld a, FIREWORK_STARTY ld [hli], a ; set start Y ld [hli], a ; set subpixel the same as pixel, because why not ld a, HIGH(FIREWORK_START_YVEL) ld [hli], a ; set start Y velocity ld a, LOW(FIREWORK_START_YVEL) ld [hli], a ; set velocity fraction ld a, c ld [hli], a ; set X ld a, 1 ld [wFireworkState], a ; move to shooting up state ld hl, _FX_FireworkShoot jp PlayNewFX ; tail call to play firework shoot sound .flyingState: ld hl, wFireworkArray ld a, FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS ldh [hFireworkSpritePtr], a call updateParticleY ld a, d cp $FF ; continue going if particle has velocity < -1 ret nz ; initialise exploding state ld hl, wFireworkArray ld bc, STARTOF("FireworkVelocityTable") ld d, NUM_FIREWORK_SPRITES .setupArrayLp: ld a, [wFireworkArray] ; ld [hli], a ; load ypos from shooting up particle ld [hli], a ; ld a, [bc] ; inc bc ; ld [hli], a ; yvel ld a, [bc] ; inc bc ; ld [hli], a ; ld a, [wFireworkArray + 4] ; ld [hli], a ; load xpos from shooting up particle ld [hli], a ; ld a, [bc] ; inc bc ; ld [hli], a ; xvel ld a, [bc] ; inc bc ; ld [hli], a ; dec d jr nz, .setupArrayLp ld hl, wShadowOAM + (FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS) + OAMA_TILEID ld b, NUM_FIREWORK_SPRITES .setupSpritesLp: ld a, FIREWORK_TILEINDEX ld [hli], a ld a, [wFireworkCurPalette] ; or OAMF_PAL1 ; use OBJ PAL 1 on DMG, FireworkCurPalette on CGB ld [hli], a ; sprite attributes inc hl inc hl dec b jr nz, .setupSpritesLp ld a, FIREWORK_ALIVETIME ld [wFireworkTimer], a ld a, 2 ld [wFireworkState], a ; move to exploding state ld hl, _FX_FireworkExplode call PlayNewFX ; fall into explode state .explodingState: ld hl, wFireworkTimer dec [hl] jr nz, .explodingStateFade ld a, FIREWORK_FADETIME ld [wFireworkTimer], a ld a, FIREWORK_TILEINDEX ld [wFireworkCurTile], a ld a, 3 ld [wFireworkState], a ; move to fading state .explodingStateFade: ld hl, wFireworkArray ld a, FIREWORK_FIRST_SPRITE * sizeof_OAM_ATTRS ldh [hFireworkSpritePtr], a .mainlp: call updateParticleY ; Update X position push hl ld a, [hli] ; BC = FIREWORK_XPOS ld b, a ld a, [hli] ld c, a ld a, [hli] ; DE = FIREWORK_XVEL ld d, a ld a, [hli] ld e, a add c ; BC = FIREWORK_XPOS + FIREWORK_XVEL ld c, a ld a, d adc b ld b, a pop hl ; reset HL back to FIREWORK_XPOS ld a, b ; save new FIREWORK_XPOS ld [hli], a ld a, c ld [hli], a ; Set sprite X ldh a, [hFireworkSpritePtr] ld c, a ld a, b ld b, HIGH(wShadowOAM) ld [bc], a ld a, c add 3 ; skip over tile and attribute, go to next sprite Y pos ldh [hFireworkSpritePtr], a ; go to next entry inc hl inc hl ; Check if we've done all the particles yet ldh a, [hFireworkSpritePtr] cp (FIREWORK_FIRST_SPRITE + NUM_FIREWORK_SPRITES) * sizeof_OAM_ATTRS jr c, .mainlp ret ; Used in both the flying state and exploding state updateParticleY: ; Update Y Position push hl ld a, [hli] ; BC = FIREWORK_YPOS ld b, a ld a, [hli] ld c, a ld a, [hli] ; DE = FIREWORK_YVEL ld d, a ld a, [hli] ld e, a add c ; BC = FIREWORK_YPOS + FIREWORK_YVEL ld c, a ld a, d adc b ld b, a pop hl ; reset HL back to FIREWORK_YPOS ld a, b ; save new FIREWORK_YPOS ld [hli], a ld a, c ld [hli], a ; Set sprite Y ldh a, [hFireworkSpritePtr] ld c, a ld a, b ld b, HIGH(wShadowOAM) ld [bc], a ld a, c inc a ldh [hFireworkSpritePtr], a ; Apply gravity to Y Velocity push hl ld hl, GRAVITY add hl, de ld d, h ld e, l pop hl ld a, d ld [hli], a ld a, e ld [hli], a ret
; OUT: EAX: upper Memory / 1024 kernel_paging_get_memory: push ebx mov ebx, [kernel_multiboot_info_pointer] mov eax, [ebx] ; EAX has flags and eax, 1 ; If it's zero then it means that the bootloader didn't tell us the memory ; Crash the system if that is the case jz kernel_exception_fault mov eax, [ebx+8] pop ebx ret ; OUT = EAX: Physical memory address of page kernel_paging_allocate_physical_page: mov eax, [kernel_paging_first_free_physical_memory_address] ; Round down to closest multiple of 4096 and eax, 0xFFFFF000 add eax, 4096 mov [kernel_paging_first_free_physical_memory_address], eax ret ; This function allocates some space for a page table ; OUT = EAX: Physical memory address of address where the kernel can place page tables, EBX: Virtual memory address w/ page table kernel_paging_allocate_physical_page_for_page_table: call kernel_paging_allocate_physical_page or eax, KERNEL_PAGING_FLAG_PRESENT | KERNEL_PAGING_FLAG_READ_AND_WRITE xor ebx, ebx mov bx, [kernel_paging_first_free_page_in_meta_page_table] mov [kernel_paging_meta_page_table+ebx*4], eax inc word [kernel_paging_first_free_page_in_meta_page_table] ; ebx * 4KiB + [pde of page table] * 4MiB = virtual address push eax xor eax, eax mov ax, [kernel_paging_meta_page_table_directory_entry] shl eax, 22 ; Divide by 4MiB shl ebx, 12 ; Divide by 4KiB add ebx, eax mov eax, ebx pop eax and eax, 0xFFFFF000 ; Un-set flags ; We could use invlpg here ; But i'm not sure how ; Reload cr3 instead push ecx mov ecx, cr3 mov cr3, ecx pop ecx ret
%define MOD_PMEM ; module: PMem %include "hal/pmem.inc" %include "lib/bitmap.inc" %include "defs/multiboot.inc" %include "debug/debug.inc" struc region_t ; Bookkeeping for this region prev resq 1 ; list of all regions (replace with tree?) next resq 1 lock resq 1 ; for multiprocessor use basePageAddr resq 1 ; address of first pageframe in the region ; Supermap of 2MB pageframes bigpageMap resq 1 ; pointer to wordmap of 2MB pageframes bigpageMapSize resq 1 ; wordmap size in qwords bigpageStart resq 1 ; qword to start scanning (for speed) bigpageFree resq 1 ; number of free big (2MB) pageframes bigpagePrev resq 1 ; list of regions with free bigpages bigpageNext resq 1 ; Map of 4kB pageframes pageMap resq 1 ; pointer to bitmap of 4kB pageframes pageMapSize resq 1 ; bitmap size in qwords pageStart resq 1 ; qword to start scanning (for speed) pageFree resq 1 ; number of free 4kB pageframes pagePrev resq 1 ; list of regions with free pages pageNext resq 1 endstruc [section .text] [bits 64] [global PMemInit] PMemInit: ; Initialize the good-enough region structure mov rdi, pmemRegionRoot xor rcx, rcx mov [rdi + region_t.prev], rcx mov [rdi + region_t.next], rcx mov [rdi + region_t.lock], rcx mov [rdi + region_t.basePageAddr], rcx mov rdx, pmemRootBytemap mov [rdi + region_t.bigpageMap], rdx mov rdx, (1 * 4096) / 8 mov [rdi + region_t.bigpageMapSize], rdx mov [rdi + region_t.bigpageStart], rcx mov [rdi + region_t.bigpageFree], rcx mov [rdi + region_t.bigpagePrev], rcx mov [rdi + region_t.bigpageNext], rcx mov rdx, pmemRootBitmap mov [rdi + region_t.pageMap], rdx mov rdx, (32 * 4096) / 8 mov [rdi + region_t.pageMapSize], rdx mov [rdi + region_t.pageStart], rcx mov [rdi + region_t.pageFree], rcx mov [rdi + region_t.pagePrev], rcx mov [rdi + region_t.pageNext], rcx cld mov rdi, pmemRootBytemap mov rcx, (1 * 4096) / 8 xor rax, rax ; zeros (number of free pageframes) rep stosq mov rdi, pmemRootBitmap mov rcx (32 * 4096) / 8 not rax ; ones (all pageframes in use) rep stosq ; Check for the existence of the memory map mov eax, [rbx + multiboot_info_t.flags] test eax, MBINFO_FLAG_MMAP jz .noMMap ; Start traversing the memory map xor rax, rax xor rcx, rcx mov eax, [rbx + multiboot_info_t.mmap_addr] mov ecx, [rbx + multiboot_info_t.mmap_length] add rcx, rax xor rdx, rdx .mapLoop: mov ebx, [rax + mmap_entry_t.type] ; only a dword cmp ebx, TYPE_FREE jne .mapNext ; Have a free region, mark in the bitmap call PMemFreeBlock .mapNext: ; Keep track of the high watermark ; mov rbx, [rax + mmap_entry_t.base_addr] ; add rbx, [rax + mmap_entry_t.length] ; cmp rbx, rdx ; cmova rdx, rbx ; Next map region add eax, [rax + mmap_entry_t.size] add rax, 0x00000004 cmp rax, rcx jb .mapLoop ; PRINT "Memory high watermark:" ; PRINTQ rdx ret ; No memory map present, try to use memory fields .noMMap: test eax, MBINFO_FLAG_MEM jz .fail ; Use memory info PRINT "No E820 map, using mem info" PRINT "Not yet, LOL." cli hlt .fail: PRINT "PANIC: No memory info found!" cli hlt [global PMemAlloc4K] PMemAlloc4K: ret [global PMemAlloc2M] PMemAlloc2M: ret [global PMemAllocBlock] PMemAllocBlock: ret [global PMemAllocContig] PMemAllocCont: ret [global PMemFree4K] PMemFree4K: push rax push rcx push rsi push rdi ; Find the appropriate region and adjust the address call PMemFindRegion ; Clear the bit in the 4kB pageframe bitmap shr rax, 12 ; change to 4k page index mov rsi, [rdi + region_t.pageMap] mov rcx, [rdi + region_t.pageMapSize] call BitmapBitClear ; Increment the counter in the 2MB pageframe wordmap shr rax, 9 ; change to 2M page index mov rsi, [rdi + region_t.bigpageMap] inc word [rdi + rax * 2] pop rdi pop rsi pop rcx pop rax ret [global PMemFree2M] PMemFree2M: push rax push rbx push rcx push rsi push rdi call PMemFindRegion ; Find the appropriate region and adjust the address call PMemFindRegion ; Clear the bits in the 4kB pageframe bitmap shr rax, 12 ; change to 4k page index mov rsi, [rdi + region_t.pageMap] mov rcx, [rdi + region_t.pageMapSize] mov rbx, 512 ; 4k pageframes per 2M pageframe call BitmapRangeClear ; Reset the counter in the 2MB pageframe wordmap shr rax, 9 ; change to 2M page index mov rsi, [rdi + region_t.bigpageMap] mov word [rdi + rax * 2], bx pop rdi pop rsi pop rcx pop rbx pop rax ret [global PMemFreeBlock] PMemFreeBlock: call PMemFindRegion ret ; = start 4K pageframe ; = number of 4K pageframes PMemClearSupermap: ret PMemSetSupermap: ret ;------------------------------------------------------------------------------- ; function: PMemFindRegion ; ; brief: Finds a region? ; ; pass: ; rax = start 4K pageframe address ; / ; ; return: ; cf = set on error, clear on success ; rdi -> region ; rax = offset into region (still byte-aligned) ; / ; ; sideeffects: ; / ; ; detail: ; / ;------------------------------------------------------------------------------- PMemFindRegion: ; TODO: scan through list of regions ; this is here as a placeholder for now so the hooks are in place ; for later mov rdi, pmemRegionRoot sub rax, [rdi + region_t.basePageAddr] clc ret [section .data] [section .bss] ; Good enough for now - single region of 4GB pmemRegionRoot: resb region_t_size pmemRootBytemap: resb 1 * 4096 pmemRootBitmap: resb 32 * 4096
/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "Utils/CommandLineOption.hpp" #include <iostream> #include <QCoreApplication> #include <QFileInfo> #include <QCommandLineOption> #include <QCommandLineParser> namespace Sn { CommandLineOption::CommandLineOption() { parseActions(); } void CommandLineOption::parseActions() { QCommandLineOption authorsOption{QStringList() << QStringLiteral("a") << QStringLiteral("authors")}; authorsOption.setDescription(QStringLiteral("Display author information.")); QCommandLineOption privateBrowsingOption(QStringList() << QStringLiteral("i") << QStringLiteral("private-browsing")); privateBrowsingOption.setDescription(QStringLiteral("Starts private browsing.")); QCommandLineOption noRemoteOption{QStringList() << QStringLiteral("r") << QStringLiteral("no-remote")}; noRemoteOption.setDescription(QStringLiteral("Starts new browser instance.")); QCommandLineOption newTabOption{QStringList() << QStringLiteral("t") << QStringLiteral("new-tab")}; newTabOption.setDescription(QStringLiteral("Opens new tab.")); QCommandLineOption newWindowOption{QStringList() << QStringLiteral("w") << QStringLiteral("new-window")}; newWindowOption.setDescription(QStringLiteral("Opens new window")); QCommandLineOption currentTabOption{QStringList() << QStringLiteral("c") << QStringLiteral("current-tab")}; currentTabOption.setValueName(QStringLiteral("URL")); currentTabOption.setDescription(QStringLiteral("Opens URL in current tab")); QCommandLineOption openWindowOption(QStringList() << QStringLiteral("u") << QStringLiteral("open-window")); openWindowOption.setValueName(QStringLiteral("URL")); openWindowOption.setDescription(QStringLiteral("Opens URL in new window.")); QCommandLineParser parser{}; parser.setApplicationDescription(QStringLiteral("A fast web browser in C++ with Qt")); QCommandLineOption helpOption{parser.addHelpOption()}; QCommandLineOption versionOption{parser.addVersionOption()}; parser.addOption(authorsOption); parser.addOption(privateBrowsingOption); parser.addOption(noRemoteOption); parser.addOption(newTabOption); parser.addOption(newWindowOption); parser.addOption(currentTabOption); parser.addOption(openWindowOption); parser.addPositionalArgument(QStringLiteral("URL"), QStringLiteral("URLs to open"), QStringLiteral("[URL...]")); parser.parse(QCoreApplication::arguments()); if (parser.isSet(helpOption)) parser.showHelp(); if (parser.isSet(authorsOption)) { std::cout << "Victor DENIS <admin@feldrise.com>" << std::endl; ActionPair pair; pair.action = Application::CL_ExitAction; m_action.append(pair); return; } if (parser.isSet(privateBrowsingOption)) { ActionPair pair; pair.action = Application::CL_StartPrivateBrowsing; m_action.append(pair); } if (parser.isSet(noRemoteOption)) { ActionPair pair; pair.action = Application::CL_StartNewInstance; m_action.append(pair); } if (parser.isSet(newTabOption)) { ActionPair pair; pair.action = Application::CL_NewTab; m_action.append(pair); } if (parser.isSet(newWindowOption)) { ActionPair pair; pair.action = Application::CL_NewWindow; m_action.append(pair); } if (parser.isSet(currentTabOption)) { ActionPair pair; pair.action = Application::CL_OpenUrlInCurrentTab; pair.text = parser.value(currentTabOption); m_action.append(pair); } if (parser.isSet(openWindowOption)) { ActionPair pair; pair.action = Application::CL_OpenUrlInNewWindow; pair.text = parser.value(openWindowOption); m_action.append(pair); } if (parser.positionalArguments().isEmpty()) return; QString url{parser.positionalArguments().last()}; QFileInfo fileInfo{url}; if (fileInfo.exists()) url = fileInfo.absoluteFilePath(); if (!url.isEmpty() && !url.startsWith(QLatin1Char('-'))) { ActionPair pair; pair.action = Application::CL_OpenUrl; pair.text = url; m_action.append(pair); } // http://feldrise.com } }
device zxspectrum48 org $C000 ; must be in last 16k as I'm using all-RAM mapping for Layer2 INCLUDE "../../Constants.asm" INCLUDE "../../Macros.asm" INCLUDE "../../TestFunctions.asm" INCLUDE "../../TestData.asm" INCLUDE "../../OutputFunctions.asm" INCLUDE "../../timing.i.asm" ; colour definitions C_BLACK equ %00000000 ; 0 C_WHITE equ %10110110 ; 1 C_WHITE2 equ %10010010 ; 2 C_B_WHITE equ %11111111 ; 3 C_T_WHITE equ %01101101 ; 4 C_B_YELLOW equ %11011000 ; 5 C_B_GREEN equ %00011000 ; 6 C_PINK equ $E3 ; 7 C_B_GREEN2 equ %00011100 ; 8 C_B_CYAN equ %00011011 ; 9 C_PINK2 equ $E3 ; 10 C_TEXT equ %11110011 ; 11 C_D1_TEXT equ %01100101 ; 12 ; soft shadow edges ([+1,0], [0,+1]) C_D2_TEXT equ %00000000 ; 13 ; hard shadow [+1,+1] CI_BLACK equ 0 CI_WHITE equ 1 CI_WHITE2 equ 2 ; for emphasisig different layer priority block CI_B_WHITE equ 3 CI_T_WHITE equ 4 CI_B_YELLOW equ 5 CI_B_GREEN equ 6 CI_PINK equ 7 CI_B_GREEN2 equ 8 ; for Layer2 it will get "priority" bit set CI_B_CYAN equ 9 CI_PINK2 equ 10 ; for Layer2 it will get "priority" bit set CI_TEXT equ 11 CI_D1_TEXT equ 12 CI_D2_TEXT equ 13 colourDef: db C_BLACK, C_WHITE, C_WHITE2, C_B_WHITE, C_T_WHITE, C_B_YELLOW, C_B_GREEN db C_PINK, C_B_GREEN2, C_B_CYAN, C_PINK2, C_TEXT, C_D1_TEXT, C_D2_TEXT colourDefSz equ $ - colourDef LegendText: db 'Legend', 0 Start: call StartTest ; Set first-ULA palette, enable ULANext, enable auto-inc NEXTREG_nn PALETTE_CONTROL_NR_43, %00000001 NEXTREG_nn PALETTE_INDEX_NR_40, 0 ; index 0 (ink) call SetTestPalette NEXTREG_nn PALETTE_INDEX_NR_40, 128 ; index 128 (paper+border) call SetTestPalette NEXTREG_nn PALETTE_FORMAT_NR_42, $0F ; ULANext INK mask 15 ; Set first-Sprite palette, enable ULANext, enable auto-inc NEXTREG_nn PALETTE_CONTROL_NR_43, %00100001 NEXTREG_nn PALETTE_INDEX_NR_40, 0 ; index 0 call SetTestPalette ; Set first-Layer2 palette, enable ULANext, enable auto-inc NEXTREG_nn PALETTE_CONTROL_NR_43, %00010001 NEXTREG_nn PALETTE_INDEX_NR_40, 0 ; index 0 call SetTestPalette ; this did set only 8 bit colours ; modify the two extra colours exercising the "priority" bit NEXTREG_nn PALETTE_INDEX_NR_40, CI_B_GREEN2 NEXTREG_nn PALETTE_VALUE_9BIT_NR_44, C_B_GREEN2 NEXTREG_nn PALETTE_VALUE_9BIT_NR_44, $80 ; set priority bit, Blue=0 NEXTREG_nn PALETTE_INDEX_NR_40, CI_PINK2 NEXTREG_nn PALETTE_VALUE_9BIT_NR_44, C_PINK2 NEXTREG_nn PALETTE_VALUE_9BIT_NR_44, $81 ; set priority bit, Blue=1 ; setup transparency features - make pink transparent and visible as fallback NEXTREG_nn GLOBAL_TRANSPARENCY_NR_14, C_PINK NEXTREG_nn TRANSPARENCY_FALLBACK_COL_NR_4A, C_PINK NEXTREG_nn SPRITE_TRANSPARENCY_I_NR_4B, CI_PINK ; sprite transparency needs index ; show yellow border while drawing and preparing... BORDER CI_B_YELLOW ; draw ULA screen0 call DrawUlaPart ; draw the ULA part for pixel combining ; reset LoRes scroll registers (does affect ULA screen since core 2.00.25+) NEXTREG_nn LORES_XOFFSET_NR_32, 0 NEXTREG_nn LORES_YOFFSET_NR_33, 0 ; reset Layer2 scroll registers NEXTREG_nn LAYER2_XOFFSET_NR_16, 0 NEXTREG_nn LAYER2_YOFFSET_NR_17, 0 ; setup Layer2 bank to 9 (like NextZXOS does) NEXTREG_nn LAYER2_RAM_BANK_NR_12, 9 ; make Layer2 visible ld bc, LAYER2_ACCESS_P_123B ld a, LAYER2_ACCESS_L2_ENABLED out (c), a ; map last third of Layer2 into memory (into 8000..BFFF region) NEXTREG_nn MMU4_8000_NR_54, 22 ; $04 NEXTREG_nn MMU5_A000_NR_55, 23 ; $05 ; intermezzo - prepare sprite graphics + upload them, in the last third of L2 area call PrepareSpriteGraphics ; map whole Layer2 into memory (into 0000..BFFF region) (commented are default values) NEXTREG_nn MMU0_0000_NR_50, 18 ; $FF NEXTREG_nn MMU1_2000_NR_51, 19 ; $FF NEXTREG_nn MMU2_4000_NR_52, 20 ; $0A NEXTREG_nn MMU3_6000_NR_53, 21 ; $0B ; Draw Layer2: clear Layer2 with transparent colour + draw test info FILL_AREA $0000, 256*192, CI_PINK call DrawLayer2Part ; map full ROM back to make ROM characters graphics available NEXTREG_nn MMU0_0000_NR_50, $FF NEXTREG_nn MMU1_2000_NR_51, $FF ; use Layer2-over-ROM feature to write into Layer2 for 0000..3FFF region ld a,LAYER2_ACCESS_WRITE_OVER_ROM+LAYER2_ACCESS_L2_ENABLED+LAYER2_ACCESS_OVER_ROM_BANK_0 ; enable layer2, write-over-ROM, and select bank 0 for write ld bc,LAYER2_ACCESS_P_123B out (c),a ; this effectively creates L2-full-RAM mode in 0000..BFFF for WRITE call DrawCharLabels ; map low RAM back to make im1 work (updates counters in $5B00+ area) NEXTREG_nn MMU2_4000_NR_52, $0A NEXTREG_nn MMU3_6000_NR_53, $0B ; all drawing is now finished, the test will enter loop just changing layer-modes ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; loop infinitely and set correct layer ordering for various parts of screen ; the TEST areas (except the first one) are at x:88 coordinate, giving probably ; almost enough time to control register NR_15 to kick-in and modify output. ; The scanline does change at pixel x:0, i.e. after that there are instructions: ; IN 12T, JR cc 7T, RET 10T, NEXTREG_nn 20T ; => roughly 49T until the layer order is modified (first pixels of TEST may be wrong) ; (better solution would be to use COPPER for these, but when written like this, ; the test does not depend on COPPER existance/emulation, so it's written like this) ScanlinesLoop: ei halt BORDER CI_WHITE ;; SLU phase (scanlines 0..31) ; Set layers to: SLU, enable sprites (no over border), no LoRes NEXTREG_nn SPRITE_CONTROL_NR_15, %00000001 ; wait some fixed time after IM1 handler to get into scanlines 255+ IDLE_WAIT $0002 ; wait until scanline MSB becomes 0 again (scanline 0) WAIT_FOR_SCANLINE_MSB 0 ; wait until scanline 32 (31 and well over half, flip rendering after half-line) WAIT_HALF_SCANLINE_AFTER 31 ;; LSU phase (scanlines 32..63) - white border NEXTREG_nn SPRITE_CONTROL_NR_15, %00000101 BORDER CI_WHITE2 WAIT_HALF_SCANLINE_AFTER 63 ;; SUL phase (scanlines 64..95) - grey border NEXTREG_nn SPRITE_CONTROL_NR_15, %00001001 BORDER CI_WHITE WAIT_HALF_SCANLINE_AFTER 95 ;; LUS phase (scanlines 96..127) - white border NEXTREG_nn SPRITE_CONTROL_NR_15, %00001101 BORDER CI_WHITE2 WAIT_HALF_SCANLINE_AFTER 127 ;; USL phase (scanlines 128..159) - grey border NEXTREG_nn SPRITE_CONTROL_NR_15, %00010001 BORDER CI_WHITE WAIT_HALF_SCANLINE_AFTER 159 ;; ULS phase (scanlines 160..191) - white border NEXTREG_nn SPRITE_CONTROL_NR_15, %00010101 BORDER CI_WHITE2 ; make bottom border white WAIT_HALF_SCANLINE_AFTER 191 BORDER CI_WHITE jr ScanlinesLoop ;call EndTest ;;;;;;;;;;;;;;;;;;;;;;;; Set palette (currently selected one) ;;;;;;;;;;;;;;;;;;; SetTestPalette: ld hl,colourDef ld b,colourDefSz .SetPaletteColours: ld a,(hl) NEXTREG_A PALETTE_VALUE_NR_41 inc hl djnz .SetPaletteColours ret ;;;;;;;;;;;;;;;;;;;;;;;; Draw ULA part ;;;;;;;;;;;;;;;;;;; DrawUlaPart: ; set all attributes: black on white FILL_AREA MEM_ZX_ATTRIB_5800, 32*24, CI_BLACK + (CI_WHITE<<4) ; set dark white under certain areas to emphasise the separate sections ld hl,MEM_ZX_ATTRIB_5800+4*32 ld e,3 .DarkSectionsLoop: ld bc,$040F ld a,CI_BLACK + (CI_WHITE2<<4) call .DrawNxM_AttributeBox ld bc,4*32 add hl,bc dec e jr nz,.DarkSectionsLoop ; draw MachineID and core versions: ld de,MEM_ZX_SCREEN_4000 + 1*32 + 18 ; AT [1,18] machineID ld bc,MEM_ZX_SCREEN_4000 + 2*32 + 18 ; AT [2,18] core call OutMachineIdAndCore_defLabels ld hl,LegendText ld de,MEM_ZX_SCREEN_4000 + 4*32 + 23 call OutStringAtDe ; make ULA transparent under other "legend" boxes ld hl,MEM_ZX_ATTRIB_5800 + 6*32 + 23 ; SPRITE leg. NEEDS even line, odd column! call .Draw4x6TransparentBoxes ld hl,MEM_ZX_ATTRIB_5800 + 11*32 + 23 call .Draw4x6TransparentBoxes ld hl,MEM_ZX_ATTRIB_5800 + 16*32 + 23 call .Draw4x6TransparentBoxes ; make ULA transparent under legend-label area ld hl,MEM_ZX_ATTRIB_5800 + 0 ld bc,$1804 call .DrawNxMTransparentBoxes ; set attributes of "result" 6x4 boxes ld hl,MEM_ZX_ATTRIB_5800 + 5 ld e,6 .DrawTestDataForOtherModes: call .Draw4x6TestData dec e jr nz,.DrawTestDataForOtherModes ret .Draw4x6TestData: call .Draw2x6Boxes .Draw2x6Boxes: ld a,CI_BLACK+CI_B_CYAN<<4 ld bc,$0106 call .DrawNxM_AttributeBox inc b jr .DrawNxMTransparentBoxes .Draw4x6TransparentBoxes: ld bc,$0406 .DrawNxMTransparentBoxes: ld a,CI_BLACK+CI_PINK<<4 ; HL = target address, BC = rows/columns, A = attribute .DrawNxM_AttributeBox: push bc push hl ld b,0 call FillArea pop hl push af call AdvanceAttrHlToNextLine pop af pop bc djnz .DrawNxM_AttributeBox ret ;;;;;;;;;;;;;;;;;;;;;;;; Draw Layer2 part ;;;;;;;;;;;;;;;;;;; DrawLayer2Part: ; draw "legend" boxes, draw expected result areas and also the test-areas themselves ; fill background under "label/expected" areas (all 6 of them in one fill) ld a,8 ld de,CI_WHITE*256 + CI_WHITE ld bc,$0418 ld hl,0*256 + 0 call FillL2Box ; set dark white under certain areas to emphasise the separate sections ld de,CI_WHITE2*256 + CI_WHITE2 ld bc,$0404 ld hl,4*8*256 + 0 .DarkSectionsLoop: ld a,8 call FillL2Box ld a,h add a,8*8 ld h,a cp 3*8*8 jr c,.DarkSectionsLoop ; draw expected result area for orders: SLU, LSU, SUL, LUS, USL, ULS ld hl,12*256 + 4 ; SLU call .DrawExpectedResultTransparent call .DrawExpectedResultUla call .DrawExpectedResultLayer2 call .DrawExpectedResultSprites call .DrawExpectedResultLayer2p ld a,4*8 add a,h ld h,a ; LSU call .DrawExpectedResultTransparent call .DrawExpectedResultUla call .DrawExpectedResultSprites call .DrawExpectedResultLayer2 call .DrawExpectedResultLayer2p ld a,4*8 add a,h ld h,a ; SUL call .DrawExpectedResultTransparent call .DrawExpectedResultLayer2 call .DrawExpectedResultUla call .DrawExpectedResultSprites call .DrawExpectedResultLayer2p ld a,4*8 add a,h ld h,a ; LUS call .DrawExpectedResultTransparent call .DrawExpectedResultSprites call .DrawExpectedResultUla call .DrawExpectedResultLayer2 call .DrawExpectedResultLayer2p ld a,4*8 add a,h ld h,a ; USL call .DrawExpectedResultTransparent call .DrawExpectedResultLayer2 call .DrawExpectedResultSprites call .DrawExpectedResultUla call .DrawExpectedResultLayer2p ld a,4*8 add a,h ld h,a ; ULS call .DrawExpectedResultTransparent call .DrawExpectedResultSprites call .DrawExpectedResultLayer2 call .DrawExpectedResultUla call .DrawExpectedResultLayer2p ; draw Sprite-legend ld a,1 ld hl,6*8*256 + 8*(23+0) ld de,CI_BLACK*256 + CI_WHITE ld bc,$0820 call FillL2Box ld l,8*(23+5) call FillL2Box ld de,CI_B_YELLOW*256 + CI_B_YELLOW ld l,8*(23+1) call FillL2Box ld l,8*(23+3) call FillL2Box ld de,CI_B_WHITE*256 + CI_T_WHITE ld bc,$0410 ld l,8*(23+2) call FillL2BoxWithDither2x2 ld l,8*(23+4) call FillL2BoxWithDither2x2 ; draw the dithered 16x16 boxes to reveal full sprite size ld de,SPR_DITHER_BOX_GFX ld hl,(6+0)*8*256 + 8*(23+1) call DrawDitherGfxInside16x16Box ld hl,(6+0)*8*256 + 8*(23+3) call DrawDitherGfxInside16x16Box ld hl,(6+2)*8*256 + 8*(23+1) call DrawDitherGfxInside16x16Box ld hl,(6+2)*8*256 + 8*(23+3) call DrawDitherGfxInside16x16Box ; draw Layer2-legend ld bc,$0C08 ld de,CI_B_WHITE*256 + CI_T_WHITE ld hl,(11+2)*8*256 + 8*(23+0) call FillL2BoxWithDither2x2 ld de,CI_B_WHITE*256 + CI_WHITE ld hl,(11+2)*8*256 + 8*(23+3) call FillL2BoxWithDither2x2 ld de,CI_B_GREEN*256 + CI_B_GREEN ld hl,(11+0)*8*256 + 8*(23+0) call FillL2BoxWithDither2x2 ld de,CI_B_GREEN2*256 + CI_B_GREEN2 ld hl,(11+0)*8*256 + 8*(23+3) call FillL2BoxWithDither2x2 ; draw Layer2 TEST pixels for all combining modes ld h,(0+0)*8 ld ixl,6 .OtherModesDrawLoop: ld l,8*(5+0) ld de,CI_B_GREEN*256 + CI_B_GREEN call FillL2BoxWithDither2x2 ld l,8*(5+3) ld de,CI_B_GREEN2*256 + CI_B_GREEN2 call FillL2BoxWithDither2x2 ld a,16 add a,h ld h,a ld de,CI_PINK2*256 + CI_PINK2 call FillL2BoxWithDither2x2 ld a,16 add a,h ld h,a dec ixl jr nz,.OtherModesDrawLoop ; draw ULA-legend ld de,CI_B_WHITE*256 + CI_T_WHITE ld bc,$180C ld hl,(16+1)*8*256 + 8*(23+0) call FillL2BoxWithDither2x2 ld de,CI_B_CYAN*256 + CI_B_CYAN ld bc,$1804 ld hl,(16+0)*8*256 + 8*(23+0) call FillL2BoxWithDither2x2 ld hl,(16+2)*8*256 + 8*(23+0) call FillL2BoxWithDither2x2 ret .DrawExpectedResultTransparent: ld bc,$0C08 ld de,CI_B_WHITE*256 + CI_T_WHITE jp FillL2BoxWithDither2x2 .DrawExpectedResultUla: push hl ld de,CI_B_CYAN*256 + CI_B_CYAN ld bc,$0C02 ld a,2*4 add a,h ld h,a call FillL2BoxWithDither2x2 pop hl jp FillL2BoxWithDither2x2 .DrawExpectedResultSprites: push hl ld de,CI_B_YELLOW*256 + CI_B_YELLOW ld bc,$0208 ld a,1*4 add a,l ld l,a call FillL2BoxWithDither2x2 ld a,2*4 add a,l ld l,a call FillL2BoxWithDither2x2 pop hl ret .DrawExpectedResultLayer2: ld de,CI_B_GREEN*256 + CI_B_GREEN ld bc,$0604 jp FillL2BoxWithDither2x2 .DrawExpectedResultLayer2p: ;; Layer2 priority part push hl ld de,CI_B_GREEN2*256 + CI_B_GREEN2 ld bc,$0604 ld a,3*4 add a,l ld l,a call FillL2BoxWithDither2x2 pop hl ret ;;;;;;;;;;;;;;;;;;;;;;;; Setup Sprites part ;;;;;;;;;;;;;;;;;;; SPR_DITHER_BOX_GFX equ $0300 + CI_BLACK PrepareSpriteGraphics: ; draw transparent sprite colour (8x16px) ld a,1 ld bc,$0408 ld hl,$8008 ld de,CI_PINK*256 + CI_PINK call FillL2BoxWithDither2x2 ; draw the solid sprite colour (8x16px) ld l,0 ld de,CI_B_YELLOW*256 + CI_B_YELLOW call FillL2BoxWithDither2x2 ; draw the dithered rectangle inside sprite ld de,SPR_DITHER_BOX_GFX ; HL = $8000 already call DrawDitherGfxInside16x16Box ; upload prepared sprite pattern ld bc,SPRITE_STATUS_SLOT_SELECT_P_303B out (c), 0 ; Write to pattern/attribute slot 0 ld c,SPRITE_PATTERN_P_5B ; port number for pattern upload ld hl,$8000 ; starting xy L2 coordinates (= memory address) call .UploadOnePatternFromL2 ; set up sprites to be drawn (4 byte attribute set is enough for this test) ; set four sprites over test area for all 6 modes ld b,6 ld de,$2020 + 0*8*256 + 8*(5+1) ; [x,y] ld hl,$8000 ; H: visible, 4Bset, pattern 0, L:palOfs 0, ..., X9 0 .SetSpritesForOtherModes: call .UploadOneAttribSet ld a,16 add a,e ld e,a call .UploadOneAttribSet ld a,16 add a,d ld d,a call .UploadOneAttribSet ld a,-16 add a,e ld e,a call .UploadOneAttribSet ld a,16 add a,d ld d,a djnz .SetSpritesForOtherModes ; make sure all other sprites are not visible (only expects 64 total sprites) ld h,0 ; with new total 128 the remaining 64 are not set! ld b,64-6*4 .SetRemainingSpritesLoop: call .UploadOneAttribSet djnz .SetRemainingSpritesLoop ret ;E: byte1, D: byte2, L: byte3, H: byte4 .UploadOneAttribSet: ld c,SPRITE_ATTRIBUTE_P_57 out (c),e ; low8b X out (c),d ; low8b Y out (c),l ; palette offset, mirror/rotation, X9 out (c),h ; visible, 4/5B set, pattern 0..63 ret .UploadOnePatternFromL2: ld a,h add a,16 ; ending Y coordinate .UploadOnePatternPixels: push hl ld b,16 otir pop hl inc h cp h jr nz,.UploadOnePatternPixels ret ;;;;;;;;;;;;;;;;; Draw letter-hints into Layer2 ;;;;;;;;;;;;;;;;;;; LayerOrderLabelsTxt: ; array[X, Y, ASCIIZ], $FF db $C4, $34, "S", 0, $C0, $64, "L", 0, $D4, $64, "Lp", 0, $CC, $8C, "U", 0 db $04, $03, "SLU", 0, $04, $23, "LSU", 0, $04, $43, "SUL", 0 db $04, $63, "LUS", 0, $04, $83, "USL", 0, $04, $A3, "ULS", 0 db $FF DrawCharLabels: ; single-letter hints into legend with the Separate-layer graphics ; and Layers order scheme above expected results ld bc,CI_TEXT*256 + CI_D1_TEXT ; print colours ld hl,LayerOrderLabelsTxt jp OutL2StringsIn3Cols ;;;;;;;;;;;;;;;;;;;;;;;; Helper functions ;;;;;;;;;;;;;;;;;;; ; HL: coordinates, E:colour, D:ditherMask (pixels-1) DrawDitherGfxInside16x16Box: push af push hl push bc ld bc,$1010 ; 16x16 fixed size of this box (can't change easily because $0E) .DitherRowLoop: push hl push bc .DitherPixelLoop: ld a,h xor l and d jr nz,.DoNotDot ld a,h xor 2 ; moves the dots toward inside (with xor0 the edge of sprite is dotted) inc a ; 0 -> 1, 0F -> 10 and $0E ; 0 -> H=x0/xF jr z,.DoDot ld a,l xor 2 inc a ; 0 -> 1, 0F -> 10 and $0E ; 0 -> L=x0/xF jr nz,.DoNotDot .DoDot: ld (hl),e .DoNotDot: inc l djnz .DitherPixelLoop pop bc pop hl inc h dec c jr nz,.DitherRowLoop pop bc pop hl pop af ret savesna "L2Colour.sna", Start
/* Copyright (c) 2006, NIF File Format Library and Tools All rights reserved. Please see niflib.h for license. */ //-----------------------------------NOTICE----------------------------------// // Some of this file is automatically filled in by a Python script. Only // // add custom code in the designated areas or it will be overwritten during // // the next update. // //-----------------------------------NOTICE----------------------------------// //--BEGIN FILE HEAD CUSTOM CODE--// //--END CUSTOM CODE--// #include "nif/FixLink.h" #include "nif/ObjectRegistry.h" #include "nif/NIF_IO.h" #include "nif/obj/BSLightingShaderProperty.h" #include "nif/obj/BSShaderTextureSet.h" using namespace Niflib; //Definition of TYPE constant const Type BSLightingShaderProperty::TYPE("BSLightingShaderProperty", &NiProperty::TYPE ); BSLightingShaderProperty::BSLightingShaderProperty() : shaderFlags1((SkyrimShaderPropertyFlags1)2185233153), shaderFlags2((SkyrimShaderPropertyFlags2)32801), uvScale(1.0, 1.0), textureSet(NULL), emissiveMultiple(0.0f), textureClampMode((TexClampMode)0), alpha(1.0f), unknownFloat2(0.0f), glossiness(0.0f), specularStrength(1.0f), lightingEffect1(0.0f), lightingEffect2(0.0f), environmentMapScale(0.0f), maxPasses(0.0f), scale(0.0f), parallaxInnerLayerThickness(0.0f), parallaxRefractionScale(0.0f), parallaxEnvmapStrength(0.0f), eyeCubemapScale(0.0f) { //--BEGIN CONSTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } BSLightingShaderProperty::~BSLightingShaderProperty() { //--BEGIN DESTRUCTOR CUSTOM CODE--// //--END CUSTOM CODE--// } const Type & BSLightingShaderProperty::GetType() const { return TYPE; } NiObject * BSLightingShaderProperty::Create() { return new BSLightingShaderProperty; } void BSLightingShaderProperty::Read( istream& in, list<unsigned int> & link_stack, const NifInfo & info ) { //--BEGIN PRE-READ CUSTOM CODE--// //--END CUSTOM CODE--// unsigned int block_num; NiProperty::Read( in, link_stack, info ); if ( (info.userVersion == 12) ) { NifStream( shaderFlags1, in, info ); NifStream( shaderFlags2, in, info ); }; NifStream( uvOffset, in, info ); NifStream( uvScale, in, info ); NifStream( block_num, in, info ); link_stack.push_back( block_num ); NifStream( emissiveColor, in, info ); NifStream( emissiveMultiple, in, info ); NifStream( textureClampMode, in, info ); NifStream( alpha, in, info ); NifStream( unknownFloat2, in, info ); NifStream( glossiness, in, info ); NifStream( specularColor, in, info ); NifStream( specularStrength, in, info ); NifStream( lightingEffect1, in, info ); NifStream( lightingEffect2, in, info ); if ( (skyrimShaderType == 1) ) { NifStream( environmentMapScale, in, info ); }; if ( (skyrimShaderType == 5) ) { NifStream( skinTintColor, in, info ); }; if ( (skyrimShaderType == 6) ) { NifStream( hairTintColor, in, info ); }; if ( (skyrimShaderType == 7) ) { NifStream( maxPasses, in, info ); NifStream( scale, in, info ); }; if ( (skyrimShaderType == 11) ) { NifStream( parallaxInnerLayerThickness, in, info ); NifStream( parallaxRefractionScale, in, info ); NifStream( parallaxInnerLayerTextureScale, in, info ); NifStream( parallaxEnvmapStrength, in, info ); }; if ( (skyrimShaderType == 14) ) { NifStream( sparkleParameters, in, info ); }; if ( (skyrimShaderType == 16) ) { NifStream( eyeCubemapScale, in, info ); NifStream( leftEyeReflectionCenter, in, info ); NifStream( rightEyeReflectionCenter, in, info ); }; //--BEGIN POST-READ CUSTOM CODE--// //--END CUSTOM CODE--// } void BSLightingShaderProperty::Write( ostream& out, const map<NiObjectRef,unsigned int> & link_map, list<NiObject *> & missing_link_stack, const NifInfo & info ) const { //--BEGIN PRE-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// NiProperty::Write( out, link_map, missing_link_stack, info ); if ( (info.userVersion == 12) ) { NifStream( shaderFlags1, out, info ); NifStream( shaderFlags2, out, info ); }; NifStream( uvOffset, out, info ); NifStream( uvScale, out, info ); if ( info.version < VER_3_3_0_13 ) { WritePtr32( &(*textureSet), out ); } else { if ( textureSet != NULL ) { map<NiObjectRef,unsigned int>::const_iterator it = link_map.find( StaticCast<NiObject>(textureSet) ); if (it != link_map.end()) { NifStream( it->second, out, info ); missing_link_stack.push_back( NULL ); } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( textureSet ); } } else { NifStream( 0xFFFFFFFF, out, info ); missing_link_stack.push_back( NULL ); } } NifStream( emissiveColor, out, info ); NifStream( emissiveMultiple, out, info ); NifStream( textureClampMode, out, info ); NifStream( alpha, out, info ); NifStream( unknownFloat2, out, info ); NifStream( glossiness, out, info ); NifStream( specularColor, out, info ); NifStream( specularStrength, out, info ); NifStream( lightingEffect1, out, info ); NifStream( lightingEffect2, out, info ); if ( (skyrimShaderType == 1) ) { NifStream( environmentMapScale, out, info ); }; if ( (skyrimShaderType == 5) ) { NifStream( skinTintColor, out, info ); }; if ( (skyrimShaderType == 6) ) { NifStream( hairTintColor, out, info ); }; if ( (skyrimShaderType == 7) ) { NifStream( maxPasses, out, info ); NifStream( scale, out, info ); }; if ( (skyrimShaderType == 11) ) { NifStream( parallaxInnerLayerThickness, out, info ); NifStream( parallaxRefractionScale, out, info ); NifStream( parallaxInnerLayerTextureScale, out, info ); NifStream( parallaxEnvmapStrength, out, info ); }; if ( (skyrimShaderType == 14) ) { NifStream( sparkleParameters, out, info ); }; if ( (skyrimShaderType == 16) ) { NifStream( eyeCubemapScale, out, info ); NifStream( leftEyeReflectionCenter, out, info ); NifStream( rightEyeReflectionCenter, out, info ); }; //--BEGIN POST-WRITE CUSTOM CODE--// //--END CUSTOM CODE--// } std::string BSLightingShaderProperty::asString( bool verbose ) const { //--BEGIN PRE-STRING CUSTOM CODE--// //--END CUSTOM CODE--// stringstream out; out << NiProperty::asString(); out << " Shader Flags 1: " << shaderFlags1 << endl; out << " Shader Flags 2: " << shaderFlags2 << endl; out << " UV Offset: " << uvOffset << endl; out << " UV Scale: " << uvScale << endl; out << " Texture Set: " << textureSet << endl; out << " Emissive Color: " << emissiveColor << endl; out << " Emissive Multiple: " << emissiveMultiple << endl; out << " Texture Clamp Mode: " << textureClampMode << endl; out << " Alpha: " << alpha << endl; out << " Unknown Float 2: " << unknownFloat2 << endl; out << " Glossiness: " << glossiness << endl; out << " Specular Color: " << specularColor << endl; out << " Specular Strength: " << specularStrength << endl; out << " Lighting Effect 1: " << lightingEffect1 << endl; out << " Lighting Effect 2: " << lightingEffect2 << endl; if ( (skyrimShaderType == 1) ) { out << " Environment Map Scale: " << environmentMapScale << endl; }; if ( (skyrimShaderType == 5) ) { out << " Skin Tint Color: " << skinTintColor << endl; }; if ( (skyrimShaderType == 6) ) { out << " Hair Tint Color: " << hairTintColor << endl; }; if ( (skyrimShaderType == 7) ) { out << " Max Passes: " << maxPasses << endl; out << " Scale: " << scale << endl; }; if ( (skyrimShaderType == 11) ) { out << " Parallax Inner Layer Thickness: " << parallaxInnerLayerThickness << endl; out << " Parallax Refraction Scale: " << parallaxRefractionScale << endl; out << " Parallax Inner Layer Texture Scale: " << parallaxInnerLayerTextureScale << endl; out << " Parallax Envmap Strength: " << parallaxEnvmapStrength << endl; }; if ( (skyrimShaderType == 14) ) { out << " Sparkle Parameters: " << sparkleParameters << endl; }; if ( (skyrimShaderType == 16) ) { out << " Eye Cubemap Scale: " << eyeCubemapScale << endl; out << " Left Eye Reflection Center: " << leftEyeReflectionCenter << endl; out << " Right Eye Reflection Center: " << rightEyeReflectionCenter << endl; }; return out.str(); //--BEGIN POST-STRING CUSTOM CODE--// //--END CUSTOM CODE--// } void BSLightingShaderProperty::FixLinks( const map<unsigned int,NiObjectRef> & objects, list<unsigned int> & link_stack, list<NiObjectRef> & missing_link_stack, const NifInfo & info ) { //--BEGIN PRE-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// NiProperty::FixLinks( objects, link_stack, missing_link_stack, info ); textureSet = FixLink<BSShaderTextureSet>( objects, link_stack, missing_link_stack, info ); //--BEGIN POST-FIXLINKS CUSTOM CODE--// //--END CUSTOM CODE--// } std::list<NiObjectRef> BSLightingShaderProperty::GetRefs() const { list<Ref<NiObject> > refs; refs = NiProperty::GetRefs(); if ( textureSet != NULL ) refs.push_back(StaticCast<NiObject>(textureSet)); return refs; } std::list<NiObject *> BSLightingShaderProperty::GetPtrs() const { list<NiObject *> ptrs; ptrs = NiProperty::GetPtrs(); return ptrs; } //--BEGIN MISC CUSTOM CODE--// SkyrimShaderPropertyFlags1 BSLightingShaderProperty::GetShaderFlags1() const { return shaderFlags1; } void BSLightingShaderProperty::SetShaderFlags1( SkyrimShaderPropertyFlags1 value ) { shaderFlags1 = value; } SkyrimShaderPropertyFlags2 BSLightingShaderProperty::GetShaderFlags2() const { return shaderFlags2; } void BSLightingShaderProperty::SetShaderFlags2( SkyrimShaderPropertyFlags2 value ) { shaderFlags2 = value; } TexCoord BSLightingShaderProperty::GetUVOffset() const { return uvOffset; } void BSLightingShaderProperty::SetUVOffset( const TexCoord & value ) { uvOffset = value; } TexCoord BSLightingShaderProperty::GetUVScale() const { return uvScale; } void BSLightingShaderProperty::SetUVScale( const TexCoord & value ) { uvScale = value; } Ref<BSShaderTextureSet > BSLightingShaderProperty::GetTextureSet() const { return textureSet; } void BSLightingShaderProperty::SetTextureSet( Ref<BSShaderTextureSet > value ) { textureSet = value; } Color3 BSLightingShaderProperty::GetEmissiveColor() const { return emissiveColor; } void BSLightingShaderProperty::SetEmissiveColor( const Color3 & value ) { emissiveColor = value; } float BSLightingShaderProperty::GetEmissiveMultiple() const { return emissiveMultiple; } void BSLightingShaderProperty::SetEmissiveMultiple( float value ) { emissiveMultiple = value; } TexClampMode BSLightingShaderProperty::GetTextureClampMode() const { return textureClampMode; } void BSLightingShaderProperty::SetTextureClampMode( TexClampMode value ) { textureClampMode = value; } float BSLightingShaderProperty::GetAlpha() const { return alpha; } void BSLightingShaderProperty::SetAlpha( float value ) { alpha = value; } float BSLightingShaderProperty::GetUnknownFloat2() const { return unknownFloat2; } void BSLightingShaderProperty::SetUnknownFloat2( float value ) { unknownFloat2 = value; } float BSLightingShaderProperty::GetGlossiness() const { return glossiness; } void BSLightingShaderProperty::SetGlossiness( float value ) { glossiness = value; } Color3 BSLightingShaderProperty::GetSpecularColor() const { return specularColor; } void BSLightingShaderProperty::SetSpecularColor( const Color3 & value ) { specularColor = value; } float BSLightingShaderProperty::GetSpecularStrength() const { return specularStrength; } void BSLightingShaderProperty::SetSpecularStrength( float value ) { specularStrength = value; } float BSLightingShaderProperty::GetLightingEffect1() const { return lightingEffect1; } void BSLightingShaderProperty::SetLightingEffect1( float value ) { lightingEffect1 = value; } float BSLightingShaderProperty::GetLightingEffect2() const { return lightingEffect2; } void BSLightingShaderProperty::SetLightingEffect2( float value ) { lightingEffect2 = value; } float BSLightingShaderProperty::GetEnvironmentMapScale() const { return environmentMapScale; } void BSLightingShaderProperty::SetEnvironmentMapScale( float value ) { environmentMapScale = value; } Color3 BSLightingShaderProperty::GetSkinTintColor() const { return skinTintColor; } void BSLightingShaderProperty::SetSkinTintColor( const Color3 & value ) { skinTintColor = value; } Color3 BSLightingShaderProperty::GetHairTintColor() const { return hairTintColor; } void BSLightingShaderProperty::SetHairTintColor( const Color3 & value ) { hairTintColor = value; } float BSLightingShaderProperty::GetMaxPasses() const { return maxPasses; } void BSLightingShaderProperty::SetMaxPasses( float value ) { maxPasses = value; } float BSLightingShaderProperty::GetScale() const { return scale; } void BSLightingShaderProperty::SetScale( float value ) { scale = value; } float BSLightingShaderProperty::GetParallaxInnerLayerThickness() const { return parallaxInnerLayerThickness; } void BSLightingShaderProperty::SetParallaxInnerLayerThickness( float value ) { parallaxInnerLayerThickness = value; } float BSLightingShaderProperty::GetParallaxRefractionScale() const { return parallaxRefractionScale; } void BSLightingShaderProperty::SetParallaxRefractionScale( float value ) { parallaxRefractionScale = value; } TexCoord BSLightingShaderProperty::GetParallaxInnerLayerTextureScale() const { return parallaxInnerLayerTextureScale; } void BSLightingShaderProperty::SetParallaxInnerLayerTextureScale( const TexCoord & value ) { parallaxInnerLayerTextureScale = value; } float BSLightingShaderProperty::GetParallaxEnvmapStrength() const { return parallaxEnvmapStrength; } void BSLightingShaderProperty::SetParallaxEnvmapStrength( float value ) { parallaxEnvmapStrength = value; } Vector4 BSLightingShaderProperty::GetSparkleParameters() const { return sparkleParameters; } void BSLightingShaderProperty::SetSparkleParameters( const Vector4 & value ) { sparkleParameters = value; } float BSLightingShaderProperty::GetEyeCubemapScale() const { return eyeCubemapScale; } void BSLightingShaderProperty::SetEyeCubemapScale( float value ) { eyeCubemapScale = value; } Vector3 BSLightingShaderProperty::GetLeftEyeReflectionCenter() const { return leftEyeReflectionCenter; } void BSLightingShaderProperty::SetLeftEyeReflectionCenter( const Vector3 & value ) { leftEyeReflectionCenter = value; } Vector3 BSLightingShaderProperty::GetRightEyeReflectionCenter() const { return rightEyeReflectionCenter; } void BSLightingShaderProperty::SetRightEyeReflectionCenter( const Vector3 & value ) { rightEyeReflectionCenter = value; } //--END CUSTOM CODE--//
; 1 - Iterar una string en memoria y desplegar caracter por caracter .Model small .Stack 64 .Data num db "123" len equ $ - num ; Añadir (- 1) en caso de \r\n .Code MAIN PROC mov ax,@Data mov ds,ax mov bx,offset num mov cx,len PRINT_CHAR: mov dx,[bx] mov ah,02h int 21h inc bx dec cx jnz PRINT_CHAR .EXIT ENDP End MAIN
BITS 32 ; XOR [ESP], ESI and XOR ESI, [ESP] can be encoded in two ways, one of which is ; alphanumeric. NASM chooses the wrong one, which is why we have these: %define xor_esp_esi db 0x31, 0x34, 0x64 %define xor_esi_esp db 0x33, 0x34, 0x64 start: XOR [EDX], ESI ; [ESI] = base address ^ ESI XOR ESI, [EDX] ; ESI = base address ^ ESI ^ ESI = base address PUSH ESI ; [ESP0] = base address POP ECX ; ECX = [ESP0] = base address PUSH 0x66666666 ; IMUL ESI, [ESP], 0x69 db 0x6B, 0x34, 0x64, 0x69 esi_value equ -0x2A ; -Something decode_loop: INC ESI IMUL EAX, [BYTE ECX + 2*ESI + jnz_marker + 1 - ((esi_value+1)*2)], BYTE 0x30 XOR AL, [BYTE ECX + 2*ESI + jnz_marker + 2 - ((esi_value+1)*2)] XOR [BYTE ECX + ESI + jnz_marker + 1 - (esi_value+1)], AL jnz_marker: ; Jump back 0x10 bytes => F0, this must be encoded ; Assume byte1 is 0x4? and byte2 is 0x4? ; Working back: the offset is eventually stored by XORing over byte1, so the ; decoded value must be F0 ^ 4? => B?. Before that the value is XORed with ; byte2, so the value before this must be B? ^ 4? => F?. F0 can be created ; using 0x?5 * 0x30 => 0xF0, so byte1 must be 0x45. ; Working back again, using the knowledge that byte1 must be 0x45: the offset is ; eventually stored by XORing over byte1, so the decoded value must be F0 ^ 45 ; => B5. Before that the value is XORed with byte2 to and the result of that ; must be F0. B5 ^ F0 => 0x45, so byte2 must be 0x45 as well. db 0x75 ; JNZ db 0x45 ; high nibble of offset to decode_loop db 0x45 ; low nibble of offset to decode_loop